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 return; 196 // If we're still at noexcept(true) and there's a throw() callee, 197 // change to that specification. 198 case EST_DynamicNone: 199 if (ComputedEST == EST_BasicNoexcept) 200 ComputedEST = EST_DynamicNone; 201 return; 202 case EST_DependentNoexcept: 203 llvm_unreachable( 204 "should not generate implicit declarations for dependent cases"); 205 case EST_Dynamic: 206 break; 207 } 208 assert(EST == EST_Dynamic && "EST case not considered earlier."); 209 assert(ComputedEST != EST_None && 210 "Shouldn't collect exceptions when throw-all is guaranteed."); 211 ComputedEST = EST_Dynamic; 212 // Record the exceptions in this function's exception specification. 213 for (const auto &E : Proto->exceptions()) 214 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 215 Exceptions.push_back(E); 216 } 217 218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 219 if (!E || ComputedEST == EST_MSAny) 220 return; 221 222 // FIXME: 223 // 224 // C++0x [except.spec]p14: 225 // [An] implicit exception-specification specifies the type-id T if and 226 // only if T is allowed by the exception-specification of a function directly 227 // invoked by f's implicit definition; f shall allow all exceptions if any 228 // function it directly invokes allows all exceptions, and f shall allow no 229 // exceptions if every function it directly invokes allows no exceptions. 230 // 231 // Note in particular that if an implicit exception-specification is generated 232 // for a function containing a throw-expression, that specification can still 233 // be noexcept(true). 234 // 235 // Note also that 'directly invoked' is not defined in the standard, and there 236 // is no indication that we should only consider potentially-evaluated calls. 237 // 238 // Ultimately we should implement the intent of the standard: the exception 239 // specification should be the set of exceptions which can be thrown by the 240 // implicit definition. For now, we assume that any non-nothrow expression can 241 // throw any exception. 242 243 if (Self->canThrow(E)) 244 ComputedEST = EST_None; 245 } 246 247 bool 248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 249 SourceLocation EqualLoc) { 250 if (RequireCompleteType(Param->getLocation(), Param->getType(), 251 diag::err_typecheck_decl_incomplete_type)) { 252 Param->setInvalidDecl(); 253 return true; 254 } 255 256 // C++ [dcl.fct.default]p5 257 // A default argument expression is implicitly converted (clause 258 // 4) to the parameter type. The default argument expression has 259 // the same semantic constraints as the initializer expression in 260 // a declaration of a variable of the parameter type, using the 261 // copy-initialization semantics (8.5). 262 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 263 Param); 264 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 265 EqualLoc); 266 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 268 if (Result.isInvalid()) 269 return true; 270 Arg = Result.getAs<Expr>(); 271 272 CheckCompletedExpr(Arg, EqualLoc); 273 Arg = MaybeCreateExprWithCleanups(Arg); 274 275 // Okay: add the default argument to the parameter 276 Param->setDefaultArg(Arg); 277 278 // We have already instantiated this parameter; provide each of the 279 // instantiations with the uninstantiated default argument. 280 UnparsedDefaultArgInstantiationsMap::iterator InstPos 281 = UnparsedDefaultArgInstantiations.find(Param); 282 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 283 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 284 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 285 286 // We're done tracking this parameter's instantiations. 287 UnparsedDefaultArgInstantiations.erase(InstPos); 288 } 289 290 return false; 291 } 292 293 /// ActOnParamDefaultArgument - Check whether the default argument 294 /// provided for a function parameter is well-formed. If so, attach it 295 /// to the parameter declaration. 296 void 297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 298 Expr *DefaultArg) { 299 if (!param || !DefaultArg) 300 return; 301 302 ParmVarDecl *Param = cast<ParmVarDecl>(param); 303 UnparsedDefaultArgLocs.erase(Param); 304 305 // Default arguments are only permitted in C++ 306 if (!getLangOpts().CPlusPlus) { 307 Diag(EqualLoc, diag::err_param_default_argument) 308 << DefaultArg->getSourceRange(); 309 Param->setInvalidDecl(); 310 return; 311 } 312 313 // Check for unexpanded parameter packs. 314 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 315 Param->setInvalidDecl(); 316 return; 317 } 318 319 // C++11 [dcl.fct.default]p3 320 // A default argument expression [...] shall not be specified for a 321 // parameter pack. 322 if (Param->isParameterPack()) { 323 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 324 << DefaultArg->getSourceRange(); 325 return; 326 } 327 328 // Check that the default argument is well-formed 329 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 330 if (DefaultArgChecker.Visit(DefaultArg)) { 331 Param->setInvalidDecl(); 332 return; 333 } 334 335 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 336 } 337 338 /// ActOnParamUnparsedDefaultArgument - We've seen a default 339 /// argument for a function parameter, but we can't parse it yet 340 /// because we're inside a class definition. Note that this default 341 /// argument will be parsed later. 342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 343 SourceLocation EqualLoc, 344 SourceLocation ArgLoc) { 345 if (!param) 346 return; 347 348 ParmVarDecl *Param = cast<ParmVarDecl>(param); 349 Param->setUnparsedDefaultArg(); 350 UnparsedDefaultArgLocs[Param] = ArgLoc; 351 } 352 353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 354 /// the default argument for the parameter param failed. 355 void Sema::ActOnParamDefaultArgumentError(Decl *param, 356 SourceLocation EqualLoc) { 357 if (!param) 358 return; 359 360 ParmVarDecl *Param = cast<ParmVarDecl>(param); 361 Param->setInvalidDecl(); 362 UnparsedDefaultArgLocs.erase(Param); 363 Param->setDefaultArg(new(Context) 364 OpaqueValueExpr(EqualLoc, 365 Param->getType().getNonReferenceType(), 366 VK_RValue)); 367 } 368 369 /// CheckExtraCXXDefaultArguments - Check for any extra default 370 /// arguments in the declarator, which is not a function declaration 371 /// or definition and therefore is not permitted to have default 372 /// arguments. This routine should be invoked for every declarator 373 /// that is not a function declaration or definition. 374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 375 // C++ [dcl.fct.default]p3 376 // A default argument expression shall be specified only in the 377 // parameter-declaration-clause of a function declaration or in a 378 // template-parameter (14.1). It shall not be specified for a 379 // parameter pack. If it is specified in a 380 // parameter-declaration-clause, it shall not occur within a 381 // declarator or abstract-declarator of a parameter-declaration. 382 bool MightBeFunction = D.isFunctionDeclarationContext(); 383 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 384 DeclaratorChunk &chunk = D.getTypeObject(i); 385 if (chunk.Kind == DeclaratorChunk::Function) { 386 if (MightBeFunction) { 387 // This is a function declaration. It can have default arguments, but 388 // keep looking in case its return type is a function type with default 389 // arguments. 390 MightBeFunction = false; 391 continue; 392 } 393 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 394 ++argIdx) { 395 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 396 if (Param->hasUnparsedDefaultArg()) { 397 std::unique_ptr<CachedTokens> Toks = 398 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 399 SourceRange SR; 400 if (Toks->size() > 1) 401 SR = SourceRange((*Toks)[1].getLocation(), 402 Toks->back().getLocation()); 403 else 404 SR = UnparsedDefaultArgLocs[Param]; 405 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 406 << SR; 407 } else if (Param->getDefaultArg()) { 408 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 409 << Param->getDefaultArg()->getSourceRange(); 410 Param->setDefaultArg(nullptr); 411 } 412 } 413 } else if (chunk.Kind != DeclaratorChunk::Paren) { 414 MightBeFunction = false; 415 } 416 } 417 } 418 419 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 420 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 421 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 422 if (!PVD->hasDefaultArg()) 423 return false; 424 if (!PVD->hasInheritedDefaultArg()) 425 return true; 426 } 427 return false; 428 } 429 430 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 431 /// function, once we already know that they have the same 432 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 433 /// error, false otherwise. 434 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 435 Scope *S) { 436 bool Invalid = false; 437 438 // The declaration context corresponding to the scope is the semantic 439 // parent, unless this is a local function declaration, in which case 440 // it is that surrounding function. 441 DeclContext *ScopeDC = New->isLocalExternDecl() 442 ? New->getLexicalDeclContext() 443 : New->getDeclContext(); 444 445 // Find the previous declaration for the purpose of default arguments. 446 FunctionDecl *PrevForDefaultArgs = Old; 447 for (/**/; PrevForDefaultArgs; 448 // Don't bother looking back past the latest decl if this is a local 449 // extern declaration; nothing else could work. 450 PrevForDefaultArgs = New->isLocalExternDecl() 451 ? nullptr 452 : PrevForDefaultArgs->getPreviousDecl()) { 453 // Ignore hidden declarations. 454 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 455 continue; 456 457 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 458 !New->isCXXClassMember()) { 459 // Ignore default arguments of old decl if they are not in 460 // the same scope and this is not an out-of-line definition of 461 // a member function. 462 continue; 463 } 464 465 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 466 // If only one of these is a local function declaration, then they are 467 // declared in different scopes, even though isDeclInScope may think 468 // they're in the same scope. (If both are local, the scope check is 469 // sufficient, and if neither is local, then they are in the same scope.) 470 continue; 471 } 472 473 // We found the right previous declaration. 474 break; 475 } 476 477 // C++ [dcl.fct.default]p4: 478 // For non-template functions, default arguments can be added in 479 // later declarations of a function in the same 480 // scope. Declarations in different scopes have completely 481 // distinct sets of default arguments. That is, declarations in 482 // inner scopes do not acquire default arguments from 483 // declarations in outer scopes, and vice versa. In a given 484 // function declaration, all parameters subsequent to a 485 // parameter with a default argument shall have default 486 // arguments supplied in this or previous declarations. A 487 // default argument shall not be redefined by a later 488 // declaration (not even to the same value). 489 // 490 // C++ [dcl.fct.default]p6: 491 // Except for member functions of class templates, the default arguments 492 // in a member function definition that appears outside of the class 493 // definition are added to the set of default arguments provided by the 494 // member function declaration in the class definition. 495 for (unsigned p = 0, NumParams = PrevForDefaultArgs 496 ? PrevForDefaultArgs->getNumParams() 497 : 0; 498 p < NumParams; ++p) { 499 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 500 ParmVarDecl *NewParam = New->getParamDecl(p); 501 502 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 503 bool NewParamHasDfl = NewParam->hasDefaultArg(); 504 505 if (OldParamHasDfl && NewParamHasDfl) { 506 unsigned DiagDefaultParamID = 507 diag::err_param_default_argument_redefinition; 508 509 // MSVC accepts that default parameters be redefined for member functions 510 // of template class. The new default parameter's value is ignored. 511 Invalid = true; 512 if (getLangOpts().MicrosoftExt) { 513 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 514 if (MD && MD->getParent()->getDescribedClassTemplate()) { 515 // Merge the old default argument into the new parameter. 516 NewParam->setHasInheritedDefaultArg(); 517 if (OldParam->hasUninstantiatedDefaultArg()) 518 NewParam->setUninstantiatedDefaultArg( 519 OldParam->getUninstantiatedDefaultArg()); 520 else 521 NewParam->setDefaultArg(OldParam->getInit()); 522 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 523 Invalid = false; 524 } 525 } 526 527 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 528 // hint here. Alternatively, we could walk the type-source information 529 // for NewParam to find the last source location in the type... but it 530 // isn't worth the effort right now. This is the kind of test case that 531 // is hard to get right: 532 // int f(int); 533 // void g(int (*fp)(int) = f); 534 // void g(int (*fp)(int) = &f); 535 Diag(NewParam->getLocation(), DiagDefaultParamID) 536 << NewParam->getDefaultArgRange(); 537 538 // Look for the function declaration where the default argument was 539 // actually written, which may be a declaration prior to Old. 540 for (auto Older = PrevForDefaultArgs; 541 OldParam->hasInheritedDefaultArg(); /**/) { 542 Older = Older->getPreviousDecl(); 543 OldParam = Older->getParamDecl(p); 544 } 545 546 Diag(OldParam->getLocation(), diag::note_previous_definition) 547 << OldParam->getDefaultArgRange(); 548 } else if (OldParamHasDfl) { 549 // Merge the old default argument into the new parameter unless the new 550 // function is a friend declaration in a template class. In the latter 551 // case the default arguments will be inherited when the friend 552 // declaration will be instantiated. 553 if (New->getFriendObjectKind() == Decl::FOK_None || 554 !New->getLexicalDeclContext()->isDependentContext()) { 555 // It's important to use getInit() here; getDefaultArg() 556 // strips off any top-level ExprWithCleanups. 557 NewParam->setHasInheritedDefaultArg(); 558 if (OldParam->hasUnparsedDefaultArg()) 559 NewParam->setUnparsedDefaultArg(); 560 else if (OldParam->hasUninstantiatedDefaultArg()) 561 NewParam->setUninstantiatedDefaultArg( 562 OldParam->getUninstantiatedDefaultArg()); 563 else 564 NewParam->setDefaultArg(OldParam->getInit()); 565 } 566 } else if (NewParamHasDfl) { 567 if (New->getDescribedFunctionTemplate()) { 568 // Paragraph 4, quoted above, only applies to non-template functions. 569 Diag(NewParam->getLocation(), 570 diag::err_param_default_argument_template_redecl) 571 << NewParam->getDefaultArgRange(); 572 Diag(PrevForDefaultArgs->getLocation(), 573 diag::note_template_prev_declaration) 574 << false; 575 } else if (New->getTemplateSpecializationKind() 576 != TSK_ImplicitInstantiation && 577 New->getTemplateSpecializationKind() != TSK_Undeclared) { 578 // C++ [temp.expr.spec]p21: 579 // Default function arguments shall not be specified in a declaration 580 // or a definition for one of the following explicit specializations: 581 // - the explicit specialization of a function template; 582 // - the explicit specialization of a member function template; 583 // - the explicit specialization of a member function of a class 584 // template where the class template specialization to which the 585 // member function specialization belongs is implicitly 586 // instantiated. 587 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 588 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 589 << New->getDeclName() 590 << NewParam->getDefaultArgRange(); 591 } else if (New->getDeclContext()->isDependentContext()) { 592 // C++ [dcl.fct.default]p6 (DR217): 593 // Default arguments for a member function of a class template shall 594 // be specified on the initial declaration of the member function 595 // within the class template. 596 // 597 // Reading the tea leaves a bit in DR217 and its reference to DR205 598 // leads me to the conclusion that one cannot add default function 599 // arguments for an out-of-line definition of a member function of a 600 // dependent type. 601 int WhichKind = 2; 602 if (CXXRecordDecl *Record 603 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 604 if (Record->getDescribedClassTemplate()) 605 WhichKind = 0; 606 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 607 WhichKind = 1; 608 else 609 WhichKind = 2; 610 } 611 612 Diag(NewParam->getLocation(), 613 diag::err_param_default_argument_member_template_redecl) 614 << WhichKind 615 << NewParam->getDefaultArgRange(); 616 } 617 } 618 } 619 620 // DR1344: If a default argument is added outside a class definition and that 621 // default argument makes the function a special member function, the program 622 // is ill-formed. This can only happen for constructors. 623 if (isa<CXXConstructorDecl>(New) && 624 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 625 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 626 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 627 if (NewSM != OldSM) { 628 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 629 assert(NewParam->hasDefaultArg()); 630 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 631 << NewParam->getDefaultArgRange() << NewSM; 632 Diag(Old->getLocation(), diag::note_previous_declaration); 633 } 634 } 635 636 const FunctionDecl *Def; 637 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 638 // template has a constexpr specifier then all its declarations shall 639 // contain the constexpr specifier. 640 if (New->isConstexpr() != Old->isConstexpr()) { 641 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 642 << New << New->isConstexpr(); 643 Diag(Old->getLocation(), diag::note_previous_declaration); 644 Invalid = true; 645 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 646 Old->isDefined(Def) && 647 // If a friend function is inlined but does not have 'inline' 648 // specifier, it is a definition. Do not report attribute conflict 649 // in this case, redefinition will be diagnosed later. 650 (New->isInlineSpecified() || 651 New->getFriendObjectKind() == Decl::FOK_None)) { 652 // C++11 [dcl.fcn.spec]p4: 653 // If the definition of a function appears in a translation unit before its 654 // first declaration as inline, the program is ill-formed. 655 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 656 Diag(Def->getLocation(), diag::note_previous_definition); 657 Invalid = true; 658 } 659 660 // FIXME: It's not clear what should happen if multiple declarations of a 661 // deduction guide have different explicitness. For now at least we simply 662 // reject any case where the explicitness changes. 663 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New); 664 if (NewGuide && NewGuide->isExplicitSpecified() != 665 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) { 666 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch) 667 << NewGuide->isExplicitSpecified(); 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++1z [dcl.dcl]/8: 720 // The decl-specifier-seq shall contain only the type-specifier auto 721 // and cv-qualifiers. 722 auto &DS = D.getDeclSpec(); 723 { 724 SmallVector<StringRef, 8> BadSpecifiers; 725 SmallVector<SourceLocation, 8> BadSpecifierLocs; 726 if (auto SCS = DS.getStorageClassSpec()) { 727 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 728 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 729 } 730 if (auto TSCS = DS.getThreadStorageClassSpec()) { 731 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 732 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 733 } 734 if (DS.isConstexprSpecified()) { 735 BadSpecifiers.push_back("constexpr"); 736 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 737 } 738 if (DS.isInlineSpecified()) { 739 BadSpecifiers.push_back("inline"); 740 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 741 } 742 if (!BadSpecifiers.empty()) { 743 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 744 Err << (int)BadSpecifiers.size() 745 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 746 // Don't add FixItHints to remove the specifiers; we do still respect 747 // them when building the underlying variable. 748 for (auto Loc : BadSpecifierLocs) 749 Err << SourceRange(Loc, Loc); 750 } 751 // We can't recover from it being declared as a typedef. 752 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 753 return nullptr; 754 } 755 756 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 757 QualType R = TInfo->getType(); 758 759 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 760 UPPC_DeclarationType)) 761 D.setInvalidType(); 762 763 // The syntax only allows a single ref-qualifier prior to the decomposition 764 // declarator. No other declarator chunks are permitted. Also check the type 765 // specifier here. 766 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 767 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 768 (D.getNumTypeObjects() == 1 && 769 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 770 Diag(Decomp.getLSquareLoc(), 771 (D.hasGroupingParens() || 772 (D.getNumTypeObjects() && 773 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 774 ? diag::err_decomp_decl_parens 775 : diag::err_decomp_decl_type) 776 << R; 777 778 // In most cases, there's no actual problem with an explicitly-specified 779 // type, but a function type won't work here, and ActOnVariableDeclarator 780 // shouldn't be called for such a type. 781 if (R->isFunctionType()) 782 D.setInvalidType(); 783 } 784 785 // Build the BindingDecls. 786 SmallVector<BindingDecl*, 8> Bindings; 787 788 // Build the BindingDecls. 789 for (auto &B : D.getDecompositionDeclarator().bindings()) { 790 // Check for name conflicts. 791 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 792 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 793 ForVisibleRedeclaration); 794 LookupName(Previous, S, 795 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 796 797 // It's not permitted to shadow a template parameter name. 798 if (Previous.isSingleResult() && 799 Previous.getFoundDecl()->isTemplateParameter()) { 800 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 801 Previous.getFoundDecl()); 802 Previous.clear(); 803 } 804 805 bool ConsiderLinkage = DC->isFunctionOrMethod() && 806 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 807 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 808 /*AllowInlineNamespace*/false); 809 if (!Previous.empty()) { 810 auto *Old = Previous.getRepresentativeDecl(); 811 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 812 Diag(Old->getLocation(), diag::note_previous_definition); 813 } 814 815 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 816 PushOnScopeChains(BD, S, true); 817 Bindings.push_back(BD); 818 ParsingInitForAutoVars.insert(BD); 819 } 820 821 // There are no prior lookup results for the variable itself, because it 822 // is unnamed. 823 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 824 Decomp.getLSquareLoc()); 825 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 826 ForVisibleRedeclaration); 827 828 // Build the variable that holds the non-decomposed object. 829 bool AddToScope = true; 830 NamedDecl *New = 831 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 832 MultiTemplateParamsArg(), AddToScope, Bindings); 833 if (AddToScope) { 834 S->AddDecl(New); 835 CurContext->addHiddenDecl(New); 836 } 837 838 if (isInOpenMPDeclareTargetContext()) 839 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 840 841 return New; 842 } 843 844 static bool checkSimpleDecomposition( 845 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 846 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 847 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 848 if ((int64_t)Bindings.size() != NumElems) { 849 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 850 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 851 << (NumElems < Bindings.size()); 852 return true; 853 } 854 855 unsigned I = 0; 856 for (auto *B : Bindings) { 857 SourceLocation Loc = B->getLocation(); 858 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 859 if (E.isInvalid()) 860 return true; 861 E = GetInit(Loc, E.get(), I++); 862 if (E.isInvalid()) 863 return true; 864 B->setBinding(ElemType, E.get()); 865 } 866 867 return false; 868 } 869 870 static bool checkArrayLikeDecomposition(Sema &S, 871 ArrayRef<BindingDecl *> Bindings, 872 ValueDecl *Src, QualType DecompType, 873 const llvm::APSInt &NumElems, 874 QualType ElemType) { 875 return checkSimpleDecomposition( 876 S, Bindings, Src, DecompType, NumElems, ElemType, 877 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 878 ExprResult E = S.ActOnIntegerConstant(Loc, I); 879 if (E.isInvalid()) 880 return ExprError(); 881 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 882 }); 883 } 884 885 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 886 ValueDecl *Src, QualType DecompType, 887 const ConstantArrayType *CAT) { 888 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 889 llvm::APSInt(CAT->getSize()), 890 CAT->getElementType()); 891 } 892 893 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 894 ValueDecl *Src, QualType DecompType, 895 const VectorType *VT) { 896 return checkArrayLikeDecomposition( 897 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 898 S.Context.getQualifiedType(VT->getElementType(), 899 DecompType.getQualifiers())); 900 } 901 902 static bool checkComplexDecomposition(Sema &S, 903 ArrayRef<BindingDecl *> Bindings, 904 ValueDecl *Src, QualType DecompType, 905 const ComplexType *CT) { 906 return checkSimpleDecomposition( 907 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 908 S.Context.getQualifiedType(CT->getElementType(), 909 DecompType.getQualifiers()), 910 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 911 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 912 }); 913 } 914 915 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 916 TemplateArgumentListInfo &Args) { 917 SmallString<128> SS; 918 llvm::raw_svector_ostream OS(SS); 919 bool First = true; 920 for (auto &Arg : Args.arguments()) { 921 if (!First) 922 OS << ", "; 923 Arg.getArgument().print(PrintingPolicy, OS); 924 First = false; 925 } 926 return OS.str(); 927 } 928 929 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 930 SourceLocation Loc, StringRef Trait, 931 TemplateArgumentListInfo &Args, 932 unsigned DiagID) { 933 auto DiagnoseMissing = [&] { 934 if (DiagID) 935 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 936 Args); 937 return true; 938 }; 939 940 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 941 NamespaceDecl *Std = S.getStdNamespace(); 942 if (!Std) 943 return DiagnoseMissing(); 944 945 // Look up the trait itself, within namespace std. We can diagnose various 946 // problems with this lookup even if we've been asked to not diagnose a 947 // missing specialization, because this can only fail if the user has been 948 // declaring their own names in namespace std or we don't support the 949 // standard library implementation in use. 950 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 951 Loc, Sema::LookupOrdinaryName); 952 if (!S.LookupQualifiedName(Result, Std)) 953 return DiagnoseMissing(); 954 if (Result.isAmbiguous()) 955 return true; 956 957 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 958 if (!TraitTD) { 959 Result.suppressDiagnostics(); 960 NamedDecl *Found = *Result.begin(); 961 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 962 S.Diag(Found->getLocation(), diag::note_declared_at); 963 return true; 964 } 965 966 // Build the template-id. 967 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 968 if (TraitTy.isNull()) 969 return true; 970 if (!S.isCompleteType(Loc, TraitTy)) { 971 if (DiagID) 972 S.RequireCompleteType( 973 Loc, TraitTy, DiagID, 974 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 975 return true; 976 } 977 978 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 979 assert(RD && "specialization of class template is not a class?"); 980 981 // Look up the member of the trait type. 982 S.LookupQualifiedName(TraitMemberLookup, RD); 983 return TraitMemberLookup.isAmbiguous(); 984 } 985 986 static TemplateArgumentLoc 987 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 988 uint64_t I) { 989 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 990 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 991 } 992 993 static TemplateArgumentLoc 994 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 995 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 996 } 997 998 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 999 1000 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1001 llvm::APSInt &Size) { 1002 EnterExpressionEvaluationContext ContextRAII( 1003 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1004 1005 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1006 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1007 1008 // Form template argument list for tuple_size<T>. 1009 TemplateArgumentListInfo Args(Loc, Loc); 1010 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1011 1012 // If there's no tuple_size specialization, it's not tuple-like. 1013 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1014 return IsTupleLike::NotTupleLike; 1015 1016 // If we get this far, we've committed to the tuple interpretation, but 1017 // we can still fail if there actually isn't a usable ::value. 1018 1019 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1020 LookupResult &R; 1021 TemplateArgumentListInfo &Args; 1022 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1023 : R(R), Args(Args) {} 1024 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1025 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1026 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1027 } 1028 } Diagnoser(R, Args); 1029 1030 if (R.empty()) { 1031 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1032 return IsTupleLike::Error; 1033 } 1034 1035 ExprResult E = 1036 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1037 if (E.isInvalid()) 1038 return IsTupleLike::Error; 1039 1040 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1041 if (E.isInvalid()) 1042 return IsTupleLike::Error; 1043 1044 return IsTupleLike::TupleLike; 1045 } 1046 1047 /// \return std::tuple_element<I, T>::type. 1048 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1049 unsigned I, QualType T) { 1050 // Form template argument list for tuple_element<I, T>. 1051 TemplateArgumentListInfo Args(Loc, Loc); 1052 Args.addArgument( 1053 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1054 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1055 1056 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1057 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1058 if (lookupStdTypeTraitMember( 1059 S, R, Loc, "tuple_element", Args, 1060 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1061 return QualType(); 1062 1063 auto *TD = R.getAsSingle<TypeDecl>(); 1064 if (!TD) { 1065 R.suppressDiagnostics(); 1066 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1067 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1068 if (!R.empty()) 1069 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1070 return QualType(); 1071 } 1072 1073 return S.Context.getTypeDeclType(TD); 1074 } 1075 1076 namespace { 1077 struct BindingDiagnosticTrap { 1078 Sema &S; 1079 DiagnosticErrorTrap Trap; 1080 BindingDecl *BD; 1081 1082 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1083 : S(S), Trap(S.Diags), BD(BD) {} 1084 ~BindingDiagnosticTrap() { 1085 if (Trap.hasErrorOccurred()) 1086 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1087 } 1088 }; 1089 } 1090 1091 static bool checkTupleLikeDecomposition(Sema &S, 1092 ArrayRef<BindingDecl *> Bindings, 1093 VarDecl *Src, QualType DecompType, 1094 const llvm::APSInt &TupleSize) { 1095 if ((int64_t)Bindings.size() != TupleSize) { 1096 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1097 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1098 << (TupleSize < Bindings.size()); 1099 return true; 1100 } 1101 1102 if (Bindings.empty()) 1103 return false; 1104 1105 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1106 1107 // [dcl.decomp]p3: 1108 // The unqualified-id get is looked up in the scope of E by class member 1109 // access lookup ... 1110 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1111 bool UseMemberGet = false; 1112 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1113 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1114 S.LookupQualifiedName(MemberGet, RD); 1115 if (MemberGet.isAmbiguous()) 1116 return true; 1117 // ... and if that finds at least one declaration that is a function 1118 // template whose first template parameter is a non-type parameter ... 1119 for (NamedDecl *D : MemberGet) { 1120 if (FunctionTemplateDecl *FTD = 1121 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1122 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1123 if (TPL->size() != 0 && 1124 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1125 // ... the initializer is e.get<i>(). 1126 UseMemberGet = true; 1127 break; 1128 } 1129 } 1130 } 1131 } 1132 1133 unsigned I = 0; 1134 for (auto *B : Bindings) { 1135 BindingDiagnosticTrap Trap(S, B); 1136 SourceLocation Loc = B->getLocation(); 1137 1138 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1139 if (E.isInvalid()) 1140 return true; 1141 1142 // e is an lvalue if the type of the entity is an lvalue reference and 1143 // an xvalue otherwise 1144 if (!Src->getType()->isLValueReferenceType()) 1145 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1146 E.get(), nullptr, VK_XValue); 1147 1148 TemplateArgumentListInfo Args(Loc, Loc); 1149 Args.addArgument( 1150 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1151 1152 if (UseMemberGet) { 1153 // if [lookup of member get] finds at least one declaration, the 1154 // initializer is e.get<i-1>(). 1155 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1156 CXXScopeSpec(), SourceLocation(), nullptr, 1157 MemberGet, &Args, nullptr); 1158 if (E.isInvalid()) 1159 return true; 1160 1161 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1162 } else { 1163 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1164 // in the associated namespaces. 1165 Expr *Get = UnresolvedLookupExpr::Create( 1166 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1167 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1168 UnresolvedSetIterator(), UnresolvedSetIterator()); 1169 1170 Expr *Arg = E.get(); 1171 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1172 } 1173 if (E.isInvalid()) 1174 return true; 1175 Expr *Init = E.get(); 1176 1177 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1178 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1179 if (T.isNull()) 1180 return true; 1181 1182 // each vi is a variable of type "reference to T" initialized with the 1183 // initializer, where the reference is an lvalue reference if the 1184 // initializer is an lvalue and an rvalue reference otherwise 1185 QualType RefType = 1186 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1187 if (RefType.isNull()) 1188 return true; 1189 auto *RefVD = VarDecl::Create( 1190 S.Context, Src->getDeclContext(), Loc, Loc, 1191 B->getDeclName().getAsIdentifierInfo(), RefType, 1192 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1193 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1194 RefVD->setTSCSpec(Src->getTSCSpec()); 1195 RefVD->setImplicit(); 1196 if (Src->isInlineSpecified()) 1197 RefVD->setInlineSpecified(); 1198 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1199 1200 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1201 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1202 InitializationSequence Seq(S, Entity, Kind, Init); 1203 E = Seq.Perform(S, Entity, Kind, Init); 1204 if (E.isInvalid()) 1205 return true; 1206 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1207 if (E.isInvalid()) 1208 return true; 1209 RefVD->setInit(E.get()); 1210 RefVD->checkInitIsICE(); 1211 1212 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1213 DeclarationNameInfo(B->getDeclName(), Loc), 1214 RefVD); 1215 if (E.isInvalid()) 1216 return true; 1217 1218 B->setBinding(T, E.get()); 1219 I++; 1220 } 1221 1222 return false; 1223 } 1224 1225 /// Find the base class to decompose in a built-in decomposition of a class type. 1226 /// This base class search is, unfortunately, not quite like any other that we 1227 /// perform anywhere else in C++. 1228 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1229 const CXXRecordDecl *RD, 1230 CXXCastPath &BasePath) { 1231 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1232 CXXBasePath &Path) { 1233 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1234 }; 1235 1236 const CXXRecordDecl *ClassWithFields = nullptr; 1237 AccessSpecifier AS = AS_public; 1238 if (RD->hasDirectFields()) 1239 // [dcl.decomp]p4: 1240 // Otherwise, all of E's non-static data members shall be public direct 1241 // members of E ... 1242 ClassWithFields = RD; 1243 else { 1244 // ... or of ... 1245 CXXBasePaths Paths; 1246 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1247 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1248 // If no classes have fields, just decompose RD itself. (This will work 1249 // if and only if zero bindings were provided.) 1250 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1251 } 1252 1253 CXXBasePath *BestPath = nullptr; 1254 for (auto &P : Paths) { 1255 if (!BestPath) 1256 BestPath = &P; 1257 else if (!S.Context.hasSameType(P.back().Base->getType(), 1258 BestPath->back().Base->getType())) { 1259 // ... the same ... 1260 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1261 << false << RD << BestPath->back().Base->getType() 1262 << P.back().Base->getType(); 1263 return DeclAccessPair(); 1264 } else if (P.Access < BestPath->Access) { 1265 BestPath = &P; 1266 } 1267 } 1268 1269 // ... unambiguous ... 1270 QualType BaseType = BestPath->back().Base->getType(); 1271 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1272 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1273 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1274 return DeclAccessPair(); 1275 } 1276 1277 // ... [accessible, implied by other rules] base class of E. 1278 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1279 *BestPath, diag::err_decomp_decl_inaccessible_base); 1280 AS = BestPath->Access; 1281 1282 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1283 S.BuildBasePathArray(Paths, BasePath); 1284 } 1285 1286 // The above search did not check whether the selected class itself has base 1287 // classes with fields, so check that now. 1288 CXXBasePaths Paths; 1289 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1290 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1291 << (ClassWithFields == RD) << RD << ClassWithFields 1292 << Paths.front().back().Base->getType(); 1293 return DeclAccessPair(); 1294 } 1295 1296 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1297 } 1298 1299 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1300 ValueDecl *Src, QualType DecompType, 1301 const CXXRecordDecl *OrigRD) { 1302 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1303 diag::err_incomplete_type)) 1304 return true; 1305 1306 CXXCastPath BasePath; 1307 DeclAccessPair BasePair = 1308 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1309 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1310 if (!RD) 1311 return true; 1312 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1313 DecompType.getQualifiers()); 1314 1315 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1316 unsigned NumFields = 1317 std::count_if(RD->field_begin(), RD->field_end(), 1318 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1319 assert(Bindings.size() != NumFields); 1320 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1321 << DecompType << (unsigned)Bindings.size() << NumFields 1322 << (NumFields < Bindings.size()); 1323 return true; 1324 }; 1325 1326 // all of E's non-static data members shall be [...] well-formed 1327 // when named as e.name in the context of the structured binding, 1328 // E shall not have an anonymous union member, ... 1329 unsigned I = 0; 1330 for (auto *FD : RD->fields()) { 1331 if (FD->isUnnamedBitfield()) 1332 continue; 1333 1334 if (FD->isAnonymousStructOrUnion()) { 1335 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1336 << DecompType << FD->getType()->isUnionType(); 1337 S.Diag(FD->getLocation(), diag::note_declared_at); 1338 return true; 1339 } 1340 1341 // We have a real field to bind. 1342 if (I >= Bindings.size()) 1343 return DiagnoseBadNumberOfBindings(); 1344 auto *B = Bindings[I++]; 1345 SourceLocation Loc = B->getLocation(); 1346 1347 // The field must be accessible in the context of the structured binding. 1348 // We already checked that the base class is accessible. 1349 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1350 // const_cast here. 1351 S.CheckStructuredBindingMemberAccess( 1352 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1353 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1354 BasePair.getAccess(), FD->getAccess()))); 1355 1356 // Initialize the binding to Src.FD. 1357 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1358 if (E.isInvalid()) 1359 return true; 1360 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1361 VK_LValue, &BasePath); 1362 if (E.isInvalid()) 1363 return true; 1364 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1365 CXXScopeSpec(), FD, 1366 DeclAccessPair::make(FD, FD->getAccess()), 1367 DeclarationNameInfo(FD->getDeclName(), Loc)); 1368 if (E.isInvalid()) 1369 return true; 1370 1371 // If the type of the member is T, the referenced type is cv T, where cv is 1372 // the cv-qualification of the decomposition expression. 1373 // 1374 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1375 // 'const' to the type of the field. 1376 Qualifiers Q = DecompType.getQualifiers(); 1377 if (FD->isMutable()) 1378 Q.removeConst(); 1379 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1380 } 1381 1382 if (I != Bindings.size()) 1383 return DiagnoseBadNumberOfBindings(); 1384 1385 return false; 1386 } 1387 1388 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1389 QualType DecompType = DD->getType(); 1390 1391 // If the type of the decomposition is dependent, then so is the type of 1392 // each binding. 1393 if (DecompType->isDependentType()) { 1394 for (auto *B : DD->bindings()) 1395 B->setType(Context.DependentTy); 1396 return; 1397 } 1398 1399 DecompType = DecompType.getNonReferenceType(); 1400 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1401 1402 // C++1z [dcl.decomp]/2: 1403 // If E is an array type [...] 1404 // As an extension, we also support decomposition of built-in complex and 1405 // vector types. 1406 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1407 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1408 DD->setInvalidDecl(); 1409 return; 1410 } 1411 if (auto *VT = DecompType->getAs<VectorType>()) { 1412 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1413 DD->setInvalidDecl(); 1414 return; 1415 } 1416 if (auto *CT = DecompType->getAs<ComplexType>()) { 1417 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1418 DD->setInvalidDecl(); 1419 return; 1420 } 1421 1422 // C++1z [dcl.decomp]/3: 1423 // if the expression std::tuple_size<E>::value is a well-formed integral 1424 // constant expression, [...] 1425 llvm::APSInt TupleSize(32); 1426 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1427 case IsTupleLike::Error: 1428 DD->setInvalidDecl(); 1429 return; 1430 1431 case IsTupleLike::TupleLike: 1432 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1433 DD->setInvalidDecl(); 1434 return; 1435 1436 case IsTupleLike::NotTupleLike: 1437 break; 1438 } 1439 1440 // C++1z [dcl.dcl]/8: 1441 // [E shall be of array or non-union class type] 1442 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1443 if (!RD || RD->isUnion()) { 1444 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1445 << DD << !RD << DecompType; 1446 DD->setInvalidDecl(); 1447 return; 1448 } 1449 1450 // C++1z [dcl.decomp]/4: 1451 // all of E's non-static data members shall be [...] direct members of 1452 // E or of the same unambiguous public base class of E, ... 1453 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1454 DD->setInvalidDecl(); 1455 } 1456 1457 /// Merge the exception specifications of two variable declarations. 1458 /// 1459 /// This is called when there's a redeclaration of a VarDecl. The function 1460 /// checks if the redeclaration might have an exception specification and 1461 /// validates compatibility and merges the specs if necessary. 1462 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1463 // Shortcut if exceptions are disabled. 1464 if (!getLangOpts().CXXExceptions) 1465 return; 1466 1467 assert(Context.hasSameType(New->getType(), Old->getType()) && 1468 "Should only be called if types are otherwise the same."); 1469 1470 QualType NewType = New->getType(); 1471 QualType OldType = Old->getType(); 1472 1473 // We're only interested in pointers and references to functions, as well 1474 // as pointers to member functions. 1475 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1476 NewType = R->getPointeeType(); 1477 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1478 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1479 NewType = P->getPointeeType(); 1480 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1481 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1482 NewType = M->getPointeeType(); 1483 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1484 } 1485 1486 if (!NewType->isFunctionProtoType()) 1487 return; 1488 1489 // There's lots of special cases for functions. For function pointers, system 1490 // libraries are hopefully not as broken so that we don't need these 1491 // workarounds. 1492 if (CheckEquivalentExceptionSpec( 1493 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1494 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1495 New->setInvalidDecl(); 1496 } 1497 } 1498 1499 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1500 /// function declaration are well-formed according to C++ 1501 /// [dcl.fct.default]. 1502 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1503 unsigned NumParams = FD->getNumParams(); 1504 unsigned p; 1505 1506 // Find first parameter with a default argument 1507 for (p = 0; p < NumParams; ++p) { 1508 ParmVarDecl *Param = FD->getParamDecl(p); 1509 if (Param->hasDefaultArg()) 1510 break; 1511 } 1512 1513 // C++11 [dcl.fct.default]p4: 1514 // In a given function declaration, each parameter subsequent to a parameter 1515 // with a default argument shall have a default argument supplied in this or 1516 // a previous declaration or shall be a function parameter pack. A default 1517 // argument shall not be redefined by a later declaration (not even to the 1518 // same value). 1519 unsigned LastMissingDefaultArg = 0; 1520 for (; p < NumParams; ++p) { 1521 ParmVarDecl *Param = FD->getParamDecl(p); 1522 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1523 if (Param->isInvalidDecl()) 1524 /* We already complained about this parameter. */; 1525 else if (Param->getIdentifier()) 1526 Diag(Param->getLocation(), 1527 diag::err_param_default_argument_missing_name) 1528 << Param->getIdentifier(); 1529 else 1530 Diag(Param->getLocation(), 1531 diag::err_param_default_argument_missing); 1532 1533 LastMissingDefaultArg = p; 1534 } 1535 } 1536 1537 if (LastMissingDefaultArg > 0) { 1538 // Some default arguments were missing. Clear out all of the 1539 // default arguments up to (and including) the last missing 1540 // default argument, so that we leave the function parameters 1541 // in a semantically valid state. 1542 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1543 ParmVarDecl *Param = FD->getParamDecl(p); 1544 if (Param->hasDefaultArg()) { 1545 Param->setDefaultArg(nullptr); 1546 } 1547 } 1548 } 1549 } 1550 1551 // CheckConstexprParameterTypes - Check whether a function's parameter types 1552 // are all literal types. If so, return true. If not, produce a suitable 1553 // diagnostic and return false. 1554 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1555 const FunctionDecl *FD) { 1556 unsigned ArgIndex = 0; 1557 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1558 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1559 e = FT->param_type_end(); 1560 i != e; ++i, ++ArgIndex) { 1561 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1562 SourceLocation ParamLoc = PD->getLocation(); 1563 if (!(*i)->isDependentType() && 1564 SemaRef.RequireLiteralType(ParamLoc, *i, 1565 diag::err_constexpr_non_literal_param, 1566 ArgIndex+1, PD->getSourceRange(), 1567 isa<CXXConstructorDecl>(FD))) 1568 return false; 1569 } 1570 return true; 1571 } 1572 1573 /// Get diagnostic %select index for tag kind for 1574 /// record diagnostic message. 1575 /// WARNING: Indexes apply to particular diagnostics only! 1576 /// 1577 /// \returns diagnostic %select index. 1578 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1579 switch (Tag) { 1580 case TTK_Struct: return 0; 1581 case TTK_Interface: return 1; 1582 case TTK_Class: return 2; 1583 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1584 } 1585 } 1586 1587 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1588 // the requirements of a constexpr function definition or a constexpr 1589 // constructor definition. If so, return true. If not, produce appropriate 1590 // diagnostics and return false. 1591 // 1592 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1593 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1594 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1595 if (MD && MD->isInstance()) { 1596 // C++11 [dcl.constexpr]p4: 1597 // The definition of a constexpr constructor shall satisfy the following 1598 // constraints: 1599 // - the class shall not have any virtual base classes; 1600 const CXXRecordDecl *RD = MD->getParent(); 1601 if (RD->getNumVBases()) { 1602 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1603 << isa<CXXConstructorDecl>(NewFD) 1604 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1605 for (const auto &I : RD->vbases()) 1606 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1607 << I.getSourceRange(); 1608 return false; 1609 } 1610 } 1611 1612 if (!isa<CXXConstructorDecl>(NewFD)) { 1613 // C++11 [dcl.constexpr]p3: 1614 // The definition of a constexpr function shall satisfy the following 1615 // constraints: 1616 // - it shall not be virtual; 1617 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1618 if (Method && Method->isVirtual()) { 1619 Method = Method->getCanonicalDecl(); 1620 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1621 1622 // If it's not obvious why this function is virtual, find an overridden 1623 // function which uses the 'virtual' keyword. 1624 const CXXMethodDecl *WrittenVirtual = Method; 1625 while (!WrittenVirtual->isVirtualAsWritten()) 1626 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1627 if (WrittenVirtual != Method) 1628 Diag(WrittenVirtual->getLocation(), 1629 diag::note_overridden_virtual_function); 1630 return false; 1631 } 1632 1633 // - its return type shall be a literal type; 1634 QualType RT = NewFD->getReturnType(); 1635 if (!RT->isDependentType() && 1636 RequireLiteralType(NewFD->getLocation(), RT, 1637 diag::err_constexpr_non_literal_return)) 1638 return false; 1639 } 1640 1641 // - each of its parameter types shall be a literal type; 1642 if (!CheckConstexprParameterTypes(*this, NewFD)) 1643 return false; 1644 1645 return true; 1646 } 1647 1648 /// Check the given declaration statement is legal within a constexpr function 1649 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1650 /// 1651 /// \return true if the body is OK (maybe only as an extension), false if we 1652 /// have diagnosed a problem. 1653 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1654 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1655 // C++11 [dcl.constexpr]p3 and p4: 1656 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1657 // contain only 1658 for (const auto *DclIt : DS->decls()) { 1659 switch (DclIt->getKind()) { 1660 case Decl::StaticAssert: 1661 case Decl::Using: 1662 case Decl::UsingShadow: 1663 case Decl::UsingDirective: 1664 case Decl::UnresolvedUsingTypename: 1665 case Decl::UnresolvedUsingValue: 1666 // - static_assert-declarations 1667 // - using-declarations, 1668 // - using-directives, 1669 continue; 1670 1671 case Decl::Typedef: 1672 case Decl::TypeAlias: { 1673 // - typedef declarations and alias-declarations that do not define 1674 // classes or enumerations, 1675 const auto *TN = cast<TypedefNameDecl>(DclIt); 1676 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1677 // Don't allow variably-modified types in constexpr functions. 1678 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1679 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1680 << TL.getSourceRange() << TL.getType() 1681 << isa<CXXConstructorDecl>(Dcl); 1682 return false; 1683 } 1684 continue; 1685 } 1686 1687 case Decl::Enum: 1688 case Decl::CXXRecord: 1689 // C++1y allows types to be defined, not just declared. 1690 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1691 SemaRef.Diag(DS->getBeginLoc(), 1692 SemaRef.getLangOpts().CPlusPlus14 1693 ? diag::warn_cxx11_compat_constexpr_type_definition 1694 : diag::ext_constexpr_type_definition) 1695 << isa<CXXConstructorDecl>(Dcl); 1696 continue; 1697 1698 case Decl::EnumConstant: 1699 case Decl::IndirectField: 1700 case Decl::ParmVar: 1701 // These can only appear with other declarations which are banned in 1702 // C++11 and permitted in C++1y, so ignore them. 1703 continue; 1704 1705 case Decl::Var: 1706 case Decl::Decomposition: { 1707 // C++1y [dcl.constexpr]p3 allows anything except: 1708 // a definition of a variable of non-literal type or of static or 1709 // thread storage duration or for which no initialization is performed. 1710 const auto *VD = cast<VarDecl>(DclIt); 1711 if (VD->isThisDeclarationADefinition()) { 1712 if (VD->isStaticLocal()) { 1713 SemaRef.Diag(VD->getLocation(), 1714 diag::err_constexpr_local_var_static) 1715 << isa<CXXConstructorDecl>(Dcl) 1716 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1717 return false; 1718 } 1719 if (!VD->getType()->isDependentType() && 1720 SemaRef.RequireLiteralType( 1721 VD->getLocation(), VD->getType(), 1722 diag::err_constexpr_local_var_non_literal_type, 1723 isa<CXXConstructorDecl>(Dcl))) 1724 return false; 1725 if (!VD->getType()->isDependentType() && 1726 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1727 SemaRef.Diag(VD->getLocation(), 1728 diag::err_constexpr_local_var_no_init) 1729 << isa<CXXConstructorDecl>(Dcl); 1730 return false; 1731 } 1732 } 1733 SemaRef.Diag(VD->getLocation(), 1734 SemaRef.getLangOpts().CPlusPlus14 1735 ? diag::warn_cxx11_compat_constexpr_local_var 1736 : diag::ext_constexpr_local_var) 1737 << isa<CXXConstructorDecl>(Dcl); 1738 continue; 1739 } 1740 1741 case Decl::NamespaceAlias: 1742 case Decl::Function: 1743 // These are disallowed in C++11 and permitted in C++1y. Allow them 1744 // everywhere as an extension. 1745 if (!Cxx1yLoc.isValid()) 1746 Cxx1yLoc = DS->getBeginLoc(); 1747 continue; 1748 1749 default: 1750 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1751 << isa<CXXConstructorDecl>(Dcl); 1752 return false; 1753 } 1754 } 1755 1756 return true; 1757 } 1758 1759 /// Check that the given field is initialized within a constexpr constructor. 1760 /// 1761 /// \param Dcl The constexpr constructor being checked. 1762 /// \param Field The field being checked. This may be a member of an anonymous 1763 /// struct or union nested within the class being checked. 1764 /// \param Inits All declarations, including anonymous struct/union members and 1765 /// indirect members, for which any initialization was provided. 1766 /// \param Diagnosed Set to true if an error is produced. 1767 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1768 const FunctionDecl *Dcl, 1769 FieldDecl *Field, 1770 llvm::SmallSet<Decl*, 16> &Inits, 1771 bool &Diagnosed) { 1772 if (Field->isInvalidDecl()) 1773 return; 1774 1775 if (Field->isUnnamedBitfield()) 1776 return; 1777 1778 // Anonymous unions with no variant members and empty anonymous structs do not 1779 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1780 // indirect fields don't need initializing. 1781 if (Field->isAnonymousStructOrUnion() && 1782 (Field->getType()->isUnionType() 1783 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1784 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1785 return; 1786 1787 if (!Inits.count(Field)) { 1788 if (!Diagnosed) { 1789 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1790 Diagnosed = true; 1791 } 1792 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1793 } else if (Field->isAnonymousStructOrUnion()) { 1794 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1795 for (auto *I : RD->fields()) 1796 // If an anonymous union contains an anonymous struct of which any member 1797 // is initialized, all members must be initialized. 1798 if (!RD->isUnion() || Inits.count(I)) 1799 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1800 } 1801 } 1802 1803 /// Check the provided statement is allowed in a constexpr function 1804 /// definition. 1805 static bool 1806 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1807 SmallVectorImpl<SourceLocation> &ReturnStmts, 1808 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) { 1809 // - its function-body shall be [...] a compound-statement that contains only 1810 switch (S->getStmtClass()) { 1811 case Stmt::NullStmtClass: 1812 // - null statements, 1813 return true; 1814 1815 case Stmt::DeclStmtClass: 1816 // - static_assert-declarations 1817 // - using-declarations, 1818 // - using-directives, 1819 // - typedef declarations and alias-declarations that do not define 1820 // classes or enumerations, 1821 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1822 return false; 1823 return true; 1824 1825 case Stmt::ReturnStmtClass: 1826 // - and exactly one return statement; 1827 if (isa<CXXConstructorDecl>(Dcl)) { 1828 // C++1y allows return statements in constexpr constructors. 1829 if (!Cxx1yLoc.isValid()) 1830 Cxx1yLoc = S->getBeginLoc(); 1831 return true; 1832 } 1833 1834 ReturnStmts.push_back(S->getBeginLoc()); 1835 return true; 1836 1837 case Stmt::CompoundStmtClass: { 1838 // C++1y allows compound-statements. 1839 if (!Cxx1yLoc.isValid()) 1840 Cxx1yLoc = S->getBeginLoc(); 1841 1842 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1843 for (auto *BodyIt : CompStmt->body()) { 1844 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1845 Cxx1yLoc, Cxx2aLoc)) 1846 return false; 1847 } 1848 return true; 1849 } 1850 1851 case Stmt::AttributedStmtClass: 1852 if (!Cxx1yLoc.isValid()) 1853 Cxx1yLoc = S->getBeginLoc(); 1854 return true; 1855 1856 case Stmt::IfStmtClass: { 1857 // C++1y allows if-statements. 1858 if (!Cxx1yLoc.isValid()) 1859 Cxx1yLoc = S->getBeginLoc(); 1860 1861 IfStmt *If = cast<IfStmt>(S); 1862 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1863 Cxx1yLoc, Cxx2aLoc)) 1864 return false; 1865 if (If->getElse() && 1866 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1867 Cxx1yLoc, Cxx2aLoc)) 1868 return false; 1869 return true; 1870 } 1871 1872 case Stmt::WhileStmtClass: 1873 case Stmt::DoStmtClass: 1874 case Stmt::ForStmtClass: 1875 case Stmt::CXXForRangeStmtClass: 1876 case Stmt::ContinueStmtClass: 1877 // C++1y allows all of these. We don't allow them as extensions in C++11, 1878 // because they don't make sense without variable mutation. 1879 if (!SemaRef.getLangOpts().CPlusPlus14) 1880 break; 1881 if (!Cxx1yLoc.isValid()) 1882 Cxx1yLoc = S->getBeginLoc(); 1883 for (Stmt *SubStmt : S->children()) 1884 if (SubStmt && 1885 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1886 Cxx1yLoc, Cxx2aLoc)) 1887 return false; 1888 return true; 1889 1890 case Stmt::SwitchStmtClass: 1891 case Stmt::CaseStmtClass: 1892 case Stmt::DefaultStmtClass: 1893 case Stmt::BreakStmtClass: 1894 // C++1y allows switch-statements, and since they don't need variable 1895 // mutation, we can reasonably allow them in C++11 as an extension. 1896 if (!Cxx1yLoc.isValid()) 1897 Cxx1yLoc = S->getBeginLoc(); 1898 for (Stmt *SubStmt : S->children()) 1899 if (SubStmt && 1900 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1901 Cxx1yLoc, Cxx2aLoc)) 1902 return false; 1903 return true; 1904 1905 case Stmt::CXXTryStmtClass: 1906 if (Cxx2aLoc.isInvalid()) 1907 Cxx2aLoc = S->getBeginLoc(); 1908 for (Stmt *SubStmt : S->children()) { 1909 if (SubStmt && 1910 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1911 Cxx1yLoc, Cxx2aLoc)) 1912 return false; 1913 } 1914 return true; 1915 1916 case Stmt::CXXCatchStmtClass: 1917 // Do not bother checking the language mode (already covered by the 1918 // try block check). 1919 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 1920 cast<CXXCatchStmt>(S)->getHandlerBlock(), 1921 ReturnStmts, Cxx1yLoc, Cxx2aLoc)) 1922 return false; 1923 return true; 1924 1925 default: 1926 if (!isa<Expr>(S)) 1927 break; 1928 1929 // C++1y allows expression-statements. 1930 if (!Cxx1yLoc.isValid()) 1931 Cxx1yLoc = S->getBeginLoc(); 1932 return true; 1933 } 1934 1935 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1936 << isa<CXXConstructorDecl>(Dcl); 1937 return false; 1938 } 1939 1940 /// Check the body for the given constexpr function declaration only contains 1941 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1942 /// 1943 /// \return true if the body is OK, false if we have diagnosed a problem. 1944 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1945 SmallVector<SourceLocation, 4> ReturnStmts; 1946 1947 if (isa<CXXTryStmt>(Body)) { 1948 // C++11 [dcl.constexpr]p3: 1949 // The definition of a constexpr function shall satisfy the following 1950 // constraints: [...] 1951 // - its function-body shall be = delete, = default, or a 1952 // compound-statement 1953 // 1954 // C++11 [dcl.constexpr]p4: 1955 // In the definition of a constexpr constructor, [...] 1956 // - its function-body shall not be a function-try-block; 1957 // 1958 // This restriction is lifted in C++2a, as long as inner statements also 1959 // apply the general constexpr rules. 1960 Diag(Body->getBeginLoc(), 1961 !getLangOpts().CPlusPlus2a 1962 ? diag::ext_constexpr_function_try_block_cxx2a 1963 : diag::warn_cxx17_compat_constexpr_function_try_block) 1964 << isa<CXXConstructorDecl>(Dcl); 1965 } 1966 1967 // - its function-body shall be [...] a compound-statement that contains only 1968 // [... list of cases ...] 1969 // 1970 // Note that walking the children here is enough to properly check for 1971 // CompoundStmt and CXXTryStmt body. 1972 SourceLocation Cxx1yLoc, Cxx2aLoc; 1973 for (Stmt *SubStmt : Body->children()) { 1974 if (SubStmt && 1975 !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts, 1976 Cxx1yLoc, Cxx2aLoc)) 1977 return false; 1978 } 1979 1980 if (Cxx2aLoc.isValid()) 1981 Diag(Cxx2aLoc, 1982 getLangOpts().CPlusPlus2a 1983 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 1984 : diag::ext_constexpr_body_invalid_stmt_cxx2a) 1985 << isa<CXXConstructorDecl>(Dcl); 1986 if (Cxx1yLoc.isValid()) 1987 Diag(Cxx1yLoc, 1988 getLangOpts().CPlusPlus14 1989 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1990 : diag::ext_constexpr_body_invalid_stmt) 1991 << isa<CXXConstructorDecl>(Dcl); 1992 1993 if (const CXXConstructorDecl *Constructor 1994 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1995 const CXXRecordDecl *RD = Constructor->getParent(); 1996 // DR1359: 1997 // - every non-variant non-static data member and base class sub-object 1998 // shall be initialized; 1999 // DR1460: 2000 // - if the class is a union having variant members, exactly one of them 2001 // shall be initialized; 2002 if (RD->isUnion()) { 2003 if (Constructor->getNumCtorInitializers() == 0 && 2004 RD->hasVariantMembers()) { 2005 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 2006 return false; 2007 } 2008 } else if (!Constructor->isDependentContext() && 2009 !Constructor->isDelegatingConstructor()) { 2010 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2011 2012 // Skip detailed checking if we have enough initializers, and we would 2013 // allow at most one initializer per member. 2014 bool AnyAnonStructUnionMembers = false; 2015 unsigned Fields = 0; 2016 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2017 E = RD->field_end(); I != E; ++I, ++Fields) { 2018 if (I->isAnonymousStructOrUnion()) { 2019 AnyAnonStructUnionMembers = true; 2020 break; 2021 } 2022 } 2023 // DR1460: 2024 // - if the class is a union-like class, but is not a union, for each of 2025 // its anonymous union members having variant members, exactly one of 2026 // them shall be initialized; 2027 if (AnyAnonStructUnionMembers || 2028 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2029 // Check initialization of non-static data members. Base classes are 2030 // always initialized so do not need to be checked. Dependent bases 2031 // might not have initializers in the member initializer list. 2032 llvm::SmallSet<Decl*, 16> Inits; 2033 for (const auto *I: Constructor->inits()) { 2034 if (FieldDecl *FD = I->getMember()) 2035 Inits.insert(FD); 2036 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2037 Inits.insert(ID->chain_begin(), ID->chain_end()); 2038 } 2039 2040 bool Diagnosed = false; 2041 for (auto *I : RD->fields()) 2042 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2043 if (Diagnosed) 2044 return false; 2045 } 2046 } 2047 } else { 2048 if (ReturnStmts.empty()) { 2049 // C++1y doesn't require constexpr functions to contain a 'return' 2050 // statement. We still do, unless the return type might be void, because 2051 // otherwise if there's no return statement, the function cannot 2052 // be used in a core constant expression. 2053 bool OK = getLangOpts().CPlusPlus14 && 2054 (Dcl->getReturnType()->isVoidType() || 2055 Dcl->getReturnType()->isDependentType()); 2056 Diag(Dcl->getLocation(), 2057 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2058 : diag::err_constexpr_body_no_return); 2059 if (!OK) 2060 return false; 2061 } else if (ReturnStmts.size() > 1) { 2062 Diag(ReturnStmts.back(), 2063 getLangOpts().CPlusPlus14 2064 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2065 : diag::ext_constexpr_body_multiple_return); 2066 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2067 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2068 } 2069 } 2070 2071 // C++11 [dcl.constexpr]p5: 2072 // if no function argument values exist such that the function invocation 2073 // substitution would produce a constant expression, the program is 2074 // ill-formed; no diagnostic required. 2075 // C++11 [dcl.constexpr]p3: 2076 // - every constructor call and implicit conversion used in initializing the 2077 // return value shall be one of those allowed in a constant expression. 2078 // C++11 [dcl.constexpr]p4: 2079 // - every constructor involved in initializing non-static data members and 2080 // base class sub-objects shall be a constexpr constructor. 2081 SmallVector<PartialDiagnosticAt, 8> Diags; 2082 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2083 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2084 << isa<CXXConstructorDecl>(Dcl); 2085 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2086 Diag(Diags[I].first, Diags[I].second); 2087 // Don't return false here: we allow this for compatibility in 2088 // system headers. 2089 } 2090 2091 return true; 2092 } 2093 2094 /// Get the class that is directly named by the current context. This is the 2095 /// class for which an unqualified-id in this scope could name a constructor 2096 /// or destructor. 2097 /// 2098 /// If the scope specifier denotes a class, this will be that class. 2099 /// If the scope specifier is empty, this will be the class whose 2100 /// member-specification we are currently within. Otherwise, there 2101 /// is no such class. 2102 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2103 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2104 2105 if (SS && SS->isInvalid()) 2106 return nullptr; 2107 2108 if (SS && SS->isNotEmpty()) { 2109 DeclContext *DC = computeDeclContext(*SS, true); 2110 return dyn_cast_or_null<CXXRecordDecl>(DC); 2111 } 2112 2113 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2114 } 2115 2116 /// isCurrentClassName - Determine whether the identifier II is the 2117 /// name of the class type currently being defined. In the case of 2118 /// nested classes, this will only return true if II is the name of 2119 /// the innermost class. 2120 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2121 const CXXScopeSpec *SS) { 2122 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2123 return CurDecl && &II == CurDecl->getIdentifier(); 2124 } 2125 2126 /// Determine whether the identifier II is a typo for the name of 2127 /// the class type currently being defined. If so, update it to the identifier 2128 /// that should have been used. 2129 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2130 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2131 2132 if (!getLangOpts().SpellChecking) 2133 return false; 2134 2135 CXXRecordDecl *CurDecl; 2136 if (SS && SS->isSet() && !SS->isInvalid()) { 2137 DeclContext *DC = computeDeclContext(*SS, true); 2138 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2139 } else 2140 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2141 2142 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2143 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2144 < II->getLength()) { 2145 II = CurDecl->getIdentifier(); 2146 return true; 2147 } 2148 2149 return false; 2150 } 2151 2152 /// Determine whether the given class is a base class of the given 2153 /// class, including looking at dependent bases. 2154 static bool findCircularInheritance(const CXXRecordDecl *Class, 2155 const CXXRecordDecl *Current) { 2156 SmallVector<const CXXRecordDecl*, 8> Queue; 2157 2158 Class = Class->getCanonicalDecl(); 2159 while (true) { 2160 for (const auto &I : Current->bases()) { 2161 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2162 if (!Base) 2163 continue; 2164 2165 Base = Base->getDefinition(); 2166 if (!Base) 2167 continue; 2168 2169 if (Base->getCanonicalDecl() == Class) 2170 return true; 2171 2172 Queue.push_back(Base); 2173 } 2174 2175 if (Queue.empty()) 2176 return false; 2177 2178 Current = Queue.pop_back_val(); 2179 } 2180 2181 return false; 2182 } 2183 2184 /// Check the validity of a C++ base class specifier. 2185 /// 2186 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2187 /// and returns NULL otherwise. 2188 CXXBaseSpecifier * 2189 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2190 SourceRange SpecifierRange, 2191 bool Virtual, AccessSpecifier Access, 2192 TypeSourceInfo *TInfo, 2193 SourceLocation EllipsisLoc) { 2194 QualType BaseType = TInfo->getType(); 2195 2196 // C++ [class.union]p1: 2197 // A union shall not have base classes. 2198 if (Class->isUnion()) { 2199 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2200 << SpecifierRange; 2201 return nullptr; 2202 } 2203 2204 if (EllipsisLoc.isValid() && 2205 !TInfo->getType()->containsUnexpandedParameterPack()) { 2206 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2207 << TInfo->getTypeLoc().getSourceRange(); 2208 EllipsisLoc = SourceLocation(); 2209 } 2210 2211 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2212 2213 if (BaseType->isDependentType()) { 2214 // Make sure that we don't have circular inheritance among our dependent 2215 // bases. For non-dependent bases, the check for completeness below handles 2216 // this. 2217 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2218 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2219 ((BaseDecl = BaseDecl->getDefinition()) && 2220 findCircularInheritance(Class, BaseDecl))) { 2221 Diag(BaseLoc, diag::err_circular_inheritance) 2222 << BaseType << Context.getTypeDeclType(Class); 2223 2224 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2225 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2226 << BaseType; 2227 2228 return nullptr; 2229 } 2230 } 2231 2232 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2233 Class->getTagKind() == TTK_Class, 2234 Access, TInfo, EllipsisLoc); 2235 } 2236 2237 // Base specifiers must be record types. 2238 if (!BaseType->isRecordType()) { 2239 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2240 return nullptr; 2241 } 2242 2243 // C++ [class.union]p1: 2244 // A union shall not be used as a base class. 2245 if (BaseType->isUnionType()) { 2246 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2247 return nullptr; 2248 } 2249 2250 // For the MS ABI, propagate DLL attributes to base class templates. 2251 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2252 if (Attr *ClassAttr = getDLLAttr(Class)) { 2253 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2254 BaseType->getAsCXXRecordDecl())) { 2255 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2256 BaseLoc); 2257 } 2258 } 2259 } 2260 2261 // C++ [class.derived]p2: 2262 // The class-name in a base-specifier shall not be an incompletely 2263 // defined class. 2264 if (RequireCompleteType(BaseLoc, BaseType, 2265 diag::err_incomplete_base_class, SpecifierRange)) { 2266 Class->setInvalidDecl(); 2267 return nullptr; 2268 } 2269 2270 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2271 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2272 assert(BaseDecl && "Record type has no declaration"); 2273 BaseDecl = BaseDecl->getDefinition(); 2274 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2275 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2276 assert(CXXBaseDecl && "Base type is not a C++ type"); 2277 2278 // Microsoft docs say: 2279 // "If a base-class has a code_seg attribute, derived classes must have the 2280 // same attribute." 2281 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2282 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2283 if ((DerivedCSA || BaseCSA) && 2284 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2285 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2286 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2287 << CXXBaseDecl; 2288 return nullptr; 2289 } 2290 2291 // A class which contains a flexible array member is not suitable for use as a 2292 // base class: 2293 // - If the layout determines that a base comes before another base, 2294 // the flexible array member would index into the subsequent base. 2295 // - If the layout determines that base comes before the derived class, 2296 // the flexible array member would index into the derived class. 2297 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2298 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2299 << CXXBaseDecl->getDeclName(); 2300 return nullptr; 2301 } 2302 2303 // C++ [class]p3: 2304 // If a class is marked final and it appears as a base-type-specifier in 2305 // base-clause, the program is ill-formed. 2306 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2307 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2308 << CXXBaseDecl->getDeclName() 2309 << FA->isSpelledAsSealed(); 2310 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2311 << CXXBaseDecl->getDeclName() << FA->getRange(); 2312 return nullptr; 2313 } 2314 2315 if (BaseDecl->isInvalidDecl()) 2316 Class->setInvalidDecl(); 2317 2318 // Create the base specifier. 2319 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2320 Class->getTagKind() == TTK_Class, 2321 Access, TInfo, EllipsisLoc); 2322 } 2323 2324 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2325 /// one entry in the base class list of a class specifier, for 2326 /// example: 2327 /// class foo : public bar, virtual private baz { 2328 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2329 BaseResult 2330 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2331 ParsedAttributes &Attributes, 2332 bool Virtual, AccessSpecifier Access, 2333 ParsedType basetype, SourceLocation BaseLoc, 2334 SourceLocation EllipsisLoc) { 2335 if (!classdecl) 2336 return true; 2337 2338 AdjustDeclIfTemplate(classdecl); 2339 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2340 if (!Class) 2341 return true; 2342 2343 // We haven't yet attached the base specifiers. 2344 Class->setIsParsingBaseSpecifiers(); 2345 2346 // We do not support any C++11 attributes on base-specifiers yet. 2347 // Diagnose any attributes we see. 2348 for (const ParsedAttr &AL : Attributes) { 2349 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2350 continue; 2351 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2352 ? (unsigned)diag::warn_unknown_attribute_ignored 2353 : (unsigned)diag::err_base_specifier_attribute) 2354 << AL.getName(); 2355 } 2356 2357 TypeSourceInfo *TInfo = nullptr; 2358 GetTypeFromParser(basetype, &TInfo); 2359 2360 if (EllipsisLoc.isInvalid() && 2361 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2362 UPPC_BaseType)) 2363 return true; 2364 2365 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2366 Virtual, Access, TInfo, 2367 EllipsisLoc)) 2368 return BaseSpec; 2369 else 2370 Class->setInvalidDecl(); 2371 2372 return true; 2373 } 2374 2375 /// Use small set to collect indirect bases. As this is only used 2376 /// locally, there's no need to abstract the small size parameter. 2377 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2378 2379 /// Recursively add the bases of Type. Don't add Type itself. 2380 static void 2381 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2382 const QualType &Type) 2383 { 2384 // Even though the incoming type is a base, it might not be 2385 // a class -- it could be a template parm, for instance. 2386 if (auto Rec = Type->getAs<RecordType>()) { 2387 auto Decl = Rec->getAsCXXRecordDecl(); 2388 2389 // Iterate over its bases. 2390 for (const auto &BaseSpec : Decl->bases()) { 2391 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2392 .getUnqualifiedType(); 2393 if (Set.insert(Base).second) 2394 // If we've not already seen it, recurse. 2395 NoteIndirectBases(Context, Set, Base); 2396 } 2397 } 2398 } 2399 2400 /// Performs the actual work of attaching the given base class 2401 /// specifiers to a C++ class. 2402 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2403 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2404 if (Bases.empty()) 2405 return false; 2406 2407 // Used to keep track of which base types we have already seen, so 2408 // that we can properly diagnose redundant direct base types. Note 2409 // that the key is always the unqualified canonical type of the base 2410 // class. 2411 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2412 2413 // Used to track indirect bases so we can see if a direct base is 2414 // ambiguous. 2415 IndirectBaseSet IndirectBaseTypes; 2416 2417 // Copy non-redundant base specifiers into permanent storage. 2418 unsigned NumGoodBases = 0; 2419 bool Invalid = false; 2420 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2421 QualType NewBaseType 2422 = Context.getCanonicalType(Bases[idx]->getType()); 2423 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2424 2425 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2426 if (KnownBase) { 2427 // C++ [class.mi]p3: 2428 // A class shall not be specified as a direct base class of a 2429 // derived class more than once. 2430 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2431 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2432 2433 // Delete the duplicate base class specifier; we're going to 2434 // overwrite its pointer later. 2435 Context.Deallocate(Bases[idx]); 2436 2437 Invalid = true; 2438 } else { 2439 // Okay, add this new base class. 2440 KnownBase = Bases[idx]; 2441 Bases[NumGoodBases++] = Bases[idx]; 2442 2443 // Note this base's direct & indirect bases, if there could be ambiguity. 2444 if (Bases.size() > 1) 2445 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2446 2447 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2448 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2449 if (Class->isInterface() && 2450 (!RD->isInterfaceLike() || 2451 KnownBase->getAccessSpecifier() != AS_public)) { 2452 // The Microsoft extension __interface does not permit bases that 2453 // are not themselves public interfaces. 2454 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2455 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2456 << RD->getSourceRange(); 2457 Invalid = true; 2458 } 2459 if (RD->hasAttr<WeakAttr>()) 2460 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2461 } 2462 } 2463 } 2464 2465 // Attach the remaining base class specifiers to the derived class. 2466 Class->setBases(Bases.data(), NumGoodBases); 2467 2468 // Check that the only base classes that are duplicate are virtual. 2469 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2470 // Check whether this direct base is inaccessible due to ambiguity. 2471 QualType BaseType = Bases[idx]->getType(); 2472 2473 // Skip all dependent types in templates being used as base specifiers. 2474 // Checks below assume that the base specifier is a CXXRecord. 2475 if (BaseType->isDependentType()) 2476 continue; 2477 2478 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2479 .getUnqualifiedType(); 2480 2481 if (IndirectBaseTypes.count(CanonicalBase)) { 2482 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2483 /*DetectVirtual=*/true); 2484 bool found 2485 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2486 assert(found); 2487 (void)found; 2488 2489 if (Paths.isAmbiguous(CanonicalBase)) 2490 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2491 << BaseType << getAmbiguousPathsDisplayString(Paths) 2492 << Bases[idx]->getSourceRange(); 2493 else 2494 assert(Bases[idx]->isVirtual()); 2495 } 2496 2497 // Delete the base class specifier, since its data has been copied 2498 // into the CXXRecordDecl. 2499 Context.Deallocate(Bases[idx]); 2500 } 2501 2502 return Invalid; 2503 } 2504 2505 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2506 /// class, after checking whether there are any duplicate base 2507 /// classes. 2508 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2509 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2510 if (!ClassDecl || Bases.empty()) 2511 return; 2512 2513 AdjustDeclIfTemplate(ClassDecl); 2514 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2515 } 2516 2517 /// Determine whether the type \p Derived is a C++ class that is 2518 /// derived from the type \p Base. 2519 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2520 if (!getLangOpts().CPlusPlus) 2521 return false; 2522 2523 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2524 if (!DerivedRD) 2525 return false; 2526 2527 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2528 if (!BaseRD) 2529 return false; 2530 2531 // If either the base or the derived type is invalid, don't try to 2532 // check whether one is derived from the other. 2533 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2534 return false; 2535 2536 // FIXME: In a modules build, do we need the entire path to be visible for us 2537 // to be able to use the inheritance relationship? 2538 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2539 return false; 2540 2541 return DerivedRD->isDerivedFrom(BaseRD); 2542 } 2543 2544 /// Determine whether the type \p Derived is a C++ class that is 2545 /// derived from the type \p Base. 2546 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2547 CXXBasePaths &Paths) { 2548 if (!getLangOpts().CPlusPlus) 2549 return false; 2550 2551 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2552 if (!DerivedRD) 2553 return false; 2554 2555 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2556 if (!BaseRD) 2557 return false; 2558 2559 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2560 return false; 2561 2562 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2563 } 2564 2565 static void BuildBasePathArray(const CXXBasePath &Path, 2566 CXXCastPath &BasePathArray) { 2567 // We first go backward and check if we have a virtual base. 2568 // FIXME: It would be better if CXXBasePath had the base specifier for 2569 // the nearest virtual base. 2570 unsigned Start = 0; 2571 for (unsigned I = Path.size(); I != 0; --I) { 2572 if (Path[I - 1].Base->isVirtual()) { 2573 Start = I - 1; 2574 break; 2575 } 2576 } 2577 2578 // Now add all bases. 2579 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2580 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2581 } 2582 2583 2584 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2585 CXXCastPath &BasePathArray) { 2586 assert(BasePathArray.empty() && "Base path array must be empty!"); 2587 assert(Paths.isRecordingPaths() && "Must record paths!"); 2588 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2589 } 2590 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2591 /// conversion (where Derived and Base are class types) is 2592 /// well-formed, meaning that the conversion is unambiguous (and 2593 /// that all of the base classes are accessible). Returns true 2594 /// and emits a diagnostic if the code is ill-formed, returns false 2595 /// otherwise. Loc is the location where this routine should point to 2596 /// if there is an error, and Range is the source range to highlight 2597 /// if there is an error. 2598 /// 2599 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2600 /// diagnostic for the respective type of error will be suppressed, but the 2601 /// check for ill-formed code will still be performed. 2602 bool 2603 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2604 unsigned InaccessibleBaseID, 2605 unsigned AmbigiousBaseConvID, 2606 SourceLocation Loc, SourceRange Range, 2607 DeclarationName Name, 2608 CXXCastPath *BasePath, 2609 bool IgnoreAccess) { 2610 // First, determine whether the path from Derived to Base is 2611 // ambiguous. This is slightly more expensive than checking whether 2612 // the Derived to Base conversion exists, because here we need to 2613 // explore multiple paths to determine if there is an ambiguity. 2614 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2615 /*DetectVirtual=*/false); 2616 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2617 if (!DerivationOkay) 2618 return true; 2619 2620 const CXXBasePath *Path = nullptr; 2621 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2622 Path = &Paths.front(); 2623 2624 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2625 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2626 // user to access such bases. 2627 if (!Path && getLangOpts().MSVCCompat) { 2628 for (const CXXBasePath &PossiblePath : Paths) { 2629 if (PossiblePath.size() == 1) { 2630 Path = &PossiblePath; 2631 if (AmbigiousBaseConvID) 2632 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2633 << Base << Derived << Range; 2634 break; 2635 } 2636 } 2637 } 2638 2639 if (Path) { 2640 if (!IgnoreAccess) { 2641 // Check that the base class can be accessed. 2642 switch ( 2643 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2644 case AR_inaccessible: 2645 return true; 2646 case AR_accessible: 2647 case AR_dependent: 2648 case AR_delayed: 2649 break; 2650 } 2651 } 2652 2653 // Build a base path if necessary. 2654 if (BasePath) 2655 ::BuildBasePathArray(*Path, *BasePath); 2656 return false; 2657 } 2658 2659 if (AmbigiousBaseConvID) { 2660 // We know that the derived-to-base conversion is ambiguous, and 2661 // we're going to produce a diagnostic. Perform the derived-to-base 2662 // search just one more time to compute all of the possible paths so 2663 // that we can print them out. This is more expensive than any of 2664 // the previous derived-to-base checks we've done, but at this point 2665 // performance isn't as much of an issue. 2666 Paths.clear(); 2667 Paths.setRecordingPaths(true); 2668 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2669 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2670 (void)StillOkay; 2671 2672 // Build up a textual representation of the ambiguous paths, e.g., 2673 // D -> B -> A, that will be used to illustrate the ambiguous 2674 // conversions in the diagnostic. We only print one of the paths 2675 // to each base class subobject. 2676 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2677 2678 Diag(Loc, AmbigiousBaseConvID) 2679 << Derived << Base << PathDisplayStr << Range << Name; 2680 } 2681 return true; 2682 } 2683 2684 bool 2685 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2686 SourceLocation Loc, SourceRange Range, 2687 CXXCastPath *BasePath, 2688 bool IgnoreAccess) { 2689 return CheckDerivedToBaseConversion( 2690 Derived, Base, diag::err_upcast_to_inaccessible_base, 2691 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2692 BasePath, IgnoreAccess); 2693 } 2694 2695 2696 /// Builds a string representing ambiguous paths from a 2697 /// specific derived class to different subobjects of the same base 2698 /// class. 2699 /// 2700 /// This function builds a string that can be used in error messages 2701 /// to show the different paths that one can take through the 2702 /// inheritance hierarchy to go from the derived class to different 2703 /// subobjects of a base class. The result looks something like this: 2704 /// @code 2705 /// struct D -> struct B -> struct A 2706 /// struct D -> struct C -> struct A 2707 /// @endcode 2708 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2709 std::string PathDisplayStr; 2710 std::set<unsigned> DisplayedPaths; 2711 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2712 Path != Paths.end(); ++Path) { 2713 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2714 // We haven't displayed a path to this particular base 2715 // class subobject yet. 2716 PathDisplayStr += "\n "; 2717 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2718 for (CXXBasePath::const_iterator Element = Path->begin(); 2719 Element != Path->end(); ++Element) 2720 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2721 } 2722 } 2723 2724 return PathDisplayStr; 2725 } 2726 2727 //===----------------------------------------------------------------------===// 2728 // C++ class member Handling 2729 //===----------------------------------------------------------------------===// 2730 2731 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2732 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2733 SourceLocation ColonLoc, 2734 const ParsedAttributesView &Attrs) { 2735 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2736 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2737 ASLoc, ColonLoc); 2738 CurContext->addHiddenDecl(ASDecl); 2739 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2740 } 2741 2742 /// CheckOverrideControl - Check C++11 override control semantics. 2743 void Sema::CheckOverrideControl(NamedDecl *D) { 2744 if (D->isInvalidDecl()) 2745 return; 2746 2747 // We only care about "override" and "final" declarations. 2748 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2749 return; 2750 2751 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2752 2753 // We can't check dependent instance methods. 2754 if (MD && MD->isInstance() && 2755 (MD->getParent()->hasAnyDependentBases() || 2756 MD->getType()->isDependentType())) 2757 return; 2758 2759 if (MD && !MD->isVirtual()) { 2760 // If we have a non-virtual method, check if if hides a virtual method. 2761 // (In that case, it's most likely the method has the wrong type.) 2762 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2763 FindHiddenVirtualMethods(MD, OverloadedMethods); 2764 2765 if (!OverloadedMethods.empty()) { 2766 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2767 Diag(OA->getLocation(), 2768 diag::override_keyword_hides_virtual_member_function) 2769 << "override" << (OverloadedMethods.size() > 1); 2770 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2771 Diag(FA->getLocation(), 2772 diag::override_keyword_hides_virtual_member_function) 2773 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2774 << (OverloadedMethods.size() > 1); 2775 } 2776 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2777 MD->setInvalidDecl(); 2778 return; 2779 } 2780 // Fall through into the general case diagnostic. 2781 // FIXME: We might want to attempt typo correction here. 2782 } 2783 2784 if (!MD || !MD->isVirtual()) { 2785 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2786 Diag(OA->getLocation(), 2787 diag::override_keyword_only_allowed_on_virtual_member_functions) 2788 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2789 D->dropAttr<OverrideAttr>(); 2790 } 2791 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2792 Diag(FA->getLocation(), 2793 diag::override_keyword_only_allowed_on_virtual_member_functions) 2794 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2795 << FixItHint::CreateRemoval(FA->getLocation()); 2796 D->dropAttr<FinalAttr>(); 2797 } 2798 return; 2799 } 2800 2801 // C++11 [class.virtual]p5: 2802 // If a function is marked with the virt-specifier override and 2803 // does not override a member function of a base class, the program is 2804 // ill-formed. 2805 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2806 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2807 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2808 << MD->getDeclName(); 2809 } 2810 2811 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2812 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2813 return; 2814 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2815 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2816 return; 2817 2818 SourceLocation Loc = MD->getLocation(); 2819 SourceLocation SpellingLoc = Loc; 2820 if (getSourceManager().isMacroArgExpansion(Loc)) 2821 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 2822 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2823 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2824 return; 2825 2826 if (MD->size_overridden_methods() > 0) { 2827 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2828 ? diag::warn_destructor_marked_not_override_overriding 2829 : diag::warn_function_marked_not_override_overriding; 2830 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2831 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2832 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2833 } 2834 } 2835 2836 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2837 /// function overrides a virtual member function marked 'final', according to 2838 /// C++11 [class.virtual]p4. 2839 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2840 const CXXMethodDecl *Old) { 2841 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2842 if (!FA) 2843 return false; 2844 2845 Diag(New->getLocation(), diag::err_final_function_overridden) 2846 << New->getDeclName() 2847 << FA->isSpelledAsSealed(); 2848 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2849 return true; 2850 } 2851 2852 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2853 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2854 // FIXME: Destruction of ObjC lifetime types has side-effects. 2855 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2856 return !RD->isCompleteDefinition() || 2857 !RD->hasTrivialDefaultConstructor() || 2858 !RD->hasTrivialDestructor(); 2859 return false; 2860 } 2861 2862 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 2863 ParsedAttributesView::const_iterator Itr = 2864 llvm::find_if(list, [](const ParsedAttr &AL) { 2865 return AL.isDeclspecPropertyAttribute(); 2866 }); 2867 if (Itr != list.end()) 2868 return &*Itr; 2869 return nullptr; 2870 } 2871 2872 // Check if there is a field shadowing. 2873 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2874 DeclarationName FieldName, 2875 const CXXRecordDecl *RD, 2876 bool DeclIsField) { 2877 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2878 return; 2879 2880 // To record a shadowed field in a base 2881 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2882 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2883 CXXBasePath &Path) { 2884 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2885 // Record an ambiguous path directly 2886 if (Bases.find(Base) != Bases.end()) 2887 return true; 2888 for (const auto Field : Base->lookup(FieldName)) { 2889 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2890 Field->getAccess() != AS_private) { 2891 assert(Field->getAccess() != AS_none); 2892 assert(Bases.find(Base) == Bases.end()); 2893 Bases[Base] = Field; 2894 return true; 2895 } 2896 } 2897 return false; 2898 }; 2899 2900 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2901 /*DetectVirtual=*/true); 2902 if (!RD->lookupInBases(FieldShadowed, Paths)) 2903 return; 2904 2905 for (const auto &P : Paths) { 2906 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2907 auto It = Bases.find(Base); 2908 // Skip duplicated bases 2909 if (It == Bases.end()) 2910 continue; 2911 auto BaseField = It->second; 2912 assert(BaseField->getAccess() != AS_private); 2913 if (AS_none != 2914 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2915 Diag(Loc, diag::warn_shadow_field) 2916 << FieldName << RD << Base << DeclIsField; 2917 Diag(BaseField->getLocation(), diag::note_shadow_field); 2918 Bases.erase(It); 2919 } 2920 } 2921 } 2922 2923 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2924 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2925 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2926 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2927 /// present (but parsing it has been deferred). 2928 NamedDecl * 2929 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2930 MultiTemplateParamsArg TemplateParameterLists, 2931 Expr *BW, const VirtSpecifiers &VS, 2932 InClassInitStyle InitStyle) { 2933 const DeclSpec &DS = D.getDeclSpec(); 2934 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2935 DeclarationName Name = NameInfo.getName(); 2936 SourceLocation Loc = NameInfo.getLoc(); 2937 2938 // For anonymous bitfields, the location should point to the type. 2939 if (Loc.isInvalid()) 2940 Loc = D.getBeginLoc(); 2941 2942 Expr *BitWidth = static_cast<Expr*>(BW); 2943 2944 assert(isa<CXXRecordDecl>(CurContext)); 2945 assert(!DS.isFriendSpecified()); 2946 2947 bool isFunc = D.isDeclarationOfFunction(); 2948 const ParsedAttr *MSPropertyAttr = 2949 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 2950 2951 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2952 // The Microsoft extension __interface only permits public member functions 2953 // and prohibits constructors, destructors, operators, non-public member 2954 // functions, static methods and data members. 2955 unsigned InvalidDecl; 2956 bool ShowDeclName = true; 2957 if (!isFunc && 2958 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2959 InvalidDecl = 0; 2960 else if (!isFunc) 2961 InvalidDecl = 1; 2962 else if (AS != AS_public) 2963 InvalidDecl = 2; 2964 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2965 InvalidDecl = 3; 2966 else switch (Name.getNameKind()) { 2967 case DeclarationName::CXXConstructorName: 2968 InvalidDecl = 4; 2969 ShowDeclName = false; 2970 break; 2971 2972 case DeclarationName::CXXDestructorName: 2973 InvalidDecl = 5; 2974 ShowDeclName = false; 2975 break; 2976 2977 case DeclarationName::CXXOperatorName: 2978 case DeclarationName::CXXConversionFunctionName: 2979 InvalidDecl = 6; 2980 break; 2981 2982 default: 2983 InvalidDecl = 0; 2984 break; 2985 } 2986 2987 if (InvalidDecl) { 2988 if (ShowDeclName) 2989 Diag(Loc, diag::err_invalid_member_in_interface) 2990 << (InvalidDecl-1) << Name; 2991 else 2992 Diag(Loc, diag::err_invalid_member_in_interface) 2993 << (InvalidDecl-1) << ""; 2994 return nullptr; 2995 } 2996 } 2997 2998 // C++ 9.2p6: A member shall not be declared to have automatic storage 2999 // duration (auto, register) or with the extern storage-class-specifier. 3000 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3001 // data members and cannot be applied to names declared const or static, 3002 // and cannot be applied to reference members. 3003 switch (DS.getStorageClassSpec()) { 3004 case DeclSpec::SCS_unspecified: 3005 case DeclSpec::SCS_typedef: 3006 case DeclSpec::SCS_static: 3007 break; 3008 case DeclSpec::SCS_mutable: 3009 if (isFunc) { 3010 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3011 3012 // FIXME: It would be nicer if the keyword was ignored only for this 3013 // declarator. Otherwise we could get follow-up errors. 3014 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3015 } 3016 break; 3017 default: 3018 Diag(DS.getStorageClassSpecLoc(), 3019 diag::err_storageclass_invalid_for_member); 3020 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3021 break; 3022 } 3023 3024 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3025 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3026 !isFunc); 3027 3028 if (DS.isConstexprSpecified() && isInstField) { 3029 SemaDiagnosticBuilder B = 3030 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3031 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3032 if (InitStyle == ICIS_NoInit) { 3033 B << 0 << 0; 3034 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3035 B << FixItHint::CreateRemoval(ConstexprLoc); 3036 else { 3037 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3038 D.getMutableDeclSpec().ClearConstexprSpec(); 3039 const char *PrevSpec; 3040 unsigned DiagID; 3041 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3042 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3043 (void)Failed; 3044 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3045 } 3046 } else { 3047 B << 1; 3048 const char *PrevSpec; 3049 unsigned DiagID; 3050 if (D.getMutableDeclSpec().SetStorageClassSpec( 3051 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3052 Context.getPrintingPolicy())) { 3053 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3054 "This is the only DeclSpec that should fail to be applied"); 3055 B << 1; 3056 } else { 3057 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3058 isInstField = false; 3059 } 3060 } 3061 } 3062 3063 NamedDecl *Member; 3064 if (isInstField) { 3065 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3066 3067 // Data members must have identifiers for names. 3068 if (!Name.isIdentifier()) { 3069 Diag(Loc, diag::err_bad_variable_name) 3070 << Name; 3071 return nullptr; 3072 } 3073 3074 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3075 3076 // Member field could not be with "template" keyword. 3077 // So TemplateParameterLists should be empty in this case. 3078 if (TemplateParameterLists.size()) { 3079 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3080 if (TemplateParams->size()) { 3081 // There is no such thing as a member field template. 3082 Diag(D.getIdentifierLoc(), diag::err_template_member) 3083 << II 3084 << SourceRange(TemplateParams->getTemplateLoc(), 3085 TemplateParams->getRAngleLoc()); 3086 } else { 3087 // There is an extraneous 'template<>' for this member. 3088 Diag(TemplateParams->getTemplateLoc(), 3089 diag::err_template_member_noparams) 3090 << II 3091 << SourceRange(TemplateParams->getTemplateLoc(), 3092 TemplateParams->getRAngleLoc()); 3093 } 3094 return nullptr; 3095 } 3096 3097 if (SS.isSet() && !SS.isInvalid()) { 3098 // The user provided a superfluous scope specifier inside a class 3099 // definition: 3100 // 3101 // class X { 3102 // int X::member; 3103 // }; 3104 if (DeclContext *DC = computeDeclContext(SS, false)) 3105 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3106 D.getName().getKind() == 3107 UnqualifiedIdKind::IK_TemplateId); 3108 else 3109 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3110 << Name << SS.getRange(); 3111 3112 SS.clear(); 3113 } 3114 3115 if (MSPropertyAttr) { 3116 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3117 BitWidth, InitStyle, AS, *MSPropertyAttr); 3118 if (!Member) 3119 return nullptr; 3120 isInstField = false; 3121 } else { 3122 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3123 BitWidth, InitStyle, AS); 3124 if (!Member) 3125 return nullptr; 3126 } 3127 3128 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3129 } else { 3130 Member = HandleDeclarator(S, D, TemplateParameterLists); 3131 if (!Member) 3132 return nullptr; 3133 3134 // Non-instance-fields can't have a bitfield. 3135 if (BitWidth) { 3136 if (Member->isInvalidDecl()) { 3137 // don't emit another diagnostic. 3138 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3139 // C++ 9.6p3: A bit-field shall not be a static member. 3140 // "static member 'A' cannot be a bit-field" 3141 Diag(Loc, diag::err_static_not_bitfield) 3142 << Name << BitWidth->getSourceRange(); 3143 } else if (isa<TypedefDecl>(Member)) { 3144 // "typedef member 'x' cannot be a bit-field" 3145 Diag(Loc, diag::err_typedef_not_bitfield) 3146 << Name << BitWidth->getSourceRange(); 3147 } else { 3148 // A function typedef ("typedef int f(); f a;"). 3149 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3150 Diag(Loc, diag::err_not_integral_type_bitfield) 3151 << Name << cast<ValueDecl>(Member)->getType() 3152 << BitWidth->getSourceRange(); 3153 } 3154 3155 BitWidth = nullptr; 3156 Member->setInvalidDecl(); 3157 } 3158 3159 NamedDecl *NonTemplateMember = Member; 3160 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3161 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3162 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3163 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3164 3165 Member->setAccess(AS); 3166 3167 // If we have declared a member function template or static data member 3168 // template, set the access of the templated declaration as well. 3169 if (NonTemplateMember != Member) 3170 NonTemplateMember->setAccess(AS); 3171 3172 // C++ [temp.deduct.guide]p3: 3173 // A deduction guide [...] for a member class template [shall be 3174 // declared] with the same access [as the template]. 3175 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3176 auto *TD = DG->getDeducedTemplate(); 3177 // Access specifiers are only meaningful if both the template and the 3178 // deduction guide are from the same scope. 3179 if (AS != TD->getAccess() && 3180 TD->getDeclContext()->getRedeclContext()->Equals( 3181 DG->getDeclContext()->getRedeclContext())) { 3182 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3183 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3184 << TD->getAccess(); 3185 const AccessSpecDecl *LastAccessSpec = nullptr; 3186 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3187 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3188 LastAccessSpec = AccessSpec; 3189 } 3190 assert(LastAccessSpec && "differing access with no access specifier"); 3191 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3192 << AS; 3193 } 3194 } 3195 } 3196 3197 if (VS.isOverrideSpecified()) 3198 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3199 if (VS.isFinalSpecified()) 3200 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3201 VS.isFinalSpelledSealed())); 3202 3203 if (VS.getLastLocation().isValid()) { 3204 // Update the end location of a method that has a virt-specifiers. 3205 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3206 MD->setRangeEnd(VS.getLastLocation()); 3207 } 3208 3209 CheckOverrideControl(Member); 3210 3211 assert((Name || isInstField) && "No identifier for non-field ?"); 3212 3213 if (isInstField) { 3214 FieldDecl *FD = cast<FieldDecl>(Member); 3215 FieldCollector->Add(FD); 3216 3217 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3218 // Remember all explicit private FieldDecls that have a name, no side 3219 // effects and are not part of a dependent type declaration. 3220 if (!FD->isImplicit() && FD->getDeclName() && 3221 FD->getAccess() == AS_private && 3222 !FD->hasAttr<UnusedAttr>() && 3223 !FD->getParent()->isDependentContext() && 3224 !InitializationHasSideEffects(*FD)) 3225 UnusedPrivateFields.insert(FD); 3226 } 3227 } 3228 3229 return Member; 3230 } 3231 3232 namespace { 3233 class UninitializedFieldVisitor 3234 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3235 Sema &S; 3236 // List of Decls to generate a warning on. Also remove Decls that become 3237 // initialized. 3238 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3239 // List of base classes of the record. Classes are removed after their 3240 // initializers. 3241 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3242 // Vector of decls to be removed from the Decl set prior to visiting the 3243 // nodes. These Decls may have been initialized in the prior initializer. 3244 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3245 // If non-null, add a note to the warning pointing back to the constructor. 3246 const CXXConstructorDecl *Constructor; 3247 // Variables to hold state when processing an initializer list. When 3248 // InitList is true, special case initialization of FieldDecls matching 3249 // InitListFieldDecl. 3250 bool InitList; 3251 FieldDecl *InitListFieldDecl; 3252 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3253 3254 public: 3255 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3256 UninitializedFieldVisitor(Sema &S, 3257 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3258 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3259 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3260 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3261 3262 // Returns true if the use of ME is not an uninitialized use. 3263 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3264 bool CheckReferenceOnly) { 3265 llvm::SmallVector<FieldDecl*, 4> Fields; 3266 bool ReferenceField = false; 3267 while (ME) { 3268 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3269 if (!FD) 3270 return false; 3271 Fields.push_back(FD); 3272 if (FD->getType()->isReferenceType()) 3273 ReferenceField = true; 3274 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3275 } 3276 3277 // Binding a reference to an uninitialized field is not an 3278 // uninitialized use. 3279 if (CheckReferenceOnly && !ReferenceField) 3280 return true; 3281 3282 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3283 // Discard the first field since it is the field decl that is being 3284 // initialized. 3285 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3286 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3287 } 3288 3289 for (auto UsedIter = UsedFieldIndex.begin(), 3290 UsedEnd = UsedFieldIndex.end(), 3291 OrigIter = InitFieldIndex.begin(), 3292 OrigEnd = InitFieldIndex.end(); 3293 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3294 if (*UsedIter < *OrigIter) 3295 return true; 3296 if (*UsedIter > *OrigIter) 3297 break; 3298 } 3299 3300 return false; 3301 } 3302 3303 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3304 bool AddressOf) { 3305 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3306 return; 3307 3308 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3309 // or union. 3310 MemberExpr *FieldME = ME; 3311 3312 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3313 3314 Expr *Base = ME; 3315 while (MemberExpr *SubME = 3316 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3317 3318 if (isa<VarDecl>(SubME->getMemberDecl())) 3319 return; 3320 3321 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3322 if (!FD->isAnonymousStructOrUnion()) 3323 FieldME = SubME; 3324 3325 if (!FieldME->getType().isPODType(S.Context)) 3326 AllPODFields = false; 3327 3328 Base = SubME->getBase(); 3329 } 3330 3331 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3332 return; 3333 3334 if (AddressOf && AllPODFields) 3335 return; 3336 3337 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3338 3339 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3340 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3341 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3342 } 3343 3344 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3345 QualType T = BaseCast->getType(); 3346 if (T->isPointerType() && 3347 BaseClasses.count(T->getPointeeType())) { 3348 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3349 << T->getPointeeType() << FoundVD; 3350 } 3351 } 3352 } 3353 3354 if (!Decls.count(FoundVD)) 3355 return; 3356 3357 const bool IsReference = FoundVD->getType()->isReferenceType(); 3358 3359 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3360 // Special checking for initializer lists. 3361 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3362 return; 3363 } 3364 } else { 3365 // Prevent double warnings on use of unbounded references. 3366 if (CheckReferenceOnly && !IsReference) 3367 return; 3368 } 3369 3370 unsigned diag = IsReference 3371 ? diag::warn_reference_field_is_uninit 3372 : diag::warn_field_is_uninit; 3373 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3374 if (Constructor) 3375 S.Diag(Constructor->getLocation(), 3376 diag::note_uninit_in_this_constructor) 3377 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3378 3379 } 3380 3381 void HandleValue(Expr *E, bool AddressOf) { 3382 E = E->IgnoreParens(); 3383 3384 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3385 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3386 AddressOf /*AddressOf*/); 3387 return; 3388 } 3389 3390 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3391 Visit(CO->getCond()); 3392 HandleValue(CO->getTrueExpr(), AddressOf); 3393 HandleValue(CO->getFalseExpr(), AddressOf); 3394 return; 3395 } 3396 3397 if (BinaryConditionalOperator *BCO = 3398 dyn_cast<BinaryConditionalOperator>(E)) { 3399 Visit(BCO->getCond()); 3400 HandleValue(BCO->getFalseExpr(), AddressOf); 3401 return; 3402 } 3403 3404 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3405 HandleValue(OVE->getSourceExpr(), AddressOf); 3406 return; 3407 } 3408 3409 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3410 switch (BO->getOpcode()) { 3411 default: 3412 break; 3413 case(BO_PtrMemD): 3414 case(BO_PtrMemI): 3415 HandleValue(BO->getLHS(), AddressOf); 3416 Visit(BO->getRHS()); 3417 return; 3418 case(BO_Comma): 3419 Visit(BO->getLHS()); 3420 HandleValue(BO->getRHS(), AddressOf); 3421 return; 3422 } 3423 } 3424 3425 Visit(E); 3426 } 3427 3428 void CheckInitListExpr(InitListExpr *ILE) { 3429 InitFieldIndex.push_back(0); 3430 for (auto Child : ILE->children()) { 3431 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3432 CheckInitListExpr(SubList); 3433 } else { 3434 Visit(Child); 3435 } 3436 ++InitFieldIndex.back(); 3437 } 3438 InitFieldIndex.pop_back(); 3439 } 3440 3441 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3442 FieldDecl *Field, const Type *BaseClass) { 3443 // Remove Decls that may have been initialized in the previous 3444 // initializer. 3445 for (ValueDecl* VD : DeclsToRemove) 3446 Decls.erase(VD); 3447 DeclsToRemove.clear(); 3448 3449 Constructor = FieldConstructor; 3450 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3451 3452 if (ILE && Field) { 3453 InitList = true; 3454 InitListFieldDecl = Field; 3455 InitFieldIndex.clear(); 3456 CheckInitListExpr(ILE); 3457 } else { 3458 InitList = false; 3459 Visit(E); 3460 } 3461 3462 if (Field) 3463 Decls.erase(Field); 3464 if (BaseClass) 3465 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3466 } 3467 3468 void VisitMemberExpr(MemberExpr *ME) { 3469 // All uses of unbounded reference fields will warn. 3470 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3471 } 3472 3473 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3474 if (E->getCastKind() == CK_LValueToRValue) { 3475 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3476 return; 3477 } 3478 3479 Inherited::VisitImplicitCastExpr(E); 3480 } 3481 3482 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3483 if (E->getConstructor()->isCopyConstructor()) { 3484 Expr *ArgExpr = E->getArg(0); 3485 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3486 if (ILE->getNumInits() == 1) 3487 ArgExpr = ILE->getInit(0); 3488 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3489 if (ICE->getCastKind() == CK_NoOp) 3490 ArgExpr = ICE->getSubExpr(); 3491 HandleValue(ArgExpr, false /*AddressOf*/); 3492 return; 3493 } 3494 Inherited::VisitCXXConstructExpr(E); 3495 } 3496 3497 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3498 Expr *Callee = E->getCallee(); 3499 if (isa<MemberExpr>(Callee)) { 3500 HandleValue(Callee, false /*AddressOf*/); 3501 for (auto Arg : E->arguments()) 3502 Visit(Arg); 3503 return; 3504 } 3505 3506 Inherited::VisitCXXMemberCallExpr(E); 3507 } 3508 3509 void VisitCallExpr(CallExpr *E) { 3510 // Treat std::move as a use. 3511 if (E->isCallToStdMove()) { 3512 HandleValue(E->getArg(0), /*AddressOf=*/false); 3513 return; 3514 } 3515 3516 Inherited::VisitCallExpr(E); 3517 } 3518 3519 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3520 Expr *Callee = E->getCallee(); 3521 3522 if (isa<UnresolvedLookupExpr>(Callee)) 3523 return Inherited::VisitCXXOperatorCallExpr(E); 3524 3525 Visit(Callee); 3526 for (auto Arg : E->arguments()) 3527 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3528 } 3529 3530 void VisitBinaryOperator(BinaryOperator *E) { 3531 // If a field assignment is detected, remove the field from the 3532 // uninitiailized field set. 3533 if (E->getOpcode() == BO_Assign) 3534 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3535 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3536 if (!FD->getType()->isReferenceType()) 3537 DeclsToRemove.push_back(FD); 3538 3539 if (E->isCompoundAssignmentOp()) { 3540 HandleValue(E->getLHS(), false /*AddressOf*/); 3541 Visit(E->getRHS()); 3542 return; 3543 } 3544 3545 Inherited::VisitBinaryOperator(E); 3546 } 3547 3548 void VisitUnaryOperator(UnaryOperator *E) { 3549 if (E->isIncrementDecrementOp()) { 3550 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3551 return; 3552 } 3553 if (E->getOpcode() == UO_AddrOf) { 3554 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3555 HandleValue(ME->getBase(), true /*AddressOf*/); 3556 return; 3557 } 3558 } 3559 3560 Inherited::VisitUnaryOperator(E); 3561 } 3562 }; 3563 3564 // Diagnose value-uses of fields to initialize themselves, e.g. 3565 // foo(foo) 3566 // where foo is not also a parameter to the constructor. 3567 // Also diagnose across field uninitialized use such as 3568 // x(y), y(x) 3569 // TODO: implement -Wuninitialized and fold this into that framework. 3570 static void DiagnoseUninitializedFields( 3571 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3572 3573 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3574 Constructor->getLocation())) { 3575 return; 3576 } 3577 3578 if (Constructor->isInvalidDecl()) 3579 return; 3580 3581 const CXXRecordDecl *RD = Constructor->getParent(); 3582 3583 if (RD->getDescribedClassTemplate()) 3584 return; 3585 3586 // Holds fields that are uninitialized. 3587 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3588 3589 // At the beginning, all fields are uninitialized. 3590 for (auto *I : RD->decls()) { 3591 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3592 UninitializedFields.insert(FD); 3593 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3594 UninitializedFields.insert(IFD->getAnonField()); 3595 } 3596 } 3597 3598 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3599 for (auto I : RD->bases()) 3600 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3601 3602 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3603 return; 3604 3605 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3606 UninitializedFields, 3607 UninitializedBaseClasses); 3608 3609 for (const auto *FieldInit : Constructor->inits()) { 3610 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3611 break; 3612 3613 Expr *InitExpr = FieldInit->getInit(); 3614 if (!InitExpr) 3615 continue; 3616 3617 if (CXXDefaultInitExpr *Default = 3618 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3619 InitExpr = Default->getExpr(); 3620 if (!InitExpr) 3621 continue; 3622 // In class initializers will point to the constructor. 3623 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3624 FieldInit->getAnyMember(), 3625 FieldInit->getBaseClass()); 3626 } else { 3627 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3628 FieldInit->getAnyMember(), 3629 FieldInit->getBaseClass()); 3630 } 3631 } 3632 } 3633 } // namespace 3634 3635 /// Enter a new C++ default initializer scope. After calling this, the 3636 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3637 /// parsing or instantiating the initializer failed. 3638 void Sema::ActOnStartCXXInClassMemberInitializer() { 3639 // Create a synthetic function scope to represent the call to the constructor 3640 // that notionally surrounds a use of this initializer. 3641 PushFunctionScope(); 3642 } 3643 3644 /// This is invoked after parsing an in-class initializer for a 3645 /// non-static C++ class member, and after instantiating an in-class initializer 3646 /// in a class template. Such actions are deferred until the class is complete. 3647 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3648 SourceLocation InitLoc, 3649 Expr *InitExpr) { 3650 // Pop the notional constructor scope we created earlier. 3651 PopFunctionScopeInfo(nullptr, D); 3652 3653 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3654 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3655 "must set init style when field is created"); 3656 3657 if (!InitExpr) { 3658 D->setInvalidDecl(); 3659 if (FD) 3660 FD->removeInClassInitializer(); 3661 return; 3662 } 3663 3664 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3665 FD->setInvalidDecl(); 3666 FD->removeInClassInitializer(); 3667 return; 3668 } 3669 3670 ExprResult Init = InitExpr; 3671 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3672 InitializedEntity Entity = 3673 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3674 InitializationKind Kind = 3675 FD->getInClassInitStyle() == ICIS_ListInit 3676 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3677 InitExpr->getBeginLoc(), 3678 InitExpr->getEndLoc()) 3679 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3680 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3681 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3682 if (Init.isInvalid()) { 3683 FD->setInvalidDecl(); 3684 return; 3685 } 3686 } 3687 3688 // C++11 [class.base.init]p7: 3689 // The initialization of each base and member constitutes a 3690 // full-expression. 3691 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3692 if (Init.isInvalid()) { 3693 FD->setInvalidDecl(); 3694 return; 3695 } 3696 3697 InitExpr = Init.get(); 3698 3699 FD->setInClassInitializer(InitExpr); 3700 } 3701 3702 /// Find the direct and/or virtual base specifiers that 3703 /// correspond to the given base type, for use in base initialization 3704 /// within a constructor. 3705 static bool FindBaseInitializer(Sema &SemaRef, 3706 CXXRecordDecl *ClassDecl, 3707 QualType BaseType, 3708 const CXXBaseSpecifier *&DirectBaseSpec, 3709 const CXXBaseSpecifier *&VirtualBaseSpec) { 3710 // First, check for a direct base class. 3711 DirectBaseSpec = nullptr; 3712 for (const auto &Base : ClassDecl->bases()) { 3713 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3714 // We found a direct base of this type. That's what we're 3715 // initializing. 3716 DirectBaseSpec = &Base; 3717 break; 3718 } 3719 } 3720 3721 // Check for a virtual base class. 3722 // FIXME: We might be able to short-circuit this if we know in advance that 3723 // there are no virtual bases. 3724 VirtualBaseSpec = nullptr; 3725 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3726 // We haven't found a base yet; search the class hierarchy for a 3727 // virtual base class. 3728 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3729 /*DetectVirtual=*/false); 3730 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3731 SemaRef.Context.getTypeDeclType(ClassDecl), 3732 BaseType, Paths)) { 3733 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3734 Path != Paths.end(); ++Path) { 3735 if (Path->back().Base->isVirtual()) { 3736 VirtualBaseSpec = Path->back().Base; 3737 break; 3738 } 3739 } 3740 } 3741 } 3742 3743 return DirectBaseSpec || VirtualBaseSpec; 3744 } 3745 3746 /// Handle a C++ member initializer using braced-init-list syntax. 3747 MemInitResult 3748 Sema::ActOnMemInitializer(Decl *ConstructorD, 3749 Scope *S, 3750 CXXScopeSpec &SS, 3751 IdentifierInfo *MemberOrBase, 3752 ParsedType TemplateTypeTy, 3753 const DeclSpec &DS, 3754 SourceLocation IdLoc, 3755 Expr *InitList, 3756 SourceLocation EllipsisLoc) { 3757 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3758 DS, IdLoc, InitList, 3759 EllipsisLoc); 3760 } 3761 3762 /// Handle a C++ member initializer using parentheses syntax. 3763 MemInitResult 3764 Sema::ActOnMemInitializer(Decl *ConstructorD, 3765 Scope *S, 3766 CXXScopeSpec &SS, 3767 IdentifierInfo *MemberOrBase, 3768 ParsedType TemplateTypeTy, 3769 const DeclSpec &DS, 3770 SourceLocation IdLoc, 3771 SourceLocation LParenLoc, 3772 ArrayRef<Expr *> Args, 3773 SourceLocation RParenLoc, 3774 SourceLocation EllipsisLoc) { 3775 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 3776 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3777 DS, IdLoc, List, EllipsisLoc); 3778 } 3779 3780 namespace { 3781 3782 // Callback to only accept typo corrections that can be a valid C++ member 3783 // intializer: either a non-static field member or a base class. 3784 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3785 public: 3786 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3787 : ClassDecl(ClassDecl) {} 3788 3789 bool ValidateCandidate(const TypoCorrection &candidate) override { 3790 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3791 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3792 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3793 return isa<TypeDecl>(ND); 3794 } 3795 return false; 3796 } 3797 3798 private: 3799 CXXRecordDecl *ClassDecl; 3800 }; 3801 3802 } 3803 3804 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 3805 CXXScopeSpec &SS, 3806 ParsedType TemplateTypeTy, 3807 IdentifierInfo *MemberOrBase) { 3808 if (SS.getScopeRep() || TemplateTypeTy) 3809 return nullptr; 3810 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3811 if (Result.empty()) 3812 return nullptr; 3813 ValueDecl *Member; 3814 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3815 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 3816 return Member; 3817 return nullptr; 3818 } 3819 3820 /// Handle a C++ member initializer. 3821 MemInitResult 3822 Sema::BuildMemInitializer(Decl *ConstructorD, 3823 Scope *S, 3824 CXXScopeSpec &SS, 3825 IdentifierInfo *MemberOrBase, 3826 ParsedType TemplateTypeTy, 3827 const DeclSpec &DS, 3828 SourceLocation IdLoc, 3829 Expr *Init, 3830 SourceLocation EllipsisLoc) { 3831 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3832 if (!Res.isUsable()) 3833 return true; 3834 Init = Res.get(); 3835 3836 if (!ConstructorD) 3837 return true; 3838 3839 AdjustDeclIfTemplate(ConstructorD); 3840 3841 CXXConstructorDecl *Constructor 3842 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3843 if (!Constructor) { 3844 // The user wrote a constructor initializer on a function that is 3845 // not a C++ constructor. Ignore the error for now, because we may 3846 // have more member initializers coming; we'll diagnose it just 3847 // once in ActOnMemInitializers. 3848 return true; 3849 } 3850 3851 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3852 3853 // C++ [class.base.init]p2: 3854 // Names in a mem-initializer-id are looked up in the scope of the 3855 // constructor's class and, if not found in that scope, are looked 3856 // up in the scope containing the constructor's definition. 3857 // [Note: if the constructor's class contains a member with the 3858 // same name as a direct or virtual base class of the class, a 3859 // mem-initializer-id naming the member or base class and composed 3860 // of a single identifier refers to the class member. A 3861 // mem-initializer-id for the hidden base class may be specified 3862 // using a qualified name. ] 3863 3864 // Look for a member, first. 3865 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 3866 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 3867 if (EllipsisLoc.isValid()) 3868 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3869 << MemberOrBase 3870 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3871 3872 return BuildMemberInitializer(Member, Init, IdLoc); 3873 } 3874 // It didn't name a member, so see if it names a class. 3875 QualType BaseType; 3876 TypeSourceInfo *TInfo = nullptr; 3877 3878 if (TemplateTypeTy) { 3879 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3880 } else if (DS.getTypeSpecType() == TST_decltype) { 3881 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3882 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3883 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3884 return true; 3885 } else { 3886 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3887 LookupParsedName(R, S, &SS); 3888 3889 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3890 if (!TyD) { 3891 if (R.isAmbiguous()) return true; 3892 3893 // We don't want access-control diagnostics here. 3894 R.suppressDiagnostics(); 3895 3896 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3897 bool NotUnknownSpecialization = false; 3898 DeclContext *DC = computeDeclContext(SS, false); 3899 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3900 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3901 3902 if (!NotUnknownSpecialization) { 3903 // When the scope specifier can refer to a member of an unknown 3904 // specialization, we take it as a type name. 3905 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3906 SS.getWithLocInContext(Context), 3907 *MemberOrBase, IdLoc); 3908 if (BaseType.isNull()) 3909 return true; 3910 3911 TInfo = Context.CreateTypeSourceInfo(BaseType); 3912 DependentNameTypeLoc TL = 3913 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3914 if (!TL.isNull()) { 3915 TL.setNameLoc(IdLoc); 3916 TL.setElaboratedKeywordLoc(SourceLocation()); 3917 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3918 } 3919 3920 R.clear(); 3921 R.setLookupName(MemberOrBase); 3922 } 3923 } 3924 3925 // If no results were found, try to correct typos. 3926 TypoCorrection Corr; 3927 if (R.empty() && BaseType.isNull() && 3928 (Corr = CorrectTypo( 3929 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3930 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3931 CTK_ErrorRecovery, ClassDecl))) { 3932 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3933 // We have found a non-static data member with a similar 3934 // name to what was typed; complain and initialize that 3935 // member. 3936 diagnoseTypo(Corr, 3937 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3938 << MemberOrBase << true); 3939 return BuildMemberInitializer(Member, Init, IdLoc); 3940 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3941 const CXXBaseSpecifier *DirectBaseSpec; 3942 const CXXBaseSpecifier *VirtualBaseSpec; 3943 if (FindBaseInitializer(*this, ClassDecl, 3944 Context.getTypeDeclType(Type), 3945 DirectBaseSpec, VirtualBaseSpec)) { 3946 // We have found a direct or virtual base class with a 3947 // similar name to what was typed; complain and initialize 3948 // that base class. 3949 diagnoseTypo(Corr, 3950 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3951 << MemberOrBase << false, 3952 PDiag() /*Suppress note, we provide our own.*/); 3953 3954 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3955 : VirtualBaseSpec; 3956 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 3957 << BaseSpec->getType() << BaseSpec->getSourceRange(); 3958 3959 TyD = Type; 3960 } 3961 } 3962 } 3963 3964 if (!TyD && BaseType.isNull()) { 3965 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3966 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3967 return true; 3968 } 3969 } 3970 3971 if (BaseType.isNull()) { 3972 BaseType = Context.getTypeDeclType(TyD); 3973 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3974 if (SS.isSet()) { 3975 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3976 BaseType); 3977 TInfo = Context.CreateTypeSourceInfo(BaseType); 3978 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3979 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3980 TL.setElaboratedKeywordLoc(SourceLocation()); 3981 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3982 } 3983 } 3984 } 3985 3986 if (!TInfo) 3987 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3988 3989 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3990 } 3991 3992 MemInitResult 3993 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3994 SourceLocation IdLoc) { 3995 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3996 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3997 assert((DirectMember || IndirectMember) && 3998 "Member must be a FieldDecl or IndirectFieldDecl"); 3999 4000 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4001 return true; 4002 4003 if (Member->isInvalidDecl()) 4004 return true; 4005 4006 MultiExprArg Args; 4007 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4008 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4009 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4010 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4011 } else { 4012 // Template instantiation doesn't reconstruct ParenListExprs for us. 4013 Args = Init; 4014 } 4015 4016 SourceRange InitRange = Init->getSourceRange(); 4017 4018 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4019 // Can't check initialization for a member of dependent type or when 4020 // any of the arguments are type-dependent expressions. 4021 DiscardCleanupsInEvaluationContext(); 4022 } else { 4023 bool InitList = false; 4024 if (isa<InitListExpr>(Init)) { 4025 InitList = true; 4026 Args = Init; 4027 } 4028 4029 // Initialize the member. 4030 InitializedEntity MemberEntity = 4031 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4032 : InitializedEntity::InitializeMember(IndirectMember, 4033 nullptr); 4034 InitializationKind Kind = 4035 InitList ? InitializationKind::CreateDirectList( 4036 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4037 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4038 InitRange.getEnd()); 4039 4040 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4041 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4042 nullptr); 4043 if (MemberInit.isInvalid()) 4044 return true; 4045 4046 // C++11 [class.base.init]p7: 4047 // The initialization of each base and member constitutes a 4048 // full-expression. 4049 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4050 /*DiscardedValue*/ false); 4051 if (MemberInit.isInvalid()) 4052 return true; 4053 4054 Init = MemberInit.get(); 4055 } 4056 4057 if (DirectMember) { 4058 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4059 InitRange.getBegin(), Init, 4060 InitRange.getEnd()); 4061 } else { 4062 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4063 InitRange.getBegin(), Init, 4064 InitRange.getEnd()); 4065 } 4066 } 4067 4068 MemInitResult 4069 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4070 CXXRecordDecl *ClassDecl) { 4071 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4072 if (!LangOpts.CPlusPlus11) 4073 return Diag(NameLoc, diag::err_delegating_ctor) 4074 << TInfo->getTypeLoc().getLocalSourceRange(); 4075 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4076 4077 bool InitList = true; 4078 MultiExprArg Args = Init; 4079 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4080 InitList = false; 4081 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4082 } 4083 4084 SourceRange InitRange = Init->getSourceRange(); 4085 // Initialize the object. 4086 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4087 QualType(ClassDecl->getTypeForDecl(), 0)); 4088 InitializationKind Kind = 4089 InitList ? InitializationKind::CreateDirectList( 4090 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4091 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4092 InitRange.getEnd()); 4093 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4094 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4095 Args, nullptr); 4096 if (DelegationInit.isInvalid()) 4097 return true; 4098 4099 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4100 "Delegating constructor with no target?"); 4101 4102 // C++11 [class.base.init]p7: 4103 // The initialization of each base and member constitutes a 4104 // full-expression. 4105 DelegationInit = ActOnFinishFullExpr( 4106 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4107 if (DelegationInit.isInvalid()) 4108 return true; 4109 4110 // If we are in a dependent context, template instantiation will 4111 // perform this type-checking again. Just save the arguments that we 4112 // received in a ParenListExpr. 4113 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4114 // of the information that we have about the base 4115 // initializer. However, deconstructing the ASTs is a dicey process, 4116 // and this approach is far more likely to get the corner cases right. 4117 if (CurContext->isDependentContext()) 4118 DelegationInit = Init; 4119 4120 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4121 DelegationInit.getAs<Expr>(), 4122 InitRange.getEnd()); 4123 } 4124 4125 MemInitResult 4126 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4127 Expr *Init, CXXRecordDecl *ClassDecl, 4128 SourceLocation EllipsisLoc) { 4129 SourceLocation BaseLoc 4130 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4131 4132 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4133 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4134 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4135 4136 // C++ [class.base.init]p2: 4137 // [...] Unless the mem-initializer-id names a nonstatic data 4138 // member of the constructor's class or a direct or virtual base 4139 // of that class, the mem-initializer is ill-formed. A 4140 // mem-initializer-list can initialize a base class using any 4141 // name that denotes that base class type. 4142 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4143 4144 SourceRange InitRange = Init->getSourceRange(); 4145 if (EllipsisLoc.isValid()) { 4146 // This is a pack expansion. 4147 if (!BaseType->containsUnexpandedParameterPack()) { 4148 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4149 << SourceRange(BaseLoc, InitRange.getEnd()); 4150 4151 EllipsisLoc = SourceLocation(); 4152 } 4153 } else { 4154 // Check for any unexpanded parameter packs. 4155 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4156 return true; 4157 4158 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4159 return true; 4160 } 4161 4162 // Check for direct and virtual base classes. 4163 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4164 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4165 if (!Dependent) { 4166 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4167 BaseType)) 4168 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4169 4170 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4171 VirtualBaseSpec); 4172 4173 // C++ [base.class.init]p2: 4174 // Unless the mem-initializer-id names a nonstatic data member of the 4175 // constructor's class or a direct or virtual base of that class, the 4176 // mem-initializer is ill-formed. 4177 if (!DirectBaseSpec && !VirtualBaseSpec) { 4178 // If the class has any dependent bases, then it's possible that 4179 // one of those types will resolve to the same type as 4180 // BaseType. Therefore, just treat this as a dependent base 4181 // class initialization. FIXME: Should we try to check the 4182 // initialization anyway? It seems odd. 4183 if (ClassDecl->hasAnyDependentBases()) 4184 Dependent = true; 4185 else 4186 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4187 << BaseType << Context.getTypeDeclType(ClassDecl) 4188 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4189 } 4190 } 4191 4192 if (Dependent) { 4193 DiscardCleanupsInEvaluationContext(); 4194 4195 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4196 /*IsVirtual=*/false, 4197 InitRange.getBegin(), Init, 4198 InitRange.getEnd(), EllipsisLoc); 4199 } 4200 4201 // C++ [base.class.init]p2: 4202 // If a mem-initializer-id is ambiguous because it designates both 4203 // a direct non-virtual base class and an inherited virtual base 4204 // class, the mem-initializer is ill-formed. 4205 if (DirectBaseSpec && VirtualBaseSpec) 4206 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4207 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4208 4209 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4210 if (!BaseSpec) 4211 BaseSpec = VirtualBaseSpec; 4212 4213 // Initialize the base. 4214 bool InitList = true; 4215 MultiExprArg Args = Init; 4216 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4217 InitList = false; 4218 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4219 } 4220 4221 InitializedEntity BaseEntity = 4222 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4223 InitializationKind Kind = 4224 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4225 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4226 InitRange.getEnd()); 4227 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4228 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4229 if (BaseInit.isInvalid()) 4230 return true; 4231 4232 // C++11 [class.base.init]p7: 4233 // The initialization of each base and member constitutes a 4234 // full-expression. 4235 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4236 /*DiscardedValue*/ false); 4237 if (BaseInit.isInvalid()) 4238 return true; 4239 4240 // If we are in a dependent context, template instantiation will 4241 // perform this type-checking again. Just save the arguments that we 4242 // received in a ParenListExpr. 4243 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4244 // of the information that we have about the base 4245 // initializer. However, deconstructing the ASTs is a dicey process, 4246 // and this approach is far more likely to get the corner cases right. 4247 if (CurContext->isDependentContext()) 4248 BaseInit = Init; 4249 4250 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4251 BaseSpec->isVirtual(), 4252 InitRange.getBegin(), 4253 BaseInit.getAs<Expr>(), 4254 InitRange.getEnd(), EllipsisLoc); 4255 } 4256 4257 // Create a static_cast\<T&&>(expr). 4258 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4259 if (T.isNull()) T = E->getType(); 4260 QualType TargetType = SemaRef.BuildReferenceType( 4261 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4262 SourceLocation ExprLoc = E->getBeginLoc(); 4263 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4264 TargetType, ExprLoc); 4265 4266 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4267 SourceRange(ExprLoc, ExprLoc), 4268 E->getSourceRange()).get(); 4269 } 4270 4271 /// ImplicitInitializerKind - How an implicit base or member initializer should 4272 /// initialize its base or member. 4273 enum ImplicitInitializerKind { 4274 IIK_Default, 4275 IIK_Copy, 4276 IIK_Move, 4277 IIK_Inherit 4278 }; 4279 4280 static bool 4281 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4282 ImplicitInitializerKind ImplicitInitKind, 4283 CXXBaseSpecifier *BaseSpec, 4284 bool IsInheritedVirtualBase, 4285 CXXCtorInitializer *&CXXBaseInit) { 4286 InitializedEntity InitEntity 4287 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4288 IsInheritedVirtualBase); 4289 4290 ExprResult BaseInit; 4291 4292 switch (ImplicitInitKind) { 4293 case IIK_Inherit: 4294 case IIK_Default: { 4295 InitializationKind InitKind 4296 = InitializationKind::CreateDefault(Constructor->getLocation()); 4297 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4298 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4299 break; 4300 } 4301 4302 case IIK_Move: 4303 case IIK_Copy: { 4304 bool Moving = ImplicitInitKind == IIK_Move; 4305 ParmVarDecl *Param = Constructor->getParamDecl(0); 4306 QualType ParamType = Param->getType().getNonReferenceType(); 4307 4308 Expr *CopyCtorArg = 4309 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4310 SourceLocation(), Param, false, 4311 Constructor->getLocation(), ParamType, 4312 VK_LValue, nullptr); 4313 4314 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4315 4316 // Cast to the base class to avoid ambiguities. 4317 QualType ArgTy = 4318 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4319 ParamType.getQualifiers()); 4320 4321 if (Moving) { 4322 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4323 } 4324 4325 CXXCastPath BasePath; 4326 BasePath.push_back(BaseSpec); 4327 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4328 CK_UncheckedDerivedToBase, 4329 Moving ? VK_XValue : VK_LValue, 4330 &BasePath).get(); 4331 4332 InitializationKind InitKind 4333 = InitializationKind::CreateDirect(Constructor->getLocation(), 4334 SourceLocation(), SourceLocation()); 4335 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4336 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4337 break; 4338 } 4339 } 4340 4341 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4342 if (BaseInit.isInvalid()) 4343 return true; 4344 4345 CXXBaseInit = 4346 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4347 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4348 SourceLocation()), 4349 BaseSpec->isVirtual(), 4350 SourceLocation(), 4351 BaseInit.getAs<Expr>(), 4352 SourceLocation(), 4353 SourceLocation()); 4354 4355 return false; 4356 } 4357 4358 static bool RefersToRValueRef(Expr *MemRef) { 4359 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4360 return Referenced->getType()->isRValueReferenceType(); 4361 } 4362 4363 static bool 4364 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4365 ImplicitInitializerKind ImplicitInitKind, 4366 FieldDecl *Field, IndirectFieldDecl *Indirect, 4367 CXXCtorInitializer *&CXXMemberInit) { 4368 if (Field->isInvalidDecl()) 4369 return true; 4370 4371 SourceLocation Loc = Constructor->getLocation(); 4372 4373 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4374 bool Moving = ImplicitInitKind == IIK_Move; 4375 ParmVarDecl *Param = Constructor->getParamDecl(0); 4376 QualType ParamType = Param->getType().getNonReferenceType(); 4377 4378 // Suppress copying zero-width bitfields. 4379 if (Field->isZeroLengthBitField(SemaRef.Context)) 4380 return false; 4381 4382 Expr *MemberExprBase = 4383 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4384 SourceLocation(), Param, false, 4385 Loc, ParamType, VK_LValue, nullptr); 4386 4387 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4388 4389 if (Moving) { 4390 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4391 } 4392 4393 // Build a reference to this field within the parameter. 4394 CXXScopeSpec SS; 4395 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4396 Sema::LookupMemberName); 4397 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4398 : cast<ValueDecl>(Field), AS_public); 4399 MemberLookup.resolveKind(); 4400 ExprResult CtorArg 4401 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4402 ParamType, Loc, 4403 /*IsArrow=*/false, 4404 SS, 4405 /*TemplateKWLoc=*/SourceLocation(), 4406 /*FirstQualifierInScope=*/nullptr, 4407 MemberLookup, 4408 /*TemplateArgs=*/nullptr, 4409 /*S*/nullptr); 4410 if (CtorArg.isInvalid()) 4411 return true; 4412 4413 // C++11 [class.copy]p15: 4414 // - if a member m has rvalue reference type T&&, it is direct-initialized 4415 // with static_cast<T&&>(x.m); 4416 if (RefersToRValueRef(CtorArg.get())) { 4417 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4418 } 4419 4420 InitializedEntity Entity = 4421 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4422 /*Implicit*/ true) 4423 : InitializedEntity::InitializeMember(Field, nullptr, 4424 /*Implicit*/ true); 4425 4426 // Direct-initialize to use the copy constructor. 4427 InitializationKind InitKind = 4428 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4429 4430 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4431 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4432 ExprResult MemberInit = 4433 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4434 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4435 if (MemberInit.isInvalid()) 4436 return true; 4437 4438 if (Indirect) 4439 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4440 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4441 else 4442 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4443 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4444 return false; 4445 } 4446 4447 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4448 "Unhandled implicit init kind!"); 4449 4450 QualType FieldBaseElementType = 4451 SemaRef.Context.getBaseElementType(Field->getType()); 4452 4453 if (FieldBaseElementType->isRecordType()) { 4454 InitializedEntity InitEntity = 4455 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4456 /*Implicit*/ true) 4457 : InitializedEntity::InitializeMember(Field, nullptr, 4458 /*Implicit*/ true); 4459 InitializationKind InitKind = 4460 InitializationKind::CreateDefault(Loc); 4461 4462 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4463 ExprResult MemberInit = 4464 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4465 4466 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4467 if (MemberInit.isInvalid()) 4468 return true; 4469 4470 if (Indirect) 4471 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4472 Indirect, Loc, 4473 Loc, 4474 MemberInit.get(), 4475 Loc); 4476 else 4477 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4478 Field, Loc, Loc, 4479 MemberInit.get(), 4480 Loc); 4481 return false; 4482 } 4483 4484 if (!Field->getParent()->isUnion()) { 4485 if (FieldBaseElementType->isReferenceType()) { 4486 SemaRef.Diag(Constructor->getLocation(), 4487 diag::err_uninitialized_member_in_ctor) 4488 << (int)Constructor->isImplicit() 4489 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4490 << 0 << Field->getDeclName(); 4491 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4492 return true; 4493 } 4494 4495 if (FieldBaseElementType.isConstQualified()) { 4496 SemaRef.Diag(Constructor->getLocation(), 4497 diag::err_uninitialized_member_in_ctor) 4498 << (int)Constructor->isImplicit() 4499 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4500 << 1 << Field->getDeclName(); 4501 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4502 return true; 4503 } 4504 } 4505 4506 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4507 // ARC and Weak: 4508 // Default-initialize Objective-C pointers to NULL. 4509 CXXMemberInit 4510 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4511 Loc, Loc, 4512 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4513 Loc); 4514 return false; 4515 } 4516 4517 // Nothing to initialize. 4518 CXXMemberInit = nullptr; 4519 return false; 4520 } 4521 4522 namespace { 4523 struct BaseAndFieldInfo { 4524 Sema &S; 4525 CXXConstructorDecl *Ctor; 4526 bool AnyErrorsInInits; 4527 ImplicitInitializerKind IIK; 4528 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4529 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4530 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4531 4532 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4533 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4534 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4535 if (Ctor->getInheritedConstructor()) 4536 IIK = IIK_Inherit; 4537 else if (Generated && Ctor->isCopyConstructor()) 4538 IIK = IIK_Copy; 4539 else if (Generated && Ctor->isMoveConstructor()) 4540 IIK = IIK_Move; 4541 else 4542 IIK = IIK_Default; 4543 } 4544 4545 bool isImplicitCopyOrMove() const { 4546 switch (IIK) { 4547 case IIK_Copy: 4548 case IIK_Move: 4549 return true; 4550 4551 case IIK_Default: 4552 case IIK_Inherit: 4553 return false; 4554 } 4555 4556 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4557 } 4558 4559 bool addFieldInitializer(CXXCtorInitializer *Init) { 4560 AllToInit.push_back(Init); 4561 4562 // Check whether this initializer makes the field "used". 4563 if (Init->getInit()->HasSideEffects(S.Context)) 4564 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4565 4566 return false; 4567 } 4568 4569 bool isInactiveUnionMember(FieldDecl *Field) { 4570 RecordDecl *Record = Field->getParent(); 4571 if (!Record->isUnion()) 4572 return false; 4573 4574 if (FieldDecl *Active = 4575 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4576 return Active != Field->getCanonicalDecl(); 4577 4578 // In an implicit copy or move constructor, ignore any in-class initializer. 4579 if (isImplicitCopyOrMove()) 4580 return true; 4581 4582 // If there's no explicit initialization, the field is active only if it 4583 // has an in-class initializer... 4584 if (Field->hasInClassInitializer()) 4585 return false; 4586 // ... or it's an anonymous struct or union whose class has an in-class 4587 // initializer. 4588 if (!Field->isAnonymousStructOrUnion()) 4589 return true; 4590 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4591 return !FieldRD->hasInClassInitializer(); 4592 } 4593 4594 /// Determine whether the given field is, or is within, a union member 4595 /// that is inactive (because there was an initializer given for a different 4596 /// member of the union, or because the union was not initialized at all). 4597 bool isWithinInactiveUnionMember(FieldDecl *Field, 4598 IndirectFieldDecl *Indirect) { 4599 if (!Indirect) 4600 return isInactiveUnionMember(Field); 4601 4602 for (auto *C : Indirect->chain()) { 4603 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4604 if (Field && isInactiveUnionMember(Field)) 4605 return true; 4606 } 4607 return false; 4608 } 4609 }; 4610 } 4611 4612 /// Determine whether the given type is an incomplete or zero-lenfgth 4613 /// array type. 4614 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4615 if (T->isIncompleteArrayType()) 4616 return true; 4617 4618 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4619 if (!ArrayT->getSize()) 4620 return true; 4621 4622 T = ArrayT->getElementType(); 4623 } 4624 4625 return false; 4626 } 4627 4628 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4629 FieldDecl *Field, 4630 IndirectFieldDecl *Indirect = nullptr) { 4631 if (Field->isInvalidDecl()) 4632 return false; 4633 4634 // Overwhelmingly common case: we have a direct initializer for this field. 4635 if (CXXCtorInitializer *Init = 4636 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4637 return Info.addFieldInitializer(Init); 4638 4639 // C++11 [class.base.init]p8: 4640 // if the entity is a non-static data member that has a 4641 // brace-or-equal-initializer and either 4642 // -- the constructor's class is a union and no other variant member of that 4643 // union is designated by a mem-initializer-id or 4644 // -- the constructor's class is not a union, and, if the entity is a member 4645 // of an anonymous union, no other member of that union is designated by 4646 // a mem-initializer-id, 4647 // the entity is initialized as specified in [dcl.init]. 4648 // 4649 // We also apply the same rules to handle anonymous structs within anonymous 4650 // unions. 4651 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4652 return false; 4653 4654 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4655 ExprResult DIE = 4656 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4657 if (DIE.isInvalid()) 4658 return true; 4659 4660 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4661 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4662 4663 CXXCtorInitializer *Init; 4664 if (Indirect) 4665 Init = new (SemaRef.Context) 4666 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4667 SourceLocation(), DIE.get(), SourceLocation()); 4668 else 4669 Init = new (SemaRef.Context) 4670 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4671 SourceLocation(), DIE.get(), SourceLocation()); 4672 return Info.addFieldInitializer(Init); 4673 } 4674 4675 // Don't initialize incomplete or zero-length arrays. 4676 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4677 return false; 4678 4679 // Don't try to build an implicit initializer if there were semantic 4680 // errors in any of the initializers (and therefore we might be 4681 // missing some that the user actually wrote). 4682 if (Info.AnyErrorsInInits) 4683 return false; 4684 4685 CXXCtorInitializer *Init = nullptr; 4686 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4687 Indirect, Init)) 4688 return true; 4689 4690 if (!Init) 4691 return false; 4692 4693 return Info.addFieldInitializer(Init); 4694 } 4695 4696 bool 4697 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4698 CXXCtorInitializer *Initializer) { 4699 assert(Initializer->isDelegatingInitializer()); 4700 Constructor->setNumCtorInitializers(1); 4701 CXXCtorInitializer **initializer = 4702 new (Context) CXXCtorInitializer*[1]; 4703 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4704 Constructor->setCtorInitializers(initializer); 4705 4706 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4707 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4708 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4709 } 4710 4711 DelegatingCtorDecls.push_back(Constructor); 4712 4713 DiagnoseUninitializedFields(*this, Constructor); 4714 4715 return false; 4716 } 4717 4718 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4719 ArrayRef<CXXCtorInitializer *> Initializers) { 4720 if (Constructor->isDependentContext()) { 4721 // Just store the initializers as written, they will be checked during 4722 // instantiation. 4723 if (!Initializers.empty()) { 4724 Constructor->setNumCtorInitializers(Initializers.size()); 4725 CXXCtorInitializer **baseOrMemberInitializers = 4726 new (Context) CXXCtorInitializer*[Initializers.size()]; 4727 memcpy(baseOrMemberInitializers, Initializers.data(), 4728 Initializers.size() * sizeof(CXXCtorInitializer*)); 4729 Constructor->setCtorInitializers(baseOrMemberInitializers); 4730 } 4731 4732 // Let template instantiation know whether we had errors. 4733 if (AnyErrors) 4734 Constructor->setInvalidDecl(); 4735 4736 return false; 4737 } 4738 4739 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4740 4741 // We need to build the initializer AST according to order of construction 4742 // and not what user specified in the Initializers list. 4743 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4744 if (!ClassDecl) 4745 return true; 4746 4747 bool HadError = false; 4748 4749 for (unsigned i = 0; i < Initializers.size(); i++) { 4750 CXXCtorInitializer *Member = Initializers[i]; 4751 4752 if (Member->isBaseInitializer()) 4753 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4754 else { 4755 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4756 4757 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4758 for (auto *C : F->chain()) { 4759 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4760 if (FD && FD->getParent()->isUnion()) 4761 Info.ActiveUnionMember.insert(std::make_pair( 4762 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4763 } 4764 } else if (FieldDecl *FD = Member->getMember()) { 4765 if (FD->getParent()->isUnion()) 4766 Info.ActiveUnionMember.insert(std::make_pair( 4767 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4768 } 4769 } 4770 } 4771 4772 // Keep track of the direct virtual bases. 4773 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4774 for (auto &I : ClassDecl->bases()) { 4775 if (I.isVirtual()) 4776 DirectVBases.insert(&I); 4777 } 4778 4779 // Push virtual bases before others. 4780 for (auto &VBase : ClassDecl->vbases()) { 4781 if (CXXCtorInitializer *Value 4782 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4783 // [class.base.init]p7, per DR257: 4784 // A mem-initializer where the mem-initializer-id names a virtual base 4785 // class is ignored during execution of a constructor of any class that 4786 // is not the most derived class. 4787 if (ClassDecl->isAbstract()) { 4788 // FIXME: Provide a fixit to remove the base specifier. This requires 4789 // tracking the location of the associated comma for a base specifier. 4790 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4791 << VBase.getType() << ClassDecl; 4792 DiagnoseAbstractType(ClassDecl); 4793 } 4794 4795 Info.AllToInit.push_back(Value); 4796 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4797 // [class.base.init]p8, per DR257: 4798 // If a given [...] base class is not named by a mem-initializer-id 4799 // [...] and the entity is not a virtual base class of an abstract 4800 // class, then [...] the entity is default-initialized. 4801 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4802 CXXCtorInitializer *CXXBaseInit; 4803 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4804 &VBase, IsInheritedVirtualBase, 4805 CXXBaseInit)) { 4806 HadError = true; 4807 continue; 4808 } 4809 4810 Info.AllToInit.push_back(CXXBaseInit); 4811 } 4812 } 4813 4814 // Non-virtual bases. 4815 for (auto &Base : ClassDecl->bases()) { 4816 // Virtuals are in the virtual base list and already constructed. 4817 if (Base.isVirtual()) 4818 continue; 4819 4820 if (CXXCtorInitializer *Value 4821 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4822 Info.AllToInit.push_back(Value); 4823 } else if (!AnyErrors) { 4824 CXXCtorInitializer *CXXBaseInit; 4825 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4826 &Base, /*IsInheritedVirtualBase=*/false, 4827 CXXBaseInit)) { 4828 HadError = true; 4829 continue; 4830 } 4831 4832 Info.AllToInit.push_back(CXXBaseInit); 4833 } 4834 } 4835 4836 // Fields. 4837 for (auto *Mem : ClassDecl->decls()) { 4838 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4839 // C++ [class.bit]p2: 4840 // A declaration for a bit-field that omits the identifier declares an 4841 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4842 // initialized. 4843 if (F->isUnnamedBitfield()) 4844 continue; 4845 4846 // If we're not generating the implicit copy/move constructor, then we'll 4847 // handle anonymous struct/union fields based on their individual 4848 // indirect fields. 4849 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4850 continue; 4851 4852 if (CollectFieldInitializer(*this, Info, F)) 4853 HadError = true; 4854 continue; 4855 } 4856 4857 // Beyond this point, we only consider default initialization. 4858 if (Info.isImplicitCopyOrMove()) 4859 continue; 4860 4861 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4862 if (F->getType()->isIncompleteArrayType()) { 4863 assert(ClassDecl->hasFlexibleArrayMember() && 4864 "Incomplete array type is not valid"); 4865 continue; 4866 } 4867 4868 // Initialize each field of an anonymous struct individually. 4869 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4870 HadError = true; 4871 4872 continue; 4873 } 4874 } 4875 4876 unsigned NumInitializers = Info.AllToInit.size(); 4877 if (NumInitializers > 0) { 4878 Constructor->setNumCtorInitializers(NumInitializers); 4879 CXXCtorInitializer **baseOrMemberInitializers = 4880 new (Context) CXXCtorInitializer*[NumInitializers]; 4881 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4882 NumInitializers * sizeof(CXXCtorInitializer*)); 4883 Constructor->setCtorInitializers(baseOrMemberInitializers); 4884 4885 // Constructors implicitly reference the base and member 4886 // destructors. 4887 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4888 Constructor->getParent()); 4889 } 4890 4891 return HadError; 4892 } 4893 4894 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4895 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4896 const RecordDecl *RD = RT->getDecl(); 4897 if (RD->isAnonymousStructOrUnion()) { 4898 for (auto *Field : RD->fields()) 4899 PopulateKeysForFields(Field, IdealInits); 4900 return; 4901 } 4902 } 4903 IdealInits.push_back(Field->getCanonicalDecl()); 4904 } 4905 4906 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4907 return Context.getCanonicalType(BaseType).getTypePtr(); 4908 } 4909 4910 static const void *GetKeyForMember(ASTContext &Context, 4911 CXXCtorInitializer *Member) { 4912 if (!Member->isAnyMemberInitializer()) 4913 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4914 4915 return Member->getAnyMember()->getCanonicalDecl(); 4916 } 4917 4918 static void DiagnoseBaseOrMemInitializerOrder( 4919 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4920 ArrayRef<CXXCtorInitializer *> Inits) { 4921 if (Constructor->getDeclContext()->isDependentContext()) 4922 return; 4923 4924 // Don't check initializers order unless the warning is enabled at the 4925 // location of at least one initializer. 4926 bool ShouldCheckOrder = false; 4927 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4928 CXXCtorInitializer *Init = Inits[InitIndex]; 4929 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4930 Init->getSourceLocation())) { 4931 ShouldCheckOrder = true; 4932 break; 4933 } 4934 } 4935 if (!ShouldCheckOrder) 4936 return; 4937 4938 // Build the list of bases and members in the order that they'll 4939 // actually be initialized. The explicit initializers should be in 4940 // this same order but may be missing things. 4941 SmallVector<const void*, 32> IdealInitKeys; 4942 4943 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4944 4945 // 1. Virtual bases. 4946 for (const auto &VBase : ClassDecl->vbases()) 4947 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4948 4949 // 2. Non-virtual bases. 4950 for (const auto &Base : ClassDecl->bases()) { 4951 if (Base.isVirtual()) 4952 continue; 4953 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4954 } 4955 4956 // 3. Direct fields. 4957 for (auto *Field : ClassDecl->fields()) { 4958 if (Field->isUnnamedBitfield()) 4959 continue; 4960 4961 PopulateKeysForFields(Field, IdealInitKeys); 4962 } 4963 4964 unsigned NumIdealInits = IdealInitKeys.size(); 4965 unsigned IdealIndex = 0; 4966 4967 CXXCtorInitializer *PrevInit = nullptr; 4968 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4969 CXXCtorInitializer *Init = Inits[InitIndex]; 4970 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4971 4972 // Scan forward to try to find this initializer in the idealized 4973 // initializers list. 4974 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4975 if (InitKey == IdealInitKeys[IdealIndex]) 4976 break; 4977 4978 // If we didn't find this initializer, it must be because we 4979 // scanned past it on a previous iteration. That can only 4980 // happen if we're out of order; emit a warning. 4981 if (IdealIndex == NumIdealInits && PrevInit) { 4982 Sema::SemaDiagnosticBuilder D = 4983 SemaRef.Diag(PrevInit->getSourceLocation(), 4984 diag::warn_initializer_out_of_order); 4985 4986 if (PrevInit->isAnyMemberInitializer()) 4987 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4988 else 4989 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4990 4991 if (Init->isAnyMemberInitializer()) 4992 D << 0 << Init->getAnyMember()->getDeclName(); 4993 else 4994 D << 1 << Init->getTypeSourceInfo()->getType(); 4995 4996 // Move back to the initializer's location in the ideal list. 4997 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4998 if (InitKey == IdealInitKeys[IdealIndex]) 4999 break; 5000 5001 assert(IdealIndex < NumIdealInits && 5002 "initializer not found in initializer list"); 5003 } 5004 5005 PrevInit = Init; 5006 } 5007 } 5008 5009 namespace { 5010 bool CheckRedundantInit(Sema &S, 5011 CXXCtorInitializer *Init, 5012 CXXCtorInitializer *&PrevInit) { 5013 if (!PrevInit) { 5014 PrevInit = Init; 5015 return false; 5016 } 5017 5018 if (FieldDecl *Field = Init->getAnyMember()) 5019 S.Diag(Init->getSourceLocation(), 5020 diag::err_multiple_mem_initialization) 5021 << Field->getDeclName() 5022 << Init->getSourceRange(); 5023 else { 5024 const Type *BaseClass = Init->getBaseClass(); 5025 assert(BaseClass && "neither field nor base"); 5026 S.Diag(Init->getSourceLocation(), 5027 diag::err_multiple_base_initialization) 5028 << QualType(BaseClass, 0) 5029 << Init->getSourceRange(); 5030 } 5031 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5032 << 0 << PrevInit->getSourceRange(); 5033 5034 return true; 5035 } 5036 5037 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5038 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5039 5040 bool CheckRedundantUnionInit(Sema &S, 5041 CXXCtorInitializer *Init, 5042 RedundantUnionMap &Unions) { 5043 FieldDecl *Field = Init->getAnyMember(); 5044 RecordDecl *Parent = Field->getParent(); 5045 NamedDecl *Child = Field; 5046 5047 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5048 if (Parent->isUnion()) { 5049 UnionEntry &En = Unions[Parent]; 5050 if (En.first && En.first != Child) { 5051 S.Diag(Init->getSourceLocation(), 5052 diag::err_multiple_mem_union_initialization) 5053 << Field->getDeclName() 5054 << Init->getSourceRange(); 5055 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5056 << 0 << En.second->getSourceRange(); 5057 return true; 5058 } 5059 if (!En.first) { 5060 En.first = Child; 5061 En.second = Init; 5062 } 5063 if (!Parent->isAnonymousStructOrUnion()) 5064 return false; 5065 } 5066 5067 Child = Parent; 5068 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5069 } 5070 5071 return false; 5072 } 5073 } 5074 5075 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5076 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5077 SourceLocation ColonLoc, 5078 ArrayRef<CXXCtorInitializer*> MemInits, 5079 bool AnyErrors) { 5080 if (!ConstructorDecl) 5081 return; 5082 5083 AdjustDeclIfTemplate(ConstructorDecl); 5084 5085 CXXConstructorDecl *Constructor 5086 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5087 5088 if (!Constructor) { 5089 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5090 return; 5091 } 5092 5093 // Mapping for the duplicate initializers check. 5094 // For member initializers, this is keyed with a FieldDecl*. 5095 // For base initializers, this is keyed with a Type*. 5096 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5097 5098 // Mapping for the inconsistent anonymous-union initializers check. 5099 RedundantUnionMap MemberUnions; 5100 5101 bool HadError = false; 5102 for (unsigned i = 0; i < MemInits.size(); i++) { 5103 CXXCtorInitializer *Init = MemInits[i]; 5104 5105 // Set the source order index. 5106 Init->setSourceOrder(i); 5107 5108 if (Init->isAnyMemberInitializer()) { 5109 const void *Key = GetKeyForMember(Context, Init); 5110 if (CheckRedundantInit(*this, Init, Members[Key]) || 5111 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5112 HadError = true; 5113 } else if (Init->isBaseInitializer()) { 5114 const void *Key = GetKeyForMember(Context, Init); 5115 if (CheckRedundantInit(*this, Init, Members[Key])) 5116 HadError = true; 5117 } else { 5118 assert(Init->isDelegatingInitializer()); 5119 // This must be the only initializer 5120 if (MemInits.size() != 1) { 5121 Diag(Init->getSourceLocation(), 5122 diag::err_delegating_initializer_alone) 5123 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5124 // We will treat this as being the only initializer. 5125 } 5126 SetDelegatingInitializer(Constructor, MemInits[i]); 5127 // Return immediately as the initializer is set. 5128 return; 5129 } 5130 } 5131 5132 if (HadError) 5133 return; 5134 5135 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5136 5137 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5138 5139 DiagnoseUninitializedFields(*this, Constructor); 5140 } 5141 5142 void 5143 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5144 CXXRecordDecl *ClassDecl) { 5145 // Ignore dependent contexts. Also ignore unions, since their members never 5146 // have destructors implicitly called. 5147 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5148 return; 5149 5150 // FIXME: all the access-control diagnostics are positioned on the 5151 // field/base declaration. That's probably good; that said, the 5152 // user might reasonably want to know why the destructor is being 5153 // emitted, and we currently don't say. 5154 5155 // Non-static data members. 5156 for (auto *Field : ClassDecl->fields()) { 5157 if (Field->isInvalidDecl()) 5158 continue; 5159 5160 // Don't destroy incomplete or zero-length arrays. 5161 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5162 continue; 5163 5164 QualType FieldType = Context.getBaseElementType(Field->getType()); 5165 5166 const RecordType* RT = FieldType->getAs<RecordType>(); 5167 if (!RT) 5168 continue; 5169 5170 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5171 if (FieldClassDecl->isInvalidDecl()) 5172 continue; 5173 if (FieldClassDecl->hasIrrelevantDestructor()) 5174 continue; 5175 // The destructor for an implicit anonymous union member is never invoked. 5176 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5177 continue; 5178 5179 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5180 assert(Dtor && "No dtor found for FieldClassDecl!"); 5181 CheckDestructorAccess(Field->getLocation(), Dtor, 5182 PDiag(diag::err_access_dtor_field) 5183 << Field->getDeclName() 5184 << FieldType); 5185 5186 MarkFunctionReferenced(Location, Dtor); 5187 DiagnoseUseOfDecl(Dtor, Location); 5188 } 5189 5190 // We only potentially invoke the destructors of potentially constructed 5191 // subobjects. 5192 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5193 5194 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5195 5196 // Bases. 5197 for (const auto &Base : ClassDecl->bases()) { 5198 // Bases are always records in a well-formed non-dependent class. 5199 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5200 5201 // Remember direct virtual bases. 5202 if (Base.isVirtual()) { 5203 if (!VisitVirtualBases) 5204 continue; 5205 DirectVirtualBases.insert(RT); 5206 } 5207 5208 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5209 // If our base class is invalid, we probably can't get its dtor anyway. 5210 if (BaseClassDecl->isInvalidDecl()) 5211 continue; 5212 if (BaseClassDecl->hasIrrelevantDestructor()) 5213 continue; 5214 5215 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5216 assert(Dtor && "No dtor found for BaseClassDecl!"); 5217 5218 // FIXME: caret should be on the start of the class name 5219 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5220 PDiag(diag::err_access_dtor_base) 5221 << Base.getType() << Base.getSourceRange(), 5222 Context.getTypeDeclType(ClassDecl)); 5223 5224 MarkFunctionReferenced(Location, Dtor); 5225 DiagnoseUseOfDecl(Dtor, Location); 5226 } 5227 5228 if (!VisitVirtualBases) 5229 return; 5230 5231 // Virtual bases. 5232 for (const auto &VBase : ClassDecl->vbases()) { 5233 // Bases are always records in a well-formed non-dependent class. 5234 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5235 5236 // Ignore direct virtual bases. 5237 if (DirectVirtualBases.count(RT)) 5238 continue; 5239 5240 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5241 // If our base class is invalid, we probably can't get its dtor anyway. 5242 if (BaseClassDecl->isInvalidDecl()) 5243 continue; 5244 if (BaseClassDecl->hasIrrelevantDestructor()) 5245 continue; 5246 5247 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5248 assert(Dtor && "No dtor found for BaseClassDecl!"); 5249 if (CheckDestructorAccess( 5250 ClassDecl->getLocation(), Dtor, 5251 PDiag(diag::err_access_dtor_vbase) 5252 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5253 Context.getTypeDeclType(ClassDecl)) == 5254 AR_accessible) { 5255 CheckDerivedToBaseConversion( 5256 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5257 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5258 SourceRange(), DeclarationName(), nullptr); 5259 } 5260 5261 MarkFunctionReferenced(Location, Dtor); 5262 DiagnoseUseOfDecl(Dtor, Location); 5263 } 5264 } 5265 5266 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5267 if (!CDtorDecl) 5268 return; 5269 5270 if (CXXConstructorDecl *Constructor 5271 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5272 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5273 DiagnoseUninitializedFields(*this, Constructor); 5274 } 5275 } 5276 5277 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5278 if (!getLangOpts().CPlusPlus) 5279 return false; 5280 5281 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5282 if (!RD) 5283 return false; 5284 5285 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5286 // class template specialization here, but doing so breaks a lot of code. 5287 5288 // We can't answer whether something is abstract until it has a 5289 // definition. If it's currently being defined, we'll walk back 5290 // over all the declarations when we have a full definition. 5291 const CXXRecordDecl *Def = RD->getDefinition(); 5292 if (!Def || Def->isBeingDefined()) 5293 return false; 5294 5295 return RD->isAbstract(); 5296 } 5297 5298 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5299 TypeDiagnoser &Diagnoser) { 5300 if (!isAbstractType(Loc, T)) 5301 return false; 5302 5303 T = Context.getBaseElementType(T); 5304 Diagnoser.diagnose(*this, Loc, T); 5305 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5306 return true; 5307 } 5308 5309 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5310 // Check if we've already emitted the list of pure virtual functions 5311 // for this class. 5312 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5313 return; 5314 5315 // If the diagnostic is suppressed, don't emit the notes. We're only 5316 // going to emit them once, so try to attach them to a diagnostic we're 5317 // actually going to show. 5318 if (Diags.isLastDiagnosticIgnored()) 5319 return; 5320 5321 CXXFinalOverriderMap FinalOverriders; 5322 RD->getFinalOverriders(FinalOverriders); 5323 5324 // Keep a set of seen pure methods so we won't diagnose the same method 5325 // more than once. 5326 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5327 5328 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5329 MEnd = FinalOverriders.end(); 5330 M != MEnd; 5331 ++M) { 5332 for (OverridingMethods::iterator SO = M->second.begin(), 5333 SOEnd = M->second.end(); 5334 SO != SOEnd; ++SO) { 5335 // C++ [class.abstract]p4: 5336 // A class is abstract if it contains or inherits at least one 5337 // pure virtual function for which the final overrider is pure 5338 // virtual. 5339 5340 // 5341 if (SO->second.size() != 1) 5342 continue; 5343 5344 if (!SO->second.front().Method->isPure()) 5345 continue; 5346 5347 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5348 continue; 5349 5350 Diag(SO->second.front().Method->getLocation(), 5351 diag::note_pure_virtual_function) 5352 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5353 } 5354 } 5355 5356 if (!PureVirtualClassDiagSet) 5357 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5358 PureVirtualClassDiagSet->insert(RD); 5359 } 5360 5361 namespace { 5362 struct AbstractUsageInfo { 5363 Sema &S; 5364 CXXRecordDecl *Record; 5365 CanQualType AbstractType; 5366 bool Invalid; 5367 5368 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5369 : S(S), Record(Record), 5370 AbstractType(S.Context.getCanonicalType( 5371 S.Context.getTypeDeclType(Record))), 5372 Invalid(false) {} 5373 5374 void DiagnoseAbstractType() { 5375 if (Invalid) return; 5376 S.DiagnoseAbstractType(Record); 5377 Invalid = true; 5378 } 5379 5380 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5381 }; 5382 5383 struct CheckAbstractUsage { 5384 AbstractUsageInfo &Info; 5385 const NamedDecl *Ctx; 5386 5387 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5388 : Info(Info), Ctx(Ctx) {} 5389 5390 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5391 switch (TL.getTypeLocClass()) { 5392 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5393 #define TYPELOC(CLASS, PARENT) \ 5394 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5395 #include "clang/AST/TypeLocNodes.def" 5396 } 5397 } 5398 5399 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5400 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5401 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5402 if (!TL.getParam(I)) 5403 continue; 5404 5405 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5406 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5407 } 5408 } 5409 5410 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5411 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5412 } 5413 5414 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5415 // Visit the type parameters from a permissive context. 5416 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5417 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5418 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5419 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5420 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5421 // TODO: other template argument types? 5422 } 5423 } 5424 5425 // Visit pointee types from a permissive context. 5426 #define CheckPolymorphic(Type) \ 5427 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5428 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5429 } 5430 CheckPolymorphic(PointerTypeLoc) 5431 CheckPolymorphic(ReferenceTypeLoc) 5432 CheckPolymorphic(MemberPointerTypeLoc) 5433 CheckPolymorphic(BlockPointerTypeLoc) 5434 CheckPolymorphic(AtomicTypeLoc) 5435 5436 /// Handle all the types we haven't given a more specific 5437 /// implementation for above. 5438 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5439 // Every other kind of type that we haven't called out already 5440 // that has an inner type is either (1) sugar or (2) contains that 5441 // inner type in some way as a subobject. 5442 if (TypeLoc Next = TL.getNextTypeLoc()) 5443 return Visit(Next, Sel); 5444 5445 // If there's no inner type and we're in a permissive context, 5446 // don't diagnose. 5447 if (Sel == Sema::AbstractNone) return; 5448 5449 // Check whether the type matches the abstract type. 5450 QualType T = TL.getType(); 5451 if (T->isArrayType()) { 5452 Sel = Sema::AbstractArrayType; 5453 T = Info.S.Context.getBaseElementType(T); 5454 } 5455 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5456 if (CT != Info.AbstractType) return; 5457 5458 // It matched; do some magic. 5459 if (Sel == Sema::AbstractArrayType) { 5460 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5461 << T << TL.getSourceRange(); 5462 } else { 5463 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5464 << Sel << T << TL.getSourceRange(); 5465 } 5466 Info.DiagnoseAbstractType(); 5467 } 5468 }; 5469 5470 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5471 Sema::AbstractDiagSelID Sel) { 5472 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5473 } 5474 5475 } 5476 5477 /// Check for invalid uses of an abstract type in a method declaration. 5478 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5479 CXXMethodDecl *MD) { 5480 // No need to do the check on definitions, which require that 5481 // the return/param types be complete. 5482 if (MD->doesThisDeclarationHaveABody()) 5483 return; 5484 5485 // For safety's sake, just ignore it if we don't have type source 5486 // information. This should never happen for non-implicit methods, 5487 // but... 5488 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5489 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5490 } 5491 5492 /// Check for invalid uses of an abstract type within a class definition. 5493 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5494 CXXRecordDecl *RD) { 5495 for (auto *D : RD->decls()) { 5496 if (D->isImplicit()) continue; 5497 5498 // Methods and method templates. 5499 if (isa<CXXMethodDecl>(D)) { 5500 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5501 } else if (isa<FunctionTemplateDecl>(D)) { 5502 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5503 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5504 5505 // Fields and static variables. 5506 } else if (isa<FieldDecl>(D)) { 5507 FieldDecl *FD = cast<FieldDecl>(D); 5508 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5509 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5510 } else if (isa<VarDecl>(D)) { 5511 VarDecl *VD = cast<VarDecl>(D); 5512 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5513 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5514 5515 // Nested classes and class templates. 5516 } else if (isa<CXXRecordDecl>(D)) { 5517 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5518 } else if (isa<ClassTemplateDecl>(D)) { 5519 CheckAbstractClassUsage(Info, 5520 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5521 } 5522 } 5523 } 5524 5525 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5526 Attr *ClassAttr = getDLLAttr(Class); 5527 if (!ClassAttr) 5528 return; 5529 5530 assert(ClassAttr->getKind() == attr::DLLExport); 5531 5532 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5533 5534 if (TSK == TSK_ExplicitInstantiationDeclaration) 5535 // Don't go any further if this is just an explicit instantiation 5536 // declaration. 5537 return; 5538 5539 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5540 S.MarkVTableUsed(Class->getLocation(), Class, true); 5541 5542 for (Decl *Member : Class->decls()) { 5543 // Defined static variables that are members of an exported base 5544 // class must be marked export too. 5545 auto *VD = dyn_cast<VarDecl>(Member); 5546 if (VD && Member->getAttr<DLLExportAttr>() && 5547 VD->getStorageClass() == SC_Static && 5548 TSK == TSK_ImplicitInstantiation) 5549 S.MarkVariableReferenced(VD->getLocation(), VD); 5550 5551 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5552 if (!MD) 5553 continue; 5554 5555 if (Member->getAttr<DLLExportAttr>()) { 5556 if (MD->isUserProvided()) { 5557 // Instantiate non-default class member functions ... 5558 5559 // .. except for certain kinds of template specializations. 5560 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5561 continue; 5562 5563 S.MarkFunctionReferenced(Class->getLocation(), MD); 5564 5565 // The function will be passed to the consumer when its definition is 5566 // encountered. 5567 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5568 MD->isCopyAssignmentOperator() || 5569 MD->isMoveAssignmentOperator()) { 5570 // Synthesize and instantiate non-trivial implicit methods, explicitly 5571 // defaulted methods, and the copy and move assignment operators. The 5572 // latter are exported even if they are trivial, because the address of 5573 // an operator can be taken and should compare equal across libraries. 5574 DiagnosticErrorTrap Trap(S.Diags); 5575 S.MarkFunctionReferenced(Class->getLocation(), MD); 5576 if (Trap.hasErrorOccurred()) { 5577 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5578 << Class << !S.getLangOpts().CPlusPlus11; 5579 break; 5580 } 5581 5582 // There is no later point when we will see the definition of this 5583 // function, so pass it to the consumer now. 5584 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5585 } 5586 } 5587 } 5588 } 5589 5590 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5591 CXXRecordDecl *Class) { 5592 // Only the MS ABI has default constructor closures, so we don't need to do 5593 // this semantic checking anywhere else. 5594 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5595 return; 5596 5597 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5598 for (Decl *Member : Class->decls()) { 5599 // Look for exported default constructors. 5600 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5601 if (!CD || !CD->isDefaultConstructor()) 5602 continue; 5603 auto *Attr = CD->getAttr<DLLExportAttr>(); 5604 if (!Attr) 5605 continue; 5606 5607 // If the class is non-dependent, mark the default arguments as ODR-used so 5608 // that we can properly codegen the constructor closure. 5609 if (!Class->isDependentContext()) { 5610 for (ParmVarDecl *PD : CD->parameters()) { 5611 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5612 S.DiscardCleanupsInEvaluationContext(); 5613 } 5614 } 5615 5616 if (LastExportedDefaultCtor) { 5617 S.Diag(LastExportedDefaultCtor->getLocation(), 5618 diag::err_attribute_dll_ambiguous_default_ctor) 5619 << Class; 5620 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5621 << CD->getDeclName(); 5622 return; 5623 } 5624 LastExportedDefaultCtor = CD; 5625 } 5626 } 5627 5628 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5629 // Mark any compiler-generated routines with the implicit code_seg attribute. 5630 for (auto *Method : Class->methods()) { 5631 if (Method->isUserProvided()) 5632 continue; 5633 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5634 Method->addAttr(A); 5635 } 5636 } 5637 5638 /// Check class-level dllimport/dllexport attribute. 5639 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5640 Attr *ClassAttr = getDLLAttr(Class); 5641 5642 // MSVC inherits DLL attributes to partial class template specializations. 5643 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5644 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5645 if (Attr *TemplateAttr = 5646 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5647 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5648 A->setInherited(true); 5649 ClassAttr = A; 5650 } 5651 } 5652 } 5653 5654 if (!ClassAttr) 5655 return; 5656 5657 if (!Class->isExternallyVisible()) { 5658 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5659 << Class << ClassAttr; 5660 return; 5661 } 5662 5663 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5664 !ClassAttr->isInherited()) { 5665 // Diagnose dll attributes on members of class with dll attribute. 5666 for (Decl *Member : Class->decls()) { 5667 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5668 continue; 5669 InheritableAttr *MemberAttr = getDLLAttr(Member); 5670 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5671 continue; 5672 5673 Diag(MemberAttr->getLocation(), 5674 diag::err_attribute_dll_member_of_dll_class) 5675 << MemberAttr << ClassAttr; 5676 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5677 Member->setInvalidDecl(); 5678 } 5679 } 5680 5681 if (Class->getDescribedClassTemplate()) 5682 // Don't inherit dll attribute until the template is instantiated. 5683 return; 5684 5685 // The class is either imported or exported. 5686 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5687 5688 // Check if this was a dllimport attribute propagated from a derived class to 5689 // a base class template specialization. We don't apply these attributes to 5690 // static data members. 5691 const bool PropagatedImport = 5692 !ClassExported && 5693 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5694 5695 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5696 5697 // Ignore explicit dllexport on explicit class template instantiation declarations. 5698 if (ClassExported && !ClassAttr->isInherited() && 5699 TSK == TSK_ExplicitInstantiationDeclaration) { 5700 Class->dropAttr<DLLExportAttr>(); 5701 return; 5702 } 5703 5704 // Force declaration of implicit members so they can inherit the attribute. 5705 ForceDeclarationOfImplicitMembers(Class); 5706 5707 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5708 // seem to be true in practice? 5709 5710 for (Decl *Member : Class->decls()) { 5711 VarDecl *VD = dyn_cast<VarDecl>(Member); 5712 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5713 5714 // Only methods and static fields inherit the attributes. 5715 if (!VD && !MD) 5716 continue; 5717 5718 if (MD) { 5719 // Don't process deleted methods. 5720 if (MD->isDeleted()) 5721 continue; 5722 5723 if (MD->isInlined()) { 5724 // MinGW does not import or export inline methods. 5725 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5726 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5727 continue; 5728 5729 // MSVC versions before 2015 don't export the move assignment operators 5730 // and move constructor, so don't attempt to import/export them if 5731 // we have a definition. 5732 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5733 if ((MD->isMoveAssignmentOperator() || 5734 (Ctor && Ctor->isMoveConstructor())) && 5735 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5736 continue; 5737 5738 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5739 // operator is exported anyway. 5740 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5741 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5742 continue; 5743 } 5744 } 5745 5746 // Don't apply dllimport attributes to static data members of class template 5747 // instantiations when the attribute is propagated from a derived class. 5748 if (VD && PropagatedImport) 5749 continue; 5750 5751 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5752 continue; 5753 5754 if (!getDLLAttr(Member)) { 5755 InheritableAttr *NewAttr = nullptr; 5756 5757 // Do not export/import inline function when -fno-dllexport-inlines is 5758 // passed. But add attribute for later local static var check. 5759 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 5760 TSK != TSK_ExplicitInstantiationDeclaration && 5761 TSK != TSK_ExplicitInstantiationDefinition) { 5762 if (ClassExported) { 5763 NewAttr = ::new (getASTContext()) 5764 DLLExportStaticLocalAttr(ClassAttr->getRange(), 5765 getASTContext(), 5766 ClassAttr->getSpellingListIndex()); 5767 } else { 5768 NewAttr = ::new (getASTContext()) 5769 DLLImportStaticLocalAttr(ClassAttr->getRange(), 5770 getASTContext(), 5771 ClassAttr->getSpellingListIndex()); 5772 } 5773 } else { 5774 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5775 } 5776 5777 NewAttr->setInherited(true); 5778 Member->addAttr(NewAttr); 5779 5780 if (MD) { 5781 // Propagate DLLAttr to friend re-declarations of MD that have already 5782 // been constructed. 5783 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5784 FD = FD->getPreviousDecl()) { 5785 if (FD->getFriendObjectKind() == Decl::FOK_None) 5786 continue; 5787 assert(!getDLLAttr(FD) && 5788 "friend re-decl should not already have a DLLAttr"); 5789 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5790 NewAttr->setInherited(true); 5791 FD->addAttr(NewAttr); 5792 } 5793 } 5794 } 5795 } 5796 5797 if (ClassExported) 5798 DelayedDllExportClasses.push_back(Class); 5799 } 5800 5801 /// Perform propagation of DLL attributes from a derived class to a 5802 /// templated base class for MS compatibility. 5803 void Sema::propagateDLLAttrToBaseClassTemplate( 5804 CXXRecordDecl *Class, Attr *ClassAttr, 5805 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5806 if (getDLLAttr( 5807 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5808 // If the base class template has a DLL attribute, don't try to change it. 5809 return; 5810 } 5811 5812 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5813 if (!getDLLAttr(BaseTemplateSpec) && 5814 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5815 TSK == TSK_ImplicitInstantiation)) { 5816 // The template hasn't been instantiated yet (or it has, but only as an 5817 // explicit instantiation declaration or implicit instantiation, which means 5818 // we haven't codegenned any members yet), so propagate the attribute. 5819 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5820 NewAttr->setInherited(true); 5821 BaseTemplateSpec->addAttr(NewAttr); 5822 5823 // If this was an import, mark that we propagated it from a derived class to 5824 // a base class template specialization. 5825 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 5826 ImportAttr->setPropagatedToBaseTemplate(); 5827 5828 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5829 // needs to be run again to work see the new attribute. Otherwise this will 5830 // get run whenever the template is instantiated. 5831 if (TSK != TSK_Undeclared) 5832 checkClassLevelDLLAttribute(BaseTemplateSpec); 5833 5834 return; 5835 } 5836 5837 if (getDLLAttr(BaseTemplateSpec)) { 5838 // The template has already been specialized or instantiated with an 5839 // attribute, explicitly or through propagation. We should not try to change 5840 // it. 5841 return; 5842 } 5843 5844 // The template was previously instantiated or explicitly specialized without 5845 // a dll attribute, It's too late for us to add an attribute, so warn that 5846 // this is unsupported. 5847 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5848 << BaseTemplateSpec->isExplicitSpecialization(); 5849 Diag(ClassAttr->getLocation(), diag::note_attribute); 5850 if (BaseTemplateSpec->isExplicitSpecialization()) { 5851 Diag(BaseTemplateSpec->getLocation(), 5852 diag::note_template_class_explicit_specialization_was_here) 5853 << BaseTemplateSpec; 5854 } else { 5855 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5856 diag::note_template_class_instantiation_was_here) 5857 << BaseTemplateSpec; 5858 } 5859 } 5860 5861 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5862 SourceLocation DefaultLoc) { 5863 switch (S.getSpecialMember(MD)) { 5864 case Sema::CXXDefaultConstructor: 5865 S.DefineImplicitDefaultConstructor(DefaultLoc, 5866 cast<CXXConstructorDecl>(MD)); 5867 break; 5868 case Sema::CXXCopyConstructor: 5869 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5870 break; 5871 case Sema::CXXCopyAssignment: 5872 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5873 break; 5874 case Sema::CXXDestructor: 5875 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5876 break; 5877 case Sema::CXXMoveConstructor: 5878 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5879 break; 5880 case Sema::CXXMoveAssignment: 5881 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5882 break; 5883 case Sema::CXXInvalid: 5884 llvm_unreachable("Invalid special member."); 5885 } 5886 } 5887 5888 /// Determine whether a type is permitted to be passed or returned in 5889 /// registers, per C++ [class.temporary]p3. 5890 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 5891 TargetInfo::CallingConvKind CCK) { 5892 if (D->isDependentType() || D->isInvalidDecl()) 5893 return false; 5894 5895 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 5896 // The PS4 platform ABI follows the behavior of Clang 3.2. 5897 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 5898 return !D->hasNonTrivialDestructorForCall() && 5899 !D->hasNonTrivialCopyConstructorForCall(); 5900 5901 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 5902 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 5903 bool DtorIsTrivialForCall = false; 5904 5905 // If a class has at least one non-deleted, trivial copy constructor, it 5906 // is passed according to the C ABI. Otherwise, it is passed indirectly. 5907 // 5908 // Note: This permits classes with non-trivial copy or move ctors to be 5909 // passed in registers, so long as they *also* have a trivial copy ctor, 5910 // which is non-conforming. 5911 if (D->needsImplicitCopyConstructor()) { 5912 if (!D->defaultedCopyConstructorIsDeleted()) { 5913 if (D->hasTrivialCopyConstructor()) 5914 CopyCtorIsTrivial = true; 5915 if (D->hasTrivialCopyConstructorForCall()) 5916 CopyCtorIsTrivialForCall = true; 5917 } 5918 } else { 5919 for (const CXXConstructorDecl *CD : D->ctors()) { 5920 if (CD->isCopyConstructor() && !CD->isDeleted()) { 5921 if (CD->isTrivial()) 5922 CopyCtorIsTrivial = true; 5923 if (CD->isTrivialForCall()) 5924 CopyCtorIsTrivialForCall = true; 5925 } 5926 } 5927 } 5928 5929 if (D->needsImplicitDestructor()) { 5930 if (!D->defaultedDestructorIsDeleted() && 5931 D->hasTrivialDestructorForCall()) 5932 DtorIsTrivialForCall = true; 5933 } else if (const auto *DD = D->getDestructor()) { 5934 if (!DD->isDeleted() && DD->isTrivialForCall()) 5935 DtorIsTrivialForCall = true; 5936 } 5937 5938 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 5939 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 5940 return true; 5941 5942 // If a class has a destructor, we'd really like to pass it indirectly 5943 // because it allows us to elide copies. Unfortunately, MSVC makes that 5944 // impossible for small types, which it will pass in a single register or 5945 // stack slot. Most objects with dtors are large-ish, so handle that early. 5946 // We can't call out all large objects as being indirect because there are 5947 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 5948 // how we pass large POD types. 5949 5950 // Note: This permits small classes with nontrivial destructors to be 5951 // passed in registers, which is non-conforming. 5952 if (CopyCtorIsTrivial && 5953 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64) 5954 return true; 5955 return false; 5956 } 5957 5958 // Per C++ [class.temporary]p3, the relevant condition is: 5959 // each copy constructor, move constructor, and destructor of X is 5960 // either trivial or deleted, and X has at least one non-deleted copy 5961 // or move constructor 5962 bool HasNonDeletedCopyOrMove = false; 5963 5964 if (D->needsImplicitCopyConstructor() && 5965 !D->defaultedCopyConstructorIsDeleted()) { 5966 if (!D->hasTrivialCopyConstructorForCall()) 5967 return false; 5968 HasNonDeletedCopyOrMove = true; 5969 } 5970 5971 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5972 !D->defaultedMoveConstructorIsDeleted()) { 5973 if (!D->hasTrivialMoveConstructorForCall()) 5974 return false; 5975 HasNonDeletedCopyOrMove = true; 5976 } 5977 5978 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5979 !D->hasTrivialDestructorForCall()) 5980 return false; 5981 5982 for (const CXXMethodDecl *MD : D->methods()) { 5983 if (MD->isDeleted()) 5984 continue; 5985 5986 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5987 if (CD && CD->isCopyOrMoveConstructor()) 5988 HasNonDeletedCopyOrMove = true; 5989 else if (!isa<CXXDestructorDecl>(MD)) 5990 continue; 5991 5992 if (!MD->isTrivialForCall()) 5993 return false; 5994 } 5995 5996 return HasNonDeletedCopyOrMove; 5997 } 5998 5999 /// Perform semantic checks on a class definition that has been 6000 /// completing, introducing implicitly-declared members, checking for 6001 /// abstract types, etc. 6002 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 6003 if (!Record) 6004 return; 6005 6006 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6007 AbstractUsageInfo Info(*this, Record); 6008 CheckAbstractClassUsage(Info, Record); 6009 } 6010 6011 // If this is not an aggregate type and has no user-declared constructor, 6012 // complain about any non-static data members of reference or const scalar 6013 // type, since they will never get initializers. 6014 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6015 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6016 !Record->isLambda()) { 6017 bool Complained = false; 6018 for (const auto *F : Record->fields()) { 6019 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6020 continue; 6021 6022 if (F->getType()->isReferenceType() || 6023 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6024 if (!Complained) { 6025 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6026 << Record->getTagKind() << Record; 6027 Complained = true; 6028 } 6029 6030 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6031 << F->getType()->isReferenceType() 6032 << F->getDeclName(); 6033 } 6034 } 6035 } 6036 6037 if (Record->getIdentifier()) { 6038 // C++ [class.mem]p13: 6039 // If T is the name of a class, then each of the following shall have a 6040 // name different from T: 6041 // - every member of every anonymous union that is a member of class T. 6042 // 6043 // C++ [class.mem]p14: 6044 // In addition, if class T has a user-declared constructor (12.1), every 6045 // non-static data member of class T shall have a name different from T. 6046 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6047 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6048 ++I) { 6049 NamedDecl *D = (*I)->getUnderlyingDecl(); 6050 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6051 Record->hasUserDeclaredConstructor()) || 6052 isa<IndirectFieldDecl>(D)) { 6053 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6054 << D->getDeclName(); 6055 break; 6056 } 6057 } 6058 } 6059 6060 // Warn if the class has virtual methods but non-virtual public destructor. 6061 if (Record->isPolymorphic() && !Record->isDependentType()) { 6062 CXXDestructorDecl *dtor = Record->getDestructor(); 6063 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6064 !Record->hasAttr<FinalAttr>()) 6065 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6066 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6067 } 6068 6069 if (Record->isAbstract()) { 6070 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6071 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6072 << FA->isSpelledAsSealed(); 6073 DiagnoseAbstractType(Record); 6074 } 6075 } 6076 6077 // See if trivial_abi has to be dropped. 6078 if (Record->hasAttr<TrivialABIAttr>()) 6079 checkIllFormedTrivialABIStruct(*Record); 6080 6081 // Set HasTrivialSpecialMemberForCall if the record has attribute 6082 // "trivial_abi". 6083 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6084 6085 if (HasTrivialABI) 6086 Record->setHasTrivialSpecialMemberForCall(); 6087 6088 bool HasMethodWithOverrideControl = false, 6089 HasOverridingMethodWithoutOverrideControl = false; 6090 if (!Record->isDependentType()) { 6091 for (auto *M : Record->methods()) { 6092 // See if a method overloads virtual methods in a base 6093 // class without overriding any. 6094 if (!M->isStatic()) 6095 DiagnoseHiddenVirtualMethods(M); 6096 if (M->hasAttr<OverrideAttr>()) 6097 HasMethodWithOverrideControl = true; 6098 else if (M->size_overridden_methods() > 0) 6099 HasOverridingMethodWithoutOverrideControl = true; 6100 // Check whether the explicitly-defaulted special members are valid. 6101 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6102 CheckExplicitlyDefaultedSpecialMember(M); 6103 6104 // For an explicitly defaulted or deleted special member, we defer 6105 // determining triviality until the class is complete. That time is now! 6106 CXXSpecialMember CSM = getSpecialMember(M); 6107 if (!M->isImplicit() && !M->isUserProvided()) { 6108 if (CSM != CXXInvalid) { 6109 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6110 // Inform the class that we've finished declaring this member. 6111 Record->finishedDefaultedOrDeletedMember(M); 6112 M->setTrivialForCall( 6113 HasTrivialABI || 6114 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6115 Record->setTrivialForCallFlags(M); 6116 } 6117 } 6118 6119 // Set triviality for the purpose of calls if this is a user-provided 6120 // copy/move constructor or destructor. 6121 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6122 CSM == CXXDestructor) && M->isUserProvided()) { 6123 M->setTrivialForCall(HasTrivialABI); 6124 Record->setTrivialForCallFlags(M); 6125 } 6126 6127 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6128 M->hasAttr<DLLExportAttr>()) { 6129 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6130 M->isTrivial() && 6131 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6132 CSM == CXXDestructor)) 6133 M->dropAttr<DLLExportAttr>(); 6134 6135 if (M->hasAttr<DLLExportAttr>()) { 6136 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6137 ActOnFinishInlineFunctionDef(M); 6138 } 6139 } 6140 } 6141 } 6142 6143 if (HasMethodWithOverrideControl && 6144 HasOverridingMethodWithoutOverrideControl) { 6145 // At least one method has the 'override' control declared. 6146 // Diagnose all other overridden methods which do not have 'override' specified on them. 6147 for (auto *M : Record->methods()) 6148 DiagnoseAbsenceOfOverrideControl(M); 6149 } 6150 6151 // ms_struct is a request to use the same ABI rules as MSVC. Check 6152 // whether this class uses any C++ features that are implemented 6153 // completely differently in MSVC, and if so, emit a diagnostic. 6154 // That diagnostic defaults to an error, but we allow projects to 6155 // map it down to a warning (or ignore it). It's a fairly common 6156 // practice among users of the ms_struct pragma to mass-annotate 6157 // headers, sweeping up a bunch of types that the project doesn't 6158 // really rely on MSVC-compatible layout for. We must therefore 6159 // support "ms_struct except for C++ stuff" as a secondary ABI. 6160 if (Record->isMsStruct(Context) && 6161 (Record->isPolymorphic() || Record->getNumBases())) { 6162 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6163 } 6164 6165 checkClassLevelDLLAttribute(Record); 6166 checkClassLevelCodeSegAttribute(Record); 6167 6168 bool ClangABICompat4 = 6169 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6170 TargetInfo::CallingConvKind CCK = 6171 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6172 bool CanPass = canPassInRegisters(*this, Record, CCK); 6173 6174 // Do not change ArgPassingRestrictions if it has already been set to 6175 // APK_CanNeverPassInRegs. 6176 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6177 Record->setArgPassingRestrictions(CanPass 6178 ? RecordDecl::APK_CanPassInRegs 6179 : RecordDecl::APK_CannotPassInRegs); 6180 6181 // If canPassInRegisters returns true despite the record having a non-trivial 6182 // destructor, the record is destructed in the callee. This happens only when 6183 // the record or one of its subobjects has a field annotated with trivial_abi 6184 // or a field qualified with ObjC __strong/__weak. 6185 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6186 Record->setParamDestroyedInCallee(true); 6187 else if (Record->hasNonTrivialDestructor()) 6188 Record->setParamDestroyedInCallee(CanPass); 6189 6190 if (getLangOpts().ForceEmitVTables) { 6191 // If we want to emit all the vtables, we need to mark it as used. This 6192 // is especially required for cases like vtable assumption loads. 6193 MarkVTableUsed(Record->getInnerLocStart(), Record); 6194 } 6195 } 6196 6197 /// Look up the special member function that would be called by a special 6198 /// member function for a subobject of class type. 6199 /// 6200 /// \param Class The class type of the subobject. 6201 /// \param CSM The kind of special member function. 6202 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6203 /// \param ConstRHS True if this is a copy operation with a const object 6204 /// on its RHS, that is, if the argument to the outer special member 6205 /// function is 'const' and this is not a field marked 'mutable'. 6206 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6207 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6208 unsigned FieldQuals, bool ConstRHS) { 6209 unsigned LHSQuals = 0; 6210 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6211 LHSQuals = FieldQuals; 6212 6213 unsigned RHSQuals = FieldQuals; 6214 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6215 RHSQuals = 0; 6216 else if (ConstRHS) 6217 RHSQuals |= Qualifiers::Const; 6218 6219 return S.LookupSpecialMember(Class, CSM, 6220 RHSQuals & Qualifiers::Const, 6221 RHSQuals & Qualifiers::Volatile, 6222 false, 6223 LHSQuals & Qualifiers::Const, 6224 LHSQuals & Qualifiers::Volatile); 6225 } 6226 6227 class Sema::InheritedConstructorInfo { 6228 Sema &S; 6229 SourceLocation UseLoc; 6230 6231 /// A mapping from the base classes through which the constructor was 6232 /// inherited to the using shadow declaration in that base class (or a null 6233 /// pointer if the constructor was declared in that base class). 6234 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6235 InheritedFromBases; 6236 6237 public: 6238 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6239 ConstructorUsingShadowDecl *Shadow) 6240 : S(S), UseLoc(UseLoc) { 6241 bool DiagnosedMultipleConstructedBases = false; 6242 CXXRecordDecl *ConstructedBase = nullptr; 6243 UsingDecl *ConstructedBaseUsing = nullptr; 6244 6245 // Find the set of such base class subobjects and check that there's a 6246 // unique constructed subobject. 6247 for (auto *D : Shadow->redecls()) { 6248 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6249 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6250 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6251 6252 InheritedFromBases.insert( 6253 std::make_pair(DNominatedBase->getCanonicalDecl(), 6254 DShadow->getNominatedBaseClassShadowDecl())); 6255 if (DShadow->constructsVirtualBase()) 6256 InheritedFromBases.insert( 6257 std::make_pair(DConstructedBase->getCanonicalDecl(), 6258 DShadow->getConstructedBaseClassShadowDecl())); 6259 else 6260 assert(DNominatedBase == DConstructedBase); 6261 6262 // [class.inhctor.init]p2: 6263 // If the constructor was inherited from multiple base class subobjects 6264 // of type B, the program is ill-formed. 6265 if (!ConstructedBase) { 6266 ConstructedBase = DConstructedBase; 6267 ConstructedBaseUsing = D->getUsingDecl(); 6268 } else if (ConstructedBase != DConstructedBase && 6269 !Shadow->isInvalidDecl()) { 6270 if (!DiagnosedMultipleConstructedBases) { 6271 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6272 << Shadow->getTargetDecl(); 6273 S.Diag(ConstructedBaseUsing->getLocation(), 6274 diag::note_ambiguous_inherited_constructor_using) 6275 << ConstructedBase; 6276 DiagnosedMultipleConstructedBases = true; 6277 } 6278 S.Diag(D->getUsingDecl()->getLocation(), 6279 diag::note_ambiguous_inherited_constructor_using) 6280 << DConstructedBase; 6281 } 6282 } 6283 6284 if (DiagnosedMultipleConstructedBases) 6285 Shadow->setInvalidDecl(); 6286 } 6287 6288 /// Find the constructor to use for inherited construction of a base class, 6289 /// and whether that base class constructor inherits the constructor from a 6290 /// virtual base class (in which case it won't actually invoke it). 6291 std::pair<CXXConstructorDecl *, bool> 6292 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6293 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6294 if (It == InheritedFromBases.end()) 6295 return std::make_pair(nullptr, false); 6296 6297 // This is an intermediary class. 6298 if (It->second) 6299 return std::make_pair( 6300 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6301 It->second->constructsVirtualBase()); 6302 6303 // This is the base class from which the constructor was inherited. 6304 return std::make_pair(Ctor, false); 6305 } 6306 }; 6307 6308 /// Is the special member function which would be selected to perform the 6309 /// specified operation on the specified class type a constexpr constructor? 6310 static bool 6311 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6312 Sema::CXXSpecialMember CSM, unsigned Quals, 6313 bool ConstRHS, 6314 CXXConstructorDecl *InheritedCtor = nullptr, 6315 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6316 // If we're inheriting a constructor, see if we need to call it for this base 6317 // class. 6318 if (InheritedCtor) { 6319 assert(CSM == Sema::CXXDefaultConstructor); 6320 auto BaseCtor = 6321 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6322 if (BaseCtor) 6323 return BaseCtor->isConstexpr(); 6324 } 6325 6326 if (CSM == Sema::CXXDefaultConstructor) 6327 return ClassDecl->hasConstexprDefaultConstructor(); 6328 6329 Sema::SpecialMemberOverloadResult SMOR = 6330 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6331 if (!SMOR.getMethod()) 6332 // A constructor we wouldn't select can't be "involved in initializing" 6333 // anything. 6334 return true; 6335 return SMOR.getMethod()->isConstexpr(); 6336 } 6337 6338 /// Determine whether the specified special member function would be constexpr 6339 /// if it were implicitly defined. 6340 static bool defaultedSpecialMemberIsConstexpr( 6341 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6342 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6343 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6344 if (!S.getLangOpts().CPlusPlus11) 6345 return false; 6346 6347 // C++11 [dcl.constexpr]p4: 6348 // In the definition of a constexpr constructor [...] 6349 bool Ctor = true; 6350 switch (CSM) { 6351 case Sema::CXXDefaultConstructor: 6352 if (Inherited) 6353 break; 6354 // Since default constructor lookup is essentially trivial (and cannot 6355 // involve, for instance, template instantiation), we compute whether a 6356 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6357 // 6358 // This is important for performance; we need to know whether the default 6359 // constructor is constexpr to determine whether the type is a literal type. 6360 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6361 6362 case Sema::CXXCopyConstructor: 6363 case Sema::CXXMoveConstructor: 6364 // For copy or move constructors, we need to perform overload resolution. 6365 break; 6366 6367 case Sema::CXXCopyAssignment: 6368 case Sema::CXXMoveAssignment: 6369 if (!S.getLangOpts().CPlusPlus14) 6370 return false; 6371 // In C++1y, we need to perform overload resolution. 6372 Ctor = false; 6373 break; 6374 6375 case Sema::CXXDestructor: 6376 case Sema::CXXInvalid: 6377 return false; 6378 } 6379 6380 // -- if the class is a non-empty union, or for each non-empty anonymous 6381 // union member of a non-union class, exactly one non-static data member 6382 // shall be initialized; [DR1359] 6383 // 6384 // If we squint, this is guaranteed, since exactly one non-static data member 6385 // will be initialized (if the constructor isn't deleted), we just don't know 6386 // which one. 6387 if (Ctor && ClassDecl->isUnion()) 6388 return CSM == Sema::CXXDefaultConstructor 6389 ? ClassDecl->hasInClassInitializer() || 6390 !ClassDecl->hasVariantMembers() 6391 : true; 6392 6393 // -- the class shall not have any virtual base classes; 6394 if (Ctor && ClassDecl->getNumVBases()) 6395 return false; 6396 6397 // C++1y [class.copy]p26: 6398 // -- [the class] is a literal type, and 6399 if (!Ctor && !ClassDecl->isLiteral()) 6400 return false; 6401 6402 // -- every constructor involved in initializing [...] base class 6403 // sub-objects shall be a constexpr constructor; 6404 // -- the assignment operator selected to copy/move each direct base 6405 // class is a constexpr function, and 6406 for (const auto &B : ClassDecl->bases()) { 6407 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6408 if (!BaseType) continue; 6409 6410 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6411 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6412 InheritedCtor, Inherited)) 6413 return false; 6414 } 6415 6416 // -- every constructor involved in initializing non-static data members 6417 // [...] shall be a constexpr constructor; 6418 // -- every non-static data member and base class sub-object shall be 6419 // initialized 6420 // -- for each non-static data member of X that is of class type (or array 6421 // thereof), the assignment operator selected to copy/move that member is 6422 // a constexpr function 6423 for (const auto *F : ClassDecl->fields()) { 6424 if (F->isInvalidDecl()) 6425 continue; 6426 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6427 continue; 6428 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6429 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6430 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6431 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6432 BaseType.getCVRQualifiers(), 6433 ConstArg && !F->isMutable())) 6434 return false; 6435 } else if (CSM == Sema::CXXDefaultConstructor) { 6436 return false; 6437 } 6438 } 6439 6440 // All OK, it's constexpr! 6441 return true; 6442 } 6443 6444 static Sema::ImplicitExceptionSpecification 6445 ComputeDefaultedSpecialMemberExceptionSpec( 6446 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6447 Sema::InheritedConstructorInfo *ICI); 6448 6449 static Sema::ImplicitExceptionSpecification 6450 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6451 auto CSM = S.getSpecialMember(MD); 6452 if (CSM != Sema::CXXInvalid) 6453 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6454 6455 auto *CD = cast<CXXConstructorDecl>(MD); 6456 assert(CD->getInheritedConstructor() && 6457 "only special members have implicit exception specs"); 6458 Sema::InheritedConstructorInfo ICI( 6459 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6460 return ComputeDefaultedSpecialMemberExceptionSpec( 6461 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6462 } 6463 6464 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6465 CXXMethodDecl *MD) { 6466 FunctionProtoType::ExtProtoInfo EPI; 6467 6468 // Build an exception specification pointing back at this member. 6469 EPI.ExceptionSpec.Type = EST_Unevaluated; 6470 EPI.ExceptionSpec.SourceDecl = MD; 6471 6472 // Set the calling convention to the default for C++ instance methods. 6473 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6474 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6475 /*IsCXXMethod=*/true)); 6476 return EPI; 6477 } 6478 6479 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6480 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6481 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6482 return; 6483 6484 // Evaluate the exception specification. 6485 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6486 auto ESI = IES.getExceptionSpec(); 6487 6488 // Update the type of the special member to use it. 6489 UpdateExceptionSpec(MD, ESI); 6490 6491 // A user-provided destructor can be defined outside the class. When that 6492 // happens, be sure to update the exception specification on both 6493 // declarations. 6494 const FunctionProtoType *CanonicalFPT = 6495 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6496 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6497 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6498 } 6499 6500 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6501 CXXRecordDecl *RD = MD->getParent(); 6502 CXXSpecialMember CSM = getSpecialMember(MD); 6503 6504 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6505 "not an explicitly-defaulted special member"); 6506 6507 // Whether this was the first-declared instance of the constructor. 6508 // This affects whether we implicitly add an exception spec and constexpr. 6509 bool First = MD == MD->getCanonicalDecl(); 6510 6511 bool HadError = false; 6512 6513 // C++11 [dcl.fct.def.default]p1: 6514 // A function that is explicitly defaulted shall 6515 // -- be a special member function (checked elsewhere), 6516 // -- have the same type (except for ref-qualifiers, and except that a 6517 // copy operation can take a non-const reference) as an implicit 6518 // declaration, and 6519 // -- not have default arguments. 6520 // C++2a changes the second bullet to instead delete the function if it's 6521 // defaulted on its first declaration, unless it's "an assignment operator, 6522 // and its return type differs or its parameter type is not a reference". 6523 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6524 bool ShouldDeleteForTypeMismatch = false; 6525 unsigned ExpectedParams = 1; 6526 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6527 ExpectedParams = 0; 6528 if (MD->getNumParams() != ExpectedParams) { 6529 // This checks for default arguments: a copy or move constructor with a 6530 // default argument is classified as a default constructor, and assignment 6531 // operations and destructors can't have default arguments. 6532 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6533 << CSM << MD->getSourceRange(); 6534 HadError = true; 6535 } else if (MD->isVariadic()) { 6536 if (DeleteOnTypeMismatch) 6537 ShouldDeleteForTypeMismatch = true; 6538 else { 6539 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6540 << CSM << MD->getSourceRange(); 6541 HadError = true; 6542 } 6543 } 6544 6545 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6546 6547 bool CanHaveConstParam = false; 6548 if (CSM == CXXCopyConstructor) 6549 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6550 else if (CSM == CXXCopyAssignment) 6551 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6552 6553 QualType ReturnType = Context.VoidTy; 6554 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6555 // Check for return type matching. 6556 ReturnType = Type->getReturnType(); 6557 6558 QualType DeclType = Context.getTypeDeclType(RD); 6559 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 6560 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 6561 6562 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6563 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6564 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6565 HadError = true; 6566 } 6567 6568 // A defaulted special member cannot have cv-qualifiers. 6569 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 6570 if (DeleteOnTypeMismatch) 6571 ShouldDeleteForTypeMismatch = true; 6572 else { 6573 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6574 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6575 HadError = true; 6576 } 6577 } 6578 } 6579 6580 // Check for parameter type matching. 6581 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6582 bool HasConstParam = false; 6583 if (ExpectedParams && ArgType->isReferenceType()) { 6584 // Argument must be reference to possibly-const T. 6585 QualType ReferentType = ArgType->getPointeeType(); 6586 HasConstParam = ReferentType.isConstQualified(); 6587 6588 if (ReferentType.isVolatileQualified()) { 6589 if (DeleteOnTypeMismatch) 6590 ShouldDeleteForTypeMismatch = true; 6591 else { 6592 Diag(MD->getLocation(), 6593 diag::err_defaulted_special_member_volatile_param) << CSM; 6594 HadError = true; 6595 } 6596 } 6597 6598 if (HasConstParam && !CanHaveConstParam) { 6599 if (DeleteOnTypeMismatch) 6600 ShouldDeleteForTypeMismatch = true; 6601 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6602 Diag(MD->getLocation(), 6603 diag::err_defaulted_special_member_copy_const_param) 6604 << (CSM == CXXCopyAssignment); 6605 // FIXME: Explain why this special member can't be const. 6606 HadError = true; 6607 } else { 6608 Diag(MD->getLocation(), 6609 diag::err_defaulted_special_member_move_const_param) 6610 << (CSM == CXXMoveAssignment); 6611 HadError = true; 6612 } 6613 } 6614 } else if (ExpectedParams) { 6615 // A copy assignment operator can take its argument by value, but a 6616 // defaulted one cannot. 6617 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6618 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6619 HadError = true; 6620 } 6621 6622 // C++11 [dcl.fct.def.default]p2: 6623 // An explicitly-defaulted function may be declared constexpr only if it 6624 // would have been implicitly declared as constexpr, 6625 // Do not apply this rule to members of class templates, since core issue 1358 6626 // makes such functions always instantiate to constexpr functions. For 6627 // functions which cannot be constexpr (for non-constructors in C++11 and for 6628 // destructors in C++1y), this is checked elsewhere. 6629 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6630 HasConstParam); 6631 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6632 : isa<CXXConstructorDecl>(MD)) && 6633 MD->isConstexpr() && !Constexpr && 6634 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6635 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM; 6636 // FIXME: Explain why the special member can't be constexpr. 6637 HadError = true; 6638 } 6639 6640 // and may have an explicit exception-specification only if it is compatible 6641 // with the exception-specification on the implicit declaration. 6642 if (Type->hasExceptionSpec()) { 6643 // Delay the check if this is the first declaration of the special member, 6644 // since we may not have parsed some necessary in-class initializers yet. 6645 if (First) { 6646 // If the exception specification needs to be instantiated, do so now, 6647 // before we clobber it with an EST_Unevaluated specification below. 6648 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6649 InstantiateExceptionSpec(MD->getBeginLoc(), MD); 6650 Type = MD->getType()->getAs<FunctionProtoType>(); 6651 } 6652 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6653 } else 6654 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6655 } 6656 6657 // If a function is explicitly defaulted on its first declaration, 6658 if (First) { 6659 // -- it is implicitly considered to be constexpr if the implicit 6660 // definition would be, 6661 MD->setConstexpr(Constexpr); 6662 6663 // -- it is implicitly considered to have the same exception-specification 6664 // as if it had been implicitly declared, 6665 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6666 EPI.ExceptionSpec.Type = EST_Unevaluated; 6667 EPI.ExceptionSpec.SourceDecl = MD; 6668 MD->setType(Context.getFunctionType(ReturnType, 6669 llvm::makeArrayRef(&ArgType, 6670 ExpectedParams), 6671 EPI)); 6672 } 6673 6674 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 6675 if (First) { 6676 SetDeclDeleted(MD, MD->getLocation()); 6677 if (!inTemplateInstantiation() && !HadError) { 6678 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 6679 if (ShouldDeleteForTypeMismatch) { 6680 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 6681 } else { 6682 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6683 } 6684 } 6685 if (ShouldDeleteForTypeMismatch && !HadError) { 6686 Diag(MD->getLocation(), 6687 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 6688 } 6689 } else { 6690 // C++11 [dcl.fct.def.default]p4: 6691 // [For a] user-provided explicitly-defaulted function [...] if such a 6692 // function is implicitly defined as deleted, the program is ill-formed. 6693 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6694 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 6695 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6696 HadError = true; 6697 } 6698 } 6699 6700 if (HadError) 6701 MD->setInvalidDecl(); 6702 } 6703 6704 /// Check whether the exception specification provided for an 6705 /// explicitly-defaulted special member matches the exception specification 6706 /// that would have been generated for an implicit special member, per 6707 /// C++11 [dcl.fct.def.default]p2. 6708 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6709 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6710 // If the exception specification was explicitly specified but hadn't been 6711 // parsed when the method was defaulted, grab it now. 6712 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6713 SpecifiedType = 6714 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6715 6716 // Compute the implicit exception specification. 6717 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6718 /*IsCXXMethod=*/true); 6719 FunctionProtoType::ExtProtoInfo EPI(CC); 6720 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6721 EPI.ExceptionSpec = IES.getExceptionSpec(); 6722 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6723 Context.getFunctionType(Context.VoidTy, None, EPI)); 6724 6725 // Ensure that it matches. 6726 CheckEquivalentExceptionSpec( 6727 PDiag(diag::err_incorrect_defaulted_exception_spec) 6728 << getSpecialMember(MD), PDiag(), 6729 ImplicitType, SourceLocation(), 6730 SpecifiedType, MD->getLocation()); 6731 } 6732 6733 void Sema::CheckDelayedMemberExceptionSpecs() { 6734 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 6735 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 6736 decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted; 6737 6738 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 6739 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 6740 std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs); 6741 6742 // Perform any deferred checking of exception specifications for virtual 6743 // destructors. 6744 for (auto &Check : Overriding) 6745 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6746 6747 // Perform any deferred checking of exception specifications for befriended 6748 // special members. 6749 for (auto &Check : Equivalent) 6750 CheckEquivalentExceptionSpec(Check.second, Check.first); 6751 6752 // Check that any explicitly-defaulted methods have exception specifications 6753 // compatible with their implicit exception specifications. 6754 for (auto &Spec : Defaulted) 6755 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6756 } 6757 6758 namespace { 6759 /// CRTP base class for visiting operations performed by a special member 6760 /// function (or inherited constructor). 6761 template<typename Derived> 6762 struct SpecialMemberVisitor { 6763 Sema &S; 6764 CXXMethodDecl *MD; 6765 Sema::CXXSpecialMember CSM; 6766 Sema::InheritedConstructorInfo *ICI; 6767 6768 // Properties of the special member, computed for convenience. 6769 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6770 6771 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6772 Sema::InheritedConstructorInfo *ICI) 6773 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6774 switch (CSM) { 6775 case Sema::CXXDefaultConstructor: 6776 case Sema::CXXCopyConstructor: 6777 case Sema::CXXMoveConstructor: 6778 IsConstructor = true; 6779 break; 6780 case Sema::CXXCopyAssignment: 6781 case Sema::CXXMoveAssignment: 6782 IsAssignment = true; 6783 break; 6784 case Sema::CXXDestructor: 6785 break; 6786 case Sema::CXXInvalid: 6787 llvm_unreachable("invalid special member kind"); 6788 } 6789 6790 if (MD->getNumParams()) { 6791 if (const ReferenceType *RT = 6792 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6793 ConstArg = RT->getPointeeType().isConstQualified(); 6794 } 6795 } 6796 6797 Derived &getDerived() { return static_cast<Derived&>(*this); } 6798 6799 /// Is this a "move" special member? 6800 bool isMove() const { 6801 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6802 } 6803 6804 /// Look up the corresponding special member in the given class. 6805 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6806 unsigned Quals, bool IsMutable) { 6807 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6808 ConstArg && !IsMutable); 6809 } 6810 6811 /// Look up the constructor for the specified base class to see if it's 6812 /// overridden due to this being an inherited constructor. 6813 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6814 if (!ICI) 6815 return {}; 6816 assert(CSM == Sema::CXXDefaultConstructor); 6817 auto *BaseCtor = 6818 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6819 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6820 return MD; 6821 return {}; 6822 } 6823 6824 /// A base or member subobject. 6825 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6826 6827 /// Get the location to use for a subobject in diagnostics. 6828 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6829 // FIXME: For an indirect virtual base, the direct base leading to 6830 // the indirect virtual base would be a more useful choice. 6831 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6832 return B->getBaseTypeLoc(); 6833 else 6834 return Subobj.get<FieldDecl*>()->getLocation(); 6835 } 6836 6837 enum BasesToVisit { 6838 /// Visit all non-virtual (direct) bases. 6839 VisitNonVirtualBases, 6840 /// Visit all direct bases, virtual or not. 6841 VisitDirectBases, 6842 /// Visit all non-virtual bases, and all virtual bases if the class 6843 /// is not abstract. 6844 VisitPotentiallyConstructedBases, 6845 /// Visit all direct or virtual bases. 6846 VisitAllBases 6847 }; 6848 6849 // Visit the bases and members of the class. 6850 bool visit(BasesToVisit Bases) { 6851 CXXRecordDecl *RD = MD->getParent(); 6852 6853 if (Bases == VisitPotentiallyConstructedBases) 6854 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6855 6856 for (auto &B : RD->bases()) 6857 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6858 getDerived().visitBase(&B)) 6859 return true; 6860 6861 if (Bases == VisitAllBases) 6862 for (auto &B : RD->vbases()) 6863 if (getDerived().visitBase(&B)) 6864 return true; 6865 6866 for (auto *F : RD->fields()) 6867 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6868 getDerived().visitField(F)) 6869 return true; 6870 6871 return false; 6872 } 6873 }; 6874 } 6875 6876 namespace { 6877 struct SpecialMemberDeletionInfo 6878 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6879 bool Diagnose; 6880 6881 SourceLocation Loc; 6882 6883 bool AllFieldsAreConst; 6884 6885 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6886 Sema::CXXSpecialMember CSM, 6887 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6888 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6889 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6890 6891 bool inUnion() const { return MD->getParent()->isUnion(); } 6892 6893 Sema::CXXSpecialMember getEffectiveCSM() { 6894 return ICI ? Sema::CXXInvalid : CSM; 6895 } 6896 6897 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 6898 6899 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6900 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6901 6902 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6903 bool shouldDeleteForField(FieldDecl *FD); 6904 bool shouldDeleteForAllConstMembers(); 6905 6906 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6907 unsigned Quals); 6908 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6909 Sema::SpecialMemberOverloadResult SMOR, 6910 bool IsDtorCallInCtor); 6911 6912 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6913 }; 6914 } 6915 6916 /// Is the given special member inaccessible when used on the given 6917 /// sub-object. 6918 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6919 CXXMethodDecl *target) { 6920 /// If we're operating on a base class, the object type is the 6921 /// type of this special member. 6922 QualType objectTy; 6923 AccessSpecifier access = target->getAccess(); 6924 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6925 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6926 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6927 6928 // If we're operating on a field, the object type is the type of the field. 6929 } else { 6930 objectTy = S.Context.getTypeDeclType(target->getParent()); 6931 } 6932 6933 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6934 } 6935 6936 /// Check whether we should delete a special member due to the implicit 6937 /// definition containing a call to a special member of a subobject. 6938 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6939 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6940 bool IsDtorCallInCtor) { 6941 CXXMethodDecl *Decl = SMOR.getMethod(); 6942 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6943 6944 int DiagKind = -1; 6945 6946 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6947 DiagKind = !Decl ? 0 : 1; 6948 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6949 DiagKind = 2; 6950 else if (!isAccessible(Subobj, Decl)) 6951 DiagKind = 3; 6952 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6953 !Decl->isTrivial()) { 6954 // A member of a union must have a trivial corresponding special member. 6955 // As a weird special case, a destructor call from a union's constructor 6956 // must be accessible and non-deleted, but need not be trivial. Such a 6957 // destructor is never actually called, but is semantically checked as 6958 // if it were. 6959 DiagKind = 4; 6960 } 6961 6962 if (DiagKind == -1) 6963 return false; 6964 6965 if (Diagnose) { 6966 if (Field) { 6967 S.Diag(Field->getLocation(), 6968 diag::note_deleted_special_member_class_subobject) 6969 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6970 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 6971 } else { 6972 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6973 S.Diag(Base->getBeginLoc(), 6974 diag::note_deleted_special_member_class_subobject) 6975 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 6976 << Base->getType() << DiagKind << IsDtorCallInCtor 6977 << /*IsObjCPtr*/false; 6978 } 6979 6980 if (DiagKind == 1) 6981 S.NoteDeletedFunction(Decl); 6982 // FIXME: Explain inaccessibility if DiagKind == 3. 6983 } 6984 6985 return true; 6986 } 6987 6988 /// Check whether we should delete a special member function due to having a 6989 /// direct or virtual base class or non-static data member of class type M. 6990 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6991 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6992 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6993 bool IsMutable = Field && Field->isMutable(); 6994 6995 // C++11 [class.ctor]p5: 6996 // -- any direct or virtual base class, or non-static data member with no 6997 // brace-or-equal-initializer, has class type M (or array thereof) and 6998 // either M has no default constructor or overload resolution as applied 6999 // to M's default constructor results in an ambiguity or in a function 7000 // that is deleted or inaccessible 7001 // C++11 [class.copy]p11, C++11 [class.copy]p23: 7002 // -- a direct or virtual base class B that cannot be copied/moved because 7003 // overload resolution, as applied to B's corresponding special member, 7004 // results in an ambiguity or a function that is deleted or inaccessible 7005 // from the defaulted special member 7006 // C++11 [class.dtor]p5: 7007 // -- any direct or virtual base class [...] has a type with a destructor 7008 // that is deleted or inaccessible 7009 if (!(CSM == Sema::CXXDefaultConstructor && 7010 Field && Field->hasInClassInitializer()) && 7011 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 7012 false)) 7013 return true; 7014 7015 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 7016 // -- any direct or virtual base class or non-static data member has a 7017 // type with a destructor that is deleted or inaccessible 7018 if (IsConstructor) { 7019 Sema::SpecialMemberOverloadResult SMOR = 7020 S.LookupSpecialMember(Class, Sema::CXXDestructor, 7021 false, false, false, false, false); 7022 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 7023 return true; 7024 } 7025 7026 return false; 7027 } 7028 7029 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 7030 FieldDecl *FD, QualType FieldType) { 7031 // The defaulted special functions are defined as deleted if this is a variant 7032 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 7033 // type under ARC. 7034 if (!FieldType.hasNonTrivialObjCLifetime()) 7035 return false; 7036 7037 // Don't make the defaulted default constructor defined as deleted if the 7038 // member has an in-class initializer. 7039 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 7040 return false; 7041 7042 if (Diagnose) { 7043 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 7044 S.Diag(FD->getLocation(), 7045 diag::note_deleted_special_member_class_subobject) 7046 << getEffectiveCSM() << ParentClass << /*IsField*/true 7047 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 7048 } 7049 7050 return true; 7051 } 7052 7053 /// Check whether we should delete a special member function due to the class 7054 /// having a particular direct or virtual base class. 7055 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 7056 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 7057 // If program is correct, BaseClass cannot be null, but if it is, the error 7058 // must be reported elsewhere. 7059 if (!BaseClass) 7060 return false; 7061 // If we have an inheriting constructor, check whether we're calling an 7062 // inherited constructor instead of a default constructor. 7063 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 7064 if (auto *BaseCtor = SMOR.getMethod()) { 7065 // Note that we do not check access along this path; other than that, 7066 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 7067 // FIXME: Check that the base has a usable destructor! Sink this into 7068 // shouldDeleteForClassSubobject. 7069 if (BaseCtor->isDeleted() && Diagnose) { 7070 S.Diag(Base->getBeginLoc(), 7071 diag::note_deleted_special_member_class_subobject) 7072 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7073 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 7074 << /*IsObjCPtr*/false; 7075 S.NoteDeletedFunction(BaseCtor); 7076 } 7077 return BaseCtor->isDeleted(); 7078 } 7079 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 7080 } 7081 7082 /// Check whether we should delete a special member function due to the class 7083 /// having a particular non-static data member. 7084 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 7085 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 7086 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 7087 7088 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 7089 return true; 7090 7091 if (CSM == Sema::CXXDefaultConstructor) { 7092 // For a default constructor, all references must be initialized in-class 7093 // and, if a union, it must have a non-const member. 7094 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 7095 if (Diagnose) 7096 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7097 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 7098 return true; 7099 } 7100 // C++11 [class.ctor]p5: any non-variant non-static data member of 7101 // const-qualified type (or array thereof) with no 7102 // brace-or-equal-initializer does not have a user-provided default 7103 // constructor. 7104 if (!inUnion() && FieldType.isConstQualified() && 7105 !FD->hasInClassInitializer() && 7106 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 7107 if (Diagnose) 7108 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7109 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 7110 return true; 7111 } 7112 7113 if (inUnion() && !FieldType.isConstQualified()) 7114 AllFieldsAreConst = false; 7115 } else if (CSM == Sema::CXXCopyConstructor) { 7116 // For a copy constructor, data members must not be of rvalue reference 7117 // type. 7118 if (FieldType->isRValueReferenceType()) { 7119 if (Diagnose) 7120 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 7121 << MD->getParent() << FD << FieldType; 7122 return true; 7123 } 7124 } else if (IsAssignment) { 7125 // For an assignment operator, data members must not be of reference type. 7126 if (FieldType->isReferenceType()) { 7127 if (Diagnose) 7128 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7129 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 7130 return true; 7131 } 7132 if (!FieldRecord && FieldType.isConstQualified()) { 7133 // C++11 [class.copy]p23: 7134 // -- a non-static data member of const non-class type (or array thereof) 7135 if (Diagnose) 7136 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7137 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 7138 return true; 7139 } 7140 } 7141 7142 if (FieldRecord) { 7143 // Some additional restrictions exist on the variant members. 7144 if (!inUnion() && FieldRecord->isUnion() && 7145 FieldRecord->isAnonymousStructOrUnion()) { 7146 bool AllVariantFieldsAreConst = true; 7147 7148 // FIXME: Handle anonymous unions declared within anonymous unions. 7149 for (auto *UI : FieldRecord->fields()) { 7150 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7151 7152 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 7153 return true; 7154 7155 if (!UnionFieldType.isConstQualified()) 7156 AllVariantFieldsAreConst = false; 7157 7158 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7159 if (UnionFieldRecord && 7160 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7161 UnionFieldType.getCVRQualifiers())) 7162 return true; 7163 } 7164 7165 // At least one member in each anonymous union must be non-const 7166 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7167 !FieldRecord->field_empty()) { 7168 if (Diagnose) 7169 S.Diag(FieldRecord->getLocation(), 7170 diag::note_deleted_default_ctor_all_const) 7171 << !!ICI << MD->getParent() << /*anonymous union*/1; 7172 return true; 7173 } 7174 7175 // Don't check the implicit member of the anonymous union type. 7176 // This is technically non-conformant, but sanity demands it. 7177 return false; 7178 } 7179 7180 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7181 FieldType.getCVRQualifiers())) 7182 return true; 7183 } 7184 7185 return false; 7186 } 7187 7188 /// C++11 [class.ctor] p5: 7189 /// A defaulted default constructor for a class X is defined as deleted if 7190 /// X is a union and all of its variant members are of const-qualified type. 7191 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7192 // This is a silly definition, because it gives an empty union a deleted 7193 // default constructor. Don't do that. 7194 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7195 bool AnyFields = false; 7196 for (auto *F : MD->getParent()->fields()) 7197 if ((AnyFields = !F->isUnnamedBitfield())) 7198 break; 7199 if (!AnyFields) 7200 return false; 7201 if (Diagnose) 7202 S.Diag(MD->getParent()->getLocation(), 7203 diag::note_deleted_default_ctor_all_const) 7204 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7205 return true; 7206 } 7207 return false; 7208 } 7209 7210 /// Determine whether a defaulted special member function should be defined as 7211 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7212 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7213 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7214 InheritedConstructorInfo *ICI, 7215 bool Diagnose) { 7216 if (MD->isInvalidDecl()) 7217 return false; 7218 CXXRecordDecl *RD = MD->getParent(); 7219 assert(!RD->isDependentType() && "do deletion after instantiation"); 7220 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7221 return false; 7222 7223 // C++11 [expr.lambda.prim]p19: 7224 // The closure type associated with a lambda-expression has a 7225 // deleted (8.4.3) default constructor and a deleted copy 7226 // assignment operator. 7227 // C++2a adds back these operators if the lambda has no capture-default. 7228 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 7229 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7230 if (Diagnose) 7231 Diag(RD->getLocation(), diag::note_lambda_decl); 7232 return true; 7233 } 7234 7235 // For an anonymous struct or union, the copy and assignment special members 7236 // will never be used, so skip the check. For an anonymous union declared at 7237 // namespace scope, the constructor and destructor are used. 7238 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7239 RD->isAnonymousStructOrUnion()) 7240 return false; 7241 7242 // C++11 [class.copy]p7, p18: 7243 // If the class definition declares a move constructor or move assignment 7244 // operator, an implicitly declared copy constructor or copy assignment 7245 // operator is defined as deleted. 7246 if (MD->isImplicit() && 7247 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7248 CXXMethodDecl *UserDeclaredMove = nullptr; 7249 7250 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7251 // deletion of the corresponding copy operation, not both copy operations. 7252 // MSVC 2015 has adopted the standards conforming behavior. 7253 bool DeletesOnlyMatchingCopy = 7254 getLangOpts().MSVCCompat && 7255 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7256 7257 if (RD->hasUserDeclaredMoveConstructor() && 7258 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7259 if (!Diagnose) return true; 7260 7261 // Find any user-declared move constructor. 7262 for (auto *I : RD->ctors()) { 7263 if (I->isMoveConstructor()) { 7264 UserDeclaredMove = I; 7265 break; 7266 } 7267 } 7268 assert(UserDeclaredMove); 7269 } else if (RD->hasUserDeclaredMoveAssignment() && 7270 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7271 if (!Diagnose) return true; 7272 7273 // Find any user-declared move assignment operator. 7274 for (auto *I : RD->methods()) { 7275 if (I->isMoveAssignmentOperator()) { 7276 UserDeclaredMove = I; 7277 break; 7278 } 7279 } 7280 assert(UserDeclaredMove); 7281 } 7282 7283 if (UserDeclaredMove) { 7284 Diag(UserDeclaredMove->getLocation(), 7285 diag::note_deleted_copy_user_declared_move) 7286 << (CSM == CXXCopyAssignment) << RD 7287 << UserDeclaredMove->isMoveAssignmentOperator(); 7288 return true; 7289 } 7290 } 7291 7292 // Do access control from the special member function 7293 ContextRAII MethodContext(*this, MD); 7294 7295 // C++11 [class.dtor]p5: 7296 // -- for a virtual destructor, lookup of the non-array deallocation function 7297 // results in an ambiguity or in a function that is deleted or inaccessible 7298 if (CSM == CXXDestructor && MD->isVirtual()) { 7299 FunctionDecl *OperatorDelete = nullptr; 7300 DeclarationName Name = 7301 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7302 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7303 OperatorDelete, /*Diagnose*/false)) { 7304 if (Diagnose) 7305 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7306 return true; 7307 } 7308 } 7309 7310 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7311 7312 // Per DR1611, do not consider virtual bases of constructors of abstract 7313 // classes, since we are not going to construct them. 7314 // Per DR1658, do not consider virtual bases of destructors of abstract 7315 // classes either. 7316 // Per DR2180, for assignment operators we only assign (and thus only 7317 // consider) direct bases. 7318 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7319 : SMI.VisitPotentiallyConstructedBases)) 7320 return true; 7321 7322 if (SMI.shouldDeleteForAllConstMembers()) 7323 return true; 7324 7325 if (getLangOpts().CUDA) { 7326 // We should delete the special member in CUDA mode if target inference 7327 // failed. 7328 // For inherited constructors (non-null ICI), CSM may be passed so that MD 7329 // is treated as certain special member, which may not reflect what special 7330 // member MD really is. However inferCUDATargetForImplicitSpecialMember 7331 // expects CSM to match MD, therefore recalculate CSM. 7332 assert(ICI || CSM == getSpecialMember(MD)); 7333 auto RealCSM = CSM; 7334 if (ICI) 7335 RealCSM = getSpecialMember(MD); 7336 7337 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 7338 SMI.ConstArg, Diagnose); 7339 } 7340 7341 return false; 7342 } 7343 7344 /// Perform lookup for a special member of the specified kind, and determine 7345 /// whether it is trivial. If the triviality can be determined without the 7346 /// lookup, skip it. This is intended for use when determining whether a 7347 /// special member of a containing object is trivial, and thus does not ever 7348 /// perform overload resolution for default constructors. 7349 /// 7350 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7351 /// member that was most likely to be intended to be trivial, if any. 7352 /// 7353 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7354 /// determine whether the special member is trivial. 7355 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7356 Sema::CXXSpecialMember CSM, unsigned Quals, 7357 bool ConstRHS, 7358 Sema::TrivialABIHandling TAH, 7359 CXXMethodDecl **Selected) { 7360 if (Selected) 7361 *Selected = nullptr; 7362 7363 switch (CSM) { 7364 case Sema::CXXInvalid: 7365 llvm_unreachable("not a special member"); 7366 7367 case Sema::CXXDefaultConstructor: 7368 // C++11 [class.ctor]p5: 7369 // A default constructor is trivial if: 7370 // - all the [direct subobjects] have trivial default constructors 7371 // 7372 // Note, no overload resolution is performed in this case. 7373 if (RD->hasTrivialDefaultConstructor()) 7374 return true; 7375 7376 if (Selected) { 7377 // If there's a default constructor which could have been trivial, dig it 7378 // out. Otherwise, if there's any user-provided default constructor, point 7379 // to that as an example of why there's not a trivial one. 7380 CXXConstructorDecl *DefCtor = nullptr; 7381 if (RD->needsImplicitDefaultConstructor()) 7382 S.DeclareImplicitDefaultConstructor(RD); 7383 for (auto *CI : RD->ctors()) { 7384 if (!CI->isDefaultConstructor()) 7385 continue; 7386 DefCtor = CI; 7387 if (!DefCtor->isUserProvided()) 7388 break; 7389 } 7390 7391 *Selected = DefCtor; 7392 } 7393 7394 return false; 7395 7396 case Sema::CXXDestructor: 7397 // C++11 [class.dtor]p5: 7398 // A destructor is trivial if: 7399 // - all the direct [subobjects] have trivial destructors 7400 if (RD->hasTrivialDestructor() || 7401 (TAH == Sema::TAH_ConsiderTrivialABI && 7402 RD->hasTrivialDestructorForCall())) 7403 return true; 7404 7405 if (Selected) { 7406 if (RD->needsImplicitDestructor()) 7407 S.DeclareImplicitDestructor(RD); 7408 *Selected = RD->getDestructor(); 7409 } 7410 7411 return false; 7412 7413 case Sema::CXXCopyConstructor: 7414 // C++11 [class.copy]p12: 7415 // A copy constructor is trivial if: 7416 // - the constructor selected to copy each direct [subobject] is trivial 7417 if (RD->hasTrivialCopyConstructor() || 7418 (TAH == Sema::TAH_ConsiderTrivialABI && 7419 RD->hasTrivialCopyConstructorForCall())) { 7420 if (Quals == Qualifiers::Const) 7421 // We must either select the trivial copy constructor or reach an 7422 // ambiguity; no need to actually perform overload resolution. 7423 return true; 7424 } else if (!Selected) { 7425 return false; 7426 } 7427 // In C++98, we are not supposed to perform overload resolution here, but we 7428 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7429 // cases like B as having a non-trivial copy constructor: 7430 // struct A { template<typename T> A(T&); }; 7431 // struct B { mutable A a; }; 7432 goto NeedOverloadResolution; 7433 7434 case Sema::CXXCopyAssignment: 7435 // C++11 [class.copy]p25: 7436 // A copy assignment operator is trivial if: 7437 // - the assignment operator selected to copy each direct [subobject] is 7438 // trivial 7439 if (RD->hasTrivialCopyAssignment()) { 7440 if (Quals == Qualifiers::Const) 7441 return true; 7442 } else if (!Selected) { 7443 return false; 7444 } 7445 // In C++98, we are not supposed to perform overload resolution here, but we 7446 // treat that as a language defect. 7447 goto NeedOverloadResolution; 7448 7449 case Sema::CXXMoveConstructor: 7450 case Sema::CXXMoveAssignment: 7451 NeedOverloadResolution: 7452 Sema::SpecialMemberOverloadResult SMOR = 7453 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7454 7455 // The standard doesn't describe how to behave if the lookup is ambiguous. 7456 // We treat it as not making the member non-trivial, just like the standard 7457 // mandates for the default constructor. This should rarely matter, because 7458 // the member will also be deleted. 7459 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7460 return true; 7461 7462 if (!SMOR.getMethod()) { 7463 assert(SMOR.getKind() == 7464 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7465 return false; 7466 } 7467 7468 // We deliberately don't check if we found a deleted special member. We're 7469 // not supposed to! 7470 if (Selected) 7471 *Selected = SMOR.getMethod(); 7472 7473 if (TAH == Sema::TAH_ConsiderTrivialABI && 7474 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7475 return SMOR.getMethod()->isTrivialForCall(); 7476 return SMOR.getMethod()->isTrivial(); 7477 } 7478 7479 llvm_unreachable("unknown special method kind"); 7480 } 7481 7482 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7483 for (auto *CI : RD->ctors()) 7484 if (!CI->isImplicit()) 7485 return CI; 7486 7487 // Look for constructor templates. 7488 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7489 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7490 if (CXXConstructorDecl *CD = 7491 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7492 return CD; 7493 } 7494 7495 return nullptr; 7496 } 7497 7498 /// The kind of subobject we are checking for triviality. The values of this 7499 /// enumeration are used in diagnostics. 7500 enum TrivialSubobjectKind { 7501 /// The subobject is a base class. 7502 TSK_BaseClass, 7503 /// The subobject is a non-static data member. 7504 TSK_Field, 7505 /// The object is actually the complete object. 7506 TSK_CompleteObject 7507 }; 7508 7509 /// Check whether the special member selected for a given type would be trivial. 7510 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7511 QualType SubType, bool ConstRHS, 7512 Sema::CXXSpecialMember CSM, 7513 TrivialSubobjectKind Kind, 7514 Sema::TrivialABIHandling TAH, bool Diagnose) { 7515 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7516 if (!SubRD) 7517 return true; 7518 7519 CXXMethodDecl *Selected; 7520 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7521 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7522 return true; 7523 7524 if (Diagnose) { 7525 if (ConstRHS) 7526 SubType.addConst(); 7527 7528 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7529 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7530 << Kind << SubType.getUnqualifiedType(); 7531 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7532 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7533 } else if (!Selected) 7534 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7535 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7536 else if (Selected->isUserProvided()) { 7537 if (Kind == TSK_CompleteObject) 7538 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7539 << Kind << SubType.getUnqualifiedType() << CSM; 7540 else { 7541 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7542 << Kind << SubType.getUnqualifiedType() << CSM; 7543 S.Diag(Selected->getLocation(), diag::note_declared_at); 7544 } 7545 } else { 7546 if (Kind != TSK_CompleteObject) 7547 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7548 << Kind << SubType.getUnqualifiedType() << CSM; 7549 7550 // Explain why the defaulted or deleted special member isn't trivial. 7551 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7552 Diagnose); 7553 } 7554 } 7555 7556 return false; 7557 } 7558 7559 /// Check whether the members of a class type allow a special member to be 7560 /// trivial. 7561 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7562 Sema::CXXSpecialMember CSM, 7563 bool ConstArg, 7564 Sema::TrivialABIHandling TAH, 7565 bool Diagnose) { 7566 for (const auto *FI : RD->fields()) { 7567 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7568 continue; 7569 7570 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7571 7572 // Pretend anonymous struct or union members are members of this class. 7573 if (FI->isAnonymousStructOrUnion()) { 7574 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7575 CSM, ConstArg, TAH, Diagnose)) 7576 return false; 7577 continue; 7578 } 7579 7580 // C++11 [class.ctor]p5: 7581 // A default constructor is trivial if [...] 7582 // -- no non-static data member of its class has a 7583 // brace-or-equal-initializer 7584 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7585 if (Diagnose) 7586 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7587 return false; 7588 } 7589 7590 // Objective C ARC 4.3.5: 7591 // [...] nontrivally ownership-qualified types are [...] not trivially 7592 // default constructible, copy constructible, move constructible, copy 7593 // assignable, move assignable, or destructible [...] 7594 if (FieldType.hasNonTrivialObjCLifetime()) { 7595 if (Diagnose) 7596 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7597 << RD << FieldType.getObjCLifetime(); 7598 return false; 7599 } 7600 7601 bool ConstRHS = ConstArg && !FI->isMutable(); 7602 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7603 CSM, TSK_Field, TAH, Diagnose)) 7604 return false; 7605 } 7606 7607 return true; 7608 } 7609 7610 /// Diagnose why the specified class does not have a trivial special member of 7611 /// the given kind. 7612 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7613 QualType Ty = Context.getRecordType(RD); 7614 7615 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7616 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7617 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7618 /*Diagnose*/true); 7619 } 7620 7621 /// Determine whether a defaulted or deleted special member function is trivial, 7622 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7623 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7624 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7625 TrivialABIHandling TAH, bool Diagnose) { 7626 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7627 7628 CXXRecordDecl *RD = MD->getParent(); 7629 7630 bool ConstArg = false; 7631 7632 // C++11 [class.copy]p12, p25: [DR1593] 7633 // A [special member] is trivial if [...] its parameter-type-list is 7634 // equivalent to the parameter-type-list of an implicit declaration [...] 7635 switch (CSM) { 7636 case CXXDefaultConstructor: 7637 case CXXDestructor: 7638 // Trivial default constructors and destructors cannot have parameters. 7639 break; 7640 7641 case CXXCopyConstructor: 7642 case CXXCopyAssignment: { 7643 // Trivial copy operations always have const, non-volatile parameter types. 7644 ConstArg = true; 7645 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7646 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7647 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7648 if (Diagnose) 7649 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7650 << Param0->getSourceRange() << Param0->getType() 7651 << Context.getLValueReferenceType( 7652 Context.getRecordType(RD).withConst()); 7653 return false; 7654 } 7655 break; 7656 } 7657 7658 case CXXMoveConstructor: 7659 case CXXMoveAssignment: { 7660 // Trivial move operations always have non-cv-qualified parameters. 7661 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7662 const RValueReferenceType *RT = 7663 Param0->getType()->getAs<RValueReferenceType>(); 7664 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7665 if (Diagnose) 7666 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7667 << Param0->getSourceRange() << Param0->getType() 7668 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7669 return false; 7670 } 7671 break; 7672 } 7673 7674 case CXXInvalid: 7675 llvm_unreachable("not a special member"); 7676 } 7677 7678 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7679 if (Diagnose) 7680 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7681 diag::note_nontrivial_default_arg) 7682 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7683 return false; 7684 } 7685 if (MD->isVariadic()) { 7686 if (Diagnose) 7687 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7688 return false; 7689 } 7690 7691 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7692 // A copy/move [constructor or assignment operator] is trivial if 7693 // -- the [member] selected to copy/move each direct base class subobject 7694 // is trivial 7695 // 7696 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7697 // A [default constructor or destructor] is trivial if 7698 // -- all the direct base classes have trivial [default constructors or 7699 // destructors] 7700 for (const auto &BI : RD->bases()) 7701 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 7702 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7703 return false; 7704 7705 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7706 // A copy/move [constructor or assignment operator] for a class X is 7707 // trivial if 7708 // -- for each non-static data member of X that is of class type (or array 7709 // thereof), the constructor selected to copy/move that member is 7710 // trivial 7711 // 7712 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7713 // A [default constructor or destructor] is trivial if 7714 // -- for all of the non-static data members of its class that are of class 7715 // type (or array thereof), each such class has a trivial [default 7716 // constructor or destructor] 7717 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7718 return false; 7719 7720 // C++11 [class.dtor]p5: 7721 // A destructor is trivial if [...] 7722 // -- the destructor is not virtual 7723 if (CSM == CXXDestructor && MD->isVirtual()) { 7724 if (Diagnose) 7725 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7726 return false; 7727 } 7728 7729 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7730 // A [special member] for class X is trivial if [...] 7731 // -- class X has no virtual functions and no virtual base classes 7732 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7733 if (!Diagnose) 7734 return false; 7735 7736 if (RD->getNumVBases()) { 7737 // Check for virtual bases. We already know that the corresponding 7738 // member in all bases is trivial, so vbases must all be direct. 7739 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7740 assert(BS.isVirtual()); 7741 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 7742 return false; 7743 } 7744 7745 // Must have a virtual method. 7746 for (const auto *MI : RD->methods()) { 7747 if (MI->isVirtual()) { 7748 SourceLocation MLoc = MI->getBeginLoc(); 7749 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7750 return false; 7751 } 7752 } 7753 7754 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7755 } 7756 7757 // Looks like it's trivial! 7758 return true; 7759 } 7760 7761 namespace { 7762 struct FindHiddenVirtualMethod { 7763 Sema *S; 7764 CXXMethodDecl *Method; 7765 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7766 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7767 7768 private: 7769 /// Check whether any most overridden method from MD in Methods 7770 static bool CheckMostOverridenMethods( 7771 const CXXMethodDecl *MD, 7772 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7773 if (MD->size_overridden_methods() == 0) 7774 return Methods.count(MD->getCanonicalDecl()); 7775 for (const CXXMethodDecl *O : MD->overridden_methods()) 7776 if (CheckMostOverridenMethods(O, Methods)) 7777 return true; 7778 return false; 7779 } 7780 7781 public: 7782 /// Member lookup function that determines whether a given C++ 7783 /// method overloads virtual methods in a base class without overriding any, 7784 /// to be used with CXXRecordDecl::lookupInBases(). 7785 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7786 RecordDecl *BaseRecord = 7787 Specifier->getType()->getAs<RecordType>()->getDecl(); 7788 7789 DeclarationName Name = Method->getDeclName(); 7790 assert(Name.getNameKind() == DeclarationName::Identifier); 7791 7792 bool foundSameNameMethod = false; 7793 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7794 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7795 Path.Decls = Path.Decls.slice(1)) { 7796 NamedDecl *D = Path.Decls.front(); 7797 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7798 MD = MD->getCanonicalDecl(); 7799 foundSameNameMethod = true; 7800 // Interested only in hidden virtual methods. 7801 if (!MD->isVirtual()) 7802 continue; 7803 // If the method we are checking overrides a method from its base 7804 // don't warn about the other overloaded methods. Clang deviates from 7805 // GCC by only diagnosing overloads of inherited virtual functions that 7806 // do not override any other virtual functions in the base. GCC's 7807 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7808 // function from a base class. These cases may be better served by a 7809 // warning (not specific to virtual functions) on call sites when the 7810 // call would select a different function from the base class, were it 7811 // visible. 7812 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7813 if (!S->IsOverload(Method, MD, false)) 7814 return true; 7815 // Collect the overload only if its hidden. 7816 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7817 overloadedMethods.push_back(MD); 7818 } 7819 } 7820 7821 if (foundSameNameMethod) 7822 OverloadedMethods.append(overloadedMethods.begin(), 7823 overloadedMethods.end()); 7824 return foundSameNameMethod; 7825 } 7826 }; 7827 } // end anonymous namespace 7828 7829 /// Add the most overriden methods from MD to Methods 7830 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7831 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7832 if (MD->size_overridden_methods() == 0) 7833 Methods.insert(MD->getCanonicalDecl()); 7834 else 7835 for (const CXXMethodDecl *O : MD->overridden_methods()) 7836 AddMostOverridenMethods(O, Methods); 7837 } 7838 7839 /// Check if a method overloads virtual methods in a base class without 7840 /// overriding any. 7841 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7842 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7843 if (!MD->getDeclName().isIdentifier()) 7844 return; 7845 7846 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7847 /*bool RecordPaths=*/false, 7848 /*bool DetectVirtual=*/false); 7849 FindHiddenVirtualMethod FHVM; 7850 FHVM.Method = MD; 7851 FHVM.S = this; 7852 7853 // Keep the base methods that were overridden or introduced in the subclass 7854 // by 'using' in a set. A base method not in this set is hidden. 7855 CXXRecordDecl *DC = MD->getParent(); 7856 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7857 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7858 NamedDecl *ND = *I; 7859 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7860 ND = shad->getTargetDecl(); 7861 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7862 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7863 } 7864 7865 if (DC->lookupInBases(FHVM, Paths)) 7866 OverloadedMethods = FHVM.OverloadedMethods; 7867 } 7868 7869 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7870 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7871 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7872 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7873 PartialDiagnostic PD = PDiag( 7874 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7875 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7876 Diag(overloadedMD->getLocation(), PD); 7877 } 7878 } 7879 7880 /// Diagnose methods which overload virtual methods in a base class 7881 /// without overriding any. 7882 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7883 if (MD->isInvalidDecl()) 7884 return; 7885 7886 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7887 return; 7888 7889 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7890 FindHiddenVirtualMethods(MD, OverloadedMethods); 7891 if (!OverloadedMethods.empty()) { 7892 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7893 << MD << (OverloadedMethods.size() > 1); 7894 7895 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7896 } 7897 } 7898 7899 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 7900 auto PrintDiagAndRemoveAttr = [&]() { 7901 // No diagnostics if this is a template instantiation. 7902 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 7903 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 7904 diag::ext_cannot_use_trivial_abi) << &RD; 7905 RD.dropAttr<TrivialABIAttr>(); 7906 }; 7907 7908 // Ill-formed if the struct has virtual functions. 7909 if (RD.isPolymorphic()) { 7910 PrintDiagAndRemoveAttr(); 7911 return; 7912 } 7913 7914 for (const auto &B : RD.bases()) { 7915 // Ill-formed if the base class is non-trivial for the purpose of calls or a 7916 // virtual base. 7917 if ((!B.getType()->isDependentType() && 7918 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 7919 B.isVirtual()) { 7920 PrintDiagAndRemoveAttr(); 7921 return; 7922 } 7923 } 7924 7925 for (const auto *FD : RD.fields()) { 7926 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 7927 // non-trivial for the purpose of calls. 7928 QualType FT = FD->getType(); 7929 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 7930 PrintDiagAndRemoveAttr(); 7931 return; 7932 } 7933 7934 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 7935 if (!RT->isDependentType() && 7936 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 7937 PrintDiagAndRemoveAttr(); 7938 return; 7939 } 7940 } 7941 } 7942 7943 void Sema::ActOnFinishCXXMemberSpecification( 7944 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 7945 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 7946 if (!TagDecl) 7947 return; 7948 7949 AdjustDeclIfTemplate(TagDecl); 7950 7951 for (const ParsedAttr &AL : AttrList) { 7952 if (AL.getKind() != ParsedAttr::AT_Visibility) 7953 continue; 7954 AL.setInvalid(); 7955 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) 7956 << AL.getName(); 7957 } 7958 7959 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7960 // strict aliasing violation! 7961 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7962 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7963 7964 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); 7965 } 7966 7967 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7968 /// special functions, such as the default constructor, copy 7969 /// constructor, or destructor, to the given C++ class (C++ 7970 /// [special]p1). This routine can only be executed just before the 7971 /// definition of the class is complete. 7972 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7973 if (ClassDecl->needsImplicitDefaultConstructor()) { 7974 ++ASTContext::NumImplicitDefaultConstructors; 7975 7976 if (ClassDecl->hasInheritedConstructor()) 7977 DeclareImplicitDefaultConstructor(ClassDecl); 7978 } 7979 7980 if (ClassDecl->needsImplicitCopyConstructor()) { 7981 ++ASTContext::NumImplicitCopyConstructors; 7982 7983 // If the properties or semantics of the copy constructor couldn't be 7984 // determined while the class was being declared, force a declaration 7985 // of it now. 7986 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7987 ClassDecl->hasInheritedConstructor()) 7988 DeclareImplicitCopyConstructor(ClassDecl); 7989 // For the MS ABI we need to know whether the copy ctor is deleted. A 7990 // prerequisite for deleting the implicit copy ctor is that the class has a 7991 // move ctor or move assignment that is either user-declared or whose 7992 // semantics are inherited from a subobject. FIXME: We should provide a more 7993 // direct way for CodeGen to ask whether the constructor was deleted. 7994 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7995 (ClassDecl->hasUserDeclaredMoveConstructor() || 7996 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7997 ClassDecl->hasUserDeclaredMoveAssignment() || 7998 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7999 DeclareImplicitCopyConstructor(ClassDecl); 8000 } 8001 8002 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 8003 ++ASTContext::NumImplicitMoveConstructors; 8004 8005 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 8006 ClassDecl->hasInheritedConstructor()) 8007 DeclareImplicitMoveConstructor(ClassDecl); 8008 } 8009 8010 if (ClassDecl->needsImplicitCopyAssignment()) { 8011 ++ASTContext::NumImplicitCopyAssignmentOperators; 8012 8013 // If we have a dynamic class, then the copy assignment operator may be 8014 // virtual, so we have to declare it immediately. This ensures that, e.g., 8015 // it shows up in the right place in the vtable and that we diagnose 8016 // problems with the implicit exception specification. 8017 if (ClassDecl->isDynamicClass() || 8018 ClassDecl->needsOverloadResolutionForCopyAssignment() || 8019 ClassDecl->hasInheritedAssignment()) 8020 DeclareImplicitCopyAssignment(ClassDecl); 8021 } 8022 8023 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 8024 ++ASTContext::NumImplicitMoveAssignmentOperators; 8025 8026 // Likewise for the move assignment operator. 8027 if (ClassDecl->isDynamicClass() || 8028 ClassDecl->needsOverloadResolutionForMoveAssignment() || 8029 ClassDecl->hasInheritedAssignment()) 8030 DeclareImplicitMoveAssignment(ClassDecl); 8031 } 8032 8033 if (ClassDecl->needsImplicitDestructor()) { 8034 ++ASTContext::NumImplicitDestructors; 8035 8036 // If we have a dynamic class, then the destructor may be virtual, so we 8037 // have to declare the destructor immediately. This ensures that, e.g., it 8038 // shows up in the right place in the vtable and that we diagnose problems 8039 // with the implicit exception specification. 8040 if (ClassDecl->isDynamicClass() || 8041 ClassDecl->needsOverloadResolutionForDestructor()) 8042 DeclareImplicitDestructor(ClassDecl); 8043 } 8044 } 8045 8046 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 8047 if (!D) 8048 return 0; 8049 8050 // The order of template parameters is not important here. All names 8051 // get added to the same scope. 8052 SmallVector<TemplateParameterList *, 4> ParameterLists; 8053 8054 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8055 D = TD->getTemplatedDecl(); 8056 8057 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 8058 ParameterLists.push_back(PSD->getTemplateParameters()); 8059 8060 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 8061 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 8062 ParameterLists.push_back(DD->getTemplateParameterList(i)); 8063 8064 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8065 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 8066 ParameterLists.push_back(FTD->getTemplateParameters()); 8067 } 8068 } 8069 8070 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 8071 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 8072 ParameterLists.push_back(TD->getTemplateParameterList(i)); 8073 8074 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 8075 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 8076 ParameterLists.push_back(CTD->getTemplateParameters()); 8077 } 8078 } 8079 8080 unsigned Count = 0; 8081 for (TemplateParameterList *Params : ParameterLists) { 8082 if (Params->size() > 0) 8083 // Ignore explicit specializations; they don't contribute to the template 8084 // depth. 8085 ++Count; 8086 for (NamedDecl *Param : *Params) { 8087 if (Param->getDeclName()) { 8088 S->AddDecl(Param); 8089 IdResolver.AddDecl(Param); 8090 } 8091 } 8092 } 8093 8094 return Count; 8095 } 8096 8097 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8098 if (!RecordD) return; 8099 AdjustDeclIfTemplate(RecordD); 8100 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 8101 PushDeclContext(S, Record); 8102 } 8103 8104 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8105 if (!RecordD) return; 8106 PopDeclContext(); 8107 } 8108 8109 /// This is used to implement the constant expression evaluation part of the 8110 /// attribute enable_if extension. There is nothing in standard C++ which would 8111 /// require reentering parameters. 8112 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 8113 if (!Param) 8114 return; 8115 8116 S->AddDecl(Param); 8117 if (Param->getDeclName()) 8118 IdResolver.AddDecl(Param); 8119 } 8120 8121 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 8122 /// parsing a top-level (non-nested) C++ class, and we are now 8123 /// parsing those parts of the given Method declaration that could 8124 /// not be parsed earlier (C++ [class.mem]p2), such as default 8125 /// arguments. This action should enter the scope of the given 8126 /// Method declaration as if we had just parsed the qualified method 8127 /// name. However, it should not bring the parameters into scope; 8128 /// that will be performed by ActOnDelayedCXXMethodParameter. 8129 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8130 } 8131 8132 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 8133 /// C++ method declaration. We're (re-)introducing the given 8134 /// function parameter into scope for use in parsing later parts of 8135 /// the method declaration. For example, we could see an 8136 /// ActOnParamDefaultArgument event for this parameter. 8137 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 8138 if (!ParamD) 8139 return; 8140 8141 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 8142 8143 // If this parameter has an unparsed default argument, clear it out 8144 // to make way for the parsed default argument. 8145 if (Param->hasUnparsedDefaultArg()) 8146 Param->setDefaultArg(nullptr); 8147 8148 S->AddDecl(Param); 8149 if (Param->getDeclName()) 8150 IdResolver.AddDecl(Param); 8151 } 8152 8153 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8154 /// processing the delayed method declaration for Method. The method 8155 /// declaration is now considered finished. There may be a separate 8156 /// ActOnStartOfFunctionDef action later (not necessarily 8157 /// immediately!) for this method, if it was also defined inside the 8158 /// class body. 8159 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8160 if (!MethodD) 8161 return; 8162 8163 AdjustDeclIfTemplate(MethodD); 8164 8165 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8166 8167 // Now that we have our default arguments, check the constructor 8168 // again. It could produce additional diagnostics or affect whether 8169 // the class has implicitly-declared destructors, among other 8170 // things. 8171 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8172 CheckConstructor(Constructor); 8173 8174 // Check the default arguments, which we may have added. 8175 if (!Method->isInvalidDecl()) 8176 CheckCXXDefaultArguments(Method); 8177 } 8178 8179 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8180 /// the well-formedness of the constructor declarator @p D with type @p 8181 /// R. If there are any errors in the declarator, this routine will 8182 /// emit diagnostics and set the invalid bit to true. In any case, the type 8183 /// will be updated to reflect a well-formed type for the constructor and 8184 /// returned. 8185 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8186 StorageClass &SC) { 8187 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8188 8189 // C++ [class.ctor]p3: 8190 // A constructor shall not be virtual (10.3) or static (9.4). A 8191 // constructor can be invoked for a const, volatile or const 8192 // volatile object. A constructor shall not be declared const, 8193 // volatile, or const volatile (9.3.2). 8194 if (isVirtual) { 8195 if (!D.isInvalidType()) 8196 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8197 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8198 << SourceRange(D.getIdentifierLoc()); 8199 D.setInvalidType(); 8200 } 8201 if (SC == SC_Static) { 8202 if (!D.isInvalidType()) 8203 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8204 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8205 << SourceRange(D.getIdentifierLoc()); 8206 D.setInvalidType(); 8207 SC = SC_None; 8208 } 8209 8210 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8211 diagnoseIgnoredQualifiers( 8212 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8213 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8214 D.getDeclSpec().getRestrictSpecLoc(), 8215 D.getDeclSpec().getAtomicSpecLoc()); 8216 D.setInvalidType(); 8217 } 8218 8219 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8220 if (FTI.hasMethodTypeQualifiers()) { 8221 FTI.MethodQualifiers->forEachQualifier( 8222 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { 8223 Diag(SL, diag::err_invalid_qualified_constructor) 8224 << QualName << SourceRange(SL); 8225 }); 8226 D.setInvalidType(); 8227 } 8228 8229 // C++0x [class.ctor]p4: 8230 // A constructor shall not be declared with a ref-qualifier. 8231 if (FTI.hasRefQualifier()) { 8232 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8233 << FTI.RefQualifierIsLValueRef 8234 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8235 D.setInvalidType(); 8236 } 8237 8238 // Rebuild the function type "R" without any type qualifiers (in 8239 // case any of the errors above fired) and with "void" as the 8240 // return type, since constructors don't have return types. 8241 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8242 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8243 return R; 8244 8245 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8246 EPI.TypeQuals = Qualifiers(); 8247 EPI.RefQualifier = RQ_None; 8248 8249 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8250 } 8251 8252 /// CheckConstructor - Checks a fully-formed constructor for 8253 /// well-formedness, issuing any diagnostics required. Returns true if 8254 /// the constructor declarator is invalid. 8255 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8256 CXXRecordDecl *ClassDecl 8257 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8258 if (!ClassDecl) 8259 return Constructor->setInvalidDecl(); 8260 8261 // C++ [class.copy]p3: 8262 // A declaration of a constructor for a class X is ill-formed if 8263 // its first parameter is of type (optionally cv-qualified) X and 8264 // either there are no other parameters or else all other 8265 // parameters have default arguments. 8266 if (!Constructor->isInvalidDecl() && 8267 ((Constructor->getNumParams() == 1) || 8268 (Constructor->getNumParams() > 1 && 8269 Constructor->getParamDecl(1)->hasDefaultArg())) && 8270 Constructor->getTemplateSpecializationKind() 8271 != TSK_ImplicitInstantiation) { 8272 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8273 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8274 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8275 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8276 const char *ConstRef 8277 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8278 : " const &"; 8279 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8280 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8281 8282 // FIXME: Rather that making the constructor invalid, we should endeavor 8283 // to fix the type. 8284 Constructor->setInvalidDecl(); 8285 } 8286 } 8287 } 8288 8289 /// CheckDestructor - Checks a fully-formed destructor definition for 8290 /// well-formedness, issuing any diagnostics required. Returns true 8291 /// on error. 8292 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8293 CXXRecordDecl *RD = Destructor->getParent(); 8294 8295 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8296 SourceLocation Loc; 8297 8298 if (!Destructor->isImplicit()) 8299 Loc = Destructor->getLocation(); 8300 else 8301 Loc = RD->getLocation(); 8302 8303 // If we have a virtual destructor, look up the deallocation function 8304 if (FunctionDecl *OperatorDelete = 8305 FindDeallocationFunctionForDestructor(Loc, RD)) { 8306 Expr *ThisArg = nullptr; 8307 8308 // If the notional 'delete this' expression requires a non-trivial 8309 // conversion from 'this' to the type of a destroying operator delete's 8310 // first parameter, perform that conversion now. 8311 if (OperatorDelete->isDestroyingOperatorDelete()) { 8312 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8313 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8314 // C++ [class.dtor]p13: 8315 // ... as if for the expression 'delete this' appearing in a 8316 // non-virtual destructor of the destructor's class. 8317 ContextRAII SwitchContext(*this, Destructor); 8318 ExprResult This = 8319 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8320 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8321 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8322 if (This.isInvalid()) { 8323 // FIXME: Register this as a context note so that it comes out 8324 // in the right order. 8325 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8326 return true; 8327 } 8328 ThisArg = This.get(); 8329 } 8330 } 8331 8332 DiagnoseUseOfDecl(OperatorDelete, Loc); 8333 MarkFunctionReferenced(Loc, OperatorDelete); 8334 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8335 } 8336 } 8337 8338 return false; 8339 } 8340 8341 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8342 /// the well-formednes of the destructor declarator @p D with type @p 8343 /// R. If there are any errors in the declarator, this routine will 8344 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8345 /// will be updated to reflect a well-formed type for the destructor and 8346 /// returned. 8347 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8348 StorageClass& SC) { 8349 // C++ [class.dtor]p1: 8350 // [...] A typedef-name that names a class is a class-name 8351 // (7.1.3); however, a typedef-name that names a class shall not 8352 // be used as the identifier in the declarator for a destructor 8353 // declaration. 8354 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8355 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8356 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8357 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8358 else if (const TemplateSpecializationType *TST = 8359 DeclaratorType->getAs<TemplateSpecializationType>()) 8360 if (TST->isTypeAlias()) 8361 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8362 << DeclaratorType << 1; 8363 8364 // C++ [class.dtor]p2: 8365 // A destructor is used to destroy objects of its class type. A 8366 // destructor takes no parameters, and no return type can be 8367 // specified for it (not even void). The address of a destructor 8368 // shall not be taken. A destructor shall not be static. A 8369 // destructor can be invoked for a const, volatile or const 8370 // volatile object. A destructor shall not be declared const, 8371 // volatile or const volatile (9.3.2). 8372 if (SC == SC_Static) { 8373 if (!D.isInvalidType()) 8374 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8375 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8376 << SourceRange(D.getIdentifierLoc()) 8377 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8378 8379 SC = SC_None; 8380 } 8381 if (!D.isInvalidType()) { 8382 // Destructors don't have return types, but the parser will 8383 // happily parse something like: 8384 // 8385 // class X { 8386 // float ~X(); 8387 // }; 8388 // 8389 // The return type will be eliminated later. 8390 if (D.getDeclSpec().hasTypeSpecifier()) 8391 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8392 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8393 << SourceRange(D.getIdentifierLoc()); 8394 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8395 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8396 SourceLocation(), 8397 D.getDeclSpec().getConstSpecLoc(), 8398 D.getDeclSpec().getVolatileSpecLoc(), 8399 D.getDeclSpec().getRestrictSpecLoc(), 8400 D.getDeclSpec().getAtomicSpecLoc()); 8401 D.setInvalidType(); 8402 } 8403 } 8404 8405 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8406 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 8407 FTI.MethodQualifiers->forEachQualifier( 8408 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { 8409 Diag(SL, diag::err_invalid_qualified_destructor) 8410 << QualName << SourceRange(SL); 8411 }); 8412 D.setInvalidType(); 8413 } 8414 8415 // C++0x [class.dtor]p2: 8416 // A destructor shall not be declared with a ref-qualifier. 8417 if (FTI.hasRefQualifier()) { 8418 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8419 << FTI.RefQualifierIsLValueRef 8420 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8421 D.setInvalidType(); 8422 } 8423 8424 // Make sure we don't have any parameters. 8425 if (FTIHasNonVoidParameters(FTI)) { 8426 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8427 8428 // Delete the parameters. 8429 FTI.freeParams(); 8430 D.setInvalidType(); 8431 } 8432 8433 // Make sure the destructor isn't variadic. 8434 if (FTI.isVariadic) { 8435 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8436 D.setInvalidType(); 8437 } 8438 8439 // Rebuild the function type "R" without any type qualifiers or 8440 // parameters (in case any of the errors above fired) and with 8441 // "void" as the return type, since destructors don't have return 8442 // types. 8443 if (!D.isInvalidType()) 8444 return R; 8445 8446 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8447 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8448 EPI.Variadic = false; 8449 EPI.TypeQuals = Qualifiers(); 8450 EPI.RefQualifier = RQ_None; 8451 return Context.getFunctionType(Context.VoidTy, None, EPI); 8452 } 8453 8454 static void extendLeft(SourceRange &R, SourceRange Before) { 8455 if (Before.isInvalid()) 8456 return; 8457 R.setBegin(Before.getBegin()); 8458 if (R.getEnd().isInvalid()) 8459 R.setEnd(Before.getEnd()); 8460 } 8461 8462 static void extendRight(SourceRange &R, SourceRange After) { 8463 if (After.isInvalid()) 8464 return; 8465 if (R.getBegin().isInvalid()) 8466 R.setBegin(After.getBegin()); 8467 R.setEnd(After.getEnd()); 8468 } 8469 8470 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8471 /// well-formednes of the conversion function declarator @p D with 8472 /// type @p R. If there are any errors in the declarator, this routine 8473 /// will emit diagnostics and return true. Otherwise, it will return 8474 /// false. Either way, the type @p R will be updated to reflect a 8475 /// well-formed type for the conversion operator. 8476 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8477 StorageClass& SC) { 8478 // C++ [class.conv.fct]p1: 8479 // Neither parameter types nor return type can be specified. The 8480 // type of a conversion function (8.3.5) is "function taking no 8481 // parameter returning conversion-type-id." 8482 if (SC == SC_Static) { 8483 if (!D.isInvalidType()) 8484 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8485 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8486 << D.getName().getSourceRange(); 8487 D.setInvalidType(); 8488 SC = SC_None; 8489 } 8490 8491 TypeSourceInfo *ConvTSI = nullptr; 8492 QualType ConvType = 8493 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8494 8495 const DeclSpec &DS = D.getDeclSpec(); 8496 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8497 // Conversion functions don't have return types, but the parser will 8498 // happily parse something like: 8499 // 8500 // class X { 8501 // float operator bool(); 8502 // }; 8503 // 8504 // The return type will be changed later anyway. 8505 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8506 << SourceRange(DS.getTypeSpecTypeLoc()) 8507 << SourceRange(D.getIdentifierLoc()); 8508 D.setInvalidType(); 8509 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8510 // It's also plausible that the user writes type qualifiers in the wrong 8511 // place, such as: 8512 // struct S { const operator int(); }; 8513 // FIXME: we could provide a fixit to move the qualifiers onto the 8514 // conversion type. 8515 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8516 << SourceRange(D.getIdentifierLoc()) << 0; 8517 D.setInvalidType(); 8518 } 8519 8520 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8521 8522 // Make sure we don't have any parameters. 8523 if (Proto->getNumParams() > 0) { 8524 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8525 8526 // Delete the parameters. 8527 D.getFunctionTypeInfo().freeParams(); 8528 D.setInvalidType(); 8529 } else if (Proto->isVariadic()) { 8530 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8531 D.setInvalidType(); 8532 } 8533 8534 // Diagnose "&operator bool()" and other such nonsense. This 8535 // is actually a gcc extension which we don't support. 8536 if (Proto->getReturnType() != ConvType) { 8537 bool NeedsTypedef = false; 8538 SourceRange Before, After; 8539 8540 // Walk the chunks and extract information on them for our diagnostic. 8541 bool PastFunctionChunk = false; 8542 for (auto &Chunk : D.type_objects()) { 8543 switch (Chunk.Kind) { 8544 case DeclaratorChunk::Function: 8545 if (!PastFunctionChunk) { 8546 if (Chunk.Fun.HasTrailingReturnType) { 8547 TypeSourceInfo *TRT = nullptr; 8548 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8549 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8550 } 8551 PastFunctionChunk = true; 8552 break; 8553 } 8554 LLVM_FALLTHROUGH; 8555 case DeclaratorChunk::Array: 8556 NeedsTypedef = true; 8557 extendRight(After, Chunk.getSourceRange()); 8558 break; 8559 8560 case DeclaratorChunk::Pointer: 8561 case DeclaratorChunk::BlockPointer: 8562 case DeclaratorChunk::Reference: 8563 case DeclaratorChunk::MemberPointer: 8564 case DeclaratorChunk::Pipe: 8565 extendLeft(Before, Chunk.getSourceRange()); 8566 break; 8567 8568 case DeclaratorChunk::Paren: 8569 extendLeft(Before, Chunk.Loc); 8570 extendRight(After, Chunk.EndLoc); 8571 break; 8572 } 8573 } 8574 8575 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8576 After.isValid() ? After.getBegin() : 8577 D.getIdentifierLoc(); 8578 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8579 DB << Before << After; 8580 8581 if (!NeedsTypedef) { 8582 DB << /*don't need a typedef*/0; 8583 8584 // If we can provide a correct fix-it hint, do so. 8585 if (After.isInvalid() && ConvTSI) { 8586 SourceLocation InsertLoc = 8587 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 8588 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8589 << FixItHint::CreateInsertionFromRange( 8590 InsertLoc, CharSourceRange::getTokenRange(Before)) 8591 << FixItHint::CreateRemoval(Before); 8592 } 8593 } else if (!Proto->getReturnType()->isDependentType()) { 8594 DB << /*typedef*/1 << Proto->getReturnType(); 8595 } else if (getLangOpts().CPlusPlus11) { 8596 DB << /*alias template*/2 << Proto->getReturnType(); 8597 } else { 8598 DB << /*might not be fixable*/3; 8599 } 8600 8601 // Recover by incorporating the other type chunks into the result type. 8602 // Note, this does *not* change the name of the function. This is compatible 8603 // with the GCC extension: 8604 // struct S { &operator int(); } s; 8605 // int &r = s.operator int(); // ok in GCC 8606 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8607 ConvType = Proto->getReturnType(); 8608 } 8609 8610 // C++ [class.conv.fct]p4: 8611 // The conversion-type-id shall not represent a function type nor 8612 // an array type. 8613 if (ConvType->isArrayType()) { 8614 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8615 ConvType = Context.getPointerType(ConvType); 8616 D.setInvalidType(); 8617 } else if (ConvType->isFunctionType()) { 8618 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8619 ConvType = Context.getPointerType(ConvType); 8620 D.setInvalidType(); 8621 } 8622 8623 // Rebuild the function type "R" without any parameters (in case any 8624 // of the errors above fired) and with the conversion type as the 8625 // return type. 8626 if (D.isInvalidType()) 8627 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8628 8629 // C++0x explicit conversion operators. 8630 if (DS.isExplicitSpecified()) 8631 Diag(DS.getExplicitSpecLoc(), 8632 getLangOpts().CPlusPlus11 8633 ? diag::warn_cxx98_compat_explicit_conversion_functions 8634 : diag::ext_explicit_conversion_functions) 8635 << SourceRange(DS.getExplicitSpecLoc()); 8636 } 8637 8638 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8639 /// the declaration of the given C++ conversion function. This routine 8640 /// is responsible for recording the conversion function in the C++ 8641 /// class, if possible. 8642 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8643 assert(Conversion && "Expected to receive a conversion function declaration"); 8644 8645 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8646 8647 // Make sure we aren't redeclaring the conversion function. 8648 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8649 8650 // C++ [class.conv.fct]p1: 8651 // [...] A conversion function is never used to convert a 8652 // (possibly cv-qualified) object to the (possibly cv-qualified) 8653 // same object type (or a reference to it), to a (possibly 8654 // cv-qualified) base class of that type (or a reference to it), 8655 // or to (possibly cv-qualified) void. 8656 // FIXME: Suppress this warning if the conversion function ends up being a 8657 // virtual function that overrides a virtual function in a base class. 8658 QualType ClassType 8659 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8660 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8661 ConvType = ConvTypeRef->getPointeeType(); 8662 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8663 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8664 /* Suppress diagnostics for instantiations. */; 8665 else if (ConvType->isRecordType()) { 8666 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8667 if (ConvType == ClassType) 8668 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8669 << ClassType; 8670 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8671 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8672 << ClassType << ConvType; 8673 } else if (ConvType->isVoidType()) { 8674 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8675 << ClassType << ConvType; 8676 } 8677 8678 if (FunctionTemplateDecl *ConversionTemplate 8679 = Conversion->getDescribedFunctionTemplate()) 8680 return ConversionTemplate; 8681 8682 return Conversion; 8683 } 8684 8685 namespace { 8686 /// Utility class to accumulate and print a diagnostic listing the invalid 8687 /// specifier(s) on a declaration. 8688 struct BadSpecifierDiagnoser { 8689 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8690 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8691 ~BadSpecifierDiagnoser() { 8692 Diagnostic << Specifiers; 8693 } 8694 8695 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8696 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8697 } 8698 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8699 return check(SpecLoc, 8700 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8701 } 8702 void check(SourceLocation SpecLoc, const char *Spec) { 8703 if (SpecLoc.isInvalid()) return; 8704 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8705 if (!Specifiers.empty()) Specifiers += " "; 8706 Specifiers += Spec; 8707 } 8708 8709 Sema &S; 8710 Sema::SemaDiagnosticBuilder Diagnostic; 8711 std::string Specifiers; 8712 }; 8713 } 8714 8715 /// Check the validity of a declarator that we parsed for a deduction-guide. 8716 /// These aren't actually declarators in the grammar, so we need to check that 8717 /// the user didn't specify any pieces that are not part of the deduction-guide 8718 /// grammar. 8719 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8720 StorageClass &SC) { 8721 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8722 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8723 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8724 8725 // C++ [temp.deduct.guide]p3: 8726 // A deduction-gide shall be declared in the same scope as the 8727 // corresponding class template. 8728 if (!CurContext->getRedeclContext()->Equals( 8729 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8730 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8731 << GuidedTemplateDecl; 8732 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8733 } 8734 8735 auto &DS = D.getMutableDeclSpec(); 8736 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8737 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8738 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8739 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8740 BadSpecifierDiagnoser Diagnoser( 8741 *this, D.getIdentifierLoc(), 8742 diag::err_deduction_guide_invalid_specifier); 8743 8744 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8745 DS.ClearStorageClassSpecs(); 8746 SC = SC_None; 8747 8748 // 'explicit' is permitted. 8749 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8750 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8751 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8752 DS.ClearConstexprSpec(); 8753 8754 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8755 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8756 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8757 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8758 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8759 DS.ClearTypeQualifiers(); 8760 8761 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8762 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8763 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8764 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8765 DS.ClearTypeSpecType(); 8766 } 8767 8768 if (D.isInvalidType()) 8769 return; 8770 8771 // Check the declarator is simple enough. 8772 bool FoundFunction = false; 8773 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8774 if (Chunk.Kind == DeclaratorChunk::Paren) 8775 continue; 8776 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8777 Diag(D.getDeclSpec().getBeginLoc(), 8778 diag::err_deduction_guide_with_complex_decl) 8779 << D.getSourceRange(); 8780 break; 8781 } 8782 if (!Chunk.Fun.hasTrailingReturnType()) { 8783 Diag(D.getName().getBeginLoc(), 8784 diag::err_deduction_guide_no_trailing_return_type); 8785 break; 8786 } 8787 8788 // Check that the return type is written as a specialization of 8789 // the template specified as the deduction-guide's name. 8790 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8791 TypeSourceInfo *TSI = nullptr; 8792 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8793 assert(TSI && "deduction guide has valid type but invalid return type?"); 8794 bool AcceptableReturnType = false; 8795 bool MightInstantiateToSpecialization = false; 8796 if (auto RetTST = 8797 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8798 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8799 bool TemplateMatches = 8800 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8801 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8802 AcceptableReturnType = true; 8803 else { 8804 // This could still instantiate to the right type, unless we know it 8805 // names the wrong class template. 8806 auto *TD = SpecifiedName.getAsTemplateDecl(); 8807 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8808 !TemplateMatches); 8809 } 8810 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8811 MightInstantiateToSpecialization = true; 8812 } 8813 8814 if (!AcceptableReturnType) { 8815 Diag(TSI->getTypeLoc().getBeginLoc(), 8816 diag::err_deduction_guide_bad_trailing_return_type) 8817 << GuidedTemplate << TSI->getType() 8818 << MightInstantiateToSpecialization 8819 << TSI->getTypeLoc().getSourceRange(); 8820 } 8821 8822 // Keep going to check that we don't have any inner declarator pieces (we 8823 // could still have a function returning a pointer to a function). 8824 FoundFunction = true; 8825 } 8826 8827 if (D.isFunctionDefinition()) 8828 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8829 } 8830 8831 //===----------------------------------------------------------------------===// 8832 // Namespace Handling 8833 //===----------------------------------------------------------------------===// 8834 8835 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 8836 /// reopened. 8837 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8838 SourceLocation Loc, 8839 IdentifierInfo *II, bool *IsInline, 8840 NamespaceDecl *PrevNS) { 8841 assert(*IsInline != PrevNS->isInline()); 8842 8843 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8844 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8845 // inline namespaces, with the intention of bringing names into namespace std. 8846 // 8847 // We support this just well enough to get that case working; this is not 8848 // sufficient to support reopening namespaces as inline in general. 8849 if (*IsInline && II && II->getName().startswith("__atomic") && 8850 S.getSourceManager().isInSystemHeader(Loc)) { 8851 // Mark all prior declarations of the namespace as inline. 8852 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8853 NS = NS->getPreviousDecl()) 8854 NS->setInline(*IsInline); 8855 // Patch up the lookup table for the containing namespace. This isn't really 8856 // correct, but it's good enough for this particular case. 8857 for (auto *I : PrevNS->decls()) 8858 if (auto *ND = dyn_cast<NamedDecl>(I)) 8859 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8860 return; 8861 } 8862 8863 if (PrevNS->isInline()) 8864 // The user probably just forgot the 'inline', so suggest that it 8865 // be added back. 8866 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8867 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8868 else 8869 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8870 8871 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8872 *IsInline = PrevNS->isInline(); 8873 } 8874 8875 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8876 /// definition. 8877 Decl *Sema::ActOnStartNamespaceDef( 8878 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 8879 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 8880 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 8881 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8882 // For anonymous namespace, take the location of the left brace. 8883 SourceLocation Loc = II ? IdentLoc : LBrace; 8884 bool IsInline = InlineLoc.isValid(); 8885 bool IsInvalid = false; 8886 bool IsStd = false; 8887 bool AddToKnown = false; 8888 Scope *DeclRegionScope = NamespcScope->getParent(); 8889 8890 NamespaceDecl *PrevNS = nullptr; 8891 if (II) { 8892 // C++ [namespace.def]p2: 8893 // The identifier in an original-namespace-definition shall not 8894 // have been previously defined in the declarative region in 8895 // which the original-namespace-definition appears. The 8896 // identifier in an original-namespace-definition is the name of 8897 // the namespace. Subsequently in that declarative region, it is 8898 // treated as an original-namespace-name. 8899 // 8900 // Since namespace names are unique in their scope, and we don't 8901 // look through using directives, just look for any ordinary names 8902 // as if by qualified name lookup. 8903 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8904 ForExternalRedeclaration); 8905 LookupQualifiedName(R, CurContext->getRedeclContext()); 8906 NamedDecl *PrevDecl = 8907 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8908 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8909 8910 if (PrevNS) { 8911 // This is an extended namespace definition. 8912 if (IsInline != PrevNS->isInline()) 8913 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8914 &IsInline, PrevNS); 8915 } else if (PrevDecl) { 8916 // This is an invalid name redefinition. 8917 Diag(Loc, diag::err_redefinition_different_kind) 8918 << II; 8919 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8920 IsInvalid = true; 8921 // Continue on to push Namespc as current DeclContext and return it. 8922 } else if (II->isStr("std") && 8923 CurContext->getRedeclContext()->isTranslationUnit()) { 8924 // This is the first "real" definition of the namespace "std", so update 8925 // our cache of the "std" namespace to point at this definition. 8926 PrevNS = getStdNamespace(); 8927 IsStd = true; 8928 AddToKnown = !IsInline; 8929 } else { 8930 // We've seen this namespace for the first time. 8931 AddToKnown = !IsInline; 8932 } 8933 } else { 8934 // Anonymous namespaces. 8935 8936 // Determine whether the parent already has an anonymous namespace. 8937 DeclContext *Parent = CurContext->getRedeclContext(); 8938 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8939 PrevNS = TU->getAnonymousNamespace(); 8940 } else { 8941 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8942 PrevNS = ND->getAnonymousNamespace(); 8943 } 8944 8945 if (PrevNS && IsInline != PrevNS->isInline()) 8946 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8947 &IsInline, PrevNS); 8948 } 8949 8950 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8951 StartLoc, Loc, II, PrevNS); 8952 if (IsInvalid) 8953 Namespc->setInvalidDecl(); 8954 8955 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8956 AddPragmaAttributes(DeclRegionScope, Namespc); 8957 8958 // FIXME: Should we be merging attributes? 8959 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8960 PushNamespaceVisibilityAttr(Attr, Loc); 8961 8962 if (IsStd) 8963 StdNamespace = Namespc; 8964 if (AddToKnown) 8965 KnownNamespaces[Namespc] = false; 8966 8967 if (II) { 8968 PushOnScopeChains(Namespc, DeclRegionScope); 8969 } else { 8970 // Link the anonymous namespace into its parent. 8971 DeclContext *Parent = CurContext->getRedeclContext(); 8972 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8973 TU->setAnonymousNamespace(Namespc); 8974 } else { 8975 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8976 } 8977 8978 CurContext->addDecl(Namespc); 8979 8980 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8981 // behaves as if it were replaced by 8982 // namespace unique { /* empty body */ } 8983 // using namespace unique; 8984 // namespace unique { namespace-body } 8985 // where all occurrences of 'unique' in a translation unit are 8986 // replaced by the same identifier and this identifier differs 8987 // from all other identifiers in the entire program. 8988 8989 // We just create the namespace with an empty name and then add an 8990 // implicit using declaration, just like the standard suggests. 8991 // 8992 // CodeGen enforces the "universally unique" aspect by giving all 8993 // declarations semantically contained within an anonymous 8994 // namespace internal linkage. 8995 8996 if (!PrevNS) { 8997 UD = UsingDirectiveDecl::Create(Context, Parent, 8998 /* 'using' */ LBrace, 8999 /* 'namespace' */ SourceLocation(), 9000 /* qualifier */ NestedNameSpecifierLoc(), 9001 /* identifier */ SourceLocation(), 9002 Namespc, 9003 /* Ancestor */ Parent); 9004 UD->setImplicit(); 9005 Parent->addDecl(UD); 9006 } 9007 } 9008 9009 ActOnDocumentableDecl(Namespc); 9010 9011 // Although we could have an invalid decl (i.e. the namespace name is a 9012 // redefinition), push it as current DeclContext and try to continue parsing. 9013 // FIXME: We should be able to push Namespc here, so that the each DeclContext 9014 // for the namespace has the declarations that showed up in that particular 9015 // namespace definition. 9016 PushDeclContext(NamespcScope, Namespc); 9017 return Namespc; 9018 } 9019 9020 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 9021 /// is a namespace alias, returns the namespace it points to. 9022 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 9023 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 9024 return AD->getNamespace(); 9025 return dyn_cast_or_null<NamespaceDecl>(D); 9026 } 9027 9028 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 9029 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 9030 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 9031 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 9032 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 9033 Namespc->setRBraceLoc(RBrace); 9034 PopDeclContext(); 9035 if (Namespc->hasAttr<VisibilityAttr>()) 9036 PopPragmaVisibility(true, RBrace); 9037 } 9038 9039 CXXRecordDecl *Sema::getStdBadAlloc() const { 9040 return cast_or_null<CXXRecordDecl>( 9041 StdBadAlloc.get(Context.getExternalSource())); 9042 } 9043 9044 EnumDecl *Sema::getStdAlignValT() const { 9045 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 9046 } 9047 9048 NamespaceDecl *Sema::getStdNamespace() const { 9049 return cast_or_null<NamespaceDecl>( 9050 StdNamespace.get(Context.getExternalSource())); 9051 } 9052 9053 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 9054 if (!StdExperimentalNamespaceCache) { 9055 if (auto Std = getStdNamespace()) { 9056 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 9057 SourceLocation(), LookupNamespaceName); 9058 if (!LookupQualifiedName(Result, Std) || 9059 !(StdExperimentalNamespaceCache = 9060 Result.getAsSingle<NamespaceDecl>())) 9061 Result.suppressDiagnostics(); 9062 } 9063 } 9064 return StdExperimentalNamespaceCache; 9065 } 9066 9067 namespace { 9068 9069 enum UnsupportedSTLSelect { 9070 USS_InvalidMember, 9071 USS_MissingMember, 9072 USS_NonTrivial, 9073 USS_Other 9074 }; 9075 9076 struct InvalidSTLDiagnoser { 9077 Sema &S; 9078 SourceLocation Loc; 9079 QualType TyForDiags; 9080 9081 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 9082 const VarDecl *VD = nullptr) { 9083 { 9084 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 9085 << TyForDiags << ((int)Sel); 9086 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 9087 assert(!Name.empty()); 9088 D << Name; 9089 } 9090 } 9091 if (Sel == USS_InvalidMember) { 9092 S.Diag(VD->getLocation(), diag::note_var_declared_here) 9093 << VD << VD->getSourceRange(); 9094 } 9095 return QualType(); 9096 } 9097 }; 9098 } // namespace 9099 9100 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 9101 SourceLocation Loc) { 9102 assert(getLangOpts().CPlusPlus && 9103 "Looking for comparison category type outside of C++."); 9104 9105 // Check if we've already successfully checked the comparison category type 9106 // before. If so, skip checking it again. 9107 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 9108 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 9109 return Info->getType(); 9110 9111 // If lookup failed 9112 if (!Info) { 9113 std::string NameForDiags = "std::"; 9114 NameForDiags += ComparisonCategories::getCategoryString(Kind); 9115 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 9116 << NameForDiags; 9117 return QualType(); 9118 } 9119 9120 assert(Info->Kind == Kind); 9121 assert(Info->Record); 9122 9123 // Update the Record decl in case we encountered a forward declaration on our 9124 // first pass. FIXME: This is a bit of a hack. 9125 if (Info->Record->hasDefinition()) 9126 Info->Record = Info->Record->getDefinition(); 9127 9128 // Use an elaborated type for diagnostics which has a name containing the 9129 // prepended 'std' namespace but not any inline namespace names. 9130 QualType TyForDiags = [&]() { 9131 auto *NNS = 9132 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 9133 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 9134 }(); 9135 9136 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 9137 return QualType(); 9138 9139 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 9140 9141 if (!Info->Record->isTriviallyCopyable()) 9142 return UnsupportedSTLError(USS_NonTrivial); 9143 9144 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 9145 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 9146 // Tolerate empty base classes. 9147 if (Base->isEmpty()) 9148 continue; 9149 // Reject STL implementations which have at least one non-empty base. 9150 return UnsupportedSTLError(); 9151 } 9152 9153 // Check that the STL has implemented the types using a single integer field. 9154 // This expectation allows better codegen for builtin operators. We require: 9155 // (1) The class has exactly one field. 9156 // (2) The field is an integral or enumeration type. 9157 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9158 if (std::distance(FIt, FEnd) != 1 || 9159 !FIt->getType()->isIntegralOrEnumerationType()) { 9160 return UnsupportedSTLError(); 9161 } 9162 9163 // Build each of the require values and store them in Info. 9164 for (ComparisonCategoryResult CCR : 9165 ComparisonCategories::getPossibleResultsForType(Kind)) { 9166 StringRef MemName = ComparisonCategories::getResultString(CCR); 9167 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9168 9169 if (!ValInfo) 9170 return UnsupportedSTLError(USS_MissingMember, MemName); 9171 9172 VarDecl *VD = ValInfo->VD; 9173 assert(VD && "should not be null!"); 9174 9175 // Attempt to diagnose reasons why the STL definition of this type 9176 // might be foobar, including it failing to be a constant expression. 9177 // TODO Handle more ways the lookup or result can be invalid. 9178 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9179 !VD->checkInitIsICE()) 9180 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9181 9182 // Attempt to evaluate the var decl as a constant expression and extract 9183 // the value of its first field as a ICE. If this fails, the STL 9184 // implementation is not supported. 9185 if (!ValInfo->hasValidIntValue()) 9186 return UnsupportedSTLError(); 9187 9188 MarkVariableReferenced(Loc, VD); 9189 } 9190 9191 // We've successfully built the required types and expressions. Update 9192 // the cache and return the newly cached value. 9193 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9194 return Info->getType(); 9195 } 9196 9197 /// Retrieve the special "std" namespace, which may require us to 9198 /// implicitly define the namespace. 9199 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9200 if (!StdNamespace) { 9201 // The "std" namespace has not yet been defined, so build one implicitly. 9202 StdNamespace = NamespaceDecl::Create(Context, 9203 Context.getTranslationUnitDecl(), 9204 /*Inline=*/false, 9205 SourceLocation(), SourceLocation(), 9206 &PP.getIdentifierTable().get("std"), 9207 /*PrevDecl=*/nullptr); 9208 getStdNamespace()->setImplicit(true); 9209 } 9210 9211 return getStdNamespace(); 9212 } 9213 9214 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9215 assert(getLangOpts().CPlusPlus && 9216 "Looking for std::initializer_list outside of C++."); 9217 9218 // We're looking for implicit instantiations of 9219 // template <typename E> class std::initializer_list. 9220 9221 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9222 return false; 9223 9224 ClassTemplateDecl *Template = nullptr; 9225 const TemplateArgument *Arguments = nullptr; 9226 9227 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9228 9229 ClassTemplateSpecializationDecl *Specialization = 9230 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9231 if (!Specialization) 9232 return false; 9233 9234 Template = Specialization->getSpecializedTemplate(); 9235 Arguments = Specialization->getTemplateArgs().data(); 9236 } else if (const TemplateSpecializationType *TST = 9237 Ty->getAs<TemplateSpecializationType>()) { 9238 Template = dyn_cast_or_null<ClassTemplateDecl>( 9239 TST->getTemplateName().getAsTemplateDecl()); 9240 Arguments = TST->getArgs(); 9241 } 9242 if (!Template) 9243 return false; 9244 9245 if (!StdInitializerList) { 9246 // Haven't recognized std::initializer_list yet, maybe this is it. 9247 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9248 if (TemplateClass->getIdentifier() != 9249 &PP.getIdentifierTable().get("initializer_list") || 9250 !getStdNamespace()->InEnclosingNamespaceSetOf( 9251 TemplateClass->getDeclContext())) 9252 return false; 9253 // This is a template called std::initializer_list, but is it the right 9254 // template? 9255 TemplateParameterList *Params = Template->getTemplateParameters(); 9256 if (Params->getMinRequiredArguments() != 1) 9257 return false; 9258 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9259 return false; 9260 9261 // It's the right template. 9262 StdInitializerList = Template; 9263 } 9264 9265 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9266 return false; 9267 9268 // This is an instance of std::initializer_list. Find the argument type. 9269 if (Element) 9270 *Element = Arguments[0].getAsType(); 9271 return true; 9272 } 9273 9274 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9275 NamespaceDecl *Std = S.getStdNamespace(); 9276 if (!Std) { 9277 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9278 return nullptr; 9279 } 9280 9281 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9282 Loc, Sema::LookupOrdinaryName); 9283 if (!S.LookupQualifiedName(Result, Std)) { 9284 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9285 return nullptr; 9286 } 9287 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9288 if (!Template) { 9289 Result.suppressDiagnostics(); 9290 // We found something weird. Complain about the first thing we found. 9291 NamedDecl *Found = *Result.begin(); 9292 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9293 return nullptr; 9294 } 9295 9296 // We found some template called std::initializer_list. Now verify that it's 9297 // correct. 9298 TemplateParameterList *Params = Template->getTemplateParameters(); 9299 if (Params->getMinRequiredArguments() != 1 || 9300 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9301 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9302 return nullptr; 9303 } 9304 9305 return Template; 9306 } 9307 9308 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9309 if (!StdInitializerList) { 9310 StdInitializerList = LookupStdInitializerList(*this, Loc); 9311 if (!StdInitializerList) 9312 return QualType(); 9313 } 9314 9315 TemplateArgumentListInfo Args(Loc, Loc); 9316 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9317 Context.getTrivialTypeSourceInfo(Element, 9318 Loc))); 9319 return Context.getCanonicalType( 9320 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9321 } 9322 9323 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9324 // C++ [dcl.init.list]p2: 9325 // A constructor is an initializer-list constructor if its first parameter 9326 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9327 // std::initializer_list<E> for some type E, and either there are no other 9328 // parameters or else all other parameters have default arguments. 9329 if (Ctor->getNumParams() < 1 || 9330 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9331 return false; 9332 9333 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9334 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9335 ArgType = RT->getPointeeType().getUnqualifiedType(); 9336 9337 return isStdInitializerList(ArgType, nullptr); 9338 } 9339 9340 /// Determine whether a using statement is in a context where it will be 9341 /// apply in all contexts. 9342 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9343 switch (CurContext->getDeclKind()) { 9344 case Decl::TranslationUnit: 9345 return true; 9346 case Decl::LinkageSpec: 9347 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9348 default: 9349 return false; 9350 } 9351 } 9352 9353 namespace { 9354 9355 // Callback to only accept typo corrections that are namespaces. 9356 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 9357 public: 9358 bool ValidateCandidate(const TypoCorrection &candidate) override { 9359 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9360 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9361 return false; 9362 } 9363 }; 9364 9365 } 9366 9367 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9368 CXXScopeSpec &SS, 9369 SourceLocation IdentLoc, 9370 IdentifierInfo *Ident) { 9371 R.clear(); 9372 if (TypoCorrection Corrected = 9373 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 9374 llvm::make_unique<NamespaceValidatorCCC>(), 9375 Sema::CTK_ErrorRecovery)) { 9376 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9377 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9378 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9379 Ident->getName().equals(CorrectedStr); 9380 S.diagnoseTypo(Corrected, 9381 S.PDiag(diag::err_using_directive_member_suggest) 9382 << Ident << DC << DroppedSpecifier << SS.getRange(), 9383 S.PDiag(diag::note_namespace_defined_here)); 9384 } else { 9385 S.diagnoseTypo(Corrected, 9386 S.PDiag(diag::err_using_directive_suggest) << Ident, 9387 S.PDiag(diag::note_namespace_defined_here)); 9388 } 9389 R.addDecl(Corrected.getFoundDecl()); 9390 return true; 9391 } 9392 return false; 9393 } 9394 9395 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 9396 SourceLocation NamespcLoc, CXXScopeSpec &SS, 9397 SourceLocation IdentLoc, 9398 IdentifierInfo *NamespcName, 9399 const ParsedAttributesView &AttrList) { 9400 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9401 assert(NamespcName && "Invalid NamespcName."); 9402 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9403 9404 // This can only happen along a recovery path. 9405 while (S->isTemplateParamScope()) 9406 S = S->getParent(); 9407 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9408 9409 UsingDirectiveDecl *UDir = nullptr; 9410 NestedNameSpecifier *Qualifier = nullptr; 9411 if (SS.isSet()) 9412 Qualifier = SS.getScopeRep(); 9413 9414 // Lookup namespace name. 9415 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9416 LookupParsedName(R, S, &SS); 9417 if (R.isAmbiguous()) 9418 return nullptr; 9419 9420 if (R.empty()) { 9421 R.clear(); 9422 // Allow "using namespace std;" or "using namespace ::std;" even if 9423 // "std" hasn't been defined yet, for GCC compatibility. 9424 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9425 NamespcName->isStr("std")) { 9426 Diag(IdentLoc, diag::ext_using_undefined_std); 9427 R.addDecl(getOrCreateStdNamespace()); 9428 R.resolveKind(); 9429 } 9430 // Otherwise, attempt typo correction. 9431 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9432 } 9433 9434 if (!R.empty()) { 9435 NamedDecl *Named = R.getRepresentativeDecl(); 9436 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9437 assert(NS && "expected namespace decl"); 9438 9439 // The use of a nested name specifier may trigger deprecation warnings. 9440 DiagnoseUseOfDecl(Named, IdentLoc); 9441 9442 // C++ [namespace.udir]p1: 9443 // A using-directive specifies that the names in the nominated 9444 // namespace can be used in the scope in which the 9445 // using-directive appears after the using-directive. During 9446 // unqualified name lookup (3.4.1), the names appear as if they 9447 // were declared in the nearest enclosing namespace which 9448 // contains both the using-directive and the nominated 9449 // namespace. [Note: in this context, "contains" means "contains 9450 // directly or indirectly". ] 9451 9452 // Find enclosing context containing both using-directive and 9453 // nominated namespace. 9454 DeclContext *CommonAncestor = NS; 9455 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9456 CommonAncestor = CommonAncestor->getParent(); 9457 9458 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9459 SS.getWithLocInContext(Context), 9460 IdentLoc, Named, CommonAncestor); 9461 9462 if (IsUsingDirectiveInToplevelContext(CurContext) && 9463 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9464 Diag(IdentLoc, diag::warn_using_directive_in_header); 9465 } 9466 9467 PushUsingDirective(S, UDir); 9468 } else { 9469 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9470 } 9471 9472 if (UDir) 9473 ProcessDeclAttributeList(S, UDir, AttrList); 9474 9475 return UDir; 9476 } 9477 9478 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9479 // If the scope has an associated entity and the using directive is at 9480 // namespace or translation unit scope, add the UsingDirectiveDecl into 9481 // its lookup structure so qualified name lookup can find it. 9482 DeclContext *Ctx = S->getEntity(); 9483 if (Ctx && !Ctx->isFunctionOrMethod()) 9484 Ctx->addDecl(UDir); 9485 else 9486 // Otherwise, it is at block scope. The using-directives will affect lookup 9487 // only to the end of the scope. 9488 S->PushUsingDirective(UDir); 9489 } 9490 9491 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 9492 SourceLocation UsingLoc, 9493 SourceLocation TypenameLoc, CXXScopeSpec &SS, 9494 UnqualifiedId &Name, 9495 SourceLocation EllipsisLoc, 9496 const ParsedAttributesView &AttrList) { 9497 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9498 9499 if (SS.isEmpty()) { 9500 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 9501 return nullptr; 9502 } 9503 9504 switch (Name.getKind()) { 9505 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9506 case UnqualifiedIdKind::IK_Identifier: 9507 case UnqualifiedIdKind::IK_OperatorFunctionId: 9508 case UnqualifiedIdKind::IK_LiteralOperatorId: 9509 case UnqualifiedIdKind::IK_ConversionFunctionId: 9510 break; 9511 9512 case UnqualifiedIdKind::IK_ConstructorName: 9513 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9514 // C++11 inheriting constructors. 9515 Diag(Name.getBeginLoc(), 9516 getLangOpts().CPlusPlus11 9517 ? diag::warn_cxx98_compat_using_decl_constructor 9518 : diag::err_using_decl_constructor) 9519 << SS.getRange(); 9520 9521 if (getLangOpts().CPlusPlus11) break; 9522 9523 return nullptr; 9524 9525 case UnqualifiedIdKind::IK_DestructorName: 9526 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 9527 return nullptr; 9528 9529 case UnqualifiedIdKind::IK_TemplateId: 9530 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 9531 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9532 return nullptr; 9533 9534 case UnqualifiedIdKind::IK_DeductionGuideName: 9535 llvm_unreachable("cannot parse qualified deduction guide name"); 9536 } 9537 9538 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9539 DeclarationName TargetName = TargetNameInfo.getName(); 9540 if (!TargetName) 9541 return nullptr; 9542 9543 // Warn about access declarations. 9544 if (UsingLoc.isInvalid()) { 9545 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 9546 ? diag::err_access_decl 9547 : diag::warn_access_decl_deprecated) 9548 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9549 } 9550 9551 if (EllipsisLoc.isInvalid()) { 9552 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9553 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9554 return nullptr; 9555 } else { 9556 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9557 !TargetNameInfo.containsUnexpandedParameterPack()) { 9558 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9559 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9560 EllipsisLoc = SourceLocation(); 9561 } 9562 } 9563 9564 NamedDecl *UD = 9565 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9566 SS, TargetNameInfo, EllipsisLoc, AttrList, 9567 /*IsInstantiation*/false); 9568 if (UD) 9569 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9570 9571 return UD; 9572 } 9573 9574 /// Determine whether a using declaration considers the given 9575 /// declarations as "equivalent", e.g., if they are redeclarations of 9576 /// the same entity or are both typedefs of the same type. 9577 static bool 9578 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9579 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9580 return true; 9581 9582 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9583 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9584 return Context.hasSameType(TD1->getUnderlyingType(), 9585 TD2->getUnderlyingType()); 9586 9587 return false; 9588 } 9589 9590 9591 /// Determines whether to create a using shadow decl for a particular 9592 /// decl, given the set of decls existing prior to this using lookup. 9593 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9594 const LookupResult &Previous, 9595 UsingShadowDecl *&PrevShadow) { 9596 // Diagnose finding a decl which is not from a base class of the 9597 // current class. We do this now because there are cases where this 9598 // function will silently decide not to build a shadow decl, which 9599 // will pre-empt further diagnostics. 9600 // 9601 // We don't need to do this in C++11 because we do the check once on 9602 // the qualifier. 9603 // 9604 // FIXME: diagnose the following if we care enough: 9605 // struct A { int foo; }; 9606 // struct B : A { using A::foo; }; 9607 // template <class T> struct C : A {}; 9608 // template <class T> struct D : C<T> { using B::foo; } // <--- 9609 // This is invalid (during instantiation) in C++03 because B::foo 9610 // resolves to the using decl in B, which is not a base class of D<T>. 9611 // We can't diagnose it immediately because C<T> is an unknown 9612 // specialization. The UsingShadowDecl in D<T> then points directly 9613 // to A::foo, which will look well-formed when we instantiate. 9614 // The right solution is to not collapse the shadow-decl chain. 9615 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9616 DeclContext *OrigDC = Orig->getDeclContext(); 9617 9618 // Handle enums and anonymous structs. 9619 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9620 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9621 while (OrigRec->isAnonymousStructOrUnion()) 9622 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9623 9624 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9625 if (OrigDC == CurContext) { 9626 Diag(Using->getLocation(), 9627 diag::err_using_decl_nested_name_specifier_is_current_class) 9628 << Using->getQualifierLoc().getSourceRange(); 9629 Diag(Orig->getLocation(), diag::note_using_decl_target); 9630 Using->setInvalidDecl(); 9631 return true; 9632 } 9633 9634 Diag(Using->getQualifierLoc().getBeginLoc(), 9635 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9636 << Using->getQualifier() 9637 << cast<CXXRecordDecl>(CurContext) 9638 << Using->getQualifierLoc().getSourceRange(); 9639 Diag(Orig->getLocation(), diag::note_using_decl_target); 9640 Using->setInvalidDecl(); 9641 return true; 9642 } 9643 } 9644 9645 if (Previous.empty()) return false; 9646 9647 NamedDecl *Target = Orig; 9648 if (isa<UsingShadowDecl>(Target)) 9649 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9650 9651 // If the target happens to be one of the previous declarations, we 9652 // don't have a conflict. 9653 // 9654 // FIXME: but we might be increasing its access, in which case we 9655 // should redeclare it. 9656 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9657 bool FoundEquivalentDecl = false; 9658 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9659 I != E; ++I) { 9660 NamedDecl *D = (*I)->getUnderlyingDecl(); 9661 // We can have UsingDecls in our Previous results because we use the same 9662 // LookupResult for checking whether the UsingDecl itself is a valid 9663 // redeclaration. 9664 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9665 continue; 9666 9667 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9668 // C++ [class.mem]p19: 9669 // If T is the name of a class, then [every named member other than 9670 // a non-static data member] shall have a name different from T 9671 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 9672 !isa<IndirectFieldDecl>(Target) && 9673 !isa<UnresolvedUsingValueDecl>(Target) && 9674 DiagnoseClassNameShadow( 9675 CurContext, 9676 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 9677 return true; 9678 } 9679 9680 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9681 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9682 PrevShadow = Shadow; 9683 FoundEquivalentDecl = true; 9684 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9685 // We don't conflict with an existing using shadow decl of an equivalent 9686 // declaration, but we're not a redeclaration of it. 9687 FoundEquivalentDecl = true; 9688 } 9689 9690 if (isVisible(D)) 9691 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9692 } 9693 9694 if (FoundEquivalentDecl) 9695 return false; 9696 9697 if (FunctionDecl *FD = Target->getAsFunction()) { 9698 NamedDecl *OldDecl = nullptr; 9699 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9700 /*IsForUsingDecl*/ true)) { 9701 case Ovl_Overload: 9702 return false; 9703 9704 case Ovl_NonFunction: 9705 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9706 break; 9707 9708 // We found a decl with the exact signature. 9709 case Ovl_Match: 9710 // If we're in a record, we want to hide the target, so we 9711 // return true (without a diagnostic) to tell the caller not to 9712 // build a shadow decl. 9713 if (CurContext->isRecord()) 9714 return true; 9715 9716 // If we're not in a record, this is an error. 9717 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9718 break; 9719 } 9720 9721 Diag(Target->getLocation(), diag::note_using_decl_target); 9722 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9723 Using->setInvalidDecl(); 9724 return true; 9725 } 9726 9727 // Target is not a function. 9728 9729 if (isa<TagDecl>(Target)) { 9730 // No conflict between a tag and a non-tag. 9731 if (!Tag) return false; 9732 9733 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9734 Diag(Target->getLocation(), diag::note_using_decl_target); 9735 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9736 Using->setInvalidDecl(); 9737 return true; 9738 } 9739 9740 // No conflict between a tag and a non-tag. 9741 if (!NonTag) return false; 9742 9743 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9744 Diag(Target->getLocation(), diag::note_using_decl_target); 9745 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9746 Using->setInvalidDecl(); 9747 return true; 9748 } 9749 9750 /// Determine whether a direct base class is a virtual base class. 9751 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9752 if (!Derived->getNumVBases()) 9753 return false; 9754 for (auto &B : Derived->bases()) 9755 if (B.getType()->getAsCXXRecordDecl() == Base) 9756 return B.isVirtual(); 9757 llvm_unreachable("not a direct base class"); 9758 } 9759 9760 /// Builds a shadow declaration corresponding to a 'using' declaration. 9761 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9762 UsingDecl *UD, 9763 NamedDecl *Orig, 9764 UsingShadowDecl *PrevDecl) { 9765 // If we resolved to another shadow declaration, just coalesce them. 9766 NamedDecl *Target = Orig; 9767 if (isa<UsingShadowDecl>(Target)) { 9768 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9769 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9770 } 9771 9772 NamedDecl *NonTemplateTarget = Target; 9773 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9774 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9775 9776 UsingShadowDecl *Shadow; 9777 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9778 bool IsVirtualBase = 9779 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9780 UD->getQualifier()->getAsRecordDecl()); 9781 Shadow = ConstructorUsingShadowDecl::Create( 9782 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9783 } else { 9784 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9785 Target); 9786 } 9787 UD->addShadowDecl(Shadow); 9788 9789 Shadow->setAccess(UD->getAccess()); 9790 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9791 Shadow->setInvalidDecl(); 9792 9793 Shadow->setPreviousDecl(PrevDecl); 9794 9795 if (S) 9796 PushOnScopeChains(Shadow, S); 9797 else 9798 CurContext->addDecl(Shadow); 9799 9800 9801 return Shadow; 9802 } 9803 9804 /// Hides a using shadow declaration. This is required by the current 9805 /// using-decl implementation when a resolvable using declaration in a 9806 /// class is followed by a declaration which would hide or override 9807 /// one or more of the using decl's targets; for example: 9808 /// 9809 /// struct Base { void foo(int); }; 9810 /// struct Derived : Base { 9811 /// using Base::foo; 9812 /// void foo(int); 9813 /// }; 9814 /// 9815 /// The governing language is C++03 [namespace.udecl]p12: 9816 /// 9817 /// When a using-declaration brings names from a base class into a 9818 /// derived class scope, member functions in the derived class 9819 /// override and/or hide member functions with the same name and 9820 /// parameter types in a base class (rather than conflicting). 9821 /// 9822 /// There are two ways to implement this: 9823 /// (1) optimistically create shadow decls when they're not hidden 9824 /// by existing declarations, or 9825 /// (2) don't create any shadow decls (or at least don't make them 9826 /// visible) until we've fully parsed/instantiated the class. 9827 /// The problem with (1) is that we might have to retroactively remove 9828 /// a shadow decl, which requires several O(n) operations because the 9829 /// decl structures are (very reasonably) not designed for removal. 9830 /// (2) avoids this but is very fiddly and phase-dependent. 9831 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9832 if (Shadow->getDeclName().getNameKind() == 9833 DeclarationName::CXXConversionFunctionName) 9834 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9835 9836 // Remove it from the DeclContext... 9837 Shadow->getDeclContext()->removeDecl(Shadow); 9838 9839 // ...and the scope, if applicable... 9840 if (S) { 9841 S->RemoveDecl(Shadow); 9842 IdResolver.RemoveDecl(Shadow); 9843 } 9844 9845 // ...and the using decl. 9846 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9847 9848 // TODO: complain somehow if Shadow was used. It shouldn't 9849 // be possible for this to happen, because...? 9850 } 9851 9852 /// Find the base specifier for a base class with the given type. 9853 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9854 QualType DesiredBase, 9855 bool &AnyDependentBases) { 9856 // Check whether the named type is a direct base class. 9857 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9858 for (auto &Base : Derived->bases()) { 9859 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9860 if (CanonicalDesiredBase == BaseType) 9861 return &Base; 9862 if (BaseType->isDependentType()) 9863 AnyDependentBases = true; 9864 } 9865 return nullptr; 9866 } 9867 9868 namespace { 9869 class UsingValidatorCCC : public CorrectionCandidateCallback { 9870 public: 9871 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9872 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9873 : HasTypenameKeyword(HasTypenameKeyword), 9874 IsInstantiation(IsInstantiation), OldNNS(NNS), 9875 RequireMemberOf(RequireMemberOf) {} 9876 9877 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9878 NamedDecl *ND = Candidate.getCorrectionDecl(); 9879 9880 // Keywords are not valid here. 9881 if (!ND || isa<NamespaceDecl>(ND)) 9882 return false; 9883 9884 // Completely unqualified names are invalid for a 'using' declaration. 9885 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9886 return false; 9887 9888 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9889 // reject. 9890 9891 if (RequireMemberOf) { 9892 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9893 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9894 // No-one ever wants a using-declaration to name an injected-class-name 9895 // of a base class, unless they're declaring an inheriting constructor. 9896 ASTContext &Ctx = ND->getASTContext(); 9897 if (!Ctx.getLangOpts().CPlusPlus11) 9898 return false; 9899 QualType FoundType = Ctx.getRecordType(FoundRecord); 9900 9901 // Check that the injected-class-name is named as a member of its own 9902 // type; we don't want to suggest 'using Derived::Base;', since that 9903 // means something else. 9904 NestedNameSpecifier *Specifier = 9905 Candidate.WillReplaceSpecifier() 9906 ? Candidate.getCorrectionSpecifier() 9907 : OldNNS; 9908 if (!Specifier->getAsType() || 9909 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9910 return false; 9911 9912 // Check that this inheriting constructor declaration actually names a 9913 // direct base class of the current class. 9914 bool AnyDependentBases = false; 9915 if (!findDirectBaseWithType(RequireMemberOf, 9916 Ctx.getRecordType(FoundRecord), 9917 AnyDependentBases) && 9918 !AnyDependentBases) 9919 return false; 9920 } else { 9921 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9922 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9923 return false; 9924 9925 // FIXME: Check that the base class member is accessible? 9926 } 9927 } else { 9928 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9929 if (FoundRecord && FoundRecord->isInjectedClassName()) 9930 return false; 9931 } 9932 9933 if (isa<TypeDecl>(ND)) 9934 return HasTypenameKeyword || !IsInstantiation; 9935 9936 return !HasTypenameKeyword; 9937 } 9938 9939 private: 9940 bool HasTypenameKeyword; 9941 bool IsInstantiation; 9942 NestedNameSpecifier *OldNNS; 9943 CXXRecordDecl *RequireMemberOf; 9944 }; 9945 } // end anonymous namespace 9946 9947 /// Builds a using declaration. 9948 /// 9949 /// \param IsInstantiation - Whether this call arises from an 9950 /// instantiation of an unresolved using declaration. We treat 9951 /// the lookup differently for these declarations. 9952 NamedDecl *Sema::BuildUsingDeclaration( 9953 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 9954 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 9955 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 9956 const ParsedAttributesView &AttrList, bool IsInstantiation) { 9957 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9958 SourceLocation IdentLoc = NameInfo.getLoc(); 9959 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9960 9961 // FIXME: We ignore attributes for now. 9962 9963 // For an inheriting constructor declaration, the name of the using 9964 // declaration is the name of a constructor in this class, not in the 9965 // base class. 9966 DeclarationNameInfo UsingName = NameInfo; 9967 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9968 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9969 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9970 Context.getCanonicalType(Context.getRecordType(RD)))); 9971 9972 // Do the redeclaration lookup in the current scope. 9973 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9974 ForVisibleRedeclaration); 9975 Previous.setHideTags(false); 9976 if (S) { 9977 LookupName(Previous, S); 9978 9979 // It is really dumb that we have to do this. 9980 LookupResult::Filter F = Previous.makeFilter(); 9981 while (F.hasNext()) { 9982 NamedDecl *D = F.next(); 9983 if (!isDeclInScope(D, CurContext, S)) 9984 F.erase(); 9985 // If we found a local extern declaration that's not ordinarily visible, 9986 // and this declaration is being added to a non-block scope, ignore it. 9987 // We're only checking for scope conflicts here, not also for violations 9988 // of the linkage rules. 9989 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9990 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9991 F.erase(); 9992 } 9993 F.done(); 9994 } else { 9995 assert(IsInstantiation && "no scope in non-instantiation"); 9996 if (CurContext->isRecord()) 9997 LookupQualifiedName(Previous, CurContext); 9998 else { 9999 // No redeclaration check is needed here; in non-member contexts we 10000 // diagnosed all possible conflicts with other using-declarations when 10001 // building the template: 10002 // 10003 // For a dependent non-type using declaration, the only valid case is 10004 // if we instantiate to a single enumerator. We check for conflicts 10005 // between shadow declarations we introduce, and we check in the template 10006 // definition for conflicts between a non-type using declaration and any 10007 // other declaration, which together covers all cases. 10008 // 10009 // A dependent typename using declaration will never successfully 10010 // instantiate, since it will always name a class member, so we reject 10011 // that in the template definition. 10012 } 10013 } 10014 10015 // Check for invalid redeclarations. 10016 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 10017 SS, IdentLoc, Previous)) 10018 return nullptr; 10019 10020 // Check for bad qualifiers. 10021 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 10022 IdentLoc)) 10023 return nullptr; 10024 10025 DeclContext *LookupContext = computeDeclContext(SS); 10026 NamedDecl *D; 10027 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10028 if (!LookupContext || EllipsisLoc.isValid()) { 10029 if (HasTypenameKeyword) { 10030 // FIXME: not all declaration name kinds are legal here 10031 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 10032 UsingLoc, TypenameLoc, 10033 QualifierLoc, 10034 IdentLoc, NameInfo.getName(), 10035 EllipsisLoc); 10036 } else { 10037 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 10038 QualifierLoc, NameInfo, EllipsisLoc); 10039 } 10040 D->setAccess(AS); 10041 CurContext->addDecl(D); 10042 return D; 10043 } 10044 10045 auto Build = [&](bool Invalid) { 10046 UsingDecl *UD = 10047 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 10048 UsingName, HasTypenameKeyword); 10049 UD->setAccess(AS); 10050 CurContext->addDecl(UD); 10051 UD->setInvalidDecl(Invalid); 10052 return UD; 10053 }; 10054 auto BuildInvalid = [&]{ return Build(true); }; 10055 auto BuildValid = [&]{ return Build(false); }; 10056 10057 if (RequireCompleteDeclContext(SS, LookupContext)) 10058 return BuildInvalid(); 10059 10060 // Look up the target name. 10061 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10062 10063 // Unlike most lookups, we don't always want to hide tag 10064 // declarations: tag names are visible through the using declaration 10065 // even if hidden by ordinary names, *except* in a dependent context 10066 // where it's important for the sanity of two-phase lookup. 10067 if (!IsInstantiation) 10068 R.setHideTags(false); 10069 10070 // For the purposes of this lookup, we have a base object type 10071 // equal to that of the current context. 10072 if (CurContext->isRecord()) { 10073 R.setBaseObjectType( 10074 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 10075 } 10076 10077 LookupQualifiedName(R, LookupContext); 10078 10079 // Try to correct typos if possible. If constructor name lookup finds no 10080 // results, that means the named class has no explicit constructors, and we 10081 // suppressed declaring implicit ones (probably because it's dependent or 10082 // invalid). 10083 if (R.empty() && 10084 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 10085 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 10086 // it will believe that glibc provides a ::gets in cases where it does not, 10087 // and will try to pull it into namespace std with a using-declaration. 10088 // Just ignore the using-declaration in that case. 10089 auto *II = NameInfo.getName().getAsIdentifierInfo(); 10090 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 10091 CurContext->isStdNamespace() && 10092 isa<TranslationUnitDecl>(LookupContext) && 10093 getSourceManager().isInSystemHeader(UsingLoc)) 10094 return nullptr; 10095 if (TypoCorrection Corrected = CorrectTypo( 10096 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 10097 llvm::make_unique<UsingValidatorCCC>( 10098 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 10099 dyn_cast<CXXRecordDecl>(CurContext)), 10100 CTK_ErrorRecovery)) { 10101 // We reject candidates where DroppedSpecifier == true, hence the 10102 // literal '0' below. 10103 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 10104 << NameInfo.getName() << LookupContext << 0 10105 << SS.getRange()); 10106 10107 // If we picked a correction with no attached Decl we can't do anything 10108 // useful with it, bail out. 10109 NamedDecl *ND = Corrected.getCorrectionDecl(); 10110 if (!ND) 10111 return BuildInvalid(); 10112 10113 // If we corrected to an inheriting constructor, handle it as one. 10114 auto *RD = dyn_cast<CXXRecordDecl>(ND); 10115 if (RD && RD->isInjectedClassName()) { 10116 // The parent of the injected class name is the class itself. 10117 RD = cast<CXXRecordDecl>(RD->getParent()); 10118 10119 // Fix up the information we'll use to build the using declaration. 10120 if (Corrected.WillReplaceSpecifier()) { 10121 NestedNameSpecifierLocBuilder Builder; 10122 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 10123 QualifierLoc.getSourceRange()); 10124 QualifierLoc = Builder.getWithLocInContext(Context); 10125 } 10126 10127 // In this case, the name we introduce is the name of a derived class 10128 // constructor. 10129 auto *CurClass = cast<CXXRecordDecl>(CurContext); 10130 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10131 Context.getCanonicalType(Context.getRecordType(CurClass)))); 10132 UsingName.setNamedTypeInfo(nullptr); 10133 for (auto *Ctor : LookupConstructors(RD)) 10134 R.addDecl(Ctor); 10135 R.resolveKind(); 10136 } else { 10137 // FIXME: Pick up all the declarations if we found an overloaded 10138 // function. 10139 UsingName.setName(ND->getDeclName()); 10140 R.addDecl(ND); 10141 } 10142 } else { 10143 Diag(IdentLoc, diag::err_no_member) 10144 << NameInfo.getName() << LookupContext << SS.getRange(); 10145 return BuildInvalid(); 10146 } 10147 } 10148 10149 if (R.isAmbiguous()) 10150 return BuildInvalid(); 10151 10152 if (HasTypenameKeyword) { 10153 // If we asked for a typename and got a non-type decl, error out. 10154 if (!R.getAsSingle<TypeDecl>()) { 10155 Diag(IdentLoc, diag::err_using_typename_non_type); 10156 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10157 Diag((*I)->getUnderlyingDecl()->getLocation(), 10158 diag::note_using_decl_target); 10159 return BuildInvalid(); 10160 } 10161 } else { 10162 // If we asked for a non-typename and we got a type, error out, 10163 // but only if this is an instantiation of an unresolved using 10164 // decl. Otherwise just silently find the type name. 10165 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10166 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10167 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10168 return BuildInvalid(); 10169 } 10170 } 10171 10172 // C++14 [namespace.udecl]p6: 10173 // A using-declaration shall not name a namespace. 10174 if (R.getAsSingle<NamespaceDecl>()) { 10175 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10176 << SS.getRange(); 10177 return BuildInvalid(); 10178 } 10179 10180 // C++14 [namespace.udecl]p7: 10181 // A using-declaration shall not name a scoped enumerator. 10182 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10183 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10184 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10185 << SS.getRange(); 10186 return BuildInvalid(); 10187 } 10188 } 10189 10190 UsingDecl *UD = BuildValid(); 10191 10192 // Some additional rules apply to inheriting constructors. 10193 if (UsingName.getName().getNameKind() == 10194 DeclarationName::CXXConstructorName) { 10195 // Suppress access diagnostics; the access check is instead performed at the 10196 // point of use for an inheriting constructor. 10197 R.suppressDiagnostics(); 10198 if (CheckInheritingConstructorUsingDecl(UD)) 10199 return UD; 10200 } 10201 10202 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10203 UsingShadowDecl *PrevDecl = nullptr; 10204 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10205 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10206 } 10207 10208 return UD; 10209 } 10210 10211 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10212 ArrayRef<NamedDecl *> Expansions) { 10213 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10214 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10215 isa<UsingPackDecl>(InstantiatedFrom)); 10216 10217 auto *UPD = 10218 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10219 UPD->setAccess(InstantiatedFrom->getAccess()); 10220 CurContext->addDecl(UPD); 10221 return UPD; 10222 } 10223 10224 /// Additional checks for a using declaration referring to a constructor name. 10225 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10226 assert(!UD->hasTypename() && "expecting a constructor name"); 10227 10228 const Type *SourceType = UD->getQualifier()->getAsType(); 10229 assert(SourceType && 10230 "Using decl naming constructor doesn't have type in scope spec."); 10231 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10232 10233 // Check whether the named type is a direct base class. 10234 bool AnyDependentBases = false; 10235 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10236 AnyDependentBases); 10237 if (!Base && !AnyDependentBases) { 10238 Diag(UD->getUsingLoc(), 10239 diag::err_using_decl_constructor_not_in_direct_base) 10240 << UD->getNameInfo().getSourceRange() 10241 << QualType(SourceType, 0) << TargetClass; 10242 UD->setInvalidDecl(); 10243 return true; 10244 } 10245 10246 if (Base) 10247 Base->setInheritConstructors(); 10248 10249 return false; 10250 } 10251 10252 /// Checks that the given using declaration is not an invalid 10253 /// redeclaration. Note that this is checking only for the using decl 10254 /// itself, not for any ill-formedness among the UsingShadowDecls. 10255 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10256 bool HasTypenameKeyword, 10257 const CXXScopeSpec &SS, 10258 SourceLocation NameLoc, 10259 const LookupResult &Prev) { 10260 NestedNameSpecifier *Qual = SS.getScopeRep(); 10261 10262 // C++03 [namespace.udecl]p8: 10263 // C++0x [namespace.udecl]p10: 10264 // A using-declaration is a declaration and can therefore be used 10265 // repeatedly where (and only where) multiple declarations are 10266 // allowed. 10267 // 10268 // That's in non-member contexts. 10269 if (!CurContext->getRedeclContext()->isRecord()) { 10270 // A dependent qualifier outside a class can only ever resolve to an 10271 // enumeration type. Therefore it conflicts with any other non-type 10272 // declaration in the same scope. 10273 // FIXME: How should we check for dependent type-type conflicts at block 10274 // scope? 10275 if (Qual->isDependent() && !HasTypenameKeyword) { 10276 for (auto *D : Prev) { 10277 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10278 bool OldCouldBeEnumerator = 10279 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10280 Diag(NameLoc, 10281 OldCouldBeEnumerator ? diag::err_redefinition 10282 : diag::err_redefinition_different_kind) 10283 << Prev.getLookupName(); 10284 Diag(D->getLocation(), diag::note_previous_definition); 10285 return true; 10286 } 10287 } 10288 } 10289 return false; 10290 } 10291 10292 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10293 NamedDecl *D = *I; 10294 10295 bool DTypename; 10296 NestedNameSpecifier *DQual; 10297 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10298 DTypename = UD->hasTypename(); 10299 DQual = UD->getQualifier(); 10300 } else if (UnresolvedUsingValueDecl *UD 10301 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10302 DTypename = false; 10303 DQual = UD->getQualifier(); 10304 } else if (UnresolvedUsingTypenameDecl *UD 10305 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10306 DTypename = true; 10307 DQual = UD->getQualifier(); 10308 } else continue; 10309 10310 // using decls differ if one says 'typename' and the other doesn't. 10311 // FIXME: non-dependent using decls? 10312 if (HasTypenameKeyword != DTypename) continue; 10313 10314 // using decls differ if they name different scopes (but note that 10315 // template instantiation can cause this check to trigger when it 10316 // didn't before instantiation). 10317 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10318 Context.getCanonicalNestedNameSpecifier(DQual)) 10319 continue; 10320 10321 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10322 Diag(D->getLocation(), diag::note_using_decl) << 1; 10323 return true; 10324 } 10325 10326 return false; 10327 } 10328 10329 10330 /// Checks that the given nested-name qualifier used in a using decl 10331 /// in the current context is appropriately related to the current 10332 /// scope. If an error is found, diagnoses it and returns true. 10333 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10334 bool HasTypename, 10335 const CXXScopeSpec &SS, 10336 const DeclarationNameInfo &NameInfo, 10337 SourceLocation NameLoc) { 10338 DeclContext *NamedContext = computeDeclContext(SS); 10339 10340 if (!CurContext->isRecord()) { 10341 // C++03 [namespace.udecl]p3: 10342 // C++0x [namespace.udecl]p8: 10343 // A using-declaration for a class member shall be a member-declaration. 10344 10345 // If we weren't able to compute a valid scope, it might validly be a 10346 // dependent class scope or a dependent enumeration unscoped scope. If 10347 // we have a 'typename' keyword, the scope must resolve to a class type. 10348 if ((HasTypename && !NamedContext) || 10349 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10350 auto *RD = NamedContext 10351 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10352 : nullptr; 10353 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10354 RD = nullptr; 10355 10356 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10357 << SS.getRange(); 10358 10359 // If we have a complete, non-dependent source type, try to suggest a 10360 // way to get the same effect. 10361 if (!RD) 10362 return true; 10363 10364 // Find what this using-declaration was referring to. 10365 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10366 R.setHideTags(false); 10367 R.suppressDiagnostics(); 10368 LookupQualifiedName(R, RD); 10369 10370 if (R.getAsSingle<TypeDecl>()) { 10371 if (getLangOpts().CPlusPlus11) { 10372 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10373 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10374 << 0 // alias declaration 10375 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10376 NameInfo.getName().getAsString() + 10377 " = "); 10378 } else { 10379 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10380 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 10381 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10382 << 1 // typedef declaration 10383 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10384 << FixItHint::CreateInsertion( 10385 InsertLoc, " " + NameInfo.getName().getAsString()); 10386 } 10387 } else if (R.getAsSingle<VarDecl>()) { 10388 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10389 // repeating the type of the static data member here. 10390 FixItHint FixIt; 10391 if (getLangOpts().CPlusPlus11) { 10392 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10393 FixIt = FixItHint::CreateReplacement( 10394 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10395 } 10396 10397 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10398 << 2 // reference declaration 10399 << FixIt; 10400 } else if (R.getAsSingle<EnumConstantDecl>()) { 10401 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10402 // repeating the type of the enumeration here, and we can't do so if 10403 // the type is anonymous. 10404 FixItHint FixIt; 10405 if (getLangOpts().CPlusPlus11) { 10406 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10407 FixIt = FixItHint::CreateReplacement( 10408 UsingLoc, 10409 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10410 } 10411 10412 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10413 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10414 << FixIt; 10415 } 10416 return true; 10417 } 10418 10419 // Otherwise, this might be valid. 10420 return false; 10421 } 10422 10423 // The current scope is a record. 10424 10425 // If the named context is dependent, we can't decide much. 10426 if (!NamedContext) { 10427 // FIXME: in C++0x, we can diagnose if we can prove that the 10428 // nested-name-specifier does not refer to a base class, which is 10429 // still possible in some cases. 10430 10431 // Otherwise we have to conservatively report that things might be 10432 // okay. 10433 return false; 10434 } 10435 10436 if (!NamedContext->isRecord()) { 10437 // Ideally this would point at the last name in the specifier, 10438 // but we don't have that level of source info. 10439 Diag(SS.getRange().getBegin(), 10440 diag::err_using_decl_nested_name_specifier_is_not_class) 10441 << SS.getScopeRep() << SS.getRange(); 10442 return true; 10443 } 10444 10445 if (!NamedContext->isDependentContext() && 10446 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10447 return true; 10448 10449 if (getLangOpts().CPlusPlus11) { 10450 // C++11 [namespace.udecl]p3: 10451 // In a using-declaration used as a member-declaration, the 10452 // nested-name-specifier shall name a base class of the class 10453 // being defined. 10454 10455 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10456 cast<CXXRecordDecl>(NamedContext))) { 10457 if (CurContext == NamedContext) { 10458 Diag(NameLoc, 10459 diag::err_using_decl_nested_name_specifier_is_current_class) 10460 << SS.getRange(); 10461 return true; 10462 } 10463 10464 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10465 Diag(SS.getRange().getBegin(), 10466 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10467 << SS.getScopeRep() 10468 << cast<CXXRecordDecl>(CurContext) 10469 << SS.getRange(); 10470 } 10471 return true; 10472 } 10473 10474 return false; 10475 } 10476 10477 // C++03 [namespace.udecl]p4: 10478 // A using-declaration used as a member-declaration shall refer 10479 // to a member of a base class of the class being defined [etc.]. 10480 10481 // Salient point: SS doesn't have to name a base class as long as 10482 // lookup only finds members from base classes. Therefore we can 10483 // diagnose here only if we can prove that that can't happen, 10484 // i.e. if the class hierarchies provably don't intersect. 10485 10486 // TODO: it would be nice if "definitely valid" results were cached 10487 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10488 // need to be repeated. 10489 10490 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10491 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10492 Bases.insert(Base); 10493 return true; 10494 }; 10495 10496 // Collect all bases. Return false if we find a dependent base. 10497 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10498 return false; 10499 10500 // Returns true if the base is dependent or is one of the accumulated base 10501 // classes. 10502 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10503 return !Bases.count(Base); 10504 }; 10505 10506 // Return false if the class has a dependent base or if it or one 10507 // of its bases is present in the base set of the current context. 10508 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10509 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10510 return false; 10511 10512 Diag(SS.getRange().getBegin(), 10513 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10514 << SS.getScopeRep() 10515 << cast<CXXRecordDecl>(CurContext) 10516 << SS.getRange(); 10517 10518 return true; 10519 } 10520 10521 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 10522 MultiTemplateParamsArg TemplateParamLists, 10523 SourceLocation UsingLoc, UnqualifiedId &Name, 10524 const ParsedAttributesView &AttrList, 10525 TypeResult Type, Decl *DeclFromDeclSpec) { 10526 // Skip up to the relevant declaration scope. 10527 while (S->isTemplateParamScope()) 10528 S = S->getParent(); 10529 assert((S->getFlags() & Scope::DeclScope) && 10530 "got alias-declaration outside of declaration scope"); 10531 10532 if (Type.isInvalid()) 10533 return nullptr; 10534 10535 bool Invalid = false; 10536 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10537 TypeSourceInfo *TInfo = nullptr; 10538 GetTypeFromParser(Type.get(), &TInfo); 10539 10540 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10541 return nullptr; 10542 10543 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10544 UPPC_DeclarationType)) { 10545 Invalid = true; 10546 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10547 TInfo->getTypeLoc().getBeginLoc()); 10548 } 10549 10550 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10551 TemplateParamLists.size() 10552 ? forRedeclarationInCurContext() 10553 : ForVisibleRedeclaration); 10554 LookupName(Previous, S); 10555 10556 // Warn about shadowing the name of a template parameter. 10557 if (Previous.isSingleResult() && 10558 Previous.getFoundDecl()->isTemplateParameter()) { 10559 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10560 Previous.clear(); 10561 } 10562 10563 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10564 "name in alias declaration must be an identifier"); 10565 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10566 Name.StartLocation, 10567 Name.Identifier, TInfo); 10568 10569 NewTD->setAccess(AS); 10570 10571 if (Invalid) 10572 NewTD->setInvalidDecl(); 10573 10574 ProcessDeclAttributeList(S, NewTD, AttrList); 10575 AddPragmaAttributes(S, NewTD); 10576 10577 CheckTypedefForVariablyModifiedType(S, NewTD); 10578 Invalid |= NewTD->isInvalidDecl(); 10579 10580 bool Redeclaration = false; 10581 10582 NamedDecl *NewND; 10583 if (TemplateParamLists.size()) { 10584 TypeAliasTemplateDecl *OldDecl = nullptr; 10585 TemplateParameterList *OldTemplateParams = nullptr; 10586 10587 if (TemplateParamLists.size() != 1) { 10588 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10589 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10590 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10591 } 10592 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10593 10594 // Check that we can declare a template here. 10595 if (CheckTemplateDeclScope(S, TemplateParams)) 10596 return nullptr; 10597 10598 // Only consider previous declarations in the same scope. 10599 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10600 /*ExplicitInstantiationOrSpecialization*/false); 10601 if (!Previous.empty()) { 10602 Redeclaration = true; 10603 10604 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10605 if (!OldDecl && !Invalid) { 10606 Diag(UsingLoc, diag::err_redefinition_different_kind) 10607 << Name.Identifier; 10608 10609 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10610 if (OldD->getLocation().isValid()) 10611 Diag(OldD->getLocation(), diag::note_previous_definition); 10612 10613 Invalid = true; 10614 } 10615 10616 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10617 if (TemplateParameterListsAreEqual(TemplateParams, 10618 OldDecl->getTemplateParameters(), 10619 /*Complain=*/true, 10620 TPL_TemplateMatch)) 10621 OldTemplateParams = 10622 OldDecl->getMostRecentDecl()->getTemplateParameters(); 10623 else 10624 Invalid = true; 10625 10626 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10627 if (!Invalid && 10628 !Context.hasSameType(OldTD->getUnderlyingType(), 10629 NewTD->getUnderlyingType())) { 10630 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10631 // but we can't reasonably accept it. 10632 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10633 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10634 if (OldTD->getLocation().isValid()) 10635 Diag(OldTD->getLocation(), diag::note_previous_definition); 10636 Invalid = true; 10637 } 10638 } 10639 } 10640 10641 // Merge any previous default template arguments into our parameters, 10642 // and check the parameter list. 10643 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10644 TPC_TypeAliasTemplate)) 10645 return nullptr; 10646 10647 TypeAliasTemplateDecl *NewDecl = 10648 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10649 Name.Identifier, TemplateParams, 10650 NewTD); 10651 NewTD->setDescribedAliasTemplate(NewDecl); 10652 10653 NewDecl->setAccess(AS); 10654 10655 if (Invalid) 10656 NewDecl->setInvalidDecl(); 10657 else if (OldDecl) { 10658 NewDecl->setPreviousDecl(OldDecl); 10659 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10660 } 10661 10662 NewND = NewDecl; 10663 } else { 10664 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10665 setTagNameForLinkagePurposes(TD, NewTD); 10666 handleTagNumbering(TD, S); 10667 } 10668 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10669 NewND = NewTD; 10670 } 10671 10672 PushOnScopeChains(NewND, S); 10673 ActOnDocumentableDecl(NewND); 10674 return NewND; 10675 } 10676 10677 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10678 SourceLocation AliasLoc, 10679 IdentifierInfo *Alias, CXXScopeSpec &SS, 10680 SourceLocation IdentLoc, 10681 IdentifierInfo *Ident) { 10682 10683 // Lookup the namespace name. 10684 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10685 LookupParsedName(R, S, &SS); 10686 10687 if (R.isAmbiguous()) 10688 return nullptr; 10689 10690 if (R.empty()) { 10691 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10692 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10693 return nullptr; 10694 } 10695 } 10696 assert(!R.isAmbiguous() && !R.empty()); 10697 NamedDecl *ND = R.getRepresentativeDecl(); 10698 10699 // Check if we have a previous declaration with the same name. 10700 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10701 ForVisibleRedeclaration); 10702 LookupName(PrevR, S); 10703 10704 // Check we're not shadowing a template parameter. 10705 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10706 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10707 PrevR.clear(); 10708 } 10709 10710 // Filter out any other lookup result from an enclosing scope. 10711 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10712 /*AllowInlineNamespace*/false); 10713 10714 // Find the previous declaration and check that we can redeclare it. 10715 NamespaceAliasDecl *Prev = nullptr; 10716 if (PrevR.isSingleResult()) { 10717 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10718 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10719 // We already have an alias with the same name that points to the same 10720 // namespace; check that it matches. 10721 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10722 Prev = AD; 10723 } else if (isVisible(PrevDecl)) { 10724 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10725 << Alias; 10726 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10727 << AD->getNamespace(); 10728 return nullptr; 10729 } 10730 } else if (isVisible(PrevDecl)) { 10731 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10732 ? diag::err_redefinition 10733 : diag::err_redefinition_different_kind; 10734 Diag(AliasLoc, DiagID) << Alias; 10735 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10736 return nullptr; 10737 } 10738 } 10739 10740 // The use of a nested name specifier may trigger deprecation warnings. 10741 DiagnoseUseOfDecl(ND, IdentLoc); 10742 10743 NamespaceAliasDecl *AliasDecl = 10744 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10745 Alias, SS.getWithLocInContext(Context), 10746 IdentLoc, ND); 10747 if (Prev) 10748 AliasDecl->setPreviousDecl(Prev); 10749 10750 PushOnScopeChains(AliasDecl, S); 10751 return AliasDecl; 10752 } 10753 10754 namespace { 10755 struct SpecialMemberExceptionSpecInfo 10756 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10757 SourceLocation Loc; 10758 Sema::ImplicitExceptionSpecification ExceptSpec; 10759 10760 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10761 Sema::CXXSpecialMember CSM, 10762 Sema::InheritedConstructorInfo *ICI, 10763 SourceLocation Loc) 10764 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10765 10766 bool visitBase(CXXBaseSpecifier *Base); 10767 bool visitField(FieldDecl *FD); 10768 10769 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10770 unsigned Quals); 10771 10772 void visitSubobjectCall(Subobject Subobj, 10773 Sema::SpecialMemberOverloadResult SMOR); 10774 }; 10775 } 10776 10777 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10778 auto *RT = Base->getType()->getAs<RecordType>(); 10779 if (!RT) 10780 return false; 10781 10782 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10783 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10784 if (auto *BaseCtor = SMOR.getMethod()) { 10785 visitSubobjectCall(Base, BaseCtor); 10786 return false; 10787 } 10788 10789 visitClassSubobject(BaseClass, Base, 0); 10790 return false; 10791 } 10792 10793 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10794 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10795 Expr *E = FD->getInClassInitializer(); 10796 if (!E) 10797 // FIXME: It's a little wasteful to build and throw away a 10798 // CXXDefaultInitExpr here. 10799 // FIXME: We should have a single context note pointing at Loc, and 10800 // this location should be MD->getLocation() instead, since that's 10801 // the location where we actually use the default init expression. 10802 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10803 if (E) 10804 ExceptSpec.CalledExpr(E); 10805 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10806 ->getAs<RecordType>()) { 10807 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10808 FD->getType().getCVRQualifiers()); 10809 } 10810 return false; 10811 } 10812 10813 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10814 Subobject Subobj, 10815 unsigned Quals) { 10816 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10817 bool IsMutable = Field && Field->isMutable(); 10818 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10819 } 10820 10821 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10822 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10823 // Note, if lookup fails, it doesn't matter what exception specification we 10824 // choose because the special member will be deleted. 10825 if (CXXMethodDecl *MD = SMOR.getMethod()) 10826 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10827 } 10828 10829 namespace { 10830 /// RAII object to register a special member as being currently declared. 10831 struct ComputingExceptionSpec { 10832 Sema &S; 10833 10834 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) 10835 : S(S) { 10836 Sema::CodeSynthesisContext Ctx; 10837 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 10838 Ctx.PointOfInstantiation = Loc; 10839 Ctx.Entity = MD; 10840 S.pushCodeSynthesisContext(Ctx); 10841 } 10842 ~ComputingExceptionSpec() { 10843 S.popCodeSynthesisContext(); 10844 } 10845 }; 10846 } 10847 10848 static Sema::ImplicitExceptionSpecification 10849 ComputeDefaultedSpecialMemberExceptionSpec( 10850 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10851 Sema::InheritedConstructorInfo *ICI) { 10852 ComputingExceptionSpec CES(S, MD, Loc); 10853 10854 CXXRecordDecl *ClassDecl = MD->getParent(); 10855 10856 // C++ [except.spec]p14: 10857 // An implicitly declared special member function (Clause 12) shall have an 10858 // exception-specification. [...] 10859 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 10860 if (ClassDecl->isInvalidDecl()) 10861 return Info.ExceptSpec; 10862 10863 // FIXME: If this diagnostic fires, we're probably missing a check for 10864 // attempting to resolve an exception specification before it's known 10865 // at a higher level. 10866 if (S.RequireCompleteType(MD->getLocation(), 10867 S.Context.getRecordType(ClassDecl), 10868 diag::err_exception_spec_incomplete_type)) 10869 return Info.ExceptSpec; 10870 10871 // C++1z [except.spec]p7: 10872 // [Look for exceptions thrown by] a constructor selected [...] to 10873 // initialize a potentially constructed subobject, 10874 // C++1z [except.spec]p8: 10875 // The exception specification for an implicitly-declared destructor, or a 10876 // destructor without a noexcept-specifier, is potentially-throwing if and 10877 // only if any of the destructors for any of its potentially constructed 10878 // subojects is potentially throwing. 10879 // FIXME: We respect the first rule but ignore the "potentially constructed" 10880 // in the second rule to resolve a core issue (no number yet) that would have 10881 // us reject: 10882 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10883 // struct B : A {}; 10884 // struct C : B { void f(); }; 10885 // ... due to giving B::~B() a non-throwing exception specification. 10886 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10887 : Info.VisitAllBases); 10888 10889 return Info.ExceptSpec; 10890 } 10891 10892 namespace { 10893 /// RAII object to register a special member as being currently declared. 10894 struct DeclaringSpecialMember { 10895 Sema &S; 10896 Sema::SpecialMemberDecl D; 10897 Sema::ContextRAII SavedContext; 10898 bool WasAlreadyBeingDeclared; 10899 10900 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10901 : S(S), D(RD, CSM), SavedContext(S, RD) { 10902 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10903 if (WasAlreadyBeingDeclared) 10904 // This almost never happens, but if it does, ensure that our cache 10905 // doesn't contain a stale result. 10906 S.SpecialMemberCache.clear(); 10907 else { 10908 // Register a note to be produced if we encounter an error while 10909 // declaring the special member. 10910 Sema::CodeSynthesisContext Ctx; 10911 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10912 // FIXME: We don't have a location to use here. Using the class's 10913 // location maintains the fiction that we declare all special members 10914 // with the class, but (1) it's not clear that lying about that helps our 10915 // users understand what's going on, and (2) there may be outer contexts 10916 // on the stack (some of which are relevant) and printing them exposes 10917 // our lies. 10918 Ctx.PointOfInstantiation = RD->getLocation(); 10919 Ctx.Entity = RD; 10920 Ctx.SpecialMember = CSM; 10921 S.pushCodeSynthesisContext(Ctx); 10922 } 10923 } 10924 ~DeclaringSpecialMember() { 10925 if (!WasAlreadyBeingDeclared) { 10926 S.SpecialMembersBeingDeclared.erase(D); 10927 S.popCodeSynthesisContext(); 10928 } 10929 } 10930 10931 /// Are we already trying to declare this special member? 10932 bool isAlreadyBeingDeclared() const { 10933 return WasAlreadyBeingDeclared; 10934 } 10935 }; 10936 } 10937 10938 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10939 // Look up any existing declarations, but don't trigger declaration of all 10940 // implicit special members with this name. 10941 DeclarationName Name = FD->getDeclName(); 10942 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10943 ForExternalRedeclaration); 10944 for (auto *D : FD->getParent()->lookup(Name)) 10945 if (auto *Acceptable = R.getAcceptableDecl(D)) 10946 R.addDecl(Acceptable); 10947 R.resolveKind(); 10948 R.suppressDiagnostics(); 10949 10950 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10951 } 10952 10953 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 10954 QualType ResultTy, 10955 ArrayRef<QualType> Args) { 10956 // Build an exception specification pointing back at this constructor. 10957 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 10958 10959 if (getLangOpts().OpenCLCPlusPlus) { 10960 // OpenCL: Implicitly defaulted special member are of the generic address 10961 // space. 10962 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic); 10963 } 10964 10965 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 10966 SpecialMem->setType(QT); 10967 } 10968 10969 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10970 CXXRecordDecl *ClassDecl) { 10971 // C++ [class.ctor]p5: 10972 // A default constructor for a class X is a constructor of class X 10973 // that can be called without an argument. If there is no 10974 // user-declared constructor for class X, a default constructor is 10975 // implicitly declared. An implicitly-declared default constructor 10976 // is an inline public member of its class. 10977 assert(ClassDecl->needsImplicitDefaultConstructor() && 10978 "Should not build implicit default constructor!"); 10979 10980 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10981 if (DSM.isAlreadyBeingDeclared()) 10982 return nullptr; 10983 10984 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10985 CXXDefaultConstructor, 10986 false); 10987 10988 // Create the actual constructor declaration. 10989 CanQualType ClassType 10990 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10991 SourceLocation ClassLoc = ClassDecl->getLocation(); 10992 DeclarationName Name 10993 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10994 DeclarationNameInfo NameInfo(Name, ClassLoc); 10995 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10996 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10997 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10998 /*isImplicitlyDeclared=*/true, Constexpr); 10999 DefaultCon->setAccess(AS_public); 11000 DefaultCon->setDefaulted(); 11001 11002 if (getLangOpts().CUDA) { 11003 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 11004 DefaultCon, 11005 /* ConstRHS */ false, 11006 /* Diagnose */ false); 11007 } 11008 11009 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 11010 11011 // We don't need to use SpecialMemberIsTrivial here; triviality for default 11012 // constructors is easy to compute. 11013 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 11014 11015 // Note that we have declared this constructor. 11016 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 11017 11018 Scope *S = getScopeForContext(ClassDecl); 11019 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 11020 11021 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 11022 SetDeclDeleted(DefaultCon, ClassLoc); 11023 11024 if (S) 11025 PushOnScopeChains(DefaultCon, S, false); 11026 ClassDecl->addDecl(DefaultCon); 11027 11028 return DefaultCon; 11029 } 11030 11031 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 11032 CXXConstructorDecl *Constructor) { 11033 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 11034 !Constructor->doesThisDeclarationHaveABody() && 11035 !Constructor->isDeleted()) && 11036 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 11037 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11038 return; 11039 11040 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11041 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 11042 11043 SynthesizedFunctionScope Scope(*this, Constructor); 11044 11045 // The exception specification is needed because we are defining the 11046 // function. 11047 ResolveExceptionSpec(CurrentLocation, 11048 Constructor->getType()->castAs<FunctionProtoType>()); 11049 MarkVTableUsed(CurrentLocation, ClassDecl); 11050 11051 // Add a context note for diagnostics produced after this point. 11052 Scope.addContextNote(CurrentLocation); 11053 11054 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 11055 Constructor->setInvalidDecl(); 11056 return; 11057 } 11058 11059 SourceLocation Loc = Constructor->getEndLoc().isValid() 11060 ? Constructor->getEndLoc() 11061 : Constructor->getLocation(); 11062 Constructor->setBody(new (Context) CompoundStmt(Loc)); 11063 Constructor->markUsed(Context); 11064 11065 if (ASTMutationListener *L = getASTMutationListener()) { 11066 L->CompletedImplicitDefinition(Constructor); 11067 } 11068 11069 DiagnoseUninitializedFields(*this, Constructor); 11070 } 11071 11072 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 11073 // Perform any delayed checks on exception specifications. 11074 CheckDelayedMemberExceptionSpecs(); 11075 } 11076 11077 /// Find or create the fake constructor we synthesize to model constructing an 11078 /// object of a derived class via a constructor of a base class. 11079 CXXConstructorDecl * 11080 Sema::findInheritingConstructor(SourceLocation Loc, 11081 CXXConstructorDecl *BaseCtor, 11082 ConstructorUsingShadowDecl *Shadow) { 11083 CXXRecordDecl *Derived = Shadow->getParent(); 11084 SourceLocation UsingLoc = Shadow->getLocation(); 11085 11086 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 11087 // For now we use the name of the base class constructor as a member of the 11088 // derived class to indicate a (fake) inherited constructor name. 11089 DeclarationName Name = BaseCtor->getDeclName(); 11090 11091 // Check to see if we already have a fake constructor for this inherited 11092 // constructor call. 11093 for (NamedDecl *Ctor : Derived->lookup(Name)) 11094 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 11095 ->getInheritedConstructor() 11096 .getConstructor(), 11097 BaseCtor)) 11098 return cast<CXXConstructorDecl>(Ctor); 11099 11100 DeclarationNameInfo NameInfo(Name, UsingLoc); 11101 TypeSourceInfo *TInfo = 11102 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 11103 FunctionProtoTypeLoc ProtoLoc = 11104 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 11105 11106 // Check the inherited constructor is valid and find the list of base classes 11107 // from which it was inherited. 11108 InheritedConstructorInfo ICI(*this, Loc, Shadow); 11109 11110 bool Constexpr = 11111 BaseCtor->isConstexpr() && 11112 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 11113 false, BaseCtor, &ICI); 11114 11115 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 11116 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 11117 BaseCtor->isExplicit(), /*Inline=*/true, 11118 /*ImplicitlyDeclared=*/true, Constexpr, 11119 InheritedConstructor(Shadow, BaseCtor)); 11120 if (Shadow->isInvalidDecl()) 11121 DerivedCtor->setInvalidDecl(); 11122 11123 // Build an unevaluated exception specification for this fake constructor. 11124 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 11125 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11126 EPI.ExceptionSpec.Type = EST_Unevaluated; 11127 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 11128 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 11129 FPT->getParamTypes(), EPI)); 11130 11131 // Build the parameter declarations. 11132 SmallVector<ParmVarDecl *, 16> ParamDecls; 11133 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 11134 TypeSourceInfo *TInfo = 11135 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 11136 ParmVarDecl *PD = ParmVarDecl::Create( 11137 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 11138 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 11139 PD->setScopeInfo(0, I); 11140 PD->setImplicit(); 11141 // Ensure attributes are propagated onto parameters (this matters for 11142 // format, pass_object_size, ...). 11143 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 11144 ParamDecls.push_back(PD); 11145 ProtoLoc.setParam(I, PD); 11146 } 11147 11148 // Set up the new constructor. 11149 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 11150 DerivedCtor->setAccess(BaseCtor->getAccess()); 11151 DerivedCtor->setParams(ParamDecls); 11152 Derived->addDecl(DerivedCtor); 11153 11154 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 11155 SetDeclDeleted(DerivedCtor, UsingLoc); 11156 11157 return DerivedCtor; 11158 } 11159 11160 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 11161 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 11162 Ctor->getInheritedConstructor().getShadowDecl()); 11163 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 11164 /*Diagnose*/true); 11165 } 11166 11167 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 11168 CXXConstructorDecl *Constructor) { 11169 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11170 assert(Constructor->getInheritedConstructor() && 11171 !Constructor->doesThisDeclarationHaveABody() && 11172 !Constructor->isDeleted()); 11173 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11174 return; 11175 11176 // Initializations are performed "as if by a defaulted default constructor", 11177 // so enter the appropriate scope. 11178 SynthesizedFunctionScope Scope(*this, Constructor); 11179 11180 // The exception specification is needed because we are defining the 11181 // function. 11182 ResolveExceptionSpec(CurrentLocation, 11183 Constructor->getType()->castAs<FunctionProtoType>()); 11184 MarkVTableUsed(CurrentLocation, ClassDecl); 11185 11186 // Add a context note for diagnostics produced after this point. 11187 Scope.addContextNote(CurrentLocation); 11188 11189 ConstructorUsingShadowDecl *Shadow = 11190 Constructor->getInheritedConstructor().getShadowDecl(); 11191 CXXConstructorDecl *InheritedCtor = 11192 Constructor->getInheritedConstructor().getConstructor(); 11193 11194 // [class.inhctor.init]p1: 11195 // initialization proceeds as if a defaulted default constructor is used to 11196 // initialize the D object and each base class subobject from which the 11197 // constructor was inherited 11198 11199 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11200 CXXRecordDecl *RD = Shadow->getParent(); 11201 SourceLocation InitLoc = Shadow->getLocation(); 11202 11203 // Build explicit initializers for all base classes from which the 11204 // constructor was inherited. 11205 SmallVector<CXXCtorInitializer*, 8> Inits; 11206 for (bool VBase : {false, true}) { 11207 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11208 if (B.isVirtual() != VBase) 11209 continue; 11210 11211 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11212 if (!BaseRD) 11213 continue; 11214 11215 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11216 if (!BaseCtor.first) 11217 continue; 11218 11219 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11220 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11221 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11222 11223 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11224 Inits.push_back(new (Context) CXXCtorInitializer( 11225 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11226 SourceLocation())); 11227 } 11228 } 11229 11230 // We now proceed as if for a defaulted default constructor, with the relevant 11231 // initializers replaced. 11232 11233 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11234 Constructor->setInvalidDecl(); 11235 return; 11236 } 11237 11238 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11239 Constructor->markUsed(Context); 11240 11241 if (ASTMutationListener *L = getASTMutationListener()) { 11242 L->CompletedImplicitDefinition(Constructor); 11243 } 11244 11245 DiagnoseUninitializedFields(*this, Constructor); 11246 } 11247 11248 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11249 // C++ [class.dtor]p2: 11250 // If a class has no user-declared destructor, a destructor is 11251 // declared implicitly. An implicitly-declared destructor is an 11252 // inline public member of its class. 11253 assert(ClassDecl->needsImplicitDestructor()); 11254 11255 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11256 if (DSM.isAlreadyBeingDeclared()) 11257 return nullptr; 11258 11259 // Create the actual destructor declaration. 11260 CanQualType ClassType 11261 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11262 SourceLocation ClassLoc = ClassDecl->getLocation(); 11263 DeclarationName Name 11264 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11265 DeclarationNameInfo NameInfo(Name, ClassLoc); 11266 CXXDestructorDecl *Destructor 11267 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11268 QualType(), nullptr, /*isInline=*/true, 11269 /*isImplicitlyDeclared=*/true); 11270 Destructor->setAccess(AS_public); 11271 Destructor->setDefaulted(); 11272 11273 if (getLangOpts().CUDA) { 11274 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11275 Destructor, 11276 /* ConstRHS */ false, 11277 /* Diagnose */ false); 11278 } 11279 11280 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 11281 11282 // We don't need to use SpecialMemberIsTrivial here; triviality for 11283 // destructors is easy to compute. 11284 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11285 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11286 ClassDecl->hasTrivialDestructorForCall()); 11287 11288 // Note that we have declared this destructor. 11289 ++ASTContext::NumImplicitDestructorsDeclared; 11290 11291 Scope *S = getScopeForContext(ClassDecl); 11292 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11293 11294 // We can't check whether an implicit destructor is deleted before we complete 11295 // the definition of the class, because its validity depends on the alignment 11296 // of the class. We'll check this from ActOnFields once the class is complete. 11297 if (ClassDecl->isCompleteDefinition() && 11298 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11299 SetDeclDeleted(Destructor, ClassLoc); 11300 11301 // Introduce this destructor into its scope. 11302 if (S) 11303 PushOnScopeChains(Destructor, S, false); 11304 ClassDecl->addDecl(Destructor); 11305 11306 return Destructor; 11307 } 11308 11309 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11310 CXXDestructorDecl *Destructor) { 11311 assert((Destructor->isDefaulted() && 11312 !Destructor->doesThisDeclarationHaveABody() && 11313 !Destructor->isDeleted()) && 11314 "DefineImplicitDestructor - call it for implicit default dtor"); 11315 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11316 return; 11317 11318 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11319 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11320 11321 SynthesizedFunctionScope Scope(*this, Destructor); 11322 11323 // The exception specification is needed because we are defining the 11324 // function. 11325 ResolveExceptionSpec(CurrentLocation, 11326 Destructor->getType()->castAs<FunctionProtoType>()); 11327 MarkVTableUsed(CurrentLocation, ClassDecl); 11328 11329 // Add a context note for diagnostics produced after this point. 11330 Scope.addContextNote(CurrentLocation); 11331 11332 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11333 Destructor->getParent()); 11334 11335 if (CheckDestructor(Destructor)) { 11336 Destructor->setInvalidDecl(); 11337 return; 11338 } 11339 11340 SourceLocation Loc = Destructor->getEndLoc().isValid() 11341 ? Destructor->getEndLoc() 11342 : Destructor->getLocation(); 11343 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11344 Destructor->markUsed(Context); 11345 11346 if (ASTMutationListener *L = getASTMutationListener()) { 11347 L->CompletedImplicitDefinition(Destructor); 11348 } 11349 } 11350 11351 /// Perform any semantic analysis which needs to be delayed until all 11352 /// pending class member declarations have been parsed. 11353 void Sema::ActOnFinishCXXMemberDecls() { 11354 // If the context is an invalid C++ class, just suppress these checks. 11355 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11356 if (Record->isInvalidDecl()) { 11357 DelayedOverridingExceptionSpecChecks.clear(); 11358 DelayedEquivalentExceptionSpecChecks.clear(); 11359 DelayedDefaultedMemberExceptionSpecs.clear(); 11360 return; 11361 } 11362 checkForMultipleExportedDefaultConstructors(*this, Record); 11363 } 11364 } 11365 11366 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11367 referenceDLLExportedClassMethods(); 11368 } 11369 11370 void Sema::referenceDLLExportedClassMethods() { 11371 if (!DelayedDllExportClasses.empty()) { 11372 // Calling ReferenceDllExportedMembers might cause the current function to 11373 // be called again, so use a local copy of DelayedDllExportClasses. 11374 SmallVector<CXXRecordDecl *, 4> WorkList; 11375 std::swap(DelayedDllExportClasses, WorkList); 11376 for (CXXRecordDecl *Class : WorkList) 11377 ReferenceDllExportedMembers(*this, Class); 11378 } 11379 } 11380 11381 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 11382 assert(getLangOpts().CPlusPlus11 && 11383 "adjusting dtor exception specs was introduced in c++11"); 11384 11385 if (Destructor->isDependentContext()) 11386 return; 11387 11388 // C++11 [class.dtor]p3: 11389 // A declaration of a destructor that does not have an exception- 11390 // specification is implicitly considered to have the same exception- 11391 // specification as an implicit declaration. 11392 const FunctionProtoType *DtorType = Destructor->getType()-> 11393 getAs<FunctionProtoType>(); 11394 if (DtorType->hasExceptionSpec()) 11395 return; 11396 11397 // Replace the destructor's type, building off the existing one. Fortunately, 11398 // the only thing of interest in the destructor type is its extended info. 11399 // The return and arguments are fixed. 11400 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11401 EPI.ExceptionSpec.Type = EST_Unevaluated; 11402 EPI.ExceptionSpec.SourceDecl = Destructor; 11403 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11404 11405 // FIXME: If the destructor has a body that could throw, and the newly created 11406 // spec doesn't allow exceptions, we should emit a warning, because this 11407 // change in behavior can break conforming C++03 programs at runtime. 11408 // However, we don't have a body or an exception specification yet, so it 11409 // needs to be done somewhere else. 11410 } 11411 11412 namespace { 11413 /// An abstract base class for all helper classes used in building the 11414 // copy/move operators. These classes serve as factory functions and help us 11415 // avoid using the same Expr* in the AST twice. 11416 class ExprBuilder { 11417 ExprBuilder(const ExprBuilder&) = delete; 11418 ExprBuilder &operator=(const ExprBuilder&) = delete; 11419 11420 protected: 11421 static Expr *assertNotNull(Expr *E) { 11422 assert(E && "Expression construction must not fail."); 11423 return E; 11424 } 11425 11426 public: 11427 ExprBuilder() {} 11428 virtual ~ExprBuilder() {} 11429 11430 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11431 }; 11432 11433 class RefBuilder: public ExprBuilder { 11434 VarDecl *Var; 11435 QualType VarType; 11436 11437 public: 11438 Expr *build(Sema &S, SourceLocation Loc) const override { 11439 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 11440 } 11441 11442 RefBuilder(VarDecl *Var, QualType VarType) 11443 : Var(Var), VarType(VarType) {} 11444 }; 11445 11446 class ThisBuilder: public ExprBuilder { 11447 public: 11448 Expr *build(Sema &S, SourceLocation Loc) const override { 11449 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11450 } 11451 }; 11452 11453 class CastBuilder: public ExprBuilder { 11454 const ExprBuilder &Builder; 11455 QualType Type; 11456 ExprValueKind Kind; 11457 const CXXCastPath &Path; 11458 11459 public: 11460 Expr *build(Sema &S, SourceLocation Loc) const override { 11461 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11462 CK_UncheckedDerivedToBase, Kind, 11463 &Path).get()); 11464 } 11465 11466 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11467 const CXXCastPath &Path) 11468 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11469 }; 11470 11471 class DerefBuilder: public ExprBuilder { 11472 const ExprBuilder &Builder; 11473 11474 public: 11475 Expr *build(Sema &S, SourceLocation Loc) const override { 11476 return assertNotNull( 11477 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11478 } 11479 11480 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11481 }; 11482 11483 class MemberBuilder: public ExprBuilder { 11484 const ExprBuilder &Builder; 11485 QualType Type; 11486 CXXScopeSpec SS; 11487 bool IsArrow; 11488 LookupResult &MemberLookup; 11489 11490 public: 11491 Expr *build(Sema &S, SourceLocation Loc) const override { 11492 return assertNotNull(S.BuildMemberReferenceExpr( 11493 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11494 nullptr, MemberLookup, nullptr, nullptr).get()); 11495 } 11496 11497 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11498 LookupResult &MemberLookup) 11499 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11500 MemberLookup(MemberLookup) {} 11501 }; 11502 11503 class MoveCastBuilder: public ExprBuilder { 11504 const ExprBuilder &Builder; 11505 11506 public: 11507 Expr *build(Sema &S, SourceLocation Loc) const override { 11508 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11509 } 11510 11511 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11512 }; 11513 11514 class LvalueConvBuilder: public ExprBuilder { 11515 const ExprBuilder &Builder; 11516 11517 public: 11518 Expr *build(Sema &S, SourceLocation Loc) const override { 11519 return assertNotNull( 11520 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11521 } 11522 11523 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11524 }; 11525 11526 class SubscriptBuilder: public ExprBuilder { 11527 const ExprBuilder &Base; 11528 const ExprBuilder &Index; 11529 11530 public: 11531 Expr *build(Sema &S, SourceLocation Loc) const override { 11532 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11533 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11534 } 11535 11536 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11537 : Base(Base), Index(Index) {} 11538 }; 11539 11540 } // end anonymous namespace 11541 11542 /// When generating a defaulted copy or move assignment operator, if a field 11543 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11544 /// do so. This optimization only applies for arrays of scalars, and for arrays 11545 /// of class type where the selected copy/move-assignment operator is trivial. 11546 static StmtResult 11547 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11548 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11549 // Compute the size of the memory buffer to be copied. 11550 QualType SizeType = S.Context.getSizeType(); 11551 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11552 S.Context.getTypeSizeInChars(T).getQuantity()); 11553 11554 // Take the address of the field references for "from" and "to". We 11555 // directly construct UnaryOperators here because semantic analysis 11556 // does not permit us to take the address of an xvalue. 11557 Expr *From = FromB.build(S, Loc); 11558 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11559 S.Context.getPointerType(From->getType()), 11560 VK_RValue, OK_Ordinary, Loc, false); 11561 Expr *To = ToB.build(S, Loc); 11562 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11563 S.Context.getPointerType(To->getType()), 11564 VK_RValue, OK_Ordinary, Loc, false); 11565 11566 const Type *E = T->getBaseElementTypeUnsafe(); 11567 bool NeedsCollectableMemCpy = 11568 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11569 11570 // Create a reference to the __builtin_objc_memmove_collectable function 11571 StringRef MemCpyName = NeedsCollectableMemCpy ? 11572 "__builtin_objc_memmove_collectable" : 11573 "__builtin_memcpy"; 11574 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11575 Sema::LookupOrdinaryName); 11576 S.LookupName(R, S.TUScope, true); 11577 11578 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11579 if (!MemCpy) 11580 // Something went horribly wrong earlier, and we will have complained 11581 // about it. 11582 return StmtError(); 11583 11584 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11585 VK_RValue, Loc, nullptr); 11586 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11587 11588 Expr *CallArgs[] = { 11589 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11590 }; 11591 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11592 Loc, CallArgs, Loc); 11593 11594 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11595 return Call.getAs<Stmt>(); 11596 } 11597 11598 /// Builds a statement that copies/moves the given entity from \p From to 11599 /// \c To. 11600 /// 11601 /// This routine is used to copy/move the members of a class with an 11602 /// implicitly-declared copy/move assignment operator. When the entities being 11603 /// copied are arrays, this routine builds for loops to copy them. 11604 /// 11605 /// \param S The Sema object used for type-checking. 11606 /// 11607 /// \param Loc The location where the implicit copy/move is being generated. 11608 /// 11609 /// \param T The type of the expressions being copied/moved. Both expressions 11610 /// must have this type. 11611 /// 11612 /// \param To The expression we are copying/moving to. 11613 /// 11614 /// \param From The expression we are copying/moving from. 11615 /// 11616 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11617 /// Otherwise, it's a non-static member subobject. 11618 /// 11619 /// \param Copying Whether we're copying or moving. 11620 /// 11621 /// \param Depth Internal parameter recording the depth of the recursion. 11622 /// 11623 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11624 /// if a memcpy should be used instead. 11625 static StmtResult 11626 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11627 const ExprBuilder &To, const ExprBuilder &From, 11628 bool CopyingBaseSubobject, bool Copying, 11629 unsigned Depth = 0) { 11630 // C++11 [class.copy]p28: 11631 // Each subobject is assigned in the manner appropriate to its type: 11632 // 11633 // - if the subobject is of class type, as if by a call to operator= with 11634 // the subobject as the object expression and the corresponding 11635 // subobject of x as a single function argument (as if by explicit 11636 // qualification; that is, ignoring any possible virtual overriding 11637 // functions in more derived classes); 11638 // 11639 // C++03 [class.copy]p13: 11640 // - if the subobject is of class type, the copy assignment operator for 11641 // the class is used (as if by explicit qualification; that is, 11642 // ignoring any possible virtual overriding functions in more derived 11643 // classes); 11644 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11645 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11646 11647 // Look for operator=. 11648 DeclarationName Name 11649 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11650 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11651 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11652 11653 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11654 // operator. 11655 if (!S.getLangOpts().CPlusPlus11) { 11656 LookupResult::Filter F = OpLookup.makeFilter(); 11657 while (F.hasNext()) { 11658 NamedDecl *D = F.next(); 11659 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11660 if (Method->isCopyAssignmentOperator() || 11661 (!Copying && Method->isMoveAssignmentOperator())) 11662 continue; 11663 11664 F.erase(); 11665 } 11666 F.done(); 11667 } 11668 11669 // Suppress the protected check (C++ [class.protected]) for each of the 11670 // assignment operators we found. This strange dance is required when 11671 // we're assigning via a base classes's copy-assignment operator. To 11672 // ensure that we're getting the right base class subobject (without 11673 // ambiguities), we need to cast "this" to that subobject type; to 11674 // ensure that we don't go through the virtual call mechanism, we need 11675 // to qualify the operator= name with the base class (see below). However, 11676 // this means that if the base class has a protected copy assignment 11677 // operator, the protected member access check will fail. So, we 11678 // rewrite "protected" access to "public" access in this case, since we 11679 // know by construction that we're calling from a derived class. 11680 if (CopyingBaseSubobject) { 11681 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11682 L != LEnd; ++L) { 11683 if (L.getAccess() == AS_protected) 11684 L.setAccess(AS_public); 11685 } 11686 } 11687 11688 // Create the nested-name-specifier that will be used to qualify the 11689 // reference to operator=; this is required to suppress the virtual 11690 // call mechanism. 11691 CXXScopeSpec SS; 11692 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11693 SS.MakeTrivial(S.Context, 11694 NestedNameSpecifier::Create(S.Context, nullptr, false, 11695 CanonicalT), 11696 Loc); 11697 11698 // Create the reference to operator=. 11699 ExprResult OpEqualRef 11700 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11701 SS, /*TemplateKWLoc=*/SourceLocation(), 11702 /*FirstQualifierInScope=*/nullptr, 11703 OpLookup, 11704 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11705 /*SuppressQualifierCheck=*/true); 11706 if (OpEqualRef.isInvalid()) 11707 return StmtError(); 11708 11709 // Build the call to the assignment operator. 11710 11711 Expr *FromInst = From.build(S, Loc); 11712 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11713 OpEqualRef.getAs<Expr>(), 11714 Loc, FromInst, Loc); 11715 if (Call.isInvalid()) 11716 return StmtError(); 11717 11718 // If we built a call to a trivial 'operator=' while copying an array, 11719 // bail out. We'll replace the whole shebang with a memcpy. 11720 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11721 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11722 return StmtResult((Stmt*)nullptr); 11723 11724 // Convert to an expression-statement, and clean up any produced 11725 // temporaries. 11726 return S.ActOnExprStmt(Call); 11727 } 11728 11729 // - if the subobject is of scalar type, the built-in assignment 11730 // operator is used. 11731 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11732 if (!ArrayTy) { 11733 ExprResult Assignment = S.CreateBuiltinBinOp( 11734 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11735 if (Assignment.isInvalid()) 11736 return StmtError(); 11737 return S.ActOnExprStmt(Assignment); 11738 } 11739 11740 // - if the subobject is an array, each element is assigned, in the 11741 // manner appropriate to the element type; 11742 11743 // Construct a loop over the array bounds, e.g., 11744 // 11745 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11746 // 11747 // that will copy each of the array elements. 11748 QualType SizeType = S.Context.getSizeType(); 11749 11750 // Create the iteration variable. 11751 IdentifierInfo *IterationVarName = nullptr; 11752 { 11753 SmallString<8> Str; 11754 llvm::raw_svector_ostream OS(Str); 11755 OS << "__i" << Depth; 11756 IterationVarName = &S.Context.Idents.get(OS.str()); 11757 } 11758 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11759 IterationVarName, SizeType, 11760 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11761 SC_None); 11762 11763 // Initialize the iteration variable to zero. 11764 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11765 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11766 11767 // Creates a reference to the iteration variable. 11768 RefBuilder IterationVarRef(IterationVar, SizeType); 11769 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11770 11771 // Create the DeclStmt that holds the iteration variable. 11772 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11773 11774 // Subscript the "from" and "to" expressions with the iteration variable. 11775 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11776 MoveCastBuilder FromIndexMove(FromIndexCopy); 11777 const ExprBuilder *FromIndex; 11778 if (Copying) 11779 FromIndex = &FromIndexCopy; 11780 else 11781 FromIndex = &FromIndexMove; 11782 11783 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11784 11785 // Build the copy/move for an individual element of the array. 11786 StmtResult Copy = 11787 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11788 ToIndex, *FromIndex, CopyingBaseSubobject, 11789 Copying, Depth + 1); 11790 // Bail out if copying fails or if we determined that we should use memcpy. 11791 if (Copy.isInvalid() || !Copy.get()) 11792 return Copy; 11793 11794 // Create the comparison against the array bound. 11795 llvm::APInt Upper 11796 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11797 Expr *Comparison 11798 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11799 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11800 BO_NE, S.Context.BoolTy, 11801 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11802 11803 // Create the pre-increment of the iteration variable. We can determine 11804 // whether the increment will overflow based on the value of the array 11805 // bound. 11806 Expr *Increment = new (S.Context) 11807 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11808 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11809 11810 // Construct the loop that copies all elements of this array. 11811 return S.ActOnForStmt( 11812 Loc, Loc, InitStmt, 11813 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11814 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11815 } 11816 11817 static StmtResult 11818 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11819 const ExprBuilder &To, const ExprBuilder &From, 11820 bool CopyingBaseSubobject, bool Copying) { 11821 // Maybe we should use a memcpy? 11822 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11823 T.isTriviallyCopyableType(S.Context)) 11824 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11825 11826 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11827 CopyingBaseSubobject, 11828 Copying, 0)); 11829 11830 // If we ended up picking a trivial assignment operator for an array of a 11831 // non-trivially-copyable class type, just emit a memcpy. 11832 if (!Result.isInvalid() && !Result.get()) 11833 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11834 11835 return Result; 11836 } 11837 11838 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11839 // Note: The following rules are largely analoguous to the copy 11840 // constructor rules. Note that virtual bases are not taken into account 11841 // for determining the argument type of the operator. Note also that 11842 // operators taking an object instead of a reference are allowed. 11843 assert(ClassDecl->needsImplicitCopyAssignment()); 11844 11845 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11846 if (DSM.isAlreadyBeingDeclared()) 11847 return nullptr; 11848 11849 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11850 if (Context.getLangOpts().OpenCLCPlusPlus) 11851 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 11852 QualType RetType = Context.getLValueReferenceType(ArgType); 11853 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11854 if (Const) 11855 ArgType = ArgType.withConst(); 11856 11857 ArgType = Context.getLValueReferenceType(ArgType); 11858 11859 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11860 CXXCopyAssignment, 11861 Const); 11862 11863 // An implicitly-declared copy assignment operator is an inline public 11864 // member of its class. 11865 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11866 SourceLocation ClassLoc = ClassDecl->getLocation(); 11867 DeclarationNameInfo NameInfo(Name, ClassLoc); 11868 CXXMethodDecl *CopyAssignment = 11869 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11870 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11871 /*isInline=*/true, Constexpr, SourceLocation()); 11872 CopyAssignment->setAccess(AS_public); 11873 CopyAssignment->setDefaulted(); 11874 CopyAssignment->setImplicit(); 11875 11876 if (getLangOpts().CUDA) { 11877 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11878 CopyAssignment, 11879 /* ConstRHS */ Const, 11880 /* Diagnose */ false); 11881 } 11882 11883 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 11884 11885 // Add the parameter to the operator. 11886 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11887 ClassLoc, ClassLoc, 11888 /*Id=*/nullptr, ArgType, 11889 /*TInfo=*/nullptr, SC_None, 11890 nullptr); 11891 CopyAssignment->setParams(FromParam); 11892 11893 CopyAssignment->setTrivial( 11894 ClassDecl->needsOverloadResolutionForCopyAssignment() 11895 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11896 : ClassDecl->hasTrivialCopyAssignment()); 11897 11898 // Note that we have added this copy-assignment operator. 11899 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11900 11901 Scope *S = getScopeForContext(ClassDecl); 11902 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11903 11904 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11905 SetDeclDeleted(CopyAssignment, ClassLoc); 11906 11907 if (S) 11908 PushOnScopeChains(CopyAssignment, S, false); 11909 ClassDecl->addDecl(CopyAssignment); 11910 11911 return CopyAssignment; 11912 } 11913 11914 /// Diagnose an implicit copy operation for a class which is odr-used, but 11915 /// which is deprecated because the class has a user-declared copy constructor, 11916 /// copy assignment operator, or destructor. 11917 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11918 assert(CopyOp->isImplicit()); 11919 11920 CXXRecordDecl *RD = CopyOp->getParent(); 11921 CXXMethodDecl *UserDeclaredOperation = nullptr; 11922 11923 // In Microsoft mode, assignment operations don't affect constructors and 11924 // vice versa. 11925 if (RD->hasUserDeclaredDestructor()) { 11926 UserDeclaredOperation = RD->getDestructor(); 11927 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11928 RD->hasUserDeclaredCopyConstructor() && 11929 !S.getLangOpts().MSVCCompat) { 11930 // Find any user-declared copy constructor. 11931 for (auto *I : RD->ctors()) { 11932 if (I->isCopyConstructor()) { 11933 UserDeclaredOperation = I; 11934 break; 11935 } 11936 } 11937 assert(UserDeclaredOperation); 11938 } else if (isa<CXXConstructorDecl>(CopyOp) && 11939 RD->hasUserDeclaredCopyAssignment() && 11940 !S.getLangOpts().MSVCCompat) { 11941 // Find any user-declared move assignment operator. 11942 for (auto *I : RD->methods()) { 11943 if (I->isCopyAssignmentOperator()) { 11944 UserDeclaredOperation = I; 11945 break; 11946 } 11947 } 11948 assert(UserDeclaredOperation); 11949 } 11950 11951 if (UserDeclaredOperation) { 11952 S.Diag(UserDeclaredOperation->getLocation(), 11953 diag::warn_deprecated_copy_operation) 11954 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11955 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11956 } 11957 } 11958 11959 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11960 CXXMethodDecl *CopyAssignOperator) { 11961 assert((CopyAssignOperator->isDefaulted() && 11962 CopyAssignOperator->isOverloadedOperator() && 11963 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11964 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11965 !CopyAssignOperator->isDeleted()) && 11966 "DefineImplicitCopyAssignment called for wrong function"); 11967 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11968 return; 11969 11970 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11971 if (ClassDecl->isInvalidDecl()) { 11972 CopyAssignOperator->setInvalidDecl(); 11973 return; 11974 } 11975 11976 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11977 11978 // The exception specification is needed because we are defining the 11979 // function. 11980 ResolveExceptionSpec(CurrentLocation, 11981 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11982 11983 // Add a context note for diagnostics produced after this point. 11984 Scope.addContextNote(CurrentLocation); 11985 11986 // C++11 [class.copy]p18: 11987 // The [definition of an implicitly declared copy assignment operator] is 11988 // deprecated if the class has a user-declared copy constructor or a 11989 // user-declared destructor. 11990 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11991 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11992 11993 // C++0x [class.copy]p30: 11994 // The implicitly-defined or explicitly-defaulted copy assignment operator 11995 // for a non-union class X performs memberwise copy assignment of its 11996 // subobjects. The direct base classes of X are assigned first, in the 11997 // order of their declaration in the base-specifier-list, and then the 11998 // immediate non-static data members of X are assigned, in the order in 11999 // which they were declared in the class definition. 12000 12001 // The statements that form the synthesized function body. 12002 SmallVector<Stmt*, 8> Statements; 12003 12004 // The parameter for the "other" object, which we are copying from. 12005 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 12006 Qualifiers OtherQuals = Other->getType().getQualifiers(); 12007 QualType OtherRefType = Other->getType(); 12008 if (const LValueReferenceType *OtherRef 12009 = OtherRefType->getAs<LValueReferenceType>()) { 12010 OtherRefType = OtherRef->getPointeeType(); 12011 OtherQuals = OtherRefType.getQualifiers(); 12012 } 12013 12014 // Our location for everything implicitly-generated. 12015 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 12016 ? CopyAssignOperator->getEndLoc() 12017 : CopyAssignOperator->getLocation(); 12018 12019 // Builds a DeclRefExpr for the "other" object. 12020 RefBuilder OtherRef(Other, OtherRefType); 12021 12022 // Builds the "this" pointer. 12023 ThisBuilder This; 12024 12025 // Assign base classes. 12026 bool Invalid = false; 12027 for (auto &Base : ClassDecl->bases()) { 12028 // Form the assignment: 12029 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 12030 QualType BaseType = Base.getType().getUnqualifiedType(); 12031 if (!BaseType->isRecordType()) { 12032 Invalid = true; 12033 continue; 12034 } 12035 12036 CXXCastPath BasePath; 12037 BasePath.push_back(&Base); 12038 12039 // Construct the "from" expression, which is an implicit cast to the 12040 // appropriately-qualified base type. 12041 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 12042 VK_LValue, BasePath); 12043 12044 // Dereference "this". 12045 DerefBuilder DerefThis(This); 12046 CastBuilder To(DerefThis, 12047 Context.getQualifiedType( 12048 BaseType, CopyAssignOperator->getMethodQualifiers()), 12049 VK_LValue, BasePath); 12050 12051 // Build the copy. 12052 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 12053 To, From, 12054 /*CopyingBaseSubobject=*/true, 12055 /*Copying=*/true); 12056 if (Copy.isInvalid()) { 12057 CopyAssignOperator->setInvalidDecl(); 12058 return; 12059 } 12060 12061 // Success! Record the copy. 12062 Statements.push_back(Copy.getAs<Expr>()); 12063 } 12064 12065 // Assign non-static members. 12066 for (auto *Field : ClassDecl->fields()) { 12067 // FIXME: We should form some kind of AST representation for the implied 12068 // memcpy in a union copy operation. 12069 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12070 continue; 12071 12072 if (Field->isInvalidDecl()) { 12073 Invalid = true; 12074 continue; 12075 } 12076 12077 // Check for members of reference type; we can't copy those. 12078 if (Field->getType()->isReferenceType()) { 12079 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12080 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12081 Diag(Field->getLocation(), diag::note_declared_at); 12082 Invalid = true; 12083 continue; 12084 } 12085 12086 // Check for members of const-qualified, non-class type. 12087 QualType BaseType = Context.getBaseElementType(Field->getType()); 12088 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12089 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12090 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12091 Diag(Field->getLocation(), diag::note_declared_at); 12092 Invalid = true; 12093 continue; 12094 } 12095 12096 // Suppress assigning zero-width bitfields. 12097 if (Field->isZeroLengthBitField(Context)) 12098 continue; 12099 12100 QualType FieldType = Field->getType().getNonReferenceType(); 12101 if (FieldType->isIncompleteArrayType()) { 12102 assert(ClassDecl->hasFlexibleArrayMember() && 12103 "Incomplete array type is not valid"); 12104 continue; 12105 } 12106 12107 // Build references to the field in the object we're copying from and to. 12108 CXXScopeSpec SS; // Intentionally empty 12109 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12110 LookupMemberName); 12111 MemberLookup.addDecl(Field); 12112 MemberLookup.resolveKind(); 12113 12114 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 12115 12116 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 12117 12118 // Build the copy of this field. 12119 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 12120 To, From, 12121 /*CopyingBaseSubobject=*/false, 12122 /*Copying=*/true); 12123 if (Copy.isInvalid()) { 12124 CopyAssignOperator->setInvalidDecl(); 12125 return; 12126 } 12127 12128 // Success! Record the copy. 12129 Statements.push_back(Copy.getAs<Stmt>()); 12130 } 12131 12132 if (!Invalid) { 12133 // Add a "return *this;" 12134 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12135 12136 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12137 if (Return.isInvalid()) 12138 Invalid = true; 12139 else 12140 Statements.push_back(Return.getAs<Stmt>()); 12141 } 12142 12143 if (Invalid) { 12144 CopyAssignOperator->setInvalidDecl(); 12145 return; 12146 } 12147 12148 StmtResult Body; 12149 { 12150 CompoundScopeRAII CompoundScope(*this); 12151 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12152 /*isStmtExpr=*/false); 12153 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12154 } 12155 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 12156 CopyAssignOperator->markUsed(Context); 12157 12158 if (ASTMutationListener *L = getASTMutationListener()) { 12159 L->CompletedImplicitDefinition(CopyAssignOperator); 12160 } 12161 } 12162 12163 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 12164 assert(ClassDecl->needsImplicitMoveAssignment()); 12165 12166 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 12167 if (DSM.isAlreadyBeingDeclared()) 12168 return nullptr; 12169 12170 // Note: The following rules are largely analoguous to the move 12171 // constructor rules. 12172 12173 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12174 if (Context.getLangOpts().OpenCLCPlusPlus) 12175 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12176 QualType RetType = Context.getLValueReferenceType(ArgType); 12177 ArgType = Context.getRValueReferenceType(ArgType); 12178 12179 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12180 CXXMoveAssignment, 12181 false); 12182 12183 // An implicitly-declared move assignment operator is an inline public 12184 // member of its class. 12185 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12186 SourceLocation ClassLoc = ClassDecl->getLocation(); 12187 DeclarationNameInfo NameInfo(Name, ClassLoc); 12188 CXXMethodDecl *MoveAssignment = 12189 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12190 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12191 /*isInline=*/true, Constexpr, SourceLocation()); 12192 MoveAssignment->setAccess(AS_public); 12193 MoveAssignment->setDefaulted(); 12194 MoveAssignment->setImplicit(); 12195 12196 if (getLangOpts().CUDA) { 12197 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12198 MoveAssignment, 12199 /* ConstRHS */ false, 12200 /* Diagnose */ false); 12201 } 12202 12203 // Build an exception specification pointing back at this member. 12204 FunctionProtoType::ExtProtoInfo EPI = 12205 getImplicitMethodEPI(*this, MoveAssignment); 12206 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12207 12208 // Add the parameter to the operator. 12209 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12210 ClassLoc, ClassLoc, 12211 /*Id=*/nullptr, ArgType, 12212 /*TInfo=*/nullptr, SC_None, 12213 nullptr); 12214 MoveAssignment->setParams(FromParam); 12215 12216 MoveAssignment->setTrivial( 12217 ClassDecl->needsOverloadResolutionForMoveAssignment() 12218 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12219 : ClassDecl->hasTrivialMoveAssignment()); 12220 12221 // Note that we have added this copy-assignment operator. 12222 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 12223 12224 Scope *S = getScopeForContext(ClassDecl); 12225 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12226 12227 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12228 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12229 SetDeclDeleted(MoveAssignment, ClassLoc); 12230 } 12231 12232 if (S) 12233 PushOnScopeChains(MoveAssignment, S, false); 12234 ClassDecl->addDecl(MoveAssignment); 12235 12236 return MoveAssignment; 12237 } 12238 12239 /// Check if we're implicitly defining a move assignment operator for a class 12240 /// with virtual bases. Such a move assignment might move-assign the virtual 12241 /// base multiple times. 12242 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12243 SourceLocation CurrentLocation) { 12244 assert(!Class->isDependentContext() && "should not define dependent move"); 12245 12246 // Only a virtual base could get implicitly move-assigned multiple times. 12247 // Only a non-trivial move assignment can observe this. We only want to 12248 // diagnose if we implicitly define an assignment operator that assigns 12249 // two base classes, both of which move-assign the same virtual base. 12250 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12251 Class->getNumBases() < 2) 12252 return; 12253 12254 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12255 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12256 VBaseMap VBases; 12257 12258 for (auto &BI : Class->bases()) { 12259 Worklist.push_back(&BI); 12260 while (!Worklist.empty()) { 12261 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12262 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12263 12264 // If the base has no non-trivial move assignment operators, 12265 // we don't care about moves from it. 12266 if (!Base->hasNonTrivialMoveAssignment()) 12267 continue; 12268 12269 // If there's nothing virtual here, skip it. 12270 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12271 continue; 12272 12273 // If we're not actually going to call a move assignment for this base, 12274 // or the selected move assignment is trivial, skip it. 12275 Sema::SpecialMemberOverloadResult SMOR = 12276 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12277 /*ConstArg*/false, /*VolatileArg*/false, 12278 /*RValueThis*/true, /*ConstThis*/false, 12279 /*VolatileThis*/false); 12280 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12281 !SMOR.getMethod()->isMoveAssignmentOperator()) 12282 continue; 12283 12284 if (BaseSpec->isVirtual()) { 12285 // We're going to move-assign this virtual base, and its move 12286 // assignment operator is not trivial. If this can happen for 12287 // multiple distinct direct bases of Class, diagnose it. (If it 12288 // only happens in one base, we'll diagnose it when synthesizing 12289 // that base class's move assignment operator.) 12290 CXXBaseSpecifier *&Existing = 12291 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12292 .first->second; 12293 if (Existing && Existing != &BI) { 12294 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12295 << Class << Base; 12296 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 12297 << (Base->getCanonicalDecl() == 12298 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12299 << Base << Existing->getType() << Existing->getSourceRange(); 12300 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 12301 << (Base->getCanonicalDecl() == 12302 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12303 << Base << BI.getType() << BaseSpec->getSourceRange(); 12304 12305 // Only diagnose each vbase once. 12306 Existing = nullptr; 12307 } 12308 } else { 12309 // Only walk over bases that have defaulted move assignment operators. 12310 // We assume that any user-provided move assignment operator handles 12311 // the multiple-moves-of-vbase case itself somehow. 12312 if (!SMOR.getMethod()->isDefaulted()) 12313 continue; 12314 12315 // We're going to move the base classes of Base. Add them to the list. 12316 for (auto &BI : Base->bases()) 12317 Worklist.push_back(&BI); 12318 } 12319 } 12320 } 12321 } 12322 12323 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12324 CXXMethodDecl *MoveAssignOperator) { 12325 assert((MoveAssignOperator->isDefaulted() && 12326 MoveAssignOperator->isOverloadedOperator() && 12327 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12328 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12329 !MoveAssignOperator->isDeleted()) && 12330 "DefineImplicitMoveAssignment called for wrong function"); 12331 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12332 return; 12333 12334 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12335 if (ClassDecl->isInvalidDecl()) { 12336 MoveAssignOperator->setInvalidDecl(); 12337 return; 12338 } 12339 12340 // C++0x [class.copy]p28: 12341 // The implicitly-defined or move assignment operator for a non-union class 12342 // X performs memberwise move assignment of its subobjects. The direct base 12343 // classes of X are assigned first, in the order of their declaration in the 12344 // base-specifier-list, and then the immediate non-static data members of X 12345 // are assigned, in the order in which they were declared in the class 12346 // definition. 12347 12348 // Issue a warning if our implicit move assignment operator will move 12349 // from a virtual base more than once. 12350 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12351 12352 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12353 12354 // The exception specification is needed because we are defining the 12355 // function. 12356 ResolveExceptionSpec(CurrentLocation, 12357 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12358 12359 // Add a context note for diagnostics produced after this point. 12360 Scope.addContextNote(CurrentLocation); 12361 12362 // The statements that form the synthesized function body. 12363 SmallVector<Stmt*, 8> Statements; 12364 12365 // The parameter for the "other" object, which we are move from. 12366 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12367 QualType OtherRefType = Other->getType()-> 12368 getAs<RValueReferenceType>()->getPointeeType(); 12369 12370 // Our location for everything implicitly-generated. 12371 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 12372 ? MoveAssignOperator->getEndLoc() 12373 : MoveAssignOperator->getLocation(); 12374 12375 // Builds a reference to the "other" object. 12376 RefBuilder OtherRef(Other, OtherRefType); 12377 // Cast to rvalue. 12378 MoveCastBuilder MoveOther(OtherRef); 12379 12380 // Builds the "this" pointer. 12381 ThisBuilder This; 12382 12383 // Assign base classes. 12384 bool Invalid = false; 12385 for (auto &Base : ClassDecl->bases()) { 12386 // C++11 [class.copy]p28: 12387 // It is unspecified whether subobjects representing virtual base classes 12388 // are assigned more than once by the implicitly-defined copy assignment 12389 // operator. 12390 // FIXME: Do not assign to a vbase that will be assigned by some other base 12391 // class. For a move-assignment, this can result in the vbase being moved 12392 // multiple times. 12393 12394 // Form the assignment: 12395 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12396 QualType BaseType = Base.getType().getUnqualifiedType(); 12397 if (!BaseType->isRecordType()) { 12398 Invalid = true; 12399 continue; 12400 } 12401 12402 CXXCastPath BasePath; 12403 BasePath.push_back(&Base); 12404 12405 // Construct the "from" expression, which is an implicit cast to the 12406 // appropriately-qualified base type. 12407 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12408 12409 // Dereference "this". 12410 DerefBuilder DerefThis(This); 12411 12412 // Implicitly cast "this" to the appropriately-qualified base type. 12413 CastBuilder To(DerefThis, 12414 Context.getQualifiedType( 12415 BaseType, MoveAssignOperator->getMethodQualifiers()), 12416 VK_LValue, BasePath); 12417 12418 // Build the move. 12419 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12420 To, From, 12421 /*CopyingBaseSubobject=*/true, 12422 /*Copying=*/false); 12423 if (Move.isInvalid()) { 12424 MoveAssignOperator->setInvalidDecl(); 12425 return; 12426 } 12427 12428 // Success! Record the move. 12429 Statements.push_back(Move.getAs<Expr>()); 12430 } 12431 12432 // Assign non-static members. 12433 for (auto *Field : ClassDecl->fields()) { 12434 // FIXME: We should form some kind of AST representation for the implied 12435 // memcpy in a union copy operation. 12436 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12437 continue; 12438 12439 if (Field->isInvalidDecl()) { 12440 Invalid = true; 12441 continue; 12442 } 12443 12444 // Check for members of reference type; we can't move those. 12445 if (Field->getType()->isReferenceType()) { 12446 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12447 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12448 Diag(Field->getLocation(), diag::note_declared_at); 12449 Invalid = true; 12450 continue; 12451 } 12452 12453 // Check for members of const-qualified, non-class type. 12454 QualType BaseType = Context.getBaseElementType(Field->getType()); 12455 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12456 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12457 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12458 Diag(Field->getLocation(), diag::note_declared_at); 12459 Invalid = true; 12460 continue; 12461 } 12462 12463 // Suppress assigning zero-width bitfields. 12464 if (Field->isZeroLengthBitField(Context)) 12465 continue; 12466 12467 QualType FieldType = Field->getType().getNonReferenceType(); 12468 if (FieldType->isIncompleteArrayType()) { 12469 assert(ClassDecl->hasFlexibleArrayMember() && 12470 "Incomplete array type is not valid"); 12471 continue; 12472 } 12473 12474 // Build references to the field in the object we're copying from and to. 12475 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12476 LookupMemberName); 12477 MemberLookup.addDecl(Field); 12478 MemberLookup.resolveKind(); 12479 MemberBuilder From(MoveOther, OtherRefType, 12480 /*IsArrow=*/false, MemberLookup); 12481 MemberBuilder To(This, getCurrentThisType(), 12482 /*IsArrow=*/true, MemberLookup); 12483 12484 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12485 "Member reference with rvalue base must be rvalue except for reference " 12486 "members, which aren't allowed for move assignment."); 12487 12488 // Build the move of this field. 12489 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12490 To, From, 12491 /*CopyingBaseSubobject=*/false, 12492 /*Copying=*/false); 12493 if (Move.isInvalid()) { 12494 MoveAssignOperator->setInvalidDecl(); 12495 return; 12496 } 12497 12498 // Success! Record the copy. 12499 Statements.push_back(Move.getAs<Stmt>()); 12500 } 12501 12502 if (!Invalid) { 12503 // Add a "return *this;" 12504 ExprResult ThisObj = 12505 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12506 12507 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12508 if (Return.isInvalid()) 12509 Invalid = true; 12510 else 12511 Statements.push_back(Return.getAs<Stmt>()); 12512 } 12513 12514 if (Invalid) { 12515 MoveAssignOperator->setInvalidDecl(); 12516 return; 12517 } 12518 12519 StmtResult Body; 12520 { 12521 CompoundScopeRAII CompoundScope(*this); 12522 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12523 /*isStmtExpr=*/false); 12524 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12525 } 12526 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12527 MoveAssignOperator->markUsed(Context); 12528 12529 if (ASTMutationListener *L = getASTMutationListener()) { 12530 L->CompletedImplicitDefinition(MoveAssignOperator); 12531 } 12532 } 12533 12534 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12535 CXXRecordDecl *ClassDecl) { 12536 // C++ [class.copy]p4: 12537 // If the class definition does not explicitly declare a copy 12538 // constructor, one is declared implicitly. 12539 assert(ClassDecl->needsImplicitCopyConstructor()); 12540 12541 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12542 if (DSM.isAlreadyBeingDeclared()) 12543 return nullptr; 12544 12545 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12546 QualType ArgType = ClassType; 12547 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12548 if (Const) 12549 ArgType = ArgType.withConst(); 12550 12551 if (Context.getLangOpts().OpenCLCPlusPlus) 12552 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12553 12554 ArgType = Context.getLValueReferenceType(ArgType); 12555 12556 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12557 CXXCopyConstructor, 12558 Const); 12559 12560 DeclarationName Name 12561 = Context.DeclarationNames.getCXXConstructorName( 12562 Context.getCanonicalType(ClassType)); 12563 SourceLocation ClassLoc = ClassDecl->getLocation(); 12564 DeclarationNameInfo NameInfo(Name, ClassLoc); 12565 12566 // An implicitly-declared copy constructor is an inline public 12567 // member of its class. 12568 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12569 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12570 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12571 Constexpr); 12572 CopyConstructor->setAccess(AS_public); 12573 CopyConstructor->setDefaulted(); 12574 12575 if (getLangOpts().CUDA) { 12576 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12577 CopyConstructor, 12578 /* ConstRHS */ Const, 12579 /* Diagnose */ false); 12580 } 12581 12582 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 12583 12584 // Add the parameter to the constructor. 12585 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12586 ClassLoc, ClassLoc, 12587 /*IdentifierInfo=*/nullptr, 12588 ArgType, /*TInfo=*/nullptr, 12589 SC_None, nullptr); 12590 CopyConstructor->setParams(FromParam); 12591 12592 CopyConstructor->setTrivial( 12593 ClassDecl->needsOverloadResolutionForCopyConstructor() 12594 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12595 : ClassDecl->hasTrivialCopyConstructor()); 12596 12597 CopyConstructor->setTrivialForCall( 12598 ClassDecl->hasAttr<TrivialABIAttr>() || 12599 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12600 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12601 TAH_ConsiderTrivialABI) 12602 : ClassDecl->hasTrivialCopyConstructorForCall())); 12603 12604 // Note that we have declared this constructor. 12605 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12606 12607 Scope *S = getScopeForContext(ClassDecl); 12608 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12609 12610 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12611 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12612 SetDeclDeleted(CopyConstructor, ClassLoc); 12613 } 12614 12615 if (S) 12616 PushOnScopeChains(CopyConstructor, S, false); 12617 ClassDecl->addDecl(CopyConstructor); 12618 12619 return CopyConstructor; 12620 } 12621 12622 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12623 CXXConstructorDecl *CopyConstructor) { 12624 assert((CopyConstructor->isDefaulted() && 12625 CopyConstructor->isCopyConstructor() && 12626 !CopyConstructor->doesThisDeclarationHaveABody() && 12627 !CopyConstructor->isDeleted()) && 12628 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12629 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12630 return; 12631 12632 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12633 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12634 12635 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12636 12637 // The exception specification is needed because we are defining the 12638 // function. 12639 ResolveExceptionSpec(CurrentLocation, 12640 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12641 MarkVTableUsed(CurrentLocation, ClassDecl); 12642 12643 // Add a context note for diagnostics produced after this point. 12644 Scope.addContextNote(CurrentLocation); 12645 12646 // C++11 [class.copy]p7: 12647 // The [definition of an implicitly declared copy constructor] is 12648 // deprecated if the class has a user-declared copy assignment operator 12649 // or a user-declared destructor. 12650 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12651 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12652 12653 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12654 CopyConstructor->setInvalidDecl(); 12655 } else { 12656 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 12657 ? CopyConstructor->getEndLoc() 12658 : CopyConstructor->getLocation(); 12659 Sema::CompoundScopeRAII CompoundScope(*this); 12660 CopyConstructor->setBody( 12661 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12662 CopyConstructor->markUsed(Context); 12663 } 12664 12665 if (ASTMutationListener *L = getASTMutationListener()) { 12666 L->CompletedImplicitDefinition(CopyConstructor); 12667 } 12668 } 12669 12670 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12671 CXXRecordDecl *ClassDecl) { 12672 assert(ClassDecl->needsImplicitMoveConstructor()); 12673 12674 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12675 if (DSM.isAlreadyBeingDeclared()) 12676 return nullptr; 12677 12678 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12679 12680 QualType ArgType = ClassType; 12681 if (Context.getLangOpts().OpenCLCPlusPlus) 12682 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic); 12683 ArgType = Context.getRValueReferenceType(ArgType); 12684 12685 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12686 CXXMoveConstructor, 12687 false); 12688 12689 DeclarationName Name 12690 = Context.DeclarationNames.getCXXConstructorName( 12691 Context.getCanonicalType(ClassType)); 12692 SourceLocation ClassLoc = ClassDecl->getLocation(); 12693 DeclarationNameInfo NameInfo(Name, ClassLoc); 12694 12695 // C++11 [class.copy]p11: 12696 // An implicitly-declared copy/move constructor is an inline public 12697 // member of its class. 12698 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12699 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12700 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12701 Constexpr); 12702 MoveConstructor->setAccess(AS_public); 12703 MoveConstructor->setDefaulted(); 12704 12705 if (getLangOpts().CUDA) { 12706 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12707 MoveConstructor, 12708 /* ConstRHS */ false, 12709 /* Diagnose */ false); 12710 } 12711 12712 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 12713 12714 // Add the parameter to the constructor. 12715 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12716 ClassLoc, ClassLoc, 12717 /*IdentifierInfo=*/nullptr, 12718 ArgType, /*TInfo=*/nullptr, 12719 SC_None, nullptr); 12720 MoveConstructor->setParams(FromParam); 12721 12722 MoveConstructor->setTrivial( 12723 ClassDecl->needsOverloadResolutionForMoveConstructor() 12724 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12725 : ClassDecl->hasTrivialMoveConstructor()); 12726 12727 MoveConstructor->setTrivialForCall( 12728 ClassDecl->hasAttr<TrivialABIAttr>() || 12729 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12730 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12731 TAH_ConsiderTrivialABI) 12732 : ClassDecl->hasTrivialMoveConstructorForCall())); 12733 12734 // Note that we have declared this constructor. 12735 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12736 12737 Scope *S = getScopeForContext(ClassDecl); 12738 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12739 12740 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12741 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12742 SetDeclDeleted(MoveConstructor, ClassLoc); 12743 } 12744 12745 if (S) 12746 PushOnScopeChains(MoveConstructor, S, false); 12747 ClassDecl->addDecl(MoveConstructor); 12748 12749 return MoveConstructor; 12750 } 12751 12752 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12753 CXXConstructorDecl *MoveConstructor) { 12754 assert((MoveConstructor->isDefaulted() && 12755 MoveConstructor->isMoveConstructor() && 12756 !MoveConstructor->doesThisDeclarationHaveABody() && 12757 !MoveConstructor->isDeleted()) && 12758 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12759 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12760 return; 12761 12762 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12763 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12764 12765 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12766 12767 // The exception specification is needed because we are defining the 12768 // function. 12769 ResolveExceptionSpec(CurrentLocation, 12770 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12771 MarkVTableUsed(CurrentLocation, ClassDecl); 12772 12773 // Add a context note for diagnostics produced after this point. 12774 Scope.addContextNote(CurrentLocation); 12775 12776 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12777 MoveConstructor->setInvalidDecl(); 12778 } else { 12779 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 12780 ? MoveConstructor->getEndLoc() 12781 : MoveConstructor->getLocation(); 12782 Sema::CompoundScopeRAII CompoundScope(*this); 12783 MoveConstructor->setBody(ActOnCompoundStmt( 12784 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12785 MoveConstructor->markUsed(Context); 12786 } 12787 12788 if (ASTMutationListener *L = getASTMutationListener()) { 12789 L->CompletedImplicitDefinition(MoveConstructor); 12790 } 12791 } 12792 12793 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12794 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12795 } 12796 12797 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12798 SourceLocation CurrentLocation, 12799 CXXConversionDecl *Conv) { 12800 SynthesizedFunctionScope Scope(*this, Conv); 12801 assert(!Conv->getReturnType()->isUndeducedType()); 12802 12803 CXXRecordDecl *Lambda = Conv->getParent(); 12804 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12805 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12806 12807 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 12808 CallOp = InstantiateFunctionDeclaration( 12809 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12810 if (!CallOp) 12811 return; 12812 12813 Invoker = InstantiateFunctionDeclaration( 12814 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12815 if (!Invoker) 12816 return; 12817 } 12818 12819 if (CallOp->isInvalidDecl()) 12820 return; 12821 12822 // Mark the call operator referenced (and add to pending instantiations 12823 // if necessary). 12824 // For both the conversion and static-invoker template specializations 12825 // we construct their body's in this function, so no need to add them 12826 // to the PendingInstantiations. 12827 MarkFunctionReferenced(CurrentLocation, CallOp); 12828 12829 // Fill in the __invoke function with a dummy implementation. IR generation 12830 // will fill in the actual details. Update its type in case it contained 12831 // an 'auto'. 12832 Invoker->markUsed(Context); 12833 Invoker->setReferenced(); 12834 Invoker->setType(Conv->getReturnType()->getPointeeType()); 12835 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12836 12837 // Construct the body of the conversion function { return __invoke; }. 12838 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12839 VK_LValue, Conv->getLocation()).get(); 12840 assert(FunctionRef && "Can't refer to __invoke function?"); 12841 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12842 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 12843 Conv->getLocation())); 12844 Conv->markUsed(Context); 12845 Conv->setReferenced(); 12846 12847 if (ASTMutationListener *L = getASTMutationListener()) { 12848 L->CompletedImplicitDefinition(Conv); 12849 L->CompletedImplicitDefinition(Invoker); 12850 } 12851 } 12852 12853 12854 12855 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12856 SourceLocation CurrentLocation, 12857 CXXConversionDecl *Conv) 12858 { 12859 assert(!Conv->getParent()->isGenericLambda()); 12860 12861 SynthesizedFunctionScope Scope(*this, Conv); 12862 12863 // Copy-initialize the lambda object as needed to capture it. 12864 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12865 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12866 12867 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12868 Conv->getLocation(), 12869 Conv, DerefThis); 12870 12871 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12872 // behavior. Note that only the general conversion function does this 12873 // (since it's unusable otherwise); in the case where we inline the 12874 // block literal, it has block literal lifetime semantics. 12875 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12876 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12877 CK_CopyAndAutoreleaseBlockObject, 12878 BuildBlock.get(), nullptr, VK_RValue); 12879 12880 if (BuildBlock.isInvalid()) { 12881 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12882 Conv->setInvalidDecl(); 12883 return; 12884 } 12885 12886 // Create the return statement that returns the block from the conversion 12887 // function. 12888 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12889 if (Return.isInvalid()) { 12890 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12891 Conv->setInvalidDecl(); 12892 return; 12893 } 12894 12895 // Set the body of the conversion function. 12896 Stmt *ReturnS = Return.get(); 12897 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 12898 Conv->getLocation())); 12899 Conv->markUsed(Context); 12900 12901 // We're done; notify the mutation listener, if any. 12902 if (ASTMutationListener *L = getASTMutationListener()) { 12903 L->CompletedImplicitDefinition(Conv); 12904 } 12905 } 12906 12907 /// Determine whether the given list arguments contains exactly one 12908 /// "real" (non-default) argument. 12909 static bool hasOneRealArgument(MultiExprArg Args) { 12910 switch (Args.size()) { 12911 case 0: 12912 return false; 12913 12914 default: 12915 if (!Args[1]->isDefaultArgument()) 12916 return false; 12917 12918 LLVM_FALLTHROUGH; 12919 case 1: 12920 return !Args[0]->isDefaultArgument(); 12921 } 12922 12923 return false; 12924 } 12925 12926 ExprResult 12927 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12928 NamedDecl *FoundDecl, 12929 CXXConstructorDecl *Constructor, 12930 MultiExprArg ExprArgs, 12931 bool HadMultipleCandidates, 12932 bool IsListInitialization, 12933 bool IsStdInitListInitialization, 12934 bool RequiresZeroInit, 12935 unsigned ConstructKind, 12936 SourceRange ParenRange) { 12937 bool Elidable = false; 12938 12939 // C++0x [class.copy]p34: 12940 // When certain criteria are met, an implementation is allowed to 12941 // omit the copy/move construction of a class object, even if the 12942 // copy/move constructor and/or destructor for the object have 12943 // side effects. [...] 12944 // - when a temporary class object that has not been bound to a 12945 // reference (12.2) would be copied/moved to a class object 12946 // with the same cv-unqualified type, the copy/move operation 12947 // can be omitted by constructing the temporary object 12948 // directly into the target of the omitted copy/move 12949 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12950 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12951 Expr *SubExpr = ExprArgs[0]; 12952 Elidable = SubExpr->isTemporaryObject( 12953 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12954 } 12955 12956 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12957 FoundDecl, Constructor, 12958 Elidable, ExprArgs, HadMultipleCandidates, 12959 IsListInitialization, 12960 IsStdInitListInitialization, RequiresZeroInit, 12961 ConstructKind, ParenRange); 12962 } 12963 12964 ExprResult 12965 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12966 NamedDecl *FoundDecl, 12967 CXXConstructorDecl *Constructor, 12968 bool Elidable, 12969 MultiExprArg ExprArgs, 12970 bool HadMultipleCandidates, 12971 bool IsListInitialization, 12972 bool IsStdInitListInitialization, 12973 bool RequiresZeroInit, 12974 unsigned ConstructKind, 12975 SourceRange ParenRange) { 12976 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12977 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12978 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12979 return ExprError(); 12980 } 12981 12982 return BuildCXXConstructExpr( 12983 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12984 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12985 RequiresZeroInit, ConstructKind, ParenRange); 12986 } 12987 12988 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12989 /// including handling of its default argument expressions. 12990 ExprResult 12991 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12992 CXXConstructorDecl *Constructor, 12993 bool Elidable, 12994 MultiExprArg ExprArgs, 12995 bool HadMultipleCandidates, 12996 bool IsListInitialization, 12997 bool IsStdInitListInitialization, 12998 bool RequiresZeroInit, 12999 unsigned ConstructKind, 13000 SourceRange ParenRange) { 13001 assert(declaresSameEntity( 13002 Constructor->getParent(), 13003 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 13004 "given constructor for wrong type"); 13005 MarkFunctionReferenced(ConstructLoc, Constructor); 13006 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 13007 return ExprError(); 13008 13009 return CXXConstructExpr::Create( 13010 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 13011 ExprArgs, HadMultipleCandidates, IsListInitialization, 13012 IsStdInitListInitialization, RequiresZeroInit, 13013 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 13014 ParenRange); 13015 } 13016 13017 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 13018 assert(Field->hasInClassInitializer()); 13019 13020 // If we already have the in-class initializer nothing needs to be done. 13021 if (Field->getInClassInitializer()) 13022 return CXXDefaultInitExpr::Create(Context, Loc, Field); 13023 13024 // If we might have already tried and failed to instantiate, don't try again. 13025 if (Field->isInvalidDecl()) 13026 return ExprError(); 13027 13028 // Maybe we haven't instantiated the in-class initializer. Go check the 13029 // pattern FieldDecl to see if it has one. 13030 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 13031 13032 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 13033 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 13034 DeclContext::lookup_result Lookup = 13035 ClassPattern->lookup(Field->getDeclName()); 13036 13037 // Lookup can return at most two results: the pattern for the field, or the 13038 // injected class name of the parent record. No other member can have the 13039 // same name as the field. 13040 // In modules mode, lookup can return multiple results (coming from 13041 // different modules). 13042 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 13043 "more than two lookup results for field name"); 13044 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 13045 if (!Pattern) { 13046 assert(isa<CXXRecordDecl>(Lookup[0]) && 13047 "cannot have other non-field member with same name"); 13048 for (auto L : Lookup) 13049 if (isa<FieldDecl>(L)) { 13050 Pattern = cast<FieldDecl>(L); 13051 break; 13052 } 13053 assert(Pattern && "We must have set the Pattern!"); 13054 } 13055 13056 if (!Pattern->hasInClassInitializer() || 13057 InstantiateInClassInitializer(Loc, Field, Pattern, 13058 getTemplateInstantiationArgs(Field))) { 13059 // Don't diagnose this again. 13060 Field->setInvalidDecl(); 13061 return ExprError(); 13062 } 13063 return CXXDefaultInitExpr::Create(Context, Loc, Field); 13064 } 13065 13066 // DR1351: 13067 // If the brace-or-equal-initializer of a non-static data member 13068 // invokes a defaulted default constructor of its class or of an 13069 // enclosing class in a potentially evaluated subexpression, the 13070 // program is ill-formed. 13071 // 13072 // This resolution is unworkable: the exception specification of the 13073 // default constructor can be needed in an unevaluated context, in 13074 // particular, in the operand of a noexcept-expression, and we can be 13075 // unable to compute an exception specification for an enclosed class. 13076 // 13077 // Any attempt to resolve the exception specification of a defaulted default 13078 // constructor before the initializer is lexically complete will ultimately 13079 // come here at which point we can diagnose it. 13080 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 13081 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 13082 << OutermostClass << Field; 13083 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 13084 // Recover by marking the field invalid, unless we're in a SFINAE context. 13085 if (!isSFINAEContext()) 13086 Field->setInvalidDecl(); 13087 return ExprError(); 13088 } 13089 13090 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 13091 if (VD->isInvalidDecl()) return; 13092 13093 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 13094 if (ClassDecl->isInvalidDecl()) return; 13095 if (ClassDecl->hasIrrelevantDestructor()) return; 13096 if (ClassDecl->isDependentContext()) return; 13097 13098 if (VD->isNoDestroy(getASTContext())) 13099 return; 13100 13101 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13102 MarkFunctionReferenced(VD->getLocation(), Destructor); 13103 CheckDestructorAccess(VD->getLocation(), Destructor, 13104 PDiag(diag::err_access_dtor_var) 13105 << VD->getDeclName() 13106 << VD->getType()); 13107 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 13108 13109 if (Destructor->isTrivial()) return; 13110 if (!VD->hasGlobalStorage()) return; 13111 13112 // Emit warning for non-trivial dtor in global scope (a real global, 13113 // class-static, function-static). 13114 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 13115 13116 // TODO: this should be re-enabled for static locals by !CXAAtExit 13117 if (!VD->isStaticLocal()) 13118 Diag(VD->getLocation(), diag::warn_global_destructor); 13119 } 13120 13121 /// Given a constructor and the set of arguments provided for the 13122 /// constructor, convert the arguments and add any required default arguments 13123 /// to form a proper call to this constructor. 13124 /// 13125 /// \returns true if an error occurred, false otherwise. 13126 bool 13127 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 13128 MultiExprArg ArgsPtr, 13129 SourceLocation Loc, 13130 SmallVectorImpl<Expr*> &ConvertedArgs, 13131 bool AllowExplicit, 13132 bool IsListInitialization) { 13133 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 13134 unsigned NumArgs = ArgsPtr.size(); 13135 Expr **Args = ArgsPtr.data(); 13136 13137 const FunctionProtoType *Proto 13138 = Constructor->getType()->getAs<FunctionProtoType>(); 13139 assert(Proto && "Constructor without a prototype?"); 13140 unsigned NumParams = Proto->getNumParams(); 13141 13142 // If too few arguments are available, we'll fill in the rest with defaults. 13143 if (NumArgs < NumParams) 13144 ConvertedArgs.reserve(NumParams); 13145 else 13146 ConvertedArgs.reserve(NumArgs); 13147 13148 VariadicCallType CallType = 13149 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 13150 SmallVector<Expr *, 8> AllArgs; 13151 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 13152 Proto, 0, 13153 llvm::makeArrayRef(Args, NumArgs), 13154 AllArgs, 13155 CallType, AllowExplicit, 13156 IsListInitialization); 13157 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 13158 13159 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 13160 13161 CheckConstructorCall(Constructor, 13162 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 13163 Proto, Loc); 13164 13165 return Invalid; 13166 } 13167 13168 static inline bool 13169 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 13170 const FunctionDecl *FnDecl) { 13171 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 13172 if (isa<NamespaceDecl>(DC)) { 13173 return SemaRef.Diag(FnDecl->getLocation(), 13174 diag::err_operator_new_delete_declared_in_namespace) 13175 << FnDecl->getDeclName(); 13176 } 13177 13178 if (isa<TranslationUnitDecl>(DC) && 13179 FnDecl->getStorageClass() == SC_Static) { 13180 return SemaRef.Diag(FnDecl->getLocation(), 13181 diag::err_operator_new_delete_declared_static) 13182 << FnDecl->getDeclName(); 13183 } 13184 13185 return false; 13186 } 13187 13188 static QualType 13189 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 13190 QualType QTy = PtrTy->getPointeeType(); 13191 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 13192 return SemaRef.Context.getPointerType(QTy); 13193 } 13194 13195 static inline bool 13196 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13197 CanQualType ExpectedResultType, 13198 CanQualType ExpectedFirstParamType, 13199 unsigned DependentParamTypeDiag, 13200 unsigned InvalidParamTypeDiag) { 13201 QualType ResultType = 13202 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13203 13204 // Check that the result type is not dependent. 13205 if (ResultType->isDependentType()) 13206 return SemaRef.Diag(FnDecl->getLocation(), 13207 diag::err_operator_new_delete_dependent_result_type) 13208 << FnDecl->getDeclName() << ExpectedResultType; 13209 13210 // OpenCL C++: the operator is valid on any address space. 13211 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13212 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13213 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13214 } 13215 } 13216 13217 // Check that the result type is what we expect. 13218 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13219 return SemaRef.Diag(FnDecl->getLocation(), 13220 diag::err_operator_new_delete_invalid_result_type) 13221 << FnDecl->getDeclName() << ExpectedResultType; 13222 13223 // A function template must have at least 2 parameters. 13224 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13225 return SemaRef.Diag(FnDecl->getLocation(), 13226 diag::err_operator_new_delete_template_too_few_parameters) 13227 << FnDecl->getDeclName(); 13228 13229 // The function decl must have at least 1 parameter. 13230 if (FnDecl->getNumParams() == 0) 13231 return SemaRef.Diag(FnDecl->getLocation(), 13232 diag::err_operator_new_delete_too_few_parameters) 13233 << FnDecl->getDeclName(); 13234 13235 // Check the first parameter type is not dependent. 13236 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13237 if (FirstParamType->isDependentType()) 13238 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13239 << FnDecl->getDeclName() << ExpectedFirstParamType; 13240 13241 // Check that the first parameter type is what we expect. 13242 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13243 // OpenCL C++: the operator is valid on any address space. 13244 if (auto *PtrTy = 13245 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13246 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13247 } 13248 } 13249 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13250 ExpectedFirstParamType) 13251 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13252 << FnDecl->getDeclName() << ExpectedFirstParamType; 13253 13254 return false; 13255 } 13256 13257 static bool 13258 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13259 // C++ [basic.stc.dynamic.allocation]p1: 13260 // A program is ill-formed if an allocation function is declared in a 13261 // namespace scope other than global scope or declared static in global 13262 // scope. 13263 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13264 return true; 13265 13266 CanQualType SizeTy = 13267 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13268 13269 // C++ [basic.stc.dynamic.allocation]p1: 13270 // The return type shall be void*. The first parameter shall have type 13271 // std::size_t. 13272 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13273 SizeTy, 13274 diag::err_operator_new_dependent_param_type, 13275 diag::err_operator_new_param_type)) 13276 return true; 13277 13278 // C++ [basic.stc.dynamic.allocation]p1: 13279 // The first parameter shall not have an associated default argument. 13280 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13281 return SemaRef.Diag(FnDecl->getLocation(), 13282 diag::err_operator_new_default_arg) 13283 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13284 13285 return false; 13286 } 13287 13288 static bool 13289 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13290 // C++ [basic.stc.dynamic.deallocation]p1: 13291 // A program is ill-formed if deallocation functions are declared in a 13292 // namespace scope other than global scope or declared static in global 13293 // scope. 13294 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13295 return true; 13296 13297 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13298 13299 // C++ P0722: 13300 // Within a class C, the first parameter of a destroying operator delete 13301 // shall be of type C *. The first parameter of any other deallocation 13302 // function shall be of type void *. 13303 CanQualType ExpectedFirstParamType = 13304 MD && MD->isDestroyingOperatorDelete() 13305 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13306 SemaRef.Context.getRecordType(MD->getParent()))) 13307 : SemaRef.Context.VoidPtrTy; 13308 13309 // C++ [basic.stc.dynamic.deallocation]p2: 13310 // Each deallocation function shall return void 13311 if (CheckOperatorNewDeleteTypes( 13312 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13313 diag::err_operator_delete_dependent_param_type, 13314 diag::err_operator_delete_param_type)) 13315 return true; 13316 13317 // C++ P0722: 13318 // A destroying operator delete shall be a usual deallocation function. 13319 if (MD && !MD->getParent()->isDependentContext() && 13320 MD->isDestroyingOperatorDelete() && 13321 !SemaRef.isUsualDeallocationFunction(MD)) { 13322 SemaRef.Diag(MD->getLocation(), 13323 diag::err_destroying_operator_delete_not_usual); 13324 return true; 13325 } 13326 13327 return false; 13328 } 13329 13330 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13331 /// of this overloaded operator is well-formed. If so, returns false; 13332 /// otherwise, emits appropriate diagnostics and returns true. 13333 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13334 assert(FnDecl && FnDecl->isOverloadedOperator() && 13335 "Expected an overloaded operator declaration"); 13336 13337 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13338 13339 // C++ [over.oper]p5: 13340 // The allocation and deallocation functions, operator new, 13341 // operator new[], operator delete and operator delete[], are 13342 // described completely in 3.7.3. The attributes and restrictions 13343 // found in the rest of this subclause do not apply to them unless 13344 // explicitly stated in 3.7.3. 13345 if (Op == OO_Delete || Op == OO_Array_Delete) 13346 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13347 13348 if (Op == OO_New || Op == OO_Array_New) 13349 return CheckOperatorNewDeclaration(*this, FnDecl); 13350 13351 // C++ [over.oper]p6: 13352 // An operator function shall either be a non-static member 13353 // function or be a non-member function and have at least one 13354 // parameter whose type is a class, a reference to a class, an 13355 // enumeration, or a reference to an enumeration. 13356 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13357 if (MethodDecl->isStatic()) 13358 return Diag(FnDecl->getLocation(), 13359 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13360 } else { 13361 bool ClassOrEnumParam = false; 13362 for (auto Param : FnDecl->parameters()) { 13363 QualType ParamType = Param->getType().getNonReferenceType(); 13364 if (ParamType->isDependentType() || ParamType->isRecordType() || 13365 ParamType->isEnumeralType()) { 13366 ClassOrEnumParam = true; 13367 break; 13368 } 13369 } 13370 13371 if (!ClassOrEnumParam) 13372 return Diag(FnDecl->getLocation(), 13373 diag::err_operator_overload_needs_class_or_enum) 13374 << FnDecl->getDeclName(); 13375 } 13376 13377 // C++ [over.oper]p8: 13378 // An operator function cannot have default arguments (8.3.6), 13379 // except where explicitly stated below. 13380 // 13381 // Only the function-call operator allows default arguments 13382 // (C++ [over.call]p1). 13383 if (Op != OO_Call) { 13384 for (auto Param : FnDecl->parameters()) { 13385 if (Param->hasDefaultArg()) 13386 return Diag(Param->getLocation(), 13387 diag::err_operator_overload_default_arg) 13388 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13389 } 13390 } 13391 13392 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13393 { false, false, false } 13394 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13395 , { Unary, Binary, MemberOnly } 13396 #include "clang/Basic/OperatorKinds.def" 13397 }; 13398 13399 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13400 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13401 bool MustBeMemberOperator = OperatorUses[Op][2]; 13402 13403 // C++ [over.oper]p8: 13404 // [...] Operator functions cannot have more or fewer parameters 13405 // than the number required for the corresponding operator, as 13406 // described in the rest of this subclause. 13407 unsigned NumParams = FnDecl->getNumParams() 13408 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13409 if (Op != OO_Call && 13410 ((NumParams == 1 && !CanBeUnaryOperator) || 13411 (NumParams == 2 && !CanBeBinaryOperator) || 13412 (NumParams < 1) || (NumParams > 2))) { 13413 // We have the wrong number of parameters. 13414 unsigned ErrorKind; 13415 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13416 ErrorKind = 2; // 2 -> unary or binary. 13417 } else if (CanBeUnaryOperator) { 13418 ErrorKind = 0; // 0 -> unary 13419 } else { 13420 assert(CanBeBinaryOperator && 13421 "All non-call overloaded operators are unary or binary!"); 13422 ErrorKind = 1; // 1 -> binary 13423 } 13424 13425 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13426 << FnDecl->getDeclName() << NumParams << ErrorKind; 13427 } 13428 13429 // Overloaded operators other than operator() cannot be variadic. 13430 if (Op != OO_Call && 13431 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13432 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13433 << FnDecl->getDeclName(); 13434 } 13435 13436 // Some operators must be non-static member functions. 13437 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13438 return Diag(FnDecl->getLocation(), 13439 diag::err_operator_overload_must_be_member) 13440 << FnDecl->getDeclName(); 13441 } 13442 13443 // C++ [over.inc]p1: 13444 // The user-defined function called operator++ implements the 13445 // prefix and postfix ++ operator. If this function is a member 13446 // function with no parameters, or a non-member function with one 13447 // parameter of class or enumeration type, it defines the prefix 13448 // increment operator ++ for objects of that type. If the function 13449 // is a member function with one parameter (which shall be of type 13450 // int) or a non-member function with two parameters (the second 13451 // of which shall be of type int), it defines the postfix 13452 // increment operator ++ for objects of that type. 13453 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13454 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13455 QualType ParamType = LastParam->getType(); 13456 13457 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13458 !ParamType->isDependentType()) 13459 return Diag(LastParam->getLocation(), 13460 diag::err_operator_overload_post_incdec_must_be_int) 13461 << LastParam->getType() << (Op == OO_MinusMinus); 13462 } 13463 13464 return false; 13465 } 13466 13467 static bool 13468 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13469 FunctionTemplateDecl *TpDecl) { 13470 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13471 13472 // Must have one or two template parameters. 13473 if (TemplateParams->size() == 1) { 13474 NonTypeTemplateParmDecl *PmDecl = 13475 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13476 13477 // The template parameter must be a char parameter pack. 13478 if (PmDecl && PmDecl->isTemplateParameterPack() && 13479 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13480 return false; 13481 13482 } else if (TemplateParams->size() == 2) { 13483 TemplateTypeParmDecl *PmType = 13484 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13485 NonTypeTemplateParmDecl *PmArgs = 13486 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13487 13488 // The second template parameter must be a parameter pack with the 13489 // first template parameter as its type. 13490 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13491 PmArgs->isTemplateParameterPack()) { 13492 const TemplateTypeParmType *TArgs = 13493 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13494 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13495 TArgs->getIndex() == PmType->getIndex()) { 13496 if (!SemaRef.inTemplateInstantiation()) 13497 SemaRef.Diag(TpDecl->getLocation(), 13498 diag::ext_string_literal_operator_template); 13499 return false; 13500 } 13501 } 13502 } 13503 13504 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13505 diag::err_literal_operator_template) 13506 << TpDecl->getTemplateParameters()->getSourceRange(); 13507 return true; 13508 } 13509 13510 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13511 /// of this literal operator function is well-formed. If so, returns 13512 /// false; otherwise, emits appropriate diagnostics and returns true. 13513 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13514 if (isa<CXXMethodDecl>(FnDecl)) { 13515 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13516 << FnDecl->getDeclName(); 13517 return true; 13518 } 13519 13520 if (FnDecl->isExternC()) { 13521 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13522 if (const LinkageSpecDecl *LSD = 13523 FnDecl->getDeclContext()->getExternCContext()) 13524 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13525 return true; 13526 } 13527 13528 // This might be the definition of a literal operator template. 13529 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13530 13531 // This might be a specialization of a literal operator template. 13532 if (!TpDecl) 13533 TpDecl = FnDecl->getPrimaryTemplate(); 13534 13535 // template <char...> type operator "" name() and 13536 // template <class T, T...> type operator "" name() are the only valid 13537 // template signatures, and the only valid signatures with no parameters. 13538 if (TpDecl) { 13539 if (FnDecl->param_size() != 0) { 13540 Diag(FnDecl->getLocation(), 13541 diag::err_literal_operator_template_with_params); 13542 return true; 13543 } 13544 13545 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13546 return true; 13547 13548 } else if (FnDecl->param_size() == 1) { 13549 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13550 13551 QualType ParamType = Param->getType().getUnqualifiedType(); 13552 13553 // Only unsigned long long int, long double, any character type, and const 13554 // char * are allowed as the only parameters. 13555 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13556 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13557 Context.hasSameType(ParamType, Context.CharTy) || 13558 Context.hasSameType(ParamType, Context.WideCharTy) || 13559 Context.hasSameType(ParamType, Context.Char8Ty) || 13560 Context.hasSameType(ParamType, Context.Char16Ty) || 13561 Context.hasSameType(ParamType, Context.Char32Ty)) { 13562 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13563 QualType InnerType = Ptr->getPointeeType(); 13564 13565 // Pointer parameter must be a const char *. 13566 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13567 Context.CharTy) && 13568 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13569 Diag(Param->getSourceRange().getBegin(), 13570 diag::err_literal_operator_param) 13571 << ParamType << "'const char *'" << Param->getSourceRange(); 13572 return true; 13573 } 13574 13575 } else if (ParamType->isRealFloatingType()) { 13576 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13577 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13578 return true; 13579 13580 } else if (ParamType->isIntegerType()) { 13581 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13582 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13583 return true; 13584 13585 } else { 13586 Diag(Param->getSourceRange().getBegin(), 13587 diag::err_literal_operator_invalid_param) 13588 << ParamType << Param->getSourceRange(); 13589 return true; 13590 } 13591 13592 } else if (FnDecl->param_size() == 2) { 13593 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13594 13595 // First, verify that the first parameter is correct. 13596 13597 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13598 13599 // Two parameter function must have a pointer to const as a 13600 // first parameter; let's strip those qualifiers. 13601 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13602 13603 if (!PT) { 13604 Diag((*Param)->getSourceRange().getBegin(), 13605 diag::err_literal_operator_param) 13606 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13607 return true; 13608 } 13609 13610 QualType PointeeType = PT->getPointeeType(); 13611 // First parameter must be const 13612 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13613 Diag((*Param)->getSourceRange().getBegin(), 13614 diag::err_literal_operator_param) 13615 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13616 return true; 13617 } 13618 13619 QualType InnerType = PointeeType.getUnqualifiedType(); 13620 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13621 // const char32_t* are allowed as the first parameter to a two-parameter 13622 // function 13623 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13624 Context.hasSameType(InnerType, Context.WideCharTy) || 13625 Context.hasSameType(InnerType, Context.Char8Ty) || 13626 Context.hasSameType(InnerType, Context.Char16Ty) || 13627 Context.hasSameType(InnerType, Context.Char32Ty))) { 13628 Diag((*Param)->getSourceRange().getBegin(), 13629 diag::err_literal_operator_param) 13630 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13631 return true; 13632 } 13633 13634 // Move on to the second and final parameter. 13635 ++Param; 13636 13637 // The second parameter must be a std::size_t. 13638 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13639 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13640 Diag((*Param)->getSourceRange().getBegin(), 13641 diag::err_literal_operator_param) 13642 << SecondParamType << Context.getSizeType() 13643 << (*Param)->getSourceRange(); 13644 return true; 13645 } 13646 } else { 13647 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13648 return true; 13649 } 13650 13651 // Parameters are good. 13652 13653 // A parameter-declaration-clause containing a default argument is not 13654 // equivalent to any of the permitted forms. 13655 for (auto Param : FnDecl->parameters()) { 13656 if (Param->hasDefaultArg()) { 13657 Diag(Param->getDefaultArgRange().getBegin(), 13658 diag::err_literal_operator_default_argument) 13659 << Param->getDefaultArgRange(); 13660 break; 13661 } 13662 } 13663 13664 StringRef LiteralName 13665 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13666 if (LiteralName[0] != '_' && 13667 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13668 // C++11 [usrlit.suffix]p1: 13669 // Literal suffix identifiers that do not start with an underscore 13670 // are reserved for future standardization. 13671 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13672 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13673 } 13674 13675 return false; 13676 } 13677 13678 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13679 /// linkage specification, including the language and (if present) 13680 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13681 /// language string literal. LBraceLoc, if valid, provides the location of 13682 /// the '{' brace. Otherwise, this linkage specification does not 13683 /// have any braces. 13684 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13685 Expr *LangStr, 13686 SourceLocation LBraceLoc) { 13687 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13688 if (!Lit->isAscii()) { 13689 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13690 << LangStr->getSourceRange(); 13691 return nullptr; 13692 } 13693 13694 StringRef Lang = Lit->getString(); 13695 LinkageSpecDecl::LanguageIDs Language; 13696 if (Lang == "C") 13697 Language = LinkageSpecDecl::lang_c; 13698 else if (Lang == "C++") 13699 Language = LinkageSpecDecl::lang_cxx; 13700 else { 13701 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13702 << LangStr->getSourceRange(); 13703 return nullptr; 13704 } 13705 13706 // FIXME: Add all the various semantics of linkage specifications 13707 13708 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13709 LangStr->getExprLoc(), Language, 13710 LBraceLoc.isValid()); 13711 CurContext->addDecl(D); 13712 PushDeclContext(S, D); 13713 return D; 13714 } 13715 13716 /// ActOnFinishLinkageSpecification - Complete the definition of 13717 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13718 /// valid, it's the position of the closing '}' brace in a linkage 13719 /// specification that uses braces. 13720 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13721 Decl *LinkageSpec, 13722 SourceLocation RBraceLoc) { 13723 if (RBraceLoc.isValid()) { 13724 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13725 LSDecl->setRBraceLoc(RBraceLoc); 13726 } 13727 PopDeclContext(); 13728 return LinkageSpec; 13729 } 13730 13731 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13732 const ParsedAttributesView &AttrList, 13733 SourceLocation SemiLoc) { 13734 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13735 // Attribute declarations appertain to empty declaration so we handle 13736 // them here. 13737 ProcessDeclAttributeList(S, ED, AttrList); 13738 13739 CurContext->addDecl(ED); 13740 return ED; 13741 } 13742 13743 /// Perform semantic analysis for the variable declaration that 13744 /// occurs within a C++ catch clause, returning the newly-created 13745 /// variable. 13746 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13747 TypeSourceInfo *TInfo, 13748 SourceLocation StartLoc, 13749 SourceLocation Loc, 13750 IdentifierInfo *Name) { 13751 bool Invalid = false; 13752 QualType ExDeclType = TInfo->getType(); 13753 13754 // Arrays and functions decay. 13755 if (ExDeclType->isArrayType()) 13756 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13757 else if (ExDeclType->isFunctionType()) 13758 ExDeclType = Context.getPointerType(ExDeclType); 13759 13760 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13761 // The exception-declaration shall not denote a pointer or reference to an 13762 // incomplete type, other than [cv] void*. 13763 // N2844 forbids rvalue references. 13764 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13765 Diag(Loc, diag::err_catch_rvalue_ref); 13766 Invalid = true; 13767 } 13768 13769 if (ExDeclType->isVariablyModifiedType()) { 13770 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13771 Invalid = true; 13772 } 13773 13774 QualType BaseType = ExDeclType; 13775 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13776 unsigned DK = diag::err_catch_incomplete; 13777 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13778 BaseType = Ptr->getPointeeType(); 13779 Mode = 1; 13780 DK = diag::err_catch_incomplete_ptr; 13781 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13782 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13783 BaseType = Ref->getPointeeType(); 13784 Mode = 2; 13785 DK = diag::err_catch_incomplete_ref; 13786 } 13787 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13788 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13789 Invalid = true; 13790 13791 if (!Invalid && !ExDeclType->isDependentType() && 13792 RequireNonAbstractType(Loc, ExDeclType, 13793 diag::err_abstract_type_in_decl, 13794 AbstractVariableType)) 13795 Invalid = true; 13796 13797 // Only the non-fragile NeXT runtime currently supports C++ catches 13798 // of ObjC types, and no runtime supports catching ObjC types by value. 13799 if (!Invalid && getLangOpts().ObjC) { 13800 QualType T = ExDeclType; 13801 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13802 T = RT->getPointeeType(); 13803 13804 if (T->isObjCObjectType()) { 13805 Diag(Loc, diag::err_objc_object_catch); 13806 Invalid = true; 13807 } else if (T->isObjCObjectPointerType()) { 13808 // FIXME: should this be a test for macosx-fragile specifically? 13809 if (getLangOpts().ObjCRuntime.isFragile()) 13810 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13811 } 13812 } 13813 13814 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13815 ExDeclType, TInfo, SC_None); 13816 ExDecl->setExceptionVariable(true); 13817 13818 // In ARC, infer 'retaining' for variables of retainable type. 13819 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13820 Invalid = true; 13821 13822 if (!Invalid && !ExDeclType->isDependentType()) { 13823 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13824 // Insulate this from anything else we might currently be parsing. 13825 EnterExpressionEvaluationContext scope( 13826 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13827 13828 // C++ [except.handle]p16: 13829 // The object declared in an exception-declaration or, if the 13830 // exception-declaration does not specify a name, a temporary (12.2) is 13831 // copy-initialized (8.5) from the exception object. [...] 13832 // The object is destroyed when the handler exits, after the destruction 13833 // of any automatic objects initialized within the handler. 13834 // 13835 // We just pretend to initialize the object with itself, then make sure 13836 // it can be destroyed later. 13837 QualType initType = Context.getExceptionObjectType(ExDeclType); 13838 13839 InitializedEntity entity = 13840 InitializedEntity::InitializeVariable(ExDecl); 13841 InitializationKind initKind = 13842 InitializationKind::CreateCopy(Loc, SourceLocation()); 13843 13844 Expr *opaqueValue = 13845 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13846 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13847 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13848 if (result.isInvalid()) 13849 Invalid = true; 13850 else { 13851 // If the constructor used was non-trivial, set this as the 13852 // "initializer". 13853 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13854 if (!construct->getConstructor()->isTrivial()) { 13855 Expr *init = MaybeCreateExprWithCleanups(construct); 13856 ExDecl->setInit(init); 13857 } 13858 13859 // And make sure it's destructable. 13860 FinalizeVarWithDestructor(ExDecl, recordType); 13861 } 13862 } 13863 } 13864 13865 if (Invalid) 13866 ExDecl->setInvalidDecl(); 13867 13868 return ExDecl; 13869 } 13870 13871 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13872 /// handler. 13873 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13874 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13875 bool Invalid = D.isInvalidType(); 13876 13877 // Check for unexpanded parameter packs. 13878 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13879 UPPC_ExceptionType)) { 13880 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13881 D.getIdentifierLoc()); 13882 Invalid = true; 13883 } 13884 13885 IdentifierInfo *II = D.getIdentifier(); 13886 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13887 LookupOrdinaryName, 13888 ForVisibleRedeclaration)) { 13889 // The scope should be freshly made just for us. There is just no way 13890 // it contains any previous declaration, except for function parameters in 13891 // a function-try-block's catch statement. 13892 assert(!S->isDeclScope(PrevDecl)); 13893 if (isDeclInScope(PrevDecl, CurContext, S)) { 13894 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13895 << D.getIdentifier(); 13896 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13897 Invalid = true; 13898 } else if (PrevDecl->isTemplateParameter()) 13899 // Maybe we will complain about the shadowed template parameter. 13900 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13901 } 13902 13903 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13904 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13905 << D.getCXXScopeSpec().getRange(); 13906 Invalid = true; 13907 } 13908 13909 VarDecl *ExDecl = BuildExceptionDeclaration( 13910 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 13911 if (Invalid) 13912 ExDecl->setInvalidDecl(); 13913 13914 // Add the exception declaration into this scope. 13915 if (II) 13916 PushOnScopeChains(ExDecl, S); 13917 else 13918 CurContext->addDecl(ExDecl); 13919 13920 ProcessDeclAttributes(S, ExDecl, D); 13921 return ExDecl; 13922 } 13923 13924 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13925 Expr *AssertExpr, 13926 Expr *AssertMessageExpr, 13927 SourceLocation RParenLoc) { 13928 StringLiteral *AssertMessage = 13929 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13930 13931 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13932 return nullptr; 13933 13934 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13935 AssertMessage, RParenLoc, false); 13936 } 13937 13938 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13939 Expr *AssertExpr, 13940 StringLiteral *AssertMessage, 13941 SourceLocation RParenLoc, 13942 bool Failed) { 13943 assert(AssertExpr != nullptr && "Expected non-null condition"); 13944 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13945 !Failed) { 13946 // In a static_assert-declaration, the constant-expression shall be a 13947 // constant expression that can be contextually converted to bool. 13948 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13949 if (Converted.isInvalid()) 13950 Failed = true; 13951 else 13952 Converted = ConstantExpr::Create(Context, Converted.get()); 13953 13954 llvm::APSInt Cond; 13955 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13956 diag::err_static_assert_expression_is_not_constant, 13957 /*AllowFold=*/false).isInvalid()) 13958 Failed = true; 13959 13960 if (!Failed && !Cond) { 13961 SmallString<256> MsgBuffer; 13962 llvm::raw_svector_ostream Msg(MsgBuffer); 13963 if (AssertMessage) 13964 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13965 13966 Expr *InnerCond = nullptr; 13967 std::string InnerCondDescription; 13968 std::tie(InnerCond, InnerCondDescription) = 13969 findFailedBooleanCondition(Converted.get()); 13970 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 13971 && !isa<IntegerLiteral>(InnerCond)) { 13972 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13973 << InnerCondDescription << !AssertMessage 13974 << Msg.str() << InnerCond->getSourceRange(); 13975 } else { 13976 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13977 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13978 } 13979 Failed = true; 13980 } 13981 } 13982 13983 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13984 /*DiscardedValue*/false, 13985 /*IsConstexpr*/true); 13986 if (FullAssertExpr.isInvalid()) 13987 Failed = true; 13988 else 13989 AssertExpr = FullAssertExpr.get(); 13990 13991 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13992 AssertExpr, AssertMessage, RParenLoc, 13993 Failed); 13994 13995 CurContext->addDecl(Decl); 13996 return Decl; 13997 } 13998 13999 /// Perform semantic analysis of the given friend type declaration. 14000 /// 14001 /// \returns A friend declaration that. 14002 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 14003 SourceLocation FriendLoc, 14004 TypeSourceInfo *TSInfo) { 14005 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 14006 14007 QualType T = TSInfo->getType(); 14008 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 14009 14010 // C++03 [class.friend]p2: 14011 // An elaborated-type-specifier shall be used in a friend declaration 14012 // for a class.* 14013 // 14014 // * The class-key of the elaborated-type-specifier is required. 14015 if (!CodeSynthesisContexts.empty()) { 14016 // Do not complain about the form of friend template types during any kind 14017 // of code synthesis. For template instantiation, we will have complained 14018 // when the template was defined. 14019 } else { 14020 if (!T->isElaboratedTypeSpecifier()) { 14021 // If we evaluated the type to a record type, suggest putting 14022 // a tag in front. 14023 if (const RecordType *RT = T->getAs<RecordType>()) { 14024 RecordDecl *RD = RT->getDecl(); 14025 14026 SmallString<16> InsertionText(" "); 14027 InsertionText += RD->getKindName(); 14028 14029 Diag(TypeRange.getBegin(), 14030 getLangOpts().CPlusPlus11 ? 14031 diag::warn_cxx98_compat_unelaborated_friend_type : 14032 diag::ext_unelaborated_friend_type) 14033 << (unsigned) RD->getTagKind() 14034 << T 14035 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 14036 InsertionText); 14037 } else { 14038 Diag(FriendLoc, 14039 getLangOpts().CPlusPlus11 ? 14040 diag::warn_cxx98_compat_nonclass_type_friend : 14041 diag::ext_nonclass_type_friend) 14042 << T 14043 << TypeRange; 14044 } 14045 } else if (T->getAs<EnumType>()) { 14046 Diag(FriendLoc, 14047 getLangOpts().CPlusPlus11 ? 14048 diag::warn_cxx98_compat_enum_friend : 14049 diag::ext_enum_friend) 14050 << T 14051 << TypeRange; 14052 } 14053 14054 // C++11 [class.friend]p3: 14055 // A friend declaration that does not declare a function shall have one 14056 // of the following forms: 14057 // friend elaborated-type-specifier ; 14058 // friend simple-type-specifier ; 14059 // friend typename-specifier ; 14060 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 14061 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 14062 } 14063 14064 // If the type specifier in a friend declaration designates a (possibly 14065 // cv-qualified) class type, that class is declared as a friend; otherwise, 14066 // the friend declaration is ignored. 14067 return FriendDecl::Create(Context, CurContext, 14068 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 14069 FriendLoc); 14070 } 14071 14072 /// Handle a friend tag declaration where the scope specifier was 14073 /// templated. 14074 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 14075 unsigned TagSpec, SourceLocation TagLoc, 14076 CXXScopeSpec &SS, IdentifierInfo *Name, 14077 SourceLocation NameLoc, 14078 const ParsedAttributesView &Attr, 14079 MultiTemplateParamsArg TempParamLists) { 14080 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14081 14082 bool IsMemberSpecialization = false; 14083 bool Invalid = false; 14084 14085 if (TemplateParameterList *TemplateParams = 14086 MatchTemplateParametersToScopeSpecifier( 14087 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 14088 IsMemberSpecialization, Invalid)) { 14089 if (TemplateParams->size() > 0) { 14090 // This is a declaration of a class template. 14091 if (Invalid) 14092 return nullptr; 14093 14094 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 14095 NameLoc, Attr, TemplateParams, AS_public, 14096 /*ModulePrivateLoc=*/SourceLocation(), 14097 FriendLoc, TempParamLists.size() - 1, 14098 TempParamLists.data()).get(); 14099 } else { 14100 // The "template<>" header is extraneous. 14101 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14102 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14103 IsMemberSpecialization = true; 14104 } 14105 } 14106 14107 if (Invalid) return nullptr; 14108 14109 bool isAllExplicitSpecializations = true; 14110 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 14111 if (TempParamLists[I]->size()) { 14112 isAllExplicitSpecializations = false; 14113 break; 14114 } 14115 } 14116 14117 // FIXME: don't ignore attributes. 14118 14119 // If it's explicit specializations all the way down, just forget 14120 // about the template header and build an appropriate non-templated 14121 // friend. TODO: for source fidelity, remember the headers. 14122 if (isAllExplicitSpecializations) { 14123 if (SS.isEmpty()) { 14124 bool Owned = false; 14125 bool IsDependent = false; 14126 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 14127 Attr, AS_public, 14128 /*ModulePrivateLoc=*/SourceLocation(), 14129 MultiTemplateParamsArg(), Owned, IsDependent, 14130 /*ScopedEnumKWLoc=*/SourceLocation(), 14131 /*ScopedEnumUsesClassTag=*/false, 14132 /*UnderlyingType=*/TypeResult(), 14133 /*IsTypeSpecifier=*/false, 14134 /*IsTemplateParamOrArg=*/false); 14135 } 14136 14137 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 14138 ElaboratedTypeKeyword Keyword 14139 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14140 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 14141 *Name, NameLoc); 14142 if (T.isNull()) 14143 return nullptr; 14144 14145 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14146 if (isa<DependentNameType>(T)) { 14147 DependentNameTypeLoc TL = 14148 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14149 TL.setElaboratedKeywordLoc(TagLoc); 14150 TL.setQualifierLoc(QualifierLoc); 14151 TL.setNameLoc(NameLoc); 14152 } else { 14153 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 14154 TL.setElaboratedKeywordLoc(TagLoc); 14155 TL.setQualifierLoc(QualifierLoc); 14156 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 14157 } 14158 14159 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14160 TSI, FriendLoc, TempParamLists); 14161 Friend->setAccess(AS_public); 14162 CurContext->addDecl(Friend); 14163 return Friend; 14164 } 14165 14166 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 14167 14168 14169 14170 // Handle the case of a templated-scope friend class. e.g. 14171 // template <class T> class A<T>::B; 14172 // FIXME: we don't support these right now. 14173 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 14174 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 14175 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14176 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 14177 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14178 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14179 TL.setElaboratedKeywordLoc(TagLoc); 14180 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 14181 TL.setNameLoc(NameLoc); 14182 14183 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14184 TSI, FriendLoc, TempParamLists); 14185 Friend->setAccess(AS_public); 14186 Friend->setUnsupportedFriend(true); 14187 CurContext->addDecl(Friend); 14188 return Friend; 14189 } 14190 14191 /// Handle a friend type declaration. This works in tandem with 14192 /// ActOnTag. 14193 /// 14194 /// Notes on friend class templates: 14195 /// 14196 /// We generally treat friend class declarations as if they were 14197 /// declaring a class. So, for example, the elaborated type specifier 14198 /// in a friend declaration is required to obey the restrictions of a 14199 /// class-head (i.e. no typedefs in the scope chain), template 14200 /// parameters are required to match up with simple template-ids, &c. 14201 /// However, unlike when declaring a template specialization, it's 14202 /// okay to refer to a template specialization without an empty 14203 /// template parameter declaration, e.g. 14204 /// friend class A<T>::B<unsigned>; 14205 /// We permit this as a special case; if there are any template 14206 /// parameters present at all, require proper matching, i.e. 14207 /// template <> template \<class T> friend class A<int>::B; 14208 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14209 MultiTemplateParamsArg TempParams) { 14210 SourceLocation Loc = DS.getBeginLoc(); 14211 14212 assert(DS.isFriendSpecified()); 14213 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14214 14215 // C++ [class.friend]p3: 14216 // A friend declaration that does not declare a function shall have one of 14217 // the following forms: 14218 // friend elaborated-type-specifier ; 14219 // friend simple-type-specifier ; 14220 // friend typename-specifier ; 14221 // 14222 // Any declaration with a type qualifier does not have that form. (It's 14223 // legal to specify a qualified type as a friend, you just can't write the 14224 // keywords.) 14225 if (DS.getTypeQualifiers()) { 14226 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 14227 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 14228 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 14229 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 14230 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 14231 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 14232 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 14233 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 14234 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 14235 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 14236 } 14237 14238 // Try to convert the decl specifier to a type. This works for 14239 // friend templates because ActOnTag never produces a ClassTemplateDecl 14240 // for a TUK_Friend. 14241 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14242 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14243 QualType T = TSI->getType(); 14244 if (TheDeclarator.isInvalidType()) 14245 return nullptr; 14246 14247 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14248 return nullptr; 14249 14250 // This is definitely an error in C++98. It's probably meant to 14251 // be forbidden in C++0x, too, but the specification is just 14252 // poorly written. 14253 // 14254 // The problem is with declarations like the following: 14255 // template <T> friend A<T>::foo; 14256 // where deciding whether a class C is a friend or not now hinges 14257 // on whether there exists an instantiation of A that causes 14258 // 'foo' to equal C. There are restrictions on class-heads 14259 // (which we declare (by fiat) elaborated friend declarations to 14260 // be) that makes this tractable. 14261 // 14262 // FIXME: handle "template <> friend class A<T>;", which 14263 // is possibly well-formed? Who even knows? 14264 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14265 Diag(Loc, diag::err_tagless_friend_type_template) 14266 << DS.getSourceRange(); 14267 return nullptr; 14268 } 14269 14270 // C++98 [class.friend]p1: A friend of a class is a function 14271 // or class that is not a member of the class . . . 14272 // This is fixed in DR77, which just barely didn't make the C++03 14273 // deadline. It's also a very silly restriction that seriously 14274 // affects inner classes and which nobody else seems to implement; 14275 // thus we never diagnose it, not even in -pedantic. 14276 // 14277 // But note that we could warn about it: it's always useless to 14278 // friend one of your own members (it's not, however, worthless to 14279 // friend a member of an arbitrary specialization of your template). 14280 14281 Decl *D; 14282 if (!TempParams.empty()) 14283 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14284 TempParams, 14285 TSI, 14286 DS.getFriendSpecLoc()); 14287 else 14288 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14289 14290 if (!D) 14291 return nullptr; 14292 14293 D->setAccess(AS_public); 14294 CurContext->addDecl(D); 14295 14296 return D; 14297 } 14298 14299 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14300 MultiTemplateParamsArg TemplateParams) { 14301 const DeclSpec &DS = D.getDeclSpec(); 14302 14303 assert(DS.isFriendSpecified()); 14304 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14305 14306 SourceLocation Loc = D.getIdentifierLoc(); 14307 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14308 14309 // C++ [class.friend]p1 14310 // A friend of a class is a function or class.... 14311 // Note that this sees through typedefs, which is intended. 14312 // It *doesn't* see through dependent types, which is correct 14313 // according to [temp.arg.type]p3: 14314 // If a declaration acquires a function type through a 14315 // type dependent on a template-parameter and this causes 14316 // a declaration that does not use the syntactic form of a 14317 // function declarator to have a function type, the program 14318 // is ill-formed. 14319 if (!TInfo->getType()->isFunctionType()) { 14320 Diag(Loc, diag::err_unexpected_friend); 14321 14322 // It might be worthwhile to try to recover by creating an 14323 // appropriate declaration. 14324 return nullptr; 14325 } 14326 14327 // C++ [namespace.memdef]p3 14328 // - If a friend declaration in a non-local class first declares a 14329 // class or function, the friend class or function is a member 14330 // of the innermost enclosing namespace. 14331 // - The name of the friend is not found by simple name lookup 14332 // until a matching declaration is provided in that namespace 14333 // scope (either before or after the class declaration granting 14334 // friendship). 14335 // - If a friend function is called, its name may be found by the 14336 // name lookup that considers functions from namespaces and 14337 // classes associated with the types of the function arguments. 14338 // - When looking for a prior declaration of a class or a function 14339 // declared as a friend, scopes outside the innermost enclosing 14340 // namespace scope are not considered. 14341 14342 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14343 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14344 assert(NameInfo.getName()); 14345 14346 // Check for unexpanded parameter packs. 14347 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14348 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14349 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14350 return nullptr; 14351 14352 // The context we found the declaration in, or in which we should 14353 // create the declaration. 14354 DeclContext *DC; 14355 Scope *DCScope = S; 14356 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14357 ForExternalRedeclaration); 14358 14359 // There are five cases here. 14360 // - There's no scope specifier and we're in a local class. Only look 14361 // for functions declared in the immediately-enclosing block scope. 14362 // We recover from invalid scope qualifiers as if they just weren't there. 14363 FunctionDecl *FunctionContainingLocalClass = nullptr; 14364 if ((SS.isInvalid() || !SS.isSet()) && 14365 (FunctionContainingLocalClass = 14366 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14367 // C++11 [class.friend]p11: 14368 // If a friend declaration appears in a local class and the name 14369 // specified is an unqualified name, a prior declaration is 14370 // looked up without considering scopes that are outside the 14371 // innermost enclosing non-class scope. For a friend function 14372 // declaration, if there is no prior declaration, the program is 14373 // ill-formed. 14374 14375 // Find the innermost enclosing non-class scope. This is the block 14376 // scope containing the local class definition (or for a nested class, 14377 // the outer local class). 14378 DCScope = S->getFnParent(); 14379 14380 // Look up the function name in the scope. 14381 Previous.clear(LookupLocalFriendName); 14382 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14383 14384 if (!Previous.empty()) { 14385 // All possible previous declarations must have the same context: 14386 // either they were declared at block scope or they are members of 14387 // one of the enclosing local classes. 14388 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14389 } else { 14390 // This is ill-formed, but provide the context that we would have 14391 // declared the function in, if we were permitted to, for error recovery. 14392 DC = FunctionContainingLocalClass; 14393 } 14394 adjustContextForLocalExternDecl(DC); 14395 14396 // C++ [class.friend]p6: 14397 // A function can be defined in a friend declaration of a class if and 14398 // only if the class is a non-local class (9.8), the function name is 14399 // unqualified, and the function has namespace scope. 14400 if (D.isFunctionDefinition()) { 14401 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14402 } 14403 14404 // - There's no scope specifier, in which case we just go to the 14405 // appropriate scope and look for a function or function template 14406 // there as appropriate. 14407 } else if (SS.isInvalid() || !SS.isSet()) { 14408 // C++11 [namespace.memdef]p3: 14409 // If the name in a friend declaration is neither qualified nor 14410 // a template-id and the declaration is a function or an 14411 // elaborated-type-specifier, the lookup to determine whether 14412 // the entity has been previously declared shall not consider 14413 // any scopes outside the innermost enclosing namespace. 14414 bool isTemplateId = 14415 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14416 14417 // Find the appropriate context according to the above. 14418 DC = CurContext; 14419 14420 // Skip class contexts. If someone can cite chapter and verse 14421 // for this behavior, that would be nice --- it's what GCC and 14422 // EDG do, and it seems like a reasonable intent, but the spec 14423 // really only says that checks for unqualified existing 14424 // declarations should stop at the nearest enclosing namespace, 14425 // not that they should only consider the nearest enclosing 14426 // namespace. 14427 while (DC->isRecord()) 14428 DC = DC->getParent(); 14429 14430 DeclContext *LookupDC = DC; 14431 while (LookupDC->isTransparentContext()) 14432 LookupDC = LookupDC->getParent(); 14433 14434 while (true) { 14435 LookupQualifiedName(Previous, LookupDC); 14436 14437 if (!Previous.empty()) { 14438 DC = LookupDC; 14439 break; 14440 } 14441 14442 if (isTemplateId) { 14443 if (isa<TranslationUnitDecl>(LookupDC)) break; 14444 } else { 14445 if (LookupDC->isFileContext()) break; 14446 } 14447 LookupDC = LookupDC->getParent(); 14448 } 14449 14450 DCScope = getScopeForDeclContext(S, DC); 14451 14452 // - There's a non-dependent scope specifier, in which case we 14453 // compute it and do a previous lookup there for a function 14454 // or function template. 14455 } else if (!SS.getScopeRep()->isDependent()) { 14456 DC = computeDeclContext(SS); 14457 if (!DC) return nullptr; 14458 14459 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14460 14461 LookupQualifiedName(Previous, DC); 14462 14463 // C++ [class.friend]p1: A friend of a class is a function or 14464 // class that is not a member of the class . . . 14465 if (DC->Equals(CurContext)) 14466 Diag(DS.getFriendSpecLoc(), 14467 getLangOpts().CPlusPlus11 ? 14468 diag::warn_cxx98_compat_friend_is_member : 14469 diag::err_friend_is_member); 14470 14471 if (D.isFunctionDefinition()) { 14472 // C++ [class.friend]p6: 14473 // A function can be defined in a friend declaration of a class if and 14474 // only if the class is a non-local class (9.8), the function name is 14475 // unqualified, and the function has namespace scope. 14476 // 14477 // FIXME: We should only do this if the scope specifier names the 14478 // innermost enclosing namespace; otherwise the fixit changes the 14479 // meaning of the code. 14480 SemaDiagnosticBuilder DB 14481 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14482 14483 DB << SS.getScopeRep(); 14484 if (DC->isFileContext()) 14485 DB << FixItHint::CreateRemoval(SS.getRange()); 14486 SS.clear(); 14487 } 14488 14489 // - There's a scope specifier that does not match any template 14490 // parameter lists, in which case we use some arbitrary context, 14491 // create a method or method template, and wait for instantiation. 14492 // - There's a scope specifier that does match some template 14493 // parameter lists, which we don't handle right now. 14494 } else { 14495 if (D.isFunctionDefinition()) { 14496 // C++ [class.friend]p6: 14497 // A function can be defined in a friend declaration of a class if and 14498 // only if the class is a non-local class (9.8), the function name is 14499 // unqualified, and the function has namespace scope. 14500 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14501 << SS.getScopeRep(); 14502 } 14503 14504 DC = CurContext; 14505 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14506 } 14507 14508 if (!DC->isRecord()) { 14509 int DiagArg = -1; 14510 switch (D.getName().getKind()) { 14511 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14512 case UnqualifiedIdKind::IK_ConstructorName: 14513 DiagArg = 0; 14514 break; 14515 case UnqualifiedIdKind::IK_DestructorName: 14516 DiagArg = 1; 14517 break; 14518 case UnqualifiedIdKind::IK_ConversionFunctionId: 14519 DiagArg = 2; 14520 break; 14521 case UnqualifiedIdKind::IK_DeductionGuideName: 14522 DiagArg = 3; 14523 break; 14524 case UnqualifiedIdKind::IK_Identifier: 14525 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14526 case UnqualifiedIdKind::IK_LiteralOperatorId: 14527 case UnqualifiedIdKind::IK_OperatorFunctionId: 14528 case UnqualifiedIdKind::IK_TemplateId: 14529 break; 14530 } 14531 // This implies that it has to be an operator or function. 14532 if (DiagArg >= 0) { 14533 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14534 return nullptr; 14535 } 14536 } 14537 14538 // FIXME: This is an egregious hack to cope with cases where the scope stack 14539 // does not contain the declaration context, i.e., in an out-of-line 14540 // definition of a class. 14541 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14542 if (!DCScope) { 14543 FakeDCScope.setEntity(DC); 14544 DCScope = &FakeDCScope; 14545 } 14546 14547 bool AddToScope = true; 14548 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14549 TemplateParams, AddToScope); 14550 if (!ND) return nullptr; 14551 14552 assert(ND->getLexicalDeclContext() == CurContext); 14553 14554 // If we performed typo correction, we might have added a scope specifier 14555 // and changed the decl context. 14556 DC = ND->getDeclContext(); 14557 14558 // Add the function declaration to the appropriate lookup tables, 14559 // adjusting the redeclarations list as necessary. We don't 14560 // want to do this yet if the friending class is dependent. 14561 // 14562 // Also update the scope-based lookup if the target context's 14563 // lookup context is in lexical scope. 14564 if (!CurContext->isDependentContext()) { 14565 DC = DC->getRedeclContext(); 14566 DC->makeDeclVisibleInContext(ND); 14567 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14568 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14569 } 14570 14571 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14572 D.getIdentifierLoc(), ND, 14573 DS.getFriendSpecLoc()); 14574 FrD->setAccess(AS_public); 14575 CurContext->addDecl(FrD); 14576 14577 if (ND->isInvalidDecl()) { 14578 FrD->setInvalidDecl(); 14579 } else { 14580 if (DC->isRecord()) CheckFriendAccess(ND); 14581 14582 FunctionDecl *FD; 14583 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14584 FD = FTD->getTemplatedDecl(); 14585 else 14586 FD = cast<FunctionDecl>(ND); 14587 14588 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14589 // default argument expression, that declaration shall be a definition 14590 // and shall be the only declaration of the function or function 14591 // template in the translation unit. 14592 if (functionDeclHasDefaultArgument(FD)) { 14593 // We can't look at FD->getPreviousDecl() because it may not have been set 14594 // if we're in a dependent context. If the function is known to be a 14595 // redeclaration, we will have narrowed Previous down to the right decl. 14596 if (D.isRedeclaration()) { 14597 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14598 Diag(Previous.getRepresentativeDecl()->getLocation(), 14599 diag::note_previous_declaration); 14600 } else if (!D.isFunctionDefinition()) 14601 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14602 } 14603 14604 // Mark templated-scope function declarations as unsupported. 14605 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14606 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14607 << SS.getScopeRep() << SS.getRange() 14608 << cast<CXXRecordDecl>(CurContext); 14609 FrD->setUnsupportedFriend(true); 14610 } 14611 } 14612 14613 return ND; 14614 } 14615 14616 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14617 AdjustDeclIfTemplate(Dcl); 14618 14619 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14620 if (!Fn) { 14621 Diag(DelLoc, diag::err_deleted_non_function); 14622 return; 14623 } 14624 14625 // Deleted function does not have a body. 14626 Fn->setWillHaveBody(false); 14627 14628 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14629 // Don't consider the implicit declaration we generate for explicit 14630 // specializations. FIXME: Do not generate these implicit declarations. 14631 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14632 Prev->getPreviousDecl()) && 14633 !Prev->isDefined()) { 14634 Diag(DelLoc, diag::err_deleted_decl_not_first); 14635 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14636 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14637 : diag::note_previous_declaration); 14638 } 14639 // If the declaration wasn't the first, we delete the function anyway for 14640 // recovery. 14641 Fn = Fn->getCanonicalDecl(); 14642 } 14643 14644 // dllimport/dllexport cannot be deleted. 14645 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14646 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14647 Fn->setInvalidDecl(); 14648 } 14649 14650 if (Fn->isDeleted()) 14651 return; 14652 14653 // See if we're deleting a function which is already known to override a 14654 // non-deleted virtual function. 14655 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14656 bool IssuedDiagnostic = false; 14657 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14658 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14659 if (!IssuedDiagnostic) { 14660 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14661 IssuedDiagnostic = true; 14662 } 14663 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14664 } 14665 } 14666 // If this function was implicitly deleted because it was defaulted, 14667 // explain why it was deleted. 14668 if (IssuedDiagnostic && MD->isDefaulted()) 14669 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14670 /*Diagnose*/true); 14671 } 14672 14673 // C++11 [basic.start.main]p3: 14674 // A program that defines main as deleted [...] is ill-formed. 14675 if (Fn->isMain()) 14676 Diag(DelLoc, diag::err_deleted_main); 14677 14678 // C++11 [dcl.fct.def.delete]p4: 14679 // A deleted function is implicitly inline. 14680 Fn->setImplicitlyInline(); 14681 Fn->setDeletedAsWritten(); 14682 } 14683 14684 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14685 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14686 14687 if (MD) { 14688 if (MD->getParent()->isDependentType()) { 14689 MD->setDefaulted(); 14690 MD->setExplicitlyDefaulted(); 14691 return; 14692 } 14693 14694 CXXSpecialMember Member = getSpecialMember(MD); 14695 if (Member == CXXInvalid) { 14696 if (!MD->isInvalidDecl()) 14697 Diag(DefaultLoc, diag::err_default_special_members); 14698 return; 14699 } 14700 14701 MD->setDefaulted(); 14702 MD->setExplicitlyDefaulted(); 14703 14704 // Unset that we will have a body for this function. We might not, 14705 // if it turns out to be trivial, and we don't need this marking now 14706 // that we've marked it as defaulted. 14707 MD->setWillHaveBody(false); 14708 14709 // If this definition appears within the record, do the checking when 14710 // the record is complete. 14711 const FunctionDecl *Primary = MD; 14712 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14713 // Ask the template instantiation pattern that actually had the 14714 // '= default' on it. 14715 Primary = Pattern; 14716 14717 // If the method was defaulted on its first declaration, we will have 14718 // already performed the checking in CheckCompletedCXXClass. Such a 14719 // declaration doesn't trigger an implicit definition. 14720 if (Primary->getCanonicalDecl()->isDefaulted()) 14721 return; 14722 14723 CheckExplicitlyDefaultedSpecialMember(MD); 14724 14725 if (!MD->isInvalidDecl()) 14726 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14727 } else { 14728 Diag(DefaultLoc, diag::err_default_special_members); 14729 } 14730 } 14731 14732 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14733 for (Stmt *SubStmt : S->children()) { 14734 if (!SubStmt) 14735 continue; 14736 if (isa<ReturnStmt>(SubStmt)) 14737 Self.Diag(SubStmt->getBeginLoc(), 14738 diag::err_return_in_constructor_handler); 14739 if (!isa<Expr>(SubStmt)) 14740 SearchForReturnInStmt(Self, SubStmt); 14741 } 14742 } 14743 14744 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14745 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14746 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14747 SearchForReturnInStmt(*this, Handler); 14748 } 14749 } 14750 14751 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14752 const CXXMethodDecl *Old) { 14753 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14754 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14755 14756 if (OldFT->hasExtParameterInfos()) { 14757 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14758 // A parameter of the overriding method should be annotated with noescape 14759 // if the corresponding parameter of the overridden method is annotated. 14760 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14761 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14762 Diag(New->getParamDecl(I)->getLocation(), 14763 diag::warn_overriding_method_missing_noescape); 14764 Diag(Old->getParamDecl(I)->getLocation(), 14765 diag::note_overridden_marked_noescape); 14766 } 14767 } 14768 14769 // Virtual overrides must have the same code_seg. 14770 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 14771 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 14772 if ((NewCSA || OldCSA) && 14773 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 14774 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 14775 Diag(Old->getLocation(), diag::note_previous_declaration); 14776 return true; 14777 } 14778 14779 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14780 14781 // If the calling conventions match, everything is fine 14782 if (NewCC == OldCC) 14783 return false; 14784 14785 // If the calling conventions mismatch because the new function is static, 14786 // suppress the calling convention mismatch error; the error about static 14787 // function override (err_static_overrides_virtual from 14788 // Sema::CheckFunctionDeclaration) is more clear. 14789 if (New->getStorageClass() == SC_Static) 14790 return false; 14791 14792 Diag(New->getLocation(), 14793 diag::err_conflicting_overriding_cc_attributes) 14794 << New->getDeclName() << New->getType() << Old->getType(); 14795 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14796 return true; 14797 } 14798 14799 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14800 const CXXMethodDecl *Old) { 14801 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14802 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14803 14804 if (Context.hasSameType(NewTy, OldTy) || 14805 NewTy->isDependentType() || OldTy->isDependentType()) 14806 return false; 14807 14808 // Check if the return types are covariant 14809 QualType NewClassTy, OldClassTy; 14810 14811 /// Both types must be pointers or references to classes. 14812 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14813 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14814 NewClassTy = NewPT->getPointeeType(); 14815 OldClassTy = OldPT->getPointeeType(); 14816 } 14817 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14818 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14819 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14820 NewClassTy = NewRT->getPointeeType(); 14821 OldClassTy = OldRT->getPointeeType(); 14822 } 14823 } 14824 } 14825 14826 // The return types aren't either both pointers or references to a class type. 14827 if (NewClassTy.isNull()) { 14828 Diag(New->getLocation(), 14829 diag::err_different_return_type_for_overriding_virtual_function) 14830 << New->getDeclName() << NewTy << OldTy 14831 << New->getReturnTypeSourceRange(); 14832 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14833 << Old->getReturnTypeSourceRange(); 14834 14835 return true; 14836 } 14837 14838 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14839 // C++14 [class.virtual]p8: 14840 // If the class type in the covariant return type of D::f differs from 14841 // that of B::f, the class type in the return type of D::f shall be 14842 // complete at the point of declaration of D::f or shall be the class 14843 // type D. 14844 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14845 if (!RT->isBeingDefined() && 14846 RequireCompleteType(New->getLocation(), NewClassTy, 14847 diag::err_covariant_return_incomplete, 14848 New->getDeclName())) 14849 return true; 14850 } 14851 14852 // Check if the new class derives from the old class. 14853 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14854 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14855 << New->getDeclName() << NewTy << OldTy 14856 << New->getReturnTypeSourceRange(); 14857 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14858 << Old->getReturnTypeSourceRange(); 14859 return true; 14860 } 14861 14862 // Check if we the conversion from derived to base is valid. 14863 if (CheckDerivedToBaseConversion( 14864 NewClassTy, OldClassTy, 14865 diag::err_covariant_return_inaccessible_base, 14866 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14867 New->getLocation(), New->getReturnTypeSourceRange(), 14868 New->getDeclName(), nullptr)) { 14869 // FIXME: this note won't trigger for delayed access control 14870 // diagnostics, and it's impossible to get an undelayed error 14871 // here from access control during the original parse because 14872 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14873 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14874 << Old->getReturnTypeSourceRange(); 14875 return true; 14876 } 14877 } 14878 14879 // The qualifiers of the return types must be the same. 14880 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14881 Diag(New->getLocation(), 14882 diag::err_covariant_return_type_different_qualifications) 14883 << New->getDeclName() << NewTy << OldTy 14884 << New->getReturnTypeSourceRange(); 14885 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14886 << Old->getReturnTypeSourceRange(); 14887 return true; 14888 } 14889 14890 14891 // The new class type must have the same or less qualifiers as the old type. 14892 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14893 Diag(New->getLocation(), 14894 diag::err_covariant_return_type_class_type_more_qualified) 14895 << New->getDeclName() << NewTy << OldTy 14896 << New->getReturnTypeSourceRange(); 14897 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14898 << Old->getReturnTypeSourceRange(); 14899 return true; 14900 } 14901 14902 return false; 14903 } 14904 14905 /// Mark the given method pure. 14906 /// 14907 /// \param Method the method to be marked pure. 14908 /// 14909 /// \param InitRange the source range that covers the "0" initializer. 14910 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14911 SourceLocation EndLoc = InitRange.getEnd(); 14912 if (EndLoc.isValid()) 14913 Method->setRangeEnd(EndLoc); 14914 14915 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14916 Method->setPure(); 14917 return false; 14918 } 14919 14920 if (!Method->isInvalidDecl()) 14921 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14922 << Method->getDeclName() << InitRange; 14923 return true; 14924 } 14925 14926 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14927 if (D->getFriendObjectKind()) 14928 Diag(D->getLocation(), diag::err_pure_friend); 14929 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14930 CheckPureMethod(M, ZeroLoc); 14931 else 14932 Diag(D->getLocation(), diag::err_illegal_initializer); 14933 } 14934 14935 /// Determine whether the given declaration is a global variable or 14936 /// static data member. 14937 static bool isNonlocalVariable(const Decl *D) { 14938 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14939 return Var->hasGlobalStorage(); 14940 14941 return false; 14942 } 14943 14944 /// Invoked when we are about to parse an initializer for the declaration 14945 /// 'Dcl'. 14946 /// 14947 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14948 /// static data member of class X, names should be looked up in the scope of 14949 /// class X. If the declaration had a scope specifier, a scope will have 14950 /// been created and passed in for this purpose. Otherwise, S will be null. 14951 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14952 // If there is no declaration, there was an error parsing it. 14953 if (!D || D->isInvalidDecl()) 14954 return; 14955 14956 // We will always have a nested name specifier here, but this declaration 14957 // might not be out of line if the specifier names the current namespace: 14958 // extern int n; 14959 // int ::n = 0; 14960 if (S && D->isOutOfLine()) 14961 EnterDeclaratorContext(S, D->getDeclContext()); 14962 14963 // If we are parsing the initializer for a static data member, push a 14964 // new expression evaluation context that is associated with this static 14965 // data member. 14966 if (isNonlocalVariable(D)) 14967 PushExpressionEvaluationContext( 14968 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14969 } 14970 14971 /// Invoked after we are finished parsing an initializer for the declaration D. 14972 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14973 // If there is no declaration, there was an error parsing it. 14974 if (!D || D->isInvalidDecl()) 14975 return; 14976 14977 if (isNonlocalVariable(D)) 14978 PopExpressionEvaluationContext(); 14979 14980 if (S && D->isOutOfLine()) 14981 ExitDeclaratorContext(S); 14982 } 14983 14984 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14985 /// C++ if/switch/while/for statement. 14986 /// e.g: "if (int x = f()) {...}" 14987 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14988 // C++ 6.4p2: 14989 // The declarator shall not specify a function or an array. 14990 // The type-specifier-seq shall not contain typedef and shall not declare a 14991 // new class or enumeration. 14992 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14993 "Parser allowed 'typedef' as storage class of condition decl."); 14994 14995 Decl *Dcl = ActOnDeclarator(S, D); 14996 if (!Dcl) 14997 return true; 14998 14999 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 15000 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 15001 << D.getSourceRange(); 15002 return true; 15003 } 15004 15005 return Dcl; 15006 } 15007 15008 void Sema::LoadExternalVTableUses() { 15009 if (!ExternalSource) 15010 return; 15011 15012 SmallVector<ExternalVTableUse, 4> VTables; 15013 ExternalSource->ReadUsedVTables(VTables); 15014 SmallVector<VTableUse, 4> NewUses; 15015 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 15016 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 15017 = VTablesUsed.find(VTables[I].Record); 15018 // Even if a definition wasn't required before, it may be required now. 15019 if (Pos != VTablesUsed.end()) { 15020 if (!Pos->second && VTables[I].DefinitionRequired) 15021 Pos->second = true; 15022 continue; 15023 } 15024 15025 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 15026 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 15027 } 15028 15029 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 15030 } 15031 15032 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 15033 bool DefinitionRequired) { 15034 // Ignore any vtable uses in unevaluated operands or for classes that do 15035 // not have a vtable. 15036 if (!Class->isDynamicClass() || Class->isDependentContext() || 15037 CurContext->isDependentContext() || isUnevaluatedContext()) 15038 return; 15039 // Do not mark as used if compiling for the device outside of the target 15040 // region. 15041 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 15042 !isInOpenMPDeclareTargetContext() && 15043 !isInOpenMPTargetExecutionDirective()) { 15044 if (!DefinitionRequired) 15045 MarkVirtualMembersReferenced(Loc, Class); 15046 return; 15047 } 15048 15049 // Try to insert this class into the map. 15050 LoadExternalVTableUses(); 15051 Class = Class->getCanonicalDecl(); 15052 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 15053 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 15054 if (!Pos.second) { 15055 // If we already had an entry, check to see if we are promoting this vtable 15056 // to require a definition. If so, we need to reappend to the VTableUses 15057 // list, since we may have already processed the first entry. 15058 if (DefinitionRequired && !Pos.first->second) { 15059 Pos.first->second = true; 15060 } else { 15061 // Otherwise, we can early exit. 15062 return; 15063 } 15064 } else { 15065 // The Microsoft ABI requires that we perform the destructor body 15066 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 15067 // the deleting destructor is emitted with the vtable, not with the 15068 // destructor definition as in the Itanium ABI. 15069 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15070 CXXDestructorDecl *DD = Class->getDestructor(); 15071 if (DD && DD->isVirtual() && !DD->isDeleted()) { 15072 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 15073 // If this is an out-of-line declaration, marking it referenced will 15074 // not do anything. Manually call CheckDestructor to look up operator 15075 // delete(). 15076 ContextRAII SavedContext(*this, DD); 15077 CheckDestructor(DD); 15078 } else { 15079 MarkFunctionReferenced(Loc, Class->getDestructor()); 15080 } 15081 } 15082 } 15083 } 15084 15085 // Local classes need to have their virtual members marked 15086 // immediately. For all other classes, we mark their virtual members 15087 // at the end of the translation unit. 15088 if (Class->isLocalClass()) 15089 MarkVirtualMembersReferenced(Loc, Class); 15090 else 15091 VTableUses.push_back(std::make_pair(Class, Loc)); 15092 } 15093 15094 bool Sema::DefineUsedVTables() { 15095 LoadExternalVTableUses(); 15096 if (VTableUses.empty()) 15097 return false; 15098 15099 // Note: The VTableUses vector could grow as a result of marking 15100 // the members of a class as "used", so we check the size each 15101 // time through the loop and prefer indices (which are stable) to 15102 // iterators (which are not). 15103 bool DefinedAnything = false; 15104 for (unsigned I = 0; I != VTableUses.size(); ++I) { 15105 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 15106 if (!Class) 15107 continue; 15108 TemplateSpecializationKind ClassTSK = 15109 Class->getTemplateSpecializationKind(); 15110 15111 SourceLocation Loc = VTableUses[I].second; 15112 15113 bool DefineVTable = true; 15114 15115 // If this class has a key function, but that key function is 15116 // defined in another translation unit, we don't need to emit the 15117 // vtable even though we're using it. 15118 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 15119 if (KeyFunction && !KeyFunction->hasBody()) { 15120 // The key function is in another translation unit. 15121 DefineVTable = false; 15122 TemplateSpecializationKind TSK = 15123 KeyFunction->getTemplateSpecializationKind(); 15124 assert(TSK != TSK_ExplicitInstantiationDefinition && 15125 TSK != TSK_ImplicitInstantiation && 15126 "Instantiations don't have key functions"); 15127 (void)TSK; 15128 } else if (!KeyFunction) { 15129 // If we have a class with no key function that is the subject 15130 // of an explicit instantiation declaration, suppress the 15131 // vtable; it will live with the explicit instantiation 15132 // definition. 15133 bool IsExplicitInstantiationDeclaration = 15134 ClassTSK == TSK_ExplicitInstantiationDeclaration; 15135 for (auto R : Class->redecls()) { 15136 TemplateSpecializationKind TSK 15137 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 15138 if (TSK == TSK_ExplicitInstantiationDeclaration) 15139 IsExplicitInstantiationDeclaration = true; 15140 else if (TSK == TSK_ExplicitInstantiationDefinition) { 15141 IsExplicitInstantiationDeclaration = false; 15142 break; 15143 } 15144 } 15145 15146 if (IsExplicitInstantiationDeclaration) 15147 DefineVTable = false; 15148 } 15149 15150 // The exception specifications for all virtual members may be needed even 15151 // if we are not providing an authoritative form of the vtable in this TU. 15152 // We may choose to emit it available_externally anyway. 15153 if (!DefineVTable) { 15154 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 15155 continue; 15156 } 15157 15158 // Mark all of the virtual members of this class as referenced, so 15159 // that we can build a vtable. Then, tell the AST consumer that a 15160 // vtable for this class is required. 15161 DefinedAnything = true; 15162 MarkVirtualMembersReferenced(Loc, Class); 15163 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 15164 if (VTablesUsed[Canonical]) 15165 Consumer.HandleVTable(Class); 15166 15167 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 15168 // no key function or the key function is inlined. Don't warn in C++ ABIs 15169 // that lack key functions, since the user won't be able to make one. 15170 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 15171 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 15172 const FunctionDecl *KeyFunctionDef = nullptr; 15173 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 15174 KeyFunctionDef->isInlined())) { 15175 Diag(Class->getLocation(), 15176 ClassTSK == TSK_ExplicitInstantiationDefinition 15177 ? diag::warn_weak_template_vtable 15178 : diag::warn_weak_vtable) 15179 << Class; 15180 } 15181 } 15182 } 15183 VTableUses.clear(); 15184 15185 return DefinedAnything; 15186 } 15187 15188 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 15189 const CXXRecordDecl *RD) { 15190 for (const auto *I : RD->methods()) 15191 if (I->isVirtual() && !I->isPure()) 15192 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 15193 } 15194 15195 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 15196 const CXXRecordDecl *RD) { 15197 // Mark all functions which will appear in RD's vtable as used. 15198 CXXFinalOverriderMap FinalOverriders; 15199 RD->getFinalOverriders(FinalOverriders); 15200 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 15201 E = FinalOverriders.end(); 15202 I != E; ++I) { 15203 for (OverridingMethods::const_iterator OI = I->second.begin(), 15204 OE = I->second.end(); 15205 OI != OE; ++OI) { 15206 assert(OI->second.size() > 0 && "no final overrider"); 15207 CXXMethodDecl *Overrider = OI->second.front().Method; 15208 15209 // C++ [basic.def.odr]p2: 15210 // [...] A virtual member function is used if it is not pure. [...] 15211 if (!Overrider->isPure()) 15212 MarkFunctionReferenced(Loc, Overrider); 15213 } 15214 } 15215 15216 // Only classes that have virtual bases need a VTT. 15217 if (RD->getNumVBases() == 0) 15218 return; 15219 15220 for (const auto &I : RD->bases()) { 15221 const CXXRecordDecl *Base = 15222 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15223 if (Base->getNumVBases() == 0) 15224 continue; 15225 MarkVirtualMembersReferenced(Loc, Base); 15226 } 15227 } 15228 15229 /// SetIvarInitializers - This routine builds initialization ASTs for the 15230 /// Objective-C implementation whose ivars need be initialized. 15231 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15232 if (!getLangOpts().CPlusPlus) 15233 return; 15234 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15235 SmallVector<ObjCIvarDecl*, 8> ivars; 15236 CollectIvarsToConstructOrDestruct(OID, ivars); 15237 if (ivars.empty()) 15238 return; 15239 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15240 for (unsigned i = 0; i < ivars.size(); i++) { 15241 FieldDecl *Field = ivars[i]; 15242 if (Field->isInvalidDecl()) 15243 continue; 15244 15245 CXXCtorInitializer *Member; 15246 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15247 InitializationKind InitKind = 15248 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15249 15250 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15251 ExprResult MemberInit = 15252 InitSeq.Perform(*this, InitEntity, InitKind, None); 15253 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15254 // Note, MemberInit could actually come back empty if no initialization 15255 // is required (e.g., because it would call a trivial default constructor) 15256 if (!MemberInit.get() || MemberInit.isInvalid()) 15257 continue; 15258 15259 Member = 15260 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15261 SourceLocation(), 15262 MemberInit.getAs<Expr>(), 15263 SourceLocation()); 15264 AllToInit.push_back(Member); 15265 15266 // Be sure that the destructor is accessible and is marked as referenced. 15267 if (const RecordType *RecordTy = 15268 Context.getBaseElementType(Field->getType()) 15269 ->getAs<RecordType>()) { 15270 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15271 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15272 MarkFunctionReferenced(Field->getLocation(), Destructor); 15273 CheckDestructorAccess(Field->getLocation(), Destructor, 15274 PDiag(diag::err_access_dtor_ivar) 15275 << Context.getBaseElementType(Field->getType())); 15276 } 15277 } 15278 } 15279 ObjCImplementation->setIvarInitializers(Context, 15280 AllToInit.data(), AllToInit.size()); 15281 } 15282 } 15283 15284 static 15285 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15286 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15287 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15288 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15289 Sema &S) { 15290 if (Ctor->isInvalidDecl()) 15291 return; 15292 15293 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15294 15295 // Target may not be determinable yet, for instance if this is a dependent 15296 // call in an uninstantiated template. 15297 if (Target) { 15298 const FunctionDecl *FNTarget = nullptr; 15299 (void)Target->hasBody(FNTarget); 15300 Target = const_cast<CXXConstructorDecl*>( 15301 cast_or_null<CXXConstructorDecl>(FNTarget)); 15302 } 15303 15304 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15305 // Avoid dereferencing a null pointer here. 15306 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15307 15308 if (!Current.insert(Canonical).second) 15309 return; 15310 15311 // We know that beyond here, we aren't chaining into a cycle. 15312 if (!Target || !Target->isDelegatingConstructor() || 15313 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15314 Valid.insert(Current.begin(), Current.end()); 15315 Current.clear(); 15316 // We've hit a cycle. 15317 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15318 Current.count(TCanonical)) { 15319 // If we haven't diagnosed this cycle yet, do so now. 15320 if (!Invalid.count(TCanonical)) { 15321 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15322 diag::warn_delegating_ctor_cycle) 15323 << Ctor; 15324 15325 // Don't add a note for a function delegating directly to itself. 15326 if (TCanonical != Canonical) 15327 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15328 15329 CXXConstructorDecl *C = Target; 15330 while (C->getCanonicalDecl() != Canonical) { 15331 const FunctionDecl *FNTarget = nullptr; 15332 (void)C->getTargetConstructor()->hasBody(FNTarget); 15333 assert(FNTarget && "Ctor cycle through bodiless function"); 15334 15335 C = const_cast<CXXConstructorDecl*>( 15336 cast<CXXConstructorDecl>(FNTarget)); 15337 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15338 } 15339 } 15340 15341 Invalid.insert(Current.begin(), Current.end()); 15342 Current.clear(); 15343 } else { 15344 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15345 } 15346 } 15347 15348 15349 void Sema::CheckDelegatingCtorCycles() { 15350 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15351 15352 for (DelegatingCtorDeclsType::iterator 15353 I = DelegatingCtorDecls.begin(ExternalSource), 15354 E = DelegatingCtorDecls.end(); 15355 I != E; ++I) 15356 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15357 15358 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15359 (*CI)->setInvalidDecl(); 15360 } 15361 15362 namespace { 15363 /// AST visitor that finds references to the 'this' expression. 15364 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15365 Sema &S; 15366 15367 public: 15368 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15369 15370 bool VisitCXXThisExpr(CXXThisExpr *E) { 15371 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15372 << E->isImplicit(); 15373 return false; 15374 } 15375 }; 15376 } 15377 15378 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15379 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15380 if (!TSInfo) 15381 return false; 15382 15383 TypeLoc TL = TSInfo->getTypeLoc(); 15384 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15385 if (!ProtoTL) 15386 return false; 15387 15388 // C++11 [expr.prim.general]p3: 15389 // [The expression this] shall not appear before the optional 15390 // cv-qualifier-seq and it shall not appear within the declaration of a 15391 // static member function (although its type and value category are defined 15392 // within a static member function as they are within a non-static member 15393 // function). [ Note: this is because declaration matching does not occur 15394 // until the complete declarator is known. - end note ] 15395 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15396 FindCXXThisExpr Finder(*this); 15397 15398 // If the return type came after the cv-qualifier-seq, check it now. 15399 if (Proto->hasTrailingReturn() && 15400 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15401 return true; 15402 15403 // Check the exception specification. 15404 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15405 return true; 15406 15407 return checkThisInStaticMemberFunctionAttributes(Method); 15408 } 15409 15410 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15411 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15412 if (!TSInfo) 15413 return false; 15414 15415 TypeLoc TL = TSInfo->getTypeLoc(); 15416 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15417 if (!ProtoTL) 15418 return false; 15419 15420 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15421 FindCXXThisExpr Finder(*this); 15422 15423 switch (Proto->getExceptionSpecType()) { 15424 case EST_Unparsed: 15425 case EST_Uninstantiated: 15426 case EST_Unevaluated: 15427 case EST_BasicNoexcept: 15428 case EST_DynamicNone: 15429 case EST_MSAny: 15430 case EST_None: 15431 break; 15432 15433 case EST_DependentNoexcept: 15434 case EST_NoexceptFalse: 15435 case EST_NoexceptTrue: 15436 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15437 return true; 15438 LLVM_FALLTHROUGH; 15439 15440 case EST_Dynamic: 15441 for (const auto &E : Proto->exceptions()) { 15442 if (!Finder.TraverseType(E)) 15443 return true; 15444 } 15445 break; 15446 } 15447 15448 return false; 15449 } 15450 15451 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15452 FindCXXThisExpr Finder(*this); 15453 15454 // Check attributes. 15455 for (const auto *A : Method->attrs()) { 15456 // FIXME: This should be emitted by tblgen. 15457 Expr *Arg = nullptr; 15458 ArrayRef<Expr *> Args; 15459 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15460 Arg = G->getArg(); 15461 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15462 Arg = G->getArg(); 15463 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15464 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15465 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15466 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15467 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15468 Arg = ETLF->getSuccessValue(); 15469 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15470 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15471 Arg = STLF->getSuccessValue(); 15472 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15473 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15474 Arg = LR->getArg(); 15475 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15476 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15477 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15478 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15479 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15480 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15481 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15482 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15483 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15484 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15485 15486 if (Arg && !Finder.TraverseStmt(Arg)) 15487 return true; 15488 15489 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15490 if (!Finder.TraverseStmt(Args[I])) 15491 return true; 15492 } 15493 } 15494 15495 return false; 15496 } 15497 15498 void Sema::checkExceptionSpecification( 15499 bool IsTopLevel, ExceptionSpecificationType EST, 15500 ArrayRef<ParsedType> DynamicExceptions, 15501 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15502 SmallVectorImpl<QualType> &Exceptions, 15503 FunctionProtoType::ExceptionSpecInfo &ESI) { 15504 Exceptions.clear(); 15505 ESI.Type = EST; 15506 if (EST == EST_Dynamic) { 15507 Exceptions.reserve(DynamicExceptions.size()); 15508 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15509 // FIXME: Preserve type source info. 15510 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15511 15512 if (IsTopLevel) { 15513 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15514 collectUnexpandedParameterPacks(ET, Unexpanded); 15515 if (!Unexpanded.empty()) { 15516 DiagnoseUnexpandedParameterPacks( 15517 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15518 Unexpanded); 15519 continue; 15520 } 15521 } 15522 15523 // Check that the type is valid for an exception spec, and 15524 // drop it if not. 15525 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15526 Exceptions.push_back(ET); 15527 } 15528 ESI.Exceptions = Exceptions; 15529 return; 15530 } 15531 15532 if (isComputedNoexcept(EST)) { 15533 assert((NoexceptExpr->isTypeDependent() || 15534 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15535 Context.BoolTy) && 15536 "Parser should have made sure that the expression is boolean"); 15537 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15538 ESI.Type = EST_BasicNoexcept; 15539 return; 15540 } 15541 15542 ESI.NoexceptExpr = NoexceptExpr; 15543 return; 15544 } 15545 } 15546 15547 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15548 ExceptionSpecificationType EST, 15549 SourceRange SpecificationRange, 15550 ArrayRef<ParsedType> DynamicExceptions, 15551 ArrayRef<SourceRange> DynamicExceptionRanges, 15552 Expr *NoexceptExpr) { 15553 if (!MethodD) 15554 return; 15555 15556 // Dig out the method we're referring to. 15557 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15558 MethodD = FunTmpl->getTemplatedDecl(); 15559 15560 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15561 if (!Method) 15562 return; 15563 15564 // Check the exception specification. 15565 llvm::SmallVector<QualType, 4> Exceptions; 15566 FunctionProtoType::ExceptionSpecInfo ESI; 15567 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15568 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15569 ESI); 15570 15571 // Update the exception specification on the function type. 15572 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15573 15574 if (Method->isStatic()) 15575 checkThisInStaticMemberFunctionExceptionSpec(Method); 15576 15577 if (Method->isVirtual()) { 15578 // Check overrides, which we previously had to delay. 15579 for (const CXXMethodDecl *O : Method->overridden_methods()) 15580 CheckOverridingFunctionExceptionSpec(Method, O); 15581 } 15582 } 15583 15584 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15585 /// 15586 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15587 SourceLocation DeclStart, Declarator &D, 15588 Expr *BitWidth, 15589 InClassInitStyle InitStyle, 15590 AccessSpecifier AS, 15591 const ParsedAttr &MSPropertyAttr) { 15592 IdentifierInfo *II = D.getIdentifier(); 15593 if (!II) { 15594 Diag(DeclStart, diag::err_anonymous_property); 15595 return nullptr; 15596 } 15597 SourceLocation Loc = D.getIdentifierLoc(); 15598 15599 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15600 QualType T = TInfo->getType(); 15601 if (getLangOpts().CPlusPlus) { 15602 CheckExtraCXXDefaultArguments(D); 15603 15604 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15605 UPPC_DataMemberType)) { 15606 D.setInvalidType(); 15607 T = Context.IntTy; 15608 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15609 } 15610 } 15611 15612 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15613 15614 if (D.getDeclSpec().isInlineSpecified()) 15615 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15616 << getLangOpts().CPlusPlus17; 15617 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15618 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15619 diag::err_invalid_thread) 15620 << DeclSpec::getSpecifierName(TSCS); 15621 15622 // Check to see if this name was declared as a member previously 15623 NamedDecl *PrevDecl = nullptr; 15624 LookupResult Previous(*this, II, Loc, LookupMemberName, 15625 ForVisibleRedeclaration); 15626 LookupName(Previous, S); 15627 switch (Previous.getResultKind()) { 15628 case LookupResult::Found: 15629 case LookupResult::FoundUnresolvedValue: 15630 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15631 break; 15632 15633 case LookupResult::FoundOverloaded: 15634 PrevDecl = Previous.getRepresentativeDecl(); 15635 break; 15636 15637 case LookupResult::NotFound: 15638 case LookupResult::NotFoundInCurrentInstantiation: 15639 case LookupResult::Ambiguous: 15640 break; 15641 } 15642 15643 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15644 // Maybe we will complain about the shadowed template parameter. 15645 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15646 // Just pretend that we didn't see the previous declaration. 15647 PrevDecl = nullptr; 15648 } 15649 15650 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15651 PrevDecl = nullptr; 15652 15653 SourceLocation TSSL = D.getBeginLoc(); 15654 MSPropertyDecl *NewPD = 15655 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 15656 MSPropertyAttr.getPropertyDataGetter(), 15657 MSPropertyAttr.getPropertyDataSetter()); 15658 ProcessDeclAttributes(TUScope, NewPD, D); 15659 NewPD->setAccess(AS); 15660 15661 if (NewPD->isInvalidDecl()) 15662 Record->setInvalidDecl(); 15663 15664 if (D.getDeclSpec().isModulePrivateSpecified()) 15665 NewPD->setModulePrivate(); 15666 15667 if (NewPD->isInvalidDecl() && PrevDecl) { 15668 // Don't introduce NewFD into scope; there's already something 15669 // with the same name in the same scope. 15670 } else if (II) { 15671 PushOnScopeChains(NewPD, S); 15672 } else 15673 Record->addDecl(NewPD); 15674 15675 return NewPD; 15676 } 15677