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/PartialDiagnostic.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Lex/LiteralSupport.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Sema/CXXFieldCollector.h" 32 #include "clang/Sema/DeclSpec.h" 33 #include "clang/Sema/Initialization.h" 34 #include "clang/Sema/Lookup.h" 35 #include "clang/Sema/ParsedTemplate.h" 36 #include "clang/Sema/Scope.h" 37 #include "clang/Sema/ScopeInfo.h" 38 #include "clang/Sema/SemaInternal.h" 39 #include "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include "llvm/ADT/StringExtras.h" 43 #include <map> 44 #include <set> 45 46 using namespace clang; 47 48 //===----------------------------------------------------------------------===// 49 // CheckDefaultArgumentVisitor 50 //===----------------------------------------------------------------------===// 51 52 namespace { 53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 54 /// the default argument of a parameter to determine whether it 55 /// contains any ill-formed subexpressions. For example, this will 56 /// diagnose the use of local variables or parameters within the 57 /// default argument expression. 58 class CheckDefaultArgumentVisitor 59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 60 Expr *DefaultArg; 61 Sema *S; 62 63 public: 64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 65 : DefaultArg(defarg), S(s) {} 66 67 bool VisitExpr(Expr *Node); 68 bool VisitDeclRefExpr(DeclRefExpr *DRE); 69 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 70 bool VisitLambdaExpr(LambdaExpr *Lambda); 71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 72 }; 73 74 /// VisitExpr - Visit all of the children of this expression. 75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 76 bool IsInvalid = false; 77 for (Stmt *SubStmt : Node->children()) 78 IsInvalid |= Visit(SubStmt); 79 return IsInvalid; 80 } 81 82 /// VisitDeclRefExpr - Visit a reference to a declaration, to 83 /// determine whether this declaration can be used in the default 84 /// argument expression. 85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 86 NamedDecl *Decl = DRE->getDecl(); 87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 88 // C++ [dcl.fct.default]p9 89 // Default arguments are evaluated each time the function is 90 // called. The order of evaluation of function arguments is 91 // unspecified. Consequently, parameters of a function shall not 92 // be used in default argument expressions, even if they are not 93 // evaluated. Parameters of a function declared before a default 94 // argument expression are in scope and can hide namespace and 95 // class member names. 96 return S->Diag(DRE->getBeginLoc(), 97 diag::err_param_default_argument_references_param) 98 << Param->getDeclName() << DefaultArg->getSourceRange(); 99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 100 // C++ [dcl.fct.default]p7 101 // Local variables shall not be used in default argument 102 // expressions. 103 if (VDecl->isLocalVarDecl()) 104 return S->Diag(DRE->getBeginLoc(), 105 diag::err_param_default_argument_references_local) 106 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 107 } 108 109 return false; 110 } 111 112 /// VisitCXXThisExpr - Visit a C++ "this" expression. 113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 114 // C++ [dcl.fct.default]p8: 115 // The keyword this shall not be used in a default argument of a 116 // member function. 117 return S->Diag(ThisE->getBeginLoc(), 118 diag::err_param_default_argument_references_this) 119 << ThisE->getSourceRange(); 120 } 121 122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 123 bool Invalid = false; 124 for (PseudoObjectExpr::semantics_iterator 125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 126 Expr *E = *i; 127 128 // Look through bindings. 129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 130 E = OVE->getSourceExpr(); 131 assert(E && "pseudo-object binding without source expression?"); 132 } 133 134 Invalid |= Visit(E); 135 } 136 return Invalid; 137 } 138 139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 140 // C++11 [expr.lambda.prim]p13: 141 // A lambda-expression appearing in a default argument shall not 142 // implicitly or explicitly capture any entity. 143 if (Lambda->capture_begin() == Lambda->capture_end()) 144 return false; 145 146 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If we have a throw-all spec at this point, ignore the function. 166 if (ComputedEST == EST_None) 167 return; 168 169 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 170 EST = EST_BasicNoexcept; 171 172 switch (EST) { 173 case EST_Unparsed: 174 case EST_Uninstantiated: 175 case EST_Unevaluated: 176 llvm_unreachable("should not see unresolved exception specs here"); 177 178 // If this function can throw any exceptions, make a note of that. 179 case EST_MSAny: 180 case EST_None: 181 // FIXME: Whichever we see last of MSAny and None determines our result. 182 // We should make a consistent, order-independent choice here. 183 ClearExceptions(); 184 ComputedEST = EST; 185 return; 186 case EST_NoexceptFalse: 187 ClearExceptions(); 188 ComputedEST = EST_None; 189 return; 190 // FIXME: If the call to this decl is using any of its default arguments, we 191 // need to search them for potentially-throwing calls. 192 // If this function has a basic noexcept, it doesn't affect the outcome. 193 case EST_BasicNoexcept: 194 case EST_NoexceptTrue: 195 case EST_NoThrow: 196 return; 197 // If we're still at noexcept(true) and there's a throw() callee, 198 // change to that specification. 199 case EST_DynamicNone: 200 if (ComputedEST == EST_BasicNoexcept) 201 ComputedEST = EST_DynamicNone; 202 return; 203 case EST_DependentNoexcept: 204 llvm_unreachable( 205 "should not generate implicit declarations for dependent cases"); 206 case EST_Dynamic: 207 break; 208 } 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // C++11 [dcl.fct.default]p3 321 // A default argument expression [...] shall not be specified for a 322 // parameter pack. 323 if (Param->isParameterPack()) { 324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 325 << DefaultArg->getSourceRange(); 326 return; 327 } 328 329 // Check that the default argument is well-formed 330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 331 if (DefaultArgChecker.Visit(DefaultArg)) { 332 Param->setInvalidDecl(); 333 return; 334 } 335 336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 337 } 338 339 /// ActOnParamUnparsedDefaultArgument - We've seen a default 340 /// argument for a function parameter, but we can't parse it yet 341 /// because we're inside a class definition. Note that this default 342 /// argument will be parsed later. 343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 344 SourceLocation EqualLoc, 345 SourceLocation ArgLoc) { 346 if (!param) 347 return; 348 349 ParmVarDecl *Param = cast<ParmVarDecl>(param); 350 Param->setUnparsedDefaultArg(); 351 UnparsedDefaultArgLocs[Param] = ArgLoc; 352 } 353 354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 355 /// the default argument for the parameter param failed. 356 void Sema::ActOnParamDefaultArgumentError(Decl *param, 357 SourceLocation EqualLoc) { 358 if (!param) 359 return; 360 361 ParmVarDecl *Param = cast<ParmVarDecl>(param); 362 Param->setInvalidDecl(); 363 UnparsedDefaultArgLocs.erase(Param); 364 Param->setDefaultArg(new(Context) 365 OpaqueValueExpr(EqualLoc, 366 Param->getType().getNonReferenceType(), 367 VK_RValue)); 368 } 369 370 /// CheckExtraCXXDefaultArguments - Check for any extra default 371 /// arguments in the declarator, which is not a function declaration 372 /// or definition and therefore is not permitted to have default 373 /// arguments. This routine should be invoked for every declarator 374 /// that is not a function declaration or definition. 375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 376 // C++ [dcl.fct.default]p3 377 // A default argument expression shall be specified only in the 378 // parameter-declaration-clause of a function declaration or in a 379 // template-parameter (14.1). It shall not be specified for a 380 // parameter pack. If it is specified in a 381 // parameter-declaration-clause, it shall not occur within a 382 // declarator or abstract-declarator of a parameter-declaration. 383 bool MightBeFunction = D.isFunctionDeclarationContext(); 384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 385 DeclaratorChunk &chunk = D.getTypeObject(i); 386 if (chunk.Kind == DeclaratorChunk::Function) { 387 if (MightBeFunction) { 388 // This is a function declaration. It can have default arguments, but 389 // keep looking in case its return type is a function type with default 390 // arguments. 391 MightBeFunction = false; 392 continue; 393 } 394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 395 ++argIdx) { 396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 397 if (Param->hasUnparsedDefaultArg()) { 398 std::unique_ptr<CachedTokens> Toks = 399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 400 SourceRange SR; 401 if (Toks->size() > 1) 402 SR = SourceRange((*Toks)[1].getLocation(), 403 Toks->back().getLocation()); 404 else 405 SR = UnparsedDefaultArgLocs[Param]; 406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 407 << SR; 408 } else if (Param->getDefaultArg()) { 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << Param->getDefaultArg()->getSourceRange(); 411 Param->setDefaultArg(nullptr); 412 } 413 } 414 } else if (chunk.Kind != DeclaratorChunk::Paren) { 415 MightBeFunction = false; 416 } 417 } 418 } 419 420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 423 if (!PVD->hasDefaultArg()) 424 return false; 425 if (!PVD->hasInheritedDefaultArg()) 426 return true; 427 } 428 return false; 429 } 430 431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 432 /// function, once we already know that they have the same 433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 434 /// error, false otherwise. 435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 436 Scope *S) { 437 bool Invalid = false; 438 439 // The declaration context corresponding to the scope is the semantic 440 // parent, unless this is a local function declaration, in which case 441 // it is that surrounding function. 442 DeclContext *ScopeDC = New->isLocalExternDecl() 443 ? New->getLexicalDeclContext() 444 : New->getDeclContext(); 445 446 // Find the previous declaration for the purpose of default arguments. 447 FunctionDecl *PrevForDefaultArgs = Old; 448 for (/**/; PrevForDefaultArgs; 449 // Don't bother looking back past the latest decl if this is a local 450 // extern declaration; nothing else could work. 451 PrevForDefaultArgs = New->isLocalExternDecl() 452 ? nullptr 453 : PrevForDefaultArgs->getPreviousDecl()) { 454 // Ignore hidden declarations. 455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 456 continue; 457 458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 459 !New->isCXXClassMember()) { 460 // Ignore default arguments of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 continue; 464 } 465 466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 467 // If only one of these is a local function declaration, then they are 468 // declared in different scopes, even though isDeclInScope may think 469 // they're in the same scope. (If both are local, the scope check is 470 // sufficient, and if neither is local, then they are in the same scope.) 471 continue; 472 } 473 474 // We found the right previous declaration. 475 break; 476 } 477 478 // C++ [dcl.fct.default]p4: 479 // For non-template functions, default arguments can be added in 480 // later declarations of a function in the same 481 // scope. Declarations in different scopes have completely 482 // distinct sets of default arguments. That is, declarations in 483 // inner scopes do not acquire default arguments from 484 // declarations in outer scopes, and vice versa. In a given 485 // function declaration, all parameters subsequent to a 486 // parameter with a default argument shall have default 487 // arguments supplied in this or previous declarations. A 488 // default argument shall not be redefined by a later 489 // declaration (not even to the same value). 490 // 491 // C++ [dcl.fct.default]p6: 492 // Except for member functions of class templates, the default arguments 493 // in a member function definition that appears outside of the class 494 // definition are added to the set of default arguments provided by the 495 // member function declaration in the class definition. 496 for (unsigned p = 0, NumParams = PrevForDefaultArgs 497 ? PrevForDefaultArgs->getNumParams() 498 : 0; 499 p < NumParams; ++p) { 500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 501 ParmVarDecl *NewParam = New->getParamDecl(p); 502 503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 504 bool NewParamHasDfl = NewParam->hasDefaultArg(); 505 506 if (OldParamHasDfl && NewParamHasDfl) { 507 unsigned DiagDefaultParamID = 508 diag::err_param_default_argument_redefinition; 509 510 // MSVC accepts that default parameters be redefined for member functions 511 // of template class. The new default parameter's value is ignored. 512 Invalid = true; 513 if (getLangOpts().MicrosoftExt) { 514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 515 if (MD && MD->getParent()->getDescribedClassTemplate()) { 516 // Merge the old default argument into the new parameter. 517 NewParam->setHasInheritedDefaultArg(); 518 if (OldParam->hasUninstantiatedDefaultArg()) 519 NewParam->setUninstantiatedDefaultArg( 520 OldParam->getUninstantiatedDefaultArg()); 521 else 522 NewParam->setDefaultArg(OldParam->getInit()); 523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 524 Invalid = false; 525 } 526 } 527 528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 529 // hint here. Alternatively, we could walk the type-source information 530 // for NewParam to find the last source location in the type... but it 531 // isn't worth the effort right now. This is the kind of test case that 532 // is hard to get right: 533 // int f(int); 534 // void g(int (*fp)(int) = f); 535 // void g(int (*fp)(int) = &f); 536 Diag(NewParam->getLocation(), DiagDefaultParamID) 537 << NewParam->getDefaultArgRange(); 538 539 // Look for the function declaration where the default argument was 540 // actually written, which may be a declaration prior to Old. 541 for (auto Older = PrevForDefaultArgs; 542 OldParam->hasInheritedDefaultArg(); /**/) { 543 Older = Older->getPreviousDecl(); 544 OldParam = Older->getParamDecl(p); 545 } 546 547 Diag(OldParam->getLocation(), diag::note_previous_definition) 548 << OldParam->getDefaultArgRange(); 549 } else if (OldParamHasDfl) { 550 // Merge the old default argument into the new parameter unless the new 551 // function is a friend declaration in a template class. In the latter 552 // case the default arguments will be inherited when the friend 553 // declaration will be instantiated. 554 if (New->getFriendObjectKind() == Decl::FOK_None || 555 !New->getLexicalDeclContext()->isDependentContext()) { 556 // It's important to use getInit() here; getDefaultArg() 557 // strips off any top-level ExprWithCleanups. 558 NewParam->setHasInheritedDefaultArg(); 559 if (OldParam->hasUnparsedDefaultArg()) 560 NewParam->setUnparsedDefaultArg(); 561 else if (OldParam->hasUninstantiatedDefaultArg()) 562 NewParam->setUninstantiatedDefaultArg( 563 OldParam->getUninstantiatedDefaultArg()); 564 else 565 NewParam->setDefaultArg(OldParam->getInit()); 566 } 567 } else if (NewParamHasDfl) { 568 if (New->getDescribedFunctionTemplate()) { 569 // Paragraph 4, quoted above, only applies to non-template functions. 570 Diag(NewParam->getLocation(), 571 diag::err_param_default_argument_template_redecl) 572 << NewParam->getDefaultArgRange(); 573 Diag(PrevForDefaultArgs->getLocation(), 574 diag::note_template_prev_declaration) 575 << false; 576 } else if (New->getTemplateSpecializationKind() 577 != TSK_ImplicitInstantiation && 578 New->getTemplateSpecializationKind() != TSK_Undeclared) { 579 // C++ [temp.expr.spec]p21: 580 // Default function arguments shall not be specified in a declaration 581 // or a definition for one of the following explicit specializations: 582 // - the explicit specialization of a function template; 583 // - the explicit specialization of a member function template; 584 // - the explicit specialization of a member function of a class 585 // template where the class template specialization to which the 586 // member function specialization belongs is implicitly 587 // instantiated. 588 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 589 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 590 << New->getDeclName() 591 << NewParam->getDefaultArgRange(); 592 } else if (New->getDeclContext()->isDependentContext()) { 593 // C++ [dcl.fct.default]p6 (DR217): 594 // Default arguments for a member function of a class template shall 595 // be specified on the initial declaration of the member function 596 // within the class template. 597 // 598 // Reading the tea leaves a bit in DR217 and its reference to DR205 599 // leads me to the conclusion that one cannot add default function 600 // arguments for an out-of-line definition of a member function of a 601 // dependent type. 602 int WhichKind = 2; 603 if (CXXRecordDecl *Record 604 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 605 if (Record->getDescribedClassTemplate()) 606 WhichKind = 0; 607 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 608 WhichKind = 1; 609 else 610 WhichKind = 2; 611 } 612 613 Diag(NewParam->getLocation(), 614 diag::err_param_default_argument_member_template_redecl) 615 << WhichKind 616 << NewParam->getDefaultArgRange(); 617 } 618 } 619 } 620 621 // DR1344: If a default argument is added outside a class definition and that 622 // default argument makes the function a special member function, the program 623 // is ill-formed. This can only happen for constructors. 624 if (isa<CXXConstructorDecl>(New) && 625 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 626 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 627 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 628 if (NewSM != OldSM) { 629 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 630 assert(NewParam->hasDefaultArg()); 631 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 632 << NewParam->getDefaultArgRange() << NewSM; 633 Diag(Old->getLocation(), diag::note_previous_declaration); 634 } 635 } 636 637 const FunctionDecl *Def; 638 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 639 // template has a constexpr specifier then all its declarations shall 640 // contain the constexpr specifier. 641 if (New->getConstexprKind() != Old->getConstexprKind()) { 642 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 643 << New << New->getConstexprKind() << Old->getConstexprKind(); 644 Diag(Old->getLocation(), diag::note_previous_declaration); 645 Invalid = true; 646 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 647 Old->isDefined(Def) && 648 // If a friend function is inlined but does not have 'inline' 649 // specifier, it is a definition. Do not report attribute conflict 650 // in this case, redefinition will be diagnosed later. 651 (New->isInlineSpecified() || 652 New->getFriendObjectKind() == Decl::FOK_None)) { 653 // C++11 [dcl.fcn.spec]p4: 654 // If the definition of a function appears in a translation unit before its 655 // first declaration as inline, the program is ill-formed. 656 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 657 Diag(Def->getLocation(), diag::note_previous_definition); 658 Invalid = true; 659 } 660 661 // C++17 [temp.deduct.guide]p3: 662 // Two deduction guide declarations in the same translation unit 663 // for the same class template shall not have equivalent 664 // parameter-declaration-clauses. 665 if (isa<CXXDeductionGuideDecl>(New) && 666 !New->isFunctionTemplateSpecialization()) { 667 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 668 Diag(Old->getLocation(), diag::note_previous_declaration); 669 } 670 671 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 672 // argument expression, that declaration shall be a definition and shall be 673 // the only declaration of the function or function template in the 674 // translation unit. 675 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 676 functionDeclHasDefaultArgument(Old)) { 677 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 678 Diag(Old->getLocation(), diag::note_previous_declaration); 679 Invalid = true; 680 } 681 682 return Invalid; 683 } 684 685 NamedDecl * 686 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 687 MultiTemplateParamsArg TemplateParamLists) { 688 assert(D.isDecompositionDeclarator()); 689 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 690 691 // The syntax only allows a decomposition declarator as a simple-declaration, 692 // a for-range-declaration, or a condition in Clang, but we parse it in more 693 // cases than that. 694 if (!D.mayHaveDecompositionDeclarator()) { 695 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 696 << Decomp.getSourceRange(); 697 return nullptr; 698 } 699 700 if (!TemplateParamLists.empty()) { 701 // FIXME: There's no rule against this, but there are also no rules that 702 // would actually make it usable, so we reject it for now. 703 Diag(TemplateParamLists.front()->getTemplateLoc(), 704 diag::err_decomp_decl_template); 705 return nullptr; 706 } 707 708 Diag(Decomp.getLSquareLoc(), 709 !getLangOpts().CPlusPlus17 710 ? diag::ext_decomp_decl 711 : D.getContext() == DeclaratorContext::ConditionContext 712 ? diag::ext_decomp_decl_cond 713 : diag::warn_cxx14_compat_decomp_decl) 714 << Decomp.getSourceRange(); 715 716 // The semantic context is always just the current context. 717 DeclContext *const DC = CurContext; 718 719 // C++17 [dcl.dcl]/8: 720 // The decl-specifier-seq shall contain only the type-specifier auto 721 // and cv-qualifiers. 722 // C++2a [dcl.dcl]/8: 723 // If decl-specifier-seq contains any decl-specifier other than static, 724 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 725 auto &DS = D.getDeclSpec(); 726 { 727 SmallVector<StringRef, 8> BadSpecifiers; 728 SmallVector<SourceLocation, 8> BadSpecifierLocs; 729 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 730 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 731 if (auto SCS = DS.getStorageClassSpec()) { 732 if (SCS == DeclSpec::SCS_static) { 733 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 734 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 735 } else { 736 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 737 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 738 } 739 } 740 if (auto TSCS = DS.getThreadStorageClassSpec()) { 741 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 742 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 743 } 744 if (DS.hasConstexprSpecifier()) { 745 BadSpecifiers.push_back( 746 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 747 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 748 } 749 if (DS.isInlineSpecified()) { 750 BadSpecifiers.push_back("inline"); 751 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 752 } 753 if (!BadSpecifiers.empty()) { 754 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 755 Err << (int)BadSpecifiers.size() 756 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 757 // Don't add FixItHints to remove the specifiers; we do still respect 758 // them when building the underlying variable. 759 for (auto Loc : BadSpecifierLocs) 760 Err << SourceRange(Loc, Loc); 761 } else if (!CPlusPlus20Specifiers.empty()) { 762 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 763 getLangOpts().CPlusPlus2a 764 ? diag::warn_cxx17_compat_decomp_decl_spec 765 : diag::ext_decomp_decl_spec); 766 Warn << (int)CPlusPlus20Specifiers.size() 767 << llvm::join(CPlusPlus20Specifiers.begin(), 768 CPlusPlus20Specifiers.end(), " "); 769 for (auto Loc : CPlusPlus20SpecifierLocs) 770 Warn << SourceRange(Loc, Loc); 771 } 772 // We can't recover from it being declared as a typedef. 773 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 774 return nullptr; 775 } 776 777 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 778 QualType R = TInfo->getType(); 779 780 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 781 UPPC_DeclarationType)) 782 D.setInvalidType(); 783 784 // The syntax only allows a single ref-qualifier prior to the decomposition 785 // declarator. No other declarator chunks are permitted. Also check the type 786 // specifier here. 787 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 788 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 789 (D.getNumTypeObjects() == 1 && 790 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 791 Diag(Decomp.getLSquareLoc(), 792 (D.hasGroupingParens() || 793 (D.getNumTypeObjects() && 794 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 795 ? diag::err_decomp_decl_parens 796 : diag::err_decomp_decl_type) 797 << R; 798 799 // In most cases, there's no actual problem with an explicitly-specified 800 // type, but a function type won't work here, and ActOnVariableDeclarator 801 // shouldn't be called for such a type. 802 if (R->isFunctionType()) 803 D.setInvalidType(); 804 } 805 806 // Build the BindingDecls. 807 SmallVector<BindingDecl*, 8> Bindings; 808 809 // Build the BindingDecls. 810 for (auto &B : D.getDecompositionDeclarator().bindings()) { 811 // Check for name conflicts. 812 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 813 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 814 ForVisibleRedeclaration); 815 LookupName(Previous, S, 816 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 817 818 // It's not permitted to shadow a template parameter name. 819 if (Previous.isSingleResult() && 820 Previous.getFoundDecl()->isTemplateParameter()) { 821 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 822 Previous.getFoundDecl()); 823 Previous.clear(); 824 } 825 826 bool ConsiderLinkage = DC->isFunctionOrMethod() && 827 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 828 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 829 /*AllowInlineNamespace*/false); 830 if (!Previous.empty()) { 831 auto *Old = Previous.getRepresentativeDecl(); 832 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 833 Diag(Old->getLocation(), diag::note_previous_definition); 834 } 835 836 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 837 PushOnScopeChains(BD, S, true); 838 Bindings.push_back(BD); 839 ParsingInitForAutoVars.insert(BD); 840 } 841 842 // There are no prior lookup results for the variable itself, because it 843 // is unnamed. 844 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 845 Decomp.getLSquareLoc()); 846 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 847 ForVisibleRedeclaration); 848 849 // Build the variable that holds the non-decomposed object. 850 bool AddToScope = true; 851 NamedDecl *New = 852 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 853 MultiTemplateParamsArg(), AddToScope, Bindings); 854 if (AddToScope) { 855 S->AddDecl(New); 856 CurContext->addHiddenDecl(New); 857 } 858 859 if (isInOpenMPDeclareTargetContext()) 860 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 861 862 return New; 863 } 864 865 static bool checkSimpleDecomposition( 866 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 867 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 868 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 869 if ((int64_t)Bindings.size() != NumElems) { 870 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 871 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 872 << (NumElems < Bindings.size()); 873 return true; 874 } 875 876 unsigned I = 0; 877 for (auto *B : Bindings) { 878 SourceLocation Loc = B->getLocation(); 879 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 880 if (E.isInvalid()) 881 return true; 882 E = GetInit(Loc, E.get(), I++); 883 if (E.isInvalid()) 884 return true; 885 B->setBinding(ElemType, E.get()); 886 } 887 888 return false; 889 } 890 891 static bool checkArrayLikeDecomposition(Sema &S, 892 ArrayRef<BindingDecl *> Bindings, 893 ValueDecl *Src, QualType DecompType, 894 const llvm::APSInt &NumElems, 895 QualType ElemType) { 896 return checkSimpleDecomposition( 897 S, Bindings, Src, DecompType, NumElems, ElemType, 898 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 899 ExprResult E = S.ActOnIntegerConstant(Loc, I); 900 if (E.isInvalid()) 901 return ExprError(); 902 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 903 }); 904 } 905 906 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 907 ValueDecl *Src, QualType DecompType, 908 const ConstantArrayType *CAT) { 909 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 910 llvm::APSInt(CAT->getSize()), 911 CAT->getElementType()); 912 } 913 914 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 915 ValueDecl *Src, QualType DecompType, 916 const VectorType *VT) { 917 return checkArrayLikeDecomposition( 918 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 919 S.Context.getQualifiedType(VT->getElementType(), 920 DecompType.getQualifiers())); 921 } 922 923 static bool checkComplexDecomposition(Sema &S, 924 ArrayRef<BindingDecl *> Bindings, 925 ValueDecl *Src, QualType DecompType, 926 const ComplexType *CT) { 927 return checkSimpleDecomposition( 928 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 929 S.Context.getQualifiedType(CT->getElementType(), 930 DecompType.getQualifiers()), 931 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 932 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 933 }); 934 } 935 936 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 937 TemplateArgumentListInfo &Args) { 938 SmallString<128> SS; 939 llvm::raw_svector_ostream OS(SS); 940 bool First = true; 941 for (auto &Arg : Args.arguments()) { 942 if (!First) 943 OS << ", "; 944 Arg.getArgument().print(PrintingPolicy, OS); 945 First = false; 946 } 947 return OS.str(); 948 } 949 950 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 951 SourceLocation Loc, StringRef Trait, 952 TemplateArgumentListInfo &Args, 953 unsigned DiagID) { 954 auto DiagnoseMissing = [&] { 955 if (DiagID) 956 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 957 Args); 958 return true; 959 }; 960 961 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 962 NamespaceDecl *Std = S.getStdNamespace(); 963 if (!Std) 964 return DiagnoseMissing(); 965 966 // Look up the trait itself, within namespace std. We can diagnose various 967 // problems with this lookup even if we've been asked to not diagnose a 968 // missing specialization, because this can only fail if the user has been 969 // declaring their own names in namespace std or we don't support the 970 // standard library implementation in use. 971 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 972 Loc, Sema::LookupOrdinaryName); 973 if (!S.LookupQualifiedName(Result, Std)) 974 return DiagnoseMissing(); 975 if (Result.isAmbiguous()) 976 return true; 977 978 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 979 if (!TraitTD) { 980 Result.suppressDiagnostics(); 981 NamedDecl *Found = *Result.begin(); 982 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 983 S.Diag(Found->getLocation(), diag::note_declared_at); 984 return true; 985 } 986 987 // Build the template-id. 988 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 989 if (TraitTy.isNull()) 990 return true; 991 if (!S.isCompleteType(Loc, TraitTy)) { 992 if (DiagID) 993 S.RequireCompleteType( 994 Loc, TraitTy, DiagID, 995 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 996 return true; 997 } 998 999 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1000 assert(RD && "specialization of class template is not a class?"); 1001 1002 // Look up the member of the trait type. 1003 S.LookupQualifiedName(TraitMemberLookup, RD); 1004 return TraitMemberLookup.isAmbiguous(); 1005 } 1006 1007 static TemplateArgumentLoc 1008 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1009 uint64_t I) { 1010 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1011 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1012 } 1013 1014 static TemplateArgumentLoc 1015 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1016 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1017 } 1018 1019 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1020 1021 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1022 llvm::APSInt &Size) { 1023 EnterExpressionEvaluationContext ContextRAII( 1024 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1025 1026 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1027 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1028 1029 // Form template argument list for tuple_size<T>. 1030 TemplateArgumentListInfo Args(Loc, Loc); 1031 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1032 1033 // If there's no tuple_size specialization, it's not tuple-like. 1034 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1035 return IsTupleLike::NotTupleLike; 1036 1037 // If we get this far, we've committed to the tuple interpretation, but 1038 // we can still fail if there actually isn't a usable ::value. 1039 1040 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1041 LookupResult &R; 1042 TemplateArgumentListInfo &Args; 1043 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1044 : R(R), Args(Args) {} 1045 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1046 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1047 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1048 } 1049 } Diagnoser(R, Args); 1050 1051 if (R.empty()) { 1052 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1053 return IsTupleLike::Error; 1054 } 1055 1056 ExprResult E = 1057 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1058 if (E.isInvalid()) 1059 return IsTupleLike::Error; 1060 1061 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1062 if (E.isInvalid()) 1063 return IsTupleLike::Error; 1064 1065 return IsTupleLike::TupleLike; 1066 } 1067 1068 /// \return std::tuple_element<I, T>::type. 1069 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1070 unsigned I, QualType T) { 1071 // Form template argument list for tuple_element<I, T>. 1072 TemplateArgumentListInfo Args(Loc, Loc); 1073 Args.addArgument( 1074 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1075 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1076 1077 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1078 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1079 if (lookupStdTypeTraitMember( 1080 S, R, Loc, "tuple_element", Args, 1081 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1082 return QualType(); 1083 1084 auto *TD = R.getAsSingle<TypeDecl>(); 1085 if (!TD) { 1086 R.suppressDiagnostics(); 1087 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1088 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1089 if (!R.empty()) 1090 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1091 return QualType(); 1092 } 1093 1094 return S.Context.getTypeDeclType(TD); 1095 } 1096 1097 namespace { 1098 struct BindingDiagnosticTrap { 1099 Sema &S; 1100 DiagnosticErrorTrap Trap; 1101 BindingDecl *BD; 1102 1103 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1104 : S(S), Trap(S.Diags), BD(BD) {} 1105 ~BindingDiagnosticTrap() { 1106 if (Trap.hasErrorOccurred()) 1107 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1108 } 1109 }; 1110 } 1111 1112 static bool checkTupleLikeDecomposition(Sema &S, 1113 ArrayRef<BindingDecl *> Bindings, 1114 VarDecl *Src, QualType DecompType, 1115 const llvm::APSInt &TupleSize) { 1116 if ((int64_t)Bindings.size() != TupleSize) { 1117 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1118 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1119 << (TupleSize < Bindings.size()); 1120 return true; 1121 } 1122 1123 if (Bindings.empty()) 1124 return false; 1125 1126 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1127 1128 // [dcl.decomp]p3: 1129 // The unqualified-id get is looked up in the scope of E by class member 1130 // access lookup ... 1131 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1132 bool UseMemberGet = false; 1133 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1134 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1135 S.LookupQualifiedName(MemberGet, RD); 1136 if (MemberGet.isAmbiguous()) 1137 return true; 1138 // ... and if that finds at least one declaration that is a function 1139 // template whose first template parameter is a non-type parameter ... 1140 for (NamedDecl *D : MemberGet) { 1141 if (FunctionTemplateDecl *FTD = 1142 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1143 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1144 if (TPL->size() != 0 && 1145 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1146 // ... the initializer is e.get<i>(). 1147 UseMemberGet = true; 1148 break; 1149 } 1150 } 1151 } 1152 } 1153 1154 unsigned I = 0; 1155 for (auto *B : Bindings) { 1156 BindingDiagnosticTrap Trap(S, B); 1157 SourceLocation Loc = B->getLocation(); 1158 1159 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1160 if (E.isInvalid()) 1161 return true; 1162 1163 // e is an lvalue if the type of the entity is an lvalue reference and 1164 // an xvalue otherwise 1165 if (!Src->getType()->isLValueReferenceType()) 1166 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1167 E.get(), nullptr, VK_XValue); 1168 1169 TemplateArgumentListInfo Args(Loc, Loc); 1170 Args.addArgument( 1171 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1172 1173 if (UseMemberGet) { 1174 // if [lookup of member get] finds at least one declaration, the 1175 // initializer is e.get<i-1>(). 1176 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1177 CXXScopeSpec(), SourceLocation(), nullptr, 1178 MemberGet, &Args, nullptr); 1179 if (E.isInvalid()) 1180 return true; 1181 1182 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1183 } else { 1184 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1185 // in the associated namespaces. 1186 Expr *Get = UnresolvedLookupExpr::Create( 1187 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1188 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1189 UnresolvedSetIterator(), UnresolvedSetIterator()); 1190 1191 Expr *Arg = E.get(); 1192 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1193 } 1194 if (E.isInvalid()) 1195 return true; 1196 Expr *Init = E.get(); 1197 1198 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1199 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1200 if (T.isNull()) 1201 return true; 1202 1203 // each vi is a variable of type "reference to T" initialized with the 1204 // initializer, where the reference is an lvalue reference if the 1205 // initializer is an lvalue and an rvalue reference otherwise 1206 QualType RefType = 1207 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1208 if (RefType.isNull()) 1209 return true; 1210 auto *RefVD = VarDecl::Create( 1211 S.Context, Src->getDeclContext(), Loc, Loc, 1212 B->getDeclName().getAsIdentifierInfo(), RefType, 1213 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1214 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1215 RefVD->setTSCSpec(Src->getTSCSpec()); 1216 RefVD->setImplicit(); 1217 if (Src->isInlineSpecified()) 1218 RefVD->setInlineSpecified(); 1219 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1220 1221 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1222 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1223 InitializationSequence Seq(S, Entity, Kind, Init); 1224 E = Seq.Perform(S, Entity, Kind, Init); 1225 if (E.isInvalid()) 1226 return true; 1227 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1228 if (E.isInvalid()) 1229 return true; 1230 RefVD->setInit(E.get()); 1231 RefVD->checkInitIsICE(); 1232 1233 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1234 DeclarationNameInfo(B->getDeclName(), Loc), 1235 RefVD); 1236 if (E.isInvalid()) 1237 return true; 1238 1239 B->setBinding(T, E.get()); 1240 I++; 1241 } 1242 1243 return false; 1244 } 1245 1246 /// Find the base class to decompose in a built-in decomposition of a class type. 1247 /// This base class search is, unfortunately, not quite like any other that we 1248 /// perform anywhere else in C++. 1249 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1250 const CXXRecordDecl *RD, 1251 CXXCastPath &BasePath) { 1252 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1253 CXXBasePath &Path) { 1254 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1255 }; 1256 1257 const CXXRecordDecl *ClassWithFields = nullptr; 1258 AccessSpecifier AS = AS_public; 1259 if (RD->hasDirectFields()) 1260 // [dcl.decomp]p4: 1261 // Otherwise, all of E's non-static data members shall be public direct 1262 // members of E ... 1263 ClassWithFields = RD; 1264 else { 1265 // ... or of ... 1266 CXXBasePaths Paths; 1267 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1268 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1269 // If no classes have fields, just decompose RD itself. (This will work 1270 // if and only if zero bindings were provided.) 1271 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1272 } 1273 1274 CXXBasePath *BestPath = nullptr; 1275 for (auto &P : Paths) { 1276 if (!BestPath) 1277 BestPath = &P; 1278 else if (!S.Context.hasSameType(P.back().Base->getType(), 1279 BestPath->back().Base->getType())) { 1280 // ... the same ... 1281 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1282 << false << RD << BestPath->back().Base->getType() 1283 << P.back().Base->getType(); 1284 return DeclAccessPair(); 1285 } else if (P.Access < BestPath->Access) { 1286 BestPath = &P; 1287 } 1288 } 1289 1290 // ... unambiguous ... 1291 QualType BaseType = BestPath->back().Base->getType(); 1292 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1293 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1294 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1295 return DeclAccessPair(); 1296 } 1297 1298 // ... [accessible, implied by other rules] base class of E. 1299 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1300 *BestPath, diag::err_decomp_decl_inaccessible_base); 1301 AS = BestPath->Access; 1302 1303 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1304 S.BuildBasePathArray(Paths, BasePath); 1305 } 1306 1307 // The above search did not check whether the selected class itself has base 1308 // classes with fields, so check that now. 1309 CXXBasePaths Paths; 1310 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1311 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1312 << (ClassWithFields == RD) << RD << ClassWithFields 1313 << Paths.front().back().Base->getType(); 1314 return DeclAccessPair(); 1315 } 1316 1317 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1318 } 1319 1320 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1321 ValueDecl *Src, QualType DecompType, 1322 const CXXRecordDecl *OrigRD) { 1323 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1324 diag::err_incomplete_type)) 1325 return true; 1326 1327 CXXCastPath BasePath; 1328 DeclAccessPair BasePair = 1329 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1330 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1331 if (!RD) 1332 return true; 1333 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1334 DecompType.getQualifiers()); 1335 1336 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1337 unsigned NumFields = 1338 std::count_if(RD->field_begin(), RD->field_end(), 1339 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1340 assert(Bindings.size() != NumFields); 1341 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1342 << DecompType << (unsigned)Bindings.size() << NumFields 1343 << (NumFields < Bindings.size()); 1344 return true; 1345 }; 1346 1347 // all of E's non-static data members shall be [...] well-formed 1348 // when named as e.name in the context of the structured binding, 1349 // E shall not have an anonymous union member, ... 1350 unsigned I = 0; 1351 for (auto *FD : RD->fields()) { 1352 if (FD->isUnnamedBitfield()) 1353 continue; 1354 1355 if (FD->isAnonymousStructOrUnion()) { 1356 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1357 << DecompType << FD->getType()->isUnionType(); 1358 S.Diag(FD->getLocation(), diag::note_declared_at); 1359 return true; 1360 } 1361 1362 // We have a real field to bind. 1363 if (I >= Bindings.size()) 1364 return DiagnoseBadNumberOfBindings(); 1365 auto *B = Bindings[I++]; 1366 SourceLocation Loc = B->getLocation(); 1367 1368 // The field must be accessible in the context of the structured binding. 1369 // We already checked that the base class is accessible. 1370 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1371 // const_cast here. 1372 S.CheckStructuredBindingMemberAccess( 1373 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1374 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1375 BasePair.getAccess(), FD->getAccess()))); 1376 1377 // Initialize the binding to Src.FD. 1378 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1379 if (E.isInvalid()) 1380 return true; 1381 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1382 VK_LValue, &BasePath); 1383 if (E.isInvalid()) 1384 return true; 1385 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1386 CXXScopeSpec(), FD, 1387 DeclAccessPair::make(FD, FD->getAccess()), 1388 DeclarationNameInfo(FD->getDeclName(), Loc)); 1389 if (E.isInvalid()) 1390 return true; 1391 1392 // If the type of the member is T, the referenced type is cv T, where cv is 1393 // the cv-qualification of the decomposition expression. 1394 // 1395 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1396 // 'const' to the type of the field. 1397 Qualifiers Q = DecompType.getQualifiers(); 1398 if (FD->isMutable()) 1399 Q.removeConst(); 1400 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1401 } 1402 1403 if (I != Bindings.size()) 1404 return DiagnoseBadNumberOfBindings(); 1405 1406 return false; 1407 } 1408 1409 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1410 QualType DecompType = DD->getType(); 1411 1412 // If the type of the decomposition is dependent, then so is the type of 1413 // each binding. 1414 if (DecompType->isDependentType()) { 1415 for (auto *B : DD->bindings()) 1416 B->setType(Context.DependentTy); 1417 return; 1418 } 1419 1420 DecompType = DecompType.getNonReferenceType(); 1421 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1422 1423 // C++1z [dcl.decomp]/2: 1424 // If E is an array type [...] 1425 // As an extension, we also support decomposition of built-in complex and 1426 // vector types. 1427 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1428 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1429 DD->setInvalidDecl(); 1430 return; 1431 } 1432 if (auto *VT = DecompType->getAs<VectorType>()) { 1433 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1434 DD->setInvalidDecl(); 1435 return; 1436 } 1437 if (auto *CT = DecompType->getAs<ComplexType>()) { 1438 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1439 DD->setInvalidDecl(); 1440 return; 1441 } 1442 1443 // C++1z [dcl.decomp]/3: 1444 // if the expression std::tuple_size<E>::value is a well-formed integral 1445 // constant expression, [...] 1446 llvm::APSInt TupleSize(32); 1447 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1448 case IsTupleLike::Error: 1449 DD->setInvalidDecl(); 1450 return; 1451 1452 case IsTupleLike::TupleLike: 1453 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1454 DD->setInvalidDecl(); 1455 return; 1456 1457 case IsTupleLike::NotTupleLike: 1458 break; 1459 } 1460 1461 // C++1z [dcl.dcl]/8: 1462 // [E shall be of array or non-union class type] 1463 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1464 if (!RD || RD->isUnion()) { 1465 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1466 << DD << !RD << DecompType; 1467 DD->setInvalidDecl(); 1468 return; 1469 } 1470 1471 // C++1z [dcl.decomp]/4: 1472 // all of E's non-static data members shall be [...] direct members of 1473 // E or of the same unambiguous public base class of E, ... 1474 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1475 DD->setInvalidDecl(); 1476 } 1477 1478 /// Merge the exception specifications of two variable declarations. 1479 /// 1480 /// This is called when there's a redeclaration of a VarDecl. The function 1481 /// checks if the redeclaration might have an exception specification and 1482 /// validates compatibility and merges the specs if necessary. 1483 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1484 // Shortcut if exceptions are disabled. 1485 if (!getLangOpts().CXXExceptions) 1486 return; 1487 1488 assert(Context.hasSameType(New->getType(), Old->getType()) && 1489 "Should only be called if types are otherwise the same."); 1490 1491 QualType NewType = New->getType(); 1492 QualType OldType = Old->getType(); 1493 1494 // We're only interested in pointers and references to functions, as well 1495 // as pointers to member functions. 1496 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1497 NewType = R->getPointeeType(); 1498 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1499 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1500 NewType = P->getPointeeType(); 1501 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1502 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1503 NewType = M->getPointeeType(); 1504 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1505 } 1506 1507 if (!NewType->isFunctionProtoType()) 1508 return; 1509 1510 // There's lots of special cases for functions. For function pointers, system 1511 // libraries are hopefully not as broken so that we don't need these 1512 // workarounds. 1513 if (CheckEquivalentExceptionSpec( 1514 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1515 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1516 New->setInvalidDecl(); 1517 } 1518 } 1519 1520 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1521 /// function declaration are well-formed according to C++ 1522 /// [dcl.fct.default]. 1523 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1524 unsigned NumParams = FD->getNumParams(); 1525 unsigned p; 1526 1527 // Find first parameter with a default argument 1528 for (p = 0; p < NumParams; ++p) { 1529 ParmVarDecl *Param = FD->getParamDecl(p); 1530 if (Param->hasDefaultArg()) 1531 break; 1532 } 1533 1534 // C++11 [dcl.fct.default]p4: 1535 // In a given function declaration, each parameter subsequent to a parameter 1536 // with a default argument shall have a default argument supplied in this or 1537 // a previous declaration or shall be a function parameter pack. A default 1538 // argument shall not be redefined by a later declaration (not even to the 1539 // same value). 1540 unsigned LastMissingDefaultArg = 0; 1541 for (; p < NumParams; ++p) { 1542 ParmVarDecl *Param = FD->getParamDecl(p); 1543 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1544 if (Param->isInvalidDecl()) 1545 /* We already complained about this parameter. */; 1546 else if (Param->getIdentifier()) 1547 Diag(Param->getLocation(), 1548 diag::err_param_default_argument_missing_name) 1549 << Param->getIdentifier(); 1550 else 1551 Diag(Param->getLocation(), 1552 diag::err_param_default_argument_missing); 1553 1554 LastMissingDefaultArg = p; 1555 } 1556 } 1557 1558 if (LastMissingDefaultArg > 0) { 1559 // Some default arguments were missing. Clear out all of the 1560 // default arguments up to (and including) the last missing 1561 // default argument, so that we leave the function parameters 1562 // in a semantically valid state. 1563 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1564 ParmVarDecl *Param = FD->getParamDecl(p); 1565 if (Param->hasDefaultArg()) { 1566 Param->setDefaultArg(nullptr); 1567 } 1568 } 1569 } 1570 } 1571 1572 /// Check that the given type is a literal type. Issue a diagnostic if not, 1573 /// if Kind is Diagnose. 1574 /// \return \c true if a problem has been found (and optionally diagnosed). 1575 template <typename... Ts> 1576 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1577 SourceLocation Loc, QualType T, unsigned DiagID, 1578 Ts &&...DiagArgs) { 1579 if (T->isDependentType()) 1580 return false; 1581 1582 switch (Kind) { 1583 case Sema::CheckConstexprKind::Diagnose: 1584 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1585 std::forward<Ts>(DiagArgs)...); 1586 1587 case Sema::CheckConstexprKind::CheckValid: 1588 return !T->isLiteralType(SemaRef.Context); 1589 } 1590 1591 llvm_unreachable("unknown CheckConstexprKind"); 1592 } 1593 1594 // CheckConstexprParameterTypes - Check whether a function's parameter types 1595 // are all literal types. If so, return true. If not, produce a suitable 1596 // diagnostic and return false. 1597 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1598 const FunctionDecl *FD, 1599 Sema::CheckConstexprKind Kind) { 1600 unsigned ArgIndex = 0; 1601 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1602 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1603 e = FT->param_type_end(); 1604 i != e; ++i, ++ArgIndex) { 1605 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1606 SourceLocation ParamLoc = PD->getLocation(); 1607 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1608 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1609 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1610 FD->isConsteval())) 1611 return false; 1612 } 1613 return true; 1614 } 1615 1616 /// Get diagnostic %select index for tag kind for 1617 /// record diagnostic message. 1618 /// WARNING: Indexes apply to particular diagnostics only! 1619 /// 1620 /// \returns diagnostic %select index. 1621 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1622 switch (Tag) { 1623 case TTK_Struct: return 0; 1624 case TTK_Interface: return 1; 1625 case TTK_Class: return 2; 1626 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1627 } 1628 } 1629 1630 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1631 Stmt *Body, 1632 Sema::CheckConstexprKind Kind); 1633 1634 // Check whether a function declaration satisfies the requirements of a 1635 // constexpr function definition or a constexpr constructor definition. If so, 1636 // return true. If not, produce appropriate diagnostics (unless asked not to by 1637 // Kind) and return false. 1638 // 1639 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1640 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1641 CheckConstexprKind Kind) { 1642 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1643 if (MD && MD->isInstance()) { 1644 // C++11 [dcl.constexpr]p4: 1645 // The definition of a constexpr constructor shall satisfy the following 1646 // constraints: 1647 // - the class shall not have any virtual base classes; 1648 // 1649 // FIXME: This only applies to constructors, not arbitrary member 1650 // functions. 1651 const CXXRecordDecl *RD = MD->getParent(); 1652 if (RD->getNumVBases()) { 1653 if (Kind == CheckConstexprKind::CheckValid) 1654 return false; 1655 1656 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1657 << isa<CXXConstructorDecl>(NewFD) 1658 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1659 for (const auto &I : RD->vbases()) 1660 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1661 << I.getSourceRange(); 1662 return false; 1663 } 1664 } 1665 1666 if (!isa<CXXConstructorDecl>(NewFD)) { 1667 // C++11 [dcl.constexpr]p3: 1668 // The definition of a constexpr function shall satisfy the following 1669 // constraints: 1670 // - it shall not be virtual; (removed in C++20) 1671 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1672 if (Method && Method->isVirtual()) { 1673 if (getLangOpts().CPlusPlus2a) { 1674 if (Kind == CheckConstexprKind::Diagnose) 1675 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1676 } else { 1677 if (Kind == CheckConstexprKind::CheckValid) 1678 return false; 1679 1680 Method = Method->getCanonicalDecl(); 1681 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1682 1683 // If it's not obvious why this function is virtual, find an overridden 1684 // function which uses the 'virtual' keyword. 1685 const CXXMethodDecl *WrittenVirtual = Method; 1686 while (!WrittenVirtual->isVirtualAsWritten()) 1687 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1688 if (WrittenVirtual != Method) 1689 Diag(WrittenVirtual->getLocation(), 1690 diag::note_overridden_virtual_function); 1691 return false; 1692 } 1693 } 1694 1695 // - its return type shall be a literal type; 1696 QualType RT = NewFD->getReturnType(); 1697 if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT, 1698 diag::err_constexpr_non_literal_return, 1699 NewFD->isConsteval())) 1700 return false; 1701 } 1702 1703 // - each of its parameter types shall be a literal type; 1704 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1705 return false; 1706 1707 Stmt *Body = NewFD->getBody(); 1708 assert(Body && 1709 "CheckConstexprFunctionDefinition called on function with no body"); 1710 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1711 } 1712 1713 /// Check the given declaration statement is legal within a constexpr function 1714 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1715 /// 1716 /// \return true if the body is OK (maybe only as an extension), false if we 1717 /// have diagnosed a problem. 1718 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1719 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1720 Sema::CheckConstexprKind Kind) { 1721 // C++11 [dcl.constexpr]p3 and p4: 1722 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1723 // contain only 1724 for (const auto *DclIt : DS->decls()) { 1725 switch (DclIt->getKind()) { 1726 case Decl::StaticAssert: 1727 case Decl::Using: 1728 case Decl::UsingShadow: 1729 case Decl::UsingDirective: 1730 case Decl::UnresolvedUsingTypename: 1731 case Decl::UnresolvedUsingValue: 1732 // - static_assert-declarations 1733 // - using-declarations, 1734 // - using-directives, 1735 continue; 1736 1737 case Decl::Typedef: 1738 case Decl::TypeAlias: { 1739 // - typedef declarations and alias-declarations that do not define 1740 // classes or enumerations, 1741 const auto *TN = cast<TypedefNameDecl>(DclIt); 1742 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1743 // Don't allow variably-modified types in constexpr functions. 1744 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1745 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1746 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1747 << TL.getSourceRange() << TL.getType() 1748 << isa<CXXConstructorDecl>(Dcl); 1749 } 1750 return false; 1751 } 1752 continue; 1753 } 1754 1755 case Decl::Enum: 1756 case Decl::CXXRecord: 1757 // C++1y allows types to be defined, not just declared. 1758 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1759 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1760 SemaRef.Diag(DS->getBeginLoc(), 1761 SemaRef.getLangOpts().CPlusPlus14 1762 ? diag::warn_cxx11_compat_constexpr_type_definition 1763 : diag::ext_constexpr_type_definition) 1764 << isa<CXXConstructorDecl>(Dcl); 1765 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1766 return false; 1767 } 1768 } 1769 continue; 1770 1771 case Decl::EnumConstant: 1772 case Decl::IndirectField: 1773 case Decl::ParmVar: 1774 // These can only appear with other declarations which are banned in 1775 // C++11 and permitted in C++1y, so ignore them. 1776 continue; 1777 1778 case Decl::Var: 1779 case Decl::Decomposition: { 1780 // C++1y [dcl.constexpr]p3 allows anything except: 1781 // a definition of a variable of non-literal type or of static or 1782 // thread storage duration or for which no initialization is performed. 1783 const auto *VD = cast<VarDecl>(DclIt); 1784 if (VD->isThisDeclarationADefinition()) { 1785 if (VD->isStaticLocal()) { 1786 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1787 SemaRef.Diag(VD->getLocation(), 1788 diag::err_constexpr_local_var_static) 1789 << isa<CXXConstructorDecl>(Dcl) 1790 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1791 } 1792 return false; 1793 } 1794 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1795 diag::err_constexpr_local_var_non_literal_type, 1796 isa<CXXConstructorDecl>(Dcl))) 1797 return false; 1798 if (!VD->getType()->isDependentType() && 1799 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1800 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1801 SemaRef.Diag(VD->getLocation(), 1802 diag::err_constexpr_local_var_no_init) 1803 << isa<CXXConstructorDecl>(Dcl); 1804 } 1805 return false; 1806 } 1807 } 1808 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1809 SemaRef.Diag(VD->getLocation(), 1810 SemaRef.getLangOpts().CPlusPlus14 1811 ? diag::warn_cxx11_compat_constexpr_local_var 1812 : diag::ext_constexpr_local_var) 1813 << isa<CXXConstructorDecl>(Dcl); 1814 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1815 return false; 1816 } 1817 continue; 1818 } 1819 1820 case Decl::NamespaceAlias: 1821 case Decl::Function: 1822 // These are disallowed in C++11 and permitted in C++1y. Allow them 1823 // everywhere as an extension. 1824 if (!Cxx1yLoc.isValid()) 1825 Cxx1yLoc = DS->getBeginLoc(); 1826 continue; 1827 1828 default: 1829 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1830 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1831 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1832 } 1833 return false; 1834 } 1835 } 1836 1837 return true; 1838 } 1839 1840 /// Check that the given field is initialized within a constexpr constructor. 1841 /// 1842 /// \param Dcl The constexpr constructor being checked. 1843 /// \param Field The field being checked. This may be a member of an anonymous 1844 /// struct or union nested within the class being checked. 1845 /// \param Inits All declarations, including anonymous struct/union members and 1846 /// indirect members, for which any initialization was provided. 1847 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1848 /// multiple notes for different members to the same error. 1849 /// \param Kind Whether we're diagnosing a constructor as written or determining 1850 /// whether the formal requirements are satisfied. 1851 /// \return \c false if we're checking for validity and the constructor does 1852 /// not satisfy the requirements on a constexpr constructor. 1853 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1854 const FunctionDecl *Dcl, 1855 FieldDecl *Field, 1856 llvm::SmallSet<Decl*, 16> &Inits, 1857 bool &Diagnosed, 1858 Sema::CheckConstexprKind Kind) { 1859 if (Field->isInvalidDecl()) 1860 return true; 1861 1862 if (Field->isUnnamedBitfield()) 1863 return true; 1864 1865 // Anonymous unions with no variant members and empty anonymous structs do not 1866 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1867 // indirect fields don't need initializing. 1868 if (Field->isAnonymousStructOrUnion() && 1869 (Field->getType()->isUnionType() 1870 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1871 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1872 return true; 1873 1874 if (!Inits.count(Field)) { 1875 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1876 if (!Diagnosed) { 1877 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1878 Diagnosed = true; 1879 } 1880 SemaRef.Diag(Field->getLocation(), 1881 diag::note_constexpr_ctor_missing_init); 1882 } else { 1883 return false; 1884 } 1885 } else if (Field->isAnonymousStructOrUnion()) { 1886 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1887 for (auto *I : RD->fields()) 1888 // If an anonymous union contains an anonymous struct of which any member 1889 // is initialized, all members must be initialized. 1890 if (!RD->isUnion() || Inits.count(I)) 1891 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1892 Kind)) 1893 return false; 1894 } 1895 return true; 1896 } 1897 1898 /// Check the provided statement is allowed in a constexpr function 1899 /// definition. 1900 static bool 1901 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1902 SmallVectorImpl<SourceLocation> &ReturnStmts, 1903 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1904 Sema::CheckConstexprKind Kind) { 1905 // - its function-body shall be [...] a compound-statement that contains only 1906 switch (S->getStmtClass()) { 1907 case Stmt::NullStmtClass: 1908 // - null statements, 1909 return true; 1910 1911 case Stmt::DeclStmtClass: 1912 // - static_assert-declarations 1913 // - using-declarations, 1914 // - using-directives, 1915 // - typedef declarations and alias-declarations that do not define 1916 // classes or enumerations, 1917 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1918 return false; 1919 return true; 1920 1921 case Stmt::ReturnStmtClass: 1922 // - and exactly one return statement; 1923 if (isa<CXXConstructorDecl>(Dcl)) { 1924 // C++1y allows return statements in constexpr constructors. 1925 if (!Cxx1yLoc.isValid()) 1926 Cxx1yLoc = S->getBeginLoc(); 1927 return true; 1928 } 1929 1930 ReturnStmts.push_back(S->getBeginLoc()); 1931 return true; 1932 1933 case Stmt::CompoundStmtClass: { 1934 // C++1y allows compound-statements. 1935 if (!Cxx1yLoc.isValid()) 1936 Cxx1yLoc = S->getBeginLoc(); 1937 1938 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1939 for (auto *BodyIt : CompStmt->body()) { 1940 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1941 Cxx1yLoc, Cxx2aLoc, Kind)) 1942 return false; 1943 } 1944 return true; 1945 } 1946 1947 case Stmt::AttributedStmtClass: 1948 if (!Cxx1yLoc.isValid()) 1949 Cxx1yLoc = S->getBeginLoc(); 1950 return true; 1951 1952 case Stmt::IfStmtClass: { 1953 // C++1y allows if-statements. 1954 if (!Cxx1yLoc.isValid()) 1955 Cxx1yLoc = S->getBeginLoc(); 1956 1957 IfStmt *If = cast<IfStmt>(S); 1958 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1959 Cxx1yLoc, Cxx2aLoc, Kind)) 1960 return false; 1961 if (If->getElse() && 1962 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1963 Cxx1yLoc, Cxx2aLoc, Kind)) 1964 return false; 1965 return true; 1966 } 1967 1968 case Stmt::WhileStmtClass: 1969 case Stmt::DoStmtClass: 1970 case Stmt::ForStmtClass: 1971 case Stmt::CXXForRangeStmtClass: 1972 case Stmt::ContinueStmtClass: 1973 // C++1y allows all of these. We don't allow them as extensions in C++11, 1974 // because they don't make sense without variable mutation. 1975 if (!SemaRef.getLangOpts().CPlusPlus14) 1976 break; 1977 if (!Cxx1yLoc.isValid()) 1978 Cxx1yLoc = S->getBeginLoc(); 1979 for (Stmt *SubStmt : S->children()) 1980 if (SubStmt && 1981 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1982 Cxx1yLoc, Cxx2aLoc, Kind)) 1983 return false; 1984 return true; 1985 1986 case Stmt::SwitchStmtClass: 1987 case Stmt::CaseStmtClass: 1988 case Stmt::DefaultStmtClass: 1989 case Stmt::BreakStmtClass: 1990 // C++1y allows switch-statements, and since they don't need variable 1991 // mutation, we can reasonably allow them in C++11 as an extension. 1992 if (!Cxx1yLoc.isValid()) 1993 Cxx1yLoc = S->getBeginLoc(); 1994 for (Stmt *SubStmt : S->children()) 1995 if (SubStmt && 1996 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1997 Cxx1yLoc, Cxx2aLoc, Kind)) 1998 return false; 1999 return true; 2000 2001 case Stmt::CXXTryStmtClass: 2002 if (Cxx2aLoc.isInvalid()) 2003 Cxx2aLoc = S->getBeginLoc(); 2004 for (Stmt *SubStmt : S->children()) { 2005 if (SubStmt && 2006 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2007 Cxx1yLoc, Cxx2aLoc, Kind)) 2008 return false; 2009 } 2010 return true; 2011 2012 case Stmt::CXXCatchStmtClass: 2013 // Do not bother checking the language mode (already covered by the 2014 // try block check). 2015 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2016 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2017 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2018 return false; 2019 return true; 2020 2021 default: 2022 if (!isa<Expr>(S)) 2023 break; 2024 2025 // C++1y allows expression-statements. 2026 if (!Cxx1yLoc.isValid()) 2027 Cxx1yLoc = S->getBeginLoc(); 2028 return true; 2029 } 2030 2031 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2032 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2033 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2034 } 2035 return false; 2036 } 2037 2038 /// Check the body for the given constexpr function declaration only contains 2039 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2040 /// 2041 /// \return true if the body is OK, false if we have found or diagnosed a 2042 /// problem. 2043 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2044 Stmt *Body, 2045 Sema::CheckConstexprKind Kind) { 2046 SmallVector<SourceLocation, 4> ReturnStmts; 2047 2048 if (isa<CXXTryStmt>(Body)) { 2049 // C++11 [dcl.constexpr]p3: 2050 // The definition of a constexpr function shall satisfy the following 2051 // constraints: [...] 2052 // - its function-body shall be = delete, = default, or a 2053 // compound-statement 2054 // 2055 // C++11 [dcl.constexpr]p4: 2056 // In the definition of a constexpr constructor, [...] 2057 // - its function-body shall not be a function-try-block; 2058 // 2059 // This restriction is lifted in C++2a, as long as inner statements also 2060 // apply the general constexpr rules. 2061 switch (Kind) { 2062 case Sema::CheckConstexprKind::CheckValid: 2063 if (!SemaRef.getLangOpts().CPlusPlus2a) 2064 return false; 2065 break; 2066 2067 case Sema::CheckConstexprKind::Diagnose: 2068 SemaRef.Diag(Body->getBeginLoc(), 2069 !SemaRef.getLangOpts().CPlusPlus2a 2070 ? diag::ext_constexpr_function_try_block_cxx2a 2071 : diag::warn_cxx17_compat_constexpr_function_try_block) 2072 << isa<CXXConstructorDecl>(Dcl); 2073 break; 2074 } 2075 } 2076 2077 // - its function-body shall be [...] a compound-statement that contains only 2078 // [... list of cases ...] 2079 // 2080 // Note that walking the children here is enough to properly check for 2081 // CompoundStmt and CXXTryStmt body. 2082 SourceLocation Cxx1yLoc, Cxx2aLoc; 2083 for (Stmt *SubStmt : Body->children()) { 2084 if (SubStmt && 2085 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2086 Cxx1yLoc, Cxx2aLoc, Kind)) 2087 return false; 2088 } 2089 2090 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2091 // If this is only valid as an extension, report that we don't satisfy the 2092 // constraints of the current language. 2093 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) || 2094 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2095 return false; 2096 } else if (Cxx2aLoc.isValid()) { 2097 SemaRef.Diag(Cxx2aLoc, 2098 SemaRef.getLangOpts().CPlusPlus2a 2099 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2100 : diag::ext_constexpr_body_invalid_stmt_cxx2a) 2101 << isa<CXXConstructorDecl>(Dcl); 2102 } else if (Cxx1yLoc.isValid()) { 2103 SemaRef.Diag(Cxx1yLoc, 2104 SemaRef.getLangOpts().CPlusPlus14 2105 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2106 : diag::ext_constexpr_body_invalid_stmt) 2107 << isa<CXXConstructorDecl>(Dcl); 2108 } 2109 2110 if (const CXXConstructorDecl *Constructor 2111 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2112 const CXXRecordDecl *RD = Constructor->getParent(); 2113 // DR1359: 2114 // - every non-variant non-static data member and base class sub-object 2115 // shall be initialized; 2116 // DR1460: 2117 // - if the class is a union having variant members, exactly one of them 2118 // shall be initialized; 2119 if (RD->isUnion()) { 2120 if (Constructor->getNumCtorInitializers() == 0 && 2121 RD->hasVariantMembers()) { 2122 if (Kind == Sema::CheckConstexprKind::Diagnose) 2123 SemaRef.Diag(Dcl->getLocation(), 2124 diag::err_constexpr_union_ctor_no_init); 2125 return false; 2126 } 2127 } else if (!Constructor->isDependentContext() && 2128 !Constructor->isDelegatingConstructor()) { 2129 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2130 2131 // Skip detailed checking if we have enough initializers, and we would 2132 // allow at most one initializer per member. 2133 bool AnyAnonStructUnionMembers = false; 2134 unsigned Fields = 0; 2135 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2136 E = RD->field_end(); I != E; ++I, ++Fields) { 2137 if (I->isAnonymousStructOrUnion()) { 2138 AnyAnonStructUnionMembers = true; 2139 break; 2140 } 2141 } 2142 // DR1460: 2143 // - if the class is a union-like class, but is not a union, for each of 2144 // its anonymous union members having variant members, exactly one of 2145 // them shall be initialized; 2146 if (AnyAnonStructUnionMembers || 2147 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2148 // Check initialization of non-static data members. Base classes are 2149 // always initialized so do not need to be checked. Dependent bases 2150 // might not have initializers in the member initializer list. 2151 llvm::SmallSet<Decl*, 16> Inits; 2152 for (const auto *I: Constructor->inits()) { 2153 if (FieldDecl *FD = I->getMember()) 2154 Inits.insert(FD); 2155 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2156 Inits.insert(ID->chain_begin(), ID->chain_end()); 2157 } 2158 2159 bool Diagnosed = false; 2160 for (auto *I : RD->fields()) 2161 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2162 Kind)) 2163 return false; 2164 } 2165 } 2166 } else { 2167 if (ReturnStmts.empty()) { 2168 // C++1y doesn't require constexpr functions to contain a 'return' 2169 // statement. We still do, unless the return type might be void, because 2170 // otherwise if there's no return statement, the function cannot 2171 // be used in a core constant expression. 2172 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2173 (Dcl->getReturnType()->isVoidType() || 2174 Dcl->getReturnType()->isDependentType()); 2175 switch (Kind) { 2176 case Sema::CheckConstexprKind::Diagnose: 2177 SemaRef.Diag(Dcl->getLocation(), 2178 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2179 : diag::err_constexpr_body_no_return) 2180 << Dcl->isConsteval(); 2181 if (!OK) 2182 return false; 2183 break; 2184 2185 case Sema::CheckConstexprKind::CheckValid: 2186 // The formal requirements don't include this rule in C++14, even 2187 // though the "must be able to produce a constant expression" rules 2188 // still imply it in some cases. 2189 if (!SemaRef.getLangOpts().CPlusPlus14) 2190 return false; 2191 break; 2192 } 2193 } else if (ReturnStmts.size() > 1) { 2194 switch (Kind) { 2195 case Sema::CheckConstexprKind::Diagnose: 2196 SemaRef.Diag( 2197 ReturnStmts.back(), 2198 SemaRef.getLangOpts().CPlusPlus14 2199 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2200 : diag::ext_constexpr_body_multiple_return); 2201 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2202 SemaRef.Diag(ReturnStmts[I], 2203 diag::note_constexpr_body_previous_return); 2204 break; 2205 2206 case Sema::CheckConstexprKind::CheckValid: 2207 if (!SemaRef.getLangOpts().CPlusPlus14) 2208 return false; 2209 break; 2210 } 2211 } 2212 } 2213 2214 // C++11 [dcl.constexpr]p5: 2215 // if no function argument values exist such that the function invocation 2216 // substitution would produce a constant expression, the program is 2217 // ill-formed; no diagnostic required. 2218 // C++11 [dcl.constexpr]p3: 2219 // - every constructor call and implicit conversion used in initializing the 2220 // return value shall be one of those allowed in a constant expression. 2221 // C++11 [dcl.constexpr]p4: 2222 // - every constructor involved in initializing non-static data members and 2223 // base class sub-objects shall be a constexpr constructor. 2224 // 2225 // Note that this rule is distinct from the "requirements for a constexpr 2226 // function", so is not checked in CheckValid mode. 2227 SmallVector<PartialDiagnosticAt, 8> Diags; 2228 if (Kind == Sema::CheckConstexprKind::Diagnose && 2229 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2230 SemaRef.Diag(Dcl->getLocation(), 2231 diag::ext_constexpr_function_never_constant_expr) 2232 << isa<CXXConstructorDecl>(Dcl); 2233 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2234 SemaRef.Diag(Diags[I].first, Diags[I].second); 2235 // Don't return false here: we allow this for compatibility in 2236 // system headers. 2237 } 2238 2239 return true; 2240 } 2241 2242 /// Get the class that is directly named by the current context. This is the 2243 /// class for which an unqualified-id in this scope could name a constructor 2244 /// or destructor. 2245 /// 2246 /// If the scope specifier denotes a class, this will be that class. 2247 /// If the scope specifier is empty, this will be the class whose 2248 /// member-specification we are currently within. Otherwise, there 2249 /// is no such class. 2250 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2251 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2252 2253 if (SS && SS->isInvalid()) 2254 return nullptr; 2255 2256 if (SS && SS->isNotEmpty()) { 2257 DeclContext *DC = computeDeclContext(*SS, true); 2258 return dyn_cast_or_null<CXXRecordDecl>(DC); 2259 } 2260 2261 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2262 } 2263 2264 /// isCurrentClassName - Determine whether the identifier II is the 2265 /// name of the class type currently being defined. In the case of 2266 /// nested classes, this will only return true if II is the name of 2267 /// the innermost class. 2268 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2269 const CXXScopeSpec *SS) { 2270 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2271 return CurDecl && &II == CurDecl->getIdentifier(); 2272 } 2273 2274 /// Determine whether the identifier II is a typo for the name of 2275 /// the class type currently being defined. If so, update it to the identifier 2276 /// that should have been used. 2277 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2278 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2279 2280 if (!getLangOpts().SpellChecking) 2281 return false; 2282 2283 CXXRecordDecl *CurDecl; 2284 if (SS && SS->isSet() && !SS->isInvalid()) { 2285 DeclContext *DC = computeDeclContext(*SS, true); 2286 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2287 } else 2288 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2289 2290 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2291 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2292 < II->getLength()) { 2293 II = CurDecl->getIdentifier(); 2294 return true; 2295 } 2296 2297 return false; 2298 } 2299 2300 /// Determine whether the given class is a base class of the given 2301 /// class, including looking at dependent bases. 2302 static bool findCircularInheritance(const CXXRecordDecl *Class, 2303 const CXXRecordDecl *Current) { 2304 SmallVector<const CXXRecordDecl*, 8> Queue; 2305 2306 Class = Class->getCanonicalDecl(); 2307 while (true) { 2308 for (const auto &I : Current->bases()) { 2309 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2310 if (!Base) 2311 continue; 2312 2313 Base = Base->getDefinition(); 2314 if (!Base) 2315 continue; 2316 2317 if (Base->getCanonicalDecl() == Class) 2318 return true; 2319 2320 Queue.push_back(Base); 2321 } 2322 2323 if (Queue.empty()) 2324 return false; 2325 2326 Current = Queue.pop_back_val(); 2327 } 2328 2329 return false; 2330 } 2331 2332 /// Check the validity of a C++ base class specifier. 2333 /// 2334 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2335 /// and returns NULL otherwise. 2336 CXXBaseSpecifier * 2337 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2338 SourceRange SpecifierRange, 2339 bool Virtual, AccessSpecifier Access, 2340 TypeSourceInfo *TInfo, 2341 SourceLocation EllipsisLoc) { 2342 QualType BaseType = TInfo->getType(); 2343 2344 // C++ [class.union]p1: 2345 // A union shall not have base classes. 2346 if (Class->isUnion()) { 2347 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2348 << SpecifierRange; 2349 return nullptr; 2350 } 2351 2352 if (EllipsisLoc.isValid() && 2353 !TInfo->getType()->containsUnexpandedParameterPack()) { 2354 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2355 << TInfo->getTypeLoc().getSourceRange(); 2356 EllipsisLoc = SourceLocation(); 2357 } 2358 2359 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2360 2361 if (BaseType->isDependentType()) { 2362 // Make sure that we don't have circular inheritance among our dependent 2363 // bases. For non-dependent bases, the check for completeness below handles 2364 // this. 2365 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2366 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2367 ((BaseDecl = BaseDecl->getDefinition()) && 2368 findCircularInheritance(Class, BaseDecl))) { 2369 Diag(BaseLoc, diag::err_circular_inheritance) 2370 << BaseType << Context.getTypeDeclType(Class); 2371 2372 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2373 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2374 << BaseType; 2375 2376 return nullptr; 2377 } 2378 } 2379 2380 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2381 Class->getTagKind() == TTK_Class, 2382 Access, TInfo, EllipsisLoc); 2383 } 2384 2385 // Base specifiers must be record types. 2386 if (!BaseType->isRecordType()) { 2387 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2388 return nullptr; 2389 } 2390 2391 // C++ [class.union]p1: 2392 // A union shall not be used as a base class. 2393 if (BaseType->isUnionType()) { 2394 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2395 return nullptr; 2396 } 2397 2398 // For the MS ABI, propagate DLL attributes to base class templates. 2399 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2400 if (Attr *ClassAttr = getDLLAttr(Class)) { 2401 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2402 BaseType->getAsCXXRecordDecl())) { 2403 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2404 BaseLoc); 2405 } 2406 } 2407 } 2408 2409 // C++ [class.derived]p2: 2410 // The class-name in a base-specifier shall not be an incompletely 2411 // defined class. 2412 if (RequireCompleteType(BaseLoc, BaseType, 2413 diag::err_incomplete_base_class, SpecifierRange)) { 2414 Class->setInvalidDecl(); 2415 return nullptr; 2416 } 2417 2418 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2419 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2420 assert(BaseDecl && "Record type has no declaration"); 2421 BaseDecl = BaseDecl->getDefinition(); 2422 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2423 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2424 assert(CXXBaseDecl && "Base type is not a C++ type"); 2425 2426 // Microsoft docs say: 2427 // "If a base-class has a code_seg attribute, derived classes must have the 2428 // same attribute." 2429 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2430 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2431 if ((DerivedCSA || BaseCSA) && 2432 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2433 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2434 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2435 << CXXBaseDecl; 2436 return nullptr; 2437 } 2438 2439 // A class which contains a flexible array member is not suitable for use as a 2440 // base class: 2441 // - If the layout determines that a base comes before another base, 2442 // the flexible array member would index into the subsequent base. 2443 // - If the layout determines that base comes before the derived class, 2444 // the flexible array member would index into the derived class. 2445 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2446 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2447 << CXXBaseDecl->getDeclName(); 2448 return nullptr; 2449 } 2450 2451 // C++ [class]p3: 2452 // If a class is marked final and it appears as a base-type-specifier in 2453 // base-clause, the program is ill-formed. 2454 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2455 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2456 << CXXBaseDecl->getDeclName() 2457 << FA->isSpelledAsSealed(); 2458 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2459 << CXXBaseDecl->getDeclName() << FA->getRange(); 2460 return nullptr; 2461 } 2462 2463 if (BaseDecl->isInvalidDecl()) 2464 Class->setInvalidDecl(); 2465 2466 // Create the base specifier. 2467 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2468 Class->getTagKind() == TTK_Class, 2469 Access, TInfo, EllipsisLoc); 2470 } 2471 2472 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2473 /// one entry in the base class list of a class specifier, for 2474 /// example: 2475 /// class foo : public bar, virtual private baz { 2476 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2477 BaseResult 2478 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2479 ParsedAttributes &Attributes, 2480 bool Virtual, AccessSpecifier Access, 2481 ParsedType basetype, SourceLocation BaseLoc, 2482 SourceLocation EllipsisLoc) { 2483 if (!classdecl) 2484 return true; 2485 2486 AdjustDeclIfTemplate(classdecl); 2487 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2488 if (!Class) 2489 return true; 2490 2491 // We haven't yet attached the base specifiers. 2492 Class->setIsParsingBaseSpecifiers(); 2493 2494 // We do not support any C++11 attributes on base-specifiers yet. 2495 // Diagnose any attributes we see. 2496 for (const ParsedAttr &AL : Attributes) { 2497 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2498 continue; 2499 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2500 ? (unsigned)diag::warn_unknown_attribute_ignored 2501 : (unsigned)diag::err_base_specifier_attribute) 2502 << AL.getName(); 2503 } 2504 2505 TypeSourceInfo *TInfo = nullptr; 2506 GetTypeFromParser(basetype, &TInfo); 2507 2508 if (EllipsisLoc.isInvalid() && 2509 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2510 UPPC_BaseType)) 2511 return true; 2512 2513 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2514 Virtual, Access, TInfo, 2515 EllipsisLoc)) 2516 return BaseSpec; 2517 else 2518 Class->setInvalidDecl(); 2519 2520 return true; 2521 } 2522 2523 /// Use small set to collect indirect bases. As this is only used 2524 /// locally, there's no need to abstract the small size parameter. 2525 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2526 2527 /// Recursively add the bases of Type. Don't add Type itself. 2528 static void 2529 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2530 const QualType &Type) 2531 { 2532 // Even though the incoming type is a base, it might not be 2533 // a class -- it could be a template parm, for instance. 2534 if (auto Rec = Type->getAs<RecordType>()) { 2535 auto Decl = Rec->getAsCXXRecordDecl(); 2536 2537 // Iterate over its bases. 2538 for (const auto &BaseSpec : Decl->bases()) { 2539 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2540 .getUnqualifiedType(); 2541 if (Set.insert(Base).second) 2542 // If we've not already seen it, recurse. 2543 NoteIndirectBases(Context, Set, Base); 2544 } 2545 } 2546 } 2547 2548 /// Performs the actual work of attaching the given base class 2549 /// specifiers to a C++ class. 2550 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2551 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2552 if (Bases.empty()) 2553 return false; 2554 2555 // Used to keep track of which base types we have already seen, so 2556 // that we can properly diagnose redundant direct base types. Note 2557 // that the key is always the unqualified canonical type of the base 2558 // class. 2559 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2560 2561 // Used to track indirect bases so we can see if a direct base is 2562 // ambiguous. 2563 IndirectBaseSet IndirectBaseTypes; 2564 2565 // Copy non-redundant base specifiers into permanent storage. 2566 unsigned NumGoodBases = 0; 2567 bool Invalid = false; 2568 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2569 QualType NewBaseType 2570 = Context.getCanonicalType(Bases[idx]->getType()); 2571 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2572 2573 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2574 if (KnownBase) { 2575 // C++ [class.mi]p3: 2576 // A class shall not be specified as a direct base class of a 2577 // derived class more than once. 2578 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2579 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2580 2581 // Delete the duplicate base class specifier; we're going to 2582 // overwrite its pointer later. 2583 Context.Deallocate(Bases[idx]); 2584 2585 Invalid = true; 2586 } else { 2587 // Okay, add this new base class. 2588 KnownBase = Bases[idx]; 2589 Bases[NumGoodBases++] = Bases[idx]; 2590 2591 // Note this base's direct & indirect bases, if there could be ambiguity. 2592 if (Bases.size() > 1) 2593 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2594 2595 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2596 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2597 if (Class->isInterface() && 2598 (!RD->isInterfaceLike() || 2599 KnownBase->getAccessSpecifier() != AS_public)) { 2600 // The Microsoft extension __interface does not permit bases that 2601 // are not themselves public interfaces. 2602 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2603 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2604 << RD->getSourceRange(); 2605 Invalid = true; 2606 } 2607 if (RD->hasAttr<WeakAttr>()) 2608 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2609 } 2610 } 2611 } 2612 2613 // Attach the remaining base class specifiers to the derived class. 2614 Class->setBases(Bases.data(), NumGoodBases); 2615 2616 // Check that the only base classes that are duplicate are virtual. 2617 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2618 // Check whether this direct base is inaccessible due to ambiguity. 2619 QualType BaseType = Bases[idx]->getType(); 2620 2621 // Skip all dependent types in templates being used as base specifiers. 2622 // Checks below assume that the base specifier is a CXXRecord. 2623 if (BaseType->isDependentType()) 2624 continue; 2625 2626 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2627 .getUnqualifiedType(); 2628 2629 if (IndirectBaseTypes.count(CanonicalBase)) { 2630 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2631 /*DetectVirtual=*/true); 2632 bool found 2633 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2634 assert(found); 2635 (void)found; 2636 2637 if (Paths.isAmbiguous(CanonicalBase)) 2638 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2639 << BaseType << getAmbiguousPathsDisplayString(Paths) 2640 << Bases[idx]->getSourceRange(); 2641 else 2642 assert(Bases[idx]->isVirtual()); 2643 } 2644 2645 // Delete the base class specifier, since its data has been copied 2646 // into the CXXRecordDecl. 2647 Context.Deallocate(Bases[idx]); 2648 } 2649 2650 return Invalid; 2651 } 2652 2653 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2654 /// class, after checking whether there are any duplicate base 2655 /// classes. 2656 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2657 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2658 if (!ClassDecl || Bases.empty()) 2659 return; 2660 2661 AdjustDeclIfTemplate(ClassDecl); 2662 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2663 } 2664 2665 /// Determine whether the type \p Derived is a C++ class that is 2666 /// derived from the type \p Base. 2667 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2668 if (!getLangOpts().CPlusPlus) 2669 return false; 2670 2671 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2672 if (!DerivedRD) 2673 return false; 2674 2675 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2676 if (!BaseRD) 2677 return false; 2678 2679 // If either the base or the derived type is invalid, don't try to 2680 // check whether one is derived from the other. 2681 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2682 return false; 2683 2684 // FIXME: In a modules build, do we need the entire path to be visible for us 2685 // to be able to use the inheritance relationship? 2686 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2687 return false; 2688 2689 return DerivedRD->isDerivedFrom(BaseRD); 2690 } 2691 2692 /// Determine whether the type \p Derived is a C++ class that is 2693 /// derived from the type \p Base. 2694 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2695 CXXBasePaths &Paths) { 2696 if (!getLangOpts().CPlusPlus) 2697 return false; 2698 2699 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2700 if (!DerivedRD) 2701 return false; 2702 2703 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2704 if (!BaseRD) 2705 return false; 2706 2707 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2708 return false; 2709 2710 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2711 } 2712 2713 static void BuildBasePathArray(const CXXBasePath &Path, 2714 CXXCastPath &BasePathArray) { 2715 // We first go backward and check if we have a virtual base. 2716 // FIXME: It would be better if CXXBasePath had the base specifier for 2717 // the nearest virtual base. 2718 unsigned Start = 0; 2719 for (unsigned I = Path.size(); I != 0; --I) { 2720 if (Path[I - 1].Base->isVirtual()) { 2721 Start = I - 1; 2722 break; 2723 } 2724 } 2725 2726 // Now add all bases. 2727 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2728 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2729 } 2730 2731 2732 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2733 CXXCastPath &BasePathArray) { 2734 assert(BasePathArray.empty() && "Base path array must be empty!"); 2735 assert(Paths.isRecordingPaths() && "Must record paths!"); 2736 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2737 } 2738 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2739 /// conversion (where Derived and Base are class types) is 2740 /// well-formed, meaning that the conversion is unambiguous (and 2741 /// that all of the base classes are accessible). Returns true 2742 /// and emits a diagnostic if the code is ill-formed, returns false 2743 /// otherwise. Loc is the location where this routine should point to 2744 /// if there is an error, and Range is the source range to highlight 2745 /// if there is an error. 2746 /// 2747 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2748 /// diagnostic for the respective type of error will be suppressed, but the 2749 /// check for ill-formed code will still be performed. 2750 bool 2751 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2752 unsigned InaccessibleBaseID, 2753 unsigned AmbigiousBaseConvID, 2754 SourceLocation Loc, SourceRange Range, 2755 DeclarationName Name, 2756 CXXCastPath *BasePath, 2757 bool IgnoreAccess) { 2758 // First, determine whether the path from Derived to Base is 2759 // ambiguous. This is slightly more expensive than checking whether 2760 // the Derived to Base conversion exists, because here we need to 2761 // explore multiple paths to determine if there is an ambiguity. 2762 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2763 /*DetectVirtual=*/false); 2764 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2765 if (!DerivationOkay) 2766 return true; 2767 2768 const CXXBasePath *Path = nullptr; 2769 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2770 Path = &Paths.front(); 2771 2772 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2773 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2774 // user to access such bases. 2775 if (!Path && getLangOpts().MSVCCompat) { 2776 for (const CXXBasePath &PossiblePath : Paths) { 2777 if (PossiblePath.size() == 1) { 2778 Path = &PossiblePath; 2779 if (AmbigiousBaseConvID) 2780 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2781 << Base << Derived << Range; 2782 break; 2783 } 2784 } 2785 } 2786 2787 if (Path) { 2788 if (!IgnoreAccess) { 2789 // Check that the base class can be accessed. 2790 switch ( 2791 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2792 case AR_inaccessible: 2793 return true; 2794 case AR_accessible: 2795 case AR_dependent: 2796 case AR_delayed: 2797 break; 2798 } 2799 } 2800 2801 // Build a base path if necessary. 2802 if (BasePath) 2803 ::BuildBasePathArray(*Path, *BasePath); 2804 return false; 2805 } 2806 2807 if (AmbigiousBaseConvID) { 2808 // We know that the derived-to-base conversion is ambiguous, and 2809 // we're going to produce a diagnostic. Perform the derived-to-base 2810 // search just one more time to compute all of the possible paths so 2811 // that we can print them out. This is more expensive than any of 2812 // the previous derived-to-base checks we've done, but at this point 2813 // performance isn't as much of an issue. 2814 Paths.clear(); 2815 Paths.setRecordingPaths(true); 2816 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2817 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2818 (void)StillOkay; 2819 2820 // Build up a textual representation of the ambiguous paths, e.g., 2821 // D -> B -> A, that will be used to illustrate the ambiguous 2822 // conversions in the diagnostic. We only print one of the paths 2823 // to each base class subobject. 2824 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2825 2826 Diag(Loc, AmbigiousBaseConvID) 2827 << Derived << Base << PathDisplayStr << Range << Name; 2828 } 2829 return true; 2830 } 2831 2832 bool 2833 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2834 SourceLocation Loc, SourceRange Range, 2835 CXXCastPath *BasePath, 2836 bool IgnoreAccess) { 2837 return CheckDerivedToBaseConversion( 2838 Derived, Base, diag::err_upcast_to_inaccessible_base, 2839 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2840 BasePath, IgnoreAccess); 2841 } 2842 2843 2844 /// Builds a string representing ambiguous paths from a 2845 /// specific derived class to different subobjects of the same base 2846 /// class. 2847 /// 2848 /// This function builds a string that can be used in error messages 2849 /// to show the different paths that one can take through the 2850 /// inheritance hierarchy to go from the derived class to different 2851 /// subobjects of a base class. The result looks something like this: 2852 /// @code 2853 /// struct D -> struct B -> struct A 2854 /// struct D -> struct C -> struct A 2855 /// @endcode 2856 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2857 std::string PathDisplayStr; 2858 std::set<unsigned> DisplayedPaths; 2859 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2860 Path != Paths.end(); ++Path) { 2861 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2862 // We haven't displayed a path to this particular base 2863 // class subobject yet. 2864 PathDisplayStr += "\n "; 2865 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2866 for (CXXBasePath::const_iterator Element = Path->begin(); 2867 Element != Path->end(); ++Element) 2868 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2869 } 2870 } 2871 2872 return PathDisplayStr; 2873 } 2874 2875 //===----------------------------------------------------------------------===// 2876 // C++ class member Handling 2877 //===----------------------------------------------------------------------===// 2878 2879 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2880 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2881 SourceLocation ColonLoc, 2882 const ParsedAttributesView &Attrs) { 2883 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2884 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2885 ASLoc, ColonLoc); 2886 CurContext->addHiddenDecl(ASDecl); 2887 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2888 } 2889 2890 /// CheckOverrideControl - Check C++11 override control semantics. 2891 void Sema::CheckOverrideControl(NamedDecl *D) { 2892 if (D->isInvalidDecl()) 2893 return; 2894 2895 // We only care about "override" and "final" declarations. 2896 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2897 return; 2898 2899 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2900 2901 // We can't check dependent instance methods. 2902 if (MD && MD->isInstance() && 2903 (MD->getParent()->hasAnyDependentBases() || 2904 MD->getType()->isDependentType())) 2905 return; 2906 2907 if (MD && !MD->isVirtual()) { 2908 // If we have a non-virtual method, check if if hides a virtual method. 2909 // (In that case, it's most likely the method has the wrong type.) 2910 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2911 FindHiddenVirtualMethods(MD, OverloadedMethods); 2912 2913 if (!OverloadedMethods.empty()) { 2914 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2915 Diag(OA->getLocation(), 2916 diag::override_keyword_hides_virtual_member_function) 2917 << "override" << (OverloadedMethods.size() > 1); 2918 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2919 Diag(FA->getLocation(), 2920 diag::override_keyword_hides_virtual_member_function) 2921 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2922 << (OverloadedMethods.size() > 1); 2923 } 2924 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2925 MD->setInvalidDecl(); 2926 return; 2927 } 2928 // Fall through into the general case diagnostic. 2929 // FIXME: We might want to attempt typo correction here. 2930 } 2931 2932 if (!MD || !MD->isVirtual()) { 2933 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2934 Diag(OA->getLocation(), 2935 diag::override_keyword_only_allowed_on_virtual_member_functions) 2936 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2937 D->dropAttr<OverrideAttr>(); 2938 } 2939 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2940 Diag(FA->getLocation(), 2941 diag::override_keyword_only_allowed_on_virtual_member_functions) 2942 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2943 << FixItHint::CreateRemoval(FA->getLocation()); 2944 D->dropAttr<FinalAttr>(); 2945 } 2946 return; 2947 } 2948 2949 // C++11 [class.virtual]p5: 2950 // If a function is marked with the virt-specifier override and 2951 // does not override a member function of a base class, the program is 2952 // ill-formed. 2953 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2954 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2955 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2956 << MD->getDeclName(); 2957 } 2958 2959 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2960 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2961 return; 2962 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2963 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2964 return; 2965 2966 SourceLocation Loc = MD->getLocation(); 2967 SourceLocation SpellingLoc = Loc; 2968 if (getSourceManager().isMacroArgExpansion(Loc)) 2969 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 2970 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2971 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2972 return; 2973 2974 if (MD->size_overridden_methods() > 0) { 2975 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2976 ? diag::warn_destructor_marked_not_override_overriding 2977 : diag::warn_function_marked_not_override_overriding; 2978 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2979 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2980 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2981 } 2982 } 2983 2984 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2985 /// function overrides a virtual member function marked 'final', according to 2986 /// C++11 [class.virtual]p4. 2987 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2988 const CXXMethodDecl *Old) { 2989 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2990 if (!FA) 2991 return false; 2992 2993 Diag(New->getLocation(), diag::err_final_function_overridden) 2994 << New->getDeclName() 2995 << FA->isSpelledAsSealed(); 2996 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2997 return true; 2998 } 2999 3000 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3001 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3002 // FIXME: Destruction of ObjC lifetime types has side-effects. 3003 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3004 return !RD->isCompleteDefinition() || 3005 !RD->hasTrivialDefaultConstructor() || 3006 !RD->hasTrivialDestructor(); 3007 return false; 3008 } 3009 3010 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3011 ParsedAttributesView::const_iterator Itr = 3012 llvm::find_if(list, [](const ParsedAttr &AL) { 3013 return AL.isDeclspecPropertyAttribute(); 3014 }); 3015 if (Itr != list.end()) 3016 return &*Itr; 3017 return nullptr; 3018 } 3019 3020 // Check if there is a field shadowing. 3021 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3022 DeclarationName FieldName, 3023 const CXXRecordDecl *RD, 3024 bool DeclIsField) { 3025 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3026 return; 3027 3028 // To record a shadowed field in a base 3029 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3030 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3031 CXXBasePath &Path) { 3032 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3033 // Record an ambiguous path directly 3034 if (Bases.find(Base) != Bases.end()) 3035 return true; 3036 for (const auto Field : Base->lookup(FieldName)) { 3037 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3038 Field->getAccess() != AS_private) { 3039 assert(Field->getAccess() != AS_none); 3040 assert(Bases.find(Base) == Bases.end()); 3041 Bases[Base] = Field; 3042 return true; 3043 } 3044 } 3045 return false; 3046 }; 3047 3048 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3049 /*DetectVirtual=*/true); 3050 if (!RD->lookupInBases(FieldShadowed, Paths)) 3051 return; 3052 3053 for (const auto &P : Paths) { 3054 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3055 auto It = Bases.find(Base); 3056 // Skip duplicated bases 3057 if (It == Bases.end()) 3058 continue; 3059 auto BaseField = It->second; 3060 assert(BaseField->getAccess() != AS_private); 3061 if (AS_none != 3062 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3063 Diag(Loc, diag::warn_shadow_field) 3064 << FieldName << RD << Base << DeclIsField; 3065 Diag(BaseField->getLocation(), diag::note_shadow_field); 3066 Bases.erase(It); 3067 } 3068 } 3069 } 3070 3071 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3072 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3073 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3074 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3075 /// present (but parsing it has been deferred). 3076 NamedDecl * 3077 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3078 MultiTemplateParamsArg TemplateParameterLists, 3079 Expr *BW, const VirtSpecifiers &VS, 3080 InClassInitStyle InitStyle) { 3081 const DeclSpec &DS = D.getDeclSpec(); 3082 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3083 DeclarationName Name = NameInfo.getName(); 3084 SourceLocation Loc = NameInfo.getLoc(); 3085 3086 // For anonymous bitfields, the location should point to the type. 3087 if (Loc.isInvalid()) 3088 Loc = D.getBeginLoc(); 3089 3090 Expr *BitWidth = static_cast<Expr*>(BW); 3091 3092 assert(isa<CXXRecordDecl>(CurContext)); 3093 assert(!DS.isFriendSpecified()); 3094 3095 bool isFunc = D.isDeclarationOfFunction(); 3096 const ParsedAttr *MSPropertyAttr = 3097 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3098 3099 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3100 // The Microsoft extension __interface only permits public member functions 3101 // and prohibits constructors, destructors, operators, non-public member 3102 // functions, static methods and data members. 3103 unsigned InvalidDecl; 3104 bool ShowDeclName = true; 3105 if (!isFunc && 3106 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3107 InvalidDecl = 0; 3108 else if (!isFunc) 3109 InvalidDecl = 1; 3110 else if (AS != AS_public) 3111 InvalidDecl = 2; 3112 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3113 InvalidDecl = 3; 3114 else switch (Name.getNameKind()) { 3115 case DeclarationName::CXXConstructorName: 3116 InvalidDecl = 4; 3117 ShowDeclName = false; 3118 break; 3119 3120 case DeclarationName::CXXDestructorName: 3121 InvalidDecl = 5; 3122 ShowDeclName = false; 3123 break; 3124 3125 case DeclarationName::CXXOperatorName: 3126 case DeclarationName::CXXConversionFunctionName: 3127 InvalidDecl = 6; 3128 break; 3129 3130 default: 3131 InvalidDecl = 0; 3132 break; 3133 } 3134 3135 if (InvalidDecl) { 3136 if (ShowDeclName) 3137 Diag(Loc, diag::err_invalid_member_in_interface) 3138 << (InvalidDecl-1) << Name; 3139 else 3140 Diag(Loc, diag::err_invalid_member_in_interface) 3141 << (InvalidDecl-1) << ""; 3142 return nullptr; 3143 } 3144 } 3145 3146 // C++ 9.2p6: A member shall not be declared to have automatic storage 3147 // duration (auto, register) or with the extern storage-class-specifier. 3148 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3149 // data members and cannot be applied to names declared const or static, 3150 // and cannot be applied to reference members. 3151 switch (DS.getStorageClassSpec()) { 3152 case DeclSpec::SCS_unspecified: 3153 case DeclSpec::SCS_typedef: 3154 case DeclSpec::SCS_static: 3155 break; 3156 case DeclSpec::SCS_mutable: 3157 if (isFunc) { 3158 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3159 3160 // FIXME: It would be nicer if the keyword was ignored only for this 3161 // declarator. Otherwise we could get follow-up errors. 3162 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3163 } 3164 break; 3165 default: 3166 Diag(DS.getStorageClassSpecLoc(), 3167 diag::err_storageclass_invalid_for_member); 3168 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3169 break; 3170 } 3171 3172 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3173 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3174 !isFunc); 3175 3176 if (DS.hasConstexprSpecifier() && isInstField) { 3177 SemaDiagnosticBuilder B = 3178 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3179 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3180 if (InitStyle == ICIS_NoInit) { 3181 B << 0 << 0; 3182 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3183 B << FixItHint::CreateRemoval(ConstexprLoc); 3184 else { 3185 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3186 D.getMutableDeclSpec().ClearConstexprSpec(); 3187 const char *PrevSpec; 3188 unsigned DiagID; 3189 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3190 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3191 (void)Failed; 3192 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3193 } 3194 } else { 3195 B << 1; 3196 const char *PrevSpec; 3197 unsigned DiagID; 3198 if (D.getMutableDeclSpec().SetStorageClassSpec( 3199 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3200 Context.getPrintingPolicy())) { 3201 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3202 "This is the only DeclSpec that should fail to be applied"); 3203 B << 1; 3204 } else { 3205 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3206 isInstField = false; 3207 } 3208 } 3209 } 3210 3211 NamedDecl *Member; 3212 if (isInstField) { 3213 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3214 3215 // Data members must have identifiers for names. 3216 if (!Name.isIdentifier()) { 3217 Diag(Loc, diag::err_bad_variable_name) 3218 << Name; 3219 return nullptr; 3220 } 3221 3222 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3223 3224 // Member field could not be with "template" keyword. 3225 // So TemplateParameterLists should be empty in this case. 3226 if (TemplateParameterLists.size()) { 3227 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3228 if (TemplateParams->size()) { 3229 // There is no such thing as a member field template. 3230 Diag(D.getIdentifierLoc(), diag::err_template_member) 3231 << II 3232 << SourceRange(TemplateParams->getTemplateLoc(), 3233 TemplateParams->getRAngleLoc()); 3234 } else { 3235 // There is an extraneous 'template<>' for this member. 3236 Diag(TemplateParams->getTemplateLoc(), 3237 diag::err_template_member_noparams) 3238 << II 3239 << SourceRange(TemplateParams->getTemplateLoc(), 3240 TemplateParams->getRAngleLoc()); 3241 } 3242 return nullptr; 3243 } 3244 3245 if (SS.isSet() && !SS.isInvalid()) { 3246 // The user provided a superfluous scope specifier inside a class 3247 // definition: 3248 // 3249 // class X { 3250 // int X::member; 3251 // }; 3252 if (DeclContext *DC = computeDeclContext(SS, false)) 3253 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3254 D.getName().getKind() == 3255 UnqualifiedIdKind::IK_TemplateId); 3256 else 3257 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3258 << Name << SS.getRange(); 3259 3260 SS.clear(); 3261 } 3262 3263 if (MSPropertyAttr) { 3264 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3265 BitWidth, InitStyle, AS, *MSPropertyAttr); 3266 if (!Member) 3267 return nullptr; 3268 isInstField = false; 3269 } else { 3270 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3271 BitWidth, InitStyle, AS); 3272 if (!Member) 3273 return nullptr; 3274 } 3275 3276 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3277 } else { 3278 Member = HandleDeclarator(S, D, TemplateParameterLists); 3279 if (!Member) 3280 return nullptr; 3281 3282 // Non-instance-fields can't have a bitfield. 3283 if (BitWidth) { 3284 if (Member->isInvalidDecl()) { 3285 // don't emit another diagnostic. 3286 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3287 // C++ 9.6p3: A bit-field shall not be a static member. 3288 // "static member 'A' cannot be a bit-field" 3289 Diag(Loc, diag::err_static_not_bitfield) 3290 << Name << BitWidth->getSourceRange(); 3291 } else if (isa<TypedefDecl>(Member)) { 3292 // "typedef member 'x' cannot be a bit-field" 3293 Diag(Loc, diag::err_typedef_not_bitfield) 3294 << Name << BitWidth->getSourceRange(); 3295 } else { 3296 // A function typedef ("typedef int f(); f a;"). 3297 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3298 Diag(Loc, diag::err_not_integral_type_bitfield) 3299 << Name << cast<ValueDecl>(Member)->getType() 3300 << BitWidth->getSourceRange(); 3301 } 3302 3303 BitWidth = nullptr; 3304 Member->setInvalidDecl(); 3305 } 3306 3307 NamedDecl *NonTemplateMember = Member; 3308 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3309 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3310 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3311 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3312 3313 Member->setAccess(AS); 3314 3315 // If we have declared a member function template or static data member 3316 // template, set the access of the templated declaration as well. 3317 if (NonTemplateMember != Member) 3318 NonTemplateMember->setAccess(AS); 3319 3320 // C++ [temp.deduct.guide]p3: 3321 // A deduction guide [...] for a member class template [shall be 3322 // declared] with the same access [as the template]. 3323 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3324 auto *TD = DG->getDeducedTemplate(); 3325 // Access specifiers are only meaningful if both the template and the 3326 // deduction guide are from the same scope. 3327 if (AS != TD->getAccess() && 3328 TD->getDeclContext()->getRedeclContext()->Equals( 3329 DG->getDeclContext()->getRedeclContext())) { 3330 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3331 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3332 << TD->getAccess(); 3333 const AccessSpecDecl *LastAccessSpec = nullptr; 3334 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3335 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3336 LastAccessSpec = AccessSpec; 3337 } 3338 assert(LastAccessSpec && "differing access with no access specifier"); 3339 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3340 << AS; 3341 } 3342 } 3343 } 3344 3345 if (VS.isOverrideSpecified()) 3346 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3347 if (VS.isFinalSpecified()) 3348 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3349 VS.isFinalSpelledSealed())); 3350 3351 if (VS.getLastLocation().isValid()) { 3352 // Update the end location of a method that has a virt-specifiers. 3353 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3354 MD->setRangeEnd(VS.getLastLocation()); 3355 } 3356 3357 CheckOverrideControl(Member); 3358 3359 assert((Name || isInstField) && "No identifier for non-field ?"); 3360 3361 if (isInstField) { 3362 FieldDecl *FD = cast<FieldDecl>(Member); 3363 FieldCollector->Add(FD); 3364 3365 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3366 // Remember all explicit private FieldDecls that have a name, no side 3367 // effects and are not part of a dependent type declaration. 3368 if (!FD->isImplicit() && FD->getDeclName() && 3369 FD->getAccess() == AS_private && 3370 !FD->hasAttr<UnusedAttr>() && 3371 !FD->getParent()->isDependentContext() && 3372 !InitializationHasSideEffects(*FD)) 3373 UnusedPrivateFields.insert(FD); 3374 } 3375 } 3376 3377 return Member; 3378 } 3379 3380 namespace { 3381 class UninitializedFieldVisitor 3382 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3383 Sema &S; 3384 // List of Decls to generate a warning on. Also remove Decls that become 3385 // initialized. 3386 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3387 // List of base classes of the record. Classes are removed after their 3388 // initializers. 3389 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3390 // Vector of decls to be removed from the Decl set prior to visiting the 3391 // nodes. These Decls may have been initialized in the prior initializer. 3392 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3393 // If non-null, add a note to the warning pointing back to the constructor. 3394 const CXXConstructorDecl *Constructor; 3395 // Variables to hold state when processing an initializer list. When 3396 // InitList is true, special case initialization of FieldDecls matching 3397 // InitListFieldDecl. 3398 bool InitList; 3399 FieldDecl *InitListFieldDecl; 3400 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3401 3402 public: 3403 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3404 UninitializedFieldVisitor(Sema &S, 3405 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3406 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3407 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3408 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3409 3410 // Returns true if the use of ME is not an uninitialized use. 3411 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3412 bool CheckReferenceOnly) { 3413 llvm::SmallVector<FieldDecl*, 4> Fields; 3414 bool ReferenceField = false; 3415 while (ME) { 3416 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3417 if (!FD) 3418 return false; 3419 Fields.push_back(FD); 3420 if (FD->getType()->isReferenceType()) 3421 ReferenceField = true; 3422 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3423 } 3424 3425 // Binding a reference to an uninitialized field is not an 3426 // uninitialized use. 3427 if (CheckReferenceOnly && !ReferenceField) 3428 return true; 3429 3430 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3431 // Discard the first field since it is the field decl that is being 3432 // initialized. 3433 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3434 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3435 } 3436 3437 for (auto UsedIter = UsedFieldIndex.begin(), 3438 UsedEnd = UsedFieldIndex.end(), 3439 OrigIter = InitFieldIndex.begin(), 3440 OrigEnd = InitFieldIndex.end(); 3441 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3442 if (*UsedIter < *OrigIter) 3443 return true; 3444 if (*UsedIter > *OrigIter) 3445 break; 3446 } 3447 3448 return false; 3449 } 3450 3451 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3452 bool AddressOf) { 3453 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3454 return; 3455 3456 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3457 // or union. 3458 MemberExpr *FieldME = ME; 3459 3460 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3461 3462 Expr *Base = ME; 3463 while (MemberExpr *SubME = 3464 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3465 3466 if (isa<VarDecl>(SubME->getMemberDecl())) 3467 return; 3468 3469 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3470 if (!FD->isAnonymousStructOrUnion()) 3471 FieldME = SubME; 3472 3473 if (!FieldME->getType().isPODType(S.Context)) 3474 AllPODFields = false; 3475 3476 Base = SubME->getBase(); 3477 } 3478 3479 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3480 return; 3481 3482 if (AddressOf && AllPODFields) 3483 return; 3484 3485 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3486 3487 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3488 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3489 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3490 } 3491 3492 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3493 QualType T = BaseCast->getType(); 3494 if (T->isPointerType() && 3495 BaseClasses.count(T->getPointeeType())) { 3496 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3497 << T->getPointeeType() << FoundVD; 3498 } 3499 } 3500 } 3501 3502 if (!Decls.count(FoundVD)) 3503 return; 3504 3505 const bool IsReference = FoundVD->getType()->isReferenceType(); 3506 3507 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3508 // Special checking for initializer lists. 3509 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3510 return; 3511 } 3512 } else { 3513 // Prevent double warnings on use of unbounded references. 3514 if (CheckReferenceOnly && !IsReference) 3515 return; 3516 } 3517 3518 unsigned diag = IsReference 3519 ? diag::warn_reference_field_is_uninit 3520 : diag::warn_field_is_uninit; 3521 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3522 if (Constructor) 3523 S.Diag(Constructor->getLocation(), 3524 diag::note_uninit_in_this_constructor) 3525 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3526 3527 } 3528 3529 void HandleValue(Expr *E, bool AddressOf) { 3530 E = E->IgnoreParens(); 3531 3532 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3533 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3534 AddressOf /*AddressOf*/); 3535 return; 3536 } 3537 3538 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3539 Visit(CO->getCond()); 3540 HandleValue(CO->getTrueExpr(), AddressOf); 3541 HandleValue(CO->getFalseExpr(), AddressOf); 3542 return; 3543 } 3544 3545 if (BinaryConditionalOperator *BCO = 3546 dyn_cast<BinaryConditionalOperator>(E)) { 3547 Visit(BCO->getCond()); 3548 HandleValue(BCO->getFalseExpr(), AddressOf); 3549 return; 3550 } 3551 3552 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3553 HandleValue(OVE->getSourceExpr(), AddressOf); 3554 return; 3555 } 3556 3557 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3558 switch (BO->getOpcode()) { 3559 default: 3560 break; 3561 case(BO_PtrMemD): 3562 case(BO_PtrMemI): 3563 HandleValue(BO->getLHS(), AddressOf); 3564 Visit(BO->getRHS()); 3565 return; 3566 case(BO_Comma): 3567 Visit(BO->getLHS()); 3568 HandleValue(BO->getRHS(), AddressOf); 3569 return; 3570 } 3571 } 3572 3573 Visit(E); 3574 } 3575 3576 void CheckInitListExpr(InitListExpr *ILE) { 3577 InitFieldIndex.push_back(0); 3578 for (auto Child : ILE->children()) { 3579 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3580 CheckInitListExpr(SubList); 3581 } else { 3582 Visit(Child); 3583 } 3584 ++InitFieldIndex.back(); 3585 } 3586 InitFieldIndex.pop_back(); 3587 } 3588 3589 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3590 FieldDecl *Field, const Type *BaseClass) { 3591 // Remove Decls that may have been initialized in the previous 3592 // initializer. 3593 for (ValueDecl* VD : DeclsToRemove) 3594 Decls.erase(VD); 3595 DeclsToRemove.clear(); 3596 3597 Constructor = FieldConstructor; 3598 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3599 3600 if (ILE && Field) { 3601 InitList = true; 3602 InitListFieldDecl = Field; 3603 InitFieldIndex.clear(); 3604 CheckInitListExpr(ILE); 3605 } else { 3606 InitList = false; 3607 Visit(E); 3608 } 3609 3610 if (Field) 3611 Decls.erase(Field); 3612 if (BaseClass) 3613 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3614 } 3615 3616 void VisitMemberExpr(MemberExpr *ME) { 3617 // All uses of unbounded reference fields will warn. 3618 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3619 } 3620 3621 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3622 if (E->getCastKind() == CK_LValueToRValue) { 3623 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3624 return; 3625 } 3626 3627 Inherited::VisitImplicitCastExpr(E); 3628 } 3629 3630 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3631 if (E->getConstructor()->isCopyConstructor()) { 3632 Expr *ArgExpr = E->getArg(0); 3633 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3634 if (ILE->getNumInits() == 1) 3635 ArgExpr = ILE->getInit(0); 3636 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3637 if (ICE->getCastKind() == CK_NoOp) 3638 ArgExpr = ICE->getSubExpr(); 3639 HandleValue(ArgExpr, false /*AddressOf*/); 3640 return; 3641 } 3642 Inherited::VisitCXXConstructExpr(E); 3643 } 3644 3645 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3646 Expr *Callee = E->getCallee(); 3647 if (isa<MemberExpr>(Callee)) { 3648 HandleValue(Callee, false /*AddressOf*/); 3649 for (auto Arg : E->arguments()) 3650 Visit(Arg); 3651 return; 3652 } 3653 3654 Inherited::VisitCXXMemberCallExpr(E); 3655 } 3656 3657 void VisitCallExpr(CallExpr *E) { 3658 // Treat std::move as a use. 3659 if (E->isCallToStdMove()) { 3660 HandleValue(E->getArg(0), /*AddressOf=*/false); 3661 return; 3662 } 3663 3664 Inherited::VisitCallExpr(E); 3665 } 3666 3667 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3668 Expr *Callee = E->getCallee(); 3669 3670 if (isa<UnresolvedLookupExpr>(Callee)) 3671 return Inherited::VisitCXXOperatorCallExpr(E); 3672 3673 Visit(Callee); 3674 for (auto Arg : E->arguments()) 3675 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3676 } 3677 3678 void VisitBinaryOperator(BinaryOperator *E) { 3679 // If a field assignment is detected, remove the field from the 3680 // uninitiailized field set. 3681 if (E->getOpcode() == BO_Assign) 3682 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3683 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3684 if (!FD->getType()->isReferenceType()) 3685 DeclsToRemove.push_back(FD); 3686 3687 if (E->isCompoundAssignmentOp()) { 3688 HandleValue(E->getLHS(), false /*AddressOf*/); 3689 Visit(E->getRHS()); 3690 return; 3691 } 3692 3693 Inherited::VisitBinaryOperator(E); 3694 } 3695 3696 void VisitUnaryOperator(UnaryOperator *E) { 3697 if (E->isIncrementDecrementOp()) { 3698 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3699 return; 3700 } 3701 if (E->getOpcode() == UO_AddrOf) { 3702 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3703 HandleValue(ME->getBase(), true /*AddressOf*/); 3704 return; 3705 } 3706 } 3707 3708 Inherited::VisitUnaryOperator(E); 3709 } 3710 }; 3711 3712 // Diagnose value-uses of fields to initialize themselves, e.g. 3713 // foo(foo) 3714 // where foo is not also a parameter to the constructor. 3715 // Also diagnose across field uninitialized use such as 3716 // x(y), y(x) 3717 // TODO: implement -Wuninitialized and fold this into that framework. 3718 static void DiagnoseUninitializedFields( 3719 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3720 3721 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3722 Constructor->getLocation())) { 3723 return; 3724 } 3725 3726 if (Constructor->isInvalidDecl()) 3727 return; 3728 3729 const CXXRecordDecl *RD = Constructor->getParent(); 3730 3731 if (RD->getDescribedClassTemplate()) 3732 return; 3733 3734 // Holds fields that are uninitialized. 3735 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3736 3737 // At the beginning, all fields are uninitialized. 3738 for (auto *I : RD->decls()) { 3739 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3740 UninitializedFields.insert(FD); 3741 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3742 UninitializedFields.insert(IFD->getAnonField()); 3743 } 3744 } 3745 3746 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3747 for (auto I : RD->bases()) 3748 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3749 3750 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3751 return; 3752 3753 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3754 UninitializedFields, 3755 UninitializedBaseClasses); 3756 3757 for (const auto *FieldInit : Constructor->inits()) { 3758 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3759 break; 3760 3761 Expr *InitExpr = FieldInit->getInit(); 3762 if (!InitExpr) 3763 continue; 3764 3765 if (CXXDefaultInitExpr *Default = 3766 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3767 InitExpr = Default->getExpr(); 3768 if (!InitExpr) 3769 continue; 3770 // In class initializers will point to the constructor. 3771 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3772 FieldInit->getAnyMember(), 3773 FieldInit->getBaseClass()); 3774 } else { 3775 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3776 FieldInit->getAnyMember(), 3777 FieldInit->getBaseClass()); 3778 } 3779 } 3780 } 3781 } // namespace 3782 3783 /// Enter a new C++ default initializer scope. After calling this, the 3784 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3785 /// parsing or instantiating the initializer failed. 3786 void Sema::ActOnStartCXXInClassMemberInitializer() { 3787 // Create a synthetic function scope to represent the call to the constructor 3788 // that notionally surrounds a use of this initializer. 3789 PushFunctionScope(); 3790 } 3791 3792 /// This is invoked after parsing an in-class initializer for a 3793 /// non-static C++ class member, and after instantiating an in-class initializer 3794 /// in a class template. Such actions are deferred until the class is complete. 3795 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3796 SourceLocation InitLoc, 3797 Expr *InitExpr) { 3798 // Pop the notional constructor scope we created earlier. 3799 PopFunctionScopeInfo(nullptr, D); 3800 3801 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3802 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3803 "must set init style when field is created"); 3804 3805 if (!InitExpr) { 3806 D->setInvalidDecl(); 3807 if (FD) 3808 FD->removeInClassInitializer(); 3809 return; 3810 } 3811 3812 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3813 FD->setInvalidDecl(); 3814 FD->removeInClassInitializer(); 3815 return; 3816 } 3817 3818 ExprResult Init = InitExpr; 3819 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3820 InitializedEntity Entity = 3821 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3822 InitializationKind Kind = 3823 FD->getInClassInitStyle() == ICIS_ListInit 3824 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3825 InitExpr->getBeginLoc(), 3826 InitExpr->getEndLoc()) 3827 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3828 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3829 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3830 if (Init.isInvalid()) { 3831 FD->setInvalidDecl(); 3832 return; 3833 } 3834 } 3835 3836 // C++11 [class.base.init]p7: 3837 // The initialization of each base and member constitutes a 3838 // full-expression. 3839 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3840 if (Init.isInvalid()) { 3841 FD->setInvalidDecl(); 3842 return; 3843 } 3844 3845 InitExpr = Init.get(); 3846 3847 FD->setInClassInitializer(InitExpr); 3848 } 3849 3850 /// Find the direct and/or virtual base specifiers that 3851 /// correspond to the given base type, for use in base initialization 3852 /// within a constructor. 3853 static bool FindBaseInitializer(Sema &SemaRef, 3854 CXXRecordDecl *ClassDecl, 3855 QualType BaseType, 3856 const CXXBaseSpecifier *&DirectBaseSpec, 3857 const CXXBaseSpecifier *&VirtualBaseSpec) { 3858 // First, check for a direct base class. 3859 DirectBaseSpec = nullptr; 3860 for (const auto &Base : ClassDecl->bases()) { 3861 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3862 // We found a direct base of this type. That's what we're 3863 // initializing. 3864 DirectBaseSpec = &Base; 3865 break; 3866 } 3867 } 3868 3869 // Check for a virtual base class. 3870 // FIXME: We might be able to short-circuit this if we know in advance that 3871 // there are no virtual bases. 3872 VirtualBaseSpec = nullptr; 3873 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3874 // We haven't found a base yet; search the class hierarchy for a 3875 // virtual base class. 3876 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3877 /*DetectVirtual=*/false); 3878 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3879 SemaRef.Context.getTypeDeclType(ClassDecl), 3880 BaseType, Paths)) { 3881 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3882 Path != Paths.end(); ++Path) { 3883 if (Path->back().Base->isVirtual()) { 3884 VirtualBaseSpec = Path->back().Base; 3885 break; 3886 } 3887 } 3888 } 3889 } 3890 3891 return DirectBaseSpec || VirtualBaseSpec; 3892 } 3893 3894 /// Handle a C++ member initializer using braced-init-list syntax. 3895 MemInitResult 3896 Sema::ActOnMemInitializer(Decl *ConstructorD, 3897 Scope *S, 3898 CXXScopeSpec &SS, 3899 IdentifierInfo *MemberOrBase, 3900 ParsedType TemplateTypeTy, 3901 const DeclSpec &DS, 3902 SourceLocation IdLoc, 3903 Expr *InitList, 3904 SourceLocation EllipsisLoc) { 3905 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3906 DS, IdLoc, InitList, 3907 EllipsisLoc); 3908 } 3909 3910 /// Handle a C++ member initializer using parentheses syntax. 3911 MemInitResult 3912 Sema::ActOnMemInitializer(Decl *ConstructorD, 3913 Scope *S, 3914 CXXScopeSpec &SS, 3915 IdentifierInfo *MemberOrBase, 3916 ParsedType TemplateTypeTy, 3917 const DeclSpec &DS, 3918 SourceLocation IdLoc, 3919 SourceLocation LParenLoc, 3920 ArrayRef<Expr *> Args, 3921 SourceLocation RParenLoc, 3922 SourceLocation EllipsisLoc) { 3923 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 3924 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3925 DS, IdLoc, List, EllipsisLoc); 3926 } 3927 3928 namespace { 3929 3930 // Callback to only accept typo corrections that can be a valid C++ member 3931 // intializer: either a non-static field member or a base class. 3932 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 3933 public: 3934 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3935 : ClassDecl(ClassDecl) {} 3936 3937 bool ValidateCandidate(const TypoCorrection &candidate) override { 3938 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3939 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3940 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3941 return isa<TypeDecl>(ND); 3942 } 3943 return false; 3944 } 3945 3946 std::unique_ptr<CorrectionCandidateCallback> clone() override { 3947 return llvm::make_unique<MemInitializerValidatorCCC>(*this); 3948 } 3949 3950 private: 3951 CXXRecordDecl *ClassDecl; 3952 }; 3953 3954 } 3955 3956 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 3957 CXXScopeSpec &SS, 3958 ParsedType TemplateTypeTy, 3959 IdentifierInfo *MemberOrBase) { 3960 if (SS.getScopeRep() || TemplateTypeTy) 3961 return nullptr; 3962 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3963 if (Result.empty()) 3964 return nullptr; 3965 ValueDecl *Member; 3966 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3967 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 3968 return Member; 3969 return nullptr; 3970 } 3971 3972 /// Handle a C++ member initializer. 3973 MemInitResult 3974 Sema::BuildMemInitializer(Decl *ConstructorD, 3975 Scope *S, 3976 CXXScopeSpec &SS, 3977 IdentifierInfo *MemberOrBase, 3978 ParsedType TemplateTypeTy, 3979 const DeclSpec &DS, 3980 SourceLocation IdLoc, 3981 Expr *Init, 3982 SourceLocation EllipsisLoc) { 3983 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3984 if (!Res.isUsable()) 3985 return true; 3986 Init = Res.get(); 3987 3988 if (!ConstructorD) 3989 return true; 3990 3991 AdjustDeclIfTemplate(ConstructorD); 3992 3993 CXXConstructorDecl *Constructor 3994 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3995 if (!Constructor) { 3996 // The user wrote a constructor initializer on a function that is 3997 // not a C++ constructor. Ignore the error for now, because we may 3998 // have more member initializers coming; we'll diagnose it just 3999 // once in ActOnMemInitializers. 4000 return true; 4001 } 4002 4003 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4004 4005 // C++ [class.base.init]p2: 4006 // Names in a mem-initializer-id are looked up in the scope of the 4007 // constructor's class and, if not found in that scope, are looked 4008 // up in the scope containing the constructor's definition. 4009 // [Note: if the constructor's class contains a member with the 4010 // same name as a direct or virtual base class of the class, a 4011 // mem-initializer-id naming the member or base class and composed 4012 // of a single identifier refers to the class member. A 4013 // mem-initializer-id for the hidden base class may be specified 4014 // using a qualified name. ] 4015 4016 // Look for a member, first. 4017 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4018 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4019 if (EllipsisLoc.isValid()) 4020 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4021 << MemberOrBase 4022 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4023 4024 return BuildMemberInitializer(Member, Init, IdLoc); 4025 } 4026 // It didn't name a member, so see if it names a class. 4027 QualType BaseType; 4028 TypeSourceInfo *TInfo = nullptr; 4029 4030 if (TemplateTypeTy) { 4031 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4032 if (BaseType.isNull()) 4033 return true; 4034 } else if (DS.getTypeSpecType() == TST_decltype) { 4035 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4036 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4037 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4038 return true; 4039 } else { 4040 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4041 LookupParsedName(R, S, &SS); 4042 4043 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4044 if (!TyD) { 4045 if (R.isAmbiguous()) return true; 4046 4047 // We don't want access-control diagnostics here. 4048 R.suppressDiagnostics(); 4049 4050 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4051 bool NotUnknownSpecialization = false; 4052 DeclContext *DC = computeDeclContext(SS, false); 4053 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4054 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4055 4056 if (!NotUnknownSpecialization) { 4057 // When the scope specifier can refer to a member of an unknown 4058 // specialization, we take it as a type name. 4059 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4060 SS.getWithLocInContext(Context), 4061 *MemberOrBase, IdLoc); 4062 if (BaseType.isNull()) 4063 return true; 4064 4065 TInfo = Context.CreateTypeSourceInfo(BaseType); 4066 DependentNameTypeLoc TL = 4067 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4068 if (!TL.isNull()) { 4069 TL.setNameLoc(IdLoc); 4070 TL.setElaboratedKeywordLoc(SourceLocation()); 4071 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4072 } 4073 4074 R.clear(); 4075 R.setLookupName(MemberOrBase); 4076 } 4077 } 4078 4079 // If no results were found, try to correct typos. 4080 TypoCorrection Corr; 4081 MemInitializerValidatorCCC CCC(ClassDecl); 4082 if (R.empty() && BaseType.isNull() && 4083 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4084 CCC, CTK_ErrorRecovery, ClassDecl))) { 4085 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4086 // We have found a non-static data member with a similar 4087 // name to what was typed; complain and initialize that 4088 // member. 4089 diagnoseTypo(Corr, 4090 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4091 << MemberOrBase << true); 4092 return BuildMemberInitializer(Member, Init, IdLoc); 4093 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4094 const CXXBaseSpecifier *DirectBaseSpec; 4095 const CXXBaseSpecifier *VirtualBaseSpec; 4096 if (FindBaseInitializer(*this, ClassDecl, 4097 Context.getTypeDeclType(Type), 4098 DirectBaseSpec, VirtualBaseSpec)) { 4099 // We have found a direct or virtual base class with a 4100 // similar name to what was typed; complain and initialize 4101 // that base class. 4102 diagnoseTypo(Corr, 4103 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4104 << MemberOrBase << false, 4105 PDiag() /*Suppress note, we provide our own.*/); 4106 4107 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4108 : VirtualBaseSpec; 4109 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4110 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4111 4112 TyD = Type; 4113 } 4114 } 4115 } 4116 4117 if (!TyD && BaseType.isNull()) { 4118 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4119 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4120 return true; 4121 } 4122 } 4123 4124 if (BaseType.isNull()) { 4125 BaseType = Context.getTypeDeclType(TyD); 4126 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4127 if (SS.isSet()) { 4128 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4129 BaseType); 4130 TInfo = Context.CreateTypeSourceInfo(BaseType); 4131 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4132 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4133 TL.setElaboratedKeywordLoc(SourceLocation()); 4134 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4135 } 4136 } 4137 } 4138 4139 if (!TInfo) 4140 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4141 4142 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4143 } 4144 4145 MemInitResult 4146 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4147 SourceLocation IdLoc) { 4148 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4149 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4150 assert((DirectMember || IndirectMember) && 4151 "Member must be a FieldDecl or IndirectFieldDecl"); 4152 4153 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4154 return true; 4155 4156 if (Member->isInvalidDecl()) 4157 return true; 4158 4159 MultiExprArg Args; 4160 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4161 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4162 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4163 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4164 } else { 4165 // Template instantiation doesn't reconstruct ParenListExprs for us. 4166 Args = Init; 4167 } 4168 4169 SourceRange InitRange = Init->getSourceRange(); 4170 4171 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4172 // Can't check initialization for a member of dependent type or when 4173 // any of the arguments are type-dependent expressions. 4174 DiscardCleanupsInEvaluationContext(); 4175 } else { 4176 bool InitList = false; 4177 if (isa<InitListExpr>(Init)) { 4178 InitList = true; 4179 Args = Init; 4180 } 4181 4182 // Initialize the member. 4183 InitializedEntity MemberEntity = 4184 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4185 : InitializedEntity::InitializeMember(IndirectMember, 4186 nullptr); 4187 InitializationKind Kind = 4188 InitList ? InitializationKind::CreateDirectList( 4189 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4190 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4191 InitRange.getEnd()); 4192 4193 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4194 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4195 nullptr); 4196 if (MemberInit.isInvalid()) 4197 return true; 4198 4199 // C++11 [class.base.init]p7: 4200 // The initialization of each base and member constitutes a 4201 // full-expression. 4202 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4203 /*DiscardedValue*/ false); 4204 if (MemberInit.isInvalid()) 4205 return true; 4206 4207 Init = MemberInit.get(); 4208 } 4209 4210 if (DirectMember) { 4211 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4212 InitRange.getBegin(), Init, 4213 InitRange.getEnd()); 4214 } else { 4215 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4216 InitRange.getBegin(), Init, 4217 InitRange.getEnd()); 4218 } 4219 } 4220 4221 MemInitResult 4222 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4223 CXXRecordDecl *ClassDecl) { 4224 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4225 if (!LangOpts.CPlusPlus11) 4226 return Diag(NameLoc, diag::err_delegating_ctor) 4227 << TInfo->getTypeLoc().getLocalSourceRange(); 4228 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4229 4230 bool InitList = true; 4231 MultiExprArg Args = Init; 4232 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4233 InitList = false; 4234 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4235 } 4236 4237 SourceRange InitRange = Init->getSourceRange(); 4238 // Initialize the object. 4239 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4240 QualType(ClassDecl->getTypeForDecl(), 0)); 4241 InitializationKind Kind = 4242 InitList ? InitializationKind::CreateDirectList( 4243 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4244 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4245 InitRange.getEnd()); 4246 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4247 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4248 Args, nullptr); 4249 if (DelegationInit.isInvalid()) 4250 return true; 4251 4252 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4253 "Delegating constructor with no target?"); 4254 4255 // C++11 [class.base.init]p7: 4256 // The initialization of each base and member constitutes a 4257 // full-expression. 4258 DelegationInit = ActOnFinishFullExpr( 4259 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4260 if (DelegationInit.isInvalid()) 4261 return true; 4262 4263 // If we are in a dependent context, template instantiation will 4264 // perform this type-checking again. Just save the arguments that we 4265 // received in a ParenListExpr. 4266 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4267 // of the information that we have about the base 4268 // initializer. However, deconstructing the ASTs is a dicey process, 4269 // and this approach is far more likely to get the corner cases right. 4270 if (CurContext->isDependentContext()) 4271 DelegationInit = Init; 4272 4273 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4274 DelegationInit.getAs<Expr>(), 4275 InitRange.getEnd()); 4276 } 4277 4278 MemInitResult 4279 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4280 Expr *Init, CXXRecordDecl *ClassDecl, 4281 SourceLocation EllipsisLoc) { 4282 SourceLocation BaseLoc 4283 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4284 4285 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4286 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4287 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4288 4289 // C++ [class.base.init]p2: 4290 // [...] Unless the mem-initializer-id names a nonstatic data 4291 // member of the constructor's class or a direct or virtual base 4292 // of that class, the mem-initializer is ill-formed. A 4293 // mem-initializer-list can initialize a base class using any 4294 // name that denotes that base class type. 4295 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4296 4297 SourceRange InitRange = Init->getSourceRange(); 4298 if (EllipsisLoc.isValid()) { 4299 // This is a pack expansion. 4300 if (!BaseType->containsUnexpandedParameterPack()) { 4301 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4302 << SourceRange(BaseLoc, InitRange.getEnd()); 4303 4304 EllipsisLoc = SourceLocation(); 4305 } 4306 } else { 4307 // Check for any unexpanded parameter packs. 4308 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4309 return true; 4310 4311 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4312 return true; 4313 } 4314 4315 // Check for direct and virtual base classes. 4316 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4317 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4318 if (!Dependent) { 4319 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4320 BaseType)) 4321 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4322 4323 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4324 VirtualBaseSpec); 4325 4326 // C++ [base.class.init]p2: 4327 // Unless the mem-initializer-id names a nonstatic data member of the 4328 // constructor's class or a direct or virtual base of that class, the 4329 // mem-initializer is ill-formed. 4330 if (!DirectBaseSpec && !VirtualBaseSpec) { 4331 // If the class has any dependent bases, then it's possible that 4332 // one of those types will resolve to the same type as 4333 // BaseType. Therefore, just treat this as a dependent base 4334 // class initialization. FIXME: Should we try to check the 4335 // initialization anyway? It seems odd. 4336 if (ClassDecl->hasAnyDependentBases()) 4337 Dependent = true; 4338 else 4339 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4340 << BaseType << Context.getTypeDeclType(ClassDecl) 4341 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4342 } 4343 } 4344 4345 if (Dependent) { 4346 DiscardCleanupsInEvaluationContext(); 4347 4348 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4349 /*IsVirtual=*/false, 4350 InitRange.getBegin(), Init, 4351 InitRange.getEnd(), EllipsisLoc); 4352 } 4353 4354 // C++ [base.class.init]p2: 4355 // If a mem-initializer-id is ambiguous because it designates both 4356 // a direct non-virtual base class and an inherited virtual base 4357 // class, the mem-initializer is ill-formed. 4358 if (DirectBaseSpec && VirtualBaseSpec) 4359 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4360 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4361 4362 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4363 if (!BaseSpec) 4364 BaseSpec = VirtualBaseSpec; 4365 4366 // Initialize the base. 4367 bool InitList = true; 4368 MultiExprArg Args = Init; 4369 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4370 InitList = false; 4371 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4372 } 4373 4374 InitializedEntity BaseEntity = 4375 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4376 InitializationKind Kind = 4377 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4378 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4379 InitRange.getEnd()); 4380 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4381 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4382 if (BaseInit.isInvalid()) 4383 return true; 4384 4385 // C++11 [class.base.init]p7: 4386 // The initialization of each base and member constitutes a 4387 // full-expression. 4388 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4389 /*DiscardedValue*/ false); 4390 if (BaseInit.isInvalid()) 4391 return true; 4392 4393 // If we are in a dependent context, template instantiation will 4394 // perform this type-checking again. Just save the arguments that we 4395 // received in a ParenListExpr. 4396 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4397 // of the information that we have about the base 4398 // initializer. However, deconstructing the ASTs is a dicey process, 4399 // and this approach is far more likely to get the corner cases right. 4400 if (CurContext->isDependentContext()) 4401 BaseInit = Init; 4402 4403 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4404 BaseSpec->isVirtual(), 4405 InitRange.getBegin(), 4406 BaseInit.getAs<Expr>(), 4407 InitRange.getEnd(), EllipsisLoc); 4408 } 4409 4410 // Create a static_cast\<T&&>(expr). 4411 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4412 if (T.isNull()) T = E->getType(); 4413 QualType TargetType = SemaRef.BuildReferenceType( 4414 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4415 SourceLocation ExprLoc = E->getBeginLoc(); 4416 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4417 TargetType, ExprLoc); 4418 4419 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4420 SourceRange(ExprLoc, ExprLoc), 4421 E->getSourceRange()).get(); 4422 } 4423 4424 /// ImplicitInitializerKind - How an implicit base or member initializer should 4425 /// initialize its base or member. 4426 enum ImplicitInitializerKind { 4427 IIK_Default, 4428 IIK_Copy, 4429 IIK_Move, 4430 IIK_Inherit 4431 }; 4432 4433 static bool 4434 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4435 ImplicitInitializerKind ImplicitInitKind, 4436 CXXBaseSpecifier *BaseSpec, 4437 bool IsInheritedVirtualBase, 4438 CXXCtorInitializer *&CXXBaseInit) { 4439 InitializedEntity InitEntity 4440 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4441 IsInheritedVirtualBase); 4442 4443 ExprResult BaseInit; 4444 4445 switch (ImplicitInitKind) { 4446 case IIK_Inherit: 4447 case IIK_Default: { 4448 InitializationKind InitKind 4449 = InitializationKind::CreateDefault(Constructor->getLocation()); 4450 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4451 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4452 break; 4453 } 4454 4455 case IIK_Move: 4456 case IIK_Copy: { 4457 bool Moving = ImplicitInitKind == IIK_Move; 4458 ParmVarDecl *Param = Constructor->getParamDecl(0); 4459 QualType ParamType = Param->getType().getNonReferenceType(); 4460 4461 Expr *CopyCtorArg = 4462 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4463 SourceLocation(), Param, false, 4464 Constructor->getLocation(), ParamType, 4465 VK_LValue, nullptr); 4466 4467 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4468 4469 // Cast to the base class to avoid ambiguities. 4470 QualType ArgTy = 4471 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4472 ParamType.getQualifiers()); 4473 4474 if (Moving) { 4475 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4476 } 4477 4478 CXXCastPath BasePath; 4479 BasePath.push_back(BaseSpec); 4480 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4481 CK_UncheckedDerivedToBase, 4482 Moving ? VK_XValue : VK_LValue, 4483 &BasePath).get(); 4484 4485 InitializationKind InitKind 4486 = InitializationKind::CreateDirect(Constructor->getLocation(), 4487 SourceLocation(), SourceLocation()); 4488 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4489 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4490 break; 4491 } 4492 } 4493 4494 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4495 if (BaseInit.isInvalid()) 4496 return true; 4497 4498 CXXBaseInit = 4499 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4500 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4501 SourceLocation()), 4502 BaseSpec->isVirtual(), 4503 SourceLocation(), 4504 BaseInit.getAs<Expr>(), 4505 SourceLocation(), 4506 SourceLocation()); 4507 4508 return false; 4509 } 4510 4511 static bool RefersToRValueRef(Expr *MemRef) { 4512 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4513 return Referenced->getType()->isRValueReferenceType(); 4514 } 4515 4516 static bool 4517 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4518 ImplicitInitializerKind ImplicitInitKind, 4519 FieldDecl *Field, IndirectFieldDecl *Indirect, 4520 CXXCtorInitializer *&CXXMemberInit) { 4521 if (Field->isInvalidDecl()) 4522 return true; 4523 4524 SourceLocation Loc = Constructor->getLocation(); 4525 4526 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4527 bool Moving = ImplicitInitKind == IIK_Move; 4528 ParmVarDecl *Param = Constructor->getParamDecl(0); 4529 QualType ParamType = Param->getType().getNonReferenceType(); 4530 4531 // Suppress copying zero-width bitfields. 4532 if (Field->isZeroLengthBitField(SemaRef.Context)) 4533 return false; 4534 4535 Expr *MemberExprBase = 4536 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4537 SourceLocation(), Param, false, 4538 Loc, ParamType, VK_LValue, nullptr); 4539 4540 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4541 4542 if (Moving) { 4543 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4544 } 4545 4546 // Build a reference to this field within the parameter. 4547 CXXScopeSpec SS; 4548 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4549 Sema::LookupMemberName); 4550 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4551 : cast<ValueDecl>(Field), AS_public); 4552 MemberLookup.resolveKind(); 4553 ExprResult CtorArg 4554 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4555 ParamType, Loc, 4556 /*IsArrow=*/false, 4557 SS, 4558 /*TemplateKWLoc=*/SourceLocation(), 4559 /*FirstQualifierInScope=*/nullptr, 4560 MemberLookup, 4561 /*TemplateArgs=*/nullptr, 4562 /*S*/nullptr); 4563 if (CtorArg.isInvalid()) 4564 return true; 4565 4566 // C++11 [class.copy]p15: 4567 // - if a member m has rvalue reference type T&&, it is direct-initialized 4568 // with static_cast<T&&>(x.m); 4569 if (RefersToRValueRef(CtorArg.get())) { 4570 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4571 } 4572 4573 InitializedEntity Entity = 4574 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4575 /*Implicit*/ true) 4576 : InitializedEntity::InitializeMember(Field, nullptr, 4577 /*Implicit*/ true); 4578 4579 // Direct-initialize to use the copy constructor. 4580 InitializationKind InitKind = 4581 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4582 4583 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4584 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4585 ExprResult MemberInit = 4586 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4587 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4588 if (MemberInit.isInvalid()) 4589 return true; 4590 4591 if (Indirect) 4592 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4593 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4594 else 4595 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4596 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4597 return false; 4598 } 4599 4600 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4601 "Unhandled implicit init kind!"); 4602 4603 QualType FieldBaseElementType = 4604 SemaRef.Context.getBaseElementType(Field->getType()); 4605 4606 if (FieldBaseElementType->isRecordType()) { 4607 InitializedEntity InitEntity = 4608 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4609 /*Implicit*/ true) 4610 : InitializedEntity::InitializeMember(Field, nullptr, 4611 /*Implicit*/ true); 4612 InitializationKind InitKind = 4613 InitializationKind::CreateDefault(Loc); 4614 4615 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4616 ExprResult MemberInit = 4617 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4618 4619 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4620 if (MemberInit.isInvalid()) 4621 return true; 4622 4623 if (Indirect) 4624 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4625 Indirect, Loc, 4626 Loc, 4627 MemberInit.get(), 4628 Loc); 4629 else 4630 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4631 Field, Loc, Loc, 4632 MemberInit.get(), 4633 Loc); 4634 return false; 4635 } 4636 4637 if (!Field->getParent()->isUnion()) { 4638 if (FieldBaseElementType->isReferenceType()) { 4639 SemaRef.Diag(Constructor->getLocation(), 4640 diag::err_uninitialized_member_in_ctor) 4641 << (int)Constructor->isImplicit() 4642 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4643 << 0 << Field->getDeclName(); 4644 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4645 return true; 4646 } 4647 4648 if (FieldBaseElementType.isConstQualified()) { 4649 SemaRef.Diag(Constructor->getLocation(), 4650 diag::err_uninitialized_member_in_ctor) 4651 << (int)Constructor->isImplicit() 4652 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4653 << 1 << Field->getDeclName(); 4654 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4655 return true; 4656 } 4657 } 4658 4659 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4660 // ARC and Weak: 4661 // Default-initialize Objective-C pointers to NULL. 4662 CXXMemberInit 4663 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4664 Loc, Loc, 4665 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4666 Loc); 4667 return false; 4668 } 4669 4670 // Nothing to initialize. 4671 CXXMemberInit = nullptr; 4672 return false; 4673 } 4674 4675 namespace { 4676 struct BaseAndFieldInfo { 4677 Sema &S; 4678 CXXConstructorDecl *Ctor; 4679 bool AnyErrorsInInits; 4680 ImplicitInitializerKind IIK; 4681 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4682 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4683 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4684 4685 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4686 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4687 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4688 if (Ctor->getInheritedConstructor()) 4689 IIK = IIK_Inherit; 4690 else if (Generated && Ctor->isCopyConstructor()) 4691 IIK = IIK_Copy; 4692 else if (Generated && Ctor->isMoveConstructor()) 4693 IIK = IIK_Move; 4694 else 4695 IIK = IIK_Default; 4696 } 4697 4698 bool isImplicitCopyOrMove() const { 4699 switch (IIK) { 4700 case IIK_Copy: 4701 case IIK_Move: 4702 return true; 4703 4704 case IIK_Default: 4705 case IIK_Inherit: 4706 return false; 4707 } 4708 4709 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4710 } 4711 4712 bool addFieldInitializer(CXXCtorInitializer *Init) { 4713 AllToInit.push_back(Init); 4714 4715 // Check whether this initializer makes the field "used". 4716 if (Init->getInit()->HasSideEffects(S.Context)) 4717 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4718 4719 return false; 4720 } 4721 4722 bool isInactiveUnionMember(FieldDecl *Field) { 4723 RecordDecl *Record = Field->getParent(); 4724 if (!Record->isUnion()) 4725 return false; 4726 4727 if (FieldDecl *Active = 4728 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4729 return Active != Field->getCanonicalDecl(); 4730 4731 // In an implicit copy or move constructor, ignore any in-class initializer. 4732 if (isImplicitCopyOrMove()) 4733 return true; 4734 4735 // If there's no explicit initialization, the field is active only if it 4736 // has an in-class initializer... 4737 if (Field->hasInClassInitializer()) 4738 return false; 4739 // ... or it's an anonymous struct or union whose class has an in-class 4740 // initializer. 4741 if (!Field->isAnonymousStructOrUnion()) 4742 return true; 4743 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4744 return !FieldRD->hasInClassInitializer(); 4745 } 4746 4747 /// Determine whether the given field is, or is within, a union member 4748 /// that is inactive (because there was an initializer given for a different 4749 /// member of the union, or because the union was not initialized at all). 4750 bool isWithinInactiveUnionMember(FieldDecl *Field, 4751 IndirectFieldDecl *Indirect) { 4752 if (!Indirect) 4753 return isInactiveUnionMember(Field); 4754 4755 for (auto *C : Indirect->chain()) { 4756 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4757 if (Field && isInactiveUnionMember(Field)) 4758 return true; 4759 } 4760 return false; 4761 } 4762 }; 4763 } 4764 4765 /// Determine whether the given type is an incomplete or zero-lenfgth 4766 /// array type. 4767 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4768 if (T->isIncompleteArrayType()) 4769 return true; 4770 4771 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4772 if (!ArrayT->getSize()) 4773 return true; 4774 4775 T = ArrayT->getElementType(); 4776 } 4777 4778 return false; 4779 } 4780 4781 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4782 FieldDecl *Field, 4783 IndirectFieldDecl *Indirect = nullptr) { 4784 if (Field->isInvalidDecl()) 4785 return false; 4786 4787 // Overwhelmingly common case: we have a direct initializer for this field. 4788 if (CXXCtorInitializer *Init = 4789 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4790 return Info.addFieldInitializer(Init); 4791 4792 // C++11 [class.base.init]p8: 4793 // if the entity is a non-static data member that has a 4794 // brace-or-equal-initializer and either 4795 // -- the constructor's class is a union and no other variant member of that 4796 // union is designated by a mem-initializer-id or 4797 // -- the constructor's class is not a union, and, if the entity is a member 4798 // of an anonymous union, no other member of that union is designated by 4799 // a mem-initializer-id, 4800 // the entity is initialized as specified in [dcl.init]. 4801 // 4802 // We also apply the same rules to handle anonymous structs within anonymous 4803 // unions. 4804 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4805 return false; 4806 4807 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4808 ExprResult DIE = 4809 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4810 if (DIE.isInvalid()) 4811 return true; 4812 4813 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4814 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4815 4816 CXXCtorInitializer *Init; 4817 if (Indirect) 4818 Init = new (SemaRef.Context) 4819 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4820 SourceLocation(), DIE.get(), SourceLocation()); 4821 else 4822 Init = new (SemaRef.Context) 4823 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4824 SourceLocation(), DIE.get(), SourceLocation()); 4825 return Info.addFieldInitializer(Init); 4826 } 4827 4828 // Don't initialize incomplete or zero-length arrays. 4829 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4830 return false; 4831 4832 // Don't try to build an implicit initializer if there were semantic 4833 // errors in any of the initializers (and therefore we might be 4834 // missing some that the user actually wrote). 4835 if (Info.AnyErrorsInInits) 4836 return false; 4837 4838 CXXCtorInitializer *Init = nullptr; 4839 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4840 Indirect, Init)) 4841 return true; 4842 4843 if (!Init) 4844 return false; 4845 4846 return Info.addFieldInitializer(Init); 4847 } 4848 4849 bool 4850 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4851 CXXCtorInitializer *Initializer) { 4852 assert(Initializer->isDelegatingInitializer()); 4853 Constructor->setNumCtorInitializers(1); 4854 CXXCtorInitializer **initializer = 4855 new (Context) CXXCtorInitializer*[1]; 4856 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4857 Constructor->setCtorInitializers(initializer); 4858 4859 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4860 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4861 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4862 } 4863 4864 DelegatingCtorDecls.push_back(Constructor); 4865 4866 DiagnoseUninitializedFields(*this, Constructor); 4867 4868 return false; 4869 } 4870 4871 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4872 ArrayRef<CXXCtorInitializer *> Initializers) { 4873 if (Constructor->isDependentContext()) { 4874 // Just store the initializers as written, they will be checked during 4875 // instantiation. 4876 if (!Initializers.empty()) { 4877 Constructor->setNumCtorInitializers(Initializers.size()); 4878 CXXCtorInitializer **baseOrMemberInitializers = 4879 new (Context) CXXCtorInitializer*[Initializers.size()]; 4880 memcpy(baseOrMemberInitializers, Initializers.data(), 4881 Initializers.size() * sizeof(CXXCtorInitializer*)); 4882 Constructor->setCtorInitializers(baseOrMemberInitializers); 4883 } 4884 4885 // Let template instantiation know whether we had errors. 4886 if (AnyErrors) 4887 Constructor->setInvalidDecl(); 4888 4889 return false; 4890 } 4891 4892 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4893 4894 // We need to build the initializer AST according to order of construction 4895 // and not what user specified in the Initializers list. 4896 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4897 if (!ClassDecl) 4898 return true; 4899 4900 bool HadError = false; 4901 4902 for (unsigned i = 0; i < Initializers.size(); i++) { 4903 CXXCtorInitializer *Member = Initializers[i]; 4904 4905 if (Member->isBaseInitializer()) 4906 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4907 else { 4908 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4909 4910 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4911 for (auto *C : F->chain()) { 4912 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4913 if (FD && FD->getParent()->isUnion()) 4914 Info.ActiveUnionMember.insert(std::make_pair( 4915 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4916 } 4917 } else if (FieldDecl *FD = Member->getMember()) { 4918 if (FD->getParent()->isUnion()) 4919 Info.ActiveUnionMember.insert(std::make_pair( 4920 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4921 } 4922 } 4923 } 4924 4925 // Keep track of the direct virtual bases. 4926 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4927 for (auto &I : ClassDecl->bases()) { 4928 if (I.isVirtual()) 4929 DirectVBases.insert(&I); 4930 } 4931 4932 // Push virtual bases before others. 4933 for (auto &VBase : ClassDecl->vbases()) { 4934 if (CXXCtorInitializer *Value 4935 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4936 // [class.base.init]p7, per DR257: 4937 // A mem-initializer where the mem-initializer-id names a virtual base 4938 // class is ignored during execution of a constructor of any class that 4939 // is not the most derived class. 4940 if (ClassDecl->isAbstract()) { 4941 // FIXME: Provide a fixit to remove the base specifier. This requires 4942 // tracking the location of the associated comma for a base specifier. 4943 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4944 << VBase.getType() << ClassDecl; 4945 DiagnoseAbstractType(ClassDecl); 4946 } 4947 4948 Info.AllToInit.push_back(Value); 4949 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4950 // [class.base.init]p8, per DR257: 4951 // If a given [...] base class is not named by a mem-initializer-id 4952 // [...] and the entity is not a virtual base class of an abstract 4953 // class, then [...] the entity is default-initialized. 4954 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4955 CXXCtorInitializer *CXXBaseInit; 4956 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4957 &VBase, IsInheritedVirtualBase, 4958 CXXBaseInit)) { 4959 HadError = true; 4960 continue; 4961 } 4962 4963 Info.AllToInit.push_back(CXXBaseInit); 4964 } 4965 } 4966 4967 // Non-virtual bases. 4968 for (auto &Base : ClassDecl->bases()) { 4969 // Virtuals are in the virtual base list and already constructed. 4970 if (Base.isVirtual()) 4971 continue; 4972 4973 if (CXXCtorInitializer *Value 4974 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4975 Info.AllToInit.push_back(Value); 4976 } else if (!AnyErrors) { 4977 CXXCtorInitializer *CXXBaseInit; 4978 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4979 &Base, /*IsInheritedVirtualBase=*/false, 4980 CXXBaseInit)) { 4981 HadError = true; 4982 continue; 4983 } 4984 4985 Info.AllToInit.push_back(CXXBaseInit); 4986 } 4987 } 4988 4989 // Fields. 4990 for (auto *Mem : ClassDecl->decls()) { 4991 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4992 // C++ [class.bit]p2: 4993 // A declaration for a bit-field that omits the identifier declares an 4994 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4995 // initialized. 4996 if (F->isUnnamedBitfield()) 4997 continue; 4998 4999 // If we're not generating the implicit copy/move constructor, then we'll 5000 // handle anonymous struct/union fields based on their individual 5001 // indirect fields. 5002 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5003 continue; 5004 5005 if (CollectFieldInitializer(*this, Info, F)) 5006 HadError = true; 5007 continue; 5008 } 5009 5010 // Beyond this point, we only consider default initialization. 5011 if (Info.isImplicitCopyOrMove()) 5012 continue; 5013 5014 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5015 if (F->getType()->isIncompleteArrayType()) { 5016 assert(ClassDecl->hasFlexibleArrayMember() && 5017 "Incomplete array type is not valid"); 5018 continue; 5019 } 5020 5021 // Initialize each field of an anonymous struct individually. 5022 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5023 HadError = true; 5024 5025 continue; 5026 } 5027 } 5028 5029 unsigned NumInitializers = Info.AllToInit.size(); 5030 if (NumInitializers > 0) { 5031 Constructor->setNumCtorInitializers(NumInitializers); 5032 CXXCtorInitializer **baseOrMemberInitializers = 5033 new (Context) CXXCtorInitializer*[NumInitializers]; 5034 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5035 NumInitializers * sizeof(CXXCtorInitializer*)); 5036 Constructor->setCtorInitializers(baseOrMemberInitializers); 5037 5038 // Constructors implicitly reference the base and member 5039 // destructors. 5040 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5041 Constructor->getParent()); 5042 } 5043 5044 return HadError; 5045 } 5046 5047 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5048 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5049 const RecordDecl *RD = RT->getDecl(); 5050 if (RD->isAnonymousStructOrUnion()) { 5051 for (auto *Field : RD->fields()) 5052 PopulateKeysForFields(Field, IdealInits); 5053 return; 5054 } 5055 } 5056 IdealInits.push_back(Field->getCanonicalDecl()); 5057 } 5058 5059 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5060 return Context.getCanonicalType(BaseType).getTypePtr(); 5061 } 5062 5063 static const void *GetKeyForMember(ASTContext &Context, 5064 CXXCtorInitializer *Member) { 5065 if (!Member->isAnyMemberInitializer()) 5066 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5067 5068 return Member->getAnyMember()->getCanonicalDecl(); 5069 } 5070 5071 static void DiagnoseBaseOrMemInitializerOrder( 5072 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5073 ArrayRef<CXXCtorInitializer *> Inits) { 5074 if (Constructor->getDeclContext()->isDependentContext()) 5075 return; 5076 5077 // Don't check initializers order unless the warning is enabled at the 5078 // location of at least one initializer. 5079 bool ShouldCheckOrder = false; 5080 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5081 CXXCtorInitializer *Init = Inits[InitIndex]; 5082 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5083 Init->getSourceLocation())) { 5084 ShouldCheckOrder = true; 5085 break; 5086 } 5087 } 5088 if (!ShouldCheckOrder) 5089 return; 5090 5091 // Build the list of bases and members in the order that they'll 5092 // actually be initialized. The explicit initializers should be in 5093 // this same order but may be missing things. 5094 SmallVector<const void*, 32> IdealInitKeys; 5095 5096 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5097 5098 // 1. Virtual bases. 5099 for (const auto &VBase : ClassDecl->vbases()) 5100 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5101 5102 // 2. Non-virtual bases. 5103 for (const auto &Base : ClassDecl->bases()) { 5104 if (Base.isVirtual()) 5105 continue; 5106 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5107 } 5108 5109 // 3. Direct fields. 5110 for (auto *Field : ClassDecl->fields()) { 5111 if (Field->isUnnamedBitfield()) 5112 continue; 5113 5114 PopulateKeysForFields(Field, IdealInitKeys); 5115 } 5116 5117 unsigned NumIdealInits = IdealInitKeys.size(); 5118 unsigned IdealIndex = 0; 5119 5120 CXXCtorInitializer *PrevInit = nullptr; 5121 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5122 CXXCtorInitializer *Init = Inits[InitIndex]; 5123 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5124 5125 // Scan forward to try to find this initializer in the idealized 5126 // initializers list. 5127 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5128 if (InitKey == IdealInitKeys[IdealIndex]) 5129 break; 5130 5131 // If we didn't find this initializer, it must be because we 5132 // scanned past it on a previous iteration. That can only 5133 // happen if we're out of order; emit a warning. 5134 if (IdealIndex == NumIdealInits && PrevInit) { 5135 Sema::SemaDiagnosticBuilder D = 5136 SemaRef.Diag(PrevInit->getSourceLocation(), 5137 diag::warn_initializer_out_of_order); 5138 5139 if (PrevInit->isAnyMemberInitializer()) 5140 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5141 else 5142 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5143 5144 if (Init->isAnyMemberInitializer()) 5145 D << 0 << Init->getAnyMember()->getDeclName(); 5146 else 5147 D << 1 << Init->getTypeSourceInfo()->getType(); 5148 5149 // Move back to the initializer's location in the ideal list. 5150 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5151 if (InitKey == IdealInitKeys[IdealIndex]) 5152 break; 5153 5154 assert(IdealIndex < NumIdealInits && 5155 "initializer not found in initializer list"); 5156 } 5157 5158 PrevInit = Init; 5159 } 5160 } 5161 5162 namespace { 5163 bool CheckRedundantInit(Sema &S, 5164 CXXCtorInitializer *Init, 5165 CXXCtorInitializer *&PrevInit) { 5166 if (!PrevInit) { 5167 PrevInit = Init; 5168 return false; 5169 } 5170 5171 if (FieldDecl *Field = Init->getAnyMember()) 5172 S.Diag(Init->getSourceLocation(), 5173 diag::err_multiple_mem_initialization) 5174 << Field->getDeclName() 5175 << Init->getSourceRange(); 5176 else { 5177 const Type *BaseClass = Init->getBaseClass(); 5178 assert(BaseClass && "neither field nor base"); 5179 S.Diag(Init->getSourceLocation(), 5180 diag::err_multiple_base_initialization) 5181 << QualType(BaseClass, 0) 5182 << Init->getSourceRange(); 5183 } 5184 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5185 << 0 << PrevInit->getSourceRange(); 5186 5187 return true; 5188 } 5189 5190 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5191 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5192 5193 bool CheckRedundantUnionInit(Sema &S, 5194 CXXCtorInitializer *Init, 5195 RedundantUnionMap &Unions) { 5196 FieldDecl *Field = Init->getAnyMember(); 5197 RecordDecl *Parent = Field->getParent(); 5198 NamedDecl *Child = Field; 5199 5200 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5201 if (Parent->isUnion()) { 5202 UnionEntry &En = Unions[Parent]; 5203 if (En.first && En.first != Child) { 5204 S.Diag(Init->getSourceLocation(), 5205 diag::err_multiple_mem_union_initialization) 5206 << Field->getDeclName() 5207 << Init->getSourceRange(); 5208 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5209 << 0 << En.second->getSourceRange(); 5210 return true; 5211 } 5212 if (!En.first) { 5213 En.first = Child; 5214 En.second = Init; 5215 } 5216 if (!Parent->isAnonymousStructOrUnion()) 5217 return false; 5218 } 5219 5220 Child = Parent; 5221 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5222 } 5223 5224 return false; 5225 } 5226 } 5227 5228 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5229 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5230 SourceLocation ColonLoc, 5231 ArrayRef<CXXCtorInitializer*> MemInits, 5232 bool AnyErrors) { 5233 if (!ConstructorDecl) 5234 return; 5235 5236 AdjustDeclIfTemplate(ConstructorDecl); 5237 5238 CXXConstructorDecl *Constructor 5239 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5240 5241 if (!Constructor) { 5242 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5243 return; 5244 } 5245 5246 // Mapping for the duplicate initializers check. 5247 // For member initializers, this is keyed with a FieldDecl*. 5248 // For base initializers, this is keyed with a Type*. 5249 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5250 5251 // Mapping for the inconsistent anonymous-union initializers check. 5252 RedundantUnionMap MemberUnions; 5253 5254 bool HadError = false; 5255 for (unsigned i = 0; i < MemInits.size(); i++) { 5256 CXXCtorInitializer *Init = MemInits[i]; 5257 5258 // Set the source order index. 5259 Init->setSourceOrder(i); 5260 5261 if (Init->isAnyMemberInitializer()) { 5262 const void *Key = GetKeyForMember(Context, Init); 5263 if (CheckRedundantInit(*this, Init, Members[Key]) || 5264 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5265 HadError = true; 5266 } else if (Init->isBaseInitializer()) { 5267 const void *Key = GetKeyForMember(Context, Init); 5268 if (CheckRedundantInit(*this, Init, Members[Key])) 5269 HadError = true; 5270 } else { 5271 assert(Init->isDelegatingInitializer()); 5272 // This must be the only initializer 5273 if (MemInits.size() != 1) { 5274 Diag(Init->getSourceLocation(), 5275 diag::err_delegating_initializer_alone) 5276 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5277 // We will treat this as being the only initializer. 5278 } 5279 SetDelegatingInitializer(Constructor, MemInits[i]); 5280 // Return immediately as the initializer is set. 5281 return; 5282 } 5283 } 5284 5285 if (HadError) 5286 return; 5287 5288 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5289 5290 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5291 5292 DiagnoseUninitializedFields(*this, Constructor); 5293 } 5294 5295 void 5296 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5297 CXXRecordDecl *ClassDecl) { 5298 // Ignore dependent contexts. Also ignore unions, since their members never 5299 // have destructors implicitly called. 5300 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5301 return; 5302 5303 // FIXME: all the access-control diagnostics are positioned on the 5304 // field/base declaration. That's probably good; that said, the 5305 // user might reasonably want to know why the destructor is being 5306 // emitted, and we currently don't say. 5307 5308 // Non-static data members. 5309 for (auto *Field : ClassDecl->fields()) { 5310 if (Field->isInvalidDecl()) 5311 continue; 5312 5313 // Don't destroy incomplete or zero-length arrays. 5314 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5315 continue; 5316 5317 QualType FieldType = Context.getBaseElementType(Field->getType()); 5318 5319 const RecordType* RT = FieldType->getAs<RecordType>(); 5320 if (!RT) 5321 continue; 5322 5323 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5324 if (FieldClassDecl->isInvalidDecl()) 5325 continue; 5326 if (FieldClassDecl->hasIrrelevantDestructor()) 5327 continue; 5328 // The destructor for an implicit anonymous union member is never invoked. 5329 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5330 continue; 5331 5332 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5333 assert(Dtor && "No dtor found for FieldClassDecl!"); 5334 CheckDestructorAccess(Field->getLocation(), Dtor, 5335 PDiag(diag::err_access_dtor_field) 5336 << Field->getDeclName() 5337 << FieldType); 5338 5339 MarkFunctionReferenced(Location, Dtor); 5340 DiagnoseUseOfDecl(Dtor, Location); 5341 } 5342 5343 // We only potentially invoke the destructors of potentially constructed 5344 // subobjects. 5345 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5346 5347 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5348 5349 // Bases. 5350 for (const auto &Base : ClassDecl->bases()) { 5351 // Bases are always records in a well-formed non-dependent class. 5352 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5353 5354 // Remember direct virtual bases. 5355 if (Base.isVirtual()) { 5356 if (!VisitVirtualBases) 5357 continue; 5358 DirectVirtualBases.insert(RT); 5359 } 5360 5361 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5362 // If our base class is invalid, we probably can't get its dtor anyway. 5363 if (BaseClassDecl->isInvalidDecl()) 5364 continue; 5365 if (BaseClassDecl->hasIrrelevantDestructor()) 5366 continue; 5367 5368 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5369 assert(Dtor && "No dtor found for BaseClassDecl!"); 5370 5371 // FIXME: caret should be on the start of the class name 5372 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5373 PDiag(diag::err_access_dtor_base) 5374 << Base.getType() << Base.getSourceRange(), 5375 Context.getTypeDeclType(ClassDecl)); 5376 5377 MarkFunctionReferenced(Location, Dtor); 5378 DiagnoseUseOfDecl(Dtor, Location); 5379 } 5380 5381 if (!VisitVirtualBases) 5382 return; 5383 5384 // Virtual bases. 5385 for (const auto &VBase : ClassDecl->vbases()) { 5386 // Bases are always records in a well-formed non-dependent class. 5387 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5388 5389 // Ignore direct virtual bases. 5390 if (DirectVirtualBases.count(RT)) 5391 continue; 5392 5393 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5394 // If our base class is invalid, we probably can't get its dtor anyway. 5395 if (BaseClassDecl->isInvalidDecl()) 5396 continue; 5397 if (BaseClassDecl->hasIrrelevantDestructor()) 5398 continue; 5399 5400 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5401 assert(Dtor && "No dtor found for BaseClassDecl!"); 5402 if (CheckDestructorAccess( 5403 ClassDecl->getLocation(), Dtor, 5404 PDiag(diag::err_access_dtor_vbase) 5405 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5406 Context.getTypeDeclType(ClassDecl)) == 5407 AR_accessible) { 5408 CheckDerivedToBaseConversion( 5409 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5410 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5411 SourceRange(), DeclarationName(), nullptr); 5412 } 5413 5414 MarkFunctionReferenced(Location, Dtor); 5415 DiagnoseUseOfDecl(Dtor, Location); 5416 } 5417 } 5418 5419 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5420 if (!CDtorDecl) 5421 return; 5422 5423 if (CXXConstructorDecl *Constructor 5424 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5425 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5426 DiagnoseUninitializedFields(*this, Constructor); 5427 } 5428 } 5429 5430 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5431 if (!getLangOpts().CPlusPlus) 5432 return false; 5433 5434 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5435 if (!RD) 5436 return false; 5437 5438 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5439 // class template specialization here, but doing so breaks a lot of code. 5440 5441 // We can't answer whether something is abstract until it has a 5442 // definition. If it's currently being defined, we'll walk back 5443 // over all the declarations when we have a full definition. 5444 const CXXRecordDecl *Def = RD->getDefinition(); 5445 if (!Def || Def->isBeingDefined()) 5446 return false; 5447 5448 return RD->isAbstract(); 5449 } 5450 5451 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5452 TypeDiagnoser &Diagnoser) { 5453 if (!isAbstractType(Loc, T)) 5454 return false; 5455 5456 T = Context.getBaseElementType(T); 5457 Diagnoser.diagnose(*this, Loc, T); 5458 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5459 return true; 5460 } 5461 5462 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5463 // Check if we've already emitted the list of pure virtual functions 5464 // for this class. 5465 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5466 return; 5467 5468 // If the diagnostic is suppressed, don't emit the notes. We're only 5469 // going to emit them once, so try to attach them to a diagnostic we're 5470 // actually going to show. 5471 if (Diags.isLastDiagnosticIgnored()) 5472 return; 5473 5474 CXXFinalOverriderMap FinalOverriders; 5475 RD->getFinalOverriders(FinalOverriders); 5476 5477 // Keep a set of seen pure methods so we won't diagnose the same method 5478 // more than once. 5479 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5480 5481 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5482 MEnd = FinalOverriders.end(); 5483 M != MEnd; 5484 ++M) { 5485 for (OverridingMethods::iterator SO = M->second.begin(), 5486 SOEnd = M->second.end(); 5487 SO != SOEnd; ++SO) { 5488 // C++ [class.abstract]p4: 5489 // A class is abstract if it contains or inherits at least one 5490 // pure virtual function for which the final overrider is pure 5491 // virtual. 5492 5493 // 5494 if (SO->second.size() != 1) 5495 continue; 5496 5497 if (!SO->second.front().Method->isPure()) 5498 continue; 5499 5500 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5501 continue; 5502 5503 Diag(SO->second.front().Method->getLocation(), 5504 diag::note_pure_virtual_function) 5505 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5506 } 5507 } 5508 5509 if (!PureVirtualClassDiagSet) 5510 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5511 PureVirtualClassDiagSet->insert(RD); 5512 } 5513 5514 namespace { 5515 struct AbstractUsageInfo { 5516 Sema &S; 5517 CXXRecordDecl *Record; 5518 CanQualType AbstractType; 5519 bool Invalid; 5520 5521 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5522 : S(S), Record(Record), 5523 AbstractType(S.Context.getCanonicalType( 5524 S.Context.getTypeDeclType(Record))), 5525 Invalid(false) {} 5526 5527 void DiagnoseAbstractType() { 5528 if (Invalid) return; 5529 S.DiagnoseAbstractType(Record); 5530 Invalid = true; 5531 } 5532 5533 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5534 }; 5535 5536 struct CheckAbstractUsage { 5537 AbstractUsageInfo &Info; 5538 const NamedDecl *Ctx; 5539 5540 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5541 : Info(Info), Ctx(Ctx) {} 5542 5543 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5544 switch (TL.getTypeLocClass()) { 5545 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5546 #define TYPELOC(CLASS, PARENT) \ 5547 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5548 #include "clang/AST/TypeLocNodes.def" 5549 } 5550 } 5551 5552 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5553 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5554 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5555 if (!TL.getParam(I)) 5556 continue; 5557 5558 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5559 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5560 } 5561 } 5562 5563 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5564 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5565 } 5566 5567 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5568 // Visit the type parameters from a permissive context. 5569 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5570 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5571 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5572 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5573 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5574 // TODO: other template argument types? 5575 } 5576 } 5577 5578 // Visit pointee types from a permissive context. 5579 #define CheckPolymorphic(Type) \ 5580 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5581 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5582 } 5583 CheckPolymorphic(PointerTypeLoc) 5584 CheckPolymorphic(ReferenceTypeLoc) 5585 CheckPolymorphic(MemberPointerTypeLoc) 5586 CheckPolymorphic(BlockPointerTypeLoc) 5587 CheckPolymorphic(AtomicTypeLoc) 5588 5589 /// Handle all the types we haven't given a more specific 5590 /// implementation for above. 5591 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5592 // Every other kind of type that we haven't called out already 5593 // that has an inner type is either (1) sugar or (2) contains that 5594 // inner type in some way as a subobject. 5595 if (TypeLoc Next = TL.getNextTypeLoc()) 5596 return Visit(Next, Sel); 5597 5598 // If there's no inner type and we're in a permissive context, 5599 // don't diagnose. 5600 if (Sel == Sema::AbstractNone) return; 5601 5602 // Check whether the type matches the abstract type. 5603 QualType T = TL.getType(); 5604 if (T->isArrayType()) { 5605 Sel = Sema::AbstractArrayType; 5606 T = Info.S.Context.getBaseElementType(T); 5607 } 5608 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5609 if (CT != Info.AbstractType) return; 5610 5611 // It matched; do some magic. 5612 if (Sel == Sema::AbstractArrayType) { 5613 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5614 << T << TL.getSourceRange(); 5615 } else { 5616 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5617 << Sel << T << TL.getSourceRange(); 5618 } 5619 Info.DiagnoseAbstractType(); 5620 } 5621 }; 5622 5623 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5624 Sema::AbstractDiagSelID Sel) { 5625 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5626 } 5627 5628 } 5629 5630 /// Check for invalid uses of an abstract type in a method declaration. 5631 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5632 CXXMethodDecl *MD) { 5633 // No need to do the check on definitions, which require that 5634 // the return/param types be complete. 5635 if (MD->doesThisDeclarationHaveABody()) 5636 return; 5637 5638 // For safety's sake, just ignore it if we don't have type source 5639 // information. This should never happen for non-implicit methods, 5640 // but... 5641 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5642 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5643 } 5644 5645 /// Check for invalid uses of an abstract type within a class definition. 5646 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5647 CXXRecordDecl *RD) { 5648 for (auto *D : RD->decls()) { 5649 if (D->isImplicit()) continue; 5650 5651 // Methods and method templates. 5652 if (isa<CXXMethodDecl>(D)) { 5653 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5654 } else if (isa<FunctionTemplateDecl>(D)) { 5655 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5656 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5657 5658 // Fields and static variables. 5659 } else if (isa<FieldDecl>(D)) { 5660 FieldDecl *FD = cast<FieldDecl>(D); 5661 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5662 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5663 } else if (isa<VarDecl>(D)) { 5664 VarDecl *VD = cast<VarDecl>(D); 5665 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5666 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5667 5668 // Nested classes and class templates. 5669 } else if (isa<CXXRecordDecl>(D)) { 5670 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5671 } else if (isa<ClassTemplateDecl>(D)) { 5672 CheckAbstractClassUsage(Info, 5673 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5674 } 5675 } 5676 } 5677 5678 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5679 Attr *ClassAttr = getDLLAttr(Class); 5680 if (!ClassAttr) 5681 return; 5682 5683 assert(ClassAttr->getKind() == attr::DLLExport); 5684 5685 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5686 5687 if (TSK == TSK_ExplicitInstantiationDeclaration) 5688 // Don't go any further if this is just an explicit instantiation 5689 // declaration. 5690 return; 5691 5692 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5693 S.MarkVTableUsed(Class->getLocation(), Class, true); 5694 5695 for (Decl *Member : Class->decls()) { 5696 // Defined static variables that are members of an exported base 5697 // class must be marked export too. 5698 auto *VD = dyn_cast<VarDecl>(Member); 5699 if (VD && Member->getAttr<DLLExportAttr>() && 5700 VD->getStorageClass() == SC_Static && 5701 TSK == TSK_ImplicitInstantiation) 5702 S.MarkVariableReferenced(VD->getLocation(), VD); 5703 5704 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5705 if (!MD) 5706 continue; 5707 5708 if (Member->getAttr<DLLExportAttr>()) { 5709 if (MD->isUserProvided()) { 5710 // Instantiate non-default class member functions ... 5711 5712 // .. except for certain kinds of template specializations. 5713 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5714 continue; 5715 5716 S.MarkFunctionReferenced(Class->getLocation(), MD); 5717 5718 // The function will be passed to the consumer when its definition is 5719 // encountered. 5720 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5721 MD->isCopyAssignmentOperator() || 5722 MD->isMoveAssignmentOperator()) { 5723 // Synthesize and instantiate non-trivial implicit methods, explicitly 5724 // defaulted methods, and the copy and move assignment operators. The 5725 // latter are exported even if they are trivial, because the address of 5726 // an operator can be taken and should compare equal across libraries. 5727 DiagnosticErrorTrap Trap(S.Diags); 5728 S.MarkFunctionReferenced(Class->getLocation(), MD); 5729 if (Trap.hasErrorOccurred()) { 5730 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5731 << Class << !S.getLangOpts().CPlusPlus11; 5732 break; 5733 } 5734 5735 // There is no later point when we will see the definition of this 5736 // function, so pass it to the consumer now. 5737 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5738 } 5739 } 5740 } 5741 } 5742 5743 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5744 CXXRecordDecl *Class) { 5745 // Only the MS ABI has default constructor closures, so we don't need to do 5746 // this semantic checking anywhere else. 5747 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5748 return; 5749 5750 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5751 for (Decl *Member : Class->decls()) { 5752 // Look for exported default constructors. 5753 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5754 if (!CD || !CD->isDefaultConstructor()) 5755 continue; 5756 auto *Attr = CD->getAttr<DLLExportAttr>(); 5757 if (!Attr) 5758 continue; 5759 5760 // If the class is non-dependent, mark the default arguments as ODR-used so 5761 // that we can properly codegen the constructor closure. 5762 if (!Class->isDependentContext()) { 5763 for (ParmVarDecl *PD : CD->parameters()) { 5764 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5765 S.DiscardCleanupsInEvaluationContext(); 5766 } 5767 } 5768 5769 if (LastExportedDefaultCtor) { 5770 S.Diag(LastExportedDefaultCtor->getLocation(), 5771 diag::err_attribute_dll_ambiguous_default_ctor) 5772 << Class; 5773 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5774 << CD->getDeclName(); 5775 return; 5776 } 5777 LastExportedDefaultCtor = CD; 5778 } 5779 } 5780 5781 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5782 // Mark any compiler-generated routines with the implicit code_seg attribute. 5783 for (auto *Method : Class->methods()) { 5784 if (Method->isUserProvided()) 5785 continue; 5786 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5787 Method->addAttr(A); 5788 } 5789 } 5790 5791 /// Check class-level dllimport/dllexport attribute. 5792 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5793 Attr *ClassAttr = getDLLAttr(Class); 5794 5795 // MSVC inherits DLL attributes to partial class template specializations. 5796 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5797 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5798 if (Attr *TemplateAttr = 5799 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5800 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5801 A->setInherited(true); 5802 ClassAttr = A; 5803 } 5804 } 5805 } 5806 5807 if (!ClassAttr) 5808 return; 5809 5810 if (!Class->isExternallyVisible()) { 5811 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5812 << Class << ClassAttr; 5813 return; 5814 } 5815 5816 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5817 !ClassAttr->isInherited()) { 5818 // Diagnose dll attributes on members of class with dll attribute. 5819 for (Decl *Member : Class->decls()) { 5820 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5821 continue; 5822 InheritableAttr *MemberAttr = getDLLAttr(Member); 5823 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5824 continue; 5825 5826 Diag(MemberAttr->getLocation(), 5827 diag::err_attribute_dll_member_of_dll_class) 5828 << MemberAttr << ClassAttr; 5829 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5830 Member->setInvalidDecl(); 5831 } 5832 } 5833 5834 if (Class->getDescribedClassTemplate()) 5835 // Don't inherit dll attribute until the template is instantiated. 5836 return; 5837 5838 // The class is either imported or exported. 5839 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5840 5841 // Check if this was a dllimport attribute propagated from a derived class to 5842 // a base class template specialization. We don't apply these attributes to 5843 // static data members. 5844 const bool PropagatedImport = 5845 !ClassExported && 5846 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5847 5848 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5849 5850 // Ignore explicit dllexport on explicit class template instantiation 5851 // declarations, except in MinGW mode. 5852 if (ClassExported && !ClassAttr->isInherited() && 5853 TSK == TSK_ExplicitInstantiationDeclaration && 5854 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 5855 Class->dropAttr<DLLExportAttr>(); 5856 return; 5857 } 5858 5859 // Force declaration of implicit members so they can inherit the attribute. 5860 ForceDeclarationOfImplicitMembers(Class); 5861 5862 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5863 // seem to be true in practice? 5864 5865 for (Decl *Member : Class->decls()) { 5866 VarDecl *VD = dyn_cast<VarDecl>(Member); 5867 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5868 5869 // Only methods and static fields inherit the attributes. 5870 if (!VD && !MD) 5871 continue; 5872 5873 if (MD) { 5874 // Don't process deleted methods. 5875 if (MD->isDeleted()) 5876 continue; 5877 5878 if (MD->isInlined()) { 5879 // MinGW does not import or export inline methods. But do it for 5880 // template instantiations. 5881 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5882 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 5883 TSK != TSK_ExplicitInstantiationDeclaration && 5884 TSK != TSK_ExplicitInstantiationDefinition) 5885 continue; 5886 5887 // MSVC versions before 2015 don't export the move assignment operators 5888 // and move constructor, so don't attempt to import/export them if 5889 // we have a definition. 5890 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5891 if ((MD->isMoveAssignmentOperator() || 5892 (Ctor && Ctor->isMoveConstructor())) && 5893 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5894 continue; 5895 5896 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5897 // operator is exported anyway. 5898 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5899 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5900 continue; 5901 } 5902 } 5903 5904 // Don't apply dllimport attributes to static data members of class template 5905 // instantiations when the attribute is propagated from a derived class. 5906 if (VD && PropagatedImport) 5907 continue; 5908 5909 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5910 continue; 5911 5912 if (!getDLLAttr(Member)) { 5913 InheritableAttr *NewAttr = nullptr; 5914 5915 // Do not export/import inline function when -fno-dllexport-inlines is 5916 // passed. But add attribute for later local static var check. 5917 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 5918 TSK != TSK_ExplicitInstantiationDeclaration && 5919 TSK != TSK_ExplicitInstantiationDefinition) { 5920 if (ClassExported) { 5921 NewAttr = ::new (getASTContext()) 5922 DLLExportStaticLocalAttr(ClassAttr->getRange(), 5923 getASTContext(), 5924 ClassAttr->getSpellingListIndex()); 5925 } else { 5926 NewAttr = ::new (getASTContext()) 5927 DLLImportStaticLocalAttr(ClassAttr->getRange(), 5928 getASTContext(), 5929 ClassAttr->getSpellingListIndex()); 5930 } 5931 } else { 5932 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5933 } 5934 5935 NewAttr->setInherited(true); 5936 Member->addAttr(NewAttr); 5937 5938 if (MD) { 5939 // Propagate DLLAttr to friend re-declarations of MD that have already 5940 // been constructed. 5941 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5942 FD = FD->getPreviousDecl()) { 5943 if (FD->getFriendObjectKind() == Decl::FOK_None) 5944 continue; 5945 assert(!getDLLAttr(FD) && 5946 "friend re-decl should not already have a DLLAttr"); 5947 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5948 NewAttr->setInherited(true); 5949 FD->addAttr(NewAttr); 5950 } 5951 } 5952 } 5953 } 5954 5955 if (ClassExported) 5956 DelayedDllExportClasses.push_back(Class); 5957 } 5958 5959 /// Perform propagation of DLL attributes from a derived class to a 5960 /// templated base class for MS compatibility. 5961 void Sema::propagateDLLAttrToBaseClassTemplate( 5962 CXXRecordDecl *Class, Attr *ClassAttr, 5963 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5964 if (getDLLAttr( 5965 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5966 // If the base class template has a DLL attribute, don't try to change it. 5967 return; 5968 } 5969 5970 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5971 if (!getDLLAttr(BaseTemplateSpec) && 5972 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5973 TSK == TSK_ImplicitInstantiation)) { 5974 // The template hasn't been instantiated yet (or it has, but only as an 5975 // explicit instantiation declaration or implicit instantiation, which means 5976 // we haven't codegenned any members yet), so propagate the attribute. 5977 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5978 NewAttr->setInherited(true); 5979 BaseTemplateSpec->addAttr(NewAttr); 5980 5981 // If this was an import, mark that we propagated it from a derived class to 5982 // a base class template specialization. 5983 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 5984 ImportAttr->setPropagatedToBaseTemplate(); 5985 5986 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5987 // needs to be run again to work see the new attribute. Otherwise this will 5988 // get run whenever the template is instantiated. 5989 if (TSK != TSK_Undeclared) 5990 checkClassLevelDLLAttribute(BaseTemplateSpec); 5991 5992 return; 5993 } 5994 5995 if (getDLLAttr(BaseTemplateSpec)) { 5996 // The template has already been specialized or instantiated with an 5997 // attribute, explicitly or through propagation. We should not try to change 5998 // it. 5999 return; 6000 } 6001 6002 // The template was previously instantiated or explicitly specialized without 6003 // a dll attribute, It's too late for us to add an attribute, so warn that 6004 // this is unsupported. 6005 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6006 << BaseTemplateSpec->isExplicitSpecialization(); 6007 Diag(ClassAttr->getLocation(), diag::note_attribute); 6008 if (BaseTemplateSpec->isExplicitSpecialization()) { 6009 Diag(BaseTemplateSpec->getLocation(), 6010 diag::note_template_class_explicit_specialization_was_here) 6011 << BaseTemplateSpec; 6012 } else { 6013 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6014 diag::note_template_class_instantiation_was_here) 6015 << BaseTemplateSpec; 6016 } 6017 } 6018 6019 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 6020 SourceLocation DefaultLoc) { 6021 switch (S.getSpecialMember(MD)) { 6022 case Sema::CXXDefaultConstructor: 6023 S.DefineImplicitDefaultConstructor(DefaultLoc, 6024 cast<CXXConstructorDecl>(MD)); 6025 break; 6026 case Sema::CXXCopyConstructor: 6027 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6028 break; 6029 case Sema::CXXCopyAssignment: 6030 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 6031 break; 6032 case Sema::CXXDestructor: 6033 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 6034 break; 6035 case Sema::CXXMoveConstructor: 6036 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6037 break; 6038 case Sema::CXXMoveAssignment: 6039 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 6040 break; 6041 case Sema::CXXInvalid: 6042 llvm_unreachable("Invalid special member."); 6043 } 6044 } 6045 6046 /// Determine whether a type is permitted to be passed or returned in 6047 /// registers, per C++ [class.temporary]p3. 6048 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6049 TargetInfo::CallingConvKind CCK) { 6050 if (D->isDependentType() || D->isInvalidDecl()) 6051 return false; 6052 6053 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6054 // The PS4 platform ABI follows the behavior of Clang 3.2. 6055 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6056 return !D->hasNonTrivialDestructorForCall() && 6057 !D->hasNonTrivialCopyConstructorForCall(); 6058 6059 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6060 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6061 bool DtorIsTrivialForCall = false; 6062 6063 // If a class has at least one non-deleted, trivial copy constructor, it 6064 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6065 // 6066 // Note: This permits classes with non-trivial copy or move ctors to be 6067 // passed in registers, so long as they *also* have a trivial copy ctor, 6068 // which is non-conforming. 6069 if (D->needsImplicitCopyConstructor()) { 6070 if (!D->defaultedCopyConstructorIsDeleted()) { 6071 if (D->hasTrivialCopyConstructor()) 6072 CopyCtorIsTrivial = true; 6073 if (D->hasTrivialCopyConstructorForCall()) 6074 CopyCtorIsTrivialForCall = true; 6075 } 6076 } else { 6077 for (const CXXConstructorDecl *CD : D->ctors()) { 6078 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6079 if (CD->isTrivial()) 6080 CopyCtorIsTrivial = true; 6081 if (CD->isTrivialForCall()) 6082 CopyCtorIsTrivialForCall = true; 6083 } 6084 } 6085 } 6086 6087 if (D->needsImplicitDestructor()) { 6088 if (!D->defaultedDestructorIsDeleted() && 6089 D->hasTrivialDestructorForCall()) 6090 DtorIsTrivialForCall = true; 6091 } else if (const auto *DD = D->getDestructor()) { 6092 if (!DD->isDeleted() && DD->isTrivialForCall()) 6093 DtorIsTrivialForCall = true; 6094 } 6095 6096 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6097 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6098 return true; 6099 6100 // If a class has a destructor, we'd really like to pass it indirectly 6101 // because it allows us to elide copies. Unfortunately, MSVC makes that 6102 // impossible for small types, which it will pass in a single register or 6103 // stack slot. Most objects with dtors are large-ish, so handle that early. 6104 // We can't call out all large objects as being indirect because there are 6105 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6106 // how we pass large POD types. 6107 6108 // Note: This permits small classes with nontrivial destructors to be 6109 // passed in registers, which is non-conforming. 6110 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6111 uint64_t TypeSize = isAArch64 ? 128 : 64; 6112 6113 if (CopyCtorIsTrivial && 6114 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6115 return true; 6116 return false; 6117 } 6118 6119 // Per C++ [class.temporary]p3, the relevant condition is: 6120 // each copy constructor, move constructor, and destructor of X is 6121 // either trivial or deleted, and X has at least one non-deleted copy 6122 // or move constructor 6123 bool HasNonDeletedCopyOrMove = false; 6124 6125 if (D->needsImplicitCopyConstructor() && 6126 !D->defaultedCopyConstructorIsDeleted()) { 6127 if (!D->hasTrivialCopyConstructorForCall()) 6128 return false; 6129 HasNonDeletedCopyOrMove = true; 6130 } 6131 6132 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6133 !D->defaultedMoveConstructorIsDeleted()) { 6134 if (!D->hasTrivialMoveConstructorForCall()) 6135 return false; 6136 HasNonDeletedCopyOrMove = true; 6137 } 6138 6139 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6140 !D->hasTrivialDestructorForCall()) 6141 return false; 6142 6143 for (const CXXMethodDecl *MD : D->methods()) { 6144 if (MD->isDeleted()) 6145 continue; 6146 6147 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6148 if (CD && CD->isCopyOrMoveConstructor()) 6149 HasNonDeletedCopyOrMove = true; 6150 else if (!isa<CXXDestructorDecl>(MD)) 6151 continue; 6152 6153 if (!MD->isTrivialForCall()) 6154 return false; 6155 } 6156 6157 return HasNonDeletedCopyOrMove; 6158 } 6159 6160 /// Perform semantic checks on a class definition that has been 6161 /// completing, introducing implicitly-declared members, checking for 6162 /// abstract types, etc. 6163 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 6164 if (!Record) 6165 return; 6166 6167 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6168 AbstractUsageInfo Info(*this, Record); 6169 CheckAbstractClassUsage(Info, Record); 6170 } 6171 6172 // If this is not an aggregate type and has no user-declared constructor, 6173 // complain about any non-static data members of reference or const scalar 6174 // type, since they will never get initializers. 6175 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6176 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6177 !Record->isLambda()) { 6178 bool Complained = false; 6179 for (const auto *F : Record->fields()) { 6180 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6181 continue; 6182 6183 if (F->getType()->isReferenceType() || 6184 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6185 if (!Complained) { 6186 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6187 << Record->getTagKind() << Record; 6188 Complained = true; 6189 } 6190 6191 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6192 << F->getType()->isReferenceType() 6193 << F->getDeclName(); 6194 } 6195 } 6196 } 6197 6198 if (Record->getIdentifier()) { 6199 // C++ [class.mem]p13: 6200 // If T is the name of a class, then each of the following shall have a 6201 // name different from T: 6202 // - every member of every anonymous union that is a member of class T. 6203 // 6204 // C++ [class.mem]p14: 6205 // In addition, if class T has a user-declared constructor (12.1), every 6206 // non-static data member of class T shall have a name different from T. 6207 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6208 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6209 ++I) { 6210 NamedDecl *D = (*I)->getUnderlyingDecl(); 6211 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6212 Record->hasUserDeclaredConstructor()) || 6213 isa<IndirectFieldDecl>(D)) { 6214 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6215 << D->getDeclName(); 6216 break; 6217 } 6218 } 6219 } 6220 6221 // Warn if the class has virtual methods but non-virtual public destructor. 6222 if (Record->isPolymorphic() && !Record->isDependentType()) { 6223 CXXDestructorDecl *dtor = Record->getDestructor(); 6224 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6225 !Record->hasAttr<FinalAttr>()) 6226 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6227 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6228 } 6229 6230 if (Record->isAbstract()) { 6231 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6232 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6233 << FA->isSpelledAsSealed(); 6234 DiagnoseAbstractType(Record); 6235 } 6236 } 6237 6238 // See if trivial_abi has to be dropped. 6239 if (Record->hasAttr<TrivialABIAttr>()) 6240 checkIllFormedTrivialABIStruct(*Record); 6241 6242 // Set HasTrivialSpecialMemberForCall if the record has attribute 6243 // "trivial_abi". 6244 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6245 6246 if (HasTrivialABI) 6247 Record->setHasTrivialSpecialMemberForCall(); 6248 6249 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6250 // Check whether the explicitly-defaulted special members are valid. 6251 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6252 CheckExplicitlyDefaultedSpecialMember(M); 6253 6254 // For an explicitly defaulted or deleted special member, we defer 6255 // determining triviality until the class is complete. That time is now! 6256 CXXSpecialMember CSM = getSpecialMember(M); 6257 if (!M->isImplicit() && !M->isUserProvided()) { 6258 if (CSM != CXXInvalid) { 6259 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6260 // Inform the class that we've finished declaring this member. 6261 Record->finishedDefaultedOrDeletedMember(M); 6262 M->setTrivialForCall( 6263 HasTrivialABI || 6264 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6265 Record->setTrivialForCallFlags(M); 6266 } 6267 } 6268 6269 // Set triviality for the purpose of calls if this is a user-provided 6270 // copy/move constructor or destructor. 6271 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6272 CSM == CXXDestructor) && M->isUserProvided()) { 6273 M->setTrivialForCall(HasTrivialABI); 6274 Record->setTrivialForCallFlags(M); 6275 } 6276 6277 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6278 M->hasAttr<DLLExportAttr>()) { 6279 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6280 M->isTrivial() && 6281 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6282 CSM == CXXDestructor)) 6283 M->dropAttr<DLLExportAttr>(); 6284 6285 if (M->hasAttr<DLLExportAttr>()) { 6286 // Define after any fields with in-class initializers have been parsed. 6287 DelayedDllExportMemberFunctions.push_back(M); 6288 } 6289 } 6290 }; 6291 6292 bool HasMethodWithOverrideControl = false, 6293 HasOverridingMethodWithoutOverrideControl = false; 6294 if (!Record->isDependentType()) { 6295 // Check the destructor before any other member function. We need to 6296 // determine whether it's trivial in order to determine whether the claas 6297 // type is a literal type, which is a prerequisite for determining whether 6298 // other special member functions are valid and whether they're implicitly 6299 // 'constexpr'. 6300 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6301 CompleteMemberFunction(Dtor); 6302 6303 for (auto *M : Record->methods()) { 6304 // See if a method overloads virtual methods in a base 6305 // class without overriding any. 6306 if (!M->isStatic()) 6307 DiagnoseHiddenVirtualMethods(M); 6308 if (M->hasAttr<OverrideAttr>()) 6309 HasMethodWithOverrideControl = true; 6310 else if (M->size_overridden_methods() > 0) 6311 HasOverridingMethodWithoutOverrideControl = true; 6312 6313 if (!isa<CXXDestructorDecl>(M)) 6314 CompleteMemberFunction(M); 6315 } 6316 } 6317 6318 if (HasMethodWithOverrideControl && 6319 HasOverridingMethodWithoutOverrideControl) { 6320 // At least one method has the 'override' control declared. 6321 // Diagnose all other overridden methods which do not have 'override' specified on them. 6322 for (auto *M : Record->methods()) 6323 DiagnoseAbsenceOfOverrideControl(M); 6324 } 6325 6326 // ms_struct is a request to use the same ABI rules as MSVC. Check 6327 // whether this class uses any C++ features that are implemented 6328 // completely differently in MSVC, and if so, emit a diagnostic. 6329 // That diagnostic defaults to an error, but we allow projects to 6330 // map it down to a warning (or ignore it). It's a fairly common 6331 // practice among users of the ms_struct pragma to mass-annotate 6332 // headers, sweeping up a bunch of types that the project doesn't 6333 // really rely on MSVC-compatible layout for. We must therefore 6334 // support "ms_struct except for C++ stuff" as a secondary ABI. 6335 if (Record->isMsStruct(Context) && 6336 (Record->isPolymorphic() || Record->getNumBases())) { 6337 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6338 } 6339 6340 checkClassLevelDLLAttribute(Record); 6341 checkClassLevelCodeSegAttribute(Record); 6342 6343 bool ClangABICompat4 = 6344 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6345 TargetInfo::CallingConvKind CCK = 6346 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6347 bool CanPass = canPassInRegisters(*this, Record, CCK); 6348 6349 // Do not change ArgPassingRestrictions if it has already been set to 6350 // APK_CanNeverPassInRegs. 6351 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6352 Record->setArgPassingRestrictions(CanPass 6353 ? RecordDecl::APK_CanPassInRegs 6354 : RecordDecl::APK_CannotPassInRegs); 6355 6356 // If canPassInRegisters returns true despite the record having a non-trivial 6357 // destructor, the record is destructed in the callee. This happens only when 6358 // the record or one of its subobjects has a field annotated with trivial_abi 6359 // or a field qualified with ObjC __strong/__weak. 6360 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6361 Record->setParamDestroyedInCallee(true); 6362 else if (Record->hasNonTrivialDestructor()) 6363 Record->setParamDestroyedInCallee(CanPass); 6364 6365 if (getLangOpts().ForceEmitVTables) { 6366 // If we want to emit all the vtables, we need to mark it as used. This 6367 // is especially required for cases like vtable assumption loads. 6368 MarkVTableUsed(Record->getInnerLocStart(), Record); 6369 } 6370 } 6371 6372 /// Look up the special member function that would be called by a special 6373 /// member function for a subobject of class type. 6374 /// 6375 /// \param Class The class type of the subobject. 6376 /// \param CSM The kind of special member function. 6377 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6378 /// \param ConstRHS True if this is a copy operation with a const object 6379 /// on its RHS, that is, if the argument to the outer special member 6380 /// function is 'const' and this is not a field marked 'mutable'. 6381 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6382 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6383 unsigned FieldQuals, bool ConstRHS) { 6384 unsigned LHSQuals = 0; 6385 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6386 LHSQuals = FieldQuals; 6387 6388 unsigned RHSQuals = FieldQuals; 6389 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6390 RHSQuals = 0; 6391 else if (ConstRHS) 6392 RHSQuals |= Qualifiers::Const; 6393 6394 return S.LookupSpecialMember(Class, CSM, 6395 RHSQuals & Qualifiers::Const, 6396 RHSQuals & Qualifiers::Volatile, 6397 false, 6398 LHSQuals & Qualifiers::Const, 6399 LHSQuals & Qualifiers::Volatile); 6400 } 6401 6402 class Sema::InheritedConstructorInfo { 6403 Sema &S; 6404 SourceLocation UseLoc; 6405 6406 /// A mapping from the base classes through which the constructor was 6407 /// inherited to the using shadow declaration in that base class (or a null 6408 /// pointer if the constructor was declared in that base class). 6409 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6410 InheritedFromBases; 6411 6412 public: 6413 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6414 ConstructorUsingShadowDecl *Shadow) 6415 : S(S), UseLoc(UseLoc) { 6416 bool DiagnosedMultipleConstructedBases = false; 6417 CXXRecordDecl *ConstructedBase = nullptr; 6418 UsingDecl *ConstructedBaseUsing = nullptr; 6419 6420 // Find the set of such base class subobjects and check that there's a 6421 // unique constructed subobject. 6422 for (auto *D : Shadow->redecls()) { 6423 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6424 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6425 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6426 6427 InheritedFromBases.insert( 6428 std::make_pair(DNominatedBase->getCanonicalDecl(), 6429 DShadow->getNominatedBaseClassShadowDecl())); 6430 if (DShadow->constructsVirtualBase()) 6431 InheritedFromBases.insert( 6432 std::make_pair(DConstructedBase->getCanonicalDecl(), 6433 DShadow->getConstructedBaseClassShadowDecl())); 6434 else 6435 assert(DNominatedBase == DConstructedBase); 6436 6437 // [class.inhctor.init]p2: 6438 // If the constructor was inherited from multiple base class subobjects 6439 // of type B, the program is ill-formed. 6440 if (!ConstructedBase) { 6441 ConstructedBase = DConstructedBase; 6442 ConstructedBaseUsing = D->getUsingDecl(); 6443 } else if (ConstructedBase != DConstructedBase && 6444 !Shadow->isInvalidDecl()) { 6445 if (!DiagnosedMultipleConstructedBases) { 6446 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6447 << Shadow->getTargetDecl(); 6448 S.Diag(ConstructedBaseUsing->getLocation(), 6449 diag::note_ambiguous_inherited_constructor_using) 6450 << ConstructedBase; 6451 DiagnosedMultipleConstructedBases = true; 6452 } 6453 S.Diag(D->getUsingDecl()->getLocation(), 6454 diag::note_ambiguous_inherited_constructor_using) 6455 << DConstructedBase; 6456 } 6457 } 6458 6459 if (DiagnosedMultipleConstructedBases) 6460 Shadow->setInvalidDecl(); 6461 } 6462 6463 /// Find the constructor to use for inherited construction of a base class, 6464 /// and whether that base class constructor inherits the constructor from a 6465 /// virtual base class (in which case it won't actually invoke it). 6466 std::pair<CXXConstructorDecl *, bool> 6467 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6468 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6469 if (It == InheritedFromBases.end()) 6470 return std::make_pair(nullptr, false); 6471 6472 // This is an intermediary class. 6473 if (It->second) 6474 return std::make_pair( 6475 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6476 It->second->constructsVirtualBase()); 6477 6478 // This is the base class from which the constructor was inherited. 6479 return std::make_pair(Ctor, false); 6480 } 6481 }; 6482 6483 /// Is the special member function which would be selected to perform the 6484 /// specified operation on the specified class type a constexpr constructor? 6485 static bool 6486 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6487 Sema::CXXSpecialMember CSM, unsigned Quals, 6488 bool ConstRHS, 6489 CXXConstructorDecl *InheritedCtor = nullptr, 6490 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6491 // If we're inheriting a constructor, see if we need to call it for this base 6492 // class. 6493 if (InheritedCtor) { 6494 assert(CSM == Sema::CXXDefaultConstructor); 6495 auto BaseCtor = 6496 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6497 if (BaseCtor) 6498 return BaseCtor->isConstexpr(); 6499 } 6500 6501 if (CSM == Sema::CXXDefaultConstructor) 6502 return ClassDecl->hasConstexprDefaultConstructor(); 6503 6504 Sema::SpecialMemberOverloadResult SMOR = 6505 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6506 if (!SMOR.getMethod()) 6507 // A constructor we wouldn't select can't be "involved in initializing" 6508 // anything. 6509 return true; 6510 return SMOR.getMethod()->isConstexpr(); 6511 } 6512 6513 /// Determine whether the specified special member function would be constexpr 6514 /// if it were implicitly defined. 6515 static bool defaultedSpecialMemberIsConstexpr( 6516 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6517 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6518 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6519 if (!S.getLangOpts().CPlusPlus11) 6520 return false; 6521 6522 // C++11 [dcl.constexpr]p4: 6523 // In the definition of a constexpr constructor [...] 6524 bool Ctor = true; 6525 switch (CSM) { 6526 case Sema::CXXDefaultConstructor: 6527 if (Inherited) 6528 break; 6529 // Since default constructor lookup is essentially trivial (and cannot 6530 // involve, for instance, template instantiation), we compute whether a 6531 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6532 // 6533 // This is important for performance; we need to know whether the default 6534 // constructor is constexpr to determine whether the type is a literal type. 6535 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6536 6537 case Sema::CXXCopyConstructor: 6538 case Sema::CXXMoveConstructor: 6539 // For copy or move constructors, we need to perform overload resolution. 6540 break; 6541 6542 case Sema::CXXCopyAssignment: 6543 case Sema::CXXMoveAssignment: 6544 if (!S.getLangOpts().CPlusPlus14) 6545 return false; 6546 // In C++1y, we need to perform overload resolution. 6547 Ctor = false; 6548 break; 6549 6550 case Sema::CXXDestructor: 6551 case Sema::CXXInvalid: 6552 return false; 6553 } 6554 6555 // -- if the class is a non-empty union, or for each non-empty anonymous 6556 // union member of a non-union class, exactly one non-static data member 6557 // shall be initialized; [DR1359] 6558 // 6559 // If we squint, this is guaranteed, since exactly one non-static data member 6560 // will be initialized (if the constructor isn't deleted), we just don't know 6561 // which one. 6562 if (Ctor && ClassDecl->isUnion()) 6563 return CSM == Sema::CXXDefaultConstructor 6564 ? ClassDecl->hasInClassInitializer() || 6565 !ClassDecl->hasVariantMembers() 6566 : true; 6567 6568 // -- the class shall not have any virtual base classes; 6569 if (Ctor && ClassDecl->getNumVBases()) 6570 return false; 6571 6572 // C++1y [class.copy]p26: 6573 // -- [the class] is a literal type, and 6574 if (!Ctor && !ClassDecl->isLiteral()) 6575 return false; 6576 6577 // -- every constructor involved in initializing [...] base class 6578 // sub-objects shall be a constexpr constructor; 6579 // -- the assignment operator selected to copy/move each direct base 6580 // class is a constexpr function, and 6581 for (const auto &B : ClassDecl->bases()) { 6582 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6583 if (!BaseType) continue; 6584 6585 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6586 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6587 InheritedCtor, Inherited)) 6588 return false; 6589 } 6590 6591 // -- every constructor involved in initializing non-static data members 6592 // [...] shall be a constexpr constructor; 6593 // -- every non-static data member and base class sub-object shall be 6594 // initialized 6595 // -- for each non-static data member of X that is of class type (or array 6596 // thereof), the assignment operator selected to copy/move that member is 6597 // a constexpr function 6598 for (const auto *F : ClassDecl->fields()) { 6599 if (F->isInvalidDecl()) 6600 continue; 6601 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6602 continue; 6603 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6604 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6605 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6606 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6607 BaseType.getCVRQualifiers(), 6608 ConstArg && !F->isMutable())) 6609 return false; 6610 } else if (CSM == Sema::CXXDefaultConstructor) { 6611 return false; 6612 } 6613 } 6614 6615 // All OK, it's constexpr! 6616 return true; 6617 } 6618 6619 static Sema::ImplicitExceptionSpecification 6620 ComputeDefaultedSpecialMemberExceptionSpec( 6621 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6622 Sema::InheritedConstructorInfo *ICI); 6623 6624 static Sema::ImplicitExceptionSpecification 6625 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6626 auto CSM = S.getSpecialMember(MD); 6627 if (CSM != Sema::CXXInvalid) 6628 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6629 6630 auto *CD = cast<CXXConstructorDecl>(MD); 6631 assert(CD->getInheritedConstructor() && 6632 "only special members have implicit exception specs"); 6633 Sema::InheritedConstructorInfo ICI( 6634 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6635 return ComputeDefaultedSpecialMemberExceptionSpec( 6636 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6637 } 6638 6639 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6640 CXXMethodDecl *MD) { 6641 FunctionProtoType::ExtProtoInfo EPI; 6642 6643 // Build an exception specification pointing back at this member. 6644 EPI.ExceptionSpec.Type = EST_Unevaluated; 6645 EPI.ExceptionSpec.SourceDecl = MD; 6646 6647 // Set the calling convention to the default for C++ instance methods. 6648 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6649 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6650 /*IsCXXMethod=*/true)); 6651 return EPI; 6652 } 6653 6654 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6655 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6656 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6657 return; 6658 6659 // Evaluate the exception specification. 6660 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6661 auto ESI = IES.getExceptionSpec(); 6662 6663 // Update the type of the special member to use it. 6664 UpdateExceptionSpec(MD, ESI); 6665 6666 // A user-provided destructor can be defined outside the class. When that 6667 // happens, be sure to update the exception specification on both 6668 // declarations. 6669 const FunctionProtoType *CanonicalFPT = 6670 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6671 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6672 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6673 } 6674 6675 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6676 CXXRecordDecl *RD = MD->getParent(); 6677 CXXSpecialMember CSM = getSpecialMember(MD); 6678 6679 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6680 "not an explicitly-defaulted special member"); 6681 6682 // Whether this was the first-declared instance of the constructor. 6683 // This affects whether we implicitly add an exception spec and constexpr. 6684 bool First = MD == MD->getCanonicalDecl(); 6685 6686 bool HadError = false; 6687 6688 // C++11 [dcl.fct.def.default]p1: 6689 // A function that is explicitly defaulted shall 6690 // -- be a special member function (checked elsewhere), 6691 // -- have the same type (except for ref-qualifiers, and except that a 6692 // copy operation can take a non-const reference) as an implicit 6693 // declaration, and 6694 // -- not have default arguments. 6695 // C++2a changes the second bullet to instead delete the function if it's 6696 // defaulted on its first declaration, unless it's "an assignment operator, 6697 // and its return type differs or its parameter type is not a reference". 6698 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6699 bool ShouldDeleteForTypeMismatch = false; 6700 unsigned ExpectedParams = 1; 6701 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6702 ExpectedParams = 0; 6703 if (MD->getNumParams() != ExpectedParams) { 6704 // This checks for default arguments: a copy or move constructor with a 6705 // default argument is classified as a default constructor, and assignment 6706 // operations and destructors can't have default arguments. 6707 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6708 << CSM << MD->getSourceRange(); 6709 HadError = true; 6710 } else if (MD->isVariadic()) { 6711 if (DeleteOnTypeMismatch) 6712 ShouldDeleteForTypeMismatch = true; 6713 else { 6714 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6715 << CSM << MD->getSourceRange(); 6716 HadError = true; 6717 } 6718 } 6719 6720 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6721 6722 bool CanHaveConstParam = false; 6723 if (CSM == CXXCopyConstructor) 6724 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6725 else if (CSM == CXXCopyAssignment) 6726 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6727 6728 QualType ReturnType = Context.VoidTy; 6729 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6730 // Check for return type matching. 6731 ReturnType = Type->getReturnType(); 6732 6733 QualType DeclType = Context.getTypeDeclType(RD); 6734 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 6735 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 6736 6737 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6738 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6739 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6740 HadError = true; 6741 } 6742 6743 // A defaulted special member cannot have cv-qualifiers. 6744 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 6745 if (DeleteOnTypeMismatch) 6746 ShouldDeleteForTypeMismatch = true; 6747 else { 6748 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6749 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6750 HadError = true; 6751 } 6752 } 6753 } 6754 6755 // Check for parameter type matching. 6756 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6757 bool HasConstParam = false; 6758 if (ExpectedParams && ArgType->isReferenceType()) { 6759 // Argument must be reference to possibly-const T. 6760 QualType ReferentType = ArgType->getPointeeType(); 6761 HasConstParam = ReferentType.isConstQualified(); 6762 6763 if (ReferentType.isVolatileQualified()) { 6764 if (DeleteOnTypeMismatch) 6765 ShouldDeleteForTypeMismatch = true; 6766 else { 6767 Diag(MD->getLocation(), 6768 diag::err_defaulted_special_member_volatile_param) << CSM; 6769 HadError = true; 6770 } 6771 } 6772 6773 if (HasConstParam && !CanHaveConstParam) { 6774 if (DeleteOnTypeMismatch) 6775 ShouldDeleteForTypeMismatch = true; 6776 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6777 Diag(MD->getLocation(), 6778 diag::err_defaulted_special_member_copy_const_param) 6779 << (CSM == CXXCopyAssignment); 6780 // FIXME: Explain why this special member can't be const. 6781 HadError = true; 6782 } else { 6783 Diag(MD->getLocation(), 6784 diag::err_defaulted_special_member_move_const_param) 6785 << (CSM == CXXMoveAssignment); 6786 HadError = true; 6787 } 6788 } 6789 } else if (ExpectedParams) { 6790 // A copy assignment operator can take its argument by value, but a 6791 // defaulted one cannot. 6792 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6793 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6794 HadError = true; 6795 } 6796 6797 // C++11 [dcl.fct.def.default]p2: 6798 // An explicitly-defaulted function may be declared constexpr only if it 6799 // would have been implicitly declared as constexpr, 6800 // Do not apply this rule to members of class templates, since core issue 1358 6801 // makes such functions always instantiate to constexpr functions. For 6802 // functions which cannot be constexpr (for non-constructors in C++11 and for 6803 // destructors in C++1y), this is checked elsewhere. 6804 // 6805 // FIXME: This should not apply if the member is deleted. 6806 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6807 HasConstParam); 6808 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6809 : isa<CXXConstructorDecl>(MD)) && 6810 MD->isConstexpr() && !Constexpr && 6811 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6812 Diag(MD->getBeginLoc(), MD->isConsteval() 6813 ? diag::err_incorrect_defaulted_consteval 6814 : diag::err_incorrect_defaulted_constexpr) 6815 << CSM; 6816 // FIXME: Explain why the special member can't be constexpr. 6817 HadError = true; 6818 } 6819 6820 if (First) { 6821 // C++2a [dcl.fct.def.default]p3: 6822 // If a function is explicitly defaulted on its first declaration, it is 6823 // implicitly considered to be constexpr if the implicit declaration 6824 // would be. 6825 MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified); 6826 6827 if (!Type->hasExceptionSpec()) { 6828 // C++2a [except.spec]p3: 6829 // If a declaration of a function does not have a noexcept-specifier 6830 // [and] is defaulted on its first declaration, [...] the exception 6831 // specification is as specified below 6832 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6833 EPI.ExceptionSpec.Type = EST_Unevaluated; 6834 EPI.ExceptionSpec.SourceDecl = MD; 6835 MD->setType(Context.getFunctionType(ReturnType, 6836 llvm::makeArrayRef(&ArgType, 6837 ExpectedParams), 6838 EPI)); 6839 } 6840 } 6841 6842 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 6843 if (First) { 6844 SetDeclDeleted(MD, MD->getLocation()); 6845 if (!inTemplateInstantiation() && !HadError) { 6846 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 6847 if (ShouldDeleteForTypeMismatch) { 6848 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 6849 } else { 6850 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6851 } 6852 } 6853 if (ShouldDeleteForTypeMismatch && !HadError) { 6854 Diag(MD->getLocation(), 6855 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 6856 } 6857 } else { 6858 // C++11 [dcl.fct.def.default]p4: 6859 // [For a] user-provided explicitly-defaulted function [...] if such a 6860 // function is implicitly defined as deleted, the program is ill-formed. 6861 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6862 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 6863 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6864 HadError = true; 6865 } 6866 } 6867 6868 if (HadError) 6869 MD->setInvalidDecl(); 6870 } 6871 6872 void Sema::CheckDelayedMemberExceptionSpecs() { 6873 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 6874 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 6875 6876 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 6877 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 6878 6879 // Perform any deferred checking of exception specifications for virtual 6880 // destructors. 6881 for (auto &Check : Overriding) 6882 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6883 6884 // Perform any deferred checking of exception specifications for befriended 6885 // special members. 6886 for (auto &Check : Equivalent) 6887 CheckEquivalentExceptionSpec(Check.second, Check.first); 6888 } 6889 6890 namespace { 6891 /// CRTP base class for visiting operations performed by a special member 6892 /// function (or inherited constructor). 6893 template<typename Derived> 6894 struct SpecialMemberVisitor { 6895 Sema &S; 6896 CXXMethodDecl *MD; 6897 Sema::CXXSpecialMember CSM; 6898 Sema::InheritedConstructorInfo *ICI; 6899 6900 // Properties of the special member, computed for convenience. 6901 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6902 6903 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6904 Sema::InheritedConstructorInfo *ICI) 6905 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6906 switch (CSM) { 6907 case Sema::CXXDefaultConstructor: 6908 case Sema::CXXCopyConstructor: 6909 case Sema::CXXMoveConstructor: 6910 IsConstructor = true; 6911 break; 6912 case Sema::CXXCopyAssignment: 6913 case Sema::CXXMoveAssignment: 6914 IsAssignment = true; 6915 break; 6916 case Sema::CXXDestructor: 6917 break; 6918 case Sema::CXXInvalid: 6919 llvm_unreachable("invalid special member kind"); 6920 } 6921 6922 if (MD->getNumParams()) { 6923 if (const ReferenceType *RT = 6924 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6925 ConstArg = RT->getPointeeType().isConstQualified(); 6926 } 6927 } 6928 6929 Derived &getDerived() { return static_cast<Derived&>(*this); } 6930 6931 /// Is this a "move" special member? 6932 bool isMove() const { 6933 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6934 } 6935 6936 /// Look up the corresponding special member in the given class. 6937 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6938 unsigned Quals, bool IsMutable) { 6939 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6940 ConstArg && !IsMutable); 6941 } 6942 6943 /// Look up the constructor for the specified base class to see if it's 6944 /// overridden due to this being an inherited constructor. 6945 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6946 if (!ICI) 6947 return {}; 6948 assert(CSM == Sema::CXXDefaultConstructor); 6949 auto *BaseCtor = 6950 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6951 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6952 return MD; 6953 return {}; 6954 } 6955 6956 /// A base or member subobject. 6957 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6958 6959 /// Get the location to use for a subobject in diagnostics. 6960 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6961 // FIXME: For an indirect virtual base, the direct base leading to 6962 // the indirect virtual base would be a more useful choice. 6963 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6964 return B->getBaseTypeLoc(); 6965 else 6966 return Subobj.get<FieldDecl*>()->getLocation(); 6967 } 6968 6969 enum BasesToVisit { 6970 /// Visit all non-virtual (direct) bases. 6971 VisitNonVirtualBases, 6972 /// Visit all direct bases, virtual or not. 6973 VisitDirectBases, 6974 /// Visit all non-virtual bases, and all virtual bases if the class 6975 /// is not abstract. 6976 VisitPotentiallyConstructedBases, 6977 /// Visit all direct or virtual bases. 6978 VisitAllBases 6979 }; 6980 6981 // Visit the bases and members of the class. 6982 bool visit(BasesToVisit Bases) { 6983 CXXRecordDecl *RD = MD->getParent(); 6984 6985 if (Bases == VisitPotentiallyConstructedBases) 6986 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6987 6988 for (auto &B : RD->bases()) 6989 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6990 getDerived().visitBase(&B)) 6991 return true; 6992 6993 if (Bases == VisitAllBases) 6994 for (auto &B : RD->vbases()) 6995 if (getDerived().visitBase(&B)) 6996 return true; 6997 6998 for (auto *F : RD->fields()) 6999 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 7000 getDerived().visitField(F)) 7001 return true; 7002 7003 return false; 7004 } 7005 }; 7006 } 7007 7008 namespace { 7009 struct SpecialMemberDeletionInfo 7010 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 7011 bool Diagnose; 7012 7013 SourceLocation Loc; 7014 7015 bool AllFieldsAreConst; 7016 7017 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 7018 Sema::CXXSpecialMember CSM, 7019 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 7020 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 7021 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 7022 7023 bool inUnion() const { return MD->getParent()->isUnion(); } 7024 7025 Sema::CXXSpecialMember getEffectiveCSM() { 7026 return ICI ? Sema::CXXInvalid : CSM; 7027 } 7028 7029 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 7030 7031 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 7032 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 7033 7034 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 7035 bool shouldDeleteForField(FieldDecl *FD); 7036 bool shouldDeleteForAllConstMembers(); 7037 7038 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 7039 unsigned Quals); 7040 bool shouldDeleteForSubobjectCall(Subobject Subobj, 7041 Sema::SpecialMemberOverloadResult SMOR, 7042 bool IsDtorCallInCtor); 7043 7044 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 7045 }; 7046 } 7047 7048 /// Is the given special member inaccessible when used on the given 7049 /// sub-object. 7050 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 7051 CXXMethodDecl *target) { 7052 /// If we're operating on a base class, the object type is the 7053 /// type of this special member. 7054 QualType objectTy; 7055 AccessSpecifier access = target->getAccess(); 7056 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 7057 objectTy = S.Context.getTypeDeclType(MD->getParent()); 7058 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 7059 7060 // If we're operating on a field, the object type is the type of the field. 7061 } else { 7062 objectTy = S.Context.getTypeDeclType(target->getParent()); 7063 } 7064 7065 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 7066 } 7067 7068 /// Check whether we should delete a special member due to the implicit 7069 /// definition containing a call to a special member of a subobject. 7070 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 7071 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 7072 bool IsDtorCallInCtor) { 7073 CXXMethodDecl *Decl = SMOR.getMethod(); 7074 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 7075 7076 int DiagKind = -1; 7077 7078 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 7079 DiagKind = !Decl ? 0 : 1; 7080 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7081 DiagKind = 2; 7082 else if (!isAccessible(Subobj, Decl)) 7083 DiagKind = 3; 7084 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 7085 !Decl->isTrivial()) { 7086 // A member of a union must have a trivial corresponding special member. 7087 // As a weird special case, a destructor call from a union's constructor 7088 // must be accessible and non-deleted, but need not be trivial. Such a 7089 // destructor is never actually called, but is semantically checked as 7090 // if it were. 7091 DiagKind = 4; 7092 } 7093 7094 if (DiagKind == -1) 7095 return false; 7096 7097 if (Diagnose) { 7098 if (Field) { 7099 S.Diag(Field->getLocation(), 7100 diag::note_deleted_special_member_class_subobject) 7101 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 7102 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 7103 } else { 7104 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 7105 S.Diag(Base->getBeginLoc(), 7106 diag::note_deleted_special_member_class_subobject) 7107 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7108 << Base->getType() << DiagKind << IsDtorCallInCtor 7109 << /*IsObjCPtr*/false; 7110 } 7111 7112 if (DiagKind == 1) 7113 S.NoteDeletedFunction(Decl); 7114 // FIXME: Explain inaccessibility if DiagKind == 3. 7115 } 7116 7117 return true; 7118 } 7119 7120 /// Check whether we should delete a special member function due to having a 7121 /// direct or virtual base class or non-static data member of class type M. 7122 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 7123 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 7124 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 7125 bool IsMutable = Field && Field->isMutable(); 7126 7127 // C++11 [class.ctor]p5: 7128 // -- any direct or virtual base class, or non-static data member with no 7129 // brace-or-equal-initializer, has class type M (or array thereof) and 7130 // either M has no default constructor or overload resolution as applied 7131 // to M's default constructor results in an ambiguity or in a function 7132 // that is deleted or inaccessible 7133 // C++11 [class.copy]p11, C++11 [class.copy]p23: 7134 // -- a direct or virtual base class B that cannot be copied/moved because 7135 // overload resolution, as applied to B's corresponding special member, 7136 // results in an ambiguity or a function that is deleted or inaccessible 7137 // from the defaulted special member 7138 // C++11 [class.dtor]p5: 7139 // -- any direct or virtual base class [...] has a type with a destructor 7140 // that is deleted or inaccessible 7141 if (!(CSM == Sema::CXXDefaultConstructor && 7142 Field && Field->hasInClassInitializer()) && 7143 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 7144 false)) 7145 return true; 7146 7147 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 7148 // -- any direct or virtual base class or non-static data member has a 7149 // type with a destructor that is deleted or inaccessible 7150 if (IsConstructor) { 7151 Sema::SpecialMemberOverloadResult SMOR = 7152 S.LookupSpecialMember(Class, Sema::CXXDestructor, 7153 false, false, false, false, false); 7154 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 7155 return true; 7156 } 7157 7158 return false; 7159 } 7160 7161 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 7162 FieldDecl *FD, QualType FieldType) { 7163 // The defaulted special functions are defined as deleted if this is a variant 7164 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 7165 // type under ARC. 7166 if (!FieldType.hasNonTrivialObjCLifetime()) 7167 return false; 7168 7169 // Don't make the defaulted default constructor defined as deleted if the 7170 // member has an in-class initializer. 7171 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 7172 return false; 7173 7174 if (Diagnose) { 7175 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 7176 S.Diag(FD->getLocation(), 7177 diag::note_deleted_special_member_class_subobject) 7178 << getEffectiveCSM() << ParentClass << /*IsField*/true 7179 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 7180 } 7181 7182 return true; 7183 } 7184 7185 /// Check whether we should delete a special member function due to the class 7186 /// having a particular direct or virtual base class. 7187 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 7188 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 7189 // If program is correct, BaseClass cannot be null, but if it is, the error 7190 // must be reported elsewhere. 7191 if (!BaseClass) 7192 return false; 7193 // If we have an inheriting constructor, check whether we're calling an 7194 // inherited constructor instead of a default constructor. 7195 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 7196 if (auto *BaseCtor = SMOR.getMethod()) { 7197 // Note that we do not check access along this path; other than that, 7198 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 7199 // FIXME: Check that the base has a usable destructor! Sink this into 7200 // shouldDeleteForClassSubobject. 7201 if (BaseCtor->isDeleted() && Diagnose) { 7202 S.Diag(Base->getBeginLoc(), 7203 diag::note_deleted_special_member_class_subobject) 7204 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7205 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 7206 << /*IsObjCPtr*/false; 7207 S.NoteDeletedFunction(BaseCtor); 7208 } 7209 return BaseCtor->isDeleted(); 7210 } 7211 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 7212 } 7213 7214 /// Check whether we should delete a special member function due to the class 7215 /// having a particular non-static data member. 7216 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 7217 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 7218 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 7219 7220 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 7221 return true; 7222 7223 if (CSM == Sema::CXXDefaultConstructor) { 7224 // For a default constructor, all references must be initialized in-class 7225 // and, if a union, it must have a non-const member. 7226 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 7227 if (Diagnose) 7228 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7229 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 7230 return true; 7231 } 7232 // C++11 [class.ctor]p5: any non-variant non-static data member of 7233 // const-qualified type (or array thereof) with no 7234 // brace-or-equal-initializer does not have a user-provided default 7235 // constructor. 7236 if (!inUnion() && FieldType.isConstQualified() && 7237 !FD->hasInClassInitializer() && 7238 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 7239 if (Diagnose) 7240 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7241 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 7242 return true; 7243 } 7244 7245 if (inUnion() && !FieldType.isConstQualified()) 7246 AllFieldsAreConst = false; 7247 } else if (CSM == Sema::CXXCopyConstructor) { 7248 // For a copy constructor, data members must not be of rvalue reference 7249 // type. 7250 if (FieldType->isRValueReferenceType()) { 7251 if (Diagnose) 7252 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 7253 << MD->getParent() << FD << FieldType; 7254 return true; 7255 } 7256 } else if (IsAssignment) { 7257 // For an assignment operator, data members must not be of reference type. 7258 if (FieldType->isReferenceType()) { 7259 if (Diagnose) 7260 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7261 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 7262 return true; 7263 } 7264 if (!FieldRecord && FieldType.isConstQualified()) { 7265 // C++11 [class.copy]p23: 7266 // -- a non-static data member of const non-class type (or array thereof) 7267 if (Diagnose) 7268 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7269 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 7270 return true; 7271 } 7272 } 7273 7274 if (FieldRecord) { 7275 // Some additional restrictions exist on the variant members. 7276 if (!inUnion() && FieldRecord->isUnion() && 7277 FieldRecord->isAnonymousStructOrUnion()) { 7278 bool AllVariantFieldsAreConst = true; 7279 7280 // FIXME: Handle anonymous unions declared within anonymous unions. 7281 for (auto *UI : FieldRecord->fields()) { 7282 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7283 7284 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 7285 return true; 7286 7287 if (!UnionFieldType.isConstQualified()) 7288 AllVariantFieldsAreConst = false; 7289 7290 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7291 if (UnionFieldRecord && 7292 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7293 UnionFieldType.getCVRQualifiers())) 7294 return true; 7295 } 7296 7297 // At least one member in each anonymous union must be non-const 7298 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7299 !FieldRecord->field_empty()) { 7300 if (Diagnose) 7301 S.Diag(FieldRecord->getLocation(), 7302 diag::note_deleted_default_ctor_all_const) 7303 << !!ICI << MD->getParent() << /*anonymous union*/1; 7304 return true; 7305 } 7306 7307 // Don't check the implicit member of the anonymous union type. 7308 // This is technically non-conformant, but sanity demands it. 7309 return false; 7310 } 7311 7312 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7313 FieldType.getCVRQualifiers())) 7314 return true; 7315 } 7316 7317 return false; 7318 } 7319 7320 /// C++11 [class.ctor] p5: 7321 /// A defaulted default constructor for a class X is defined as deleted if 7322 /// X is a union and all of its variant members are of const-qualified type. 7323 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7324 // This is a silly definition, because it gives an empty union a deleted 7325 // default constructor. Don't do that. 7326 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7327 bool AnyFields = false; 7328 for (auto *F : MD->getParent()->fields()) 7329 if ((AnyFields = !F->isUnnamedBitfield())) 7330 break; 7331 if (!AnyFields) 7332 return false; 7333 if (Diagnose) 7334 S.Diag(MD->getParent()->getLocation(), 7335 diag::note_deleted_default_ctor_all_const) 7336 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7337 return true; 7338 } 7339 return false; 7340 } 7341 7342 /// Determine whether a defaulted special member function should be defined as 7343 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7344 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7345 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7346 InheritedConstructorInfo *ICI, 7347 bool Diagnose) { 7348 if (MD->isInvalidDecl()) 7349 return false; 7350 CXXRecordDecl *RD = MD->getParent(); 7351 assert(!RD->isDependentType() && "do deletion after instantiation"); 7352 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7353 return false; 7354 7355 // C++11 [expr.lambda.prim]p19: 7356 // The closure type associated with a lambda-expression has a 7357 // deleted (8.4.3) default constructor and a deleted copy 7358 // assignment operator. 7359 // C++2a adds back these operators if the lambda has no lambda-capture. 7360 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 7361 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7362 if (Diagnose) 7363 Diag(RD->getLocation(), diag::note_lambda_decl); 7364 return true; 7365 } 7366 7367 // For an anonymous struct or union, the copy and assignment special members 7368 // will never be used, so skip the check. For an anonymous union declared at 7369 // namespace scope, the constructor and destructor are used. 7370 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7371 RD->isAnonymousStructOrUnion()) 7372 return false; 7373 7374 // C++11 [class.copy]p7, p18: 7375 // If the class definition declares a move constructor or move assignment 7376 // operator, an implicitly declared copy constructor or copy assignment 7377 // operator is defined as deleted. 7378 if (MD->isImplicit() && 7379 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7380 CXXMethodDecl *UserDeclaredMove = nullptr; 7381 7382 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7383 // deletion of the corresponding copy operation, not both copy operations. 7384 // MSVC 2015 has adopted the standards conforming behavior. 7385 bool DeletesOnlyMatchingCopy = 7386 getLangOpts().MSVCCompat && 7387 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7388 7389 if (RD->hasUserDeclaredMoveConstructor() && 7390 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7391 if (!Diagnose) return true; 7392 7393 // Find any user-declared move constructor. 7394 for (auto *I : RD->ctors()) { 7395 if (I->isMoveConstructor()) { 7396 UserDeclaredMove = I; 7397 break; 7398 } 7399 } 7400 assert(UserDeclaredMove); 7401 } else if (RD->hasUserDeclaredMoveAssignment() && 7402 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7403 if (!Diagnose) return true; 7404 7405 // Find any user-declared move assignment operator. 7406 for (auto *I : RD->methods()) { 7407 if (I->isMoveAssignmentOperator()) { 7408 UserDeclaredMove = I; 7409 break; 7410 } 7411 } 7412 assert(UserDeclaredMove); 7413 } 7414 7415 if (UserDeclaredMove) { 7416 Diag(UserDeclaredMove->getLocation(), 7417 diag::note_deleted_copy_user_declared_move) 7418 << (CSM == CXXCopyAssignment) << RD 7419 << UserDeclaredMove->isMoveAssignmentOperator(); 7420 return true; 7421 } 7422 } 7423 7424 // Do access control from the special member function 7425 ContextRAII MethodContext(*this, MD); 7426 7427 // C++11 [class.dtor]p5: 7428 // -- for a virtual destructor, lookup of the non-array deallocation function 7429 // results in an ambiguity or in a function that is deleted or inaccessible 7430 if (CSM == CXXDestructor && MD->isVirtual()) { 7431 FunctionDecl *OperatorDelete = nullptr; 7432 DeclarationName Name = 7433 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7434 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7435 OperatorDelete, /*Diagnose*/false)) { 7436 if (Diagnose) 7437 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7438 return true; 7439 } 7440 } 7441 7442 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7443 7444 // Per DR1611, do not consider virtual bases of constructors of abstract 7445 // classes, since we are not going to construct them. 7446 // Per DR1658, do not consider virtual bases of destructors of abstract 7447 // classes either. 7448 // Per DR2180, for assignment operators we only assign (and thus only 7449 // consider) direct bases. 7450 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7451 : SMI.VisitPotentiallyConstructedBases)) 7452 return true; 7453 7454 if (SMI.shouldDeleteForAllConstMembers()) 7455 return true; 7456 7457 if (getLangOpts().CUDA) { 7458 // We should delete the special member in CUDA mode if target inference 7459 // failed. 7460 // For inherited constructors (non-null ICI), CSM may be passed so that MD 7461 // is treated as certain special member, which may not reflect what special 7462 // member MD really is. However inferCUDATargetForImplicitSpecialMember 7463 // expects CSM to match MD, therefore recalculate CSM. 7464 assert(ICI || CSM == getSpecialMember(MD)); 7465 auto RealCSM = CSM; 7466 if (ICI) 7467 RealCSM = getSpecialMember(MD); 7468 7469 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 7470 SMI.ConstArg, Diagnose); 7471 } 7472 7473 return false; 7474 } 7475 7476 /// Perform lookup for a special member of the specified kind, and determine 7477 /// whether it is trivial. If the triviality can be determined without the 7478 /// lookup, skip it. This is intended for use when determining whether a 7479 /// special member of a containing object is trivial, and thus does not ever 7480 /// perform overload resolution for default constructors. 7481 /// 7482 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7483 /// member that was most likely to be intended to be trivial, if any. 7484 /// 7485 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7486 /// determine whether the special member is trivial. 7487 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7488 Sema::CXXSpecialMember CSM, unsigned Quals, 7489 bool ConstRHS, 7490 Sema::TrivialABIHandling TAH, 7491 CXXMethodDecl **Selected) { 7492 if (Selected) 7493 *Selected = nullptr; 7494 7495 switch (CSM) { 7496 case Sema::CXXInvalid: 7497 llvm_unreachable("not a special member"); 7498 7499 case Sema::CXXDefaultConstructor: 7500 // C++11 [class.ctor]p5: 7501 // A default constructor is trivial if: 7502 // - all the [direct subobjects] have trivial default constructors 7503 // 7504 // Note, no overload resolution is performed in this case. 7505 if (RD->hasTrivialDefaultConstructor()) 7506 return true; 7507 7508 if (Selected) { 7509 // If there's a default constructor which could have been trivial, dig it 7510 // out. Otherwise, if there's any user-provided default constructor, point 7511 // to that as an example of why there's not a trivial one. 7512 CXXConstructorDecl *DefCtor = nullptr; 7513 if (RD->needsImplicitDefaultConstructor()) 7514 S.DeclareImplicitDefaultConstructor(RD); 7515 for (auto *CI : RD->ctors()) { 7516 if (!CI->isDefaultConstructor()) 7517 continue; 7518 DefCtor = CI; 7519 if (!DefCtor->isUserProvided()) 7520 break; 7521 } 7522 7523 *Selected = DefCtor; 7524 } 7525 7526 return false; 7527 7528 case Sema::CXXDestructor: 7529 // C++11 [class.dtor]p5: 7530 // A destructor is trivial if: 7531 // - all the direct [subobjects] have trivial destructors 7532 if (RD->hasTrivialDestructor() || 7533 (TAH == Sema::TAH_ConsiderTrivialABI && 7534 RD->hasTrivialDestructorForCall())) 7535 return true; 7536 7537 if (Selected) { 7538 if (RD->needsImplicitDestructor()) 7539 S.DeclareImplicitDestructor(RD); 7540 *Selected = RD->getDestructor(); 7541 } 7542 7543 return false; 7544 7545 case Sema::CXXCopyConstructor: 7546 // C++11 [class.copy]p12: 7547 // A copy constructor is trivial if: 7548 // - the constructor selected to copy each direct [subobject] is trivial 7549 if (RD->hasTrivialCopyConstructor() || 7550 (TAH == Sema::TAH_ConsiderTrivialABI && 7551 RD->hasTrivialCopyConstructorForCall())) { 7552 if (Quals == Qualifiers::Const) 7553 // We must either select the trivial copy constructor or reach an 7554 // ambiguity; no need to actually perform overload resolution. 7555 return true; 7556 } else if (!Selected) { 7557 return false; 7558 } 7559 // In C++98, we are not supposed to perform overload resolution here, but we 7560 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7561 // cases like B as having a non-trivial copy constructor: 7562 // struct A { template<typename T> A(T&); }; 7563 // struct B { mutable A a; }; 7564 goto NeedOverloadResolution; 7565 7566 case Sema::CXXCopyAssignment: 7567 // C++11 [class.copy]p25: 7568 // A copy assignment operator is trivial if: 7569 // - the assignment operator selected to copy each direct [subobject] is 7570 // trivial 7571 if (RD->hasTrivialCopyAssignment()) { 7572 if (Quals == Qualifiers::Const) 7573 return true; 7574 } else if (!Selected) { 7575 return false; 7576 } 7577 // In C++98, we are not supposed to perform overload resolution here, but we 7578 // treat that as a language defect. 7579 goto NeedOverloadResolution; 7580 7581 case Sema::CXXMoveConstructor: 7582 case Sema::CXXMoveAssignment: 7583 NeedOverloadResolution: 7584 Sema::SpecialMemberOverloadResult SMOR = 7585 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7586 7587 // The standard doesn't describe how to behave if the lookup is ambiguous. 7588 // We treat it as not making the member non-trivial, just like the standard 7589 // mandates for the default constructor. This should rarely matter, because 7590 // the member will also be deleted. 7591 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7592 return true; 7593 7594 if (!SMOR.getMethod()) { 7595 assert(SMOR.getKind() == 7596 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7597 return false; 7598 } 7599 7600 // We deliberately don't check if we found a deleted special member. We're 7601 // not supposed to! 7602 if (Selected) 7603 *Selected = SMOR.getMethod(); 7604 7605 if (TAH == Sema::TAH_ConsiderTrivialABI && 7606 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7607 return SMOR.getMethod()->isTrivialForCall(); 7608 return SMOR.getMethod()->isTrivial(); 7609 } 7610 7611 llvm_unreachable("unknown special method kind"); 7612 } 7613 7614 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7615 for (auto *CI : RD->ctors()) 7616 if (!CI->isImplicit()) 7617 return CI; 7618 7619 // Look for constructor templates. 7620 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7621 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7622 if (CXXConstructorDecl *CD = 7623 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7624 return CD; 7625 } 7626 7627 return nullptr; 7628 } 7629 7630 /// The kind of subobject we are checking for triviality. The values of this 7631 /// enumeration are used in diagnostics. 7632 enum TrivialSubobjectKind { 7633 /// The subobject is a base class. 7634 TSK_BaseClass, 7635 /// The subobject is a non-static data member. 7636 TSK_Field, 7637 /// The object is actually the complete object. 7638 TSK_CompleteObject 7639 }; 7640 7641 /// Check whether the special member selected for a given type would be trivial. 7642 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7643 QualType SubType, bool ConstRHS, 7644 Sema::CXXSpecialMember CSM, 7645 TrivialSubobjectKind Kind, 7646 Sema::TrivialABIHandling TAH, bool Diagnose) { 7647 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7648 if (!SubRD) 7649 return true; 7650 7651 CXXMethodDecl *Selected; 7652 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7653 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7654 return true; 7655 7656 if (Diagnose) { 7657 if (ConstRHS) 7658 SubType.addConst(); 7659 7660 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7661 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7662 << Kind << SubType.getUnqualifiedType(); 7663 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7664 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7665 } else if (!Selected) 7666 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7667 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7668 else if (Selected->isUserProvided()) { 7669 if (Kind == TSK_CompleteObject) 7670 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7671 << Kind << SubType.getUnqualifiedType() << CSM; 7672 else { 7673 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7674 << Kind << SubType.getUnqualifiedType() << CSM; 7675 S.Diag(Selected->getLocation(), diag::note_declared_at); 7676 } 7677 } else { 7678 if (Kind != TSK_CompleteObject) 7679 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7680 << Kind << SubType.getUnqualifiedType() << CSM; 7681 7682 // Explain why the defaulted or deleted special member isn't trivial. 7683 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7684 Diagnose); 7685 } 7686 } 7687 7688 return false; 7689 } 7690 7691 /// Check whether the members of a class type allow a special member to be 7692 /// trivial. 7693 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7694 Sema::CXXSpecialMember CSM, 7695 bool ConstArg, 7696 Sema::TrivialABIHandling TAH, 7697 bool Diagnose) { 7698 for (const auto *FI : RD->fields()) { 7699 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7700 continue; 7701 7702 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7703 7704 // Pretend anonymous struct or union members are members of this class. 7705 if (FI->isAnonymousStructOrUnion()) { 7706 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7707 CSM, ConstArg, TAH, Diagnose)) 7708 return false; 7709 continue; 7710 } 7711 7712 // C++11 [class.ctor]p5: 7713 // A default constructor is trivial if [...] 7714 // -- no non-static data member of its class has a 7715 // brace-or-equal-initializer 7716 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7717 if (Diagnose) 7718 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7719 return false; 7720 } 7721 7722 // Objective C ARC 4.3.5: 7723 // [...] nontrivally ownership-qualified types are [...] not trivially 7724 // default constructible, copy constructible, move constructible, copy 7725 // assignable, move assignable, or destructible [...] 7726 if (FieldType.hasNonTrivialObjCLifetime()) { 7727 if (Diagnose) 7728 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7729 << RD << FieldType.getObjCLifetime(); 7730 return false; 7731 } 7732 7733 bool ConstRHS = ConstArg && !FI->isMutable(); 7734 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7735 CSM, TSK_Field, TAH, Diagnose)) 7736 return false; 7737 } 7738 7739 return true; 7740 } 7741 7742 /// Diagnose why the specified class does not have a trivial special member of 7743 /// the given kind. 7744 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7745 QualType Ty = Context.getRecordType(RD); 7746 7747 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7748 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7749 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7750 /*Diagnose*/true); 7751 } 7752 7753 /// Determine whether a defaulted or deleted special member function is trivial, 7754 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7755 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7756 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7757 TrivialABIHandling TAH, bool Diagnose) { 7758 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7759 7760 CXXRecordDecl *RD = MD->getParent(); 7761 7762 bool ConstArg = false; 7763 7764 // C++11 [class.copy]p12, p25: [DR1593] 7765 // A [special member] is trivial if [...] its parameter-type-list is 7766 // equivalent to the parameter-type-list of an implicit declaration [...] 7767 switch (CSM) { 7768 case CXXDefaultConstructor: 7769 case CXXDestructor: 7770 // Trivial default constructors and destructors cannot have parameters. 7771 break; 7772 7773 case CXXCopyConstructor: 7774 case CXXCopyAssignment: { 7775 // Trivial copy operations always have const, non-volatile parameter types. 7776 ConstArg = true; 7777 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7778 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7779 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7780 if (Diagnose) 7781 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7782 << Param0->getSourceRange() << Param0->getType() 7783 << Context.getLValueReferenceType( 7784 Context.getRecordType(RD).withConst()); 7785 return false; 7786 } 7787 break; 7788 } 7789 7790 case CXXMoveConstructor: 7791 case CXXMoveAssignment: { 7792 // Trivial move operations always have non-cv-qualified parameters. 7793 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7794 const RValueReferenceType *RT = 7795 Param0->getType()->getAs<RValueReferenceType>(); 7796 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7797 if (Diagnose) 7798 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7799 << Param0->getSourceRange() << Param0->getType() 7800 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7801 return false; 7802 } 7803 break; 7804 } 7805 7806 case CXXInvalid: 7807 llvm_unreachable("not a special member"); 7808 } 7809 7810 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7811 if (Diagnose) 7812 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7813 diag::note_nontrivial_default_arg) 7814 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7815 return false; 7816 } 7817 if (MD->isVariadic()) { 7818 if (Diagnose) 7819 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7820 return false; 7821 } 7822 7823 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7824 // A copy/move [constructor or assignment operator] is trivial if 7825 // -- the [member] selected to copy/move each direct base class subobject 7826 // is trivial 7827 // 7828 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7829 // A [default constructor or destructor] is trivial if 7830 // -- all the direct base classes have trivial [default constructors or 7831 // destructors] 7832 for (const auto &BI : RD->bases()) 7833 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 7834 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7835 return false; 7836 7837 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7838 // A copy/move [constructor or assignment operator] for a class X is 7839 // trivial if 7840 // -- for each non-static data member of X that is of class type (or array 7841 // thereof), the constructor selected to copy/move that member is 7842 // trivial 7843 // 7844 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7845 // A [default constructor or destructor] is trivial if 7846 // -- for all of the non-static data members of its class that are of class 7847 // type (or array thereof), each such class has a trivial [default 7848 // constructor or destructor] 7849 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7850 return false; 7851 7852 // C++11 [class.dtor]p5: 7853 // A destructor is trivial if [...] 7854 // -- the destructor is not virtual 7855 if (CSM == CXXDestructor && MD->isVirtual()) { 7856 if (Diagnose) 7857 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7858 return false; 7859 } 7860 7861 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7862 // A [special member] for class X is trivial if [...] 7863 // -- class X has no virtual functions and no virtual base classes 7864 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7865 if (!Diagnose) 7866 return false; 7867 7868 if (RD->getNumVBases()) { 7869 // Check for virtual bases. We already know that the corresponding 7870 // member in all bases is trivial, so vbases must all be direct. 7871 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7872 assert(BS.isVirtual()); 7873 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 7874 return false; 7875 } 7876 7877 // Must have a virtual method. 7878 for (const auto *MI : RD->methods()) { 7879 if (MI->isVirtual()) { 7880 SourceLocation MLoc = MI->getBeginLoc(); 7881 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7882 return false; 7883 } 7884 } 7885 7886 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7887 } 7888 7889 // Looks like it's trivial! 7890 return true; 7891 } 7892 7893 namespace { 7894 struct FindHiddenVirtualMethod { 7895 Sema *S; 7896 CXXMethodDecl *Method; 7897 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7898 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7899 7900 private: 7901 /// Check whether any most overridden method from MD in Methods 7902 static bool CheckMostOverridenMethods( 7903 const CXXMethodDecl *MD, 7904 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7905 if (MD->size_overridden_methods() == 0) 7906 return Methods.count(MD->getCanonicalDecl()); 7907 for (const CXXMethodDecl *O : MD->overridden_methods()) 7908 if (CheckMostOverridenMethods(O, Methods)) 7909 return true; 7910 return false; 7911 } 7912 7913 public: 7914 /// Member lookup function that determines whether a given C++ 7915 /// method overloads virtual methods in a base class without overriding any, 7916 /// to be used with CXXRecordDecl::lookupInBases(). 7917 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7918 RecordDecl *BaseRecord = 7919 Specifier->getType()->getAs<RecordType>()->getDecl(); 7920 7921 DeclarationName Name = Method->getDeclName(); 7922 assert(Name.getNameKind() == DeclarationName::Identifier); 7923 7924 bool foundSameNameMethod = false; 7925 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7926 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7927 Path.Decls = Path.Decls.slice(1)) { 7928 NamedDecl *D = Path.Decls.front(); 7929 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7930 MD = MD->getCanonicalDecl(); 7931 foundSameNameMethod = true; 7932 // Interested only in hidden virtual methods. 7933 if (!MD->isVirtual()) 7934 continue; 7935 // If the method we are checking overrides a method from its base 7936 // don't warn about the other overloaded methods. Clang deviates from 7937 // GCC by only diagnosing overloads of inherited virtual functions that 7938 // do not override any other virtual functions in the base. GCC's 7939 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7940 // function from a base class. These cases may be better served by a 7941 // warning (not specific to virtual functions) on call sites when the 7942 // call would select a different function from the base class, were it 7943 // visible. 7944 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7945 if (!S->IsOverload(Method, MD, false)) 7946 return true; 7947 // Collect the overload only if its hidden. 7948 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7949 overloadedMethods.push_back(MD); 7950 } 7951 } 7952 7953 if (foundSameNameMethod) 7954 OverloadedMethods.append(overloadedMethods.begin(), 7955 overloadedMethods.end()); 7956 return foundSameNameMethod; 7957 } 7958 }; 7959 } // end anonymous namespace 7960 7961 /// Add the most overriden methods from MD to Methods 7962 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7963 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7964 if (MD->size_overridden_methods() == 0) 7965 Methods.insert(MD->getCanonicalDecl()); 7966 else 7967 for (const CXXMethodDecl *O : MD->overridden_methods()) 7968 AddMostOverridenMethods(O, Methods); 7969 } 7970 7971 /// Check if a method overloads virtual methods in a base class without 7972 /// overriding any. 7973 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7974 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7975 if (!MD->getDeclName().isIdentifier()) 7976 return; 7977 7978 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7979 /*bool RecordPaths=*/false, 7980 /*bool DetectVirtual=*/false); 7981 FindHiddenVirtualMethod FHVM; 7982 FHVM.Method = MD; 7983 FHVM.S = this; 7984 7985 // Keep the base methods that were overridden or introduced in the subclass 7986 // by 'using' in a set. A base method not in this set is hidden. 7987 CXXRecordDecl *DC = MD->getParent(); 7988 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7989 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7990 NamedDecl *ND = *I; 7991 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7992 ND = shad->getTargetDecl(); 7993 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7994 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7995 } 7996 7997 if (DC->lookupInBases(FHVM, Paths)) 7998 OverloadedMethods = FHVM.OverloadedMethods; 7999 } 8000 8001 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 8002 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 8003 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 8004 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 8005 PartialDiagnostic PD = PDiag( 8006 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 8007 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 8008 Diag(overloadedMD->getLocation(), PD); 8009 } 8010 } 8011 8012 /// Diagnose methods which overload virtual methods in a base class 8013 /// without overriding any. 8014 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 8015 if (MD->isInvalidDecl()) 8016 return; 8017 8018 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 8019 return; 8020 8021 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 8022 FindHiddenVirtualMethods(MD, OverloadedMethods); 8023 if (!OverloadedMethods.empty()) { 8024 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 8025 << MD << (OverloadedMethods.size() > 1); 8026 8027 NoteHiddenVirtualMethods(MD, OverloadedMethods); 8028 } 8029 } 8030 8031 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 8032 auto PrintDiagAndRemoveAttr = [&]() { 8033 // No diagnostics if this is a template instantiation. 8034 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 8035 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 8036 diag::ext_cannot_use_trivial_abi) << &RD; 8037 RD.dropAttr<TrivialABIAttr>(); 8038 }; 8039 8040 // Ill-formed if the struct has virtual functions. 8041 if (RD.isPolymorphic()) { 8042 PrintDiagAndRemoveAttr(); 8043 return; 8044 } 8045 8046 for (const auto &B : RD.bases()) { 8047 // Ill-formed if the base class is non-trivial for the purpose of calls or a 8048 // virtual base. 8049 if ((!B.getType()->isDependentType() && 8050 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 8051 B.isVirtual()) { 8052 PrintDiagAndRemoveAttr(); 8053 return; 8054 } 8055 } 8056 8057 for (const auto *FD : RD.fields()) { 8058 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 8059 // non-trivial for the purpose of calls. 8060 QualType FT = FD->getType(); 8061 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 8062 PrintDiagAndRemoveAttr(); 8063 return; 8064 } 8065 8066 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 8067 if (!RT->isDependentType() && 8068 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 8069 PrintDiagAndRemoveAttr(); 8070 return; 8071 } 8072 } 8073 } 8074 8075 void Sema::ActOnFinishCXXMemberSpecification( 8076 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 8077 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 8078 if (!TagDecl) 8079 return; 8080 8081 AdjustDeclIfTemplate(TagDecl); 8082 8083 for (const ParsedAttr &AL : AttrList) { 8084 if (AL.getKind() != ParsedAttr::AT_Visibility) 8085 continue; 8086 AL.setInvalid(); 8087 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) 8088 << AL.getName(); 8089 } 8090 8091 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 8092 // strict aliasing violation! 8093 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 8094 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 8095 8096 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); 8097 } 8098 8099 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 8100 /// special functions, such as the default constructor, copy 8101 /// constructor, or destructor, to the given C++ class (C++ 8102 /// [special]p1). This routine can only be executed just before the 8103 /// definition of the class is complete. 8104 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 8105 if (ClassDecl->needsImplicitDefaultConstructor()) { 8106 ++getASTContext().NumImplicitDefaultConstructors; 8107 8108 if (ClassDecl->hasInheritedConstructor()) 8109 DeclareImplicitDefaultConstructor(ClassDecl); 8110 } 8111 8112 if (ClassDecl->needsImplicitCopyConstructor()) { 8113 ++getASTContext().NumImplicitCopyConstructors; 8114 8115 // If the properties or semantics of the copy constructor couldn't be 8116 // determined while the class was being declared, force a declaration 8117 // of it now. 8118 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 8119 ClassDecl->hasInheritedConstructor()) 8120 DeclareImplicitCopyConstructor(ClassDecl); 8121 // For the MS ABI we need to know whether the copy ctor is deleted. A 8122 // prerequisite for deleting the implicit copy ctor is that the class has a 8123 // move ctor or move assignment that is either user-declared or whose 8124 // semantics are inherited from a subobject. FIXME: We should provide a more 8125 // direct way for CodeGen to ask whether the constructor was deleted. 8126 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 8127 (ClassDecl->hasUserDeclaredMoveConstructor() || 8128 ClassDecl->needsOverloadResolutionForMoveConstructor() || 8129 ClassDecl->hasUserDeclaredMoveAssignment() || 8130 ClassDecl->needsOverloadResolutionForMoveAssignment())) 8131 DeclareImplicitCopyConstructor(ClassDecl); 8132 } 8133 8134 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 8135 ++getASTContext().NumImplicitMoveConstructors; 8136 8137 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 8138 ClassDecl->hasInheritedConstructor()) 8139 DeclareImplicitMoveConstructor(ClassDecl); 8140 } 8141 8142 if (ClassDecl->needsImplicitCopyAssignment()) { 8143 ++getASTContext().NumImplicitCopyAssignmentOperators; 8144 8145 // If we have a dynamic class, then the copy assignment operator may be 8146 // virtual, so we have to declare it immediately. This ensures that, e.g., 8147 // it shows up in the right place in the vtable and that we diagnose 8148 // problems with the implicit exception specification. 8149 if (ClassDecl->isDynamicClass() || 8150 ClassDecl->needsOverloadResolutionForCopyAssignment() || 8151 ClassDecl->hasInheritedAssignment()) 8152 DeclareImplicitCopyAssignment(ClassDecl); 8153 } 8154 8155 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 8156 ++getASTContext().NumImplicitMoveAssignmentOperators; 8157 8158 // Likewise for the move assignment operator. 8159 if (ClassDecl->isDynamicClass() || 8160 ClassDecl->needsOverloadResolutionForMoveAssignment() || 8161 ClassDecl->hasInheritedAssignment()) 8162 DeclareImplicitMoveAssignment(ClassDecl); 8163 } 8164 8165 if (ClassDecl->needsImplicitDestructor()) { 8166 ++getASTContext().NumImplicitDestructors; 8167 8168 // If we have a dynamic class, then the destructor may be virtual, so we 8169 // have to declare the destructor immediately. This ensures that, e.g., it 8170 // shows up in the right place in the vtable and that we diagnose problems 8171 // with the implicit exception specification. 8172 if (ClassDecl->isDynamicClass() || 8173 ClassDecl->needsOverloadResolutionForDestructor()) 8174 DeclareImplicitDestructor(ClassDecl); 8175 } 8176 } 8177 8178 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 8179 if (!D) 8180 return 0; 8181 8182 // The order of template parameters is not important here. All names 8183 // get added to the same scope. 8184 SmallVector<TemplateParameterList *, 4> ParameterLists; 8185 8186 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8187 D = TD->getTemplatedDecl(); 8188 8189 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 8190 ParameterLists.push_back(PSD->getTemplateParameters()); 8191 8192 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 8193 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 8194 ParameterLists.push_back(DD->getTemplateParameterList(i)); 8195 8196 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8197 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 8198 ParameterLists.push_back(FTD->getTemplateParameters()); 8199 } 8200 } 8201 8202 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 8203 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 8204 ParameterLists.push_back(TD->getTemplateParameterList(i)); 8205 8206 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 8207 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 8208 ParameterLists.push_back(CTD->getTemplateParameters()); 8209 } 8210 } 8211 8212 unsigned Count = 0; 8213 for (TemplateParameterList *Params : ParameterLists) { 8214 if (Params->size() > 0) 8215 // Ignore explicit specializations; they don't contribute to the template 8216 // depth. 8217 ++Count; 8218 for (NamedDecl *Param : *Params) { 8219 if (Param->getDeclName()) { 8220 S->AddDecl(Param); 8221 IdResolver.AddDecl(Param); 8222 } 8223 } 8224 } 8225 8226 return Count; 8227 } 8228 8229 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8230 if (!RecordD) return; 8231 AdjustDeclIfTemplate(RecordD); 8232 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 8233 PushDeclContext(S, Record); 8234 } 8235 8236 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8237 if (!RecordD) return; 8238 PopDeclContext(); 8239 } 8240 8241 /// This is used to implement the constant expression evaluation part of the 8242 /// attribute enable_if extension. There is nothing in standard C++ which would 8243 /// require reentering parameters. 8244 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 8245 if (!Param) 8246 return; 8247 8248 S->AddDecl(Param); 8249 if (Param->getDeclName()) 8250 IdResolver.AddDecl(Param); 8251 } 8252 8253 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 8254 /// parsing a top-level (non-nested) C++ class, and we are now 8255 /// parsing those parts of the given Method declaration that could 8256 /// not be parsed earlier (C++ [class.mem]p2), such as default 8257 /// arguments. This action should enter the scope of the given 8258 /// Method declaration as if we had just parsed the qualified method 8259 /// name. However, it should not bring the parameters into scope; 8260 /// that will be performed by ActOnDelayedCXXMethodParameter. 8261 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8262 } 8263 8264 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 8265 /// C++ method declaration. We're (re-)introducing the given 8266 /// function parameter into scope for use in parsing later parts of 8267 /// the method declaration. For example, we could see an 8268 /// ActOnParamDefaultArgument event for this parameter. 8269 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 8270 if (!ParamD) 8271 return; 8272 8273 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 8274 8275 // If this parameter has an unparsed default argument, clear it out 8276 // to make way for the parsed default argument. 8277 if (Param->hasUnparsedDefaultArg()) 8278 Param->setDefaultArg(nullptr); 8279 8280 S->AddDecl(Param); 8281 if (Param->getDeclName()) 8282 IdResolver.AddDecl(Param); 8283 } 8284 8285 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8286 /// processing the delayed method declaration for Method. The method 8287 /// declaration is now considered finished. There may be a separate 8288 /// ActOnStartOfFunctionDef action later (not necessarily 8289 /// immediately!) for this method, if it was also defined inside the 8290 /// class body. 8291 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8292 if (!MethodD) 8293 return; 8294 8295 AdjustDeclIfTemplate(MethodD); 8296 8297 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8298 8299 // Now that we have our default arguments, check the constructor 8300 // again. It could produce additional diagnostics or affect whether 8301 // the class has implicitly-declared destructors, among other 8302 // things. 8303 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8304 CheckConstructor(Constructor); 8305 8306 // Check the default arguments, which we may have added. 8307 if (!Method->isInvalidDecl()) 8308 CheckCXXDefaultArguments(Method); 8309 } 8310 8311 // Emit the given diagnostic for each non-address-space qualifier. 8312 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 8313 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 8314 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8315 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 8316 bool DiagOccured = false; 8317 FTI.MethodQualifiers->forEachQualifier( 8318 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 8319 SourceLocation SL) { 8320 // This diagnostic should be emitted on any qualifier except an addr 8321 // space qualifier. However, forEachQualifier currently doesn't visit 8322 // addr space qualifiers, so there's no way to write this condition 8323 // right now; we just diagnose on everything. 8324 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 8325 DiagOccured = true; 8326 }); 8327 if (DiagOccured) 8328 D.setInvalidType(); 8329 } 8330 } 8331 8332 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8333 /// the well-formedness of the constructor declarator @p D with type @p 8334 /// R. If there are any errors in the declarator, this routine will 8335 /// emit diagnostics and set the invalid bit to true. In any case, the type 8336 /// will be updated to reflect a well-formed type for the constructor and 8337 /// returned. 8338 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8339 StorageClass &SC) { 8340 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8341 8342 // C++ [class.ctor]p3: 8343 // A constructor shall not be virtual (10.3) or static (9.4). A 8344 // constructor can be invoked for a const, volatile or const 8345 // volatile object. A constructor shall not be declared const, 8346 // volatile, or const volatile (9.3.2). 8347 if (isVirtual) { 8348 if (!D.isInvalidType()) 8349 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8350 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8351 << SourceRange(D.getIdentifierLoc()); 8352 D.setInvalidType(); 8353 } 8354 if (SC == SC_Static) { 8355 if (!D.isInvalidType()) 8356 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8357 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8358 << SourceRange(D.getIdentifierLoc()); 8359 D.setInvalidType(); 8360 SC = SC_None; 8361 } 8362 8363 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8364 diagnoseIgnoredQualifiers( 8365 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8366 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8367 D.getDeclSpec().getRestrictSpecLoc(), 8368 D.getDeclSpec().getAtomicSpecLoc()); 8369 D.setInvalidType(); 8370 } 8371 8372 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 8373 8374 // C++0x [class.ctor]p4: 8375 // A constructor shall not be declared with a ref-qualifier. 8376 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8377 if (FTI.hasRefQualifier()) { 8378 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8379 << FTI.RefQualifierIsLValueRef 8380 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8381 D.setInvalidType(); 8382 } 8383 8384 // Rebuild the function type "R" without any type qualifiers (in 8385 // case any of the errors above fired) and with "void" as the 8386 // return type, since constructors don't have return types. 8387 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8388 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8389 return R; 8390 8391 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8392 EPI.TypeQuals = Qualifiers(); 8393 EPI.RefQualifier = RQ_None; 8394 8395 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8396 } 8397 8398 /// CheckConstructor - Checks a fully-formed constructor for 8399 /// well-formedness, issuing any diagnostics required. Returns true if 8400 /// the constructor declarator is invalid. 8401 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8402 CXXRecordDecl *ClassDecl 8403 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8404 if (!ClassDecl) 8405 return Constructor->setInvalidDecl(); 8406 8407 // C++ [class.copy]p3: 8408 // A declaration of a constructor for a class X is ill-formed if 8409 // its first parameter is of type (optionally cv-qualified) X and 8410 // either there are no other parameters or else all other 8411 // parameters have default arguments. 8412 if (!Constructor->isInvalidDecl() && 8413 ((Constructor->getNumParams() == 1) || 8414 (Constructor->getNumParams() > 1 && 8415 Constructor->getParamDecl(1)->hasDefaultArg())) && 8416 Constructor->getTemplateSpecializationKind() 8417 != TSK_ImplicitInstantiation) { 8418 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8419 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8420 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8421 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8422 const char *ConstRef 8423 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8424 : " const &"; 8425 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8426 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8427 8428 // FIXME: Rather that making the constructor invalid, we should endeavor 8429 // to fix the type. 8430 Constructor->setInvalidDecl(); 8431 } 8432 } 8433 } 8434 8435 /// CheckDestructor - Checks a fully-formed destructor definition for 8436 /// well-formedness, issuing any diagnostics required. Returns true 8437 /// on error. 8438 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8439 CXXRecordDecl *RD = Destructor->getParent(); 8440 8441 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8442 SourceLocation Loc; 8443 8444 if (!Destructor->isImplicit()) 8445 Loc = Destructor->getLocation(); 8446 else 8447 Loc = RD->getLocation(); 8448 8449 // If we have a virtual destructor, look up the deallocation function 8450 if (FunctionDecl *OperatorDelete = 8451 FindDeallocationFunctionForDestructor(Loc, RD)) { 8452 Expr *ThisArg = nullptr; 8453 8454 // If the notional 'delete this' expression requires a non-trivial 8455 // conversion from 'this' to the type of a destroying operator delete's 8456 // first parameter, perform that conversion now. 8457 if (OperatorDelete->isDestroyingOperatorDelete()) { 8458 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8459 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8460 // C++ [class.dtor]p13: 8461 // ... as if for the expression 'delete this' appearing in a 8462 // non-virtual destructor of the destructor's class. 8463 ContextRAII SwitchContext(*this, Destructor); 8464 ExprResult This = 8465 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8466 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8467 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8468 if (This.isInvalid()) { 8469 // FIXME: Register this as a context note so that it comes out 8470 // in the right order. 8471 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8472 return true; 8473 } 8474 ThisArg = This.get(); 8475 } 8476 } 8477 8478 DiagnoseUseOfDecl(OperatorDelete, Loc); 8479 MarkFunctionReferenced(Loc, OperatorDelete); 8480 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8481 } 8482 } 8483 8484 return false; 8485 } 8486 8487 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8488 /// the well-formednes of the destructor declarator @p D with type @p 8489 /// R. If there are any errors in the declarator, this routine will 8490 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8491 /// will be updated to reflect a well-formed type for the destructor and 8492 /// returned. 8493 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8494 StorageClass& SC) { 8495 // C++ [class.dtor]p1: 8496 // [...] A typedef-name that names a class is a class-name 8497 // (7.1.3); however, a typedef-name that names a class shall not 8498 // be used as the identifier in the declarator for a destructor 8499 // declaration. 8500 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8501 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8502 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8503 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8504 else if (const TemplateSpecializationType *TST = 8505 DeclaratorType->getAs<TemplateSpecializationType>()) 8506 if (TST->isTypeAlias()) 8507 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8508 << DeclaratorType << 1; 8509 8510 // C++ [class.dtor]p2: 8511 // A destructor is used to destroy objects of its class type. A 8512 // destructor takes no parameters, and no return type can be 8513 // specified for it (not even void). The address of a destructor 8514 // shall not be taken. A destructor shall not be static. A 8515 // destructor can be invoked for a const, volatile or const 8516 // volatile object. A destructor shall not be declared const, 8517 // volatile or const volatile (9.3.2). 8518 if (SC == SC_Static) { 8519 if (!D.isInvalidType()) 8520 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8521 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8522 << SourceRange(D.getIdentifierLoc()) 8523 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8524 8525 SC = SC_None; 8526 } 8527 if (!D.isInvalidType()) { 8528 // Destructors don't have return types, but the parser will 8529 // happily parse something like: 8530 // 8531 // class X { 8532 // float ~X(); 8533 // }; 8534 // 8535 // The return type will be eliminated later. 8536 if (D.getDeclSpec().hasTypeSpecifier()) 8537 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8538 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8539 << SourceRange(D.getIdentifierLoc()); 8540 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8541 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8542 SourceLocation(), 8543 D.getDeclSpec().getConstSpecLoc(), 8544 D.getDeclSpec().getVolatileSpecLoc(), 8545 D.getDeclSpec().getRestrictSpecLoc(), 8546 D.getDeclSpec().getAtomicSpecLoc()); 8547 D.setInvalidType(); 8548 } 8549 } 8550 8551 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 8552 8553 // C++0x [class.dtor]p2: 8554 // A destructor shall not be declared with a ref-qualifier. 8555 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8556 if (FTI.hasRefQualifier()) { 8557 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8558 << FTI.RefQualifierIsLValueRef 8559 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8560 D.setInvalidType(); 8561 } 8562 8563 // Make sure we don't have any parameters. 8564 if (FTIHasNonVoidParameters(FTI)) { 8565 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8566 8567 // Delete the parameters. 8568 FTI.freeParams(); 8569 D.setInvalidType(); 8570 } 8571 8572 // Make sure the destructor isn't variadic. 8573 if (FTI.isVariadic) { 8574 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8575 D.setInvalidType(); 8576 } 8577 8578 // Rebuild the function type "R" without any type qualifiers or 8579 // parameters (in case any of the errors above fired) and with 8580 // "void" as the return type, since destructors don't have return 8581 // types. 8582 if (!D.isInvalidType()) 8583 return R; 8584 8585 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8586 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8587 EPI.Variadic = false; 8588 EPI.TypeQuals = Qualifiers(); 8589 EPI.RefQualifier = RQ_None; 8590 return Context.getFunctionType(Context.VoidTy, None, EPI); 8591 } 8592 8593 static void extendLeft(SourceRange &R, SourceRange Before) { 8594 if (Before.isInvalid()) 8595 return; 8596 R.setBegin(Before.getBegin()); 8597 if (R.getEnd().isInvalid()) 8598 R.setEnd(Before.getEnd()); 8599 } 8600 8601 static void extendRight(SourceRange &R, SourceRange After) { 8602 if (After.isInvalid()) 8603 return; 8604 if (R.getBegin().isInvalid()) 8605 R.setBegin(After.getBegin()); 8606 R.setEnd(After.getEnd()); 8607 } 8608 8609 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8610 /// well-formednes of the conversion function declarator @p D with 8611 /// type @p R. If there are any errors in the declarator, this routine 8612 /// will emit diagnostics and return true. Otherwise, it will return 8613 /// false. Either way, the type @p R will be updated to reflect a 8614 /// well-formed type for the conversion operator. 8615 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8616 StorageClass& SC) { 8617 // C++ [class.conv.fct]p1: 8618 // Neither parameter types nor return type can be specified. The 8619 // type of a conversion function (8.3.5) is "function taking no 8620 // parameter returning conversion-type-id." 8621 if (SC == SC_Static) { 8622 if (!D.isInvalidType()) 8623 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8624 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8625 << D.getName().getSourceRange(); 8626 D.setInvalidType(); 8627 SC = SC_None; 8628 } 8629 8630 TypeSourceInfo *ConvTSI = nullptr; 8631 QualType ConvType = 8632 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8633 8634 const DeclSpec &DS = D.getDeclSpec(); 8635 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8636 // Conversion functions don't have return types, but the parser will 8637 // happily parse something like: 8638 // 8639 // class X { 8640 // float operator bool(); 8641 // }; 8642 // 8643 // The return type will be changed later anyway. 8644 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8645 << SourceRange(DS.getTypeSpecTypeLoc()) 8646 << SourceRange(D.getIdentifierLoc()); 8647 D.setInvalidType(); 8648 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8649 // It's also plausible that the user writes type qualifiers in the wrong 8650 // place, such as: 8651 // struct S { const operator int(); }; 8652 // FIXME: we could provide a fixit to move the qualifiers onto the 8653 // conversion type. 8654 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8655 << SourceRange(D.getIdentifierLoc()) << 0; 8656 D.setInvalidType(); 8657 } 8658 8659 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8660 8661 // Make sure we don't have any parameters. 8662 if (Proto->getNumParams() > 0) { 8663 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8664 8665 // Delete the parameters. 8666 D.getFunctionTypeInfo().freeParams(); 8667 D.setInvalidType(); 8668 } else if (Proto->isVariadic()) { 8669 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8670 D.setInvalidType(); 8671 } 8672 8673 // Diagnose "&operator bool()" and other such nonsense. This 8674 // is actually a gcc extension which we don't support. 8675 if (Proto->getReturnType() != ConvType) { 8676 bool NeedsTypedef = false; 8677 SourceRange Before, After; 8678 8679 // Walk the chunks and extract information on them for our diagnostic. 8680 bool PastFunctionChunk = false; 8681 for (auto &Chunk : D.type_objects()) { 8682 switch (Chunk.Kind) { 8683 case DeclaratorChunk::Function: 8684 if (!PastFunctionChunk) { 8685 if (Chunk.Fun.HasTrailingReturnType) { 8686 TypeSourceInfo *TRT = nullptr; 8687 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8688 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8689 } 8690 PastFunctionChunk = true; 8691 break; 8692 } 8693 LLVM_FALLTHROUGH; 8694 case DeclaratorChunk::Array: 8695 NeedsTypedef = true; 8696 extendRight(After, Chunk.getSourceRange()); 8697 break; 8698 8699 case DeclaratorChunk::Pointer: 8700 case DeclaratorChunk::BlockPointer: 8701 case DeclaratorChunk::Reference: 8702 case DeclaratorChunk::MemberPointer: 8703 case DeclaratorChunk::Pipe: 8704 extendLeft(Before, Chunk.getSourceRange()); 8705 break; 8706 8707 case DeclaratorChunk::Paren: 8708 extendLeft(Before, Chunk.Loc); 8709 extendRight(After, Chunk.EndLoc); 8710 break; 8711 } 8712 } 8713 8714 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8715 After.isValid() ? After.getBegin() : 8716 D.getIdentifierLoc(); 8717 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8718 DB << Before << After; 8719 8720 if (!NeedsTypedef) { 8721 DB << /*don't need a typedef*/0; 8722 8723 // If we can provide a correct fix-it hint, do so. 8724 if (After.isInvalid() && ConvTSI) { 8725 SourceLocation InsertLoc = 8726 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 8727 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8728 << FixItHint::CreateInsertionFromRange( 8729 InsertLoc, CharSourceRange::getTokenRange(Before)) 8730 << FixItHint::CreateRemoval(Before); 8731 } 8732 } else if (!Proto->getReturnType()->isDependentType()) { 8733 DB << /*typedef*/1 << Proto->getReturnType(); 8734 } else if (getLangOpts().CPlusPlus11) { 8735 DB << /*alias template*/2 << Proto->getReturnType(); 8736 } else { 8737 DB << /*might not be fixable*/3; 8738 } 8739 8740 // Recover by incorporating the other type chunks into the result type. 8741 // Note, this does *not* change the name of the function. This is compatible 8742 // with the GCC extension: 8743 // struct S { &operator int(); } s; 8744 // int &r = s.operator int(); // ok in GCC 8745 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8746 ConvType = Proto->getReturnType(); 8747 } 8748 8749 // C++ [class.conv.fct]p4: 8750 // The conversion-type-id shall not represent a function type nor 8751 // an array type. 8752 if (ConvType->isArrayType()) { 8753 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8754 ConvType = Context.getPointerType(ConvType); 8755 D.setInvalidType(); 8756 } else if (ConvType->isFunctionType()) { 8757 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8758 ConvType = Context.getPointerType(ConvType); 8759 D.setInvalidType(); 8760 } 8761 8762 // Rebuild the function type "R" without any parameters (in case any 8763 // of the errors above fired) and with the conversion type as the 8764 // return type. 8765 if (D.isInvalidType()) 8766 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8767 8768 // C++0x explicit conversion operators. 8769 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) 8770 Diag(DS.getExplicitSpecLoc(), 8771 getLangOpts().CPlusPlus11 8772 ? diag::warn_cxx98_compat_explicit_conversion_functions 8773 : diag::ext_explicit_conversion_functions) 8774 << SourceRange(DS.getExplicitSpecRange()); 8775 } 8776 8777 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8778 /// the declaration of the given C++ conversion function. This routine 8779 /// is responsible for recording the conversion function in the C++ 8780 /// class, if possible. 8781 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8782 assert(Conversion && "Expected to receive a conversion function declaration"); 8783 8784 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8785 8786 // Make sure we aren't redeclaring the conversion function. 8787 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8788 8789 // C++ [class.conv.fct]p1: 8790 // [...] A conversion function is never used to convert a 8791 // (possibly cv-qualified) object to the (possibly cv-qualified) 8792 // same object type (or a reference to it), to a (possibly 8793 // cv-qualified) base class of that type (or a reference to it), 8794 // or to (possibly cv-qualified) void. 8795 // FIXME: Suppress this warning if the conversion function ends up being a 8796 // virtual function that overrides a virtual function in a base class. 8797 QualType ClassType 8798 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8799 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8800 ConvType = ConvTypeRef->getPointeeType(); 8801 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8802 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8803 /* Suppress diagnostics for instantiations. */; 8804 else if (ConvType->isRecordType()) { 8805 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8806 if (ConvType == ClassType) 8807 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8808 << ClassType; 8809 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8810 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8811 << ClassType << ConvType; 8812 } else if (ConvType->isVoidType()) { 8813 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8814 << ClassType << ConvType; 8815 } 8816 8817 if (FunctionTemplateDecl *ConversionTemplate 8818 = Conversion->getDescribedFunctionTemplate()) 8819 return ConversionTemplate; 8820 8821 return Conversion; 8822 } 8823 8824 namespace { 8825 /// Utility class to accumulate and print a diagnostic listing the invalid 8826 /// specifier(s) on a declaration. 8827 struct BadSpecifierDiagnoser { 8828 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8829 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8830 ~BadSpecifierDiagnoser() { 8831 Diagnostic << Specifiers; 8832 } 8833 8834 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8835 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8836 } 8837 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8838 return check(SpecLoc, 8839 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8840 } 8841 void check(SourceLocation SpecLoc, const char *Spec) { 8842 if (SpecLoc.isInvalid()) return; 8843 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8844 if (!Specifiers.empty()) Specifiers += " "; 8845 Specifiers += Spec; 8846 } 8847 8848 Sema &S; 8849 Sema::SemaDiagnosticBuilder Diagnostic; 8850 std::string Specifiers; 8851 }; 8852 } 8853 8854 /// Check the validity of a declarator that we parsed for a deduction-guide. 8855 /// These aren't actually declarators in the grammar, so we need to check that 8856 /// the user didn't specify any pieces that are not part of the deduction-guide 8857 /// grammar. 8858 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8859 StorageClass &SC) { 8860 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8861 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8862 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8863 8864 // C++ [temp.deduct.guide]p3: 8865 // A deduction-gide shall be declared in the same scope as the 8866 // corresponding class template. 8867 if (!CurContext->getRedeclContext()->Equals( 8868 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8869 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8870 << GuidedTemplateDecl; 8871 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8872 } 8873 8874 auto &DS = D.getMutableDeclSpec(); 8875 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8876 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8877 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8878 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 8879 BadSpecifierDiagnoser Diagnoser( 8880 *this, D.getIdentifierLoc(), 8881 diag::err_deduction_guide_invalid_specifier); 8882 8883 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8884 DS.ClearStorageClassSpecs(); 8885 SC = SC_None; 8886 8887 // 'explicit' is permitted. 8888 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8889 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8890 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8891 DS.ClearConstexprSpec(); 8892 8893 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8894 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8895 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8896 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8897 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8898 DS.ClearTypeQualifiers(); 8899 8900 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8901 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8902 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8903 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8904 DS.ClearTypeSpecType(); 8905 } 8906 8907 if (D.isInvalidType()) 8908 return; 8909 8910 // Check the declarator is simple enough. 8911 bool FoundFunction = false; 8912 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8913 if (Chunk.Kind == DeclaratorChunk::Paren) 8914 continue; 8915 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8916 Diag(D.getDeclSpec().getBeginLoc(), 8917 diag::err_deduction_guide_with_complex_decl) 8918 << D.getSourceRange(); 8919 break; 8920 } 8921 if (!Chunk.Fun.hasTrailingReturnType()) { 8922 Diag(D.getName().getBeginLoc(), 8923 diag::err_deduction_guide_no_trailing_return_type); 8924 break; 8925 } 8926 8927 // Check that the return type is written as a specialization of 8928 // the template specified as the deduction-guide's name. 8929 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8930 TypeSourceInfo *TSI = nullptr; 8931 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8932 assert(TSI && "deduction guide has valid type but invalid return type?"); 8933 bool AcceptableReturnType = false; 8934 bool MightInstantiateToSpecialization = false; 8935 if (auto RetTST = 8936 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8937 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8938 bool TemplateMatches = 8939 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8940 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8941 AcceptableReturnType = true; 8942 else { 8943 // This could still instantiate to the right type, unless we know it 8944 // names the wrong class template. 8945 auto *TD = SpecifiedName.getAsTemplateDecl(); 8946 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8947 !TemplateMatches); 8948 } 8949 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8950 MightInstantiateToSpecialization = true; 8951 } 8952 8953 if (!AcceptableReturnType) { 8954 Diag(TSI->getTypeLoc().getBeginLoc(), 8955 diag::err_deduction_guide_bad_trailing_return_type) 8956 << GuidedTemplate << TSI->getType() 8957 << MightInstantiateToSpecialization 8958 << TSI->getTypeLoc().getSourceRange(); 8959 } 8960 8961 // Keep going to check that we don't have any inner declarator pieces (we 8962 // could still have a function returning a pointer to a function). 8963 FoundFunction = true; 8964 } 8965 8966 if (D.isFunctionDefinition()) 8967 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8968 } 8969 8970 //===----------------------------------------------------------------------===// 8971 // Namespace Handling 8972 //===----------------------------------------------------------------------===// 8973 8974 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 8975 /// reopened. 8976 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8977 SourceLocation Loc, 8978 IdentifierInfo *II, bool *IsInline, 8979 NamespaceDecl *PrevNS) { 8980 assert(*IsInline != PrevNS->isInline()); 8981 8982 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8983 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8984 // inline namespaces, with the intention of bringing names into namespace std. 8985 // 8986 // We support this just well enough to get that case working; this is not 8987 // sufficient to support reopening namespaces as inline in general. 8988 if (*IsInline && II && II->getName().startswith("__atomic") && 8989 S.getSourceManager().isInSystemHeader(Loc)) { 8990 // Mark all prior declarations of the namespace as inline. 8991 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8992 NS = NS->getPreviousDecl()) 8993 NS->setInline(*IsInline); 8994 // Patch up the lookup table for the containing namespace. This isn't really 8995 // correct, but it's good enough for this particular case. 8996 for (auto *I : PrevNS->decls()) 8997 if (auto *ND = dyn_cast<NamedDecl>(I)) 8998 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8999 return; 9000 } 9001 9002 if (PrevNS->isInline()) 9003 // The user probably just forgot the 'inline', so suggest that it 9004 // be added back. 9005 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 9006 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 9007 else 9008 S.Diag(Loc, diag::err_inline_namespace_mismatch); 9009 9010 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 9011 *IsInline = PrevNS->isInline(); 9012 } 9013 9014 /// ActOnStartNamespaceDef - This is called at the start of a namespace 9015 /// definition. 9016 Decl *Sema::ActOnStartNamespaceDef( 9017 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 9018 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 9019 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 9020 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 9021 // For anonymous namespace, take the location of the left brace. 9022 SourceLocation Loc = II ? IdentLoc : LBrace; 9023 bool IsInline = InlineLoc.isValid(); 9024 bool IsInvalid = false; 9025 bool IsStd = false; 9026 bool AddToKnown = false; 9027 Scope *DeclRegionScope = NamespcScope->getParent(); 9028 9029 NamespaceDecl *PrevNS = nullptr; 9030 if (II) { 9031 // C++ [namespace.def]p2: 9032 // The identifier in an original-namespace-definition shall not 9033 // have been previously defined in the declarative region in 9034 // which the original-namespace-definition appears. The 9035 // identifier in an original-namespace-definition is the name of 9036 // the namespace. Subsequently in that declarative region, it is 9037 // treated as an original-namespace-name. 9038 // 9039 // Since namespace names are unique in their scope, and we don't 9040 // look through using directives, just look for any ordinary names 9041 // as if by qualified name lookup. 9042 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 9043 ForExternalRedeclaration); 9044 LookupQualifiedName(R, CurContext->getRedeclContext()); 9045 NamedDecl *PrevDecl = 9046 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 9047 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 9048 9049 if (PrevNS) { 9050 // This is an extended namespace definition. 9051 if (IsInline != PrevNS->isInline()) 9052 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 9053 &IsInline, PrevNS); 9054 } else if (PrevDecl) { 9055 // This is an invalid name redefinition. 9056 Diag(Loc, diag::err_redefinition_different_kind) 9057 << II; 9058 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9059 IsInvalid = true; 9060 // Continue on to push Namespc as current DeclContext and return it. 9061 } else if (II->isStr("std") && 9062 CurContext->getRedeclContext()->isTranslationUnit()) { 9063 // This is the first "real" definition of the namespace "std", so update 9064 // our cache of the "std" namespace to point at this definition. 9065 PrevNS = getStdNamespace(); 9066 IsStd = true; 9067 AddToKnown = !IsInline; 9068 } else { 9069 // We've seen this namespace for the first time. 9070 AddToKnown = !IsInline; 9071 } 9072 } else { 9073 // Anonymous namespaces. 9074 9075 // Determine whether the parent already has an anonymous namespace. 9076 DeclContext *Parent = CurContext->getRedeclContext(); 9077 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 9078 PrevNS = TU->getAnonymousNamespace(); 9079 } else { 9080 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 9081 PrevNS = ND->getAnonymousNamespace(); 9082 } 9083 9084 if (PrevNS && IsInline != PrevNS->isInline()) 9085 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 9086 &IsInline, PrevNS); 9087 } 9088 9089 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 9090 StartLoc, Loc, II, PrevNS); 9091 if (IsInvalid) 9092 Namespc->setInvalidDecl(); 9093 9094 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 9095 AddPragmaAttributes(DeclRegionScope, Namespc); 9096 9097 // FIXME: Should we be merging attributes? 9098 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 9099 PushNamespaceVisibilityAttr(Attr, Loc); 9100 9101 if (IsStd) 9102 StdNamespace = Namespc; 9103 if (AddToKnown) 9104 KnownNamespaces[Namespc] = false; 9105 9106 if (II) { 9107 PushOnScopeChains(Namespc, DeclRegionScope); 9108 } else { 9109 // Link the anonymous namespace into its parent. 9110 DeclContext *Parent = CurContext->getRedeclContext(); 9111 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 9112 TU->setAnonymousNamespace(Namespc); 9113 } else { 9114 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 9115 } 9116 9117 CurContext->addDecl(Namespc); 9118 9119 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 9120 // behaves as if it were replaced by 9121 // namespace unique { /* empty body */ } 9122 // using namespace unique; 9123 // namespace unique { namespace-body } 9124 // where all occurrences of 'unique' in a translation unit are 9125 // replaced by the same identifier and this identifier differs 9126 // from all other identifiers in the entire program. 9127 9128 // We just create the namespace with an empty name and then add an 9129 // implicit using declaration, just like the standard suggests. 9130 // 9131 // CodeGen enforces the "universally unique" aspect by giving all 9132 // declarations semantically contained within an anonymous 9133 // namespace internal linkage. 9134 9135 if (!PrevNS) { 9136 UD = UsingDirectiveDecl::Create(Context, Parent, 9137 /* 'using' */ LBrace, 9138 /* 'namespace' */ SourceLocation(), 9139 /* qualifier */ NestedNameSpecifierLoc(), 9140 /* identifier */ SourceLocation(), 9141 Namespc, 9142 /* Ancestor */ Parent); 9143 UD->setImplicit(); 9144 Parent->addDecl(UD); 9145 } 9146 } 9147 9148 ActOnDocumentableDecl(Namespc); 9149 9150 // Although we could have an invalid decl (i.e. the namespace name is a 9151 // redefinition), push it as current DeclContext and try to continue parsing. 9152 // FIXME: We should be able to push Namespc here, so that the each DeclContext 9153 // for the namespace has the declarations that showed up in that particular 9154 // namespace definition. 9155 PushDeclContext(NamespcScope, Namespc); 9156 return Namespc; 9157 } 9158 9159 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 9160 /// is a namespace alias, returns the namespace it points to. 9161 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 9162 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 9163 return AD->getNamespace(); 9164 return dyn_cast_or_null<NamespaceDecl>(D); 9165 } 9166 9167 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 9168 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 9169 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 9170 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 9171 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 9172 Namespc->setRBraceLoc(RBrace); 9173 PopDeclContext(); 9174 if (Namespc->hasAttr<VisibilityAttr>()) 9175 PopPragmaVisibility(true, RBrace); 9176 // If this namespace contains an export-declaration, export it now. 9177 if (DeferredExportedNamespaces.erase(Namespc)) 9178 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 9179 } 9180 9181 CXXRecordDecl *Sema::getStdBadAlloc() const { 9182 return cast_or_null<CXXRecordDecl>( 9183 StdBadAlloc.get(Context.getExternalSource())); 9184 } 9185 9186 EnumDecl *Sema::getStdAlignValT() const { 9187 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 9188 } 9189 9190 NamespaceDecl *Sema::getStdNamespace() const { 9191 return cast_or_null<NamespaceDecl>( 9192 StdNamespace.get(Context.getExternalSource())); 9193 } 9194 9195 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 9196 if (!StdExperimentalNamespaceCache) { 9197 if (auto Std = getStdNamespace()) { 9198 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 9199 SourceLocation(), LookupNamespaceName); 9200 if (!LookupQualifiedName(Result, Std) || 9201 !(StdExperimentalNamespaceCache = 9202 Result.getAsSingle<NamespaceDecl>())) 9203 Result.suppressDiagnostics(); 9204 } 9205 } 9206 return StdExperimentalNamespaceCache; 9207 } 9208 9209 namespace { 9210 9211 enum UnsupportedSTLSelect { 9212 USS_InvalidMember, 9213 USS_MissingMember, 9214 USS_NonTrivial, 9215 USS_Other 9216 }; 9217 9218 struct InvalidSTLDiagnoser { 9219 Sema &S; 9220 SourceLocation Loc; 9221 QualType TyForDiags; 9222 9223 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 9224 const VarDecl *VD = nullptr) { 9225 { 9226 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 9227 << TyForDiags << ((int)Sel); 9228 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 9229 assert(!Name.empty()); 9230 D << Name; 9231 } 9232 } 9233 if (Sel == USS_InvalidMember) { 9234 S.Diag(VD->getLocation(), diag::note_var_declared_here) 9235 << VD << VD->getSourceRange(); 9236 } 9237 return QualType(); 9238 } 9239 }; 9240 } // namespace 9241 9242 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 9243 SourceLocation Loc) { 9244 assert(getLangOpts().CPlusPlus && 9245 "Looking for comparison category type outside of C++."); 9246 9247 // Check if we've already successfully checked the comparison category type 9248 // before. If so, skip checking it again. 9249 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 9250 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 9251 return Info->getType(); 9252 9253 // If lookup failed 9254 if (!Info) { 9255 std::string NameForDiags = "std::"; 9256 NameForDiags += ComparisonCategories::getCategoryString(Kind); 9257 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 9258 << NameForDiags; 9259 return QualType(); 9260 } 9261 9262 assert(Info->Kind == Kind); 9263 assert(Info->Record); 9264 9265 // Update the Record decl in case we encountered a forward declaration on our 9266 // first pass. FIXME: This is a bit of a hack. 9267 if (Info->Record->hasDefinition()) 9268 Info->Record = Info->Record->getDefinition(); 9269 9270 // Use an elaborated type for diagnostics which has a name containing the 9271 // prepended 'std' namespace but not any inline namespace names. 9272 QualType TyForDiags = [&]() { 9273 auto *NNS = 9274 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 9275 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 9276 }(); 9277 9278 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 9279 return QualType(); 9280 9281 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 9282 9283 if (!Info->Record->isTriviallyCopyable()) 9284 return UnsupportedSTLError(USS_NonTrivial); 9285 9286 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 9287 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 9288 // Tolerate empty base classes. 9289 if (Base->isEmpty()) 9290 continue; 9291 // Reject STL implementations which have at least one non-empty base. 9292 return UnsupportedSTLError(); 9293 } 9294 9295 // Check that the STL has implemented the types using a single integer field. 9296 // This expectation allows better codegen for builtin operators. We require: 9297 // (1) The class has exactly one field. 9298 // (2) The field is an integral or enumeration type. 9299 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9300 if (std::distance(FIt, FEnd) != 1 || 9301 !FIt->getType()->isIntegralOrEnumerationType()) { 9302 return UnsupportedSTLError(); 9303 } 9304 9305 // Build each of the require values and store them in Info. 9306 for (ComparisonCategoryResult CCR : 9307 ComparisonCategories::getPossibleResultsForType(Kind)) { 9308 StringRef MemName = ComparisonCategories::getResultString(CCR); 9309 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9310 9311 if (!ValInfo) 9312 return UnsupportedSTLError(USS_MissingMember, MemName); 9313 9314 VarDecl *VD = ValInfo->VD; 9315 assert(VD && "should not be null!"); 9316 9317 // Attempt to diagnose reasons why the STL definition of this type 9318 // might be foobar, including it failing to be a constant expression. 9319 // TODO Handle more ways the lookup or result can be invalid. 9320 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9321 !VD->checkInitIsICE()) 9322 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9323 9324 // Attempt to evaluate the var decl as a constant expression and extract 9325 // the value of its first field as a ICE. If this fails, the STL 9326 // implementation is not supported. 9327 if (!ValInfo->hasValidIntValue()) 9328 return UnsupportedSTLError(); 9329 9330 MarkVariableReferenced(Loc, VD); 9331 } 9332 9333 // We've successfully built the required types and expressions. Update 9334 // the cache and return the newly cached value. 9335 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9336 return Info->getType(); 9337 } 9338 9339 /// Retrieve the special "std" namespace, which may require us to 9340 /// implicitly define the namespace. 9341 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9342 if (!StdNamespace) { 9343 // The "std" namespace has not yet been defined, so build one implicitly. 9344 StdNamespace = NamespaceDecl::Create(Context, 9345 Context.getTranslationUnitDecl(), 9346 /*Inline=*/false, 9347 SourceLocation(), SourceLocation(), 9348 &PP.getIdentifierTable().get("std"), 9349 /*PrevDecl=*/nullptr); 9350 getStdNamespace()->setImplicit(true); 9351 } 9352 9353 return getStdNamespace(); 9354 } 9355 9356 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9357 assert(getLangOpts().CPlusPlus && 9358 "Looking for std::initializer_list outside of C++."); 9359 9360 // We're looking for implicit instantiations of 9361 // template <typename E> class std::initializer_list. 9362 9363 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9364 return false; 9365 9366 ClassTemplateDecl *Template = nullptr; 9367 const TemplateArgument *Arguments = nullptr; 9368 9369 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9370 9371 ClassTemplateSpecializationDecl *Specialization = 9372 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9373 if (!Specialization) 9374 return false; 9375 9376 Template = Specialization->getSpecializedTemplate(); 9377 Arguments = Specialization->getTemplateArgs().data(); 9378 } else if (const TemplateSpecializationType *TST = 9379 Ty->getAs<TemplateSpecializationType>()) { 9380 Template = dyn_cast_or_null<ClassTemplateDecl>( 9381 TST->getTemplateName().getAsTemplateDecl()); 9382 Arguments = TST->getArgs(); 9383 } 9384 if (!Template) 9385 return false; 9386 9387 if (!StdInitializerList) { 9388 // Haven't recognized std::initializer_list yet, maybe this is it. 9389 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9390 if (TemplateClass->getIdentifier() != 9391 &PP.getIdentifierTable().get("initializer_list") || 9392 !getStdNamespace()->InEnclosingNamespaceSetOf( 9393 TemplateClass->getDeclContext())) 9394 return false; 9395 // This is a template called std::initializer_list, but is it the right 9396 // template? 9397 TemplateParameterList *Params = Template->getTemplateParameters(); 9398 if (Params->getMinRequiredArguments() != 1) 9399 return false; 9400 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9401 return false; 9402 9403 // It's the right template. 9404 StdInitializerList = Template; 9405 } 9406 9407 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9408 return false; 9409 9410 // This is an instance of std::initializer_list. Find the argument type. 9411 if (Element) 9412 *Element = Arguments[0].getAsType(); 9413 return true; 9414 } 9415 9416 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9417 NamespaceDecl *Std = S.getStdNamespace(); 9418 if (!Std) { 9419 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9420 return nullptr; 9421 } 9422 9423 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9424 Loc, Sema::LookupOrdinaryName); 9425 if (!S.LookupQualifiedName(Result, Std)) { 9426 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9427 return nullptr; 9428 } 9429 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9430 if (!Template) { 9431 Result.suppressDiagnostics(); 9432 // We found something weird. Complain about the first thing we found. 9433 NamedDecl *Found = *Result.begin(); 9434 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9435 return nullptr; 9436 } 9437 9438 // We found some template called std::initializer_list. Now verify that it's 9439 // correct. 9440 TemplateParameterList *Params = Template->getTemplateParameters(); 9441 if (Params->getMinRequiredArguments() != 1 || 9442 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9443 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9444 return nullptr; 9445 } 9446 9447 return Template; 9448 } 9449 9450 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9451 if (!StdInitializerList) { 9452 StdInitializerList = LookupStdInitializerList(*this, Loc); 9453 if (!StdInitializerList) 9454 return QualType(); 9455 } 9456 9457 TemplateArgumentListInfo Args(Loc, Loc); 9458 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9459 Context.getTrivialTypeSourceInfo(Element, 9460 Loc))); 9461 return Context.getCanonicalType( 9462 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9463 } 9464 9465 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9466 // C++ [dcl.init.list]p2: 9467 // A constructor is an initializer-list constructor if its first parameter 9468 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9469 // std::initializer_list<E> for some type E, and either there are no other 9470 // parameters or else all other parameters have default arguments. 9471 if (Ctor->getNumParams() < 1 || 9472 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9473 return false; 9474 9475 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9476 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9477 ArgType = RT->getPointeeType().getUnqualifiedType(); 9478 9479 return isStdInitializerList(ArgType, nullptr); 9480 } 9481 9482 /// Determine whether a using statement is in a context where it will be 9483 /// apply in all contexts. 9484 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9485 switch (CurContext->getDeclKind()) { 9486 case Decl::TranslationUnit: 9487 return true; 9488 case Decl::LinkageSpec: 9489 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9490 default: 9491 return false; 9492 } 9493 } 9494 9495 namespace { 9496 9497 // Callback to only accept typo corrections that are namespaces. 9498 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 9499 public: 9500 bool ValidateCandidate(const TypoCorrection &candidate) override { 9501 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9502 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9503 return false; 9504 } 9505 9506 std::unique_ptr<CorrectionCandidateCallback> clone() override { 9507 return llvm::make_unique<NamespaceValidatorCCC>(*this); 9508 } 9509 }; 9510 9511 } 9512 9513 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9514 CXXScopeSpec &SS, 9515 SourceLocation IdentLoc, 9516 IdentifierInfo *Ident) { 9517 R.clear(); 9518 NamespaceValidatorCCC CCC{}; 9519 if (TypoCorrection Corrected = 9520 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 9521 Sema::CTK_ErrorRecovery)) { 9522 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9523 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9524 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9525 Ident->getName().equals(CorrectedStr); 9526 S.diagnoseTypo(Corrected, 9527 S.PDiag(diag::err_using_directive_member_suggest) 9528 << Ident << DC << DroppedSpecifier << SS.getRange(), 9529 S.PDiag(diag::note_namespace_defined_here)); 9530 } else { 9531 S.diagnoseTypo(Corrected, 9532 S.PDiag(diag::err_using_directive_suggest) << Ident, 9533 S.PDiag(diag::note_namespace_defined_here)); 9534 } 9535 R.addDecl(Corrected.getFoundDecl()); 9536 return true; 9537 } 9538 return false; 9539 } 9540 9541 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 9542 SourceLocation NamespcLoc, CXXScopeSpec &SS, 9543 SourceLocation IdentLoc, 9544 IdentifierInfo *NamespcName, 9545 const ParsedAttributesView &AttrList) { 9546 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9547 assert(NamespcName && "Invalid NamespcName."); 9548 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9549 9550 // This can only happen along a recovery path. 9551 while (S->isTemplateParamScope()) 9552 S = S->getParent(); 9553 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9554 9555 UsingDirectiveDecl *UDir = nullptr; 9556 NestedNameSpecifier *Qualifier = nullptr; 9557 if (SS.isSet()) 9558 Qualifier = SS.getScopeRep(); 9559 9560 // Lookup namespace name. 9561 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9562 LookupParsedName(R, S, &SS); 9563 if (R.isAmbiguous()) 9564 return nullptr; 9565 9566 if (R.empty()) { 9567 R.clear(); 9568 // Allow "using namespace std;" or "using namespace ::std;" even if 9569 // "std" hasn't been defined yet, for GCC compatibility. 9570 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9571 NamespcName->isStr("std")) { 9572 Diag(IdentLoc, diag::ext_using_undefined_std); 9573 R.addDecl(getOrCreateStdNamespace()); 9574 R.resolveKind(); 9575 } 9576 // Otherwise, attempt typo correction. 9577 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9578 } 9579 9580 if (!R.empty()) { 9581 NamedDecl *Named = R.getRepresentativeDecl(); 9582 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9583 assert(NS && "expected namespace decl"); 9584 9585 // The use of a nested name specifier may trigger deprecation warnings. 9586 DiagnoseUseOfDecl(Named, IdentLoc); 9587 9588 // C++ [namespace.udir]p1: 9589 // A using-directive specifies that the names in the nominated 9590 // namespace can be used in the scope in which the 9591 // using-directive appears after the using-directive. During 9592 // unqualified name lookup (3.4.1), the names appear as if they 9593 // were declared in the nearest enclosing namespace which 9594 // contains both the using-directive and the nominated 9595 // namespace. [Note: in this context, "contains" means "contains 9596 // directly or indirectly". ] 9597 9598 // Find enclosing context containing both using-directive and 9599 // nominated namespace. 9600 DeclContext *CommonAncestor = NS; 9601 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9602 CommonAncestor = CommonAncestor->getParent(); 9603 9604 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9605 SS.getWithLocInContext(Context), 9606 IdentLoc, Named, CommonAncestor); 9607 9608 if (IsUsingDirectiveInToplevelContext(CurContext) && 9609 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9610 Diag(IdentLoc, diag::warn_using_directive_in_header); 9611 } 9612 9613 PushUsingDirective(S, UDir); 9614 } else { 9615 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9616 } 9617 9618 if (UDir) 9619 ProcessDeclAttributeList(S, UDir, AttrList); 9620 9621 return UDir; 9622 } 9623 9624 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9625 // If the scope has an associated entity and the using directive is at 9626 // namespace or translation unit scope, add the UsingDirectiveDecl into 9627 // its lookup structure so qualified name lookup can find it. 9628 DeclContext *Ctx = S->getEntity(); 9629 if (Ctx && !Ctx->isFunctionOrMethod()) 9630 Ctx->addDecl(UDir); 9631 else 9632 // Otherwise, it is at block scope. The using-directives will affect lookup 9633 // only to the end of the scope. 9634 S->PushUsingDirective(UDir); 9635 } 9636 9637 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 9638 SourceLocation UsingLoc, 9639 SourceLocation TypenameLoc, CXXScopeSpec &SS, 9640 UnqualifiedId &Name, 9641 SourceLocation EllipsisLoc, 9642 const ParsedAttributesView &AttrList) { 9643 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9644 9645 if (SS.isEmpty()) { 9646 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 9647 return nullptr; 9648 } 9649 9650 switch (Name.getKind()) { 9651 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9652 case UnqualifiedIdKind::IK_Identifier: 9653 case UnqualifiedIdKind::IK_OperatorFunctionId: 9654 case UnqualifiedIdKind::IK_LiteralOperatorId: 9655 case UnqualifiedIdKind::IK_ConversionFunctionId: 9656 break; 9657 9658 case UnqualifiedIdKind::IK_ConstructorName: 9659 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9660 // C++11 inheriting constructors. 9661 Diag(Name.getBeginLoc(), 9662 getLangOpts().CPlusPlus11 9663 ? diag::warn_cxx98_compat_using_decl_constructor 9664 : diag::err_using_decl_constructor) 9665 << SS.getRange(); 9666 9667 if (getLangOpts().CPlusPlus11) break; 9668 9669 return nullptr; 9670 9671 case UnqualifiedIdKind::IK_DestructorName: 9672 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 9673 return nullptr; 9674 9675 case UnqualifiedIdKind::IK_TemplateId: 9676 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 9677 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9678 return nullptr; 9679 9680 case UnqualifiedIdKind::IK_DeductionGuideName: 9681 llvm_unreachable("cannot parse qualified deduction guide name"); 9682 } 9683 9684 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9685 DeclarationName TargetName = TargetNameInfo.getName(); 9686 if (!TargetName) 9687 return nullptr; 9688 9689 // Warn about access declarations. 9690 if (UsingLoc.isInvalid()) { 9691 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 9692 ? diag::err_access_decl 9693 : diag::warn_access_decl_deprecated) 9694 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9695 } 9696 9697 if (EllipsisLoc.isInvalid()) { 9698 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9699 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9700 return nullptr; 9701 } else { 9702 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9703 !TargetNameInfo.containsUnexpandedParameterPack()) { 9704 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9705 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9706 EllipsisLoc = SourceLocation(); 9707 } 9708 } 9709 9710 NamedDecl *UD = 9711 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9712 SS, TargetNameInfo, EllipsisLoc, AttrList, 9713 /*IsInstantiation*/false); 9714 if (UD) 9715 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9716 9717 return UD; 9718 } 9719 9720 /// Determine whether a using declaration considers the given 9721 /// declarations as "equivalent", e.g., if they are redeclarations of 9722 /// the same entity or are both typedefs of the same type. 9723 static bool 9724 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9725 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9726 return true; 9727 9728 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9729 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9730 return Context.hasSameType(TD1->getUnderlyingType(), 9731 TD2->getUnderlyingType()); 9732 9733 return false; 9734 } 9735 9736 9737 /// Determines whether to create a using shadow decl for a particular 9738 /// decl, given the set of decls existing prior to this using lookup. 9739 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9740 const LookupResult &Previous, 9741 UsingShadowDecl *&PrevShadow) { 9742 // Diagnose finding a decl which is not from a base class of the 9743 // current class. We do this now because there are cases where this 9744 // function will silently decide not to build a shadow decl, which 9745 // will pre-empt further diagnostics. 9746 // 9747 // We don't need to do this in C++11 because we do the check once on 9748 // the qualifier. 9749 // 9750 // FIXME: diagnose the following if we care enough: 9751 // struct A { int foo; }; 9752 // struct B : A { using A::foo; }; 9753 // template <class T> struct C : A {}; 9754 // template <class T> struct D : C<T> { using B::foo; } // <--- 9755 // This is invalid (during instantiation) in C++03 because B::foo 9756 // resolves to the using decl in B, which is not a base class of D<T>. 9757 // We can't diagnose it immediately because C<T> is an unknown 9758 // specialization. The UsingShadowDecl in D<T> then points directly 9759 // to A::foo, which will look well-formed when we instantiate. 9760 // The right solution is to not collapse the shadow-decl chain. 9761 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9762 DeclContext *OrigDC = Orig->getDeclContext(); 9763 9764 // Handle enums and anonymous structs. 9765 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9766 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9767 while (OrigRec->isAnonymousStructOrUnion()) 9768 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9769 9770 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9771 if (OrigDC == CurContext) { 9772 Diag(Using->getLocation(), 9773 diag::err_using_decl_nested_name_specifier_is_current_class) 9774 << Using->getQualifierLoc().getSourceRange(); 9775 Diag(Orig->getLocation(), diag::note_using_decl_target); 9776 Using->setInvalidDecl(); 9777 return true; 9778 } 9779 9780 Diag(Using->getQualifierLoc().getBeginLoc(), 9781 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9782 << Using->getQualifier() 9783 << cast<CXXRecordDecl>(CurContext) 9784 << Using->getQualifierLoc().getSourceRange(); 9785 Diag(Orig->getLocation(), diag::note_using_decl_target); 9786 Using->setInvalidDecl(); 9787 return true; 9788 } 9789 } 9790 9791 if (Previous.empty()) return false; 9792 9793 NamedDecl *Target = Orig; 9794 if (isa<UsingShadowDecl>(Target)) 9795 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9796 9797 // If the target happens to be one of the previous declarations, we 9798 // don't have a conflict. 9799 // 9800 // FIXME: but we might be increasing its access, in which case we 9801 // should redeclare it. 9802 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9803 bool FoundEquivalentDecl = false; 9804 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9805 I != E; ++I) { 9806 NamedDecl *D = (*I)->getUnderlyingDecl(); 9807 // We can have UsingDecls in our Previous results because we use the same 9808 // LookupResult for checking whether the UsingDecl itself is a valid 9809 // redeclaration. 9810 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9811 continue; 9812 9813 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9814 // C++ [class.mem]p19: 9815 // If T is the name of a class, then [every named member other than 9816 // a non-static data member] shall have a name different from T 9817 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 9818 !isa<IndirectFieldDecl>(Target) && 9819 !isa<UnresolvedUsingValueDecl>(Target) && 9820 DiagnoseClassNameShadow( 9821 CurContext, 9822 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 9823 return true; 9824 } 9825 9826 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9827 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9828 PrevShadow = Shadow; 9829 FoundEquivalentDecl = true; 9830 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9831 // We don't conflict with an existing using shadow decl of an equivalent 9832 // declaration, but we're not a redeclaration of it. 9833 FoundEquivalentDecl = true; 9834 } 9835 9836 if (isVisible(D)) 9837 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9838 } 9839 9840 if (FoundEquivalentDecl) 9841 return false; 9842 9843 if (FunctionDecl *FD = Target->getAsFunction()) { 9844 NamedDecl *OldDecl = nullptr; 9845 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9846 /*IsForUsingDecl*/ true)) { 9847 case Ovl_Overload: 9848 return false; 9849 9850 case Ovl_NonFunction: 9851 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9852 break; 9853 9854 // We found a decl with the exact signature. 9855 case Ovl_Match: 9856 // If we're in a record, we want to hide the target, so we 9857 // return true (without a diagnostic) to tell the caller not to 9858 // build a shadow decl. 9859 if (CurContext->isRecord()) 9860 return true; 9861 9862 // If we're not in a record, this is an error. 9863 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9864 break; 9865 } 9866 9867 Diag(Target->getLocation(), diag::note_using_decl_target); 9868 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9869 Using->setInvalidDecl(); 9870 return true; 9871 } 9872 9873 // Target is not a function. 9874 9875 if (isa<TagDecl>(Target)) { 9876 // No conflict between a tag and a non-tag. 9877 if (!Tag) return false; 9878 9879 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9880 Diag(Target->getLocation(), diag::note_using_decl_target); 9881 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9882 Using->setInvalidDecl(); 9883 return true; 9884 } 9885 9886 // No conflict between a tag and a non-tag. 9887 if (!NonTag) return false; 9888 9889 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9890 Diag(Target->getLocation(), diag::note_using_decl_target); 9891 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9892 Using->setInvalidDecl(); 9893 return true; 9894 } 9895 9896 /// Determine whether a direct base class is a virtual base class. 9897 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9898 if (!Derived->getNumVBases()) 9899 return false; 9900 for (auto &B : Derived->bases()) 9901 if (B.getType()->getAsCXXRecordDecl() == Base) 9902 return B.isVirtual(); 9903 llvm_unreachable("not a direct base class"); 9904 } 9905 9906 /// Builds a shadow declaration corresponding to a 'using' declaration. 9907 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9908 UsingDecl *UD, 9909 NamedDecl *Orig, 9910 UsingShadowDecl *PrevDecl) { 9911 // If we resolved to another shadow declaration, just coalesce them. 9912 NamedDecl *Target = Orig; 9913 if (isa<UsingShadowDecl>(Target)) { 9914 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9915 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9916 } 9917 9918 NamedDecl *NonTemplateTarget = Target; 9919 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9920 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9921 9922 UsingShadowDecl *Shadow; 9923 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 9924 bool IsVirtualBase = 9925 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9926 UD->getQualifier()->getAsRecordDecl()); 9927 Shadow = ConstructorUsingShadowDecl::Create( 9928 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9929 } else { 9930 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9931 Target); 9932 } 9933 UD->addShadowDecl(Shadow); 9934 9935 Shadow->setAccess(UD->getAccess()); 9936 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9937 Shadow->setInvalidDecl(); 9938 9939 Shadow->setPreviousDecl(PrevDecl); 9940 9941 if (S) 9942 PushOnScopeChains(Shadow, S); 9943 else 9944 CurContext->addDecl(Shadow); 9945 9946 9947 return Shadow; 9948 } 9949 9950 /// Hides a using shadow declaration. This is required by the current 9951 /// using-decl implementation when a resolvable using declaration in a 9952 /// class is followed by a declaration which would hide or override 9953 /// one or more of the using decl's targets; for example: 9954 /// 9955 /// struct Base { void foo(int); }; 9956 /// struct Derived : Base { 9957 /// using Base::foo; 9958 /// void foo(int); 9959 /// }; 9960 /// 9961 /// The governing language is C++03 [namespace.udecl]p12: 9962 /// 9963 /// When a using-declaration brings names from a base class into a 9964 /// derived class scope, member functions in the derived class 9965 /// override and/or hide member functions with the same name and 9966 /// parameter types in a base class (rather than conflicting). 9967 /// 9968 /// There are two ways to implement this: 9969 /// (1) optimistically create shadow decls when they're not hidden 9970 /// by existing declarations, or 9971 /// (2) don't create any shadow decls (or at least don't make them 9972 /// visible) until we've fully parsed/instantiated the class. 9973 /// The problem with (1) is that we might have to retroactively remove 9974 /// a shadow decl, which requires several O(n) operations because the 9975 /// decl structures are (very reasonably) not designed for removal. 9976 /// (2) avoids this but is very fiddly and phase-dependent. 9977 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9978 if (Shadow->getDeclName().getNameKind() == 9979 DeclarationName::CXXConversionFunctionName) 9980 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9981 9982 // Remove it from the DeclContext... 9983 Shadow->getDeclContext()->removeDecl(Shadow); 9984 9985 // ...and the scope, if applicable... 9986 if (S) { 9987 S->RemoveDecl(Shadow); 9988 IdResolver.RemoveDecl(Shadow); 9989 } 9990 9991 // ...and the using decl. 9992 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9993 9994 // TODO: complain somehow if Shadow was used. It shouldn't 9995 // be possible for this to happen, because...? 9996 } 9997 9998 /// Find the base specifier for a base class with the given type. 9999 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 10000 QualType DesiredBase, 10001 bool &AnyDependentBases) { 10002 // Check whether the named type is a direct base class. 10003 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 10004 for (auto &Base : Derived->bases()) { 10005 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 10006 if (CanonicalDesiredBase == BaseType) 10007 return &Base; 10008 if (BaseType->isDependentType()) 10009 AnyDependentBases = true; 10010 } 10011 return nullptr; 10012 } 10013 10014 namespace { 10015 class UsingValidatorCCC final : public CorrectionCandidateCallback { 10016 public: 10017 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 10018 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 10019 : HasTypenameKeyword(HasTypenameKeyword), 10020 IsInstantiation(IsInstantiation), OldNNS(NNS), 10021 RequireMemberOf(RequireMemberOf) {} 10022 10023 bool ValidateCandidate(const TypoCorrection &Candidate) override { 10024 NamedDecl *ND = Candidate.getCorrectionDecl(); 10025 10026 // Keywords are not valid here. 10027 if (!ND || isa<NamespaceDecl>(ND)) 10028 return false; 10029 10030 // Completely unqualified names are invalid for a 'using' declaration. 10031 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 10032 return false; 10033 10034 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 10035 // reject. 10036 10037 if (RequireMemberOf) { 10038 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 10039 if (FoundRecord && FoundRecord->isInjectedClassName()) { 10040 // No-one ever wants a using-declaration to name an injected-class-name 10041 // of a base class, unless they're declaring an inheriting constructor. 10042 ASTContext &Ctx = ND->getASTContext(); 10043 if (!Ctx.getLangOpts().CPlusPlus11) 10044 return false; 10045 QualType FoundType = Ctx.getRecordType(FoundRecord); 10046 10047 // Check that the injected-class-name is named as a member of its own 10048 // type; we don't want to suggest 'using Derived::Base;', since that 10049 // means something else. 10050 NestedNameSpecifier *Specifier = 10051 Candidate.WillReplaceSpecifier() 10052 ? Candidate.getCorrectionSpecifier() 10053 : OldNNS; 10054 if (!Specifier->getAsType() || 10055 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 10056 return false; 10057 10058 // Check that this inheriting constructor declaration actually names a 10059 // direct base class of the current class. 10060 bool AnyDependentBases = false; 10061 if (!findDirectBaseWithType(RequireMemberOf, 10062 Ctx.getRecordType(FoundRecord), 10063 AnyDependentBases) && 10064 !AnyDependentBases) 10065 return false; 10066 } else { 10067 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 10068 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 10069 return false; 10070 10071 // FIXME: Check that the base class member is accessible? 10072 } 10073 } else { 10074 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 10075 if (FoundRecord && FoundRecord->isInjectedClassName()) 10076 return false; 10077 } 10078 10079 if (isa<TypeDecl>(ND)) 10080 return HasTypenameKeyword || !IsInstantiation; 10081 10082 return !HasTypenameKeyword; 10083 } 10084 10085 std::unique_ptr<CorrectionCandidateCallback> clone() override { 10086 return llvm::make_unique<UsingValidatorCCC>(*this); 10087 } 10088 10089 private: 10090 bool HasTypenameKeyword; 10091 bool IsInstantiation; 10092 NestedNameSpecifier *OldNNS; 10093 CXXRecordDecl *RequireMemberOf; 10094 }; 10095 } // end anonymous namespace 10096 10097 /// Builds a using declaration. 10098 /// 10099 /// \param IsInstantiation - Whether this call arises from an 10100 /// instantiation of an unresolved using declaration. We treat 10101 /// the lookup differently for these declarations. 10102 NamedDecl *Sema::BuildUsingDeclaration( 10103 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 10104 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 10105 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 10106 const ParsedAttributesView &AttrList, bool IsInstantiation) { 10107 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 10108 SourceLocation IdentLoc = NameInfo.getLoc(); 10109 assert(IdentLoc.isValid() && "Invalid TargetName location."); 10110 10111 // FIXME: We ignore attributes for now. 10112 10113 // For an inheriting constructor declaration, the name of the using 10114 // declaration is the name of a constructor in this class, not in the 10115 // base class. 10116 DeclarationNameInfo UsingName = NameInfo; 10117 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 10118 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 10119 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10120 Context.getCanonicalType(Context.getRecordType(RD)))); 10121 10122 // Do the redeclaration lookup in the current scope. 10123 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 10124 ForVisibleRedeclaration); 10125 Previous.setHideTags(false); 10126 if (S) { 10127 LookupName(Previous, S); 10128 10129 // It is really dumb that we have to do this. 10130 LookupResult::Filter F = Previous.makeFilter(); 10131 while (F.hasNext()) { 10132 NamedDecl *D = F.next(); 10133 if (!isDeclInScope(D, CurContext, S)) 10134 F.erase(); 10135 // If we found a local extern declaration that's not ordinarily visible, 10136 // and this declaration is being added to a non-block scope, ignore it. 10137 // We're only checking for scope conflicts here, not also for violations 10138 // of the linkage rules. 10139 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 10140 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 10141 F.erase(); 10142 } 10143 F.done(); 10144 } else { 10145 assert(IsInstantiation && "no scope in non-instantiation"); 10146 if (CurContext->isRecord()) 10147 LookupQualifiedName(Previous, CurContext); 10148 else { 10149 // No redeclaration check is needed here; in non-member contexts we 10150 // diagnosed all possible conflicts with other using-declarations when 10151 // building the template: 10152 // 10153 // For a dependent non-type using declaration, the only valid case is 10154 // if we instantiate to a single enumerator. We check for conflicts 10155 // between shadow declarations we introduce, and we check in the template 10156 // definition for conflicts between a non-type using declaration and any 10157 // other declaration, which together covers all cases. 10158 // 10159 // A dependent typename using declaration will never successfully 10160 // instantiate, since it will always name a class member, so we reject 10161 // that in the template definition. 10162 } 10163 } 10164 10165 // Check for invalid redeclarations. 10166 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 10167 SS, IdentLoc, Previous)) 10168 return nullptr; 10169 10170 // Check for bad qualifiers. 10171 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 10172 IdentLoc)) 10173 return nullptr; 10174 10175 DeclContext *LookupContext = computeDeclContext(SS); 10176 NamedDecl *D; 10177 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10178 if (!LookupContext || EllipsisLoc.isValid()) { 10179 if (HasTypenameKeyword) { 10180 // FIXME: not all declaration name kinds are legal here 10181 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 10182 UsingLoc, TypenameLoc, 10183 QualifierLoc, 10184 IdentLoc, NameInfo.getName(), 10185 EllipsisLoc); 10186 } else { 10187 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 10188 QualifierLoc, NameInfo, EllipsisLoc); 10189 } 10190 D->setAccess(AS); 10191 CurContext->addDecl(D); 10192 return D; 10193 } 10194 10195 auto Build = [&](bool Invalid) { 10196 UsingDecl *UD = 10197 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 10198 UsingName, HasTypenameKeyword); 10199 UD->setAccess(AS); 10200 CurContext->addDecl(UD); 10201 UD->setInvalidDecl(Invalid); 10202 return UD; 10203 }; 10204 auto BuildInvalid = [&]{ return Build(true); }; 10205 auto BuildValid = [&]{ return Build(false); }; 10206 10207 if (RequireCompleteDeclContext(SS, LookupContext)) 10208 return BuildInvalid(); 10209 10210 // Look up the target name. 10211 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10212 10213 // Unlike most lookups, we don't always want to hide tag 10214 // declarations: tag names are visible through the using declaration 10215 // even if hidden by ordinary names, *except* in a dependent context 10216 // where it's important for the sanity of two-phase lookup. 10217 if (!IsInstantiation) 10218 R.setHideTags(false); 10219 10220 // For the purposes of this lookup, we have a base object type 10221 // equal to that of the current context. 10222 if (CurContext->isRecord()) { 10223 R.setBaseObjectType( 10224 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 10225 } 10226 10227 LookupQualifiedName(R, LookupContext); 10228 10229 // Try to correct typos if possible. If constructor name lookup finds no 10230 // results, that means the named class has no explicit constructors, and we 10231 // suppressed declaring implicit ones (probably because it's dependent or 10232 // invalid). 10233 if (R.empty() && 10234 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 10235 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 10236 // it will believe that glibc provides a ::gets in cases where it does not, 10237 // and will try to pull it into namespace std with a using-declaration. 10238 // Just ignore the using-declaration in that case. 10239 auto *II = NameInfo.getName().getAsIdentifierInfo(); 10240 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 10241 CurContext->isStdNamespace() && 10242 isa<TranslationUnitDecl>(LookupContext) && 10243 getSourceManager().isInSystemHeader(UsingLoc)) 10244 return nullptr; 10245 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 10246 dyn_cast<CXXRecordDecl>(CurContext)); 10247 if (TypoCorrection Corrected = 10248 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 10249 CTK_ErrorRecovery)) { 10250 // We reject candidates where DroppedSpecifier == true, hence the 10251 // literal '0' below. 10252 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 10253 << NameInfo.getName() << LookupContext << 0 10254 << SS.getRange()); 10255 10256 // If we picked a correction with no attached Decl we can't do anything 10257 // useful with it, bail out. 10258 NamedDecl *ND = Corrected.getCorrectionDecl(); 10259 if (!ND) 10260 return BuildInvalid(); 10261 10262 // If we corrected to an inheriting constructor, handle it as one. 10263 auto *RD = dyn_cast<CXXRecordDecl>(ND); 10264 if (RD && RD->isInjectedClassName()) { 10265 // The parent of the injected class name is the class itself. 10266 RD = cast<CXXRecordDecl>(RD->getParent()); 10267 10268 // Fix up the information we'll use to build the using declaration. 10269 if (Corrected.WillReplaceSpecifier()) { 10270 NestedNameSpecifierLocBuilder Builder; 10271 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 10272 QualifierLoc.getSourceRange()); 10273 QualifierLoc = Builder.getWithLocInContext(Context); 10274 } 10275 10276 // In this case, the name we introduce is the name of a derived class 10277 // constructor. 10278 auto *CurClass = cast<CXXRecordDecl>(CurContext); 10279 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10280 Context.getCanonicalType(Context.getRecordType(CurClass)))); 10281 UsingName.setNamedTypeInfo(nullptr); 10282 for (auto *Ctor : LookupConstructors(RD)) 10283 R.addDecl(Ctor); 10284 R.resolveKind(); 10285 } else { 10286 // FIXME: Pick up all the declarations if we found an overloaded 10287 // function. 10288 UsingName.setName(ND->getDeclName()); 10289 R.addDecl(ND); 10290 } 10291 } else { 10292 Diag(IdentLoc, diag::err_no_member) 10293 << NameInfo.getName() << LookupContext << SS.getRange(); 10294 return BuildInvalid(); 10295 } 10296 } 10297 10298 if (R.isAmbiguous()) 10299 return BuildInvalid(); 10300 10301 if (HasTypenameKeyword) { 10302 // If we asked for a typename and got a non-type decl, error out. 10303 if (!R.getAsSingle<TypeDecl>()) { 10304 Diag(IdentLoc, diag::err_using_typename_non_type); 10305 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10306 Diag((*I)->getUnderlyingDecl()->getLocation(), 10307 diag::note_using_decl_target); 10308 return BuildInvalid(); 10309 } 10310 } else { 10311 // If we asked for a non-typename and we got a type, error out, 10312 // but only if this is an instantiation of an unresolved using 10313 // decl. Otherwise just silently find the type name. 10314 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10315 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10316 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10317 return BuildInvalid(); 10318 } 10319 } 10320 10321 // C++14 [namespace.udecl]p6: 10322 // A using-declaration shall not name a namespace. 10323 if (R.getAsSingle<NamespaceDecl>()) { 10324 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10325 << SS.getRange(); 10326 return BuildInvalid(); 10327 } 10328 10329 // C++14 [namespace.udecl]p7: 10330 // A using-declaration shall not name a scoped enumerator. 10331 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10332 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10333 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10334 << SS.getRange(); 10335 return BuildInvalid(); 10336 } 10337 } 10338 10339 UsingDecl *UD = BuildValid(); 10340 10341 // Some additional rules apply to inheriting constructors. 10342 if (UsingName.getName().getNameKind() == 10343 DeclarationName::CXXConstructorName) { 10344 // Suppress access diagnostics; the access check is instead performed at the 10345 // point of use for an inheriting constructor. 10346 R.suppressDiagnostics(); 10347 if (CheckInheritingConstructorUsingDecl(UD)) 10348 return UD; 10349 } 10350 10351 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10352 UsingShadowDecl *PrevDecl = nullptr; 10353 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10354 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10355 } 10356 10357 return UD; 10358 } 10359 10360 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10361 ArrayRef<NamedDecl *> Expansions) { 10362 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10363 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10364 isa<UsingPackDecl>(InstantiatedFrom)); 10365 10366 auto *UPD = 10367 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10368 UPD->setAccess(InstantiatedFrom->getAccess()); 10369 CurContext->addDecl(UPD); 10370 return UPD; 10371 } 10372 10373 /// Additional checks for a using declaration referring to a constructor name. 10374 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10375 assert(!UD->hasTypename() && "expecting a constructor name"); 10376 10377 const Type *SourceType = UD->getQualifier()->getAsType(); 10378 assert(SourceType && 10379 "Using decl naming constructor doesn't have type in scope spec."); 10380 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10381 10382 // Check whether the named type is a direct base class. 10383 bool AnyDependentBases = false; 10384 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10385 AnyDependentBases); 10386 if (!Base && !AnyDependentBases) { 10387 Diag(UD->getUsingLoc(), 10388 diag::err_using_decl_constructor_not_in_direct_base) 10389 << UD->getNameInfo().getSourceRange() 10390 << QualType(SourceType, 0) << TargetClass; 10391 UD->setInvalidDecl(); 10392 return true; 10393 } 10394 10395 if (Base) 10396 Base->setInheritConstructors(); 10397 10398 return false; 10399 } 10400 10401 /// Checks that the given using declaration is not an invalid 10402 /// redeclaration. Note that this is checking only for the using decl 10403 /// itself, not for any ill-formedness among the UsingShadowDecls. 10404 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10405 bool HasTypenameKeyword, 10406 const CXXScopeSpec &SS, 10407 SourceLocation NameLoc, 10408 const LookupResult &Prev) { 10409 NestedNameSpecifier *Qual = SS.getScopeRep(); 10410 10411 // C++03 [namespace.udecl]p8: 10412 // C++0x [namespace.udecl]p10: 10413 // A using-declaration is a declaration and can therefore be used 10414 // repeatedly where (and only where) multiple declarations are 10415 // allowed. 10416 // 10417 // That's in non-member contexts. 10418 if (!CurContext->getRedeclContext()->isRecord()) { 10419 // A dependent qualifier outside a class can only ever resolve to an 10420 // enumeration type. Therefore it conflicts with any other non-type 10421 // declaration in the same scope. 10422 // FIXME: How should we check for dependent type-type conflicts at block 10423 // scope? 10424 if (Qual->isDependent() && !HasTypenameKeyword) { 10425 for (auto *D : Prev) { 10426 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10427 bool OldCouldBeEnumerator = 10428 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10429 Diag(NameLoc, 10430 OldCouldBeEnumerator ? diag::err_redefinition 10431 : diag::err_redefinition_different_kind) 10432 << Prev.getLookupName(); 10433 Diag(D->getLocation(), diag::note_previous_definition); 10434 return true; 10435 } 10436 } 10437 } 10438 return false; 10439 } 10440 10441 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10442 NamedDecl *D = *I; 10443 10444 bool DTypename; 10445 NestedNameSpecifier *DQual; 10446 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10447 DTypename = UD->hasTypename(); 10448 DQual = UD->getQualifier(); 10449 } else if (UnresolvedUsingValueDecl *UD 10450 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10451 DTypename = false; 10452 DQual = UD->getQualifier(); 10453 } else if (UnresolvedUsingTypenameDecl *UD 10454 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10455 DTypename = true; 10456 DQual = UD->getQualifier(); 10457 } else continue; 10458 10459 // using decls differ if one says 'typename' and the other doesn't. 10460 // FIXME: non-dependent using decls? 10461 if (HasTypenameKeyword != DTypename) continue; 10462 10463 // using decls differ if they name different scopes (but note that 10464 // template instantiation can cause this check to trigger when it 10465 // didn't before instantiation). 10466 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10467 Context.getCanonicalNestedNameSpecifier(DQual)) 10468 continue; 10469 10470 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10471 Diag(D->getLocation(), diag::note_using_decl) << 1; 10472 return true; 10473 } 10474 10475 return false; 10476 } 10477 10478 10479 /// Checks that the given nested-name qualifier used in a using decl 10480 /// in the current context is appropriately related to the current 10481 /// scope. If an error is found, diagnoses it and returns true. 10482 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10483 bool HasTypename, 10484 const CXXScopeSpec &SS, 10485 const DeclarationNameInfo &NameInfo, 10486 SourceLocation NameLoc) { 10487 DeclContext *NamedContext = computeDeclContext(SS); 10488 10489 if (!CurContext->isRecord()) { 10490 // C++03 [namespace.udecl]p3: 10491 // C++0x [namespace.udecl]p8: 10492 // A using-declaration for a class member shall be a member-declaration. 10493 10494 // If we weren't able to compute a valid scope, it might validly be a 10495 // dependent class scope or a dependent enumeration unscoped scope. If 10496 // we have a 'typename' keyword, the scope must resolve to a class type. 10497 if ((HasTypename && !NamedContext) || 10498 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10499 auto *RD = NamedContext 10500 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10501 : nullptr; 10502 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10503 RD = nullptr; 10504 10505 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10506 << SS.getRange(); 10507 10508 // If we have a complete, non-dependent source type, try to suggest a 10509 // way to get the same effect. 10510 if (!RD) 10511 return true; 10512 10513 // Find what this using-declaration was referring to. 10514 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10515 R.setHideTags(false); 10516 R.suppressDiagnostics(); 10517 LookupQualifiedName(R, RD); 10518 10519 if (R.getAsSingle<TypeDecl>()) { 10520 if (getLangOpts().CPlusPlus11) { 10521 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10522 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10523 << 0 // alias declaration 10524 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10525 NameInfo.getName().getAsString() + 10526 " = "); 10527 } else { 10528 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10529 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 10530 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10531 << 1 // typedef declaration 10532 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10533 << FixItHint::CreateInsertion( 10534 InsertLoc, " " + NameInfo.getName().getAsString()); 10535 } 10536 } else if (R.getAsSingle<VarDecl>()) { 10537 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10538 // repeating the type of the static data member here. 10539 FixItHint FixIt; 10540 if (getLangOpts().CPlusPlus11) { 10541 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10542 FixIt = FixItHint::CreateReplacement( 10543 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10544 } 10545 10546 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10547 << 2 // reference declaration 10548 << FixIt; 10549 } else if (R.getAsSingle<EnumConstantDecl>()) { 10550 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10551 // repeating the type of the enumeration here, and we can't do so if 10552 // the type is anonymous. 10553 FixItHint FixIt; 10554 if (getLangOpts().CPlusPlus11) { 10555 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10556 FixIt = FixItHint::CreateReplacement( 10557 UsingLoc, 10558 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10559 } 10560 10561 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10562 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10563 << FixIt; 10564 } 10565 return true; 10566 } 10567 10568 // Otherwise, this might be valid. 10569 return false; 10570 } 10571 10572 // The current scope is a record. 10573 10574 // If the named context is dependent, we can't decide much. 10575 if (!NamedContext) { 10576 // FIXME: in C++0x, we can diagnose if we can prove that the 10577 // nested-name-specifier does not refer to a base class, which is 10578 // still possible in some cases. 10579 10580 // Otherwise we have to conservatively report that things might be 10581 // okay. 10582 return false; 10583 } 10584 10585 if (!NamedContext->isRecord()) { 10586 // Ideally this would point at the last name in the specifier, 10587 // but we don't have that level of source info. 10588 Diag(SS.getRange().getBegin(), 10589 diag::err_using_decl_nested_name_specifier_is_not_class) 10590 << SS.getScopeRep() << SS.getRange(); 10591 return true; 10592 } 10593 10594 if (!NamedContext->isDependentContext() && 10595 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10596 return true; 10597 10598 if (getLangOpts().CPlusPlus11) { 10599 // C++11 [namespace.udecl]p3: 10600 // In a using-declaration used as a member-declaration, the 10601 // nested-name-specifier shall name a base class of the class 10602 // being defined. 10603 10604 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10605 cast<CXXRecordDecl>(NamedContext))) { 10606 if (CurContext == NamedContext) { 10607 Diag(NameLoc, 10608 diag::err_using_decl_nested_name_specifier_is_current_class) 10609 << SS.getRange(); 10610 return true; 10611 } 10612 10613 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10614 Diag(SS.getRange().getBegin(), 10615 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10616 << SS.getScopeRep() 10617 << cast<CXXRecordDecl>(CurContext) 10618 << SS.getRange(); 10619 } 10620 return true; 10621 } 10622 10623 return false; 10624 } 10625 10626 // C++03 [namespace.udecl]p4: 10627 // A using-declaration used as a member-declaration shall refer 10628 // to a member of a base class of the class being defined [etc.]. 10629 10630 // Salient point: SS doesn't have to name a base class as long as 10631 // lookup only finds members from base classes. Therefore we can 10632 // diagnose here only if we can prove that that can't happen, 10633 // i.e. if the class hierarchies provably don't intersect. 10634 10635 // TODO: it would be nice if "definitely valid" results were cached 10636 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10637 // need to be repeated. 10638 10639 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10640 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10641 Bases.insert(Base); 10642 return true; 10643 }; 10644 10645 // Collect all bases. Return false if we find a dependent base. 10646 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10647 return false; 10648 10649 // Returns true if the base is dependent or is one of the accumulated base 10650 // classes. 10651 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10652 return !Bases.count(Base); 10653 }; 10654 10655 // Return false if the class has a dependent base or if it or one 10656 // of its bases is present in the base set of the current context. 10657 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10658 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10659 return false; 10660 10661 Diag(SS.getRange().getBegin(), 10662 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10663 << SS.getScopeRep() 10664 << cast<CXXRecordDecl>(CurContext) 10665 << SS.getRange(); 10666 10667 return true; 10668 } 10669 10670 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 10671 MultiTemplateParamsArg TemplateParamLists, 10672 SourceLocation UsingLoc, UnqualifiedId &Name, 10673 const ParsedAttributesView &AttrList, 10674 TypeResult Type, Decl *DeclFromDeclSpec) { 10675 // Skip up to the relevant declaration scope. 10676 while (S->isTemplateParamScope()) 10677 S = S->getParent(); 10678 assert((S->getFlags() & Scope::DeclScope) && 10679 "got alias-declaration outside of declaration scope"); 10680 10681 if (Type.isInvalid()) 10682 return nullptr; 10683 10684 bool Invalid = false; 10685 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10686 TypeSourceInfo *TInfo = nullptr; 10687 GetTypeFromParser(Type.get(), &TInfo); 10688 10689 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10690 return nullptr; 10691 10692 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10693 UPPC_DeclarationType)) { 10694 Invalid = true; 10695 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10696 TInfo->getTypeLoc().getBeginLoc()); 10697 } 10698 10699 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10700 TemplateParamLists.size() 10701 ? forRedeclarationInCurContext() 10702 : ForVisibleRedeclaration); 10703 LookupName(Previous, S); 10704 10705 // Warn about shadowing the name of a template parameter. 10706 if (Previous.isSingleResult() && 10707 Previous.getFoundDecl()->isTemplateParameter()) { 10708 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10709 Previous.clear(); 10710 } 10711 10712 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10713 "name in alias declaration must be an identifier"); 10714 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10715 Name.StartLocation, 10716 Name.Identifier, TInfo); 10717 10718 NewTD->setAccess(AS); 10719 10720 if (Invalid) 10721 NewTD->setInvalidDecl(); 10722 10723 ProcessDeclAttributeList(S, NewTD, AttrList); 10724 AddPragmaAttributes(S, NewTD); 10725 10726 CheckTypedefForVariablyModifiedType(S, NewTD); 10727 Invalid |= NewTD->isInvalidDecl(); 10728 10729 bool Redeclaration = false; 10730 10731 NamedDecl *NewND; 10732 if (TemplateParamLists.size()) { 10733 TypeAliasTemplateDecl *OldDecl = nullptr; 10734 TemplateParameterList *OldTemplateParams = nullptr; 10735 10736 if (TemplateParamLists.size() != 1) { 10737 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10738 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10739 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10740 } 10741 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10742 10743 // Check that we can declare a template here. 10744 if (CheckTemplateDeclScope(S, TemplateParams)) 10745 return nullptr; 10746 10747 // Only consider previous declarations in the same scope. 10748 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10749 /*ExplicitInstantiationOrSpecialization*/false); 10750 if (!Previous.empty()) { 10751 Redeclaration = true; 10752 10753 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10754 if (!OldDecl && !Invalid) { 10755 Diag(UsingLoc, diag::err_redefinition_different_kind) 10756 << Name.Identifier; 10757 10758 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10759 if (OldD->getLocation().isValid()) 10760 Diag(OldD->getLocation(), diag::note_previous_definition); 10761 10762 Invalid = true; 10763 } 10764 10765 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10766 if (TemplateParameterListsAreEqual(TemplateParams, 10767 OldDecl->getTemplateParameters(), 10768 /*Complain=*/true, 10769 TPL_TemplateMatch)) 10770 OldTemplateParams = 10771 OldDecl->getMostRecentDecl()->getTemplateParameters(); 10772 else 10773 Invalid = true; 10774 10775 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10776 if (!Invalid && 10777 !Context.hasSameType(OldTD->getUnderlyingType(), 10778 NewTD->getUnderlyingType())) { 10779 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10780 // but we can't reasonably accept it. 10781 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10782 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10783 if (OldTD->getLocation().isValid()) 10784 Diag(OldTD->getLocation(), diag::note_previous_definition); 10785 Invalid = true; 10786 } 10787 } 10788 } 10789 10790 // Merge any previous default template arguments into our parameters, 10791 // and check the parameter list. 10792 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10793 TPC_TypeAliasTemplate)) 10794 return nullptr; 10795 10796 TypeAliasTemplateDecl *NewDecl = 10797 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10798 Name.Identifier, TemplateParams, 10799 NewTD); 10800 NewTD->setDescribedAliasTemplate(NewDecl); 10801 10802 NewDecl->setAccess(AS); 10803 10804 if (Invalid) 10805 NewDecl->setInvalidDecl(); 10806 else if (OldDecl) { 10807 NewDecl->setPreviousDecl(OldDecl); 10808 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10809 } 10810 10811 NewND = NewDecl; 10812 } else { 10813 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10814 setTagNameForLinkagePurposes(TD, NewTD); 10815 handleTagNumbering(TD, S); 10816 } 10817 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10818 NewND = NewTD; 10819 } 10820 10821 PushOnScopeChains(NewND, S); 10822 ActOnDocumentableDecl(NewND); 10823 return NewND; 10824 } 10825 10826 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10827 SourceLocation AliasLoc, 10828 IdentifierInfo *Alias, CXXScopeSpec &SS, 10829 SourceLocation IdentLoc, 10830 IdentifierInfo *Ident) { 10831 10832 // Lookup the namespace name. 10833 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10834 LookupParsedName(R, S, &SS); 10835 10836 if (R.isAmbiguous()) 10837 return nullptr; 10838 10839 if (R.empty()) { 10840 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10841 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10842 return nullptr; 10843 } 10844 } 10845 assert(!R.isAmbiguous() && !R.empty()); 10846 NamedDecl *ND = R.getRepresentativeDecl(); 10847 10848 // Check if we have a previous declaration with the same name. 10849 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10850 ForVisibleRedeclaration); 10851 LookupName(PrevR, S); 10852 10853 // Check we're not shadowing a template parameter. 10854 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10855 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10856 PrevR.clear(); 10857 } 10858 10859 // Filter out any other lookup result from an enclosing scope. 10860 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10861 /*AllowInlineNamespace*/false); 10862 10863 // Find the previous declaration and check that we can redeclare it. 10864 NamespaceAliasDecl *Prev = nullptr; 10865 if (PrevR.isSingleResult()) { 10866 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10867 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10868 // We already have an alias with the same name that points to the same 10869 // namespace; check that it matches. 10870 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10871 Prev = AD; 10872 } else if (isVisible(PrevDecl)) { 10873 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10874 << Alias; 10875 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10876 << AD->getNamespace(); 10877 return nullptr; 10878 } 10879 } else if (isVisible(PrevDecl)) { 10880 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10881 ? diag::err_redefinition 10882 : diag::err_redefinition_different_kind; 10883 Diag(AliasLoc, DiagID) << Alias; 10884 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10885 return nullptr; 10886 } 10887 } 10888 10889 // The use of a nested name specifier may trigger deprecation warnings. 10890 DiagnoseUseOfDecl(ND, IdentLoc); 10891 10892 NamespaceAliasDecl *AliasDecl = 10893 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10894 Alias, SS.getWithLocInContext(Context), 10895 IdentLoc, ND); 10896 if (Prev) 10897 AliasDecl->setPreviousDecl(Prev); 10898 10899 PushOnScopeChains(AliasDecl, S); 10900 return AliasDecl; 10901 } 10902 10903 namespace { 10904 struct SpecialMemberExceptionSpecInfo 10905 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10906 SourceLocation Loc; 10907 Sema::ImplicitExceptionSpecification ExceptSpec; 10908 10909 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10910 Sema::CXXSpecialMember CSM, 10911 Sema::InheritedConstructorInfo *ICI, 10912 SourceLocation Loc) 10913 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10914 10915 bool visitBase(CXXBaseSpecifier *Base); 10916 bool visitField(FieldDecl *FD); 10917 10918 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10919 unsigned Quals); 10920 10921 void visitSubobjectCall(Subobject Subobj, 10922 Sema::SpecialMemberOverloadResult SMOR); 10923 }; 10924 } 10925 10926 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10927 auto *RT = Base->getType()->getAs<RecordType>(); 10928 if (!RT) 10929 return false; 10930 10931 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10932 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10933 if (auto *BaseCtor = SMOR.getMethod()) { 10934 visitSubobjectCall(Base, BaseCtor); 10935 return false; 10936 } 10937 10938 visitClassSubobject(BaseClass, Base, 0); 10939 return false; 10940 } 10941 10942 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10943 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10944 Expr *E = FD->getInClassInitializer(); 10945 if (!E) 10946 // FIXME: It's a little wasteful to build and throw away a 10947 // CXXDefaultInitExpr here. 10948 // FIXME: We should have a single context note pointing at Loc, and 10949 // this location should be MD->getLocation() instead, since that's 10950 // the location where we actually use the default init expression. 10951 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10952 if (E) 10953 ExceptSpec.CalledExpr(E); 10954 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10955 ->getAs<RecordType>()) { 10956 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10957 FD->getType().getCVRQualifiers()); 10958 } 10959 return false; 10960 } 10961 10962 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10963 Subobject Subobj, 10964 unsigned Quals) { 10965 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10966 bool IsMutable = Field && Field->isMutable(); 10967 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10968 } 10969 10970 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10971 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10972 // Note, if lookup fails, it doesn't matter what exception specification we 10973 // choose because the special member will be deleted. 10974 if (CXXMethodDecl *MD = SMOR.getMethod()) 10975 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10976 } 10977 10978 namespace { 10979 /// RAII object to register a special member as being currently declared. 10980 struct ComputingExceptionSpec { 10981 Sema &S; 10982 10983 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) 10984 : S(S) { 10985 Sema::CodeSynthesisContext Ctx; 10986 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 10987 Ctx.PointOfInstantiation = Loc; 10988 Ctx.Entity = MD; 10989 S.pushCodeSynthesisContext(Ctx); 10990 } 10991 ~ComputingExceptionSpec() { 10992 S.popCodeSynthesisContext(); 10993 } 10994 }; 10995 } 10996 10997 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 10998 llvm::APSInt Result; 10999 ExprResult Converted = CheckConvertedConstantExpression( 11000 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 11001 ExplicitSpec.setExpr(Converted.get()); 11002 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 11003 ExplicitSpec.setKind(Result.getBoolValue() 11004 ? ExplicitSpecKind::ResolvedTrue 11005 : ExplicitSpecKind::ResolvedFalse); 11006 return true; 11007 } 11008 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 11009 return false; 11010 } 11011 11012 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 11013 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 11014 if (!ExplicitExpr->isTypeDependent()) 11015 tryResolveExplicitSpecifier(ES); 11016 return ES; 11017 } 11018 11019 static Sema::ImplicitExceptionSpecification 11020 ComputeDefaultedSpecialMemberExceptionSpec( 11021 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 11022 Sema::InheritedConstructorInfo *ICI) { 11023 ComputingExceptionSpec CES(S, MD, Loc); 11024 11025 CXXRecordDecl *ClassDecl = MD->getParent(); 11026 11027 // C++ [except.spec]p14: 11028 // An implicitly declared special member function (Clause 12) shall have an 11029 // exception-specification. [...] 11030 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 11031 if (ClassDecl->isInvalidDecl()) 11032 return Info.ExceptSpec; 11033 11034 // FIXME: If this diagnostic fires, we're probably missing a check for 11035 // attempting to resolve an exception specification before it's known 11036 // at a higher level. 11037 if (S.RequireCompleteType(MD->getLocation(), 11038 S.Context.getRecordType(ClassDecl), 11039 diag::err_exception_spec_incomplete_type)) 11040 return Info.ExceptSpec; 11041 11042 // C++1z [except.spec]p7: 11043 // [Look for exceptions thrown by] a constructor selected [...] to 11044 // initialize a potentially constructed subobject, 11045 // C++1z [except.spec]p8: 11046 // The exception specification for an implicitly-declared destructor, or a 11047 // destructor without a noexcept-specifier, is potentially-throwing if and 11048 // only if any of the destructors for any of its potentially constructed 11049 // subojects is potentially throwing. 11050 // FIXME: We respect the first rule but ignore the "potentially constructed" 11051 // in the second rule to resolve a core issue (no number yet) that would have 11052 // us reject: 11053 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 11054 // struct B : A {}; 11055 // struct C : B { void f(); }; 11056 // ... due to giving B::~B() a non-throwing exception specification. 11057 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 11058 : Info.VisitAllBases); 11059 11060 return Info.ExceptSpec; 11061 } 11062 11063 namespace { 11064 /// RAII object to register a special member as being currently declared. 11065 struct DeclaringSpecialMember { 11066 Sema &S; 11067 Sema::SpecialMemberDecl D; 11068 Sema::ContextRAII SavedContext; 11069 bool WasAlreadyBeingDeclared; 11070 11071 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 11072 : S(S), D(RD, CSM), SavedContext(S, RD) { 11073 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 11074 if (WasAlreadyBeingDeclared) 11075 // This almost never happens, but if it does, ensure that our cache 11076 // doesn't contain a stale result. 11077 S.SpecialMemberCache.clear(); 11078 else { 11079 // Register a note to be produced if we encounter an error while 11080 // declaring the special member. 11081 Sema::CodeSynthesisContext Ctx; 11082 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 11083 // FIXME: We don't have a location to use here. Using the class's 11084 // location maintains the fiction that we declare all special members 11085 // with the class, but (1) it's not clear that lying about that helps our 11086 // users understand what's going on, and (2) there may be outer contexts 11087 // on the stack (some of which are relevant) and printing them exposes 11088 // our lies. 11089 Ctx.PointOfInstantiation = RD->getLocation(); 11090 Ctx.Entity = RD; 11091 Ctx.SpecialMember = CSM; 11092 S.pushCodeSynthesisContext(Ctx); 11093 } 11094 } 11095 ~DeclaringSpecialMember() { 11096 if (!WasAlreadyBeingDeclared) { 11097 S.SpecialMembersBeingDeclared.erase(D); 11098 S.popCodeSynthesisContext(); 11099 } 11100 } 11101 11102 /// Are we already trying to declare this special member? 11103 bool isAlreadyBeingDeclared() const { 11104 return WasAlreadyBeingDeclared; 11105 } 11106 }; 11107 } 11108 11109 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 11110 // Look up any existing declarations, but don't trigger declaration of all 11111 // implicit special members with this name. 11112 DeclarationName Name = FD->getDeclName(); 11113 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 11114 ForExternalRedeclaration); 11115 for (auto *D : FD->getParent()->lookup(Name)) 11116 if (auto *Acceptable = R.getAcceptableDecl(D)) 11117 R.addDecl(Acceptable); 11118 R.resolveKind(); 11119 R.suppressDiagnostics(); 11120 11121 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 11122 } 11123 11124 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 11125 QualType ResultTy, 11126 ArrayRef<QualType> Args) { 11127 // Build an exception specification pointing back at this constructor. 11128 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 11129 11130 if (getLangOpts().OpenCLCPlusPlus) { 11131 // OpenCL: Implicitly defaulted special member are of the generic address 11132 // space. 11133 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic); 11134 } 11135 11136 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 11137 SpecialMem->setType(QT); 11138 } 11139 11140 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 11141 CXXRecordDecl *ClassDecl) { 11142 // C++ [class.ctor]p5: 11143 // A default constructor for a class X is a constructor of class X 11144 // that can be called without an argument. If there is no 11145 // user-declared constructor for class X, a default constructor is 11146 // implicitly declared. An implicitly-declared default constructor 11147 // is an inline public member of its class. 11148 assert(ClassDecl->needsImplicitDefaultConstructor() && 11149 "Should not build implicit default constructor!"); 11150 11151 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 11152 if (DSM.isAlreadyBeingDeclared()) 11153 return nullptr; 11154 11155 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11156 CXXDefaultConstructor, 11157 false); 11158 11159 // Create the actual constructor declaration. 11160 CanQualType ClassType 11161 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11162 SourceLocation ClassLoc = ClassDecl->getLocation(); 11163 DeclarationName Name 11164 = Context.DeclarationNames.getCXXConstructorName(ClassType); 11165 DeclarationNameInfo NameInfo(Name, ClassLoc); 11166 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 11167 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 11168 /*TInfo=*/nullptr, ExplicitSpecifier(), 11169 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11170 Constexpr ? CSK_constexpr : CSK_unspecified); 11171 DefaultCon->setAccess(AS_public); 11172 DefaultCon->setDefaulted(); 11173 11174 if (getLangOpts().CUDA) { 11175 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 11176 DefaultCon, 11177 /* ConstRHS */ false, 11178 /* Diagnose */ false); 11179 } 11180 11181 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 11182 11183 // We don't need to use SpecialMemberIsTrivial here; triviality for default 11184 // constructors is easy to compute. 11185 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 11186 11187 // Note that we have declared this constructor. 11188 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 11189 11190 Scope *S = getScopeForContext(ClassDecl); 11191 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 11192 11193 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 11194 SetDeclDeleted(DefaultCon, ClassLoc); 11195 11196 if (S) 11197 PushOnScopeChains(DefaultCon, S, false); 11198 ClassDecl->addDecl(DefaultCon); 11199 11200 return DefaultCon; 11201 } 11202 11203 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 11204 CXXConstructorDecl *Constructor) { 11205 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 11206 !Constructor->doesThisDeclarationHaveABody() && 11207 !Constructor->isDeleted()) && 11208 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 11209 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11210 return; 11211 11212 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11213 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 11214 11215 SynthesizedFunctionScope Scope(*this, Constructor); 11216 11217 // The exception specification is needed because we are defining the 11218 // function. 11219 ResolveExceptionSpec(CurrentLocation, 11220 Constructor->getType()->castAs<FunctionProtoType>()); 11221 MarkVTableUsed(CurrentLocation, ClassDecl); 11222 11223 // Add a context note for diagnostics produced after this point. 11224 Scope.addContextNote(CurrentLocation); 11225 11226 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 11227 Constructor->setInvalidDecl(); 11228 return; 11229 } 11230 11231 SourceLocation Loc = Constructor->getEndLoc().isValid() 11232 ? Constructor->getEndLoc() 11233 : Constructor->getLocation(); 11234 Constructor->setBody(new (Context) CompoundStmt(Loc)); 11235 Constructor->markUsed(Context); 11236 11237 if (ASTMutationListener *L = getASTMutationListener()) { 11238 L->CompletedImplicitDefinition(Constructor); 11239 } 11240 11241 DiagnoseUninitializedFields(*this, Constructor); 11242 } 11243 11244 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 11245 // Perform any delayed checks on exception specifications. 11246 CheckDelayedMemberExceptionSpecs(); 11247 } 11248 11249 /// Find or create the fake constructor we synthesize to model constructing an 11250 /// object of a derived class via a constructor of a base class. 11251 CXXConstructorDecl * 11252 Sema::findInheritingConstructor(SourceLocation Loc, 11253 CXXConstructorDecl *BaseCtor, 11254 ConstructorUsingShadowDecl *Shadow) { 11255 CXXRecordDecl *Derived = Shadow->getParent(); 11256 SourceLocation UsingLoc = Shadow->getLocation(); 11257 11258 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 11259 // For now we use the name of the base class constructor as a member of the 11260 // derived class to indicate a (fake) inherited constructor name. 11261 DeclarationName Name = BaseCtor->getDeclName(); 11262 11263 // Check to see if we already have a fake constructor for this inherited 11264 // constructor call. 11265 for (NamedDecl *Ctor : Derived->lookup(Name)) 11266 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 11267 ->getInheritedConstructor() 11268 .getConstructor(), 11269 BaseCtor)) 11270 return cast<CXXConstructorDecl>(Ctor); 11271 11272 DeclarationNameInfo NameInfo(Name, UsingLoc); 11273 TypeSourceInfo *TInfo = 11274 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 11275 FunctionProtoTypeLoc ProtoLoc = 11276 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 11277 11278 // Check the inherited constructor is valid and find the list of base classes 11279 // from which it was inherited. 11280 InheritedConstructorInfo ICI(*this, Loc, Shadow); 11281 11282 bool Constexpr = 11283 BaseCtor->isConstexpr() && 11284 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 11285 false, BaseCtor, &ICI); 11286 11287 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 11288 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 11289 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 11290 /*isImplicitlyDeclared=*/true, 11291 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 11292 InheritedConstructor(Shadow, BaseCtor)); 11293 if (Shadow->isInvalidDecl()) 11294 DerivedCtor->setInvalidDecl(); 11295 11296 // Build an unevaluated exception specification for this fake constructor. 11297 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 11298 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11299 EPI.ExceptionSpec.Type = EST_Unevaluated; 11300 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 11301 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 11302 FPT->getParamTypes(), EPI)); 11303 11304 // Build the parameter declarations. 11305 SmallVector<ParmVarDecl *, 16> ParamDecls; 11306 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 11307 TypeSourceInfo *TInfo = 11308 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 11309 ParmVarDecl *PD = ParmVarDecl::Create( 11310 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 11311 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 11312 PD->setScopeInfo(0, I); 11313 PD->setImplicit(); 11314 // Ensure attributes are propagated onto parameters (this matters for 11315 // format, pass_object_size, ...). 11316 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 11317 ParamDecls.push_back(PD); 11318 ProtoLoc.setParam(I, PD); 11319 } 11320 11321 // Set up the new constructor. 11322 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 11323 DerivedCtor->setAccess(BaseCtor->getAccess()); 11324 DerivedCtor->setParams(ParamDecls); 11325 Derived->addDecl(DerivedCtor); 11326 11327 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 11328 SetDeclDeleted(DerivedCtor, UsingLoc); 11329 11330 return DerivedCtor; 11331 } 11332 11333 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 11334 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 11335 Ctor->getInheritedConstructor().getShadowDecl()); 11336 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 11337 /*Diagnose*/true); 11338 } 11339 11340 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 11341 CXXConstructorDecl *Constructor) { 11342 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11343 assert(Constructor->getInheritedConstructor() && 11344 !Constructor->doesThisDeclarationHaveABody() && 11345 !Constructor->isDeleted()); 11346 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11347 return; 11348 11349 // Initializations are performed "as if by a defaulted default constructor", 11350 // so enter the appropriate scope. 11351 SynthesizedFunctionScope Scope(*this, Constructor); 11352 11353 // The exception specification is needed because we are defining the 11354 // function. 11355 ResolveExceptionSpec(CurrentLocation, 11356 Constructor->getType()->castAs<FunctionProtoType>()); 11357 MarkVTableUsed(CurrentLocation, ClassDecl); 11358 11359 // Add a context note for diagnostics produced after this point. 11360 Scope.addContextNote(CurrentLocation); 11361 11362 ConstructorUsingShadowDecl *Shadow = 11363 Constructor->getInheritedConstructor().getShadowDecl(); 11364 CXXConstructorDecl *InheritedCtor = 11365 Constructor->getInheritedConstructor().getConstructor(); 11366 11367 // [class.inhctor.init]p1: 11368 // initialization proceeds as if a defaulted default constructor is used to 11369 // initialize the D object and each base class subobject from which the 11370 // constructor was inherited 11371 11372 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11373 CXXRecordDecl *RD = Shadow->getParent(); 11374 SourceLocation InitLoc = Shadow->getLocation(); 11375 11376 // Build explicit initializers for all base classes from which the 11377 // constructor was inherited. 11378 SmallVector<CXXCtorInitializer*, 8> Inits; 11379 for (bool VBase : {false, true}) { 11380 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11381 if (B.isVirtual() != VBase) 11382 continue; 11383 11384 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11385 if (!BaseRD) 11386 continue; 11387 11388 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11389 if (!BaseCtor.first) 11390 continue; 11391 11392 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11393 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11394 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11395 11396 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11397 Inits.push_back(new (Context) CXXCtorInitializer( 11398 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11399 SourceLocation())); 11400 } 11401 } 11402 11403 // We now proceed as if for a defaulted default constructor, with the relevant 11404 // initializers replaced. 11405 11406 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11407 Constructor->setInvalidDecl(); 11408 return; 11409 } 11410 11411 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11412 Constructor->markUsed(Context); 11413 11414 if (ASTMutationListener *L = getASTMutationListener()) { 11415 L->CompletedImplicitDefinition(Constructor); 11416 } 11417 11418 DiagnoseUninitializedFields(*this, Constructor); 11419 } 11420 11421 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11422 // C++ [class.dtor]p2: 11423 // If a class has no user-declared destructor, a destructor is 11424 // declared implicitly. An implicitly-declared destructor is an 11425 // inline public member of its class. 11426 assert(ClassDecl->needsImplicitDestructor()); 11427 11428 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11429 if (DSM.isAlreadyBeingDeclared()) 11430 return nullptr; 11431 11432 // Create the actual destructor declaration. 11433 CanQualType ClassType 11434 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11435 SourceLocation ClassLoc = ClassDecl->getLocation(); 11436 DeclarationName Name 11437 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11438 DeclarationNameInfo NameInfo(Name, ClassLoc); 11439 CXXDestructorDecl *Destructor 11440 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11441 QualType(), nullptr, /*isInline=*/true, 11442 /*isImplicitlyDeclared=*/true); 11443 Destructor->setAccess(AS_public); 11444 Destructor->setDefaulted(); 11445 11446 if (getLangOpts().CUDA) { 11447 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11448 Destructor, 11449 /* ConstRHS */ false, 11450 /* Diagnose */ false); 11451 } 11452 11453 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 11454 11455 // We don't need to use SpecialMemberIsTrivial here; triviality for 11456 // destructors is easy to compute. 11457 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11458 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11459 ClassDecl->hasTrivialDestructorForCall()); 11460 11461 // Note that we have declared this destructor. 11462 ++getASTContext().NumImplicitDestructorsDeclared; 11463 11464 Scope *S = getScopeForContext(ClassDecl); 11465 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11466 11467 // We can't check whether an implicit destructor is deleted before we complete 11468 // the definition of the class, because its validity depends on the alignment 11469 // of the class. We'll check this from ActOnFields once the class is complete. 11470 if (ClassDecl->isCompleteDefinition() && 11471 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11472 SetDeclDeleted(Destructor, ClassLoc); 11473 11474 // Introduce this destructor into its scope. 11475 if (S) 11476 PushOnScopeChains(Destructor, S, false); 11477 ClassDecl->addDecl(Destructor); 11478 11479 return Destructor; 11480 } 11481 11482 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11483 CXXDestructorDecl *Destructor) { 11484 assert((Destructor->isDefaulted() && 11485 !Destructor->doesThisDeclarationHaveABody() && 11486 !Destructor->isDeleted()) && 11487 "DefineImplicitDestructor - call it for implicit default dtor"); 11488 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11489 return; 11490 11491 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11492 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11493 11494 SynthesizedFunctionScope Scope(*this, Destructor); 11495 11496 // The exception specification is needed because we are defining the 11497 // function. 11498 ResolveExceptionSpec(CurrentLocation, 11499 Destructor->getType()->castAs<FunctionProtoType>()); 11500 MarkVTableUsed(CurrentLocation, ClassDecl); 11501 11502 // Add a context note for diagnostics produced after this point. 11503 Scope.addContextNote(CurrentLocation); 11504 11505 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11506 Destructor->getParent()); 11507 11508 if (CheckDestructor(Destructor)) { 11509 Destructor->setInvalidDecl(); 11510 return; 11511 } 11512 11513 SourceLocation Loc = Destructor->getEndLoc().isValid() 11514 ? Destructor->getEndLoc() 11515 : Destructor->getLocation(); 11516 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11517 Destructor->markUsed(Context); 11518 11519 if (ASTMutationListener *L = getASTMutationListener()) { 11520 L->CompletedImplicitDefinition(Destructor); 11521 } 11522 } 11523 11524 /// Perform any semantic analysis which needs to be delayed until all 11525 /// pending class member declarations have been parsed. 11526 void Sema::ActOnFinishCXXMemberDecls() { 11527 // If the context is an invalid C++ class, just suppress these checks. 11528 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11529 if (Record->isInvalidDecl()) { 11530 DelayedOverridingExceptionSpecChecks.clear(); 11531 DelayedEquivalentExceptionSpecChecks.clear(); 11532 return; 11533 } 11534 checkForMultipleExportedDefaultConstructors(*this, Record); 11535 } 11536 } 11537 11538 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11539 referenceDLLExportedClassMethods(); 11540 11541 if (!DelayedDllExportMemberFunctions.empty()) { 11542 SmallVector<CXXMethodDecl*, 4> WorkList; 11543 std::swap(DelayedDllExportMemberFunctions, WorkList); 11544 for (CXXMethodDecl *M : WorkList) { 11545 DefineImplicitSpecialMember(*this, M, M->getLocation()); 11546 11547 // Pass the method to the consumer to get emitted. This is not necessary 11548 // for explicit instantiation definitions, as they will get emitted 11549 // anyway. 11550 if (M->getParent()->getTemplateSpecializationKind() != 11551 TSK_ExplicitInstantiationDefinition) 11552 ActOnFinishInlineFunctionDef(M); 11553 } 11554 } 11555 } 11556 11557 void Sema::referenceDLLExportedClassMethods() { 11558 if (!DelayedDllExportClasses.empty()) { 11559 // Calling ReferenceDllExportedMembers might cause the current function to 11560 // be called again, so use a local copy of DelayedDllExportClasses. 11561 SmallVector<CXXRecordDecl *, 4> WorkList; 11562 std::swap(DelayedDllExportClasses, WorkList); 11563 for (CXXRecordDecl *Class : WorkList) 11564 ReferenceDllExportedMembers(*this, Class); 11565 } 11566 } 11567 11568 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 11569 assert(getLangOpts().CPlusPlus11 && 11570 "adjusting dtor exception specs was introduced in c++11"); 11571 11572 if (Destructor->isDependentContext()) 11573 return; 11574 11575 // C++11 [class.dtor]p3: 11576 // A declaration of a destructor that does not have an exception- 11577 // specification is implicitly considered to have the same exception- 11578 // specification as an implicit declaration. 11579 const FunctionProtoType *DtorType = Destructor->getType()-> 11580 getAs<FunctionProtoType>(); 11581 if (DtorType->hasExceptionSpec()) 11582 return; 11583 11584 // Replace the destructor's type, building off the existing one. Fortunately, 11585 // the only thing of interest in the destructor type is its extended info. 11586 // The return and arguments are fixed. 11587 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11588 EPI.ExceptionSpec.Type = EST_Unevaluated; 11589 EPI.ExceptionSpec.SourceDecl = Destructor; 11590 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11591 11592 // FIXME: If the destructor has a body that could throw, and the newly created 11593 // spec doesn't allow exceptions, we should emit a warning, because this 11594 // change in behavior can break conforming C++03 programs at runtime. 11595 // However, we don't have a body or an exception specification yet, so it 11596 // needs to be done somewhere else. 11597 } 11598 11599 namespace { 11600 /// An abstract base class for all helper classes used in building the 11601 // copy/move operators. These classes serve as factory functions and help us 11602 // avoid using the same Expr* in the AST twice. 11603 class ExprBuilder { 11604 ExprBuilder(const ExprBuilder&) = delete; 11605 ExprBuilder &operator=(const ExprBuilder&) = delete; 11606 11607 protected: 11608 static Expr *assertNotNull(Expr *E) { 11609 assert(E && "Expression construction must not fail."); 11610 return E; 11611 } 11612 11613 public: 11614 ExprBuilder() {} 11615 virtual ~ExprBuilder() {} 11616 11617 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11618 }; 11619 11620 class RefBuilder: public ExprBuilder { 11621 VarDecl *Var; 11622 QualType VarType; 11623 11624 public: 11625 Expr *build(Sema &S, SourceLocation Loc) const override { 11626 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 11627 } 11628 11629 RefBuilder(VarDecl *Var, QualType VarType) 11630 : Var(Var), VarType(VarType) {} 11631 }; 11632 11633 class ThisBuilder: public ExprBuilder { 11634 public: 11635 Expr *build(Sema &S, SourceLocation Loc) const override { 11636 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11637 } 11638 }; 11639 11640 class CastBuilder: public ExprBuilder { 11641 const ExprBuilder &Builder; 11642 QualType Type; 11643 ExprValueKind Kind; 11644 const CXXCastPath &Path; 11645 11646 public: 11647 Expr *build(Sema &S, SourceLocation Loc) const override { 11648 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11649 CK_UncheckedDerivedToBase, Kind, 11650 &Path).get()); 11651 } 11652 11653 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11654 const CXXCastPath &Path) 11655 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11656 }; 11657 11658 class DerefBuilder: public ExprBuilder { 11659 const ExprBuilder &Builder; 11660 11661 public: 11662 Expr *build(Sema &S, SourceLocation Loc) const override { 11663 return assertNotNull( 11664 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11665 } 11666 11667 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11668 }; 11669 11670 class MemberBuilder: public ExprBuilder { 11671 const ExprBuilder &Builder; 11672 QualType Type; 11673 CXXScopeSpec SS; 11674 bool IsArrow; 11675 LookupResult &MemberLookup; 11676 11677 public: 11678 Expr *build(Sema &S, SourceLocation Loc) const override { 11679 return assertNotNull(S.BuildMemberReferenceExpr( 11680 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11681 nullptr, MemberLookup, nullptr, nullptr).get()); 11682 } 11683 11684 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11685 LookupResult &MemberLookup) 11686 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11687 MemberLookup(MemberLookup) {} 11688 }; 11689 11690 class MoveCastBuilder: public ExprBuilder { 11691 const ExprBuilder &Builder; 11692 11693 public: 11694 Expr *build(Sema &S, SourceLocation Loc) const override { 11695 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11696 } 11697 11698 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11699 }; 11700 11701 class LvalueConvBuilder: public ExprBuilder { 11702 const ExprBuilder &Builder; 11703 11704 public: 11705 Expr *build(Sema &S, SourceLocation Loc) const override { 11706 return assertNotNull( 11707 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11708 } 11709 11710 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11711 }; 11712 11713 class SubscriptBuilder: public ExprBuilder { 11714 const ExprBuilder &Base; 11715 const ExprBuilder &Index; 11716 11717 public: 11718 Expr *build(Sema &S, SourceLocation Loc) const override { 11719 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11720 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11721 } 11722 11723 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11724 : Base(Base), Index(Index) {} 11725 }; 11726 11727 } // end anonymous namespace 11728 11729 /// When generating a defaulted copy or move assignment operator, if a field 11730 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11731 /// do so. This optimization only applies for arrays of scalars, and for arrays 11732 /// of class type where the selected copy/move-assignment operator is trivial. 11733 static StmtResult 11734 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11735 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11736 // Compute the size of the memory buffer to be copied. 11737 QualType SizeType = S.Context.getSizeType(); 11738 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11739 S.Context.getTypeSizeInChars(T).getQuantity()); 11740 11741 // Take the address of the field references for "from" and "to". We 11742 // directly construct UnaryOperators here because semantic analysis 11743 // does not permit us to take the address of an xvalue. 11744 Expr *From = FromB.build(S, Loc); 11745 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11746 S.Context.getPointerType(From->getType()), 11747 VK_RValue, OK_Ordinary, Loc, false); 11748 Expr *To = ToB.build(S, Loc); 11749 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11750 S.Context.getPointerType(To->getType()), 11751 VK_RValue, OK_Ordinary, Loc, false); 11752 11753 const Type *E = T->getBaseElementTypeUnsafe(); 11754 bool NeedsCollectableMemCpy = 11755 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11756 11757 // Create a reference to the __builtin_objc_memmove_collectable function 11758 StringRef MemCpyName = NeedsCollectableMemCpy ? 11759 "__builtin_objc_memmove_collectable" : 11760 "__builtin_memcpy"; 11761 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11762 Sema::LookupOrdinaryName); 11763 S.LookupName(R, S.TUScope, true); 11764 11765 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11766 if (!MemCpy) 11767 // Something went horribly wrong earlier, and we will have complained 11768 // about it. 11769 return StmtError(); 11770 11771 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11772 VK_RValue, Loc, nullptr); 11773 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11774 11775 Expr *CallArgs[] = { 11776 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11777 }; 11778 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11779 Loc, CallArgs, Loc); 11780 11781 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11782 return Call.getAs<Stmt>(); 11783 } 11784 11785 /// Builds a statement that copies/moves the given entity from \p From to 11786 /// \c To. 11787 /// 11788 /// This routine is used to copy/move the members of a class with an 11789 /// implicitly-declared copy/move assignment operator. When the entities being 11790 /// copied are arrays, this routine builds for loops to copy them. 11791 /// 11792 /// \param S The Sema object used for type-checking. 11793 /// 11794 /// \param Loc The location where the implicit copy/move is being generated. 11795 /// 11796 /// \param T The type of the expressions being copied/moved. Both expressions 11797 /// must have this type. 11798 /// 11799 /// \param To The expression we are copying/moving to. 11800 /// 11801 /// \param From The expression we are copying/moving from. 11802 /// 11803 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11804 /// Otherwise, it's a non-static member subobject. 11805 /// 11806 /// \param Copying Whether we're copying or moving. 11807 /// 11808 /// \param Depth Internal parameter recording the depth of the recursion. 11809 /// 11810 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11811 /// if a memcpy should be used instead. 11812 static StmtResult 11813 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11814 const ExprBuilder &To, const ExprBuilder &From, 11815 bool CopyingBaseSubobject, bool Copying, 11816 unsigned Depth = 0) { 11817 // C++11 [class.copy]p28: 11818 // Each subobject is assigned in the manner appropriate to its type: 11819 // 11820 // - if the subobject is of class type, as if by a call to operator= with 11821 // the subobject as the object expression and the corresponding 11822 // subobject of x as a single function argument (as if by explicit 11823 // qualification; that is, ignoring any possible virtual overriding 11824 // functions in more derived classes); 11825 // 11826 // C++03 [class.copy]p13: 11827 // - if the subobject is of class type, the copy assignment operator for 11828 // the class is used (as if by explicit qualification; that is, 11829 // ignoring any possible virtual overriding functions in more derived 11830 // classes); 11831 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11832 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11833 11834 // Look for operator=. 11835 DeclarationName Name 11836 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11837 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11838 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11839 11840 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11841 // operator. 11842 if (!S.getLangOpts().CPlusPlus11) { 11843 LookupResult::Filter F = OpLookup.makeFilter(); 11844 while (F.hasNext()) { 11845 NamedDecl *D = F.next(); 11846 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11847 if (Method->isCopyAssignmentOperator() || 11848 (!Copying && Method->isMoveAssignmentOperator())) 11849 continue; 11850 11851 F.erase(); 11852 } 11853 F.done(); 11854 } 11855 11856 // Suppress the protected check (C++ [class.protected]) for each of the 11857 // assignment operators we found. This strange dance is required when 11858 // we're assigning via a base classes's copy-assignment operator. To 11859 // ensure that we're getting the right base class subobject (without 11860 // ambiguities), we need to cast "this" to that subobject type; to 11861 // ensure that we don't go through the virtual call mechanism, we need 11862 // to qualify the operator= name with the base class (see below). However, 11863 // this means that if the base class has a protected copy assignment 11864 // operator, the protected member access check will fail. So, we 11865 // rewrite "protected" access to "public" access in this case, since we 11866 // know by construction that we're calling from a derived class. 11867 if (CopyingBaseSubobject) { 11868 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11869 L != LEnd; ++L) { 11870 if (L.getAccess() == AS_protected) 11871 L.setAccess(AS_public); 11872 } 11873 } 11874 11875 // Create the nested-name-specifier that will be used to qualify the 11876 // reference to operator=; this is required to suppress the virtual 11877 // call mechanism. 11878 CXXScopeSpec SS; 11879 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11880 SS.MakeTrivial(S.Context, 11881 NestedNameSpecifier::Create(S.Context, nullptr, false, 11882 CanonicalT), 11883 Loc); 11884 11885 // Create the reference to operator=. 11886 ExprResult OpEqualRef 11887 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 11888 SS, /*TemplateKWLoc=*/SourceLocation(), 11889 /*FirstQualifierInScope=*/nullptr, 11890 OpLookup, 11891 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11892 /*SuppressQualifierCheck=*/true); 11893 if (OpEqualRef.isInvalid()) 11894 return StmtError(); 11895 11896 // Build the call to the assignment operator. 11897 11898 Expr *FromInst = From.build(S, Loc); 11899 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11900 OpEqualRef.getAs<Expr>(), 11901 Loc, FromInst, Loc); 11902 if (Call.isInvalid()) 11903 return StmtError(); 11904 11905 // If we built a call to a trivial 'operator=' while copying an array, 11906 // bail out. We'll replace the whole shebang with a memcpy. 11907 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11908 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11909 return StmtResult((Stmt*)nullptr); 11910 11911 // Convert to an expression-statement, and clean up any produced 11912 // temporaries. 11913 return S.ActOnExprStmt(Call); 11914 } 11915 11916 // - if the subobject is of scalar type, the built-in assignment 11917 // operator is used. 11918 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11919 if (!ArrayTy) { 11920 ExprResult Assignment = S.CreateBuiltinBinOp( 11921 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11922 if (Assignment.isInvalid()) 11923 return StmtError(); 11924 return S.ActOnExprStmt(Assignment); 11925 } 11926 11927 // - if the subobject is an array, each element is assigned, in the 11928 // manner appropriate to the element type; 11929 11930 // Construct a loop over the array bounds, e.g., 11931 // 11932 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11933 // 11934 // that will copy each of the array elements. 11935 QualType SizeType = S.Context.getSizeType(); 11936 11937 // Create the iteration variable. 11938 IdentifierInfo *IterationVarName = nullptr; 11939 { 11940 SmallString<8> Str; 11941 llvm::raw_svector_ostream OS(Str); 11942 OS << "__i" << Depth; 11943 IterationVarName = &S.Context.Idents.get(OS.str()); 11944 } 11945 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11946 IterationVarName, SizeType, 11947 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11948 SC_None); 11949 11950 // Initialize the iteration variable to zero. 11951 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11952 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11953 11954 // Creates a reference to the iteration variable. 11955 RefBuilder IterationVarRef(IterationVar, SizeType); 11956 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11957 11958 // Create the DeclStmt that holds the iteration variable. 11959 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11960 11961 // Subscript the "from" and "to" expressions with the iteration variable. 11962 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11963 MoveCastBuilder FromIndexMove(FromIndexCopy); 11964 const ExprBuilder *FromIndex; 11965 if (Copying) 11966 FromIndex = &FromIndexCopy; 11967 else 11968 FromIndex = &FromIndexMove; 11969 11970 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11971 11972 // Build the copy/move for an individual element of the array. 11973 StmtResult Copy = 11974 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11975 ToIndex, *FromIndex, CopyingBaseSubobject, 11976 Copying, Depth + 1); 11977 // Bail out if copying fails or if we determined that we should use memcpy. 11978 if (Copy.isInvalid() || !Copy.get()) 11979 return Copy; 11980 11981 // Create the comparison against the array bound. 11982 llvm::APInt Upper 11983 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11984 Expr *Comparison 11985 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11986 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11987 BO_NE, S.Context.BoolTy, 11988 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11989 11990 // Create the pre-increment of the iteration variable. We can determine 11991 // whether the increment will overflow based on the value of the array 11992 // bound. 11993 Expr *Increment = new (S.Context) 11994 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11995 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11996 11997 // Construct the loop that copies all elements of this array. 11998 return S.ActOnForStmt( 11999 Loc, Loc, InitStmt, 12000 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 12001 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 12002 } 12003 12004 static StmtResult 12005 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 12006 const ExprBuilder &To, const ExprBuilder &From, 12007 bool CopyingBaseSubobject, bool Copying) { 12008 // Maybe we should use a memcpy? 12009 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 12010 T.isTriviallyCopyableType(S.Context)) 12011 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 12012 12013 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 12014 CopyingBaseSubobject, 12015 Copying, 0)); 12016 12017 // If we ended up picking a trivial assignment operator for an array of a 12018 // non-trivially-copyable class type, just emit a memcpy. 12019 if (!Result.isInvalid() && !Result.get()) 12020 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 12021 12022 return Result; 12023 } 12024 12025 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 12026 // Note: The following rules are largely analoguous to the copy 12027 // constructor rules. Note that virtual bases are not taken into account 12028 // for determining the argument type of the operator. Note also that 12029 // operators taking an object instead of a reference are allowed. 12030 assert(ClassDecl->needsImplicitCopyAssignment()); 12031 12032 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 12033 if (DSM.isAlreadyBeingDeclared()) 12034 return nullptr; 12035 12036 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12037 if (Context.getLangOpts().OpenCLCPlusPlus) 12038 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12039 QualType RetType = Context.getLValueReferenceType(ArgType); 12040 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 12041 if (Const) 12042 ArgType = ArgType.withConst(); 12043 12044 ArgType = Context.getLValueReferenceType(ArgType); 12045 12046 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12047 CXXCopyAssignment, 12048 Const); 12049 12050 // An implicitly-declared copy assignment operator is an inline public 12051 // member of its class. 12052 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12053 SourceLocation ClassLoc = ClassDecl->getLocation(); 12054 DeclarationNameInfo NameInfo(Name, ClassLoc); 12055 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 12056 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12057 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12058 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 12059 SourceLocation()); 12060 CopyAssignment->setAccess(AS_public); 12061 CopyAssignment->setDefaulted(); 12062 CopyAssignment->setImplicit(); 12063 12064 if (getLangOpts().CUDA) { 12065 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 12066 CopyAssignment, 12067 /* ConstRHS */ Const, 12068 /* Diagnose */ false); 12069 } 12070 12071 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 12072 12073 // Add the parameter to the operator. 12074 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 12075 ClassLoc, ClassLoc, 12076 /*Id=*/nullptr, ArgType, 12077 /*TInfo=*/nullptr, SC_None, 12078 nullptr); 12079 CopyAssignment->setParams(FromParam); 12080 12081 CopyAssignment->setTrivial( 12082 ClassDecl->needsOverloadResolutionForCopyAssignment() 12083 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 12084 : ClassDecl->hasTrivialCopyAssignment()); 12085 12086 // Note that we have added this copy-assignment operator. 12087 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 12088 12089 Scope *S = getScopeForContext(ClassDecl); 12090 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 12091 12092 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 12093 SetDeclDeleted(CopyAssignment, ClassLoc); 12094 12095 if (S) 12096 PushOnScopeChains(CopyAssignment, S, false); 12097 ClassDecl->addDecl(CopyAssignment); 12098 12099 return CopyAssignment; 12100 } 12101 12102 /// Diagnose an implicit copy operation for a class which is odr-used, but 12103 /// which is deprecated because the class has a user-declared copy constructor, 12104 /// copy assignment operator, or destructor. 12105 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 12106 assert(CopyOp->isImplicit()); 12107 12108 CXXRecordDecl *RD = CopyOp->getParent(); 12109 CXXMethodDecl *UserDeclaredOperation = nullptr; 12110 12111 // In Microsoft mode, assignment operations don't affect constructors and 12112 // vice versa. 12113 if (RD->hasUserDeclaredDestructor()) { 12114 UserDeclaredOperation = RD->getDestructor(); 12115 } else if (!isa<CXXConstructorDecl>(CopyOp) && 12116 RD->hasUserDeclaredCopyConstructor() && 12117 !S.getLangOpts().MSVCCompat) { 12118 // Find any user-declared copy constructor. 12119 for (auto *I : RD->ctors()) { 12120 if (I->isCopyConstructor()) { 12121 UserDeclaredOperation = I; 12122 break; 12123 } 12124 } 12125 assert(UserDeclaredOperation); 12126 } else if (isa<CXXConstructorDecl>(CopyOp) && 12127 RD->hasUserDeclaredCopyAssignment() && 12128 !S.getLangOpts().MSVCCompat) { 12129 // Find any user-declared move assignment operator. 12130 for (auto *I : RD->methods()) { 12131 if (I->isCopyAssignmentOperator()) { 12132 UserDeclaredOperation = I; 12133 break; 12134 } 12135 } 12136 assert(UserDeclaredOperation); 12137 } 12138 12139 if (UserDeclaredOperation) { 12140 S.Diag(UserDeclaredOperation->getLocation(), 12141 diag::warn_deprecated_copy_operation) 12142 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 12143 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 12144 } 12145 } 12146 12147 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 12148 CXXMethodDecl *CopyAssignOperator) { 12149 assert((CopyAssignOperator->isDefaulted() && 12150 CopyAssignOperator->isOverloadedOperator() && 12151 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 12152 !CopyAssignOperator->doesThisDeclarationHaveABody() && 12153 !CopyAssignOperator->isDeleted()) && 12154 "DefineImplicitCopyAssignment called for wrong function"); 12155 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 12156 return; 12157 12158 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 12159 if (ClassDecl->isInvalidDecl()) { 12160 CopyAssignOperator->setInvalidDecl(); 12161 return; 12162 } 12163 12164 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 12165 12166 // The exception specification is needed because we are defining the 12167 // function. 12168 ResolveExceptionSpec(CurrentLocation, 12169 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 12170 12171 // Add a context note for diagnostics produced after this point. 12172 Scope.addContextNote(CurrentLocation); 12173 12174 // C++11 [class.copy]p18: 12175 // The [definition of an implicitly declared copy assignment operator] is 12176 // deprecated if the class has a user-declared copy constructor or a 12177 // user-declared destructor. 12178 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 12179 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 12180 12181 // C++0x [class.copy]p30: 12182 // The implicitly-defined or explicitly-defaulted copy assignment operator 12183 // for a non-union class X performs memberwise copy assignment of its 12184 // subobjects. The direct base classes of X are assigned first, in the 12185 // order of their declaration in the base-specifier-list, and then the 12186 // immediate non-static data members of X are assigned, in the order in 12187 // which they were declared in the class definition. 12188 12189 // The statements that form the synthesized function body. 12190 SmallVector<Stmt*, 8> Statements; 12191 12192 // The parameter for the "other" object, which we are copying from. 12193 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 12194 Qualifiers OtherQuals = Other->getType().getQualifiers(); 12195 QualType OtherRefType = Other->getType(); 12196 if (const LValueReferenceType *OtherRef 12197 = OtherRefType->getAs<LValueReferenceType>()) { 12198 OtherRefType = OtherRef->getPointeeType(); 12199 OtherQuals = OtherRefType.getQualifiers(); 12200 } 12201 12202 // Our location for everything implicitly-generated. 12203 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 12204 ? CopyAssignOperator->getEndLoc() 12205 : CopyAssignOperator->getLocation(); 12206 12207 // Builds a DeclRefExpr for the "other" object. 12208 RefBuilder OtherRef(Other, OtherRefType); 12209 12210 // Builds the "this" pointer. 12211 ThisBuilder This; 12212 12213 // Assign base classes. 12214 bool Invalid = false; 12215 for (auto &Base : ClassDecl->bases()) { 12216 // Form the assignment: 12217 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 12218 QualType BaseType = Base.getType().getUnqualifiedType(); 12219 if (!BaseType->isRecordType()) { 12220 Invalid = true; 12221 continue; 12222 } 12223 12224 CXXCastPath BasePath; 12225 BasePath.push_back(&Base); 12226 12227 // Construct the "from" expression, which is an implicit cast to the 12228 // appropriately-qualified base type. 12229 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 12230 VK_LValue, BasePath); 12231 12232 // Dereference "this". 12233 DerefBuilder DerefThis(This); 12234 CastBuilder To(DerefThis, 12235 Context.getQualifiedType( 12236 BaseType, CopyAssignOperator->getMethodQualifiers()), 12237 VK_LValue, BasePath); 12238 12239 // Build the copy. 12240 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 12241 To, From, 12242 /*CopyingBaseSubobject=*/true, 12243 /*Copying=*/true); 12244 if (Copy.isInvalid()) { 12245 CopyAssignOperator->setInvalidDecl(); 12246 return; 12247 } 12248 12249 // Success! Record the copy. 12250 Statements.push_back(Copy.getAs<Expr>()); 12251 } 12252 12253 // Assign non-static members. 12254 for (auto *Field : ClassDecl->fields()) { 12255 // FIXME: We should form some kind of AST representation for the implied 12256 // memcpy in a union copy operation. 12257 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12258 continue; 12259 12260 if (Field->isInvalidDecl()) { 12261 Invalid = true; 12262 continue; 12263 } 12264 12265 // Check for members of reference type; we can't copy those. 12266 if (Field->getType()->isReferenceType()) { 12267 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12268 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12269 Diag(Field->getLocation(), diag::note_declared_at); 12270 Invalid = true; 12271 continue; 12272 } 12273 12274 // Check for members of const-qualified, non-class type. 12275 QualType BaseType = Context.getBaseElementType(Field->getType()); 12276 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12277 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12278 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12279 Diag(Field->getLocation(), diag::note_declared_at); 12280 Invalid = true; 12281 continue; 12282 } 12283 12284 // Suppress assigning zero-width bitfields. 12285 if (Field->isZeroLengthBitField(Context)) 12286 continue; 12287 12288 QualType FieldType = Field->getType().getNonReferenceType(); 12289 if (FieldType->isIncompleteArrayType()) { 12290 assert(ClassDecl->hasFlexibleArrayMember() && 12291 "Incomplete array type is not valid"); 12292 continue; 12293 } 12294 12295 // Build references to the field in the object we're copying from and to. 12296 CXXScopeSpec SS; // Intentionally empty 12297 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12298 LookupMemberName); 12299 MemberLookup.addDecl(Field); 12300 MemberLookup.resolveKind(); 12301 12302 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 12303 12304 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 12305 12306 // Build the copy of this field. 12307 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 12308 To, From, 12309 /*CopyingBaseSubobject=*/false, 12310 /*Copying=*/true); 12311 if (Copy.isInvalid()) { 12312 CopyAssignOperator->setInvalidDecl(); 12313 return; 12314 } 12315 12316 // Success! Record the copy. 12317 Statements.push_back(Copy.getAs<Stmt>()); 12318 } 12319 12320 if (!Invalid) { 12321 // Add a "return *this;" 12322 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12323 12324 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12325 if (Return.isInvalid()) 12326 Invalid = true; 12327 else 12328 Statements.push_back(Return.getAs<Stmt>()); 12329 } 12330 12331 if (Invalid) { 12332 CopyAssignOperator->setInvalidDecl(); 12333 return; 12334 } 12335 12336 StmtResult Body; 12337 { 12338 CompoundScopeRAII CompoundScope(*this); 12339 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12340 /*isStmtExpr=*/false); 12341 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12342 } 12343 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 12344 CopyAssignOperator->markUsed(Context); 12345 12346 if (ASTMutationListener *L = getASTMutationListener()) { 12347 L->CompletedImplicitDefinition(CopyAssignOperator); 12348 } 12349 } 12350 12351 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 12352 assert(ClassDecl->needsImplicitMoveAssignment()); 12353 12354 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 12355 if (DSM.isAlreadyBeingDeclared()) 12356 return nullptr; 12357 12358 // Note: The following rules are largely analoguous to the move 12359 // constructor rules. 12360 12361 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12362 if (Context.getLangOpts().OpenCLCPlusPlus) 12363 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12364 QualType RetType = Context.getLValueReferenceType(ArgType); 12365 ArgType = Context.getRValueReferenceType(ArgType); 12366 12367 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12368 CXXMoveAssignment, 12369 false); 12370 12371 // An implicitly-declared move assignment operator is an inline public 12372 // member of its class. 12373 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12374 SourceLocation ClassLoc = ClassDecl->getLocation(); 12375 DeclarationNameInfo NameInfo(Name, ClassLoc); 12376 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 12377 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12378 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12379 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 12380 SourceLocation()); 12381 MoveAssignment->setAccess(AS_public); 12382 MoveAssignment->setDefaulted(); 12383 MoveAssignment->setImplicit(); 12384 12385 if (getLangOpts().CUDA) { 12386 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12387 MoveAssignment, 12388 /* ConstRHS */ false, 12389 /* Diagnose */ false); 12390 } 12391 12392 // Build an exception specification pointing back at this member. 12393 FunctionProtoType::ExtProtoInfo EPI = 12394 getImplicitMethodEPI(*this, MoveAssignment); 12395 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12396 12397 // Add the parameter to the operator. 12398 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12399 ClassLoc, ClassLoc, 12400 /*Id=*/nullptr, ArgType, 12401 /*TInfo=*/nullptr, SC_None, 12402 nullptr); 12403 MoveAssignment->setParams(FromParam); 12404 12405 MoveAssignment->setTrivial( 12406 ClassDecl->needsOverloadResolutionForMoveAssignment() 12407 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12408 : ClassDecl->hasTrivialMoveAssignment()); 12409 12410 // Note that we have added this copy-assignment operator. 12411 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 12412 12413 Scope *S = getScopeForContext(ClassDecl); 12414 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12415 12416 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12417 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12418 SetDeclDeleted(MoveAssignment, ClassLoc); 12419 } 12420 12421 if (S) 12422 PushOnScopeChains(MoveAssignment, S, false); 12423 ClassDecl->addDecl(MoveAssignment); 12424 12425 return MoveAssignment; 12426 } 12427 12428 /// Check if we're implicitly defining a move assignment operator for a class 12429 /// with virtual bases. Such a move assignment might move-assign the virtual 12430 /// base multiple times. 12431 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12432 SourceLocation CurrentLocation) { 12433 assert(!Class->isDependentContext() && "should not define dependent move"); 12434 12435 // Only a virtual base could get implicitly move-assigned multiple times. 12436 // Only a non-trivial move assignment can observe this. We only want to 12437 // diagnose if we implicitly define an assignment operator that assigns 12438 // two base classes, both of which move-assign the same virtual base. 12439 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12440 Class->getNumBases() < 2) 12441 return; 12442 12443 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12444 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12445 VBaseMap VBases; 12446 12447 for (auto &BI : Class->bases()) { 12448 Worklist.push_back(&BI); 12449 while (!Worklist.empty()) { 12450 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12451 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12452 12453 // If the base has no non-trivial move assignment operators, 12454 // we don't care about moves from it. 12455 if (!Base->hasNonTrivialMoveAssignment()) 12456 continue; 12457 12458 // If there's nothing virtual here, skip it. 12459 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12460 continue; 12461 12462 // If we're not actually going to call a move assignment for this base, 12463 // or the selected move assignment is trivial, skip it. 12464 Sema::SpecialMemberOverloadResult SMOR = 12465 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12466 /*ConstArg*/false, /*VolatileArg*/false, 12467 /*RValueThis*/true, /*ConstThis*/false, 12468 /*VolatileThis*/false); 12469 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12470 !SMOR.getMethod()->isMoveAssignmentOperator()) 12471 continue; 12472 12473 if (BaseSpec->isVirtual()) { 12474 // We're going to move-assign this virtual base, and its move 12475 // assignment operator is not trivial. If this can happen for 12476 // multiple distinct direct bases of Class, diagnose it. (If it 12477 // only happens in one base, we'll diagnose it when synthesizing 12478 // that base class's move assignment operator.) 12479 CXXBaseSpecifier *&Existing = 12480 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12481 .first->second; 12482 if (Existing && Existing != &BI) { 12483 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12484 << Class << Base; 12485 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 12486 << (Base->getCanonicalDecl() == 12487 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12488 << Base << Existing->getType() << Existing->getSourceRange(); 12489 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 12490 << (Base->getCanonicalDecl() == 12491 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12492 << Base << BI.getType() << BaseSpec->getSourceRange(); 12493 12494 // Only diagnose each vbase once. 12495 Existing = nullptr; 12496 } 12497 } else { 12498 // Only walk over bases that have defaulted move assignment operators. 12499 // We assume that any user-provided move assignment operator handles 12500 // the multiple-moves-of-vbase case itself somehow. 12501 if (!SMOR.getMethod()->isDefaulted()) 12502 continue; 12503 12504 // We're going to move the base classes of Base. Add them to the list. 12505 for (auto &BI : Base->bases()) 12506 Worklist.push_back(&BI); 12507 } 12508 } 12509 } 12510 } 12511 12512 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12513 CXXMethodDecl *MoveAssignOperator) { 12514 assert((MoveAssignOperator->isDefaulted() && 12515 MoveAssignOperator->isOverloadedOperator() && 12516 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12517 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12518 !MoveAssignOperator->isDeleted()) && 12519 "DefineImplicitMoveAssignment called for wrong function"); 12520 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12521 return; 12522 12523 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12524 if (ClassDecl->isInvalidDecl()) { 12525 MoveAssignOperator->setInvalidDecl(); 12526 return; 12527 } 12528 12529 // C++0x [class.copy]p28: 12530 // The implicitly-defined or move assignment operator for a non-union class 12531 // X performs memberwise move assignment of its subobjects. The direct base 12532 // classes of X are assigned first, in the order of their declaration in the 12533 // base-specifier-list, and then the immediate non-static data members of X 12534 // are assigned, in the order in which they were declared in the class 12535 // definition. 12536 12537 // Issue a warning if our implicit move assignment operator will move 12538 // from a virtual base more than once. 12539 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12540 12541 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12542 12543 // The exception specification is needed because we are defining the 12544 // function. 12545 ResolveExceptionSpec(CurrentLocation, 12546 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12547 12548 // Add a context note for diagnostics produced after this point. 12549 Scope.addContextNote(CurrentLocation); 12550 12551 // The statements that form the synthesized function body. 12552 SmallVector<Stmt*, 8> Statements; 12553 12554 // The parameter for the "other" object, which we are move from. 12555 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12556 QualType OtherRefType = Other->getType()-> 12557 getAs<RValueReferenceType>()->getPointeeType(); 12558 12559 // Our location for everything implicitly-generated. 12560 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 12561 ? MoveAssignOperator->getEndLoc() 12562 : MoveAssignOperator->getLocation(); 12563 12564 // Builds a reference to the "other" object. 12565 RefBuilder OtherRef(Other, OtherRefType); 12566 // Cast to rvalue. 12567 MoveCastBuilder MoveOther(OtherRef); 12568 12569 // Builds the "this" pointer. 12570 ThisBuilder This; 12571 12572 // Assign base classes. 12573 bool Invalid = false; 12574 for (auto &Base : ClassDecl->bases()) { 12575 // C++11 [class.copy]p28: 12576 // It is unspecified whether subobjects representing virtual base classes 12577 // are assigned more than once by the implicitly-defined copy assignment 12578 // operator. 12579 // FIXME: Do not assign to a vbase that will be assigned by some other base 12580 // class. For a move-assignment, this can result in the vbase being moved 12581 // multiple times. 12582 12583 // Form the assignment: 12584 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12585 QualType BaseType = Base.getType().getUnqualifiedType(); 12586 if (!BaseType->isRecordType()) { 12587 Invalid = true; 12588 continue; 12589 } 12590 12591 CXXCastPath BasePath; 12592 BasePath.push_back(&Base); 12593 12594 // Construct the "from" expression, which is an implicit cast to the 12595 // appropriately-qualified base type. 12596 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12597 12598 // Dereference "this". 12599 DerefBuilder DerefThis(This); 12600 12601 // Implicitly cast "this" to the appropriately-qualified base type. 12602 CastBuilder To(DerefThis, 12603 Context.getQualifiedType( 12604 BaseType, MoveAssignOperator->getMethodQualifiers()), 12605 VK_LValue, BasePath); 12606 12607 // Build the move. 12608 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12609 To, From, 12610 /*CopyingBaseSubobject=*/true, 12611 /*Copying=*/false); 12612 if (Move.isInvalid()) { 12613 MoveAssignOperator->setInvalidDecl(); 12614 return; 12615 } 12616 12617 // Success! Record the move. 12618 Statements.push_back(Move.getAs<Expr>()); 12619 } 12620 12621 // Assign non-static members. 12622 for (auto *Field : ClassDecl->fields()) { 12623 // FIXME: We should form some kind of AST representation for the implied 12624 // memcpy in a union copy operation. 12625 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12626 continue; 12627 12628 if (Field->isInvalidDecl()) { 12629 Invalid = true; 12630 continue; 12631 } 12632 12633 // Check for members of reference type; we can't move those. 12634 if (Field->getType()->isReferenceType()) { 12635 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12636 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12637 Diag(Field->getLocation(), diag::note_declared_at); 12638 Invalid = true; 12639 continue; 12640 } 12641 12642 // Check for members of const-qualified, non-class type. 12643 QualType BaseType = Context.getBaseElementType(Field->getType()); 12644 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12645 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12646 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12647 Diag(Field->getLocation(), diag::note_declared_at); 12648 Invalid = true; 12649 continue; 12650 } 12651 12652 // Suppress assigning zero-width bitfields. 12653 if (Field->isZeroLengthBitField(Context)) 12654 continue; 12655 12656 QualType FieldType = Field->getType().getNonReferenceType(); 12657 if (FieldType->isIncompleteArrayType()) { 12658 assert(ClassDecl->hasFlexibleArrayMember() && 12659 "Incomplete array type is not valid"); 12660 continue; 12661 } 12662 12663 // Build references to the field in the object we're copying from and to. 12664 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12665 LookupMemberName); 12666 MemberLookup.addDecl(Field); 12667 MemberLookup.resolveKind(); 12668 MemberBuilder From(MoveOther, OtherRefType, 12669 /*IsArrow=*/false, MemberLookup); 12670 MemberBuilder To(This, getCurrentThisType(), 12671 /*IsArrow=*/true, MemberLookup); 12672 12673 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12674 "Member reference with rvalue base must be rvalue except for reference " 12675 "members, which aren't allowed for move assignment."); 12676 12677 // Build the move of this field. 12678 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12679 To, From, 12680 /*CopyingBaseSubobject=*/false, 12681 /*Copying=*/false); 12682 if (Move.isInvalid()) { 12683 MoveAssignOperator->setInvalidDecl(); 12684 return; 12685 } 12686 12687 // Success! Record the copy. 12688 Statements.push_back(Move.getAs<Stmt>()); 12689 } 12690 12691 if (!Invalid) { 12692 // Add a "return *this;" 12693 ExprResult ThisObj = 12694 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12695 12696 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12697 if (Return.isInvalid()) 12698 Invalid = true; 12699 else 12700 Statements.push_back(Return.getAs<Stmt>()); 12701 } 12702 12703 if (Invalid) { 12704 MoveAssignOperator->setInvalidDecl(); 12705 return; 12706 } 12707 12708 StmtResult Body; 12709 { 12710 CompoundScopeRAII CompoundScope(*this); 12711 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12712 /*isStmtExpr=*/false); 12713 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12714 } 12715 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12716 MoveAssignOperator->markUsed(Context); 12717 12718 if (ASTMutationListener *L = getASTMutationListener()) { 12719 L->CompletedImplicitDefinition(MoveAssignOperator); 12720 } 12721 } 12722 12723 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12724 CXXRecordDecl *ClassDecl) { 12725 // C++ [class.copy]p4: 12726 // If the class definition does not explicitly declare a copy 12727 // constructor, one is declared implicitly. 12728 assert(ClassDecl->needsImplicitCopyConstructor()); 12729 12730 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12731 if (DSM.isAlreadyBeingDeclared()) 12732 return nullptr; 12733 12734 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12735 QualType ArgType = ClassType; 12736 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12737 if (Const) 12738 ArgType = ArgType.withConst(); 12739 12740 if (Context.getLangOpts().OpenCLCPlusPlus) 12741 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12742 12743 ArgType = Context.getLValueReferenceType(ArgType); 12744 12745 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12746 CXXCopyConstructor, 12747 Const); 12748 12749 DeclarationName Name 12750 = Context.DeclarationNames.getCXXConstructorName( 12751 Context.getCanonicalType(ClassType)); 12752 SourceLocation ClassLoc = ClassDecl->getLocation(); 12753 DeclarationNameInfo NameInfo(Name, ClassLoc); 12754 12755 // An implicitly-declared copy constructor is an inline public 12756 // member of its class. 12757 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12758 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12759 ExplicitSpecifier(), 12760 /*isInline=*/true, 12761 /*isImplicitlyDeclared=*/true, 12762 Constexpr ? CSK_constexpr : CSK_unspecified); 12763 CopyConstructor->setAccess(AS_public); 12764 CopyConstructor->setDefaulted(); 12765 12766 if (getLangOpts().CUDA) { 12767 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12768 CopyConstructor, 12769 /* ConstRHS */ Const, 12770 /* Diagnose */ false); 12771 } 12772 12773 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 12774 12775 // Add the parameter to the constructor. 12776 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12777 ClassLoc, ClassLoc, 12778 /*IdentifierInfo=*/nullptr, 12779 ArgType, /*TInfo=*/nullptr, 12780 SC_None, nullptr); 12781 CopyConstructor->setParams(FromParam); 12782 12783 CopyConstructor->setTrivial( 12784 ClassDecl->needsOverloadResolutionForCopyConstructor() 12785 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12786 : ClassDecl->hasTrivialCopyConstructor()); 12787 12788 CopyConstructor->setTrivialForCall( 12789 ClassDecl->hasAttr<TrivialABIAttr>() || 12790 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12791 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12792 TAH_ConsiderTrivialABI) 12793 : ClassDecl->hasTrivialCopyConstructorForCall())); 12794 12795 // Note that we have declared this constructor. 12796 ++getASTContext().NumImplicitCopyConstructorsDeclared; 12797 12798 Scope *S = getScopeForContext(ClassDecl); 12799 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12800 12801 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12802 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12803 SetDeclDeleted(CopyConstructor, ClassLoc); 12804 } 12805 12806 if (S) 12807 PushOnScopeChains(CopyConstructor, S, false); 12808 ClassDecl->addDecl(CopyConstructor); 12809 12810 return CopyConstructor; 12811 } 12812 12813 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12814 CXXConstructorDecl *CopyConstructor) { 12815 assert((CopyConstructor->isDefaulted() && 12816 CopyConstructor->isCopyConstructor() && 12817 !CopyConstructor->doesThisDeclarationHaveABody() && 12818 !CopyConstructor->isDeleted()) && 12819 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12820 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12821 return; 12822 12823 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12824 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12825 12826 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12827 12828 // The exception specification is needed because we are defining the 12829 // function. 12830 ResolveExceptionSpec(CurrentLocation, 12831 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12832 MarkVTableUsed(CurrentLocation, ClassDecl); 12833 12834 // Add a context note for diagnostics produced after this point. 12835 Scope.addContextNote(CurrentLocation); 12836 12837 // C++11 [class.copy]p7: 12838 // The [definition of an implicitly declared copy constructor] is 12839 // deprecated if the class has a user-declared copy assignment operator 12840 // or a user-declared destructor. 12841 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12842 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12843 12844 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12845 CopyConstructor->setInvalidDecl(); 12846 } else { 12847 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 12848 ? CopyConstructor->getEndLoc() 12849 : CopyConstructor->getLocation(); 12850 Sema::CompoundScopeRAII CompoundScope(*this); 12851 CopyConstructor->setBody( 12852 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12853 CopyConstructor->markUsed(Context); 12854 } 12855 12856 if (ASTMutationListener *L = getASTMutationListener()) { 12857 L->CompletedImplicitDefinition(CopyConstructor); 12858 } 12859 } 12860 12861 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12862 CXXRecordDecl *ClassDecl) { 12863 assert(ClassDecl->needsImplicitMoveConstructor()); 12864 12865 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12866 if (DSM.isAlreadyBeingDeclared()) 12867 return nullptr; 12868 12869 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12870 12871 QualType ArgType = ClassType; 12872 if (Context.getLangOpts().OpenCLCPlusPlus) 12873 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic); 12874 ArgType = Context.getRValueReferenceType(ArgType); 12875 12876 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12877 CXXMoveConstructor, 12878 false); 12879 12880 DeclarationName Name 12881 = Context.DeclarationNames.getCXXConstructorName( 12882 Context.getCanonicalType(ClassType)); 12883 SourceLocation ClassLoc = ClassDecl->getLocation(); 12884 DeclarationNameInfo NameInfo(Name, ClassLoc); 12885 12886 // C++11 [class.copy]p11: 12887 // An implicitly-declared copy/move constructor is an inline public 12888 // member of its class. 12889 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12890 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12891 ExplicitSpecifier(), 12892 /*isInline=*/true, 12893 /*isImplicitlyDeclared=*/true, 12894 Constexpr ? CSK_constexpr : CSK_unspecified); 12895 MoveConstructor->setAccess(AS_public); 12896 MoveConstructor->setDefaulted(); 12897 12898 if (getLangOpts().CUDA) { 12899 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12900 MoveConstructor, 12901 /* ConstRHS */ false, 12902 /* Diagnose */ false); 12903 } 12904 12905 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 12906 12907 // Add the parameter to the constructor. 12908 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12909 ClassLoc, ClassLoc, 12910 /*IdentifierInfo=*/nullptr, 12911 ArgType, /*TInfo=*/nullptr, 12912 SC_None, nullptr); 12913 MoveConstructor->setParams(FromParam); 12914 12915 MoveConstructor->setTrivial( 12916 ClassDecl->needsOverloadResolutionForMoveConstructor() 12917 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12918 : ClassDecl->hasTrivialMoveConstructor()); 12919 12920 MoveConstructor->setTrivialForCall( 12921 ClassDecl->hasAttr<TrivialABIAttr>() || 12922 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12923 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12924 TAH_ConsiderTrivialABI) 12925 : ClassDecl->hasTrivialMoveConstructorForCall())); 12926 12927 // Note that we have declared this constructor. 12928 ++getASTContext().NumImplicitMoveConstructorsDeclared; 12929 12930 Scope *S = getScopeForContext(ClassDecl); 12931 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12932 12933 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12934 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12935 SetDeclDeleted(MoveConstructor, ClassLoc); 12936 } 12937 12938 if (S) 12939 PushOnScopeChains(MoveConstructor, S, false); 12940 ClassDecl->addDecl(MoveConstructor); 12941 12942 return MoveConstructor; 12943 } 12944 12945 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12946 CXXConstructorDecl *MoveConstructor) { 12947 assert((MoveConstructor->isDefaulted() && 12948 MoveConstructor->isMoveConstructor() && 12949 !MoveConstructor->doesThisDeclarationHaveABody() && 12950 !MoveConstructor->isDeleted()) && 12951 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12952 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12953 return; 12954 12955 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12956 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12957 12958 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12959 12960 // The exception specification is needed because we are defining the 12961 // function. 12962 ResolveExceptionSpec(CurrentLocation, 12963 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12964 MarkVTableUsed(CurrentLocation, ClassDecl); 12965 12966 // Add a context note for diagnostics produced after this point. 12967 Scope.addContextNote(CurrentLocation); 12968 12969 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12970 MoveConstructor->setInvalidDecl(); 12971 } else { 12972 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 12973 ? MoveConstructor->getEndLoc() 12974 : MoveConstructor->getLocation(); 12975 Sema::CompoundScopeRAII CompoundScope(*this); 12976 MoveConstructor->setBody(ActOnCompoundStmt( 12977 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12978 MoveConstructor->markUsed(Context); 12979 } 12980 12981 if (ASTMutationListener *L = getASTMutationListener()) { 12982 L->CompletedImplicitDefinition(MoveConstructor); 12983 } 12984 } 12985 12986 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12987 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12988 } 12989 12990 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12991 SourceLocation CurrentLocation, 12992 CXXConversionDecl *Conv) { 12993 SynthesizedFunctionScope Scope(*this, Conv); 12994 assert(!Conv->getReturnType()->isUndeducedType()); 12995 12996 CXXRecordDecl *Lambda = Conv->getParent(); 12997 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12998 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12999 13000 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 13001 CallOp = InstantiateFunctionDeclaration( 13002 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 13003 if (!CallOp) 13004 return; 13005 13006 Invoker = InstantiateFunctionDeclaration( 13007 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 13008 if (!Invoker) 13009 return; 13010 } 13011 13012 if (CallOp->isInvalidDecl()) 13013 return; 13014 13015 // Mark the call operator referenced (and add to pending instantiations 13016 // if necessary). 13017 // For both the conversion and static-invoker template specializations 13018 // we construct their body's in this function, so no need to add them 13019 // to the PendingInstantiations. 13020 MarkFunctionReferenced(CurrentLocation, CallOp); 13021 13022 // Fill in the __invoke function with a dummy implementation. IR generation 13023 // will fill in the actual details. Update its type in case it contained 13024 // an 'auto'. 13025 Invoker->markUsed(Context); 13026 Invoker->setReferenced(); 13027 Invoker->setType(Conv->getReturnType()->getPointeeType()); 13028 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 13029 13030 // Construct the body of the conversion function { return __invoke; }. 13031 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 13032 VK_LValue, Conv->getLocation()); 13033 assert(FunctionRef && "Can't refer to __invoke function?"); 13034 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 13035 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 13036 Conv->getLocation())); 13037 Conv->markUsed(Context); 13038 Conv->setReferenced(); 13039 13040 if (ASTMutationListener *L = getASTMutationListener()) { 13041 L->CompletedImplicitDefinition(Conv); 13042 L->CompletedImplicitDefinition(Invoker); 13043 } 13044 } 13045 13046 13047 13048 void Sema::DefineImplicitLambdaToBlockPointerConversion( 13049 SourceLocation CurrentLocation, 13050 CXXConversionDecl *Conv) 13051 { 13052 assert(!Conv->getParent()->isGenericLambda()); 13053 13054 SynthesizedFunctionScope Scope(*this, Conv); 13055 13056 // Copy-initialize the lambda object as needed to capture it. 13057 Expr *This = ActOnCXXThis(CurrentLocation).get(); 13058 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 13059 13060 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 13061 Conv->getLocation(), 13062 Conv, DerefThis); 13063 13064 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 13065 // behavior. Note that only the general conversion function does this 13066 // (since it's unusable otherwise); in the case where we inline the 13067 // block literal, it has block literal lifetime semantics. 13068 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 13069 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 13070 CK_CopyAndAutoreleaseBlockObject, 13071 BuildBlock.get(), nullptr, VK_RValue); 13072 13073 if (BuildBlock.isInvalid()) { 13074 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 13075 Conv->setInvalidDecl(); 13076 return; 13077 } 13078 13079 // Create the return statement that returns the block from the conversion 13080 // function. 13081 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 13082 if (Return.isInvalid()) { 13083 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 13084 Conv->setInvalidDecl(); 13085 return; 13086 } 13087 13088 // Set the body of the conversion function. 13089 Stmt *ReturnS = Return.get(); 13090 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 13091 Conv->getLocation())); 13092 Conv->markUsed(Context); 13093 13094 // We're done; notify the mutation listener, if any. 13095 if (ASTMutationListener *L = getASTMutationListener()) { 13096 L->CompletedImplicitDefinition(Conv); 13097 } 13098 } 13099 13100 /// Determine whether the given list arguments contains exactly one 13101 /// "real" (non-default) argument. 13102 static bool hasOneRealArgument(MultiExprArg Args) { 13103 switch (Args.size()) { 13104 case 0: 13105 return false; 13106 13107 default: 13108 if (!Args[1]->isDefaultArgument()) 13109 return false; 13110 13111 LLVM_FALLTHROUGH; 13112 case 1: 13113 return !Args[0]->isDefaultArgument(); 13114 } 13115 13116 return false; 13117 } 13118 13119 ExprResult 13120 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13121 NamedDecl *FoundDecl, 13122 CXXConstructorDecl *Constructor, 13123 MultiExprArg ExprArgs, 13124 bool HadMultipleCandidates, 13125 bool IsListInitialization, 13126 bool IsStdInitListInitialization, 13127 bool RequiresZeroInit, 13128 unsigned ConstructKind, 13129 SourceRange ParenRange) { 13130 bool Elidable = false; 13131 13132 // C++0x [class.copy]p34: 13133 // When certain criteria are met, an implementation is allowed to 13134 // omit the copy/move construction of a class object, even if the 13135 // copy/move constructor and/or destructor for the object have 13136 // side effects. [...] 13137 // - when a temporary class object that has not been bound to a 13138 // reference (12.2) would be copied/moved to a class object 13139 // with the same cv-unqualified type, the copy/move operation 13140 // can be omitted by constructing the temporary object 13141 // directly into the target of the omitted copy/move 13142 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 13143 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 13144 Expr *SubExpr = ExprArgs[0]; 13145 Elidable = SubExpr->isTemporaryObject( 13146 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 13147 } 13148 13149 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 13150 FoundDecl, Constructor, 13151 Elidable, ExprArgs, HadMultipleCandidates, 13152 IsListInitialization, 13153 IsStdInitListInitialization, RequiresZeroInit, 13154 ConstructKind, ParenRange); 13155 } 13156 13157 ExprResult 13158 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13159 NamedDecl *FoundDecl, 13160 CXXConstructorDecl *Constructor, 13161 bool Elidable, 13162 MultiExprArg ExprArgs, 13163 bool HadMultipleCandidates, 13164 bool IsListInitialization, 13165 bool IsStdInitListInitialization, 13166 bool RequiresZeroInit, 13167 unsigned ConstructKind, 13168 SourceRange ParenRange) { 13169 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 13170 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 13171 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 13172 return ExprError(); 13173 } 13174 13175 return BuildCXXConstructExpr( 13176 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 13177 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 13178 RequiresZeroInit, ConstructKind, ParenRange); 13179 } 13180 13181 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 13182 /// including handling of its default argument expressions. 13183 ExprResult 13184 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13185 CXXConstructorDecl *Constructor, 13186 bool Elidable, 13187 MultiExprArg ExprArgs, 13188 bool HadMultipleCandidates, 13189 bool IsListInitialization, 13190 bool IsStdInitListInitialization, 13191 bool RequiresZeroInit, 13192 unsigned ConstructKind, 13193 SourceRange ParenRange) { 13194 assert(declaresSameEntity( 13195 Constructor->getParent(), 13196 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 13197 "given constructor for wrong type"); 13198 MarkFunctionReferenced(ConstructLoc, Constructor); 13199 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 13200 return ExprError(); 13201 13202 return CXXConstructExpr::Create( 13203 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 13204 ExprArgs, HadMultipleCandidates, IsListInitialization, 13205 IsStdInitListInitialization, RequiresZeroInit, 13206 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 13207 ParenRange); 13208 } 13209 13210 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 13211 assert(Field->hasInClassInitializer()); 13212 13213 // If we already have the in-class initializer nothing needs to be done. 13214 if (Field->getInClassInitializer()) 13215 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 13216 13217 // If we might have already tried and failed to instantiate, don't try again. 13218 if (Field->isInvalidDecl()) 13219 return ExprError(); 13220 13221 // Maybe we haven't instantiated the in-class initializer. Go check the 13222 // pattern FieldDecl to see if it has one. 13223 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 13224 13225 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 13226 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 13227 DeclContext::lookup_result Lookup = 13228 ClassPattern->lookup(Field->getDeclName()); 13229 13230 // Lookup can return at most two results: the pattern for the field, or the 13231 // injected class name of the parent record. No other member can have the 13232 // same name as the field. 13233 // In modules mode, lookup can return multiple results (coming from 13234 // different modules). 13235 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 13236 "more than two lookup results for field name"); 13237 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 13238 if (!Pattern) { 13239 assert(isa<CXXRecordDecl>(Lookup[0]) && 13240 "cannot have other non-field member with same name"); 13241 for (auto L : Lookup) 13242 if (isa<FieldDecl>(L)) { 13243 Pattern = cast<FieldDecl>(L); 13244 break; 13245 } 13246 assert(Pattern && "We must have set the Pattern!"); 13247 } 13248 13249 if (!Pattern->hasInClassInitializer() || 13250 InstantiateInClassInitializer(Loc, Field, Pattern, 13251 getTemplateInstantiationArgs(Field))) { 13252 // Don't diagnose this again. 13253 Field->setInvalidDecl(); 13254 return ExprError(); 13255 } 13256 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 13257 } 13258 13259 // DR1351: 13260 // If the brace-or-equal-initializer of a non-static data member 13261 // invokes a defaulted default constructor of its class or of an 13262 // enclosing class in a potentially evaluated subexpression, the 13263 // program is ill-formed. 13264 // 13265 // This resolution is unworkable: the exception specification of the 13266 // default constructor can be needed in an unevaluated context, in 13267 // particular, in the operand of a noexcept-expression, and we can be 13268 // unable to compute an exception specification for an enclosed class. 13269 // 13270 // Any attempt to resolve the exception specification of a defaulted default 13271 // constructor before the initializer is lexically complete will ultimately 13272 // come here at which point we can diagnose it. 13273 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 13274 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 13275 << OutermostClass << Field; 13276 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 13277 // Recover by marking the field invalid, unless we're in a SFINAE context. 13278 if (!isSFINAEContext()) 13279 Field->setInvalidDecl(); 13280 return ExprError(); 13281 } 13282 13283 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 13284 if (VD->isInvalidDecl()) return; 13285 13286 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 13287 if (ClassDecl->isInvalidDecl()) return; 13288 if (ClassDecl->hasIrrelevantDestructor()) return; 13289 if (ClassDecl->isDependentContext()) return; 13290 13291 if (VD->isNoDestroy(getASTContext())) 13292 return; 13293 13294 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13295 13296 // If this is an array, we'll require the destructor during initialization, so 13297 // we can skip over this. We still want to emit exit-time destructor warnings 13298 // though. 13299 if (!VD->getType()->isArrayType()) { 13300 MarkFunctionReferenced(VD->getLocation(), Destructor); 13301 CheckDestructorAccess(VD->getLocation(), Destructor, 13302 PDiag(diag::err_access_dtor_var) 13303 << VD->getDeclName() << VD->getType()); 13304 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 13305 } 13306 13307 if (Destructor->isTrivial()) return; 13308 if (!VD->hasGlobalStorage()) return; 13309 13310 // Emit warning for non-trivial dtor in global scope (a real global, 13311 // class-static, function-static). 13312 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 13313 13314 // TODO: this should be re-enabled for static locals by !CXAAtExit 13315 if (!VD->isStaticLocal()) 13316 Diag(VD->getLocation(), diag::warn_global_destructor); 13317 } 13318 13319 /// Given a constructor and the set of arguments provided for the 13320 /// constructor, convert the arguments and add any required default arguments 13321 /// to form a proper call to this constructor. 13322 /// 13323 /// \returns true if an error occurred, false otherwise. 13324 bool 13325 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 13326 MultiExprArg ArgsPtr, 13327 SourceLocation Loc, 13328 SmallVectorImpl<Expr*> &ConvertedArgs, 13329 bool AllowExplicit, 13330 bool IsListInitialization) { 13331 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 13332 unsigned NumArgs = ArgsPtr.size(); 13333 Expr **Args = ArgsPtr.data(); 13334 13335 const FunctionProtoType *Proto 13336 = Constructor->getType()->getAs<FunctionProtoType>(); 13337 assert(Proto && "Constructor without a prototype?"); 13338 unsigned NumParams = Proto->getNumParams(); 13339 13340 // If too few arguments are available, we'll fill in the rest with defaults. 13341 if (NumArgs < NumParams) 13342 ConvertedArgs.reserve(NumParams); 13343 else 13344 ConvertedArgs.reserve(NumArgs); 13345 13346 VariadicCallType CallType = 13347 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 13348 SmallVector<Expr *, 8> AllArgs; 13349 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 13350 Proto, 0, 13351 llvm::makeArrayRef(Args, NumArgs), 13352 AllArgs, 13353 CallType, AllowExplicit, 13354 IsListInitialization); 13355 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 13356 13357 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 13358 13359 CheckConstructorCall(Constructor, 13360 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 13361 Proto, Loc); 13362 13363 return Invalid; 13364 } 13365 13366 static inline bool 13367 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 13368 const FunctionDecl *FnDecl) { 13369 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 13370 if (isa<NamespaceDecl>(DC)) { 13371 return SemaRef.Diag(FnDecl->getLocation(), 13372 diag::err_operator_new_delete_declared_in_namespace) 13373 << FnDecl->getDeclName(); 13374 } 13375 13376 if (isa<TranslationUnitDecl>(DC) && 13377 FnDecl->getStorageClass() == SC_Static) { 13378 return SemaRef.Diag(FnDecl->getLocation(), 13379 diag::err_operator_new_delete_declared_static) 13380 << FnDecl->getDeclName(); 13381 } 13382 13383 return false; 13384 } 13385 13386 static QualType 13387 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 13388 QualType QTy = PtrTy->getPointeeType(); 13389 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 13390 return SemaRef.Context.getPointerType(QTy); 13391 } 13392 13393 static inline bool 13394 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13395 CanQualType ExpectedResultType, 13396 CanQualType ExpectedFirstParamType, 13397 unsigned DependentParamTypeDiag, 13398 unsigned InvalidParamTypeDiag) { 13399 QualType ResultType = 13400 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13401 13402 // Check that the result type is not dependent. 13403 if (ResultType->isDependentType()) 13404 return SemaRef.Diag(FnDecl->getLocation(), 13405 diag::err_operator_new_delete_dependent_result_type) 13406 << FnDecl->getDeclName() << ExpectedResultType; 13407 13408 // The operator is valid on any address space for OpenCL. 13409 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13410 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13411 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13412 } 13413 } 13414 13415 // Check that the result type is what we expect. 13416 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13417 return SemaRef.Diag(FnDecl->getLocation(), 13418 diag::err_operator_new_delete_invalid_result_type) 13419 << FnDecl->getDeclName() << ExpectedResultType; 13420 13421 // A function template must have at least 2 parameters. 13422 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13423 return SemaRef.Diag(FnDecl->getLocation(), 13424 diag::err_operator_new_delete_template_too_few_parameters) 13425 << FnDecl->getDeclName(); 13426 13427 // The function decl must have at least 1 parameter. 13428 if (FnDecl->getNumParams() == 0) 13429 return SemaRef.Diag(FnDecl->getLocation(), 13430 diag::err_operator_new_delete_too_few_parameters) 13431 << FnDecl->getDeclName(); 13432 13433 // Check the first parameter type is not dependent. 13434 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13435 if (FirstParamType->isDependentType()) 13436 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13437 << FnDecl->getDeclName() << ExpectedFirstParamType; 13438 13439 // Check that the first parameter type is what we expect. 13440 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13441 // The operator is valid on any address space for OpenCL. 13442 if (auto *PtrTy = 13443 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13444 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13445 } 13446 } 13447 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13448 ExpectedFirstParamType) 13449 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13450 << FnDecl->getDeclName() << ExpectedFirstParamType; 13451 13452 return false; 13453 } 13454 13455 static bool 13456 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13457 // C++ [basic.stc.dynamic.allocation]p1: 13458 // A program is ill-formed if an allocation function is declared in a 13459 // namespace scope other than global scope or declared static in global 13460 // scope. 13461 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13462 return true; 13463 13464 CanQualType SizeTy = 13465 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13466 13467 // C++ [basic.stc.dynamic.allocation]p1: 13468 // The return type shall be void*. The first parameter shall have type 13469 // std::size_t. 13470 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13471 SizeTy, 13472 diag::err_operator_new_dependent_param_type, 13473 diag::err_operator_new_param_type)) 13474 return true; 13475 13476 // C++ [basic.stc.dynamic.allocation]p1: 13477 // The first parameter shall not have an associated default argument. 13478 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13479 return SemaRef.Diag(FnDecl->getLocation(), 13480 diag::err_operator_new_default_arg) 13481 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13482 13483 return false; 13484 } 13485 13486 static bool 13487 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13488 // C++ [basic.stc.dynamic.deallocation]p1: 13489 // A program is ill-formed if deallocation functions are declared in a 13490 // namespace scope other than global scope or declared static in global 13491 // scope. 13492 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13493 return true; 13494 13495 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13496 13497 // C++ P0722: 13498 // Within a class C, the first parameter of a destroying operator delete 13499 // shall be of type C *. The first parameter of any other deallocation 13500 // function shall be of type void *. 13501 CanQualType ExpectedFirstParamType = 13502 MD && MD->isDestroyingOperatorDelete() 13503 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13504 SemaRef.Context.getRecordType(MD->getParent()))) 13505 : SemaRef.Context.VoidPtrTy; 13506 13507 // C++ [basic.stc.dynamic.deallocation]p2: 13508 // Each deallocation function shall return void 13509 if (CheckOperatorNewDeleteTypes( 13510 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13511 diag::err_operator_delete_dependent_param_type, 13512 diag::err_operator_delete_param_type)) 13513 return true; 13514 13515 // C++ P0722: 13516 // A destroying operator delete shall be a usual deallocation function. 13517 if (MD && !MD->getParent()->isDependentContext() && 13518 MD->isDestroyingOperatorDelete() && 13519 !SemaRef.isUsualDeallocationFunction(MD)) { 13520 SemaRef.Diag(MD->getLocation(), 13521 diag::err_destroying_operator_delete_not_usual); 13522 return true; 13523 } 13524 13525 return false; 13526 } 13527 13528 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13529 /// of this overloaded operator is well-formed. If so, returns false; 13530 /// otherwise, emits appropriate diagnostics and returns true. 13531 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13532 assert(FnDecl && FnDecl->isOverloadedOperator() && 13533 "Expected an overloaded operator declaration"); 13534 13535 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13536 13537 // C++ [over.oper]p5: 13538 // The allocation and deallocation functions, operator new, 13539 // operator new[], operator delete and operator delete[], are 13540 // described completely in 3.7.3. The attributes and restrictions 13541 // found in the rest of this subclause do not apply to them unless 13542 // explicitly stated in 3.7.3. 13543 if (Op == OO_Delete || Op == OO_Array_Delete) 13544 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13545 13546 if (Op == OO_New || Op == OO_Array_New) 13547 return CheckOperatorNewDeclaration(*this, FnDecl); 13548 13549 // C++ [over.oper]p6: 13550 // An operator function shall either be a non-static member 13551 // function or be a non-member function and have at least one 13552 // parameter whose type is a class, a reference to a class, an 13553 // enumeration, or a reference to an enumeration. 13554 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13555 if (MethodDecl->isStatic()) 13556 return Diag(FnDecl->getLocation(), 13557 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13558 } else { 13559 bool ClassOrEnumParam = false; 13560 for (auto Param : FnDecl->parameters()) { 13561 QualType ParamType = Param->getType().getNonReferenceType(); 13562 if (ParamType->isDependentType() || ParamType->isRecordType() || 13563 ParamType->isEnumeralType()) { 13564 ClassOrEnumParam = true; 13565 break; 13566 } 13567 } 13568 13569 if (!ClassOrEnumParam) 13570 return Diag(FnDecl->getLocation(), 13571 diag::err_operator_overload_needs_class_or_enum) 13572 << FnDecl->getDeclName(); 13573 } 13574 13575 // C++ [over.oper]p8: 13576 // An operator function cannot have default arguments (8.3.6), 13577 // except where explicitly stated below. 13578 // 13579 // Only the function-call operator allows default arguments 13580 // (C++ [over.call]p1). 13581 if (Op != OO_Call) { 13582 for (auto Param : FnDecl->parameters()) { 13583 if (Param->hasDefaultArg()) 13584 return Diag(Param->getLocation(), 13585 diag::err_operator_overload_default_arg) 13586 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13587 } 13588 } 13589 13590 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13591 { false, false, false } 13592 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13593 , { Unary, Binary, MemberOnly } 13594 #include "clang/Basic/OperatorKinds.def" 13595 }; 13596 13597 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13598 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13599 bool MustBeMemberOperator = OperatorUses[Op][2]; 13600 13601 // C++ [over.oper]p8: 13602 // [...] Operator functions cannot have more or fewer parameters 13603 // than the number required for the corresponding operator, as 13604 // described in the rest of this subclause. 13605 unsigned NumParams = FnDecl->getNumParams() 13606 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13607 if (Op != OO_Call && 13608 ((NumParams == 1 && !CanBeUnaryOperator) || 13609 (NumParams == 2 && !CanBeBinaryOperator) || 13610 (NumParams < 1) || (NumParams > 2))) { 13611 // We have the wrong number of parameters. 13612 unsigned ErrorKind; 13613 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13614 ErrorKind = 2; // 2 -> unary or binary. 13615 } else if (CanBeUnaryOperator) { 13616 ErrorKind = 0; // 0 -> unary 13617 } else { 13618 assert(CanBeBinaryOperator && 13619 "All non-call overloaded operators are unary or binary!"); 13620 ErrorKind = 1; // 1 -> binary 13621 } 13622 13623 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13624 << FnDecl->getDeclName() << NumParams << ErrorKind; 13625 } 13626 13627 // Overloaded operators other than operator() cannot be variadic. 13628 if (Op != OO_Call && 13629 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13630 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13631 << FnDecl->getDeclName(); 13632 } 13633 13634 // Some operators must be non-static member functions. 13635 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13636 return Diag(FnDecl->getLocation(), 13637 diag::err_operator_overload_must_be_member) 13638 << FnDecl->getDeclName(); 13639 } 13640 13641 // C++ [over.inc]p1: 13642 // The user-defined function called operator++ implements the 13643 // prefix and postfix ++ operator. If this function is a member 13644 // function with no parameters, or a non-member function with one 13645 // parameter of class or enumeration type, it defines the prefix 13646 // increment operator ++ for objects of that type. If the function 13647 // is a member function with one parameter (which shall be of type 13648 // int) or a non-member function with two parameters (the second 13649 // of which shall be of type int), it defines the postfix 13650 // increment operator ++ for objects of that type. 13651 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13652 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13653 QualType ParamType = LastParam->getType(); 13654 13655 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13656 !ParamType->isDependentType()) 13657 return Diag(LastParam->getLocation(), 13658 diag::err_operator_overload_post_incdec_must_be_int) 13659 << LastParam->getType() << (Op == OO_MinusMinus); 13660 } 13661 13662 return false; 13663 } 13664 13665 static bool 13666 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13667 FunctionTemplateDecl *TpDecl) { 13668 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13669 13670 // Must have one or two template parameters. 13671 if (TemplateParams->size() == 1) { 13672 NonTypeTemplateParmDecl *PmDecl = 13673 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13674 13675 // The template parameter must be a char parameter pack. 13676 if (PmDecl && PmDecl->isTemplateParameterPack() && 13677 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13678 return false; 13679 13680 } else if (TemplateParams->size() == 2) { 13681 TemplateTypeParmDecl *PmType = 13682 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13683 NonTypeTemplateParmDecl *PmArgs = 13684 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13685 13686 // The second template parameter must be a parameter pack with the 13687 // first template parameter as its type. 13688 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13689 PmArgs->isTemplateParameterPack()) { 13690 const TemplateTypeParmType *TArgs = 13691 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13692 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13693 TArgs->getIndex() == PmType->getIndex()) { 13694 if (!SemaRef.inTemplateInstantiation()) 13695 SemaRef.Diag(TpDecl->getLocation(), 13696 diag::ext_string_literal_operator_template); 13697 return false; 13698 } 13699 } 13700 } 13701 13702 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13703 diag::err_literal_operator_template) 13704 << TpDecl->getTemplateParameters()->getSourceRange(); 13705 return true; 13706 } 13707 13708 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13709 /// of this literal operator function is well-formed. If so, returns 13710 /// false; otherwise, emits appropriate diagnostics and returns true. 13711 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13712 if (isa<CXXMethodDecl>(FnDecl)) { 13713 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13714 << FnDecl->getDeclName(); 13715 return true; 13716 } 13717 13718 if (FnDecl->isExternC()) { 13719 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13720 if (const LinkageSpecDecl *LSD = 13721 FnDecl->getDeclContext()->getExternCContext()) 13722 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13723 return true; 13724 } 13725 13726 // This might be the definition of a literal operator template. 13727 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13728 13729 // This might be a specialization of a literal operator template. 13730 if (!TpDecl) 13731 TpDecl = FnDecl->getPrimaryTemplate(); 13732 13733 // template <char...> type operator "" name() and 13734 // template <class T, T...> type operator "" name() are the only valid 13735 // template signatures, and the only valid signatures with no parameters. 13736 if (TpDecl) { 13737 if (FnDecl->param_size() != 0) { 13738 Diag(FnDecl->getLocation(), 13739 diag::err_literal_operator_template_with_params); 13740 return true; 13741 } 13742 13743 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13744 return true; 13745 13746 } else if (FnDecl->param_size() == 1) { 13747 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13748 13749 QualType ParamType = Param->getType().getUnqualifiedType(); 13750 13751 // Only unsigned long long int, long double, any character type, and const 13752 // char * are allowed as the only parameters. 13753 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13754 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13755 Context.hasSameType(ParamType, Context.CharTy) || 13756 Context.hasSameType(ParamType, Context.WideCharTy) || 13757 Context.hasSameType(ParamType, Context.Char8Ty) || 13758 Context.hasSameType(ParamType, Context.Char16Ty) || 13759 Context.hasSameType(ParamType, Context.Char32Ty)) { 13760 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13761 QualType InnerType = Ptr->getPointeeType(); 13762 13763 // Pointer parameter must be a const char *. 13764 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13765 Context.CharTy) && 13766 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13767 Diag(Param->getSourceRange().getBegin(), 13768 diag::err_literal_operator_param) 13769 << ParamType << "'const char *'" << Param->getSourceRange(); 13770 return true; 13771 } 13772 13773 } else if (ParamType->isRealFloatingType()) { 13774 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13775 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13776 return true; 13777 13778 } else if (ParamType->isIntegerType()) { 13779 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13780 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13781 return true; 13782 13783 } else { 13784 Diag(Param->getSourceRange().getBegin(), 13785 diag::err_literal_operator_invalid_param) 13786 << ParamType << Param->getSourceRange(); 13787 return true; 13788 } 13789 13790 } else if (FnDecl->param_size() == 2) { 13791 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13792 13793 // First, verify that the first parameter is correct. 13794 13795 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13796 13797 // Two parameter function must have a pointer to const as a 13798 // first parameter; let's strip those qualifiers. 13799 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13800 13801 if (!PT) { 13802 Diag((*Param)->getSourceRange().getBegin(), 13803 diag::err_literal_operator_param) 13804 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13805 return true; 13806 } 13807 13808 QualType PointeeType = PT->getPointeeType(); 13809 // First parameter must be const 13810 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13811 Diag((*Param)->getSourceRange().getBegin(), 13812 diag::err_literal_operator_param) 13813 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13814 return true; 13815 } 13816 13817 QualType InnerType = PointeeType.getUnqualifiedType(); 13818 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13819 // const char32_t* are allowed as the first parameter to a two-parameter 13820 // function 13821 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13822 Context.hasSameType(InnerType, Context.WideCharTy) || 13823 Context.hasSameType(InnerType, Context.Char8Ty) || 13824 Context.hasSameType(InnerType, Context.Char16Ty) || 13825 Context.hasSameType(InnerType, Context.Char32Ty))) { 13826 Diag((*Param)->getSourceRange().getBegin(), 13827 diag::err_literal_operator_param) 13828 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13829 return true; 13830 } 13831 13832 // Move on to the second and final parameter. 13833 ++Param; 13834 13835 // The second parameter must be a std::size_t. 13836 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13837 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13838 Diag((*Param)->getSourceRange().getBegin(), 13839 diag::err_literal_operator_param) 13840 << SecondParamType << Context.getSizeType() 13841 << (*Param)->getSourceRange(); 13842 return true; 13843 } 13844 } else { 13845 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13846 return true; 13847 } 13848 13849 // Parameters are good. 13850 13851 // A parameter-declaration-clause containing a default argument is not 13852 // equivalent to any of the permitted forms. 13853 for (auto Param : FnDecl->parameters()) { 13854 if (Param->hasDefaultArg()) { 13855 Diag(Param->getDefaultArgRange().getBegin(), 13856 diag::err_literal_operator_default_argument) 13857 << Param->getDefaultArgRange(); 13858 break; 13859 } 13860 } 13861 13862 StringRef LiteralName 13863 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13864 if (LiteralName[0] != '_' && 13865 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13866 // C++11 [usrlit.suffix]p1: 13867 // Literal suffix identifiers that do not start with an underscore 13868 // are reserved for future standardization. 13869 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13870 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13871 } 13872 13873 return false; 13874 } 13875 13876 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13877 /// linkage specification, including the language and (if present) 13878 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13879 /// language string literal. LBraceLoc, if valid, provides the location of 13880 /// the '{' brace. Otherwise, this linkage specification does not 13881 /// have any braces. 13882 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13883 Expr *LangStr, 13884 SourceLocation LBraceLoc) { 13885 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13886 if (!Lit->isAscii()) { 13887 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13888 << LangStr->getSourceRange(); 13889 return nullptr; 13890 } 13891 13892 StringRef Lang = Lit->getString(); 13893 LinkageSpecDecl::LanguageIDs Language; 13894 if (Lang == "C") 13895 Language = LinkageSpecDecl::lang_c; 13896 else if (Lang == "C++") 13897 Language = LinkageSpecDecl::lang_cxx; 13898 else { 13899 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13900 << LangStr->getSourceRange(); 13901 return nullptr; 13902 } 13903 13904 // FIXME: Add all the various semantics of linkage specifications 13905 13906 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13907 LangStr->getExprLoc(), Language, 13908 LBraceLoc.isValid()); 13909 CurContext->addDecl(D); 13910 PushDeclContext(S, D); 13911 return D; 13912 } 13913 13914 /// ActOnFinishLinkageSpecification - Complete the definition of 13915 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13916 /// valid, it's the position of the closing '}' brace in a linkage 13917 /// specification that uses braces. 13918 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13919 Decl *LinkageSpec, 13920 SourceLocation RBraceLoc) { 13921 if (RBraceLoc.isValid()) { 13922 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13923 LSDecl->setRBraceLoc(RBraceLoc); 13924 } 13925 PopDeclContext(); 13926 return LinkageSpec; 13927 } 13928 13929 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13930 const ParsedAttributesView &AttrList, 13931 SourceLocation SemiLoc) { 13932 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13933 // Attribute declarations appertain to empty declaration so we handle 13934 // them here. 13935 ProcessDeclAttributeList(S, ED, AttrList); 13936 13937 CurContext->addDecl(ED); 13938 return ED; 13939 } 13940 13941 /// Perform semantic analysis for the variable declaration that 13942 /// occurs within a C++ catch clause, returning the newly-created 13943 /// variable. 13944 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13945 TypeSourceInfo *TInfo, 13946 SourceLocation StartLoc, 13947 SourceLocation Loc, 13948 IdentifierInfo *Name) { 13949 bool Invalid = false; 13950 QualType ExDeclType = TInfo->getType(); 13951 13952 // Arrays and functions decay. 13953 if (ExDeclType->isArrayType()) 13954 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13955 else if (ExDeclType->isFunctionType()) 13956 ExDeclType = Context.getPointerType(ExDeclType); 13957 13958 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13959 // The exception-declaration shall not denote a pointer or reference to an 13960 // incomplete type, other than [cv] void*. 13961 // N2844 forbids rvalue references. 13962 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13963 Diag(Loc, diag::err_catch_rvalue_ref); 13964 Invalid = true; 13965 } 13966 13967 if (ExDeclType->isVariablyModifiedType()) { 13968 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13969 Invalid = true; 13970 } 13971 13972 QualType BaseType = ExDeclType; 13973 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13974 unsigned DK = diag::err_catch_incomplete; 13975 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13976 BaseType = Ptr->getPointeeType(); 13977 Mode = 1; 13978 DK = diag::err_catch_incomplete_ptr; 13979 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13980 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13981 BaseType = Ref->getPointeeType(); 13982 Mode = 2; 13983 DK = diag::err_catch_incomplete_ref; 13984 } 13985 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13986 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13987 Invalid = true; 13988 13989 if (!Invalid && !ExDeclType->isDependentType() && 13990 RequireNonAbstractType(Loc, ExDeclType, 13991 diag::err_abstract_type_in_decl, 13992 AbstractVariableType)) 13993 Invalid = true; 13994 13995 // Only the non-fragile NeXT runtime currently supports C++ catches 13996 // of ObjC types, and no runtime supports catching ObjC types by value. 13997 if (!Invalid && getLangOpts().ObjC) { 13998 QualType T = ExDeclType; 13999 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 14000 T = RT->getPointeeType(); 14001 14002 if (T->isObjCObjectType()) { 14003 Diag(Loc, diag::err_objc_object_catch); 14004 Invalid = true; 14005 } else if (T->isObjCObjectPointerType()) { 14006 // FIXME: should this be a test for macosx-fragile specifically? 14007 if (getLangOpts().ObjCRuntime.isFragile()) 14008 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 14009 } 14010 } 14011 14012 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 14013 ExDeclType, TInfo, SC_None); 14014 ExDecl->setExceptionVariable(true); 14015 14016 // In ARC, infer 'retaining' for variables of retainable type. 14017 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 14018 Invalid = true; 14019 14020 if (!Invalid && !ExDeclType->isDependentType()) { 14021 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 14022 // Insulate this from anything else we might currently be parsing. 14023 EnterExpressionEvaluationContext scope( 14024 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14025 14026 // C++ [except.handle]p16: 14027 // The object declared in an exception-declaration or, if the 14028 // exception-declaration does not specify a name, a temporary (12.2) is 14029 // copy-initialized (8.5) from the exception object. [...] 14030 // The object is destroyed when the handler exits, after the destruction 14031 // of any automatic objects initialized within the handler. 14032 // 14033 // We just pretend to initialize the object with itself, then make sure 14034 // it can be destroyed later. 14035 QualType initType = Context.getExceptionObjectType(ExDeclType); 14036 14037 InitializedEntity entity = 14038 InitializedEntity::InitializeVariable(ExDecl); 14039 InitializationKind initKind = 14040 InitializationKind::CreateCopy(Loc, SourceLocation()); 14041 14042 Expr *opaqueValue = 14043 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 14044 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 14045 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 14046 if (result.isInvalid()) 14047 Invalid = true; 14048 else { 14049 // If the constructor used was non-trivial, set this as the 14050 // "initializer". 14051 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 14052 if (!construct->getConstructor()->isTrivial()) { 14053 Expr *init = MaybeCreateExprWithCleanups(construct); 14054 ExDecl->setInit(init); 14055 } 14056 14057 // And make sure it's destructable. 14058 FinalizeVarWithDestructor(ExDecl, recordType); 14059 } 14060 } 14061 } 14062 14063 if (Invalid) 14064 ExDecl->setInvalidDecl(); 14065 14066 return ExDecl; 14067 } 14068 14069 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 14070 /// handler. 14071 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 14072 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14073 bool Invalid = D.isInvalidType(); 14074 14075 // Check for unexpanded parameter packs. 14076 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14077 UPPC_ExceptionType)) { 14078 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 14079 D.getIdentifierLoc()); 14080 Invalid = true; 14081 } 14082 14083 IdentifierInfo *II = D.getIdentifier(); 14084 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 14085 LookupOrdinaryName, 14086 ForVisibleRedeclaration)) { 14087 // The scope should be freshly made just for us. There is just no way 14088 // it contains any previous declaration, except for function parameters in 14089 // a function-try-block's catch statement. 14090 assert(!S->isDeclScope(PrevDecl)); 14091 if (isDeclInScope(PrevDecl, CurContext, S)) { 14092 Diag(D.getIdentifierLoc(), diag::err_redefinition) 14093 << D.getIdentifier(); 14094 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14095 Invalid = true; 14096 } else if (PrevDecl->isTemplateParameter()) 14097 // Maybe we will complain about the shadowed template parameter. 14098 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14099 } 14100 14101 if (D.getCXXScopeSpec().isSet() && !Invalid) { 14102 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 14103 << D.getCXXScopeSpec().getRange(); 14104 Invalid = true; 14105 } 14106 14107 VarDecl *ExDecl = BuildExceptionDeclaration( 14108 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 14109 if (Invalid) 14110 ExDecl->setInvalidDecl(); 14111 14112 // Add the exception declaration into this scope. 14113 if (II) 14114 PushOnScopeChains(ExDecl, S); 14115 else 14116 CurContext->addDecl(ExDecl); 14117 14118 ProcessDeclAttributes(S, ExDecl, D); 14119 return ExDecl; 14120 } 14121 14122 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 14123 Expr *AssertExpr, 14124 Expr *AssertMessageExpr, 14125 SourceLocation RParenLoc) { 14126 StringLiteral *AssertMessage = 14127 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 14128 14129 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 14130 return nullptr; 14131 14132 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 14133 AssertMessage, RParenLoc, false); 14134 } 14135 14136 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 14137 Expr *AssertExpr, 14138 StringLiteral *AssertMessage, 14139 SourceLocation RParenLoc, 14140 bool Failed) { 14141 assert(AssertExpr != nullptr && "Expected non-null condition"); 14142 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 14143 !Failed) { 14144 // In a static_assert-declaration, the constant-expression shall be a 14145 // constant expression that can be contextually converted to bool. 14146 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 14147 if (Converted.isInvalid()) 14148 Failed = true; 14149 14150 llvm::APSInt Cond; 14151 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 14152 diag::err_static_assert_expression_is_not_constant, 14153 /*AllowFold=*/false).isInvalid()) 14154 Failed = true; 14155 14156 if (!Failed && !Cond) { 14157 SmallString<256> MsgBuffer; 14158 llvm::raw_svector_ostream Msg(MsgBuffer); 14159 if (AssertMessage) 14160 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 14161 14162 Expr *InnerCond = nullptr; 14163 std::string InnerCondDescription; 14164 std::tie(InnerCond, InnerCondDescription) = 14165 findFailedBooleanCondition(Converted.get()); 14166 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 14167 && !isa<IntegerLiteral>(InnerCond)) { 14168 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 14169 << InnerCondDescription << !AssertMessage 14170 << Msg.str() << InnerCond->getSourceRange(); 14171 } else { 14172 Diag(StaticAssertLoc, diag::err_static_assert_failed) 14173 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 14174 } 14175 Failed = true; 14176 } 14177 } 14178 14179 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 14180 /*DiscardedValue*/false, 14181 /*IsConstexpr*/true); 14182 if (FullAssertExpr.isInvalid()) 14183 Failed = true; 14184 else 14185 AssertExpr = FullAssertExpr.get(); 14186 14187 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 14188 AssertExpr, AssertMessage, RParenLoc, 14189 Failed); 14190 14191 CurContext->addDecl(Decl); 14192 return Decl; 14193 } 14194 14195 /// Perform semantic analysis of the given friend type declaration. 14196 /// 14197 /// \returns A friend declaration that. 14198 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 14199 SourceLocation FriendLoc, 14200 TypeSourceInfo *TSInfo) { 14201 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 14202 14203 QualType T = TSInfo->getType(); 14204 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 14205 14206 // C++03 [class.friend]p2: 14207 // An elaborated-type-specifier shall be used in a friend declaration 14208 // for a class.* 14209 // 14210 // * The class-key of the elaborated-type-specifier is required. 14211 if (!CodeSynthesisContexts.empty()) { 14212 // Do not complain about the form of friend template types during any kind 14213 // of code synthesis. For template instantiation, we will have complained 14214 // when the template was defined. 14215 } else { 14216 if (!T->isElaboratedTypeSpecifier()) { 14217 // If we evaluated the type to a record type, suggest putting 14218 // a tag in front. 14219 if (const RecordType *RT = T->getAs<RecordType>()) { 14220 RecordDecl *RD = RT->getDecl(); 14221 14222 SmallString<16> InsertionText(" "); 14223 InsertionText += RD->getKindName(); 14224 14225 Diag(TypeRange.getBegin(), 14226 getLangOpts().CPlusPlus11 ? 14227 diag::warn_cxx98_compat_unelaborated_friend_type : 14228 diag::ext_unelaborated_friend_type) 14229 << (unsigned) RD->getTagKind() 14230 << T 14231 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 14232 InsertionText); 14233 } else { 14234 Diag(FriendLoc, 14235 getLangOpts().CPlusPlus11 ? 14236 diag::warn_cxx98_compat_nonclass_type_friend : 14237 diag::ext_nonclass_type_friend) 14238 << T 14239 << TypeRange; 14240 } 14241 } else if (T->getAs<EnumType>()) { 14242 Diag(FriendLoc, 14243 getLangOpts().CPlusPlus11 ? 14244 diag::warn_cxx98_compat_enum_friend : 14245 diag::ext_enum_friend) 14246 << T 14247 << TypeRange; 14248 } 14249 14250 // C++11 [class.friend]p3: 14251 // A friend declaration that does not declare a function shall have one 14252 // of the following forms: 14253 // friend elaborated-type-specifier ; 14254 // friend simple-type-specifier ; 14255 // friend typename-specifier ; 14256 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 14257 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 14258 } 14259 14260 // If the type specifier in a friend declaration designates a (possibly 14261 // cv-qualified) class type, that class is declared as a friend; otherwise, 14262 // the friend declaration is ignored. 14263 return FriendDecl::Create(Context, CurContext, 14264 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 14265 FriendLoc); 14266 } 14267 14268 /// Handle a friend tag declaration where the scope specifier was 14269 /// templated. 14270 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 14271 unsigned TagSpec, SourceLocation TagLoc, 14272 CXXScopeSpec &SS, IdentifierInfo *Name, 14273 SourceLocation NameLoc, 14274 const ParsedAttributesView &Attr, 14275 MultiTemplateParamsArg TempParamLists) { 14276 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14277 14278 bool IsMemberSpecialization = false; 14279 bool Invalid = false; 14280 14281 if (TemplateParameterList *TemplateParams = 14282 MatchTemplateParametersToScopeSpecifier( 14283 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 14284 IsMemberSpecialization, Invalid)) { 14285 if (TemplateParams->size() > 0) { 14286 // This is a declaration of a class template. 14287 if (Invalid) 14288 return nullptr; 14289 14290 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 14291 NameLoc, Attr, TemplateParams, AS_public, 14292 /*ModulePrivateLoc=*/SourceLocation(), 14293 FriendLoc, TempParamLists.size() - 1, 14294 TempParamLists.data()).get(); 14295 } else { 14296 // The "template<>" header is extraneous. 14297 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14298 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14299 IsMemberSpecialization = true; 14300 } 14301 } 14302 14303 if (Invalid) return nullptr; 14304 14305 bool isAllExplicitSpecializations = true; 14306 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 14307 if (TempParamLists[I]->size()) { 14308 isAllExplicitSpecializations = false; 14309 break; 14310 } 14311 } 14312 14313 // FIXME: don't ignore attributes. 14314 14315 // If it's explicit specializations all the way down, just forget 14316 // about the template header and build an appropriate non-templated 14317 // friend. TODO: for source fidelity, remember the headers. 14318 if (isAllExplicitSpecializations) { 14319 if (SS.isEmpty()) { 14320 bool Owned = false; 14321 bool IsDependent = false; 14322 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 14323 Attr, AS_public, 14324 /*ModulePrivateLoc=*/SourceLocation(), 14325 MultiTemplateParamsArg(), Owned, IsDependent, 14326 /*ScopedEnumKWLoc=*/SourceLocation(), 14327 /*ScopedEnumUsesClassTag=*/false, 14328 /*UnderlyingType=*/TypeResult(), 14329 /*IsTypeSpecifier=*/false, 14330 /*IsTemplateParamOrArg=*/false); 14331 } 14332 14333 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 14334 ElaboratedTypeKeyword Keyword 14335 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14336 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 14337 *Name, NameLoc); 14338 if (T.isNull()) 14339 return nullptr; 14340 14341 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14342 if (isa<DependentNameType>(T)) { 14343 DependentNameTypeLoc TL = 14344 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14345 TL.setElaboratedKeywordLoc(TagLoc); 14346 TL.setQualifierLoc(QualifierLoc); 14347 TL.setNameLoc(NameLoc); 14348 } else { 14349 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 14350 TL.setElaboratedKeywordLoc(TagLoc); 14351 TL.setQualifierLoc(QualifierLoc); 14352 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 14353 } 14354 14355 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14356 TSI, FriendLoc, TempParamLists); 14357 Friend->setAccess(AS_public); 14358 CurContext->addDecl(Friend); 14359 return Friend; 14360 } 14361 14362 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 14363 14364 14365 14366 // Handle the case of a templated-scope friend class. e.g. 14367 // template <class T> class A<T>::B; 14368 // FIXME: we don't support these right now. 14369 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 14370 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 14371 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14372 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 14373 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14374 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14375 TL.setElaboratedKeywordLoc(TagLoc); 14376 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 14377 TL.setNameLoc(NameLoc); 14378 14379 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14380 TSI, FriendLoc, TempParamLists); 14381 Friend->setAccess(AS_public); 14382 Friend->setUnsupportedFriend(true); 14383 CurContext->addDecl(Friend); 14384 return Friend; 14385 } 14386 14387 /// Handle a friend type declaration. This works in tandem with 14388 /// ActOnTag. 14389 /// 14390 /// Notes on friend class templates: 14391 /// 14392 /// We generally treat friend class declarations as if they were 14393 /// declaring a class. So, for example, the elaborated type specifier 14394 /// in a friend declaration is required to obey the restrictions of a 14395 /// class-head (i.e. no typedefs in the scope chain), template 14396 /// parameters are required to match up with simple template-ids, &c. 14397 /// However, unlike when declaring a template specialization, it's 14398 /// okay to refer to a template specialization without an empty 14399 /// template parameter declaration, e.g. 14400 /// friend class A<T>::B<unsigned>; 14401 /// We permit this as a special case; if there are any template 14402 /// parameters present at all, require proper matching, i.e. 14403 /// template <> template \<class T> friend class A<int>::B; 14404 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14405 MultiTemplateParamsArg TempParams) { 14406 SourceLocation Loc = DS.getBeginLoc(); 14407 14408 assert(DS.isFriendSpecified()); 14409 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14410 14411 // C++ [class.friend]p3: 14412 // A friend declaration that does not declare a function shall have one of 14413 // the following forms: 14414 // friend elaborated-type-specifier ; 14415 // friend simple-type-specifier ; 14416 // friend typename-specifier ; 14417 // 14418 // Any declaration with a type qualifier does not have that form. (It's 14419 // legal to specify a qualified type as a friend, you just can't write the 14420 // keywords.) 14421 if (DS.getTypeQualifiers()) { 14422 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 14423 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 14424 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 14425 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 14426 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 14427 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 14428 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 14429 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 14430 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 14431 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 14432 } 14433 14434 // Try to convert the decl specifier to a type. This works for 14435 // friend templates because ActOnTag never produces a ClassTemplateDecl 14436 // for a TUK_Friend. 14437 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14438 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14439 QualType T = TSI->getType(); 14440 if (TheDeclarator.isInvalidType()) 14441 return nullptr; 14442 14443 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14444 return nullptr; 14445 14446 // This is definitely an error in C++98. It's probably meant to 14447 // be forbidden in C++0x, too, but the specification is just 14448 // poorly written. 14449 // 14450 // The problem is with declarations like the following: 14451 // template <T> friend A<T>::foo; 14452 // where deciding whether a class C is a friend or not now hinges 14453 // on whether there exists an instantiation of A that causes 14454 // 'foo' to equal C. There are restrictions on class-heads 14455 // (which we declare (by fiat) elaborated friend declarations to 14456 // be) that makes this tractable. 14457 // 14458 // FIXME: handle "template <> friend class A<T>;", which 14459 // is possibly well-formed? Who even knows? 14460 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14461 Diag(Loc, diag::err_tagless_friend_type_template) 14462 << DS.getSourceRange(); 14463 return nullptr; 14464 } 14465 14466 // C++98 [class.friend]p1: A friend of a class is a function 14467 // or class that is not a member of the class . . . 14468 // This is fixed in DR77, which just barely didn't make the C++03 14469 // deadline. It's also a very silly restriction that seriously 14470 // affects inner classes and which nobody else seems to implement; 14471 // thus we never diagnose it, not even in -pedantic. 14472 // 14473 // But note that we could warn about it: it's always useless to 14474 // friend one of your own members (it's not, however, worthless to 14475 // friend a member of an arbitrary specialization of your template). 14476 14477 Decl *D; 14478 if (!TempParams.empty()) 14479 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14480 TempParams, 14481 TSI, 14482 DS.getFriendSpecLoc()); 14483 else 14484 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14485 14486 if (!D) 14487 return nullptr; 14488 14489 D->setAccess(AS_public); 14490 CurContext->addDecl(D); 14491 14492 return D; 14493 } 14494 14495 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14496 MultiTemplateParamsArg TemplateParams) { 14497 const DeclSpec &DS = D.getDeclSpec(); 14498 14499 assert(DS.isFriendSpecified()); 14500 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14501 14502 SourceLocation Loc = D.getIdentifierLoc(); 14503 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14504 14505 // C++ [class.friend]p1 14506 // A friend of a class is a function or class.... 14507 // Note that this sees through typedefs, which is intended. 14508 // It *doesn't* see through dependent types, which is correct 14509 // according to [temp.arg.type]p3: 14510 // If a declaration acquires a function type through a 14511 // type dependent on a template-parameter and this causes 14512 // a declaration that does not use the syntactic form of a 14513 // function declarator to have a function type, the program 14514 // is ill-formed. 14515 if (!TInfo->getType()->isFunctionType()) { 14516 Diag(Loc, diag::err_unexpected_friend); 14517 14518 // It might be worthwhile to try to recover by creating an 14519 // appropriate declaration. 14520 return nullptr; 14521 } 14522 14523 // C++ [namespace.memdef]p3 14524 // - If a friend declaration in a non-local class first declares a 14525 // class or function, the friend class or function is a member 14526 // of the innermost enclosing namespace. 14527 // - The name of the friend is not found by simple name lookup 14528 // until a matching declaration is provided in that namespace 14529 // scope (either before or after the class declaration granting 14530 // friendship). 14531 // - If a friend function is called, its name may be found by the 14532 // name lookup that considers functions from namespaces and 14533 // classes associated with the types of the function arguments. 14534 // - When looking for a prior declaration of a class or a function 14535 // declared as a friend, scopes outside the innermost enclosing 14536 // namespace scope are not considered. 14537 14538 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14539 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14540 assert(NameInfo.getName()); 14541 14542 // Check for unexpanded parameter packs. 14543 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14544 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14545 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14546 return nullptr; 14547 14548 // The context we found the declaration in, or in which we should 14549 // create the declaration. 14550 DeclContext *DC; 14551 Scope *DCScope = S; 14552 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14553 ForExternalRedeclaration); 14554 14555 // There are five cases here. 14556 // - There's no scope specifier and we're in a local class. Only look 14557 // for functions declared in the immediately-enclosing block scope. 14558 // We recover from invalid scope qualifiers as if they just weren't there. 14559 FunctionDecl *FunctionContainingLocalClass = nullptr; 14560 if ((SS.isInvalid() || !SS.isSet()) && 14561 (FunctionContainingLocalClass = 14562 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14563 // C++11 [class.friend]p11: 14564 // If a friend declaration appears in a local class and the name 14565 // specified is an unqualified name, a prior declaration is 14566 // looked up without considering scopes that are outside the 14567 // innermost enclosing non-class scope. For a friend function 14568 // declaration, if there is no prior declaration, the program is 14569 // ill-formed. 14570 14571 // Find the innermost enclosing non-class scope. This is the block 14572 // scope containing the local class definition (or for a nested class, 14573 // the outer local class). 14574 DCScope = S->getFnParent(); 14575 14576 // Look up the function name in the scope. 14577 Previous.clear(LookupLocalFriendName); 14578 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14579 14580 if (!Previous.empty()) { 14581 // All possible previous declarations must have the same context: 14582 // either they were declared at block scope or they are members of 14583 // one of the enclosing local classes. 14584 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14585 } else { 14586 // This is ill-formed, but provide the context that we would have 14587 // declared the function in, if we were permitted to, for error recovery. 14588 DC = FunctionContainingLocalClass; 14589 } 14590 adjustContextForLocalExternDecl(DC); 14591 14592 // C++ [class.friend]p6: 14593 // A function can be defined in a friend declaration of a class if and 14594 // only if the class is a non-local class (9.8), the function name is 14595 // unqualified, and the function has namespace scope. 14596 if (D.isFunctionDefinition()) { 14597 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14598 } 14599 14600 // - There's no scope specifier, in which case we just go to the 14601 // appropriate scope and look for a function or function template 14602 // there as appropriate. 14603 } else if (SS.isInvalid() || !SS.isSet()) { 14604 // C++11 [namespace.memdef]p3: 14605 // If the name in a friend declaration is neither qualified nor 14606 // a template-id and the declaration is a function or an 14607 // elaborated-type-specifier, the lookup to determine whether 14608 // the entity has been previously declared shall not consider 14609 // any scopes outside the innermost enclosing namespace. 14610 bool isTemplateId = 14611 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14612 14613 // Find the appropriate context according to the above. 14614 DC = CurContext; 14615 14616 // Skip class contexts. If someone can cite chapter and verse 14617 // for this behavior, that would be nice --- it's what GCC and 14618 // EDG do, and it seems like a reasonable intent, but the spec 14619 // really only says that checks for unqualified existing 14620 // declarations should stop at the nearest enclosing namespace, 14621 // not that they should only consider the nearest enclosing 14622 // namespace. 14623 while (DC->isRecord()) 14624 DC = DC->getParent(); 14625 14626 DeclContext *LookupDC = DC; 14627 while (LookupDC->isTransparentContext()) 14628 LookupDC = LookupDC->getParent(); 14629 14630 while (true) { 14631 LookupQualifiedName(Previous, LookupDC); 14632 14633 if (!Previous.empty()) { 14634 DC = LookupDC; 14635 break; 14636 } 14637 14638 if (isTemplateId) { 14639 if (isa<TranslationUnitDecl>(LookupDC)) break; 14640 } else { 14641 if (LookupDC->isFileContext()) break; 14642 } 14643 LookupDC = LookupDC->getParent(); 14644 } 14645 14646 DCScope = getScopeForDeclContext(S, DC); 14647 14648 // - There's a non-dependent scope specifier, in which case we 14649 // compute it and do a previous lookup there for a function 14650 // or function template. 14651 } else if (!SS.getScopeRep()->isDependent()) { 14652 DC = computeDeclContext(SS); 14653 if (!DC) return nullptr; 14654 14655 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14656 14657 LookupQualifiedName(Previous, DC); 14658 14659 // C++ [class.friend]p1: A friend of a class is a function or 14660 // class that is not a member of the class . . . 14661 if (DC->Equals(CurContext)) 14662 Diag(DS.getFriendSpecLoc(), 14663 getLangOpts().CPlusPlus11 ? 14664 diag::warn_cxx98_compat_friend_is_member : 14665 diag::err_friend_is_member); 14666 14667 if (D.isFunctionDefinition()) { 14668 // C++ [class.friend]p6: 14669 // A function can be defined in a friend declaration of a class if and 14670 // only if the class is a non-local class (9.8), the function name is 14671 // unqualified, and the function has namespace scope. 14672 // 14673 // FIXME: We should only do this if the scope specifier names the 14674 // innermost enclosing namespace; otherwise the fixit changes the 14675 // meaning of the code. 14676 SemaDiagnosticBuilder DB 14677 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14678 14679 DB << SS.getScopeRep(); 14680 if (DC->isFileContext()) 14681 DB << FixItHint::CreateRemoval(SS.getRange()); 14682 SS.clear(); 14683 } 14684 14685 // - There's a scope specifier that does not match any template 14686 // parameter lists, in which case we use some arbitrary context, 14687 // create a method or method template, and wait for instantiation. 14688 // - There's a scope specifier that does match some template 14689 // parameter lists, which we don't handle right now. 14690 } else { 14691 if (D.isFunctionDefinition()) { 14692 // C++ [class.friend]p6: 14693 // A function can be defined in a friend declaration of a class if and 14694 // only if the class is a non-local class (9.8), the function name is 14695 // unqualified, and the function has namespace scope. 14696 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14697 << SS.getScopeRep(); 14698 } 14699 14700 DC = CurContext; 14701 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14702 } 14703 14704 if (!DC->isRecord()) { 14705 int DiagArg = -1; 14706 switch (D.getName().getKind()) { 14707 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14708 case UnqualifiedIdKind::IK_ConstructorName: 14709 DiagArg = 0; 14710 break; 14711 case UnqualifiedIdKind::IK_DestructorName: 14712 DiagArg = 1; 14713 break; 14714 case UnqualifiedIdKind::IK_ConversionFunctionId: 14715 DiagArg = 2; 14716 break; 14717 case UnqualifiedIdKind::IK_DeductionGuideName: 14718 DiagArg = 3; 14719 break; 14720 case UnqualifiedIdKind::IK_Identifier: 14721 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14722 case UnqualifiedIdKind::IK_LiteralOperatorId: 14723 case UnqualifiedIdKind::IK_OperatorFunctionId: 14724 case UnqualifiedIdKind::IK_TemplateId: 14725 break; 14726 } 14727 // This implies that it has to be an operator or function. 14728 if (DiagArg >= 0) { 14729 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14730 return nullptr; 14731 } 14732 } 14733 14734 // FIXME: This is an egregious hack to cope with cases where the scope stack 14735 // does not contain the declaration context, i.e., in an out-of-line 14736 // definition of a class. 14737 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14738 if (!DCScope) { 14739 FakeDCScope.setEntity(DC); 14740 DCScope = &FakeDCScope; 14741 } 14742 14743 bool AddToScope = true; 14744 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14745 TemplateParams, AddToScope); 14746 if (!ND) return nullptr; 14747 14748 assert(ND->getLexicalDeclContext() == CurContext); 14749 14750 // If we performed typo correction, we might have added a scope specifier 14751 // and changed the decl context. 14752 DC = ND->getDeclContext(); 14753 14754 // Add the function declaration to the appropriate lookup tables, 14755 // adjusting the redeclarations list as necessary. We don't 14756 // want to do this yet if the friending class is dependent. 14757 // 14758 // Also update the scope-based lookup if the target context's 14759 // lookup context is in lexical scope. 14760 if (!CurContext->isDependentContext()) { 14761 DC = DC->getRedeclContext(); 14762 DC->makeDeclVisibleInContext(ND); 14763 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14764 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14765 } 14766 14767 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14768 D.getIdentifierLoc(), ND, 14769 DS.getFriendSpecLoc()); 14770 FrD->setAccess(AS_public); 14771 CurContext->addDecl(FrD); 14772 14773 if (ND->isInvalidDecl()) { 14774 FrD->setInvalidDecl(); 14775 } else { 14776 if (DC->isRecord()) CheckFriendAccess(ND); 14777 14778 FunctionDecl *FD; 14779 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14780 FD = FTD->getTemplatedDecl(); 14781 else 14782 FD = cast<FunctionDecl>(ND); 14783 14784 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14785 // default argument expression, that declaration shall be a definition 14786 // and shall be the only declaration of the function or function 14787 // template in the translation unit. 14788 if (functionDeclHasDefaultArgument(FD)) { 14789 // We can't look at FD->getPreviousDecl() because it may not have been set 14790 // if we're in a dependent context. If the function is known to be a 14791 // redeclaration, we will have narrowed Previous down to the right decl. 14792 if (D.isRedeclaration()) { 14793 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14794 Diag(Previous.getRepresentativeDecl()->getLocation(), 14795 diag::note_previous_declaration); 14796 } else if (!D.isFunctionDefinition()) 14797 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14798 } 14799 14800 // Mark templated-scope function declarations as unsupported. 14801 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14802 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14803 << SS.getScopeRep() << SS.getRange() 14804 << cast<CXXRecordDecl>(CurContext); 14805 FrD->setUnsupportedFriend(true); 14806 } 14807 } 14808 14809 return ND; 14810 } 14811 14812 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14813 AdjustDeclIfTemplate(Dcl); 14814 14815 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14816 if (!Fn) { 14817 Diag(DelLoc, diag::err_deleted_non_function); 14818 return; 14819 } 14820 14821 // Deleted function does not have a body. 14822 Fn->setWillHaveBody(false); 14823 14824 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14825 // Don't consider the implicit declaration we generate for explicit 14826 // specializations. FIXME: Do not generate these implicit declarations. 14827 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14828 Prev->getPreviousDecl()) && 14829 !Prev->isDefined()) { 14830 Diag(DelLoc, diag::err_deleted_decl_not_first); 14831 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14832 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14833 : diag::note_previous_declaration); 14834 } 14835 // If the declaration wasn't the first, we delete the function anyway for 14836 // recovery. 14837 Fn = Fn->getCanonicalDecl(); 14838 } 14839 14840 // dllimport/dllexport cannot be deleted. 14841 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14842 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14843 Fn->setInvalidDecl(); 14844 } 14845 14846 if (Fn->isDeleted()) 14847 return; 14848 14849 // See if we're deleting a function which is already known to override a 14850 // non-deleted virtual function. 14851 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14852 bool IssuedDiagnostic = false; 14853 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14854 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14855 if (!IssuedDiagnostic) { 14856 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14857 IssuedDiagnostic = true; 14858 } 14859 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14860 } 14861 } 14862 // If this function was implicitly deleted because it was defaulted, 14863 // explain why it was deleted. 14864 if (IssuedDiagnostic && MD->isDefaulted()) 14865 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14866 /*Diagnose*/true); 14867 } 14868 14869 // C++11 [basic.start.main]p3: 14870 // A program that defines main as deleted [...] is ill-formed. 14871 if (Fn->isMain()) 14872 Diag(DelLoc, diag::err_deleted_main); 14873 14874 // C++11 [dcl.fct.def.delete]p4: 14875 // A deleted function is implicitly inline. 14876 Fn->setImplicitlyInline(); 14877 Fn->setDeletedAsWritten(); 14878 } 14879 14880 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14881 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14882 14883 if (MD) { 14884 if (MD->getParent()->isDependentType()) { 14885 MD->setDefaulted(); 14886 MD->setExplicitlyDefaulted(); 14887 return; 14888 } 14889 14890 CXXSpecialMember Member = getSpecialMember(MD); 14891 if (Member == CXXInvalid) { 14892 if (!MD->isInvalidDecl()) 14893 Diag(DefaultLoc, diag::err_default_special_members); 14894 return; 14895 } 14896 14897 MD->setDefaulted(); 14898 MD->setExplicitlyDefaulted(); 14899 14900 // Unset that we will have a body for this function. We might not, 14901 // if it turns out to be trivial, and we don't need this marking now 14902 // that we've marked it as defaulted. 14903 MD->setWillHaveBody(false); 14904 14905 // If this definition appears within the record, do the checking when 14906 // the record is complete. 14907 const FunctionDecl *Primary = MD; 14908 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14909 // Ask the template instantiation pattern that actually had the 14910 // '= default' on it. 14911 Primary = Pattern; 14912 14913 // If the method was defaulted on its first declaration, we will have 14914 // already performed the checking in CheckCompletedCXXClass. Such a 14915 // declaration doesn't trigger an implicit definition. 14916 if (Primary->getCanonicalDecl()->isDefaulted()) 14917 return; 14918 14919 CheckExplicitlyDefaultedSpecialMember(MD); 14920 14921 if (!MD->isInvalidDecl()) 14922 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14923 } else { 14924 Diag(DefaultLoc, diag::err_default_special_members); 14925 } 14926 } 14927 14928 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14929 for (Stmt *SubStmt : S->children()) { 14930 if (!SubStmt) 14931 continue; 14932 if (isa<ReturnStmt>(SubStmt)) 14933 Self.Diag(SubStmt->getBeginLoc(), 14934 diag::err_return_in_constructor_handler); 14935 if (!isa<Expr>(SubStmt)) 14936 SearchForReturnInStmt(Self, SubStmt); 14937 } 14938 } 14939 14940 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14941 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14942 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14943 SearchForReturnInStmt(*this, Handler); 14944 } 14945 } 14946 14947 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14948 const CXXMethodDecl *Old) { 14949 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14950 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14951 14952 if (OldFT->hasExtParameterInfos()) { 14953 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14954 // A parameter of the overriding method should be annotated with noescape 14955 // if the corresponding parameter of the overridden method is annotated. 14956 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14957 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14958 Diag(New->getParamDecl(I)->getLocation(), 14959 diag::warn_overriding_method_missing_noescape); 14960 Diag(Old->getParamDecl(I)->getLocation(), 14961 diag::note_overridden_marked_noescape); 14962 } 14963 } 14964 14965 // Virtual overrides must have the same code_seg. 14966 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 14967 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 14968 if ((NewCSA || OldCSA) && 14969 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 14970 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 14971 Diag(Old->getLocation(), diag::note_previous_declaration); 14972 return true; 14973 } 14974 14975 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14976 14977 // If the calling conventions match, everything is fine 14978 if (NewCC == OldCC) 14979 return false; 14980 14981 // If the calling conventions mismatch because the new function is static, 14982 // suppress the calling convention mismatch error; the error about static 14983 // function override (err_static_overrides_virtual from 14984 // Sema::CheckFunctionDeclaration) is more clear. 14985 if (New->getStorageClass() == SC_Static) 14986 return false; 14987 14988 Diag(New->getLocation(), 14989 diag::err_conflicting_overriding_cc_attributes) 14990 << New->getDeclName() << New->getType() << Old->getType(); 14991 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14992 return true; 14993 } 14994 14995 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14996 const CXXMethodDecl *Old) { 14997 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14998 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14999 15000 if (Context.hasSameType(NewTy, OldTy) || 15001 NewTy->isDependentType() || OldTy->isDependentType()) 15002 return false; 15003 15004 // Check if the return types are covariant 15005 QualType NewClassTy, OldClassTy; 15006 15007 /// Both types must be pointers or references to classes. 15008 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 15009 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 15010 NewClassTy = NewPT->getPointeeType(); 15011 OldClassTy = OldPT->getPointeeType(); 15012 } 15013 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 15014 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 15015 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 15016 NewClassTy = NewRT->getPointeeType(); 15017 OldClassTy = OldRT->getPointeeType(); 15018 } 15019 } 15020 } 15021 15022 // The return types aren't either both pointers or references to a class type. 15023 if (NewClassTy.isNull()) { 15024 Diag(New->getLocation(), 15025 diag::err_different_return_type_for_overriding_virtual_function) 15026 << New->getDeclName() << NewTy << OldTy 15027 << New->getReturnTypeSourceRange(); 15028 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15029 << Old->getReturnTypeSourceRange(); 15030 15031 return true; 15032 } 15033 15034 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 15035 // C++14 [class.virtual]p8: 15036 // If the class type in the covariant return type of D::f differs from 15037 // that of B::f, the class type in the return type of D::f shall be 15038 // complete at the point of declaration of D::f or shall be the class 15039 // type D. 15040 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 15041 if (!RT->isBeingDefined() && 15042 RequireCompleteType(New->getLocation(), NewClassTy, 15043 diag::err_covariant_return_incomplete, 15044 New->getDeclName())) 15045 return true; 15046 } 15047 15048 // Check if the new class derives from the old class. 15049 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 15050 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 15051 << New->getDeclName() << NewTy << OldTy 15052 << New->getReturnTypeSourceRange(); 15053 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15054 << Old->getReturnTypeSourceRange(); 15055 return true; 15056 } 15057 15058 // Check if we the conversion from derived to base is valid. 15059 if (CheckDerivedToBaseConversion( 15060 NewClassTy, OldClassTy, 15061 diag::err_covariant_return_inaccessible_base, 15062 diag::err_covariant_return_ambiguous_derived_to_base_conv, 15063 New->getLocation(), New->getReturnTypeSourceRange(), 15064 New->getDeclName(), nullptr)) { 15065 // FIXME: this note won't trigger for delayed access control 15066 // diagnostics, and it's impossible to get an undelayed error 15067 // here from access control during the original parse because 15068 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 15069 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15070 << Old->getReturnTypeSourceRange(); 15071 return true; 15072 } 15073 } 15074 15075 // The qualifiers of the return types must be the same. 15076 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 15077 Diag(New->getLocation(), 15078 diag::err_covariant_return_type_different_qualifications) 15079 << New->getDeclName() << NewTy << OldTy 15080 << New->getReturnTypeSourceRange(); 15081 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15082 << Old->getReturnTypeSourceRange(); 15083 return true; 15084 } 15085 15086 15087 // The new class type must have the same or less qualifiers as the old type. 15088 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 15089 Diag(New->getLocation(), 15090 diag::err_covariant_return_type_class_type_more_qualified) 15091 << New->getDeclName() << NewTy << OldTy 15092 << New->getReturnTypeSourceRange(); 15093 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15094 << Old->getReturnTypeSourceRange(); 15095 return true; 15096 } 15097 15098 return false; 15099 } 15100 15101 /// Mark the given method pure. 15102 /// 15103 /// \param Method the method to be marked pure. 15104 /// 15105 /// \param InitRange the source range that covers the "0" initializer. 15106 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 15107 SourceLocation EndLoc = InitRange.getEnd(); 15108 if (EndLoc.isValid()) 15109 Method->setRangeEnd(EndLoc); 15110 15111 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 15112 Method->setPure(); 15113 return false; 15114 } 15115 15116 if (!Method->isInvalidDecl()) 15117 Diag(Method->getLocation(), diag::err_non_virtual_pure) 15118 << Method->getDeclName() << InitRange; 15119 return true; 15120 } 15121 15122 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 15123 if (D->getFriendObjectKind()) 15124 Diag(D->getLocation(), diag::err_pure_friend); 15125 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 15126 CheckPureMethod(M, ZeroLoc); 15127 else 15128 Diag(D->getLocation(), diag::err_illegal_initializer); 15129 } 15130 15131 /// Determine whether the given declaration is a global variable or 15132 /// static data member. 15133 static bool isNonlocalVariable(const Decl *D) { 15134 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 15135 return Var->hasGlobalStorage(); 15136 15137 return false; 15138 } 15139 15140 /// Invoked when we are about to parse an initializer for the declaration 15141 /// 'Dcl'. 15142 /// 15143 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 15144 /// static data member of class X, names should be looked up in the scope of 15145 /// class X. If the declaration had a scope specifier, a scope will have 15146 /// been created and passed in for this purpose. Otherwise, S will be null. 15147 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 15148 // If there is no declaration, there was an error parsing it. 15149 if (!D || D->isInvalidDecl()) 15150 return; 15151 15152 // We will always have a nested name specifier here, but this declaration 15153 // might not be out of line if the specifier names the current namespace: 15154 // extern int n; 15155 // int ::n = 0; 15156 if (S && D->isOutOfLine()) 15157 EnterDeclaratorContext(S, D->getDeclContext()); 15158 15159 // If we are parsing the initializer for a static data member, push a 15160 // new expression evaluation context that is associated with this static 15161 // data member. 15162 if (isNonlocalVariable(D)) 15163 PushExpressionEvaluationContext( 15164 ExpressionEvaluationContext::PotentiallyEvaluated, D); 15165 } 15166 15167 /// Invoked after we are finished parsing an initializer for the declaration D. 15168 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 15169 // If there is no declaration, there was an error parsing it. 15170 if (!D || D->isInvalidDecl()) 15171 return; 15172 15173 if (isNonlocalVariable(D)) 15174 PopExpressionEvaluationContext(); 15175 15176 if (S && D->isOutOfLine()) 15177 ExitDeclaratorContext(S); 15178 } 15179 15180 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 15181 /// C++ if/switch/while/for statement. 15182 /// e.g: "if (int x = f()) {...}" 15183 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 15184 // C++ 6.4p2: 15185 // The declarator shall not specify a function or an array. 15186 // The type-specifier-seq shall not contain typedef and shall not declare a 15187 // new class or enumeration. 15188 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 15189 "Parser allowed 'typedef' as storage class of condition decl."); 15190 15191 Decl *Dcl = ActOnDeclarator(S, D); 15192 if (!Dcl) 15193 return true; 15194 15195 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 15196 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 15197 << D.getSourceRange(); 15198 return true; 15199 } 15200 15201 return Dcl; 15202 } 15203 15204 void Sema::LoadExternalVTableUses() { 15205 if (!ExternalSource) 15206 return; 15207 15208 SmallVector<ExternalVTableUse, 4> VTables; 15209 ExternalSource->ReadUsedVTables(VTables); 15210 SmallVector<VTableUse, 4> NewUses; 15211 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 15212 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 15213 = VTablesUsed.find(VTables[I].Record); 15214 // Even if a definition wasn't required before, it may be required now. 15215 if (Pos != VTablesUsed.end()) { 15216 if (!Pos->second && VTables[I].DefinitionRequired) 15217 Pos->second = true; 15218 continue; 15219 } 15220 15221 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 15222 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 15223 } 15224 15225 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 15226 } 15227 15228 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 15229 bool DefinitionRequired) { 15230 // Ignore any vtable uses in unevaluated operands or for classes that do 15231 // not have a vtable. 15232 if (!Class->isDynamicClass() || Class->isDependentContext() || 15233 CurContext->isDependentContext() || isUnevaluatedContext()) 15234 return; 15235 // Do not mark as used if compiling for the device outside of the target 15236 // region. 15237 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 15238 !isInOpenMPDeclareTargetContext() && 15239 !isInOpenMPTargetExecutionDirective()) { 15240 if (!DefinitionRequired) 15241 MarkVirtualMembersReferenced(Loc, Class); 15242 return; 15243 } 15244 15245 // Try to insert this class into the map. 15246 LoadExternalVTableUses(); 15247 Class = Class->getCanonicalDecl(); 15248 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 15249 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 15250 if (!Pos.second) { 15251 // If we already had an entry, check to see if we are promoting this vtable 15252 // to require a definition. If so, we need to reappend to the VTableUses 15253 // list, since we may have already processed the first entry. 15254 if (DefinitionRequired && !Pos.first->second) { 15255 Pos.first->second = true; 15256 } else { 15257 // Otherwise, we can early exit. 15258 return; 15259 } 15260 } else { 15261 // The Microsoft ABI requires that we perform the destructor body 15262 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 15263 // the deleting destructor is emitted with the vtable, not with the 15264 // destructor definition as in the Itanium ABI. 15265 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15266 CXXDestructorDecl *DD = Class->getDestructor(); 15267 if (DD && DD->isVirtual() && !DD->isDeleted()) { 15268 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 15269 // If this is an out-of-line declaration, marking it referenced will 15270 // not do anything. Manually call CheckDestructor to look up operator 15271 // delete(). 15272 ContextRAII SavedContext(*this, DD); 15273 CheckDestructor(DD); 15274 } else { 15275 MarkFunctionReferenced(Loc, Class->getDestructor()); 15276 } 15277 } 15278 } 15279 } 15280 15281 // Local classes need to have their virtual members marked 15282 // immediately. For all other classes, we mark their virtual members 15283 // at the end of the translation unit. 15284 if (Class->isLocalClass()) 15285 MarkVirtualMembersReferenced(Loc, Class); 15286 else 15287 VTableUses.push_back(std::make_pair(Class, Loc)); 15288 } 15289 15290 bool Sema::DefineUsedVTables() { 15291 LoadExternalVTableUses(); 15292 if (VTableUses.empty()) 15293 return false; 15294 15295 // Note: The VTableUses vector could grow as a result of marking 15296 // the members of a class as "used", so we check the size each 15297 // time through the loop and prefer indices (which are stable) to 15298 // iterators (which are not). 15299 bool DefinedAnything = false; 15300 for (unsigned I = 0; I != VTableUses.size(); ++I) { 15301 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 15302 if (!Class) 15303 continue; 15304 TemplateSpecializationKind ClassTSK = 15305 Class->getTemplateSpecializationKind(); 15306 15307 SourceLocation Loc = VTableUses[I].second; 15308 15309 bool DefineVTable = true; 15310 15311 // If this class has a key function, but that key function is 15312 // defined in another translation unit, we don't need to emit the 15313 // vtable even though we're using it. 15314 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 15315 if (KeyFunction && !KeyFunction->hasBody()) { 15316 // The key function is in another translation unit. 15317 DefineVTable = false; 15318 TemplateSpecializationKind TSK = 15319 KeyFunction->getTemplateSpecializationKind(); 15320 assert(TSK != TSK_ExplicitInstantiationDefinition && 15321 TSK != TSK_ImplicitInstantiation && 15322 "Instantiations don't have key functions"); 15323 (void)TSK; 15324 } else if (!KeyFunction) { 15325 // If we have a class with no key function that is the subject 15326 // of an explicit instantiation declaration, suppress the 15327 // vtable; it will live with the explicit instantiation 15328 // definition. 15329 bool IsExplicitInstantiationDeclaration = 15330 ClassTSK == TSK_ExplicitInstantiationDeclaration; 15331 for (auto R : Class->redecls()) { 15332 TemplateSpecializationKind TSK 15333 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 15334 if (TSK == TSK_ExplicitInstantiationDeclaration) 15335 IsExplicitInstantiationDeclaration = true; 15336 else if (TSK == TSK_ExplicitInstantiationDefinition) { 15337 IsExplicitInstantiationDeclaration = false; 15338 break; 15339 } 15340 } 15341 15342 if (IsExplicitInstantiationDeclaration) 15343 DefineVTable = false; 15344 } 15345 15346 // The exception specifications for all virtual members may be needed even 15347 // if we are not providing an authoritative form of the vtable in this TU. 15348 // We may choose to emit it available_externally anyway. 15349 if (!DefineVTable) { 15350 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 15351 continue; 15352 } 15353 15354 // Mark all of the virtual members of this class as referenced, so 15355 // that we can build a vtable. Then, tell the AST consumer that a 15356 // vtable for this class is required. 15357 DefinedAnything = true; 15358 MarkVirtualMembersReferenced(Loc, Class); 15359 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 15360 if (VTablesUsed[Canonical]) 15361 Consumer.HandleVTable(Class); 15362 15363 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 15364 // no key function or the key function is inlined. Don't warn in C++ ABIs 15365 // that lack key functions, since the user won't be able to make one. 15366 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 15367 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 15368 const FunctionDecl *KeyFunctionDef = nullptr; 15369 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 15370 KeyFunctionDef->isInlined())) { 15371 Diag(Class->getLocation(), 15372 ClassTSK == TSK_ExplicitInstantiationDefinition 15373 ? diag::warn_weak_template_vtable 15374 : diag::warn_weak_vtable) 15375 << Class; 15376 } 15377 } 15378 } 15379 VTableUses.clear(); 15380 15381 return DefinedAnything; 15382 } 15383 15384 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 15385 const CXXRecordDecl *RD) { 15386 for (const auto *I : RD->methods()) 15387 if (I->isVirtual() && !I->isPure()) 15388 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 15389 } 15390 15391 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 15392 const CXXRecordDecl *RD, 15393 bool ConstexprOnly) { 15394 // Mark all functions which will appear in RD's vtable as used. 15395 CXXFinalOverriderMap FinalOverriders; 15396 RD->getFinalOverriders(FinalOverriders); 15397 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 15398 E = FinalOverriders.end(); 15399 I != E; ++I) { 15400 for (OverridingMethods::const_iterator OI = I->second.begin(), 15401 OE = I->second.end(); 15402 OI != OE; ++OI) { 15403 assert(OI->second.size() > 0 && "no final overrider"); 15404 CXXMethodDecl *Overrider = OI->second.front().Method; 15405 15406 // C++ [basic.def.odr]p2: 15407 // [...] A virtual member function is used if it is not pure. [...] 15408 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 15409 MarkFunctionReferenced(Loc, Overrider); 15410 } 15411 } 15412 15413 // Only classes that have virtual bases need a VTT. 15414 if (RD->getNumVBases() == 0) 15415 return; 15416 15417 for (const auto &I : RD->bases()) { 15418 const CXXRecordDecl *Base = 15419 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15420 if (Base->getNumVBases() == 0) 15421 continue; 15422 MarkVirtualMembersReferenced(Loc, Base); 15423 } 15424 } 15425 15426 /// SetIvarInitializers - This routine builds initialization ASTs for the 15427 /// Objective-C implementation whose ivars need be initialized. 15428 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15429 if (!getLangOpts().CPlusPlus) 15430 return; 15431 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15432 SmallVector<ObjCIvarDecl*, 8> ivars; 15433 CollectIvarsToConstructOrDestruct(OID, ivars); 15434 if (ivars.empty()) 15435 return; 15436 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15437 for (unsigned i = 0; i < ivars.size(); i++) { 15438 FieldDecl *Field = ivars[i]; 15439 if (Field->isInvalidDecl()) 15440 continue; 15441 15442 CXXCtorInitializer *Member; 15443 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15444 InitializationKind InitKind = 15445 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15446 15447 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15448 ExprResult MemberInit = 15449 InitSeq.Perform(*this, InitEntity, InitKind, None); 15450 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15451 // Note, MemberInit could actually come back empty if no initialization 15452 // is required (e.g., because it would call a trivial default constructor) 15453 if (!MemberInit.get() || MemberInit.isInvalid()) 15454 continue; 15455 15456 Member = 15457 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15458 SourceLocation(), 15459 MemberInit.getAs<Expr>(), 15460 SourceLocation()); 15461 AllToInit.push_back(Member); 15462 15463 // Be sure that the destructor is accessible and is marked as referenced. 15464 if (const RecordType *RecordTy = 15465 Context.getBaseElementType(Field->getType()) 15466 ->getAs<RecordType>()) { 15467 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15468 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15469 MarkFunctionReferenced(Field->getLocation(), Destructor); 15470 CheckDestructorAccess(Field->getLocation(), Destructor, 15471 PDiag(diag::err_access_dtor_ivar) 15472 << Context.getBaseElementType(Field->getType())); 15473 } 15474 } 15475 } 15476 ObjCImplementation->setIvarInitializers(Context, 15477 AllToInit.data(), AllToInit.size()); 15478 } 15479 } 15480 15481 static 15482 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15483 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15484 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15485 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15486 Sema &S) { 15487 if (Ctor->isInvalidDecl()) 15488 return; 15489 15490 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15491 15492 // Target may not be determinable yet, for instance if this is a dependent 15493 // call in an uninstantiated template. 15494 if (Target) { 15495 const FunctionDecl *FNTarget = nullptr; 15496 (void)Target->hasBody(FNTarget); 15497 Target = const_cast<CXXConstructorDecl*>( 15498 cast_or_null<CXXConstructorDecl>(FNTarget)); 15499 } 15500 15501 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15502 // Avoid dereferencing a null pointer here. 15503 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15504 15505 if (!Current.insert(Canonical).second) 15506 return; 15507 15508 // We know that beyond here, we aren't chaining into a cycle. 15509 if (!Target || !Target->isDelegatingConstructor() || 15510 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15511 Valid.insert(Current.begin(), Current.end()); 15512 Current.clear(); 15513 // We've hit a cycle. 15514 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15515 Current.count(TCanonical)) { 15516 // If we haven't diagnosed this cycle yet, do so now. 15517 if (!Invalid.count(TCanonical)) { 15518 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15519 diag::warn_delegating_ctor_cycle) 15520 << Ctor; 15521 15522 // Don't add a note for a function delegating directly to itself. 15523 if (TCanonical != Canonical) 15524 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15525 15526 CXXConstructorDecl *C = Target; 15527 while (C->getCanonicalDecl() != Canonical) { 15528 const FunctionDecl *FNTarget = nullptr; 15529 (void)C->getTargetConstructor()->hasBody(FNTarget); 15530 assert(FNTarget && "Ctor cycle through bodiless function"); 15531 15532 C = const_cast<CXXConstructorDecl*>( 15533 cast<CXXConstructorDecl>(FNTarget)); 15534 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15535 } 15536 } 15537 15538 Invalid.insert(Current.begin(), Current.end()); 15539 Current.clear(); 15540 } else { 15541 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15542 } 15543 } 15544 15545 15546 void Sema::CheckDelegatingCtorCycles() { 15547 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15548 15549 for (DelegatingCtorDeclsType::iterator 15550 I = DelegatingCtorDecls.begin(ExternalSource), 15551 E = DelegatingCtorDecls.end(); 15552 I != E; ++I) 15553 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15554 15555 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15556 (*CI)->setInvalidDecl(); 15557 } 15558 15559 namespace { 15560 /// AST visitor that finds references to the 'this' expression. 15561 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15562 Sema &S; 15563 15564 public: 15565 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15566 15567 bool VisitCXXThisExpr(CXXThisExpr *E) { 15568 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15569 << E->isImplicit(); 15570 return false; 15571 } 15572 }; 15573 } 15574 15575 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15576 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15577 if (!TSInfo) 15578 return false; 15579 15580 TypeLoc TL = TSInfo->getTypeLoc(); 15581 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15582 if (!ProtoTL) 15583 return false; 15584 15585 // C++11 [expr.prim.general]p3: 15586 // [The expression this] shall not appear before the optional 15587 // cv-qualifier-seq and it shall not appear within the declaration of a 15588 // static member function (although its type and value category are defined 15589 // within a static member function as they are within a non-static member 15590 // function). [ Note: this is because declaration matching does not occur 15591 // until the complete declarator is known. - end note ] 15592 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15593 FindCXXThisExpr Finder(*this); 15594 15595 // If the return type came after the cv-qualifier-seq, check it now. 15596 if (Proto->hasTrailingReturn() && 15597 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15598 return true; 15599 15600 // Check the exception specification. 15601 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15602 return true; 15603 15604 return checkThisInStaticMemberFunctionAttributes(Method); 15605 } 15606 15607 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15608 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15609 if (!TSInfo) 15610 return false; 15611 15612 TypeLoc TL = TSInfo->getTypeLoc(); 15613 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15614 if (!ProtoTL) 15615 return false; 15616 15617 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15618 FindCXXThisExpr Finder(*this); 15619 15620 switch (Proto->getExceptionSpecType()) { 15621 case EST_Unparsed: 15622 case EST_Uninstantiated: 15623 case EST_Unevaluated: 15624 case EST_BasicNoexcept: 15625 case EST_NoThrow: 15626 case EST_DynamicNone: 15627 case EST_MSAny: 15628 case EST_None: 15629 break; 15630 15631 case EST_DependentNoexcept: 15632 case EST_NoexceptFalse: 15633 case EST_NoexceptTrue: 15634 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15635 return true; 15636 LLVM_FALLTHROUGH; 15637 15638 case EST_Dynamic: 15639 for (const auto &E : Proto->exceptions()) { 15640 if (!Finder.TraverseType(E)) 15641 return true; 15642 } 15643 break; 15644 } 15645 15646 return false; 15647 } 15648 15649 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15650 FindCXXThisExpr Finder(*this); 15651 15652 // Check attributes. 15653 for (const auto *A : Method->attrs()) { 15654 // FIXME: This should be emitted by tblgen. 15655 Expr *Arg = nullptr; 15656 ArrayRef<Expr *> Args; 15657 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15658 Arg = G->getArg(); 15659 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15660 Arg = G->getArg(); 15661 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15662 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15663 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15664 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15665 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15666 Arg = ETLF->getSuccessValue(); 15667 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15668 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15669 Arg = STLF->getSuccessValue(); 15670 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15671 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15672 Arg = LR->getArg(); 15673 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15674 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15675 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15676 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15677 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15678 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15679 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15680 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15681 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15682 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15683 15684 if (Arg && !Finder.TraverseStmt(Arg)) 15685 return true; 15686 15687 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15688 if (!Finder.TraverseStmt(Args[I])) 15689 return true; 15690 } 15691 } 15692 15693 return false; 15694 } 15695 15696 void Sema::checkExceptionSpecification( 15697 bool IsTopLevel, ExceptionSpecificationType EST, 15698 ArrayRef<ParsedType> DynamicExceptions, 15699 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15700 SmallVectorImpl<QualType> &Exceptions, 15701 FunctionProtoType::ExceptionSpecInfo &ESI) { 15702 Exceptions.clear(); 15703 ESI.Type = EST; 15704 if (EST == EST_Dynamic) { 15705 Exceptions.reserve(DynamicExceptions.size()); 15706 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15707 // FIXME: Preserve type source info. 15708 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15709 15710 if (IsTopLevel) { 15711 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15712 collectUnexpandedParameterPacks(ET, Unexpanded); 15713 if (!Unexpanded.empty()) { 15714 DiagnoseUnexpandedParameterPacks( 15715 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15716 Unexpanded); 15717 continue; 15718 } 15719 } 15720 15721 // Check that the type is valid for an exception spec, and 15722 // drop it if not. 15723 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15724 Exceptions.push_back(ET); 15725 } 15726 ESI.Exceptions = Exceptions; 15727 return; 15728 } 15729 15730 if (isComputedNoexcept(EST)) { 15731 assert((NoexceptExpr->isTypeDependent() || 15732 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15733 Context.BoolTy) && 15734 "Parser should have made sure that the expression is boolean"); 15735 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15736 ESI.Type = EST_BasicNoexcept; 15737 return; 15738 } 15739 15740 ESI.NoexceptExpr = NoexceptExpr; 15741 return; 15742 } 15743 } 15744 15745 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15746 ExceptionSpecificationType EST, 15747 SourceRange SpecificationRange, 15748 ArrayRef<ParsedType> DynamicExceptions, 15749 ArrayRef<SourceRange> DynamicExceptionRanges, 15750 Expr *NoexceptExpr) { 15751 if (!MethodD) 15752 return; 15753 15754 // Dig out the method we're referring to. 15755 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15756 MethodD = FunTmpl->getTemplatedDecl(); 15757 15758 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15759 if (!Method) 15760 return; 15761 15762 // Check the exception specification. 15763 llvm::SmallVector<QualType, 4> Exceptions; 15764 FunctionProtoType::ExceptionSpecInfo ESI; 15765 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15766 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15767 ESI); 15768 15769 // Update the exception specification on the function type. 15770 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15771 15772 if (Method->isStatic()) 15773 checkThisInStaticMemberFunctionExceptionSpec(Method); 15774 15775 if (Method->isVirtual()) { 15776 // Check overrides, which we previously had to delay. 15777 for (const CXXMethodDecl *O : Method->overridden_methods()) 15778 CheckOverridingFunctionExceptionSpec(Method, O); 15779 } 15780 } 15781 15782 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15783 /// 15784 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15785 SourceLocation DeclStart, Declarator &D, 15786 Expr *BitWidth, 15787 InClassInitStyle InitStyle, 15788 AccessSpecifier AS, 15789 const ParsedAttr &MSPropertyAttr) { 15790 IdentifierInfo *II = D.getIdentifier(); 15791 if (!II) { 15792 Diag(DeclStart, diag::err_anonymous_property); 15793 return nullptr; 15794 } 15795 SourceLocation Loc = D.getIdentifierLoc(); 15796 15797 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15798 QualType T = TInfo->getType(); 15799 if (getLangOpts().CPlusPlus) { 15800 CheckExtraCXXDefaultArguments(D); 15801 15802 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15803 UPPC_DataMemberType)) { 15804 D.setInvalidType(); 15805 T = Context.IntTy; 15806 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15807 } 15808 } 15809 15810 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15811 15812 if (D.getDeclSpec().isInlineSpecified()) 15813 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15814 << getLangOpts().CPlusPlus17; 15815 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15816 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15817 diag::err_invalid_thread) 15818 << DeclSpec::getSpecifierName(TSCS); 15819 15820 // Check to see if this name was declared as a member previously 15821 NamedDecl *PrevDecl = nullptr; 15822 LookupResult Previous(*this, II, Loc, LookupMemberName, 15823 ForVisibleRedeclaration); 15824 LookupName(Previous, S); 15825 switch (Previous.getResultKind()) { 15826 case LookupResult::Found: 15827 case LookupResult::FoundUnresolvedValue: 15828 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15829 break; 15830 15831 case LookupResult::FoundOverloaded: 15832 PrevDecl = Previous.getRepresentativeDecl(); 15833 break; 15834 15835 case LookupResult::NotFound: 15836 case LookupResult::NotFoundInCurrentInstantiation: 15837 case LookupResult::Ambiguous: 15838 break; 15839 } 15840 15841 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15842 // Maybe we will complain about the shadowed template parameter. 15843 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15844 // Just pretend that we didn't see the previous declaration. 15845 PrevDecl = nullptr; 15846 } 15847 15848 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15849 PrevDecl = nullptr; 15850 15851 SourceLocation TSSL = D.getBeginLoc(); 15852 MSPropertyDecl *NewPD = 15853 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 15854 MSPropertyAttr.getPropertyDataGetter(), 15855 MSPropertyAttr.getPropertyDataSetter()); 15856 ProcessDeclAttributes(TUScope, NewPD, D); 15857 NewPD->setAccess(AS); 15858 15859 if (NewPD->isInvalidDecl()) 15860 Record->setInvalidDecl(); 15861 15862 if (D.getDeclSpec().isModulePrivateSpecified()) 15863 NewPD->setModulePrivate(); 15864 15865 if (NewPD->isInvalidDecl() && PrevDecl) { 15866 // Don't introduce NewFD into scope; there's already something 15867 // with the same name in the same scope. 15868 } else if (II) { 15869 PushOnScopeChains(NewPD, S); 15870 } else 15871 Record->addDecl(NewPD); 15872 15873 return NewPD; 15874 } 15875