1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for C++ declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/ComparisonCategories.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/STLExtras.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/StringExtras.h" 44 #include <map> 45 #include <set> 46 47 using namespace clang; 48 49 //===----------------------------------------------------------------------===// 50 // CheckDefaultArgumentVisitor 51 //===----------------------------------------------------------------------===// 52 53 namespace { 54 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 55 /// the default argument of a parameter to determine whether it 56 /// contains any ill-formed subexpressions. For example, this will 57 /// diagnose the use of local variables or parameters within the 58 /// default argument expression. 59 class CheckDefaultArgumentVisitor 60 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 61 Expr *DefaultArg; 62 Sema *S; 63 64 public: 65 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 66 : DefaultArg(defarg), S(s) {} 67 68 bool VisitExpr(Expr *Node); 69 bool VisitDeclRefExpr(DeclRefExpr *DRE); 70 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 71 bool VisitLambdaExpr(LambdaExpr *Lambda); 72 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 73 }; 74 75 /// VisitExpr - Visit all of the children of this expression. 76 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 77 bool IsInvalid = false; 78 for (Stmt *SubStmt : Node->children()) 79 IsInvalid |= Visit(SubStmt); 80 return IsInvalid; 81 } 82 83 /// VisitDeclRefExpr - Visit a reference to a declaration, to 84 /// determine whether this declaration can be used in the default 85 /// argument expression. 86 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 87 NamedDecl *Decl = DRE->getDecl(); 88 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 89 // C++ [dcl.fct.default]p9 90 // Default arguments are evaluated each time the function is 91 // called. The order of evaluation of function arguments is 92 // unspecified. Consequently, parameters of a function shall not 93 // be used in default argument expressions, even if they are not 94 // evaluated. Parameters of a function declared before a default 95 // argument expression are in scope and can hide namespace and 96 // class member names. 97 return S->Diag(DRE->getBeginLoc(), 98 diag::err_param_default_argument_references_param) 99 << Param->getDeclName() << DefaultArg->getSourceRange(); 100 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 101 // C++ [dcl.fct.default]p7 102 // Local variables shall not be used in default argument 103 // expressions. 104 if (VDecl->isLocalVarDecl()) 105 return S->Diag(DRE->getBeginLoc(), 106 diag::err_param_default_argument_references_local) 107 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 108 } 109 110 return false; 111 } 112 113 /// VisitCXXThisExpr - Visit a C++ "this" expression. 114 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 115 // C++ [dcl.fct.default]p8: 116 // The keyword this shall not be used in a default argument of a 117 // member function. 118 return S->Diag(ThisE->getBeginLoc(), 119 diag::err_param_default_argument_references_this) 120 << ThisE->getSourceRange(); 121 } 122 123 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 124 bool Invalid = false; 125 for (PseudoObjectExpr::semantics_iterator 126 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 127 Expr *E = *i; 128 129 // Look through bindings. 130 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 131 E = OVE->getSourceExpr(); 132 assert(E && "pseudo-object binding without source expression?"); 133 } 134 135 Invalid |= Visit(E); 136 } 137 return Invalid; 138 } 139 140 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 141 // C++11 [expr.lambda.prim]p13: 142 // A lambda-expression appearing in a default argument shall not 143 // implicitly or explicitly capture any entity. 144 if (Lambda->capture_begin() == Lambda->capture_end()) 145 return false; 146 147 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 148 } 149 } 150 151 void 152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 153 const CXXMethodDecl *Method) { 154 // If we have an MSAny spec already, don't bother. 155 if (!Method || ComputedEST == EST_MSAny) 156 return; 157 158 const FunctionProtoType *Proto 159 = Method->getType()->getAs<FunctionProtoType>(); 160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 161 if (!Proto) 162 return; 163 164 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 165 166 // If we have a throw-all spec at this point, ignore the function. 167 if (ComputedEST == EST_None) 168 return; 169 170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 171 EST = EST_BasicNoexcept; 172 173 switch (EST) { 174 case EST_Unparsed: 175 case EST_Uninstantiated: 176 case EST_Unevaluated: 177 llvm_unreachable("should not see unresolved exception specs here"); 178 179 // If this function can throw any exceptions, make a note of that. 180 case EST_MSAny: 181 case EST_None: 182 // FIXME: Whichever we see last of MSAny and None determines our result. 183 // We should make a consistent, order-independent choice here. 184 ClearExceptions(); 185 ComputedEST = EST; 186 return; 187 case EST_NoexceptFalse: 188 ClearExceptions(); 189 ComputedEST = EST_None; 190 return; 191 // FIXME: If the call to this decl is using any of its default arguments, we 192 // need to search them for potentially-throwing calls. 193 // If this function has a basic noexcept, it doesn't affect the outcome. 194 case EST_BasicNoexcept: 195 case EST_NoexceptTrue: 196 return; 197 // If we're still at noexcept(true) and there's a throw() callee, 198 // change to that specification. 199 case EST_DynamicNone: 200 if (ComputedEST == EST_BasicNoexcept) 201 ComputedEST = EST_DynamicNone; 202 return; 203 case EST_DependentNoexcept: 204 llvm_unreachable( 205 "should not generate implicit declarations for dependent cases"); 206 case EST_Dynamic: 207 break; 208 } 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // C++11 [dcl.fct.default]p3 321 // A default argument expression [...] shall not be specified for a 322 // parameter pack. 323 if (Param->isParameterPack()) { 324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 325 << DefaultArg->getSourceRange(); 326 return; 327 } 328 329 // Check that the default argument is well-formed 330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 331 if (DefaultArgChecker.Visit(DefaultArg)) { 332 Param->setInvalidDecl(); 333 return; 334 } 335 336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 337 } 338 339 /// ActOnParamUnparsedDefaultArgument - We've seen a default 340 /// argument for a function parameter, but we can't parse it yet 341 /// because we're inside a class definition. Note that this default 342 /// argument will be parsed later. 343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 344 SourceLocation EqualLoc, 345 SourceLocation ArgLoc) { 346 if (!param) 347 return; 348 349 ParmVarDecl *Param = cast<ParmVarDecl>(param); 350 Param->setUnparsedDefaultArg(); 351 UnparsedDefaultArgLocs[Param] = ArgLoc; 352 } 353 354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 355 /// the default argument for the parameter param failed. 356 void Sema::ActOnParamDefaultArgumentError(Decl *param, 357 SourceLocation EqualLoc) { 358 if (!param) 359 return; 360 361 ParmVarDecl *Param = cast<ParmVarDecl>(param); 362 Param->setInvalidDecl(); 363 UnparsedDefaultArgLocs.erase(Param); 364 Param->setDefaultArg(new(Context) 365 OpaqueValueExpr(EqualLoc, 366 Param->getType().getNonReferenceType(), 367 VK_RValue)); 368 } 369 370 /// CheckExtraCXXDefaultArguments - Check for any extra default 371 /// arguments in the declarator, which is not a function declaration 372 /// or definition and therefore is not permitted to have default 373 /// arguments. This routine should be invoked for every declarator 374 /// that is not a function declaration or definition. 375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 376 // C++ [dcl.fct.default]p3 377 // A default argument expression shall be specified only in the 378 // parameter-declaration-clause of a function declaration or in a 379 // template-parameter (14.1). It shall not be specified for a 380 // parameter pack. If it is specified in a 381 // parameter-declaration-clause, it shall not occur within a 382 // declarator or abstract-declarator of a parameter-declaration. 383 bool MightBeFunction = D.isFunctionDeclarationContext(); 384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 385 DeclaratorChunk &chunk = D.getTypeObject(i); 386 if (chunk.Kind == DeclaratorChunk::Function) { 387 if (MightBeFunction) { 388 // This is a function declaration. It can have default arguments, but 389 // keep looking in case its return type is a function type with default 390 // arguments. 391 MightBeFunction = false; 392 continue; 393 } 394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 395 ++argIdx) { 396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 397 if (Param->hasUnparsedDefaultArg()) { 398 std::unique_ptr<CachedTokens> Toks = 399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 400 SourceRange SR; 401 if (Toks->size() > 1) 402 SR = SourceRange((*Toks)[1].getLocation(), 403 Toks->back().getLocation()); 404 else 405 SR = UnparsedDefaultArgLocs[Param]; 406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 407 << SR; 408 } else if (Param->getDefaultArg()) { 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << Param->getDefaultArg()->getSourceRange(); 411 Param->setDefaultArg(nullptr); 412 } 413 } 414 } else if (chunk.Kind != DeclaratorChunk::Paren) { 415 MightBeFunction = false; 416 } 417 } 418 } 419 420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 423 if (!PVD->hasDefaultArg()) 424 return false; 425 if (!PVD->hasInheritedDefaultArg()) 426 return true; 427 } 428 return false; 429 } 430 431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 432 /// function, once we already know that they have the same 433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 434 /// error, false otherwise. 435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 436 Scope *S) { 437 bool Invalid = false; 438 439 // The declaration context corresponding to the scope is the semantic 440 // parent, unless this is a local function declaration, in which case 441 // it is that surrounding function. 442 DeclContext *ScopeDC = New->isLocalExternDecl() 443 ? New->getLexicalDeclContext() 444 : New->getDeclContext(); 445 446 // Find the previous declaration for the purpose of default arguments. 447 FunctionDecl *PrevForDefaultArgs = Old; 448 for (/**/; PrevForDefaultArgs; 449 // Don't bother looking back past the latest decl if this is a local 450 // extern declaration; nothing else could work. 451 PrevForDefaultArgs = New->isLocalExternDecl() 452 ? nullptr 453 : PrevForDefaultArgs->getPreviousDecl()) { 454 // Ignore hidden declarations. 455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 456 continue; 457 458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 459 !New->isCXXClassMember()) { 460 // Ignore default arguments of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 continue; 464 } 465 466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 467 // If only one of these is a local function declaration, then they are 468 // declared in different scopes, even though isDeclInScope may think 469 // they're in the same scope. (If both are local, the scope check is 470 // sufficient, and if neither is local, then they are in the same scope.) 471 continue; 472 } 473 474 // We found the right previous declaration. 475 break; 476 } 477 478 // C++ [dcl.fct.default]p4: 479 // For non-template functions, default arguments can be added in 480 // later declarations of a function in the same 481 // scope. Declarations in different scopes have completely 482 // distinct sets of default arguments. That is, declarations in 483 // inner scopes do not acquire default arguments from 484 // declarations in outer scopes, and vice versa. In a given 485 // function declaration, all parameters subsequent to a 486 // parameter with a default argument shall have default 487 // arguments supplied in this or previous declarations. A 488 // default argument shall not be redefined by a later 489 // declaration (not even to the same value). 490 // 491 // C++ [dcl.fct.default]p6: 492 // Except for member functions of class templates, the default arguments 493 // in a member function definition that appears outside of the class 494 // definition are added to the set of default arguments provided by the 495 // member function declaration in the class definition. 496 for (unsigned p = 0, NumParams = PrevForDefaultArgs 497 ? PrevForDefaultArgs->getNumParams() 498 : 0; 499 p < NumParams; ++p) { 500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 501 ParmVarDecl *NewParam = New->getParamDecl(p); 502 503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 504 bool NewParamHasDfl = NewParam->hasDefaultArg(); 505 506 if (OldParamHasDfl && NewParamHasDfl) { 507 unsigned DiagDefaultParamID = 508 diag::err_param_default_argument_redefinition; 509 510 // MSVC accepts that default parameters be redefined for member functions 511 // of template class. The new default parameter's value is ignored. 512 Invalid = true; 513 if (getLangOpts().MicrosoftExt) { 514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 515 if (MD && MD->getParent()->getDescribedClassTemplate()) { 516 // Merge the old default argument into the new parameter. 517 NewParam->setHasInheritedDefaultArg(); 518 if (OldParam->hasUninstantiatedDefaultArg()) 519 NewParam->setUninstantiatedDefaultArg( 520 OldParam->getUninstantiatedDefaultArg()); 521 else 522 NewParam->setDefaultArg(OldParam->getInit()); 523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 524 Invalid = false; 525 } 526 } 527 528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 529 // hint here. Alternatively, we could walk the type-source information 530 // for NewParam to find the last source location in the type... but it 531 // isn't worth the effort right now. This is the kind of test case that 532 // is hard to get right: 533 // int f(int); 534 // void g(int (*fp)(int) = f); 535 // void g(int (*fp)(int) = &f); 536 Diag(NewParam->getLocation(), DiagDefaultParamID) 537 << NewParam->getDefaultArgRange(); 538 539 // Look for the function declaration where the default argument was 540 // actually written, which may be a declaration prior to Old. 541 for (auto Older = PrevForDefaultArgs; 542 OldParam->hasInheritedDefaultArg(); /**/) { 543 Older = Older->getPreviousDecl(); 544 OldParam = Older->getParamDecl(p); 545 } 546 547 Diag(OldParam->getLocation(), diag::note_previous_definition) 548 << OldParam->getDefaultArgRange(); 549 } else if (OldParamHasDfl) { 550 // Merge the old default argument into the new parameter unless the new 551 // function is a friend declaration in a template class. In the latter 552 // case the default arguments will be inherited when the friend 553 // declaration will be instantiated. 554 if (New->getFriendObjectKind() == Decl::FOK_None || 555 !New->getLexicalDeclContext()->isDependentContext()) { 556 // It's important to use getInit() here; getDefaultArg() 557 // strips off any top-level ExprWithCleanups. 558 NewParam->setHasInheritedDefaultArg(); 559 if (OldParam->hasUnparsedDefaultArg()) 560 NewParam->setUnparsedDefaultArg(); 561 else if (OldParam->hasUninstantiatedDefaultArg()) 562 NewParam->setUninstantiatedDefaultArg( 563 OldParam->getUninstantiatedDefaultArg()); 564 else 565 NewParam->setDefaultArg(OldParam->getInit()); 566 } 567 } else if (NewParamHasDfl) { 568 if (New->getDescribedFunctionTemplate()) { 569 // Paragraph 4, quoted above, only applies to non-template functions. 570 Diag(NewParam->getLocation(), 571 diag::err_param_default_argument_template_redecl) 572 << NewParam->getDefaultArgRange(); 573 Diag(PrevForDefaultArgs->getLocation(), 574 diag::note_template_prev_declaration) 575 << false; 576 } else if (New->getTemplateSpecializationKind() 577 != TSK_ImplicitInstantiation && 578 New->getTemplateSpecializationKind() != TSK_Undeclared) { 579 // C++ [temp.expr.spec]p21: 580 // Default function arguments shall not be specified in a declaration 581 // or a definition for one of the following explicit specializations: 582 // - the explicit specialization of a function template; 583 // - the explicit specialization of a member function template; 584 // - the explicit specialization of a member function of a class 585 // template where the class template specialization to which the 586 // member function specialization belongs is implicitly 587 // instantiated. 588 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 589 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 590 << New->getDeclName() 591 << NewParam->getDefaultArgRange(); 592 } else if (New->getDeclContext()->isDependentContext()) { 593 // C++ [dcl.fct.default]p6 (DR217): 594 // Default arguments for a member function of a class template shall 595 // be specified on the initial declaration of the member function 596 // within the class template. 597 // 598 // Reading the tea leaves a bit in DR217 and its reference to DR205 599 // leads me to the conclusion that one cannot add default function 600 // arguments for an out-of-line definition of a member function of a 601 // dependent type. 602 int WhichKind = 2; 603 if (CXXRecordDecl *Record 604 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 605 if (Record->getDescribedClassTemplate()) 606 WhichKind = 0; 607 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 608 WhichKind = 1; 609 else 610 WhichKind = 2; 611 } 612 613 Diag(NewParam->getLocation(), 614 diag::err_param_default_argument_member_template_redecl) 615 << WhichKind 616 << NewParam->getDefaultArgRange(); 617 } 618 } 619 } 620 621 // DR1344: If a default argument is added outside a class definition and that 622 // default argument makes the function a special member function, the program 623 // is ill-formed. This can only happen for constructors. 624 if (isa<CXXConstructorDecl>(New) && 625 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 626 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 627 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 628 if (NewSM != OldSM) { 629 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 630 assert(NewParam->hasDefaultArg()); 631 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 632 << NewParam->getDefaultArgRange() << NewSM; 633 Diag(Old->getLocation(), diag::note_previous_declaration); 634 } 635 } 636 637 const FunctionDecl *Def; 638 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 639 // template has a constexpr specifier then all its declarations shall 640 // contain the constexpr specifier. 641 if (New->isConstexpr() != Old->isConstexpr()) { 642 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 643 << New << New->isConstexpr(); 644 Diag(Old->getLocation(), diag::note_previous_declaration); 645 Invalid = true; 646 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 647 Old->isDefined(Def) && 648 // If a friend function is inlined but does not have 'inline' 649 // specifier, it is a definition. Do not report attribute conflict 650 // in this case, redefinition will be diagnosed later. 651 (New->isInlineSpecified() || 652 New->getFriendObjectKind() == Decl::FOK_None)) { 653 // C++11 [dcl.fcn.spec]p4: 654 // If the definition of a function appears in a translation unit before its 655 // first declaration as inline, the program is ill-formed. 656 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 657 Diag(Def->getLocation(), diag::note_previous_definition); 658 Invalid = true; 659 } 660 661 // FIXME: It's not clear what should happen if multiple declarations of a 662 // deduction guide have different explicitness. For now at least we simply 663 // reject any case where the explicitness changes. 664 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New); 665 if (NewGuide && NewGuide->isExplicitSpecified() != 666 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) { 667 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch) 668 << NewGuide->isExplicitSpecified(); 669 Diag(Old->getLocation(), diag::note_previous_declaration); 670 } 671 672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 673 // argument expression, that declaration shall be a definition and shall be 674 // the only declaration of the function or function template in the 675 // translation unit. 676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 677 functionDeclHasDefaultArgument(Old)) { 678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 679 Diag(Old->getLocation(), diag::note_previous_declaration); 680 Invalid = true; 681 } 682 683 return Invalid; 684 } 685 686 NamedDecl * 687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 688 MultiTemplateParamsArg TemplateParamLists) { 689 assert(D.isDecompositionDeclarator()); 690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 691 692 // The syntax only allows a decomposition declarator as a simple-declaration, 693 // a for-range-declaration, or a condition in Clang, but we parse it in more 694 // cases than that. 695 if (!D.mayHaveDecompositionDeclarator()) { 696 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 697 << Decomp.getSourceRange(); 698 return nullptr; 699 } 700 701 if (!TemplateParamLists.empty()) { 702 // FIXME: There's no rule against this, but there are also no rules that 703 // would actually make it usable, so we reject it for now. 704 Diag(TemplateParamLists.front()->getTemplateLoc(), 705 diag::err_decomp_decl_template); 706 return nullptr; 707 } 708 709 Diag(Decomp.getLSquareLoc(), 710 !getLangOpts().CPlusPlus17 711 ? diag::ext_decomp_decl 712 : D.getContext() == DeclaratorContext::ConditionContext 713 ? diag::ext_decomp_decl_cond 714 : diag::warn_cxx14_compat_decomp_decl) 715 << Decomp.getSourceRange(); 716 717 // The semantic context is always just the current context. 718 DeclContext *const DC = CurContext; 719 720 // C++1z [dcl.dcl]/8: 721 // The decl-specifier-seq shall contain only the type-specifier auto 722 // and cv-qualifiers. 723 auto &DS = D.getDeclSpec(); 724 { 725 SmallVector<StringRef, 8> BadSpecifiers; 726 SmallVector<SourceLocation, 8> BadSpecifierLocs; 727 if (auto SCS = DS.getStorageClassSpec()) { 728 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 729 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 730 } 731 if (auto TSCS = DS.getThreadStorageClassSpec()) { 732 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 733 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 734 } 735 if (DS.isConstexprSpecified()) { 736 BadSpecifiers.push_back("constexpr"); 737 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 738 } 739 if (DS.isInlineSpecified()) { 740 BadSpecifiers.push_back("inline"); 741 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 742 } 743 if (!BadSpecifiers.empty()) { 744 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 745 Err << (int)BadSpecifiers.size() 746 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 747 // Don't add FixItHints to remove the specifiers; we do still respect 748 // them when building the underlying variable. 749 for (auto Loc : BadSpecifierLocs) 750 Err << SourceRange(Loc, Loc); 751 } 752 // We can't recover from it being declared as a typedef. 753 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 754 return nullptr; 755 } 756 757 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 758 QualType R = TInfo->getType(); 759 760 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 761 UPPC_DeclarationType)) 762 D.setInvalidType(); 763 764 // The syntax only allows a single ref-qualifier prior to the decomposition 765 // declarator. No other declarator chunks are permitted. Also check the type 766 // specifier here. 767 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 768 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 769 (D.getNumTypeObjects() == 1 && 770 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 771 Diag(Decomp.getLSquareLoc(), 772 (D.hasGroupingParens() || 773 (D.getNumTypeObjects() && 774 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 775 ? diag::err_decomp_decl_parens 776 : diag::err_decomp_decl_type) 777 << R; 778 779 // In most cases, there's no actual problem with an explicitly-specified 780 // type, but a function type won't work here, and ActOnVariableDeclarator 781 // shouldn't be called for such a type. 782 if (R->isFunctionType()) 783 D.setInvalidType(); 784 } 785 786 // Build the BindingDecls. 787 SmallVector<BindingDecl*, 8> Bindings; 788 789 // Build the BindingDecls. 790 for (auto &B : D.getDecompositionDeclarator().bindings()) { 791 // Check for name conflicts. 792 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 793 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 794 ForVisibleRedeclaration); 795 LookupName(Previous, S, 796 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 797 798 // It's not permitted to shadow a template parameter name. 799 if (Previous.isSingleResult() && 800 Previous.getFoundDecl()->isTemplateParameter()) { 801 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 802 Previous.getFoundDecl()); 803 Previous.clear(); 804 } 805 806 bool ConsiderLinkage = DC->isFunctionOrMethod() && 807 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 808 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 809 /*AllowInlineNamespace*/false); 810 if (!Previous.empty()) { 811 auto *Old = Previous.getRepresentativeDecl(); 812 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 813 Diag(Old->getLocation(), diag::note_previous_definition); 814 } 815 816 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 817 PushOnScopeChains(BD, S, true); 818 Bindings.push_back(BD); 819 ParsingInitForAutoVars.insert(BD); 820 } 821 822 // There are no prior lookup results for the variable itself, because it 823 // is unnamed. 824 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 825 Decomp.getLSquareLoc()); 826 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 827 ForVisibleRedeclaration); 828 829 // Build the variable that holds the non-decomposed object. 830 bool AddToScope = true; 831 NamedDecl *New = 832 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 833 MultiTemplateParamsArg(), AddToScope, Bindings); 834 if (AddToScope) { 835 S->AddDecl(New); 836 CurContext->addHiddenDecl(New); 837 } 838 839 if (isInOpenMPDeclareTargetContext()) 840 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 841 842 return New; 843 } 844 845 static bool checkSimpleDecomposition( 846 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 847 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 848 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 849 if ((int64_t)Bindings.size() != NumElems) { 850 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 851 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 852 << (NumElems < Bindings.size()); 853 return true; 854 } 855 856 unsigned I = 0; 857 for (auto *B : Bindings) { 858 SourceLocation Loc = B->getLocation(); 859 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 860 if (E.isInvalid()) 861 return true; 862 E = GetInit(Loc, E.get(), I++); 863 if (E.isInvalid()) 864 return true; 865 B->setBinding(ElemType, E.get()); 866 } 867 868 return false; 869 } 870 871 static bool checkArrayLikeDecomposition(Sema &S, 872 ArrayRef<BindingDecl *> Bindings, 873 ValueDecl *Src, QualType DecompType, 874 const llvm::APSInt &NumElems, 875 QualType ElemType) { 876 return checkSimpleDecomposition( 877 S, Bindings, Src, DecompType, NumElems, ElemType, 878 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 879 ExprResult E = S.ActOnIntegerConstant(Loc, I); 880 if (E.isInvalid()) 881 return ExprError(); 882 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 883 }); 884 } 885 886 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 887 ValueDecl *Src, QualType DecompType, 888 const ConstantArrayType *CAT) { 889 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 890 llvm::APSInt(CAT->getSize()), 891 CAT->getElementType()); 892 } 893 894 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 895 ValueDecl *Src, QualType DecompType, 896 const VectorType *VT) { 897 return checkArrayLikeDecomposition( 898 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 899 S.Context.getQualifiedType(VT->getElementType(), 900 DecompType.getQualifiers())); 901 } 902 903 static bool checkComplexDecomposition(Sema &S, 904 ArrayRef<BindingDecl *> Bindings, 905 ValueDecl *Src, QualType DecompType, 906 const ComplexType *CT) { 907 return checkSimpleDecomposition( 908 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 909 S.Context.getQualifiedType(CT->getElementType(), 910 DecompType.getQualifiers()), 911 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 912 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 913 }); 914 } 915 916 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 917 TemplateArgumentListInfo &Args) { 918 SmallString<128> SS; 919 llvm::raw_svector_ostream OS(SS); 920 bool First = true; 921 for (auto &Arg : Args.arguments()) { 922 if (!First) 923 OS << ", "; 924 Arg.getArgument().print(PrintingPolicy, OS); 925 First = false; 926 } 927 return OS.str(); 928 } 929 930 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 931 SourceLocation Loc, StringRef Trait, 932 TemplateArgumentListInfo &Args, 933 unsigned DiagID) { 934 auto DiagnoseMissing = [&] { 935 if (DiagID) 936 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 937 Args); 938 return true; 939 }; 940 941 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 942 NamespaceDecl *Std = S.getStdNamespace(); 943 if (!Std) 944 return DiagnoseMissing(); 945 946 // Look up the trait itself, within namespace std. We can diagnose various 947 // problems with this lookup even if we've been asked to not diagnose a 948 // missing specialization, because this can only fail if the user has been 949 // declaring their own names in namespace std or we don't support the 950 // standard library implementation in use. 951 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 952 Loc, Sema::LookupOrdinaryName); 953 if (!S.LookupQualifiedName(Result, Std)) 954 return DiagnoseMissing(); 955 if (Result.isAmbiguous()) 956 return true; 957 958 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 959 if (!TraitTD) { 960 Result.suppressDiagnostics(); 961 NamedDecl *Found = *Result.begin(); 962 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 963 S.Diag(Found->getLocation(), diag::note_declared_at); 964 return true; 965 } 966 967 // Build the template-id. 968 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 969 if (TraitTy.isNull()) 970 return true; 971 if (!S.isCompleteType(Loc, TraitTy)) { 972 if (DiagID) 973 S.RequireCompleteType( 974 Loc, TraitTy, DiagID, 975 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 976 return true; 977 } 978 979 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 980 assert(RD && "specialization of class template is not a class?"); 981 982 // Look up the member of the trait type. 983 S.LookupQualifiedName(TraitMemberLookup, RD); 984 return TraitMemberLookup.isAmbiguous(); 985 } 986 987 static TemplateArgumentLoc 988 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 989 uint64_t I) { 990 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 991 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 992 } 993 994 static TemplateArgumentLoc 995 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 996 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 997 } 998 999 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1000 1001 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1002 llvm::APSInt &Size) { 1003 EnterExpressionEvaluationContext ContextRAII( 1004 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1005 1006 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1007 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1008 1009 // Form template argument list for tuple_size<T>. 1010 TemplateArgumentListInfo Args(Loc, Loc); 1011 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1012 1013 // If there's no tuple_size specialization, it's not tuple-like. 1014 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1015 return IsTupleLike::NotTupleLike; 1016 1017 // If we get this far, we've committed to the tuple interpretation, but 1018 // we can still fail if there actually isn't a usable ::value. 1019 1020 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1021 LookupResult &R; 1022 TemplateArgumentListInfo &Args; 1023 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1024 : R(R), Args(Args) {} 1025 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1026 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1027 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1028 } 1029 } Diagnoser(R, Args); 1030 1031 if (R.empty()) { 1032 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1033 return IsTupleLike::Error; 1034 } 1035 1036 ExprResult E = 1037 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1038 if (E.isInvalid()) 1039 return IsTupleLike::Error; 1040 1041 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1042 if (E.isInvalid()) 1043 return IsTupleLike::Error; 1044 1045 return IsTupleLike::TupleLike; 1046 } 1047 1048 /// \return std::tuple_element<I, T>::type. 1049 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1050 unsigned I, QualType T) { 1051 // Form template argument list for tuple_element<I, T>. 1052 TemplateArgumentListInfo Args(Loc, Loc); 1053 Args.addArgument( 1054 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1055 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1056 1057 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1058 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1059 if (lookupStdTypeTraitMember( 1060 S, R, Loc, "tuple_element", Args, 1061 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1062 return QualType(); 1063 1064 auto *TD = R.getAsSingle<TypeDecl>(); 1065 if (!TD) { 1066 R.suppressDiagnostics(); 1067 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1068 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1069 if (!R.empty()) 1070 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1071 return QualType(); 1072 } 1073 1074 return S.Context.getTypeDeclType(TD); 1075 } 1076 1077 namespace { 1078 struct BindingDiagnosticTrap { 1079 Sema &S; 1080 DiagnosticErrorTrap Trap; 1081 BindingDecl *BD; 1082 1083 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1084 : S(S), Trap(S.Diags), BD(BD) {} 1085 ~BindingDiagnosticTrap() { 1086 if (Trap.hasErrorOccurred()) 1087 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1088 } 1089 }; 1090 } 1091 1092 static bool checkTupleLikeDecomposition(Sema &S, 1093 ArrayRef<BindingDecl *> Bindings, 1094 VarDecl *Src, QualType DecompType, 1095 const llvm::APSInt &TupleSize) { 1096 if ((int64_t)Bindings.size() != TupleSize) { 1097 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1098 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1099 << (TupleSize < Bindings.size()); 1100 return true; 1101 } 1102 1103 if (Bindings.empty()) 1104 return false; 1105 1106 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1107 1108 // [dcl.decomp]p3: 1109 // The unqualified-id get is looked up in the scope of E by class member 1110 // access lookup ... 1111 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1112 bool UseMemberGet = false; 1113 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1114 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1115 S.LookupQualifiedName(MemberGet, RD); 1116 if (MemberGet.isAmbiguous()) 1117 return true; 1118 // ... and if that finds at least one declaration that is a function 1119 // template whose first template parameter is a non-type parameter ... 1120 for (NamedDecl *D : MemberGet) { 1121 if (FunctionTemplateDecl *FTD = 1122 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1123 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1124 if (TPL->size() != 0 && 1125 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1126 // ... the initializer is e.get<i>(). 1127 UseMemberGet = true; 1128 break; 1129 } 1130 } 1131 } 1132 S.FilterAcceptableTemplateNames(MemberGet); 1133 } 1134 1135 unsigned I = 0; 1136 for (auto *B : Bindings) { 1137 BindingDiagnosticTrap Trap(S, B); 1138 SourceLocation Loc = B->getLocation(); 1139 1140 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1141 if (E.isInvalid()) 1142 return true; 1143 1144 // e is an lvalue if the type of the entity is an lvalue reference and 1145 // an xvalue otherwise 1146 if (!Src->getType()->isLValueReferenceType()) 1147 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1148 E.get(), nullptr, VK_XValue); 1149 1150 TemplateArgumentListInfo Args(Loc, Loc); 1151 Args.addArgument( 1152 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1153 1154 if (UseMemberGet) { 1155 // if [lookup of member get] finds at least one declaration, the 1156 // initializer is e.get<i-1>(). 1157 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1158 CXXScopeSpec(), SourceLocation(), nullptr, 1159 MemberGet, &Args, nullptr); 1160 if (E.isInvalid()) 1161 return true; 1162 1163 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1164 } else { 1165 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1166 // in the associated namespaces. 1167 Expr *Get = UnresolvedLookupExpr::Create( 1168 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1169 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1170 UnresolvedSetIterator(), UnresolvedSetIterator()); 1171 1172 Expr *Arg = E.get(); 1173 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1174 } 1175 if (E.isInvalid()) 1176 return true; 1177 Expr *Init = E.get(); 1178 1179 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1180 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1181 if (T.isNull()) 1182 return true; 1183 1184 // each vi is a variable of type "reference to T" initialized with the 1185 // initializer, where the reference is an lvalue reference if the 1186 // initializer is an lvalue and an rvalue reference otherwise 1187 QualType RefType = 1188 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1189 if (RefType.isNull()) 1190 return true; 1191 auto *RefVD = VarDecl::Create( 1192 S.Context, Src->getDeclContext(), Loc, Loc, 1193 B->getDeclName().getAsIdentifierInfo(), RefType, 1194 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1195 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1196 RefVD->setTSCSpec(Src->getTSCSpec()); 1197 RefVD->setImplicit(); 1198 if (Src->isInlineSpecified()) 1199 RefVD->setInlineSpecified(); 1200 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1201 1202 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1203 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1204 InitializationSequence Seq(S, Entity, Kind, Init); 1205 E = Seq.Perform(S, Entity, Kind, Init); 1206 if (E.isInvalid()) 1207 return true; 1208 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1209 if (E.isInvalid()) 1210 return true; 1211 RefVD->setInit(E.get()); 1212 RefVD->checkInitIsICE(); 1213 1214 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1215 DeclarationNameInfo(B->getDeclName(), Loc), 1216 RefVD); 1217 if (E.isInvalid()) 1218 return true; 1219 1220 B->setBinding(T, E.get()); 1221 I++; 1222 } 1223 1224 return false; 1225 } 1226 1227 /// Find the base class to decompose in a built-in decomposition of a class type. 1228 /// This base class search is, unfortunately, not quite like any other that we 1229 /// perform anywhere else in C++. 1230 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1231 const CXXRecordDecl *RD, 1232 CXXCastPath &BasePath) { 1233 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1234 CXXBasePath &Path) { 1235 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1236 }; 1237 1238 const CXXRecordDecl *ClassWithFields = nullptr; 1239 AccessSpecifier AS = AS_public; 1240 if (RD->hasDirectFields()) 1241 // [dcl.decomp]p4: 1242 // Otherwise, all of E's non-static data members shall be public direct 1243 // members of E ... 1244 ClassWithFields = RD; 1245 else { 1246 // ... or of ... 1247 CXXBasePaths Paths; 1248 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1249 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1250 // If no classes have fields, just decompose RD itself. (This will work 1251 // if and only if zero bindings were provided.) 1252 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1253 } 1254 1255 CXXBasePath *BestPath = nullptr; 1256 for (auto &P : Paths) { 1257 if (!BestPath) 1258 BestPath = &P; 1259 else if (!S.Context.hasSameType(P.back().Base->getType(), 1260 BestPath->back().Base->getType())) { 1261 // ... the same ... 1262 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1263 << false << RD << BestPath->back().Base->getType() 1264 << P.back().Base->getType(); 1265 return DeclAccessPair(); 1266 } else if (P.Access < BestPath->Access) { 1267 BestPath = &P; 1268 } 1269 } 1270 1271 // ... unambiguous ... 1272 QualType BaseType = BestPath->back().Base->getType(); 1273 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1274 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1275 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1276 return DeclAccessPair(); 1277 } 1278 1279 // ... [accessible, implied by other rules] base class of E. 1280 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1281 *BestPath, diag::err_decomp_decl_inaccessible_base); 1282 AS = BestPath->Access; 1283 1284 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1285 S.BuildBasePathArray(Paths, BasePath); 1286 } 1287 1288 // The above search did not check whether the selected class itself has base 1289 // classes with fields, so check that now. 1290 CXXBasePaths Paths; 1291 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1292 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1293 << (ClassWithFields == RD) << RD << ClassWithFields 1294 << Paths.front().back().Base->getType(); 1295 return DeclAccessPair(); 1296 } 1297 1298 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1299 } 1300 1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1302 ValueDecl *Src, QualType DecompType, 1303 const CXXRecordDecl *OrigRD) { 1304 CXXCastPath BasePath; 1305 DeclAccessPair BasePair = 1306 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1307 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1308 if (!RD) 1309 return true; 1310 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1311 DecompType.getQualifiers()); 1312 1313 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1314 unsigned NumFields = 1315 std::count_if(RD->field_begin(), RD->field_end(), 1316 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1317 assert(Bindings.size() != NumFields); 1318 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1319 << DecompType << (unsigned)Bindings.size() << NumFields 1320 << (NumFields < Bindings.size()); 1321 return true; 1322 }; 1323 1324 // all of E's non-static data members shall be [...] well-formed 1325 // when named as e.name in the context of the structured binding, 1326 // E shall not have an anonymous union member, ... 1327 unsigned I = 0; 1328 for (auto *FD : RD->fields()) { 1329 if (FD->isUnnamedBitfield()) 1330 continue; 1331 1332 if (FD->isAnonymousStructOrUnion()) { 1333 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1334 << DecompType << FD->getType()->isUnionType(); 1335 S.Diag(FD->getLocation(), diag::note_declared_at); 1336 return true; 1337 } 1338 1339 // We have a real field to bind. 1340 if (I >= Bindings.size()) 1341 return DiagnoseBadNumberOfBindings(); 1342 auto *B = Bindings[I++]; 1343 SourceLocation Loc = B->getLocation(); 1344 1345 // The field must be accessible in the context of the structured binding. 1346 // We already checked that the base class is accessible. 1347 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1348 // const_cast here. 1349 S.CheckStructuredBindingMemberAccess( 1350 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1351 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1352 BasePair.getAccess(), FD->getAccess()))); 1353 1354 // Initialize the binding to Src.FD. 1355 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1356 if (E.isInvalid()) 1357 return true; 1358 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1359 VK_LValue, &BasePath); 1360 if (E.isInvalid()) 1361 return true; 1362 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1363 CXXScopeSpec(), FD, 1364 DeclAccessPair::make(FD, FD->getAccess()), 1365 DeclarationNameInfo(FD->getDeclName(), Loc)); 1366 if (E.isInvalid()) 1367 return true; 1368 1369 // If the type of the member is T, the referenced type is cv T, where cv is 1370 // the cv-qualification of the decomposition expression. 1371 // 1372 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1373 // 'const' to the type of the field. 1374 Qualifiers Q = DecompType.getQualifiers(); 1375 if (FD->isMutable()) 1376 Q.removeConst(); 1377 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1378 } 1379 1380 if (I != Bindings.size()) 1381 return DiagnoseBadNumberOfBindings(); 1382 1383 return false; 1384 } 1385 1386 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1387 QualType DecompType = DD->getType(); 1388 1389 // If the type of the decomposition is dependent, then so is the type of 1390 // each binding. 1391 if (DecompType->isDependentType()) { 1392 for (auto *B : DD->bindings()) 1393 B->setType(Context.DependentTy); 1394 return; 1395 } 1396 1397 DecompType = DecompType.getNonReferenceType(); 1398 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1399 1400 // C++1z [dcl.decomp]/2: 1401 // If E is an array type [...] 1402 // As an extension, we also support decomposition of built-in complex and 1403 // vector types. 1404 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1405 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1406 DD->setInvalidDecl(); 1407 return; 1408 } 1409 if (auto *VT = DecompType->getAs<VectorType>()) { 1410 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1411 DD->setInvalidDecl(); 1412 return; 1413 } 1414 if (auto *CT = DecompType->getAs<ComplexType>()) { 1415 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1416 DD->setInvalidDecl(); 1417 return; 1418 } 1419 1420 // C++1z [dcl.decomp]/3: 1421 // if the expression std::tuple_size<E>::value is a well-formed integral 1422 // constant expression, [...] 1423 llvm::APSInt TupleSize(32); 1424 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1425 case IsTupleLike::Error: 1426 DD->setInvalidDecl(); 1427 return; 1428 1429 case IsTupleLike::TupleLike: 1430 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1431 DD->setInvalidDecl(); 1432 return; 1433 1434 case IsTupleLike::NotTupleLike: 1435 break; 1436 } 1437 1438 // C++1z [dcl.dcl]/8: 1439 // [E shall be of array or non-union class type] 1440 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1441 if (!RD || RD->isUnion()) { 1442 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1443 << DD << !RD << DecompType; 1444 DD->setInvalidDecl(); 1445 return; 1446 } 1447 1448 // C++1z [dcl.decomp]/4: 1449 // all of E's non-static data members shall be [...] direct members of 1450 // E or of the same unambiguous public base class of E, ... 1451 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1452 DD->setInvalidDecl(); 1453 } 1454 1455 /// Merge the exception specifications of two variable declarations. 1456 /// 1457 /// This is called when there's a redeclaration of a VarDecl. The function 1458 /// checks if the redeclaration might have an exception specification and 1459 /// validates compatibility and merges the specs if necessary. 1460 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1461 // Shortcut if exceptions are disabled. 1462 if (!getLangOpts().CXXExceptions) 1463 return; 1464 1465 assert(Context.hasSameType(New->getType(), Old->getType()) && 1466 "Should only be called if types are otherwise the same."); 1467 1468 QualType NewType = New->getType(); 1469 QualType OldType = Old->getType(); 1470 1471 // We're only interested in pointers and references to functions, as well 1472 // as pointers to member functions. 1473 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1474 NewType = R->getPointeeType(); 1475 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1476 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1477 NewType = P->getPointeeType(); 1478 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1479 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1480 NewType = M->getPointeeType(); 1481 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1482 } 1483 1484 if (!NewType->isFunctionProtoType()) 1485 return; 1486 1487 // There's lots of special cases for functions. For function pointers, system 1488 // libraries are hopefully not as broken so that we don't need these 1489 // workarounds. 1490 if (CheckEquivalentExceptionSpec( 1491 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1492 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1493 New->setInvalidDecl(); 1494 } 1495 } 1496 1497 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1498 /// function declaration are well-formed according to C++ 1499 /// [dcl.fct.default]. 1500 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1501 unsigned NumParams = FD->getNumParams(); 1502 unsigned p; 1503 1504 // Find first parameter with a default argument 1505 for (p = 0; p < NumParams; ++p) { 1506 ParmVarDecl *Param = FD->getParamDecl(p); 1507 if (Param->hasDefaultArg()) 1508 break; 1509 } 1510 1511 // C++11 [dcl.fct.default]p4: 1512 // In a given function declaration, each parameter subsequent to a parameter 1513 // with a default argument shall have a default argument supplied in this or 1514 // a previous declaration or shall be a function parameter pack. A default 1515 // argument shall not be redefined by a later declaration (not even to the 1516 // same value). 1517 unsigned LastMissingDefaultArg = 0; 1518 for (; p < NumParams; ++p) { 1519 ParmVarDecl *Param = FD->getParamDecl(p); 1520 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1521 if (Param->isInvalidDecl()) 1522 /* We already complained about this parameter. */; 1523 else if (Param->getIdentifier()) 1524 Diag(Param->getLocation(), 1525 diag::err_param_default_argument_missing_name) 1526 << Param->getIdentifier(); 1527 else 1528 Diag(Param->getLocation(), 1529 diag::err_param_default_argument_missing); 1530 1531 LastMissingDefaultArg = p; 1532 } 1533 } 1534 1535 if (LastMissingDefaultArg > 0) { 1536 // Some default arguments were missing. Clear out all of the 1537 // default arguments up to (and including) the last missing 1538 // default argument, so that we leave the function parameters 1539 // in a semantically valid state. 1540 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1541 ParmVarDecl *Param = FD->getParamDecl(p); 1542 if (Param->hasDefaultArg()) { 1543 Param->setDefaultArg(nullptr); 1544 } 1545 } 1546 } 1547 } 1548 1549 // CheckConstexprParameterTypes - Check whether a function's parameter types 1550 // are all literal types. If so, return true. If not, produce a suitable 1551 // diagnostic and return false. 1552 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1553 const FunctionDecl *FD) { 1554 unsigned ArgIndex = 0; 1555 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1556 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1557 e = FT->param_type_end(); 1558 i != e; ++i, ++ArgIndex) { 1559 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1560 SourceLocation ParamLoc = PD->getLocation(); 1561 if (!(*i)->isDependentType() && 1562 SemaRef.RequireLiteralType(ParamLoc, *i, 1563 diag::err_constexpr_non_literal_param, 1564 ArgIndex+1, PD->getSourceRange(), 1565 isa<CXXConstructorDecl>(FD))) 1566 return false; 1567 } 1568 return true; 1569 } 1570 1571 /// Get diagnostic %select index for tag kind for 1572 /// record diagnostic message. 1573 /// WARNING: Indexes apply to particular diagnostics only! 1574 /// 1575 /// \returns diagnostic %select index. 1576 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1577 switch (Tag) { 1578 case TTK_Struct: return 0; 1579 case TTK_Interface: return 1; 1580 case TTK_Class: return 2; 1581 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1582 } 1583 } 1584 1585 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1586 // the requirements of a constexpr function definition or a constexpr 1587 // constructor definition. If so, return true. If not, produce appropriate 1588 // diagnostics and return false. 1589 // 1590 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1591 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1592 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1593 if (MD && MD->isInstance()) { 1594 // C++11 [dcl.constexpr]p4: 1595 // The definition of a constexpr constructor shall satisfy the following 1596 // constraints: 1597 // - the class shall not have any virtual base classes; 1598 const CXXRecordDecl *RD = MD->getParent(); 1599 if (RD->getNumVBases()) { 1600 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1601 << isa<CXXConstructorDecl>(NewFD) 1602 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1603 for (const auto &I : RD->vbases()) 1604 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1605 << I.getSourceRange(); 1606 return false; 1607 } 1608 } 1609 1610 if (!isa<CXXConstructorDecl>(NewFD)) { 1611 // C++11 [dcl.constexpr]p3: 1612 // The definition of a constexpr function shall satisfy the following 1613 // constraints: 1614 // - it shall not be virtual; 1615 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1616 if (Method && Method->isVirtual()) { 1617 Method = Method->getCanonicalDecl(); 1618 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1619 1620 // If it's not obvious why this function is virtual, find an overridden 1621 // function which uses the 'virtual' keyword. 1622 const CXXMethodDecl *WrittenVirtual = Method; 1623 while (!WrittenVirtual->isVirtualAsWritten()) 1624 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1625 if (WrittenVirtual != Method) 1626 Diag(WrittenVirtual->getLocation(), 1627 diag::note_overridden_virtual_function); 1628 return false; 1629 } 1630 1631 // - its return type shall be a literal type; 1632 QualType RT = NewFD->getReturnType(); 1633 if (!RT->isDependentType() && 1634 RequireLiteralType(NewFD->getLocation(), RT, 1635 diag::err_constexpr_non_literal_return)) 1636 return false; 1637 } 1638 1639 // - each of its parameter types shall be a literal type; 1640 if (!CheckConstexprParameterTypes(*this, NewFD)) 1641 return false; 1642 1643 return true; 1644 } 1645 1646 /// Check the given declaration statement is legal within a constexpr function 1647 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1648 /// 1649 /// \return true if the body is OK (maybe only as an extension), false if we 1650 /// have diagnosed a problem. 1651 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1652 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1653 // C++11 [dcl.constexpr]p3 and p4: 1654 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1655 // contain only 1656 for (const auto *DclIt : DS->decls()) { 1657 switch (DclIt->getKind()) { 1658 case Decl::StaticAssert: 1659 case Decl::Using: 1660 case Decl::UsingShadow: 1661 case Decl::UsingDirective: 1662 case Decl::UnresolvedUsingTypename: 1663 case Decl::UnresolvedUsingValue: 1664 // - static_assert-declarations 1665 // - using-declarations, 1666 // - using-directives, 1667 continue; 1668 1669 case Decl::Typedef: 1670 case Decl::TypeAlias: { 1671 // - typedef declarations and alias-declarations that do not define 1672 // classes or enumerations, 1673 const auto *TN = cast<TypedefNameDecl>(DclIt); 1674 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1675 // Don't allow variably-modified types in constexpr functions. 1676 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1677 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1678 << TL.getSourceRange() << TL.getType() 1679 << isa<CXXConstructorDecl>(Dcl); 1680 return false; 1681 } 1682 continue; 1683 } 1684 1685 case Decl::Enum: 1686 case Decl::CXXRecord: 1687 // C++1y allows types to be defined, not just declared. 1688 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1689 SemaRef.Diag(DS->getBeginLoc(), 1690 SemaRef.getLangOpts().CPlusPlus14 1691 ? diag::warn_cxx11_compat_constexpr_type_definition 1692 : diag::ext_constexpr_type_definition) 1693 << isa<CXXConstructorDecl>(Dcl); 1694 continue; 1695 1696 case Decl::EnumConstant: 1697 case Decl::IndirectField: 1698 case Decl::ParmVar: 1699 // These can only appear with other declarations which are banned in 1700 // C++11 and permitted in C++1y, so ignore them. 1701 continue; 1702 1703 case Decl::Var: 1704 case Decl::Decomposition: { 1705 // C++1y [dcl.constexpr]p3 allows anything except: 1706 // a definition of a variable of non-literal type or of static or 1707 // thread storage duration or for which no initialization is performed. 1708 const auto *VD = cast<VarDecl>(DclIt); 1709 if (VD->isThisDeclarationADefinition()) { 1710 if (VD->isStaticLocal()) { 1711 SemaRef.Diag(VD->getLocation(), 1712 diag::err_constexpr_local_var_static) 1713 << isa<CXXConstructorDecl>(Dcl) 1714 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1715 return false; 1716 } 1717 if (!VD->getType()->isDependentType() && 1718 SemaRef.RequireLiteralType( 1719 VD->getLocation(), VD->getType(), 1720 diag::err_constexpr_local_var_non_literal_type, 1721 isa<CXXConstructorDecl>(Dcl))) 1722 return false; 1723 if (!VD->getType()->isDependentType() && 1724 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1725 SemaRef.Diag(VD->getLocation(), 1726 diag::err_constexpr_local_var_no_init) 1727 << isa<CXXConstructorDecl>(Dcl); 1728 return false; 1729 } 1730 } 1731 SemaRef.Diag(VD->getLocation(), 1732 SemaRef.getLangOpts().CPlusPlus14 1733 ? diag::warn_cxx11_compat_constexpr_local_var 1734 : diag::ext_constexpr_local_var) 1735 << isa<CXXConstructorDecl>(Dcl); 1736 continue; 1737 } 1738 1739 case Decl::NamespaceAlias: 1740 case Decl::Function: 1741 // These are disallowed in C++11 and permitted in C++1y. Allow them 1742 // everywhere as an extension. 1743 if (!Cxx1yLoc.isValid()) 1744 Cxx1yLoc = DS->getBeginLoc(); 1745 continue; 1746 1747 default: 1748 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1749 << isa<CXXConstructorDecl>(Dcl); 1750 return false; 1751 } 1752 } 1753 1754 return true; 1755 } 1756 1757 /// Check that the given field is initialized within a constexpr constructor. 1758 /// 1759 /// \param Dcl The constexpr constructor being checked. 1760 /// \param Field The field being checked. This may be a member of an anonymous 1761 /// struct or union nested within the class being checked. 1762 /// \param Inits All declarations, including anonymous struct/union members and 1763 /// indirect members, for which any initialization was provided. 1764 /// \param Diagnosed Set to true if an error is produced. 1765 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1766 const FunctionDecl *Dcl, 1767 FieldDecl *Field, 1768 llvm::SmallSet<Decl*, 16> &Inits, 1769 bool &Diagnosed) { 1770 if (Field->isInvalidDecl()) 1771 return; 1772 1773 if (Field->isUnnamedBitfield()) 1774 return; 1775 1776 // Anonymous unions with no variant members and empty anonymous structs do not 1777 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1778 // indirect fields don't need initializing. 1779 if (Field->isAnonymousStructOrUnion() && 1780 (Field->getType()->isUnionType() 1781 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1782 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1783 return; 1784 1785 if (!Inits.count(Field)) { 1786 if (!Diagnosed) { 1787 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1788 Diagnosed = true; 1789 } 1790 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1791 } else if (Field->isAnonymousStructOrUnion()) { 1792 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1793 for (auto *I : RD->fields()) 1794 // If an anonymous union contains an anonymous struct of which any member 1795 // is initialized, all members must be initialized. 1796 if (!RD->isUnion() || Inits.count(I)) 1797 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1798 } 1799 } 1800 1801 /// Check the provided statement is allowed in a constexpr function 1802 /// definition. 1803 static bool 1804 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1805 SmallVectorImpl<SourceLocation> &ReturnStmts, 1806 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) { 1807 // - its function-body shall be [...] a compound-statement that contains only 1808 switch (S->getStmtClass()) { 1809 case Stmt::NullStmtClass: 1810 // - null statements, 1811 return true; 1812 1813 case Stmt::DeclStmtClass: 1814 // - static_assert-declarations 1815 // - using-declarations, 1816 // - using-directives, 1817 // - typedef declarations and alias-declarations that do not define 1818 // classes or enumerations, 1819 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1820 return false; 1821 return true; 1822 1823 case Stmt::ReturnStmtClass: 1824 // - and exactly one return statement; 1825 if (isa<CXXConstructorDecl>(Dcl)) { 1826 // C++1y allows return statements in constexpr constructors. 1827 if (!Cxx1yLoc.isValid()) 1828 Cxx1yLoc = S->getBeginLoc(); 1829 return true; 1830 } 1831 1832 ReturnStmts.push_back(S->getBeginLoc()); 1833 return true; 1834 1835 case Stmt::CompoundStmtClass: { 1836 // C++1y allows compound-statements. 1837 if (!Cxx1yLoc.isValid()) 1838 Cxx1yLoc = S->getBeginLoc(); 1839 1840 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1841 for (auto *BodyIt : CompStmt->body()) { 1842 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1843 Cxx1yLoc, Cxx2aLoc)) 1844 return false; 1845 } 1846 return true; 1847 } 1848 1849 case Stmt::AttributedStmtClass: 1850 if (!Cxx1yLoc.isValid()) 1851 Cxx1yLoc = S->getBeginLoc(); 1852 return true; 1853 1854 case Stmt::IfStmtClass: { 1855 // C++1y allows if-statements. 1856 if (!Cxx1yLoc.isValid()) 1857 Cxx1yLoc = S->getBeginLoc(); 1858 1859 IfStmt *If = cast<IfStmt>(S); 1860 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1861 Cxx1yLoc, Cxx2aLoc)) 1862 return false; 1863 if (If->getElse() && 1864 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1865 Cxx1yLoc, Cxx2aLoc)) 1866 return false; 1867 return true; 1868 } 1869 1870 case Stmt::WhileStmtClass: 1871 case Stmt::DoStmtClass: 1872 case Stmt::ForStmtClass: 1873 case Stmt::CXXForRangeStmtClass: 1874 case Stmt::ContinueStmtClass: 1875 // C++1y allows all of these. We don't allow them as extensions in C++11, 1876 // because they don't make sense without variable mutation. 1877 if (!SemaRef.getLangOpts().CPlusPlus14) 1878 break; 1879 if (!Cxx1yLoc.isValid()) 1880 Cxx1yLoc = S->getBeginLoc(); 1881 for (Stmt *SubStmt : S->children()) 1882 if (SubStmt && 1883 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1884 Cxx1yLoc, Cxx2aLoc)) 1885 return false; 1886 return true; 1887 1888 case Stmt::SwitchStmtClass: 1889 case Stmt::CaseStmtClass: 1890 case Stmt::DefaultStmtClass: 1891 case Stmt::BreakStmtClass: 1892 // C++1y allows switch-statements, and since they don't need variable 1893 // mutation, we can reasonably allow them in C++11 as an extension. 1894 if (!Cxx1yLoc.isValid()) 1895 Cxx1yLoc = S->getBeginLoc(); 1896 for (Stmt *SubStmt : S->children()) 1897 if (SubStmt && 1898 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1899 Cxx1yLoc, Cxx2aLoc)) 1900 return false; 1901 return true; 1902 1903 case Stmt::CXXTryStmtClass: 1904 if (Cxx2aLoc.isInvalid()) 1905 Cxx2aLoc = S->getBeginLoc(); 1906 for (Stmt *SubStmt : S->children()) { 1907 if (SubStmt && 1908 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1909 Cxx1yLoc, Cxx2aLoc)) 1910 return false; 1911 } 1912 return true; 1913 1914 case Stmt::CXXCatchStmtClass: 1915 // Do not bother checking the language mode (already covered by the 1916 // try block check). 1917 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 1918 cast<CXXCatchStmt>(S)->getHandlerBlock(), 1919 ReturnStmts, Cxx1yLoc, Cxx2aLoc)) 1920 return false; 1921 return true; 1922 1923 default: 1924 if (!isa<Expr>(S)) 1925 break; 1926 1927 // C++1y allows expression-statements. 1928 if (!Cxx1yLoc.isValid()) 1929 Cxx1yLoc = S->getBeginLoc(); 1930 return true; 1931 } 1932 1933 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1934 << isa<CXXConstructorDecl>(Dcl); 1935 return false; 1936 } 1937 1938 /// Check the body for the given constexpr function declaration only contains 1939 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1940 /// 1941 /// \return true if the body is OK, false if we have diagnosed a problem. 1942 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1943 SmallVector<SourceLocation, 4> ReturnStmts; 1944 1945 if (isa<CXXTryStmt>(Body)) { 1946 // C++11 [dcl.constexpr]p3: 1947 // The definition of a constexpr function shall satisfy the following 1948 // constraints: [...] 1949 // - its function-body shall be = delete, = default, or a 1950 // compound-statement 1951 // 1952 // C++11 [dcl.constexpr]p4: 1953 // In the definition of a constexpr constructor, [...] 1954 // - its function-body shall not be a function-try-block; 1955 // 1956 // This restriction is lifted in C++2a, as long as inner statements also 1957 // apply the general constexpr rules. 1958 Diag(Body->getBeginLoc(), 1959 !getLangOpts().CPlusPlus2a 1960 ? diag::ext_constexpr_function_try_block_cxx2a 1961 : diag::warn_cxx17_compat_constexpr_function_try_block) 1962 << isa<CXXConstructorDecl>(Dcl); 1963 } 1964 1965 // - its function-body shall be [...] a compound-statement that contains only 1966 // [... list of cases ...] 1967 // 1968 // Note that walking the children here is enough to properly check for 1969 // CompoundStmt and CXXTryStmt body. 1970 SourceLocation Cxx1yLoc, Cxx2aLoc; 1971 for (Stmt *SubStmt : Body->children()) { 1972 if (SubStmt && 1973 !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts, 1974 Cxx1yLoc, Cxx2aLoc)) 1975 return false; 1976 } 1977 1978 if (Cxx2aLoc.isValid()) 1979 Diag(Cxx2aLoc, 1980 getLangOpts().CPlusPlus2a 1981 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 1982 : diag::ext_constexpr_body_invalid_stmt_cxx2a) 1983 << isa<CXXConstructorDecl>(Dcl); 1984 if (Cxx1yLoc.isValid()) 1985 Diag(Cxx1yLoc, 1986 getLangOpts().CPlusPlus14 1987 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1988 : diag::ext_constexpr_body_invalid_stmt) 1989 << isa<CXXConstructorDecl>(Dcl); 1990 1991 if (const CXXConstructorDecl *Constructor 1992 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1993 const CXXRecordDecl *RD = Constructor->getParent(); 1994 // DR1359: 1995 // - every non-variant non-static data member and base class sub-object 1996 // shall be initialized; 1997 // DR1460: 1998 // - if the class is a union having variant members, exactly one of them 1999 // shall be initialized; 2000 if (RD->isUnion()) { 2001 if (Constructor->getNumCtorInitializers() == 0 && 2002 RD->hasVariantMembers()) { 2003 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 2004 return false; 2005 } 2006 } else if (!Constructor->isDependentContext() && 2007 !Constructor->isDelegatingConstructor()) { 2008 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2009 2010 // Skip detailed checking if we have enough initializers, and we would 2011 // allow at most one initializer per member. 2012 bool AnyAnonStructUnionMembers = false; 2013 unsigned Fields = 0; 2014 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2015 E = RD->field_end(); I != E; ++I, ++Fields) { 2016 if (I->isAnonymousStructOrUnion()) { 2017 AnyAnonStructUnionMembers = true; 2018 break; 2019 } 2020 } 2021 // DR1460: 2022 // - if the class is a union-like class, but is not a union, for each of 2023 // its anonymous union members having variant members, exactly one of 2024 // them shall be initialized; 2025 if (AnyAnonStructUnionMembers || 2026 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2027 // Check initialization of non-static data members. Base classes are 2028 // always initialized so do not need to be checked. Dependent bases 2029 // might not have initializers in the member initializer list. 2030 llvm::SmallSet<Decl*, 16> Inits; 2031 for (const auto *I: Constructor->inits()) { 2032 if (FieldDecl *FD = I->getMember()) 2033 Inits.insert(FD); 2034 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2035 Inits.insert(ID->chain_begin(), ID->chain_end()); 2036 } 2037 2038 bool Diagnosed = false; 2039 for (auto *I : RD->fields()) 2040 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2041 if (Diagnosed) 2042 return false; 2043 } 2044 } 2045 } else { 2046 if (ReturnStmts.empty()) { 2047 // C++1y doesn't require constexpr functions to contain a 'return' 2048 // statement. We still do, unless the return type might be void, because 2049 // otherwise if there's no return statement, the function cannot 2050 // be used in a core constant expression. 2051 bool OK = getLangOpts().CPlusPlus14 && 2052 (Dcl->getReturnType()->isVoidType() || 2053 Dcl->getReturnType()->isDependentType()); 2054 Diag(Dcl->getLocation(), 2055 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2056 : diag::err_constexpr_body_no_return); 2057 if (!OK) 2058 return false; 2059 } else if (ReturnStmts.size() > 1) { 2060 Diag(ReturnStmts.back(), 2061 getLangOpts().CPlusPlus14 2062 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2063 : diag::ext_constexpr_body_multiple_return); 2064 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2065 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2066 } 2067 } 2068 2069 // C++11 [dcl.constexpr]p5: 2070 // if no function argument values exist such that the function invocation 2071 // substitution would produce a constant expression, the program is 2072 // ill-formed; no diagnostic required. 2073 // C++11 [dcl.constexpr]p3: 2074 // - every constructor call and implicit conversion used in initializing the 2075 // return value shall be one of those allowed in a constant expression. 2076 // C++11 [dcl.constexpr]p4: 2077 // - every constructor involved in initializing non-static data members and 2078 // base class sub-objects shall be a constexpr constructor. 2079 SmallVector<PartialDiagnosticAt, 8> Diags; 2080 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2081 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2082 << isa<CXXConstructorDecl>(Dcl); 2083 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2084 Diag(Diags[I].first, Diags[I].second); 2085 // Don't return false here: we allow this for compatibility in 2086 // system headers. 2087 } 2088 2089 return true; 2090 } 2091 2092 /// Get the class that is directly named by the current context. This is the 2093 /// class for which an unqualified-id in this scope could name a constructor 2094 /// or destructor. 2095 /// 2096 /// If the scope specifier denotes a class, this will be that class. 2097 /// If the scope specifier is empty, this will be the class whose 2098 /// member-specification we are currently within. Otherwise, there 2099 /// is no such class. 2100 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2101 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2102 2103 if (SS && SS->isInvalid()) 2104 return nullptr; 2105 2106 if (SS && SS->isNotEmpty()) { 2107 DeclContext *DC = computeDeclContext(*SS, true); 2108 return dyn_cast_or_null<CXXRecordDecl>(DC); 2109 } 2110 2111 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2112 } 2113 2114 /// isCurrentClassName - Determine whether the identifier II is the 2115 /// name of the class type currently being defined. In the case of 2116 /// nested classes, this will only return true if II is the name of 2117 /// the innermost class. 2118 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2119 const CXXScopeSpec *SS) { 2120 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2121 return CurDecl && &II == CurDecl->getIdentifier(); 2122 } 2123 2124 /// Determine whether the identifier II is a typo for the name of 2125 /// the class type currently being defined. If so, update it to the identifier 2126 /// that should have been used. 2127 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2128 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2129 2130 if (!getLangOpts().SpellChecking) 2131 return false; 2132 2133 CXXRecordDecl *CurDecl; 2134 if (SS && SS->isSet() && !SS->isInvalid()) { 2135 DeclContext *DC = computeDeclContext(*SS, true); 2136 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2137 } else 2138 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2139 2140 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2141 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2142 < II->getLength()) { 2143 II = CurDecl->getIdentifier(); 2144 return true; 2145 } 2146 2147 return false; 2148 } 2149 2150 /// Determine whether the given class is a base class of the given 2151 /// class, including looking at dependent bases. 2152 static bool findCircularInheritance(const CXXRecordDecl *Class, 2153 const CXXRecordDecl *Current) { 2154 SmallVector<const CXXRecordDecl*, 8> Queue; 2155 2156 Class = Class->getCanonicalDecl(); 2157 while (true) { 2158 for (const auto &I : Current->bases()) { 2159 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2160 if (!Base) 2161 continue; 2162 2163 Base = Base->getDefinition(); 2164 if (!Base) 2165 continue; 2166 2167 if (Base->getCanonicalDecl() == Class) 2168 return true; 2169 2170 Queue.push_back(Base); 2171 } 2172 2173 if (Queue.empty()) 2174 return false; 2175 2176 Current = Queue.pop_back_val(); 2177 } 2178 2179 return false; 2180 } 2181 2182 /// Check the validity of a C++ base class specifier. 2183 /// 2184 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2185 /// and returns NULL otherwise. 2186 CXXBaseSpecifier * 2187 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2188 SourceRange SpecifierRange, 2189 bool Virtual, AccessSpecifier Access, 2190 TypeSourceInfo *TInfo, 2191 SourceLocation EllipsisLoc) { 2192 QualType BaseType = TInfo->getType(); 2193 2194 // C++ [class.union]p1: 2195 // A union shall not have base classes. 2196 if (Class->isUnion()) { 2197 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2198 << SpecifierRange; 2199 return nullptr; 2200 } 2201 2202 if (EllipsisLoc.isValid() && 2203 !TInfo->getType()->containsUnexpandedParameterPack()) { 2204 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2205 << TInfo->getTypeLoc().getSourceRange(); 2206 EllipsisLoc = SourceLocation(); 2207 } 2208 2209 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2210 2211 if (BaseType->isDependentType()) { 2212 // Make sure that we don't have circular inheritance among our dependent 2213 // bases. For non-dependent bases, the check for completeness below handles 2214 // this. 2215 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2216 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2217 ((BaseDecl = BaseDecl->getDefinition()) && 2218 findCircularInheritance(Class, BaseDecl))) { 2219 Diag(BaseLoc, diag::err_circular_inheritance) 2220 << BaseType << Context.getTypeDeclType(Class); 2221 2222 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2223 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2224 << BaseType; 2225 2226 return nullptr; 2227 } 2228 } 2229 2230 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2231 Class->getTagKind() == TTK_Class, 2232 Access, TInfo, EllipsisLoc); 2233 } 2234 2235 // Base specifiers must be record types. 2236 if (!BaseType->isRecordType()) { 2237 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2238 return nullptr; 2239 } 2240 2241 // C++ [class.union]p1: 2242 // A union shall not be used as a base class. 2243 if (BaseType->isUnionType()) { 2244 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2245 return nullptr; 2246 } 2247 2248 // For the MS ABI, propagate DLL attributes to base class templates. 2249 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2250 if (Attr *ClassAttr = getDLLAttr(Class)) { 2251 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2252 BaseType->getAsCXXRecordDecl())) { 2253 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2254 BaseLoc); 2255 } 2256 } 2257 } 2258 2259 // C++ [class.derived]p2: 2260 // The class-name in a base-specifier shall not be an incompletely 2261 // defined class. 2262 if (RequireCompleteType(BaseLoc, BaseType, 2263 diag::err_incomplete_base_class, SpecifierRange)) { 2264 Class->setInvalidDecl(); 2265 return nullptr; 2266 } 2267 2268 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2269 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2270 assert(BaseDecl && "Record type has no declaration"); 2271 BaseDecl = BaseDecl->getDefinition(); 2272 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2273 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2274 assert(CXXBaseDecl && "Base type is not a C++ type"); 2275 2276 // Microsoft docs say: 2277 // "If a base-class has a code_seg attribute, derived classes must have the 2278 // same attribute." 2279 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2280 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2281 if ((DerivedCSA || BaseCSA) && 2282 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2283 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2284 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2285 << CXXBaseDecl; 2286 return nullptr; 2287 } 2288 2289 // A class which contains a flexible array member is not suitable for use as a 2290 // base class: 2291 // - If the layout determines that a base comes before another base, 2292 // the flexible array member would index into the subsequent base. 2293 // - If the layout determines that base comes before the derived class, 2294 // the flexible array member would index into the derived class. 2295 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2296 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2297 << CXXBaseDecl->getDeclName(); 2298 return nullptr; 2299 } 2300 2301 // C++ [class]p3: 2302 // If a class is marked final and it appears as a base-type-specifier in 2303 // base-clause, the program is ill-formed. 2304 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2305 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2306 << CXXBaseDecl->getDeclName() 2307 << FA->isSpelledAsSealed(); 2308 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2309 << CXXBaseDecl->getDeclName() << FA->getRange(); 2310 return nullptr; 2311 } 2312 2313 if (BaseDecl->isInvalidDecl()) 2314 Class->setInvalidDecl(); 2315 2316 // Create the base specifier. 2317 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2318 Class->getTagKind() == TTK_Class, 2319 Access, TInfo, EllipsisLoc); 2320 } 2321 2322 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2323 /// one entry in the base class list of a class specifier, for 2324 /// example: 2325 /// class foo : public bar, virtual private baz { 2326 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2327 BaseResult 2328 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2329 ParsedAttributes &Attributes, 2330 bool Virtual, AccessSpecifier Access, 2331 ParsedType basetype, SourceLocation BaseLoc, 2332 SourceLocation EllipsisLoc) { 2333 if (!classdecl) 2334 return true; 2335 2336 AdjustDeclIfTemplate(classdecl); 2337 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2338 if (!Class) 2339 return true; 2340 2341 // We haven't yet attached the base specifiers. 2342 Class->setIsParsingBaseSpecifiers(); 2343 2344 // We do not support any C++11 attributes on base-specifiers yet. 2345 // Diagnose any attributes we see. 2346 for (const ParsedAttr &AL : Attributes) { 2347 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2348 continue; 2349 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2350 ? (unsigned)diag::warn_unknown_attribute_ignored 2351 : (unsigned)diag::err_base_specifier_attribute) 2352 << AL.getName(); 2353 } 2354 2355 TypeSourceInfo *TInfo = nullptr; 2356 GetTypeFromParser(basetype, &TInfo); 2357 2358 if (EllipsisLoc.isInvalid() && 2359 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2360 UPPC_BaseType)) 2361 return true; 2362 2363 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2364 Virtual, Access, TInfo, 2365 EllipsisLoc)) 2366 return BaseSpec; 2367 else 2368 Class->setInvalidDecl(); 2369 2370 return true; 2371 } 2372 2373 /// Use small set to collect indirect bases. As this is only used 2374 /// locally, there's no need to abstract the small size parameter. 2375 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2376 2377 /// Recursively add the bases of Type. Don't add Type itself. 2378 static void 2379 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2380 const QualType &Type) 2381 { 2382 // Even though the incoming type is a base, it might not be 2383 // a class -- it could be a template parm, for instance. 2384 if (auto Rec = Type->getAs<RecordType>()) { 2385 auto Decl = Rec->getAsCXXRecordDecl(); 2386 2387 // Iterate over its bases. 2388 for (const auto &BaseSpec : Decl->bases()) { 2389 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2390 .getUnqualifiedType(); 2391 if (Set.insert(Base).second) 2392 // If we've not already seen it, recurse. 2393 NoteIndirectBases(Context, Set, Base); 2394 } 2395 } 2396 } 2397 2398 /// Performs the actual work of attaching the given base class 2399 /// specifiers to a C++ class. 2400 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2401 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2402 if (Bases.empty()) 2403 return false; 2404 2405 // Used to keep track of which base types we have already seen, so 2406 // that we can properly diagnose redundant direct base types. Note 2407 // that the key is always the unqualified canonical type of the base 2408 // class. 2409 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2410 2411 // Used to track indirect bases so we can see if a direct base is 2412 // ambiguous. 2413 IndirectBaseSet IndirectBaseTypes; 2414 2415 // Copy non-redundant base specifiers into permanent storage. 2416 unsigned NumGoodBases = 0; 2417 bool Invalid = false; 2418 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2419 QualType NewBaseType 2420 = Context.getCanonicalType(Bases[idx]->getType()); 2421 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2422 2423 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2424 if (KnownBase) { 2425 // C++ [class.mi]p3: 2426 // A class shall not be specified as a direct base class of a 2427 // derived class more than once. 2428 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2429 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2430 2431 // Delete the duplicate base class specifier; we're going to 2432 // overwrite its pointer later. 2433 Context.Deallocate(Bases[idx]); 2434 2435 Invalid = true; 2436 } else { 2437 // Okay, add this new base class. 2438 KnownBase = Bases[idx]; 2439 Bases[NumGoodBases++] = Bases[idx]; 2440 2441 // Note this base's direct & indirect bases, if there could be ambiguity. 2442 if (Bases.size() > 1) 2443 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2444 2445 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2446 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2447 if (Class->isInterface() && 2448 (!RD->isInterfaceLike() || 2449 KnownBase->getAccessSpecifier() != AS_public)) { 2450 // The Microsoft extension __interface does not permit bases that 2451 // are not themselves public interfaces. 2452 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2453 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2454 << RD->getSourceRange(); 2455 Invalid = true; 2456 } 2457 if (RD->hasAttr<WeakAttr>()) 2458 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2459 } 2460 } 2461 } 2462 2463 // Attach the remaining base class specifiers to the derived class. 2464 Class->setBases(Bases.data(), NumGoodBases); 2465 2466 // Check that the only base classes that are duplicate are virtual. 2467 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2468 // Check whether this direct base is inaccessible due to ambiguity. 2469 QualType BaseType = Bases[idx]->getType(); 2470 2471 // Skip all dependent types in templates being used as base specifiers. 2472 // Checks below assume that the base specifier is a CXXRecord. 2473 if (BaseType->isDependentType()) 2474 continue; 2475 2476 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2477 .getUnqualifiedType(); 2478 2479 if (IndirectBaseTypes.count(CanonicalBase)) { 2480 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2481 /*DetectVirtual=*/true); 2482 bool found 2483 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2484 assert(found); 2485 (void)found; 2486 2487 if (Paths.isAmbiguous(CanonicalBase)) 2488 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2489 << BaseType << getAmbiguousPathsDisplayString(Paths) 2490 << Bases[idx]->getSourceRange(); 2491 else 2492 assert(Bases[idx]->isVirtual()); 2493 } 2494 2495 // Delete the base class specifier, since its data has been copied 2496 // into the CXXRecordDecl. 2497 Context.Deallocate(Bases[idx]); 2498 } 2499 2500 return Invalid; 2501 } 2502 2503 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2504 /// class, after checking whether there are any duplicate base 2505 /// classes. 2506 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2507 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2508 if (!ClassDecl || Bases.empty()) 2509 return; 2510 2511 AdjustDeclIfTemplate(ClassDecl); 2512 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2513 } 2514 2515 /// Determine whether the type \p Derived is a C++ class that is 2516 /// derived from the type \p Base. 2517 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2518 if (!getLangOpts().CPlusPlus) 2519 return false; 2520 2521 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2522 if (!DerivedRD) 2523 return false; 2524 2525 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2526 if (!BaseRD) 2527 return false; 2528 2529 // If either the base or the derived type is invalid, don't try to 2530 // check whether one is derived from the other. 2531 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2532 return false; 2533 2534 // FIXME: In a modules build, do we need the entire path to be visible for us 2535 // to be able to use the inheritance relationship? 2536 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2537 return false; 2538 2539 return DerivedRD->isDerivedFrom(BaseRD); 2540 } 2541 2542 /// Determine whether the type \p Derived is a C++ class that is 2543 /// derived from the type \p Base. 2544 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2545 CXXBasePaths &Paths) { 2546 if (!getLangOpts().CPlusPlus) 2547 return false; 2548 2549 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2550 if (!DerivedRD) 2551 return false; 2552 2553 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2554 if (!BaseRD) 2555 return false; 2556 2557 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2558 return false; 2559 2560 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2561 } 2562 2563 static void BuildBasePathArray(const CXXBasePath &Path, 2564 CXXCastPath &BasePathArray) { 2565 // We first go backward and check if we have a virtual base. 2566 // FIXME: It would be better if CXXBasePath had the base specifier for 2567 // the nearest virtual base. 2568 unsigned Start = 0; 2569 for (unsigned I = Path.size(); I != 0; --I) { 2570 if (Path[I - 1].Base->isVirtual()) { 2571 Start = I - 1; 2572 break; 2573 } 2574 } 2575 2576 // Now add all bases. 2577 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2578 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2579 } 2580 2581 2582 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2583 CXXCastPath &BasePathArray) { 2584 assert(BasePathArray.empty() && "Base path array must be empty!"); 2585 assert(Paths.isRecordingPaths() && "Must record paths!"); 2586 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2587 } 2588 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2589 /// conversion (where Derived and Base are class types) is 2590 /// well-formed, meaning that the conversion is unambiguous (and 2591 /// that all of the base classes are accessible). Returns true 2592 /// and emits a diagnostic if the code is ill-formed, returns false 2593 /// otherwise. Loc is the location where this routine should point to 2594 /// if there is an error, and Range is the source range to highlight 2595 /// if there is an error. 2596 /// 2597 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2598 /// diagnostic for the respective type of error will be suppressed, but the 2599 /// check for ill-formed code will still be performed. 2600 bool 2601 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2602 unsigned InaccessibleBaseID, 2603 unsigned AmbigiousBaseConvID, 2604 SourceLocation Loc, SourceRange Range, 2605 DeclarationName Name, 2606 CXXCastPath *BasePath, 2607 bool IgnoreAccess) { 2608 // First, determine whether the path from Derived to Base is 2609 // ambiguous. This is slightly more expensive than checking whether 2610 // the Derived to Base conversion exists, because here we need to 2611 // explore multiple paths to determine if there is an ambiguity. 2612 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2613 /*DetectVirtual=*/false); 2614 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2615 if (!DerivationOkay) 2616 return true; 2617 2618 const CXXBasePath *Path = nullptr; 2619 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2620 Path = &Paths.front(); 2621 2622 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2623 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2624 // user to access such bases. 2625 if (!Path && getLangOpts().MSVCCompat) { 2626 for (const CXXBasePath &PossiblePath : Paths) { 2627 if (PossiblePath.size() == 1) { 2628 Path = &PossiblePath; 2629 if (AmbigiousBaseConvID) 2630 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2631 << Base << Derived << Range; 2632 break; 2633 } 2634 } 2635 } 2636 2637 if (Path) { 2638 if (!IgnoreAccess) { 2639 // Check that the base class can be accessed. 2640 switch ( 2641 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2642 case AR_inaccessible: 2643 return true; 2644 case AR_accessible: 2645 case AR_dependent: 2646 case AR_delayed: 2647 break; 2648 } 2649 } 2650 2651 // Build a base path if necessary. 2652 if (BasePath) 2653 ::BuildBasePathArray(*Path, *BasePath); 2654 return false; 2655 } 2656 2657 if (AmbigiousBaseConvID) { 2658 // We know that the derived-to-base conversion is ambiguous, and 2659 // we're going to produce a diagnostic. Perform the derived-to-base 2660 // search just one more time to compute all of the possible paths so 2661 // that we can print them out. This is more expensive than any of 2662 // the previous derived-to-base checks we've done, but at this point 2663 // performance isn't as much of an issue. 2664 Paths.clear(); 2665 Paths.setRecordingPaths(true); 2666 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2667 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2668 (void)StillOkay; 2669 2670 // Build up a textual representation of the ambiguous paths, e.g., 2671 // D -> B -> A, that will be used to illustrate the ambiguous 2672 // conversions in the diagnostic. We only print one of the paths 2673 // to each base class subobject. 2674 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2675 2676 Diag(Loc, AmbigiousBaseConvID) 2677 << Derived << Base << PathDisplayStr << Range << Name; 2678 } 2679 return true; 2680 } 2681 2682 bool 2683 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2684 SourceLocation Loc, SourceRange Range, 2685 CXXCastPath *BasePath, 2686 bool IgnoreAccess) { 2687 return CheckDerivedToBaseConversion( 2688 Derived, Base, diag::err_upcast_to_inaccessible_base, 2689 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2690 BasePath, IgnoreAccess); 2691 } 2692 2693 2694 /// Builds a string representing ambiguous paths from a 2695 /// specific derived class to different subobjects of the same base 2696 /// class. 2697 /// 2698 /// This function builds a string that can be used in error messages 2699 /// to show the different paths that one can take through the 2700 /// inheritance hierarchy to go from the derived class to different 2701 /// subobjects of a base class. The result looks something like this: 2702 /// @code 2703 /// struct D -> struct B -> struct A 2704 /// struct D -> struct C -> struct A 2705 /// @endcode 2706 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2707 std::string PathDisplayStr; 2708 std::set<unsigned> DisplayedPaths; 2709 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2710 Path != Paths.end(); ++Path) { 2711 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2712 // We haven't displayed a path to this particular base 2713 // class subobject yet. 2714 PathDisplayStr += "\n "; 2715 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2716 for (CXXBasePath::const_iterator Element = Path->begin(); 2717 Element != Path->end(); ++Element) 2718 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2719 } 2720 } 2721 2722 return PathDisplayStr; 2723 } 2724 2725 //===----------------------------------------------------------------------===// 2726 // C++ class member Handling 2727 //===----------------------------------------------------------------------===// 2728 2729 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2730 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2731 SourceLocation ColonLoc, 2732 const ParsedAttributesView &Attrs) { 2733 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2734 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2735 ASLoc, ColonLoc); 2736 CurContext->addHiddenDecl(ASDecl); 2737 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2738 } 2739 2740 /// CheckOverrideControl - Check C++11 override control semantics. 2741 void Sema::CheckOverrideControl(NamedDecl *D) { 2742 if (D->isInvalidDecl()) 2743 return; 2744 2745 // We only care about "override" and "final" declarations. 2746 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2747 return; 2748 2749 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2750 2751 // We can't check dependent instance methods. 2752 if (MD && MD->isInstance() && 2753 (MD->getParent()->hasAnyDependentBases() || 2754 MD->getType()->isDependentType())) 2755 return; 2756 2757 if (MD && !MD->isVirtual()) { 2758 // If we have a non-virtual method, check if if hides a virtual method. 2759 // (In that case, it's most likely the method has the wrong type.) 2760 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2761 FindHiddenVirtualMethods(MD, OverloadedMethods); 2762 2763 if (!OverloadedMethods.empty()) { 2764 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2765 Diag(OA->getLocation(), 2766 diag::override_keyword_hides_virtual_member_function) 2767 << "override" << (OverloadedMethods.size() > 1); 2768 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2769 Diag(FA->getLocation(), 2770 diag::override_keyword_hides_virtual_member_function) 2771 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2772 << (OverloadedMethods.size() > 1); 2773 } 2774 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2775 MD->setInvalidDecl(); 2776 return; 2777 } 2778 // Fall through into the general case diagnostic. 2779 // FIXME: We might want to attempt typo correction here. 2780 } 2781 2782 if (!MD || !MD->isVirtual()) { 2783 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2784 Diag(OA->getLocation(), 2785 diag::override_keyword_only_allowed_on_virtual_member_functions) 2786 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2787 D->dropAttr<OverrideAttr>(); 2788 } 2789 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2790 Diag(FA->getLocation(), 2791 diag::override_keyword_only_allowed_on_virtual_member_functions) 2792 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2793 << FixItHint::CreateRemoval(FA->getLocation()); 2794 D->dropAttr<FinalAttr>(); 2795 } 2796 return; 2797 } 2798 2799 // C++11 [class.virtual]p5: 2800 // If a function is marked with the virt-specifier override and 2801 // does not override a member function of a base class, the program is 2802 // ill-formed. 2803 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2804 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2805 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2806 << MD->getDeclName(); 2807 } 2808 2809 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2810 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2811 return; 2812 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2813 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2814 return; 2815 2816 SourceLocation Loc = MD->getLocation(); 2817 SourceLocation SpellingLoc = Loc; 2818 if (getSourceManager().isMacroArgExpansion(Loc)) 2819 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 2820 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2821 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2822 return; 2823 2824 if (MD->size_overridden_methods() > 0) { 2825 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2826 ? diag::warn_destructor_marked_not_override_overriding 2827 : diag::warn_function_marked_not_override_overriding; 2828 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2829 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2830 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2831 } 2832 } 2833 2834 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2835 /// function overrides a virtual member function marked 'final', according to 2836 /// C++11 [class.virtual]p4. 2837 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2838 const CXXMethodDecl *Old) { 2839 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2840 if (!FA) 2841 return false; 2842 2843 Diag(New->getLocation(), diag::err_final_function_overridden) 2844 << New->getDeclName() 2845 << FA->isSpelledAsSealed(); 2846 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2847 return true; 2848 } 2849 2850 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2851 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2852 // FIXME: Destruction of ObjC lifetime types has side-effects. 2853 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2854 return !RD->isCompleteDefinition() || 2855 !RD->hasTrivialDefaultConstructor() || 2856 !RD->hasTrivialDestructor(); 2857 return false; 2858 } 2859 2860 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 2861 ParsedAttributesView::const_iterator Itr = 2862 llvm::find_if(list, [](const ParsedAttr &AL) { 2863 return AL.isDeclspecPropertyAttribute(); 2864 }); 2865 if (Itr != list.end()) 2866 return &*Itr; 2867 return nullptr; 2868 } 2869 2870 // Check if there is a field shadowing. 2871 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2872 DeclarationName FieldName, 2873 const CXXRecordDecl *RD, 2874 bool DeclIsField) { 2875 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2876 return; 2877 2878 // To record a shadowed field in a base 2879 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2880 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2881 CXXBasePath &Path) { 2882 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2883 // Record an ambiguous path directly 2884 if (Bases.find(Base) != Bases.end()) 2885 return true; 2886 for (const auto Field : Base->lookup(FieldName)) { 2887 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2888 Field->getAccess() != AS_private) { 2889 assert(Field->getAccess() != AS_none); 2890 assert(Bases.find(Base) == Bases.end()); 2891 Bases[Base] = Field; 2892 return true; 2893 } 2894 } 2895 return false; 2896 }; 2897 2898 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2899 /*DetectVirtual=*/true); 2900 if (!RD->lookupInBases(FieldShadowed, Paths)) 2901 return; 2902 2903 for (const auto &P : Paths) { 2904 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2905 auto It = Bases.find(Base); 2906 // Skip duplicated bases 2907 if (It == Bases.end()) 2908 continue; 2909 auto BaseField = It->second; 2910 assert(BaseField->getAccess() != AS_private); 2911 if (AS_none != 2912 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2913 Diag(Loc, diag::warn_shadow_field) 2914 << FieldName << RD << Base << DeclIsField; 2915 Diag(BaseField->getLocation(), diag::note_shadow_field); 2916 Bases.erase(It); 2917 } 2918 } 2919 } 2920 2921 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2922 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2923 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2924 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2925 /// present (but parsing it has been deferred). 2926 NamedDecl * 2927 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2928 MultiTemplateParamsArg TemplateParameterLists, 2929 Expr *BW, const VirtSpecifiers &VS, 2930 InClassInitStyle InitStyle) { 2931 const DeclSpec &DS = D.getDeclSpec(); 2932 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2933 DeclarationName Name = NameInfo.getName(); 2934 SourceLocation Loc = NameInfo.getLoc(); 2935 2936 // For anonymous bitfields, the location should point to the type. 2937 if (Loc.isInvalid()) 2938 Loc = D.getBeginLoc(); 2939 2940 Expr *BitWidth = static_cast<Expr*>(BW); 2941 2942 assert(isa<CXXRecordDecl>(CurContext)); 2943 assert(!DS.isFriendSpecified()); 2944 2945 bool isFunc = D.isDeclarationOfFunction(); 2946 const ParsedAttr *MSPropertyAttr = 2947 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 2948 2949 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2950 // The Microsoft extension __interface only permits public member functions 2951 // and prohibits constructors, destructors, operators, non-public member 2952 // functions, static methods and data members. 2953 unsigned InvalidDecl; 2954 bool ShowDeclName = true; 2955 if (!isFunc && 2956 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2957 InvalidDecl = 0; 2958 else if (!isFunc) 2959 InvalidDecl = 1; 2960 else if (AS != AS_public) 2961 InvalidDecl = 2; 2962 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2963 InvalidDecl = 3; 2964 else switch (Name.getNameKind()) { 2965 case DeclarationName::CXXConstructorName: 2966 InvalidDecl = 4; 2967 ShowDeclName = false; 2968 break; 2969 2970 case DeclarationName::CXXDestructorName: 2971 InvalidDecl = 5; 2972 ShowDeclName = false; 2973 break; 2974 2975 case DeclarationName::CXXOperatorName: 2976 case DeclarationName::CXXConversionFunctionName: 2977 InvalidDecl = 6; 2978 break; 2979 2980 default: 2981 InvalidDecl = 0; 2982 break; 2983 } 2984 2985 if (InvalidDecl) { 2986 if (ShowDeclName) 2987 Diag(Loc, diag::err_invalid_member_in_interface) 2988 << (InvalidDecl-1) << Name; 2989 else 2990 Diag(Loc, diag::err_invalid_member_in_interface) 2991 << (InvalidDecl-1) << ""; 2992 return nullptr; 2993 } 2994 } 2995 2996 // C++ 9.2p6: A member shall not be declared to have automatic storage 2997 // duration (auto, register) or with the extern storage-class-specifier. 2998 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2999 // data members and cannot be applied to names declared const or static, 3000 // and cannot be applied to reference members. 3001 switch (DS.getStorageClassSpec()) { 3002 case DeclSpec::SCS_unspecified: 3003 case DeclSpec::SCS_typedef: 3004 case DeclSpec::SCS_static: 3005 break; 3006 case DeclSpec::SCS_mutable: 3007 if (isFunc) { 3008 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3009 3010 // FIXME: It would be nicer if the keyword was ignored only for this 3011 // declarator. Otherwise we could get follow-up errors. 3012 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3013 } 3014 break; 3015 default: 3016 Diag(DS.getStorageClassSpecLoc(), 3017 diag::err_storageclass_invalid_for_member); 3018 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3019 break; 3020 } 3021 3022 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3023 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3024 !isFunc); 3025 3026 if (DS.isConstexprSpecified() && isInstField) { 3027 SemaDiagnosticBuilder B = 3028 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3029 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3030 if (InitStyle == ICIS_NoInit) { 3031 B << 0 << 0; 3032 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3033 B << FixItHint::CreateRemoval(ConstexprLoc); 3034 else { 3035 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3036 D.getMutableDeclSpec().ClearConstexprSpec(); 3037 const char *PrevSpec; 3038 unsigned DiagID; 3039 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3040 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3041 (void)Failed; 3042 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3043 } 3044 } else { 3045 B << 1; 3046 const char *PrevSpec; 3047 unsigned DiagID; 3048 if (D.getMutableDeclSpec().SetStorageClassSpec( 3049 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3050 Context.getPrintingPolicy())) { 3051 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3052 "This is the only DeclSpec that should fail to be applied"); 3053 B << 1; 3054 } else { 3055 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3056 isInstField = false; 3057 } 3058 } 3059 } 3060 3061 NamedDecl *Member; 3062 if (isInstField) { 3063 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3064 3065 // Data members must have identifiers for names. 3066 if (!Name.isIdentifier()) { 3067 Diag(Loc, diag::err_bad_variable_name) 3068 << Name; 3069 return nullptr; 3070 } 3071 3072 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3073 3074 // Member field could not be with "template" keyword. 3075 // So TemplateParameterLists should be empty in this case. 3076 if (TemplateParameterLists.size()) { 3077 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3078 if (TemplateParams->size()) { 3079 // There is no such thing as a member field template. 3080 Diag(D.getIdentifierLoc(), diag::err_template_member) 3081 << II 3082 << SourceRange(TemplateParams->getTemplateLoc(), 3083 TemplateParams->getRAngleLoc()); 3084 } else { 3085 // There is an extraneous 'template<>' for this member. 3086 Diag(TemplateParams->getTemplateLoc(), 3087 diag::err_template_member_noparams) 3088 << II 3089 << SourceRange(TemplateParams->getTemplateLoc(), 3090 TemplateParams->getRAngleLoc()); 3091 } 3092 return nullptr; 3093 } 3094 3095 if (SS.isSet() && !SS.isInvalid()) { 3096 // The user provided a superfluous scope specifier inside a class 3097 // definition: 3098 // 3099 // class X { 3100 // int X::member; 3101 // }; 3102 if (DeclContext *DC = computeDeclContext(SS, false)) 3103 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3104 D.getName().getKind() == 3105 UnqualifiedIdKind::IK_TemplateId); 3106 else 3107 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3108 << Name << SS.getRange(); 3109 3110 SS.clear(); 3111 } 3112 3113 if (MSPropertyAttr) { 3114 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3115 BitWidth, InitStyle, AS, *MSPropertyAttr); 3116 if (!Member) 3117 return nullptr; 3118 isInstField = false; 3119 } else { 3120 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3121 BitWidth, InitStyle, AS); 3122 if (!Member) 3123 return nullptr; 3124 } 3125 3126 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3127 } else { 3128 Member = HandleDeclarator(S, D, TemplateParameterLists); 3129 if (!Member) 3130 return nullptr; 3131 3132 // Non-instance-fields can't have a bitfield. 3133 if (BitWidth) { 3134 if (Member->isInvalidDecl()) { 3135 // don't emit another diagnostic. 3136 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3137 // C++ 9.6p3: A bit-field shall not be a static member. 3138 // "static member 'A' cannot be a bit-field" 3139 Diag(Loc, diag::err_static_not_bitfield) 3140 << Name << BitWidth->getSourceRange(); 3141 } else if (isa<TypedefDecl>(Member)) { 3142 // "typedef member 'x' cannot be a bit-field" 3143 Diag(Loc, diag::err_typedef_not_bitfield) 3144 << Name << BitWidth->getSourceRange(); 3145 } else { 3146 // A function typedef ("typedef int f(); f a;"). 3147 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3148 Diag(Loc, diag::err_not_integral_type_bitfield) 3149 << Name << cast<ValueDecl>(Member)->getType() 3150 << BitWidth->getSourceRange(); 3151 } 3152 3153 BitWidth = nullptr; 3154 Member->setInvalidDecl(); 3155 } 3156 3157 NamedDecl *NonTemplateMember = Member; 3158 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3159 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3160 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3161 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3162 3163 Member->setAccess(AS); 3164 3165 // If we have declared a member function template or static data member 3166 // template, set the access of the templated declaration as well. 3167 if (NonTemplateMember != Member) 3168 NonTemplateMember->setAccess(AS); 3169 3170 // C++ [temp.deduct.guide]p3: 3171 // A deduction guide [...] for a member class template [shall be 3172 // declared] with the same access [as the template]. 3173 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3174 auto *TD = DG->getDeducedTemplate(); 3175 if (AS != TD->getAccess()) { 3176 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3177 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3178 << TD->getAccess(); 3179 const AccessSpecDecl *LastAccessSpec = nullptr; 3180 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3181 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3182 LastAccessSpec = AccessSpec; 3183 } 3184 assert(LastAccessSpec && "differing access with no access specifier"); 3185 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3186 << AS; 3187 } 3188 } 3189 } 3190 3191 if (VS.isOverrideSpecified()) 3192 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3193 if (VS.isFinalSpecified()) 3194 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3195 VS.isFinalSpelledSealed())); 3196 3197 if (VS.getLastLocation().isValid()) { 3198 // Update the end location of a method that has a virt-specifiers. 3199 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3200 MD->setRangeEnd(VS.getLastLocation()); 3201 } 3202 3203 CheckOverrideControl(Member); 3204 3205 assert((Name || isInstField) && "No identifier for non-field ?"); 3206 3207 if (isInstField) { 3208 FieldDecl *FD = cast<FieldDecl>(Member); 3209 FieldCollector->Add(FD); 3210 3211 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3212 // Remember all explicit private FieldDecls that have a name, no side 3213 // effects and are not part of a dependent type declaration. 3214 if (!FD->isImplicit() && FD->getDeclName() && 3215 FD->getAccess() == AS_private && 3216 !FD->hasAttr<UnusedAttr>() && 3217 !FD->getParent()->isDependentContext() && 3218 !InitializationHasSideEffects(*FD)) 3219 UnusedPrivateFields.insert(FD); 3220 } 3221 } 3222 3223 return Member; 3224 } 3225 3226 namespace { 3227 class UninitializedFieldVisitor 3228 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3229 Sema &S; 3230 // List of Decls to generate a warning on. Also remove Decls that become 3231 // initialized. 3232 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3233 // List of base classes of the record. Classes are removed after their 3234 // initializers. 3235 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3236 // Vector of decls to be removed from the Decl set prior to visiting the 3237 // nodes. These Decls may have been initialized in the prior initializer. 3238 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3239 // If non-null, add a note to the warning pointing back to the constructor. 3240 const CXXConstructorDecl *Constructor; 3241 // Variables to hold state when processing an initializer list. When 3242 // InitList is true, special case initialization of FieldDecls matching 3243 // InitListFieldDecl. 3244 bool InitList; 3245 FieldDecl *InitListFieldDecl; 3246 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3247 3248 public: 3249 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3250 UninitializedFieldVisitor(Sema &S, 3251 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3252 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3253 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3254 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3255 3256 // Returns true if the use of ME is not an uninitialized use. 3257 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3258 bool CheckReferenceOnly) { 3259 llvm::SmallVector<FieldDecl*, 4> Fields; 3260 bool ReferenceField = false; 3261 while (ME) { 3262 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3263 if (!FD) 3264 return false; 3265 Fields.push_back(FD); 3266 if (FD->getType()->isReferenceType()) 3267 ReferenceField = true; 3268 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3269 } 3270 3271 // Binding a reference to an uninitialized field is not an 3272 // uninitialized use. 3273 if (CheckReferenceOnly && !ReferenceField) 3274 return true; 3275 3276 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3277 // Discard the first field since it is the field decl that is being 3278 // initialized. 3279 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3280 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3281 } 3282 3283 for (auto UsedIter = UsedFieldIndex.begin(), 3284 UsedEnd = UsedFieldIndex.end(), 3285 OrigIter = InitFieldIndex.begin(), 3286 OrigEnd = InitFieldIndex.end(); 3287 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3288 if (*UsedIter < *OrigIter) 3289 return true; 3290 if (*UsedIter > *OrigIter) 3291 break; 3292 } 3293 3294 return false; 3295 } 3296 3297 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3298 bool AddressOf) { 3299 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3300 return; 3301 3302 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3303 // or union. 3304 MemberExpr *FieldME = ME; 3305 3306 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3307 3308 Expr *Base = ME; 3309 while (MemberExpr *SubME = 3310 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3311 3312 if (isa<VarDecl>(SubME->getMemberDecl())) 3313 return; 3314 3315 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3316 if (!FD->isAnonymousStructOrUnion()) 3317 FieldME = SubME; 3318 3319 if (!FieldME->getType().isPODType(S.Context)) 3320 AllPODFields = false; 3321 3322 Base = SubME->getBase(); 3323 } 3324 3325 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3326 return; 3327 3328 if (AddressOf && AllPODFields) 3329 return; 3330 3331 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3332 3333 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3334 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3335 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3336 } 3337 3338 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3339 QualType T = BaseCast->getType(); 3340 if (T->isPointerType() && 3341 BaseClasses.count(T->getPointeeType())) { 3342 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3343 << T->getPointeeType() << FoundVD; 3344 } 3345 } 3346 } 3347 3348 if (!Decls.count(FoundVD)) 3349 return; 3350 3351 const bool IsReference = FoundVD->getType()->isReferenceType(); 3352 3353 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3354 // Special checking for initializer lists. 3355 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3356 return; 3357 } 3358 } else { 3359 // Prevent double warnings on use of unbounded references. 3360 if (CheckReferenceOnly && !IsReference) 3361 return; 3362 } 3363 3364 unsigned diag = IsReference 3365 ? diag::warn_reference_field_is_uninit 3366 : diag::warn_field_is_uninit; 3367 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3368 if (Constructor) 3369 S.Diag(Constructor->getLocation(), 3370 diag::note_uninit_in_this_constructor) 3371 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3372 3373 } 3374 3375 void HandleValue(Expr *E, bool AddressOf) { 3376 E = E->IgnoreParens(); 3377 3378 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3379 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3380 AddressOf /*AddressOf*/); 3381 return; 3382 } 3383 3384 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3385 Visit(CO->getCond()); 3386 HandleValue(CO->getTrueExpr(), AddressOf); 3387 HandleValue(CO->getFalseExpr(), AddressOf); 3388 return; 3389 } 3390 3391 if (BinaryConditionalOperator *BCO = 3392 dyn_cast<BinaryConditionalOperator>(E)) { 3393 Visit(BCO->getCond()); 3394 HandleValue(BCO->getFalseExpr(), AddressOf); 3395 return; 3396 } 3397 3398 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3399 HandleValue(OVE->getSourceExpr(), AddressOf); 3400 return; 3401 } 3402 3403 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3404 switch (BO->getOpcode()) { 3405 default: 3406 break; 3407 case(BO_PtrMemD): 3408 case(BO_PtrMemI): 3409 HandleValue(BO->getLHS(), AddressOf); 3410 Visit(BO->getRHS()); 3411 return; 3412 case(BO_Comma): 3413 Visit(BO->getLHS()); 3414 HandleValue(BO->getRHS(), AddressOf); 3415 return; 3416 } 3417 } 3418 3419 Visit(E); 3420 } 3421 3422 void CheckInitListExpr(InitListExpr *ILE) { 3423 InitFieldIndex.push_back(0); 3424 for (auto Child : ILE->children()) { 3425 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3426 CheckInitListExpr(SubList); 3427 } else { 3428 Visit(Child); 3429 } 3430 ++InitFieldIndex.back(); 3431 } 3432 InitFieldIndex.pop_back(); 3433 } 3434 3435 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3436 FieldDecl *Field, const Type *BaseClass) { 3437 // Remove Decls that may have been initialized in the previous 3438 // initializer. 3439 for (ValueDecl* VD : DeclsToRemove) 3440 Decls.erase(VD); 3441 DeclsToRemove.clear(); 3442 3443 Constructor = FieldConstructor; 3444 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3445 3446 if (ILE && Field) { 3447 InitList = true; 3448 InitListFieldDecl = Field; 3449 InitFieldIndex.clear(); 3450 CheckInitListExpr(ILE); 3451 } else { 3452 InitList = false; 3453 Visit(E); 3454 } 3455 3456 if (Field) 3457 Decls.erase(Field); 3458 if (BaseClass) 3459 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3460 } 3461 3462 void VisitMemberExpr(MemberExpr *ME) { 3463 // All uses of unbounded reference fields will warn. 3464 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3465 } 3466 3467 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3468 if (E->getCastKind() == CK_LValueToRValue) { 3469 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3470 return; 3471 } 3472 3473 Inherited::VisitImplicitCastExpr(E); 3474 } 3475 3476 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3477 if (E->getConstructor()->isCopyConstructor()) { 3478 Expr *ArgExpr = E->getArg(0); 3479 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3480 if (ILE->getNumInits() == 1) 3481 ArgExpr = ILE->getInit(0); 3482 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3483 if (ICE->getCastKind() == CK_NoOp) 3484 ArgExpr = ICE->getSubExpr(); 3485 HandleValue(ArgExpr, false /*AddressOf*/); 3486 return; 3487 } 3488 Inherited::VisitCXXConstructExpr(E); 3489 } 3490 3491 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3492 Expr *Callee = E->getCallee(); 3493 if (isa<MemberExpr>(Callee)) { 3494 HandleValue(Callee, false /*AddressOf*/); 3495 for (auto Arg : E->arguments()) 3496 Visit(Arg); 3497 return; 3498 } 3499 3500 Inherited::VisitCXXMemberCallExpr(E); 3501 } 3502 3503 void VisitCallExpr(CallExpr *E) { 3504 // Treat std::move as a use. 3505 if (E->isCallToStdMove()) { 3506 HandleValue(E->getArg(0), /*AddressOf=*/false); 3507 return; 3508 } 3509 3510 Inherited::VisitCallExpr(E); 3511 } 3512 3513 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3514 Expr *Callee = E->getCallee(); 3515 3516 if (isa<UnresolvedLookupExpr>(Callee)) 3517 return Inherited::VisitCXXOperatorCallExpr(E); 3518 3519 Visit(Callee); 3520 for (auto Arg : E->arguments()) 3521 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3522 } 3523 3524 void VisitBinaryOperator(BinaryOperator *E) { 3525 // If a field assignment is detected, remove the field from the 3526 // uninitiailized field set. 3527 if (E->getOpcode() == BO_Assign) 3528 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3529 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3530 if (!FD->getType()->isReferenceType()) 3531 DeclsToRemove.push_back(FD); 3532 3533 if (E->isCompoundAssignmentOp()) { 3534 HandleValue(E->getLHS(), false /*AddressOf*/); 3535 Visit(E->getRHS()); 3536 return; 3537 } 3538 3539 Inherited::VisitBinaryOperator(E); 3540 } 3541 3542 void VisitUnaryOperator(UnaryOperator *E) { 3543 if (E->isIncrementDecrementOp()) { 3544 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3545 return; 3546 } 3547 if (E->getOpcode() == UO_AddrOf) { 3548 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3549 HandleValue(ME->getBase(), true /*AddressOf*/); 3550 return; 3551 } 3552 } 3553 3554 Inherited::VisitUnaryOperator(E); 3555 } 3556 }; 3557 3558 // Diagnose value-uses of fields to initialize themselves, e.g. 3559 // foo(foo) 3560 // where foo is not also a parameter to the constructor. 3561 // Also diagnose across field uninitialized use such as 3562 // x(y), y(x) 3563 // TODO: implement -Wuninitialized and fold this into that framework. 3564 static void DiagnoseUninitializedFields( 3565 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3566 3567 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3568 Constructor->getLocation())) { 3569 return; 3570 } 3571 3572 if (Constructor->isInvalidDecl()) 3573 return; 3574 3575 const CXXRecordDecl *RD = Constructor->getParent(); 3576 3577 if (RD->getDescribedClassTemplate()) 3578 return; 3579 3580 // Holds fields that are uninitialized. 3581 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3582 3583 // At the beginning, all fields are uninitialized. 3584 for (auto *I : RD->decls()) { 3585 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3586 UninitializedFields.insert(FD); 3587 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3588 UninitializedFields.insert(IFD->getAnonField()); 3589 } 3590 } 3591 3592 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3593 for (auto I : RD->bases()) 3594 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3595 3596 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3597 return; 3598 3599 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3600 UninitializedFields, 3601 UninitializedBaseClasses); 3602 3603 for (const auto *FieldInit : Constructor->inits()) { 3604 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3605 break; 3606 3607 Expr *InitExpr = FieldInit->getInit(); 3608 if (!InitExpr) 3609 continue; 3610 3611 if (CXXDefaultInitExpr *Default = 3612 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3613 InitExpr = Default->getExpr(); 3614 if (!InitExpr) 3615 continue; 3616 // In class initializers will point to the constructor. 3617 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3618 FieldInit->getAnyMember(), 3619 FieldInit->getBaseClass()); 3620 } else { 3621 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3622 FieldInit->getAnyMember(), 3623 FieldInit->getBaseClass()); 3624 } 3625 } 3626 } 3627 } // namespace 3628 3629 /// Enter a new C++ default initializer scope. After calling this, the 3630 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3631 /// parsing or instantiating the initializer failed. 3632 void Sema::ActOnStartCXXInClassMemberInitializer() { 3633 // Create a synthetic function scope to represent the call to the constructor 3634 // that notionally surrounds a use of this initializer. 3635 PushFunctionScope(); 3636 } 3637 3638 /// This is invoked after parsing an in-class initializer for a 3639 /// non-static C++ class member, and after instantiating an in-class initializer 3640 /// in a class template. Such actions are deferred until the class is complete. 3641 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3642 SourceLocation InitLoc, 3643 Expr *InitExpr) { 3644 // Pop the notional constructor scope we created earlier. 3645 PopFunctionScopeInfo(nullptr, D); 3646 3647 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3648 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3649 "must set init style when field is created"); 3650 3651 if (!InitExpr) { 3652 D->setInvalidDecl(); 3653 if (FD) 3654 FD->removeInClassInitializer(); 3655 return; 3656 } 3657 3658 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3659 FD->setInvalidDecl(); 3660 FD->removeInClassInitializer(); 3661 return; 3662 } 3663 3664 ExprResult Init = InitExpr; 3665 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3666 InitializedEntity Entity = 3667 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3668 InitializationKind Kind = 3669 FD->getInClassInitStyle() == ICIS_ListInit 3670 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3671 InitExpr->getBeginLoc(), 3672 InitExpr->getEndLoc()) 3673 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3674 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3675 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3676 if (Init.isInvalid()) { 3677 FD->setInvalidDecl(); 3678 return; 3679 } 3680 } 3681 3682 // C++11 [class.base.init]p7: 3683 // The initialization of each base and member constitutes a 3684 // full-expression. 3685 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3686 if (Init.isInvalid()) { 3687 FD->setInvalidDecl(); 3688 return; 3689 } 3690 3691 InitExpr = Init.get(); 3692 3693 FD->setInClassInitializer(InitExpr); 3694 } 3695 3696 /// Find the direct and/or virtual base specifiers that 3697 /// correspond to the given base type, for use in base initialization 3698 /// within a constructor. 3699 static bool FindBaseInitializer(Sema &SemaRef, 3700 CXXRecordDecl *ClassDecl, 3701 QualType BaseType, 3702 const CXXBaseSpecifier *&DirectBaseSpec, 3703 const CXXBaseSpecifier *&VirtualBaseSpec) { 3704 // First, check for a direct base class. 3705 DirectBaseSpec = nullptr; 3706 for (const auto &Base : ClassDecl->bases()) { 3707 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3708 // We found a direct base of this type. That's what we're 3709 // initializing. 3710 DirectBaseSpec = &Base; 3711 break; 3712 } 3713 } 3714 3715 // Check for a virtual base class. 3716 // FIXME: We might be able to short-circuit this if we know in advance that 3717 // there are no virtual bases. 3718 VirtualBaseSpec = nullptr; 3719 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3720 // We haven't found a base yet; search the class hierarchy for a 3721 // virtual base class. 3722 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3723 /*DetectVirtual=*/false); 3724 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3725 SemaRef.Context.getTypeDeclType(ClassDecl), 3726 BaseType, Paths)) { 3727 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3728 Path != Paths.end(); ++Path) { 3729 if (Path->back().Base->isVirtual()) { 3730 VirtualBaseSpec = Path->back().Base; 3731 break; 3732 } 3733 } 3734 } 3735 } 3736 3737 return DirectBaseSpec || VirtualBaseSpec; 3738 } 3739 3740 /// Handle a C++ member initializer using braced-init-list syntax. 3741 MemInitResult 3742 Sema::ActOnMemInitializer(Decl *ConstructorD, 3743 Scope *S, 3744 CXXScopeSpec &SS, 3745 IdentifierInfo *MemberOrBase, 3746 ParsedType TemplateTypeTy, 3747 const DeclSpec &DS, 3748 SourceLocation IdLoc, 3749 Expr *InitList, 3750 SourceLocation EllipsisLoc) { 3751 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3752 DS, IdLoc, InitList, 3753 EllipsisLoc); 3754 } 3755 3756 /// Handle a C++ member initializer using parentheses syntax. 3757 MemInitResult 3758 Sema::ActOnMemInitializer(Decl *ConstructorD, 3759 Scope *S, 3760 CXXScopeSpec &SS, 3761 IdentifierInfo *MemberOrBase, 3762 ParsedType TemplateTypeTy, 3763 const DeclSpec &DS, 3764 SourceLocation IdLoc, 3765 SourceLocation LParenLoc, 3766 ArrayRef<Expr *> Args, 3767 SourceLocation RParenLoc, 3768 SourceLocation EllipsisLoc) { 3769 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 3770 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3771 DS, IdLoc, List, EllipsisLoc); 3772 } 3773 3774 namespace { 3775 3776 // Callback to only accept typo corrections that can be a valid C++ member 3777 // intializer: either a non-static field member or a base class. 3778 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3779 public: 3780 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3781 : ClassDecl(ClassDecl) {} 3782 3783 bool ValidateCandidate(const TypoCorrection &candidate) override { 3784 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3785 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3786 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3787 return isa<TypeDecl>(ND); 3788 } 3789 return false; 3790 } 3791 3792 private: 3793 CXXRecordDecl *ClassDecl; 3794 }; 3795 3796 } 3797 3798 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 3799 CXXScopeSpec &SS, 3800 ParsedType TemplateTypeTy, 3801 IdentifierInfo *MemberOrBase) { 3802 if (SS.getScopeRep() || TemplateTypeTy) 3803 return nullptr; 3804 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3805 if (Result.empty()) 3806 return nullptr; 3807 ValueDecl *Member; 3808 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3809 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 3810 return Member; 3811 return nullptr; 3812 } 3813 3814 /// Handle a C++ member initializer. 3815 MemInitResult 3816 Sema::BuildMemInitializer(Decl *ConstructorD, 3817 Scope *S, 3818 CXXScopeSpec &SS, 3819 IdentifierInfo *MemberOrBase, 3820 ParsedType TemplateTypeTy, 3821 const DeclSpec &DS, 3822 SourceLocation IdLoc, 3823 Expr *Init, 3824 SourceLocation EllipsisLoc) { 3825 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3826 if (!Res.isUsable()) 3827 return true; 3828 Init = Res.get(); 3829 3830 if (!ConstructorD) 3831 return true; 3832 3833 AdjustDeclIfTemplate(ConstructorD); 3834 3835 CXXConstructorDecl *Constructor 3836 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3837 if (!Constructor) { 3838 // The user wrote a constructor initializer on a function that is 3839 // not a C++ constructor. Ignore the error for now, because we may 3840 // have more member initializers coming; we'll diagnose it just 3841 // once in ActOnMemInitializers. 3842 return true; 3843 } 3844 3845 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3846 3847 // C++ [class.base.init]p2: 3848 // Names in a mem-initializer-id are looked up in the scope of the 3849 // constructor's class and, if not found in that scope, are looked 3850 // up in the scope containing the constructor's definition. 3851 // [Note: if the constructor's class contains a member with the 3852 // same name as a direct or virtual base class of the class, a 3853 // mem-initializer-id naming the member or base class and composed 3854 // of a single identifier refers to the class member. A 3855 // mem-initializer-id for the hidden base class may be specified 3856 // using a qualified name. ] 3857 3858 // Look for a member, first. 3859 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 3860 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 3861 if (EllipsisLoc.isValid()) 3862 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3863 << MemberOrBase 3864 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3865 3866 return BuildMemberInitializer(Member, Init, IdLoc); 3867 } 3868 // It didn't name a member, so see if it names a class. 3869 QualType BaseType; 3870 TypeSourceInfo *TInfo = nullptr; 3871 3872 if (TemplateTypeTy) { 3873 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3874 } else if (DS.getTypeSpecType() == TST_decltype) { 3875 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3876 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3877 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3878 return true; 3879 } else { 3880 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3881 LookupParsedName(R, S, &SS); 3882 3883 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3884 if (!TyD) { 3885 if (R.isAmbiguous()) return true; 3886 3887 // We don't want access-control diagnostics here. 3888 R.suppressDiagnostics(); 3889 3890 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3891 bool NotUnknownSpecialization = false; 3892 DeclContext *DC = computeDeclContext(SS, false); 3893 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3894 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3895 3896 if (!NotUnknownSpecialization) { 3897 // When the scope specifier can refer to a member of an unknown 3898 // specialization, we take it as a type name. 3899 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3900 SS.getWithLocInContext(Context), 3901 *MemberOrBase, IdLoc); 3902 if (BaseType.isNull()) 3903 return true; 3904 3905 TInfo = Context.CreateTypeSourceInfo(BaseType); 3906 DependentNameTypeLoc TL = 3907 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3908 if (!TL.isNull()) { 3909 TL.setNameLoc(IdLoc); 3910 TL.setElaboratedKeywordLoc(SourceLocation()); 3911 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3912 } 3913 3914 R.clear(); 3915 R.setLookupName(MemberOrBase); 3916 } 3917 } 3918 3919 // If no results were found, try to correct typos. 3920 TypoCorrection Corr; 3921 if (R.empty() && BaseType.isNull() && 3922 (Corr = CorrectTypo( 3923 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3924 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3925 CTK_ErrorRecovery, ClassDecl))) { 3926 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3927 // We have found a non-static data member with a similar 3928 // name to what was typed; complain and initialize that 3929 // member. 3930 diagnoseTypo(Corr, 3931 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3932 << MemberOrBase << true); 3933 return BuildMemberInitializer(Member, Init, IdLoc); 3934 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3935 const CXXBaseSpecifier *DirectBaseSpec; 3936 const CXXBaseSpecifier *VirtualBaseSpec; 3937 if (FindBaseInitializer(*this, ClassDecl, 3938 Context.getTypeDeclType(Type), 3939 DirectBaseSpec, VirtualBaseSpec)) { 3940 // We have found a direct or virtual base class with a 3941 // similar name to what was typed; complain and initialize 3942 // that base class. 3943 diagnoseTypo(Corr, 3944 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3945 << MemberOrBase << false, 3946 PDiag() /*Suppress note, we provide our own.*/); 3947 3948 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3949 : VirtualBaseSpec; 3950 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 3951 << BaseSpec->getType() << BaseSpec->getSourceRange(); 3952 3953 TyD = Type; 3954 } 3955 } 3956 } 3957 3958 if (!TyD && BaseType.isNull()) { 3959 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3960 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3961 return true; 3962 } 3963 } 3964 3965 if (BaseType.isNull()) { 3966 BaseType = Context.getTypeDeclType(TyD); 3967 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3968 if (SS.isSet()) { 3969 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3970 BaseType); 3971 TInfo = Context.CreateTypeSourceInfo(BaseType); 3972 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3973 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3974 TL.setElaboratedKeywordLoc(SourceLocation()); 3975 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3976 } 3977 } 3978 } 3979 3980 if (!TInfo) 3981 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3982 3983 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3984 } 3985 3986 MemInitResult 3987 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3988 SourceLocation IdLoc) { 3989 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3990 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3991 assert((DirectMember || IndirectMember) && 3992 "Member must be a FieldDecl or IndirectFieldDecl"); 3993 3994 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3995 return true; 3996 3997 if (Member->isInvalidDecl()) 3998 return true; 3999 4000 MultiExprArg Args; 4001 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4002 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4003 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4004 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4005 } else { 4006 // Template instantiation doesn't reconstruct ParenListExprs for us. 4007 Args = Init; 4008 } 4009 4010 SourceRange InitRange = Init->getSourceRange(); 4011 4012 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4013 // Can't check initialization for a member of dependent type or when 4014 // any of the arguments are type-dependent expressions. 4015 DiscardCleanupsInEvaluationContext(); 4016 } else { 4017 bool InitList = false; 4018 if (isa<InitListExpr>(Init)) { 4019 InitList = true; 4020 Args = Init; 4021 } 4022 4023 // Initialize the member. 4024 InitializedEntity MemberEntity = 4025 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4026 : InitializedEntity::InitializeMember(IndirectMember, 4027 nullptr); 4028 InitializationKind Kind = 4029 InitList ? InitializationKind::CreateDirectList( 4030 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4031 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4032 InitRange.getEnd()); 4033 4034 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4035 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4036 nullptr); 4037 if (MemberInit.isInvalid()) 4038 return true; 4039 4040 // C++11 [class.base.init]p7: 4041 // The initialization of each base and member constitutes a 4042 // full-expression. 4043 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4044 /*DiscardedValue*/ false); 4045 if (MemberInit.isInvalid()) 4046 return true; 4047 4048 Init = MemberInit.get(); 4049 } 4050 4051 if (DirectMember) { 4052 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4053 InitRange.getBegin(), Init, 4054 InitRange.getEnd()); 4055 } else { 4056 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4057 InitRange.getBegin(), Init, 4058 InitRange.getEnd()); 4059 } 4060 } 4061 4062 MemInitResult 4063 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4064 CXXRecordDecl *ClassDecl) { 4065 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4066 if (!LangOpts.CPlusPlus11) 4067 return Diag(NameLoc, diag::err_delegating_ctor) 4068 << TInfo->getTypeLoc().getLocalSourceRange(); 4069 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4070 4071 bool InitList = true; 4072 MultiExprArg Args = Init; 4073 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4074 InitList = false; 4075 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4076 } 4077 4078 SourceRange InitRange = Init->getSourceRange(); 4079 // Initialize the object. 4080 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4081 QualType(ClassDecl->getTypeForDecl(), 0)); 4082 InitializationKind Kind = 4083 InitList ? InitializationKind::CreateDirectList( 4084 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4085 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4086 InitRange.getEnd()); 4087 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4088 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4089 Args, nullptr); 4090 if (DelegationInit.isInvalid()) 4091 return true; 4092 4093 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4094 "Delegating constructor with no target?"); 4095 4096 // C++11 [class.base.init]p7: 4097 // The initialization of each base and member constitutes a 4098 // full-expression. 4099 DelegationInit = ActOnFinishFullExpr( 4100 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4101 if (DelegationInit.isInvalid()) 4102 return true; 4103 4104 // If we are in a dependent context, template instantiation will 4105 // perform this type-checking again. Just save the arguments that we 4106 // received in a ParenListExpr. 4107 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4108 // of the information that we have about the base 4109 // initializer. However, deconstructing the ASTs is a dicey process, 4110 // and this approach is far more likely to get the corner cases right. 4111 if (CurContext->isDependentContext()) 4112 DelegationInit = Init; 4113 4114 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4115 DelegationInit.getAs<Expr>(), 4116 InitRange.getEnd()); 4117 } 4118 4119 MemInitResult 4120 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4121 Expr *Init, CXXRecordDecl *ClassDecl, 4122 SourceLocation EllipsisLoc) { 4123 SourceLocation BaseLoc 4124 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4125 4126 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4127 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4128 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4129 4130 // C++ [class.base.init]p2: 4131 // [...] Unless the mem-initializer-id names a nonstatic data 4132 // member of the constructor's class or a direct or virtual base 4133 // of that class, the mem-initializer is ill-formed. A 4134 // mem-initializer-list can initialize a base class using any 4135 // name that denotes that base class type. 4136 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4137 4138 SourceRange InitRange = Init->getSourceRange(); 4139 if (EllipsisLoc.isValid()) { 4140 // This is a pack expansion. 4141 if (!BaseType->containsUnexpandedParameterPack()) { 4142 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4143 << SourceRange(BaseLoc, InitRange.getEnd()); 4144 4145 EllipsisLoc = SourceLocation(); 4146 } 4147 } else { 4148 // Check for any unexpanded parameter packs. 4149 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4150 return true; 4151 4152 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4153 return true; 4154 } 4155 4156 // Check for direct and virtual base classes. 4157 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4158 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4159 if (!Dependent) { 4160 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4161 BaseType)) 4162 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4163 4164 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4165 VirtualBaseSpec); 4166 4167 // C++ [base.class.init]p2: 4168 // Unless the mem-initializer-id names a nonstatic data member of the 4169 // constructor's class or a direct or virtual base of that class, the 4170 // mem-initializer is ill-formed. 4171 if (!DirectBaseSpec && !VirtualBaseSpec) { 4172 // If the class has any dependent bases, then it's possible that 4173 // one of those types will resolve to the same type as 4174 // BaseType. Therefore, just treat this as a dependent base 4175 // class initialization. FIXME: Should we try to check the 4176 // initialization anyway? It seems odd. 4177 if (ClassDecl->hasAnyDependentBases()) 4178 Dependent = true; 4179 else 4180 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4181 << BaseType << Context.getTypeDeclType(ClassDecl) 4182 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4183 } 4184 } 4185 4186 if (Dependent) { 4187 DiscardCleanupsInEvaluationContext(); 4188 4189 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4190 /*IsVirtual=*/false, 4191 InitRange.getBegin(), Init, 4192 InitRange.getEnd(), EllipsisLoc); 4193 } 4194 4195 // C++ [base.class.init]p2: 4196 // If a mem-initializer-id is ambiguous because it designates both 4197 // a direct non-virtual base class and an inherited virtual base 4198 // class, the mem-initializer is ill-formed. 4199 if (DirectBaseSpec && VirtualBaseSpec) 4200 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4201 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4202 4203 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4204 if (!BaseSpec) 4205 BaseSpec = VirtualBaseSpec; 4206 4207 // Initialize the base. 4208 bool InitList = true; 4209 MultiExprArg Args = Init; 4210 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4211 InitList = false; 4212 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4213 } 4214 4215 InitializedEntity BaseEntity = 4216 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4217 InitializationKind Kind = 4218 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4219 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4220 InitRange.getEnd()); 4221 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4222 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4223 if (BaseInit.isInvalid()) 4224 return true; 4225 4226 // C++11 [class.base.init]p7: 4227 // The initialization of each base and member constitutes a 4228 // full-expression. 4229 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4230 /*DiscardedValue*/ false); 4231 if (BaseInit.isInvalid()) 4232 return true; 4233 4234 // If we are in a dependent context, template instantiation will 4235 // perform this type-checking again. Just save the arguments that we 4236 // received in a ParenListExpr. 4237 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4238 // of the information that we have about the base 4239 // initializer. However, deconstructing the ASTs is a dicey process, 4240 // and this approach is far more likely to get the corner cases right. 4241 if (CurContext->isDependentContext()) 4242 BaseInit = Init; 4243 4244 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4245 BaseSpec->isVirtual(), 4246 InitRange.getBegin(), 4247 BaseInit.getAs<Expr>(), 4248 InitRange.getEnd(), EllipsisLoc); 4249 } 4250 4251 // Create a static_cast\<T&&>(expr). 4252 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4253 if (T.isNull()) T = E->getType(); 4254 QualType TargetType = SemaRef.BuildReferenceType( 4255 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4256 SourceLocation ExprLoc = E->getBeginLoc(); 4257 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4258 TargetType, ExprLoc); 4259 4260 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4261 SourceRange(ExprLoc, ExprLoc), 4262 E->getSourceRange()).get(); 4263 } 4264 4265 /// ImplicitInitializerKind - How an implicit base or member initializer should 4266 /// initialize its base or member. 4267 enum ImplicitInitializerKind { 4268 IIK_Default, 4269 IIK_Copy, 4270 IIK_Move, 4271 IIK_Inherit 4272 }; 4273 4274 static bool 4275 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4276 ImplicitInitializerKind ImplicitInitKind, 4277 CXXBaseSpecifier *BaseSpec, 4278 bool IsInheritedVirtualBase, 4279 CXXCtorInitializer *&CXXBaseInit) { 4280 InitializedEntity InitEntity 4281 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4282 IsInheritedVirtualBase); 4283 4284 ExprResult BaseInit; 4285 4286 switch (ImplicitInitKind) { 4287 case IIK_Inherit: 4288 case IIK_Default: { 4289 InitializationKind InitKind 4290 = InitializationKind::CreateDefault(Constructor->getLocation()); 4291 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4292 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4293 break; 4294 } 4295 4296 case IIK_Move: 4297 case IIK_Copy: { 4298 bool Moving = ImplicitInitKind == IIK_Move; 4299 ParmVarDecl *Param = Constructor->getParamDecl(0); 4300 QualType ParamType = Param->getType().getNonReferenceType(); 4301 4302 Expr *CopyCtorArg = 4303 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4304 SourceLocation(), Param, false, 4305 Constructor->getLocation(), ParamType, 4306 VK_LValue, nullptr); 4307 4308 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4309 4310 // Cast to the base class to avoid ambiguities. 4311 QualType ArgTy = 4312 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4313 ParamType.getQualifiers()); 4314 4315 if (Moving) { 4316 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4317 } 4318 4319 CXXCastPath BasePath; 4320 BasePath.push_back(BaseSpec); 4321 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4322 CK_UncheckedDerivedToBase, 4323 Moving ? VK_XValue : VK_LValue, 4324 &BasePath).get(); 4325 4326 InitializationKind InitKind 4327 = InitializationKind::CreateDirect(Constructor->getLocation(), 4328 SourceLocation(), SourceLocation()); 4329 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4330 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4331 break; 4332 } 4333 } 4334 4335 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4336 if (BaseInit.isInvalid()) 4337 return true; 4338 4339 CXXBaseInit = 4340 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4341 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4342 SourceLocation()), 4343 BaseSpec->isVirtual(), 4344 SourceLocation(), 4345 BaseInit.getAs<Expr>(), 4346 SourceLocation(), 4347 SourceLocation()); 4348 4349 return false; 4350 } 4351 4352 static bool RefersToRValueRef(Expr *MemRef) { 4353 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4354 return Referenced->getType()->isRValueReferenceType(); 4355 } 4356 4357 static bool 4358 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4359 ImplicitInitializerKind ImplicitInitKind, 4360 FieldDecl *Field, IndirectFieldDecl *Indirect, 4361 CXXCtorInitializer *&CXXMemberInit) { 4362 if (Field->isInvalidDecl()) 4363 return true; 4364 4365 SourceLocation Loc = Constructor->getLocation(); 4366 4367 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4368 bool Moving = ImplicitInitKind == IIK_Move; 4369 ParmVarDecl *Param = Constructor->getParamDecl(0); 4370 QualType ParamType = Param->getType().getNonReferenceType(); 4371 4372 // Suppress copying zero-width bitfields. 4373 if (Field->isZeroLengthBitField(SemaRef.Context)) 4374 return false; 4375 4376 Expr *MemberExprBase = 4377 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4378 SourceLocation(), Param, false, 4379 Loc, ParamType, VK_LValue, nullptr); 4380 4381 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4382 4383 if (Moving) { 4384 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4385 } 4386 4387 // Build a reference to this field within the parameter. 4388 CXXScopeSpec SS; 4389 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4390 Sema::LookupMemberName); 4391 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4392 : cast<ValueDecl>(Field), AS_public); 4393 MemberLookup.resolveKind(); 4394 ExprResult CtorArg 4395 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4396 ParamType, Loc, 4397 /*IsArrow=*/false, 4398 SS, 4399 /*TemplateKWLoc=*/SourceLocation(), 4400 /*FirstQualifierInScope=*/nullptr, 4401 MemberLookup, 4402 /*TemplateArgs=*/nullptr, 4403 /*S*/nullptr); 4404 if (CtorArg.isInvalid()) 4405 return true; 4406 4407 // C++11 [class.copy]p15: 4408 // - if a member m has rvalue reference type T&&, it is direct-initialized 4409 // with static_cast<T&&>(x.m); 4410 if (RefersToRValueRef(CtorArg.get())) { 4411 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4412 } 4413 4414 InitializedEntity Entity = 4415 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4416 /*Implicit*/ true) 4417 : InitializedEntity::InitializeMember(Field, nullptr, 4418 /*Implicit*/ true); 4419 4420 // Direct-initialize to use the copy constructor. 4421 InitializationKind InitKind = 4422 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4423 4424 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4425 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4426 ExprResult MemberInit = 4427 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4428 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4429 if (MemberInit.isInvalid()) 4430 return true; 4431 4432 if (Indirect) 4433 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4434 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4435 else 4436 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4437 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4438 return false; 4439 } 4440 4441 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4442 "Unhandled implicit init kind!"); 4443 4444 QualType FieldBaseElementType = 4445 SemaRef.Context.getBaseElementType(Field->getType()); 4446 4447 if (FieldBaseElementType->isRecordType()) { 4448 InitializedEntity InitEntity = 4449 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4450 /*Implicit*/ true) 4451 : InitializedEntity::InitializeMember(Field, nullptr, 4452 /*Implicit*/ true); 4453 InitializationKind InitKind = 4454 InitializationKind::CreateDefault(Loc); 4455 4456 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4457 ExprResult MemberInit = 4458 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4459 4460 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4461 if (MemberInit.isInvalid()) 4462 return true; 4463 4464 if (Indirect) 4465 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4466 Indirect, Loc, 4467 Loc, 4468 MemberInit.get(), 4469 Loc); 4470 else 4471 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4472 Field, Loc, Loc, 4473 MemberInit.get(), 4474 Loc); 4475 return false; 4476 } 4477 4478 if (!Field->getParent()->isUnion()) { 4479 if (FieldBaseElementType->isReferenceType()) { 4480 SemaRef.Diag(Constructor->getLocation(), 4481 diag::err_uninitialized_member_in_ctor) 4482 << (int)Constructor->isImplicit() 4483 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4484 << 0 << Field->getDeclName(); 4485 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4486 return true; 4487 } 4488 4489 if (FieldBaseElementType.isConstQualified()) { 4490 SemaRef.Diag(Constructor->getLocation(), 4491 diag::err_uninitialized_member_in_ctor) 4492 << (int)Constructor->isImplicit() 4493 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4494 << 1 << Field->getDeclName(); 4495 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4496 return true; 4497 } 4498 } 4499 4500 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4501 // ARC and Weak: 4502 // Default-initialize Objective-C pointers to NULL. 4503 CXXMemberInit 4504 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4505 Loc, Loc, 4506 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4507 Loc); 4508 return false; 4509 } 4510 4511 // Nothing to initialize. 4512 CXXMemberInit = nullptr; 4513 return false; 4514 } 4515 4516 namespace { 4517 struct BaseAndFieldInfo { 4518 Sema &S; 4519 CXXConstructorDecl *Ctor; 4520 bool AnyErrorsInInits; 4521 ImplicitInitializerKind IIK; 4522 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4523 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4524 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4525 4526 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4527 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4528 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4529 if (Ctor->getInheritedConstructor()) 4530 IIK = IIK_Inherit; 4531 else if (Generated && Ctor->isCopyConstructor()) 4532 IIK = IIK_Copy; 4533 else if (Generated && Ctor->isMoveConstructor()) 4534 IIK = IIK_Move; 4535 else 4536 IIK = IIK_Default; 4537 } 4538 4539 bool isImplicitCopyOrMove() const { 4540 switch (IIK) { 4541 case IIK_Copy: 4542 case IIK_Move: 4543 return true; 4544 4545 case IIK_Default: 4546 case IIK_Inherit: 4547 return false; 4548 } 4549 4550 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4551 } 4552 4553 bool addFieldInitializer(CXXCtorInitializer *Init) { 4554 AllToInit.push_back(Init); 4555 4556 // Check whether this initializer makes the field "used". 4557 if (Init->getInit()->HasSideEffects(S.Context)) 4558 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4559 4560 return false; 4561 } 4562 4563 bool isInactiveUnionMember(FieldDecl *Field) { 4564 RecordDecl *Record = Field->getParent(); 4565 if (!Record->isUnion()) 4566 return false; 4567 4568 if (FieldDecl *Active = 4569 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4570 return Active != Field->getCanonicalDecl(); 4571 4572 // In an implicit copy or move constructor, ignore any in-class initializer. 4573 if (isImplicitCopyOrMove()) 4574 return true; 4575 4576 // If there's no explicit initialization, the field is active only if it 4577 // has an in-class initializer... 4578 if (Field->hasInClassInitializer()) 4579 return false; 4580 // ... or it's an anonymous struct or union whose class has an in-class 4581 // initializer. 4582 if (!Field->isAnonymousStructOrUnion()) 4583 return true; 4584 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4585 return !FieldRD->hasInClassInitializer(); 4586 } 4587 4588 /// Determine whether the given field is, or is within, a union member 4589 /// that is inactive (because there was an initializer given for a different 4590 /// member of the union, or because the union was not initialized at all). 4591 bool isWithinInactiveUnionMember(FieldDecl *Field, 4592 IndirectFieldDecl *Indirect) { 4593 if (!Indirect) 4594 return isInactiveUnionMember(Field); 4595 4596 for (auto *C : Indirect->chain()) { 4597 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4598 if (Field && isInactiveUnionMember(Field)) 4599 return true; 4600 } 4601 return false; 4602 } 4603 }; 4604 } 4605 4606 /// Determine whether the given type is an incomplete or zero-lenfgth 4607 /// array type. 4608 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4609 if (T->isIncompleteArrayType()) 4610 return true; 4611 4612 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4613 if (!ArrayT->getSize()) 4614 return true; 4615 4616 T = ArrayT->getElementType(); 4617 } 4618 4619 return false; 4620 } 4621 4622 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4623 FieldDecl *Field, 4624 IndirectFieldDecl *Indirect = nullptr) { 4625 if (Field->isInvalidDecl()) 4626 return false; 4627 4628 // Overwhelmingly common case: we have a direct initializer for this field. 4629 if (CXXCtorInitializer *Init = 4630 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4631 return Info.addFieldInitializer(Init); 4632 4633 // C++11 [class.base.init]p8: 4634 // if the entity is a non-static data member that has a 4635 // brace-or-equal-initializer and either 4636 // -- the constructor's class is a union and no other variant member of that 4637 // union is designated by a mem-initializer-id or 4638 // -- the constructor's class is not a union, and, if the entity is a member 4639 // of an anonymous union, no other member of that union is designated by 4640 // a mem-initializer-id, 4641 // the entity is initialized as specified in [dcl.init]. 4642 // 4643 // We also apply the same rules to handle anonymous structs within anonymous 4644 // unions. 4645 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4646 return false; 4647 4648 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4649 ExprResult DIE = 4650 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4651 if (DIE.isInvalid()) 4652 return true; 4653 4654 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4655 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4656 4657 CXXCtorInitializer *Init; 4658 if (Indirect) 4659 Init = new (SemaRef.Context) 4660 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4661 SourceLocation(), DIE.get(), SourceLocation()); 4662 else 4663 Init = new (SemaRef.Context) 4664 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4665 SourceLocation(), DIE.get(), SourceLocation()); 4666 return Info.addFieldInitializer(Init); 4667 } 4668 4669 // Don't initialize incomplete or zero-length arrays. 4670 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4671 return false; 4672 4673 // Don't try to build an implicit initializer if there were semantic 4674 // errors in any of the initializers (and therefore we might be 4675 // missing some that the user actually wrote). 4676 if (Info.AnyErrorsInInits) 4677 return false; 4678 4679 CXXCtorInitializer *Init = nullptr; 4680 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4681 Indirect, Init)) 4682 return true; 4683 4684 if (!Init) 4685 return false; 4686 4687 return Info.addFieldInitializer(Init); 4688 } 4689 4690 bool 4691 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4692 CXXCtorInitializer *Initializer) { 4693 assert(Initializer->isDelegatingInitializer()); 4694 Constructor->setNumCtorInitializers(1); 4695 CXXCtorInitializer **initializer = 4696 new (Context) CXXCtorInitializer*[1]; 4697 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4698 Constructor->setCtorInitializers(initializer); 4699 4700 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4701 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4702 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4703 } 4704 4705 DelegatingCtorDecls.push_back(Constructor); 4706 4707 DiagnoseUninitializedFields(*this, Constructor); 4708 4709 return false; 4710 } 4711 4712 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4713 ArrayRef<CXXCtorInitializer *> Initializers) { 4714 if (Constructor->isDependentContext()) { 4715 // Just store the initializers as written, they will be checked during 4716 // instantiation. 4717 if (!Initializers.empty()) { 4718 Constructor->setNumCtorInitializers(Initializers.size()); 4719 CXXCtorInitializer **baseOrMemberInitializers = 4720 new (Context) CXXCtorInitializer*[Initializers.size()]; 4721 memcpy(baseOrMemberInitializers, Initializers.data(), 4722 Initializers.size() * sizeof(CXXCtorInitializer*)); 4723 Constructor->setCtorInitializers(baseOrMemberInitializers); 4724 } 4725 4726 // Let template instantiation know whether we had errors. 4727 if (AnyErrors) 4728 Constructor->setInvalidDecl(); 4729 4730 return false; 4731 } 4732 4733 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4734 4735 // We need to build the initializer AST according to order of construction 4736 // and not what user specified in the Initializers list. 4737 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4738 if (!ClassDecl) 4739 return true; 4740 4741 bool HadError = false; 4742 4743 for (unsigned i = 0; i < Initializers.size(); i++) { 4744 CXXCtorInitializer *Member = Initializers[i]; 4745 4746 if (Member->isBaseInitializer()) 4747 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4748 else { 4749 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4750 4751 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4752 for (auto *C : F->chain()) { 4753 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4754 if (FD && FD->getParent()->isUnion()) 4755 Info.ActiveUnionMember.insert(std::make_pair( 4756 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4757 } 4758 } else if (FieldDecl *FD = Member->getMember()) { 4759 if (FD->getParent()->isUnion()) 4760 Info.ActiveUnionMember.insert(std::make_pair( 4761 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4762 } 4763 } 4764 } 4765 4766 // Keep track of the direct virtual bases. 4767 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4768 for (auto &I : ClassDecl->bases()) { 4769 if (I.isVirtual()) 4770 DirectVBases.insert(&I); 4771 } 4772 4773 // Push virtual bases before others. 4774 for (auto &VBase : ClassDecl->vbases()) { 4775 if (CXXCtorInitializer *Value 4776 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4777 // [class.base.init]p7, per DR257: 4778 // A mem-initializer where the mem-initializer-id names a virtual base 4779 // class is ignored during execution of a constructor of any class that 4780 // is not the most derived class. 4781 if (ClassDecl->isAbstract()) { 4782 // FIXME: Provide a fixit to remove the base specifier. This requires 4783 // tracking the location of the associated comma for a base specifier. 4784 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4785 << VBase.getType() << ClassDecl; 4786 DiagnoseAbstractType(ClassDecl); 4787 } 4788 4789 Info.AllToInit.push_back(Value); 4790 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4791 // [class.base.init]p8, per DR257: 4792 // If a given [...] base class is not named by a mem-initializer-id 4793 // [...] and the entity is not a virtual base class of an abstract 4794 // class, then [...] the entity is default-initialized. 4795 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4796 CXXCtorInitializer *CXXBaseInit; 4797 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4798 &VBase, IsInheritedVirtualBase, 4799 CXXBaseInit)) { 4800 HadError = true; 4801 continue; 4802 } 4803 4804 Info.AllToInit.push_back(CXXBaseInit); 4805 } 4806 } 4807 4808 // Non-virtual bases. 4809 for (auto &Base : ClassDecl->bases()) { 4810 // Virtuals are in the virtual base list and already constructed. 4811 if (Base.isVirtual()) 4812 continue; 4813 4814 if (CXXCtorInitializer *Value 4815 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4816 Info.AllToInit.push_back(Value); 4817 } else if (!AnyErrors) { 4818 CXXCtorInitializer *CXXBaseInit; 4819 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4820 &Base, /*IsInheritedVirtualBase=*/false, 4821 CXXBaseInit)) { 4822 HadError = true; 4823 continue; 4824 } 4825 4826 Info.AllToInit.push_back(CXXBaseInit); 4827 } 4828 } 4829 4830 // Fields. 4831 for (auto *Mem : ClassDecl->decls()) { 4832 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4833 // C++ [class.bit]p2: 4834 // A declaration for a bit-field that omits the identifier declares an 4835 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4836 // initialized. 4837 if (F->isUnnamedBitfield()) 4838 continue; 4839 4840 // If we're not generating the implicit copy/move constructor, then we'll 4841 // handle anonymous struct/union fields based on their individual 4842 // indirect fields. 4843 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4844 continue; 4845 4846 if (CollectFieldInitializer(*this, Info, F)) 4847 HadError = true; 4848 continue; 4849 } 4850 4851 // Beyond this point, we only consider default initialization. 4852 if (Info.isImplicitCopyOrMove()) 4853 continue; 4854 4855 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4856 if (F->getType()->isIncompleteArrayType()) { 4857 assert(ClassDecl->hasFlexibleArrayMember() && 4858 "Incomplete array type is not valid"); 4859 continue; 4860 } 4861 4862 // Initialize each field of an anonymous struct individually. 4863 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4864 HadError = true; 4865 4866 continue; 4867 } 4868 } 4869 4870 unsigned NumInitializers = Info.AllToInit.size(); 4871 if (NumInitializers > 0) { 4872 Constructor->setNumCtorInitializers(NumInitializers); 4873 CXXCtorInitializer **baseOrMemberInitializers = 4874 new (Context) CXXCtorInitializer*[NumInitializers]; 4875 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4876 NumInitializers * sizeof(CXXCtorInitializer*)); 4877 Constructor->setCtorInitializers(baseOrMemberInitializers); 4878 4879 // Constructors implicitly reference the base and member 4880 // destructors. 4881 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4882 Constructor->getParent()); 4883 } 4884 4885 return HadError; 4886 } 4887 4888 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4889 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4890 const RecordDecl *RD = RT->getDecl(); 4891 if (RD->isAnonymousStructOrUnion()) { 4892 for (auto *Field : RD->fields()) 4893 PopulateKeysForFields(Field, IdealInits); 4894 return; 4895 } 4896 } 4897 IdealInits.push_back(Field->getCanonicalDecl()); 4898 } 4899 4900 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4901 return Context.getCanonicalType(BaseType).getTypePtr(); 4902 } 4903 4904 static const void *GetKeyForMember(ASTContext &Context, 4905 CXXCtorInitializer *Member) { 4906 if (!Member->isAnyMemberInitializer()) 4907 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4908 4909 return Member->getAnyMember()->getCanonicalDecl(); 4910 } 4911 4912 static void DiagnoseBaseOrMemInitializerOrder( 4913 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4914 ArrayRef<CXXCtorInitializer *> Inits) { 4915 if (Constructor->getDeclContext()->isDependentContext()) 4916 return; 4917 4918 // Don't check initializers order unless the warning is enabled at the 4919 // location of at least one initializer. 4920 bool ShouldCheckOrder = false; 4921 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4922 CXXCtorInitializer *Init = Inits[InitIndex]; 4923 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4924 Init->getSourceLocation())) { 4925 ShouldCheckOrder = true; 4926 break; 4927 } 4928 } 4929 if (!ShouldCheckOrder) 4930 return; 4931 4932 // Build the list of bases and members in the order that they'll 4933 // actually be initialized. The explicit initializers should be in 4934 // this same order but may be missing things. 4935 SmallVector<const void*, 32> IdealInitKeys; 4936 4937 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4938 4939 // 1. Virtual bases. 4940 for (const auto &VBase : ClassDecl->vbases()) 4941 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4942 4943 // 2. Non-virtual bases. 4944 for (const auto &Base : ClassDecl->bases()) { 4945 if (Base.isVirtual()) 4946 continue; 4947 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4948 } 4949 4950 // 3. Direct fields. 4951 for (auto *Field : ClassDecl->fields()) { 4952 if (Field->isUnnamedBitfield()) 4953 continue; 4954 4955 PopulateKeysForFields(Field, IdealInitKeys); 4956 } 4957 4958 unsigned NumIdealInits = IdealInitKeys.size(); 4959 unsigned IdealIndex = 0; 4960 4961 CXXCtorInitializer *PrevInit = nullptr; 4962 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4963 CXXCtorInitializer *Init = Inits[InitIndex]; 4964 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4965 4966 // Scan forward to try to find this initializer in the idealized 4967 // initializers list. 4968 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4969 if (InitKey == IdealInitKeys[IdealIndex]) 4970 break; 4971 4972 // If we didn't find this initializer, it must be because we 4973 // scanned past it on a previous iteration. That can only 4974 // happen if we're out of order; emit a warning. 4975 if (IdealIndex == NumIdealInits && PrevInit) { 4976 Sema::SemaDiagnosticBuilder D = 4977 SemaRef.Diag(PrevInit->getSourceLocation(), 4978 diag::warn_initializer_out_of_order); 4979 4980 if (PrevInit->isAnyMemberInitializer()) 4981 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4982 else 4983 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4984 4985 if (Init->isAnyMemberInitializer()) 4986 D << 0 << Init->getAnyMember()->getDeclName(); 4987 else 4988 D << 1 << Init->getTypeSourceInfo()->getType(); 4989 4990 // Move back to the initializer's location in the ideal list. 4991 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4992 if (InitKey == IdealInitKeys[IdealIndex]) 4993 break; 4994 4995 assert(IdealIndex < NumIdealInits && 4996 "initializer not found in initializer list"); 4997 } 4998 4999 PrevInit = Init; 5000 } 5001 } 5002 5003 namespace { 5004 bool CheckRedundantInit(Sema &S, 5005 CXXCtorInitializer *Init, 5006 CXXCtorInitializer *&PrevInit) { 5007 if (!PrevInit) { 5008 PrevInit = Init; 5009 return false; 5010 } 5011 5012 if (FieldDecl *Field = Init->getAnyMember()) 5013 S.Diag(Init->getSourceLocation(), 5014 diag::err_multiple_mem_initialization) 5015 << Field->getDeclName() 5016 << Init->getSourceRange(); 5017 else { 5018 const Type *BaseClass = Init->getBaseClass(); 5019 assert(BaseClass && "neither field nor base"); 5020 S.Diag(Init->getSourceLocation(), 5021 diag::err_multiple_base_initialization) 5022 << QualType(BaseClass, 0) 5023 << Init->getSourceRange(); 5024 } 5025 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5026 << 0 << PrevInit->getSourceRange(); 5027 5028 return true; 5029 } 5030 5031 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5032 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5033 5034 bool CheckRedundantUnionInit(Sema &S, 5035 CXXCtorInitializer *Init, 5036 RedundantUnionMap &Unions) { 5037 FieldDecl *Field = Init->getAnyMember(); 5038 RecordDecl *Parent = Field->getParent(); 5039 NamedDecl *Child = Field; 5040 5041 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5042 if (Parent->isUnion()) { 5043 UnionEntry &En = Unions[Parent]; 5044 if (En.first && En.first != Child) { 5045 S.Diag(Init->getSourceLocation(), 5046 diag::err_multiple_mem_union_initialization) 5047 << Field->getDeclName() 5048 << Init->getSourceRange(); 5049 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5050 << 0 << En.second->getSourceRange(); 5051 return true; 5052 } 5053 if (!En.first) { 5054 En.first = Child; 5055 En.second = Init; 5056 } 5057 if (!Parent->isAnonymousStructOrUnion()) 5058 return false; 5059 } 5060 5061 Child = Parent; 5062 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5063 } 5064 5065 return false; 5066 } 5067 } 5068 5069 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5070 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5071 SourceLocation ColonLoc, 5072 ArrayRef<CXXCtorInitializer*> MemInits, 5073 bool AnyErrors) { 5074 if (!ConstructorDecl) 5075 return; 5076 5077 AdjustDeclIfTemplate(ConstructorDecl); 5078 5079 CXXConstructorDecl *Constructor 5080 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5081 5082 if (!Constructor) { 5083 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5084 return; 5085 } 5086 5087 // Mapping for the duplicate initializers check. 5088 // For member initializers, this is keyed with a FieldDecl*. 5089 // For base initializers, this is keyed with a Type*. 5090 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5091 5092 // Mapping for the inconsistent anonymous-union initializers check. 5093 RedundantUnionMap MemberUnions; 5094 5095 bool HadError = false; 5096 for (unsigned i = 0; i < MemInits.size(); i++) { 5097 CXXCtorInitializer *Init = MemInits[i]; 5098 5099 // Set the source order index. 5100 Init->setSourceOrder(i); 5101 5102 if (Init->isAnyMemberInitializer()) { 5103 const void *Key = GetKeyForMember(Context, Init); 5104 if (CheckRedundantInit(*this, Init, Members[Key]) || 5105 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5106 HadError = true; 5107 } else if (Init->isBaseInitializer()) { 5108 const void *Key = GetKeyForMember(Context, Init); 5109 if (CheckRedundantInit(*this, Init, Members[Key])) 5110 HadError = true; 5111 } else { 5112 assert(Init->isDelegatingInitializer()); 5113 // This must be the only initializer 5114 if (MemInits.size() != 1) { 5115 Diag(Init->getSourceLocation(), 5116 diag::err_delegating_initializer_alone) 5117 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5118 // We will treat this as being the only initializer. 5119 } 5120 SetDelegatingInitializer(Constructor, MemInits[i]); 5121 // Return immediately as the initializer is set. 5122 return; 5123 } 5124 } 5125 5126 if (HadError) 5127 return; 5128 5129 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5130 5131 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5132 5133 DiagnoseUninitializedFields(*this, Constructor); 5134 } 5135 5136 void 5137 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5138 CXXRecordDecl *ClassDecl) { 5139 // Ignore dependent contexts. Also ignore unions, since their members never 5140 // have destructors implicitly called. 5141 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5142 return; 5143 5144 // FIXME: all the access-control diagnostics are positioned on the 5145 // field/base declaration. That's probably good; that said, the 5146 // user might reasonably want to know why the destructor is being 5147 // emitted, and we currently don't say. 5148 5149 // Non-static data members. 5150 for (auto *Field : ClassDecl->fields()) { 5151 if (Field->isInvalidDecl()) 5152 continue; 5153 5154 // Don't destroy incomplete or zero-length arrays. 5155 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5156 continue; 5157 5158 QualType FieldType = Context.getBaseElementType(Field->getType()); 5159 5160 const RecordType* RT = FieldType->getAs<RecordType>(); 5161 if (!RT) 5162 continue; 5163 5164 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5165 if (FieldClassDecl->isInvalidDecl()) 5166 continue; 5167 if (FieldClassDecl->hasIrrelevantDestructor()) 5168 continue; 5169 // The destructor for an implicit anonymous union member is never invoked. 5170 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5171 continue; 5172 5173 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5174 assert(Dtor && "No dtor found for FieldClassDecl!"); 5175 CheckDestructorAccess(Field->getLocation(), Dtor, 5176 PDiag(diag::err_access_dtor_field) 5177 << Field->getDeclName() 5178 << FieldType); 5179 5180 MarkFunctionReferenced(Location, Dtor); 5181 DiagnoseUseOfDecl(Dtor, Location); 5182 } 5183 5184 // We only potentially invoke the destructors of potentially constructed 5185 // subobjects. 5186 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5187 5188 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5189 5190 // Bases. 5191 for (const auto &Base : ClassDecl->bases()) { 5192 // Bases are always records in a well-formed non-dependent class. 5193 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5194 5195 // Remember direct virtual bases. 5196 if (Base.isVirtual()) { 5197 if (!VisitVirtualBases) 5198 continue; 5199 DirectVirtualBases.insert(RT); 5200 } 5201 5202 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5203 // If our base class is invalid, we probably can't get its dtor anyway. 5204 if (BaseClassDecl->isInvalidDecl()) 5205 continue; 5206 if (BaseClassDecl->hasIrrelevantDestructor()) 5207 continue; 5208 5209 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5210 assert(Dtor && "No dtor found for BaseClassDecl!"); 5211 5212 // FIXME: caret should be on the start of the class name 5213 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5214 PDiag(diag::err_access_dtor_base) 5215 << Base.getType() << Base.getSourceRange(), 5216 Context.getTypeDeclType(ClassDecl)); 5217 5218 MarkFunctionReferenced(Location, Dtor); 5219 DiagnoseUseOfDecl(Dtor, Location); 5220 } 5221 5222 if (!VisitVirtualBases) 5223 return; 5224 5225 // Virtual bases. 5226 for (const auto &VBase : ClassDecl->vbases()) { 5227 // Bases are always records in a well-formed non-dependent class. 5228 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5229 5230 // Ignore direct virtual bases. 5231 if (DirectVirtualBases.count(RT)) 5232 continue; 5233 5234 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5235 // If our base class is invalid, we probably can't get its dtor anyway. 5236 if (BaseClassDecl->isInvalidDecl()) 5237 continue; 5238 if (BaseClassDecl->hasIrrelevantDestructor()) 5239 continue; 5240 5241 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5242 assert(Dtor && "No dtor found for BaseClassDecl!"); 5243 if (CheckDestructorAccess( 5244 ClassDecl->getLocation(), Dtor, 5245 PDiag(diag::err_access_dtor_vbase) 5246 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5247 Context.getTypeDeclType(ClassDecl)) == 5248 AR_accessible) { 5249 CheckDerivedToBaseConversion( 5250 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5251 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5252 SourceRange(), DeclarationName(), nullptr); 5253 } 5254 5255 MarkFunctionReferenced(Location, Dtor); 5256 DiagnoseUseOfDecl(Dtor, Location); 5257 } 5258 } 5259 5260 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5261 if (!CDtorDecl) 5262 return; 5263 5264 if (CXXConstructorDecl *Constructor 5265 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5266 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5267 DiagnoseUninitializedFields(*this, Constructor); 5268 } 5269 } 5270 5271 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5272 if (!getLangOpts().CPlusPlus) 5273 return false; 5274 5275 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5276 if (!RD) 5277 return false; 5278 5279 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5280 // class template specialization here, but doing so breaks a lot of code. 5281 5282 // We can't answer whether something is abstract until it has a 5283 // definition. If it's currently being defined, we'll walk back 5284 // over all the declarations when we have a full definition. 5285 const CXXRecordDecl *Def = RD->getDefinition(); 5286 if (!Def || Def->isBeingDefined()) 5287 return false; 5288 5289 return RD->isAbstract(); 5290 } 5291 5292 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5293 TypeDiagnoser &Diagnoser) { 5294 if (!isAbstractType(Loc, T)) 5295 return false; 5296 5297 T = Context.getBaseElementType(T); 5298 Diagnoser.diagnose(*this, Loc, T); 5299 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5300 return true; 5301 } 5302 5303 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5304 // Check if we've already emitted the list of pure virtual functions 5305 // for this class. 5306 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5307 return; 5308 5309 // If the diagnostic is suppressed, don't emit the notes. We're only 5310 // going to emit them once, so try to attach them to a diagnostic we're 5311 // actually going to show. 5312 if (Diags.isLastDiagnosticIgnored()) 5313 return; 5314 5315 CXXFinalOverriderMap FinalOverriders; 5316 RD->getFinalOverriders(FinalOverriders); 5317 5318 // Keep a set of seen pure methods so we won't diagnose the same method 5319 // more than once. 5320 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5321 5322 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5323 MEnd = FinalOverriders.end(); 5324 M != MEnd; 5325 ++M) { 5326 for (OverridingMethods::iterator SO = M->second.begin(), 5327 SOEnd = M->second.end(); 5328 SO != SOEnd; ++SO) { 5329 // C++ [class.abstract]p4: 5330 // A class is abstract if it contains or inherits at least one 5331 // pure virtual function for which the final overrider is pure 5332 // virtual. 5333 5334 // 5335 if (SO->second.size() != 1) 5336 continue; 5337 5338 if (!SO->second.front().Method->isPure()) 5339 continue; 5340 5341 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5342 continue; 5343 5344 Diag(SO->second.front().Method->getLocation(), 5345 diag::note_pure_virtual_function) 5346 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5347 } 5348 } 5349 5350 if (!PureVirtualClassDiagSet) 5351 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5352 PureVirtualClassDiagSet->insert(RD); 5353 } 5354 5355 namespace { 5356 struct AbstractUsageInfo { 5357 Sema &S; 5358 CXXRecordDecl *Record; 5359 CanQualType AbstractType; 5360 bool Invalid; 5361 5362 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5363 : S(S), Record(Record), 5364 AbstractType(S.Context.getCanonicalType( 5365 S.Context.getTypeDeclType(Record))), 5366 Invalid(false) {} 5367 5368 void DiagnoseAbstractType() { 5369 if (Invalid) return; 5370 S.DiagnoseAbstractType(Record); 5371 Invalid = true; 5372 } 5373 5374 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5375 }; 5376 5377 struct CheckAbstractUsage { 5378 AbstractUsageInfo &Info; 5379 const NamedDecl *Ctx; 5380 5381 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5382 : Info(Info), Ctx(Ctx) {} 5383 5384 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5385 switch (TL.getTypeLocClass()) { 5386 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5387 #define TYPELOC(CLASS, PARENT) \ 5388 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5389 #include "clang/AST/TypeLocNodes.def" 5390 } 5391 } 5392 5393 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5394 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5395 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5396 if (!TL.getParam(I)) 5397 continue; 5398 5399 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5400 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5401 } 5402 } 5403 5404 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5405 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5406 } 5407 5408 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5409 // Visit the type parameters from a permissive context. 5410 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5411 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5412 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5413 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5414 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5415 // TODO: other template argument types? 5416 } 5417 } 5418 5419 // Visit pointee types from a permissive context. 5420 #define CheckPolymorphic(Type) \ 5421 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5422 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5423 } 5424 CheckPolymorphic(PointerTypeLoc) 5425 CheckPolymorphic(ReferenceTypeLoc) 5426 CheckPolymorphic(MemberPointerTypeLoc) 5427 CheckPolymorphic(BlockPointerTypeLoc) 5428 CheckPolymorphic(AtomicTypeLoc) 5429 5430 /// Handle all the types we haven't given a more specific 5431 /// implementation for above. 5432 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5433 // Every other kind of type that we haven't called out already 5434 // that has an inner type is either (1) sugar or (2) contains that 5435 // inner type in some way as a subobject. 5436 if (TypeLoc Next = TL.getNextTypeLoc()) 5437 return Visit(Next, Sel); 5438 5439 // If there's no inner type and we're in a permissive context, 5440 // don't diagnose. 5441 if (Sel == Sema::AbstractNone) return; 5442 5443 // Check whether the type matches the abstract type. 5444 QualType T = TL.getType(); 5445 if (T->isArrayType()) { 5446 Sel = Sema::AbstractArrayType; 5447 T = Info.S.Context.getBaseElementType(T); 5448 } 5449 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5450 if (CT != Info.AbstractType) return; 5451 5452 // It matched; do some magic. 5453 if (Sel == Sema::AbstractArrayType) { 5454 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5455 << T << TL.getSourceRange(); 5456 } else { 5457 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5458 << Sel << T << TL.getSourceRange(); 5459 } 5460 Info.DiagnoseAbstractType(); 5461 } 5462 }; 5463 5464 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5465 Sema::AbstractDiagSelID Sel) { 5466 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5467 } 5468 5469 } 5470 5471 /// Check for invalid uses of an abstract type in a method declaration. 5472 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5473 CXXMethodDecl *MD) { 5474 // No need to do the check on definitions, which require that 5475 // the return/param types be complete. 5476 if (MD->doesThisDeclarationHaveABody()) 5477 return; 5478 5479 // For safety's sake, just ignore it if we don't have type source 5480 // information. This should never happen for non-implicit methods, 5481 // but... 5482 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5483 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5484 } 5485 5486 /// Check for invalid uses of an abstract type within a class definition. 5487 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5488 CXXRecordDecl *RD) { 5489 for (auto *D : RD->decls()) { 5490 if (D->isImplicit()) continue; 5491 5492 // Methods and method templates. 5493 if (isa<CXXMethodDecl>(D)) { 5494 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5495 } else if (isa<FunctionTemplateDecl>(D)) { 5496 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5497 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5498 5499 // Fields and static variables. 5500 } else if (isa<FieldDecl>(D)) { 5501 FieldDecl *FD = cast<FieldDecl>(D); 5502 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5503 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5504 } else if (isa<VarDecl>(D)) { 5505 VarDecl *VD = cast<VarDecl>(D); 5506 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5507 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5508 5509 // Nested classes and class templates. 5510 } else if (isa<CXXRecordDecl>(D)) { 5511 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5512 } else if (isa<ClassTemplateDecl>(D)) { 5513 CheckAbstractClassUsage(Info, 5514 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5515 } 5516 } 5517 } 5518 5519 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5520 Attr *ClassAttr = getDLLAttr(Class); 5521 if (!ClassAttr) 5522 return; 5523 5524 assert(ClassAttr->getKind() == attr::DLLExport); 5525 5526 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5527 5528 if (TSK == TSK_ExplicitInstantiationDeclaration) 5529 // Don't go any further if this is just an explicit instantiation 5530 // declaration. 5531 return; 5532 5533 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5534 S.MarkVTableUsed(Class->getLocation(), Class, true); 5535 5536 for (Decl *Member : Class->decls()) { 5537 // Defined static variables that are members of an exported base 5538 // class must be marked export too. 5539 auto *VD = dyn_cast<VarDecl>(Member); 5540 if (VD && Member->getAttr<DLLExportAttr>() && 5541 VD->getStorageClass() == SC_Static && 5542 TSK == TSK_ImplicitInstantiation) 5543 S.MarkVariableReferenced(VD->getLocation(), VD); 5544 5545 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5546 if (!MD) 5547 continue; 5548 5549 if (Member->getAttr<DLLExportAttr>()) { 5550 if (MD->isUserProvided()) { 5551 // Instantiate non-default class member functions ... 5552 5553 // .. except for certain kinds of template specializations. 5554 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5555 continue; 5556 5557 S.MarkFunctionReferenced(Class->getLocation(), MD); 5558 5559 // The function will be passed to the consumer when its definition is 5560 // encountered. 5561 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5562 MD->isCopyAssignmentOperator() || 5563 MD->isMoveAssignmentOperator()) { 5564 // Synthesize and instantiate non-trivial implicit methods, explicitly 5565 // defaulted methods, and the copy and move assignment operators. The 5566 // latter are exported even if they are trivial, because the address of 5567 // an operator can be taken and should compare equal across libraries. 5568 DiagnosticErrorTrap Trap(S.Diags); 5569 S.MarkFunctionReferenced(Class->getLocation(), MD); 5570 if (Trap.hasErrorOccurred()) { 5571 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5572 << Class << !S.getLangOpts().CPlusPlus11; 5573 break; 5574 } 5575 5576 // There is no later point when we will see the definition of this 5577 // function, so pass it to the consumer now. 5578 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5579 } 5580 } 5581 } 5582 } 5583 5584 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5585 CXXRecordDecl *Class) { 5586 // Only the MS ABI has default constructor closures, so we don't need to do 5587 // this semantic checking anywhere else. 5588 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5589 return; 5590 5591 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5592 for (Decl *Member : Class->decls()) { 5593 // Look for exported default constructors. 5594 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5595 if (!CD || !CD->isDefaultConstructor()) 5596 continue; 5597 auto *Attr = CD->getAttr<DLLExportAttr>(); 5598 if (!Attr) 5599 continue; 5600 5601 // If the class is non-dependent, mark the default arguments as ODR-used so 5602 // that we can properly codegen the constructor closure. 5603 if (!Class->isDependentContext()) { 5604 for (ParmVarDecl *PD : CD->parameters()) { 5605 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5606 S.DiscardCleanupsInEvaluationContext(); 5607 } 5608 } 5609 5610 if (LastExportedDefaultCtor) { 5611 S.Diag(LastExportedDefaultCtor->getLocation(), 5612 diag::err_attribute_dll_ambiguous_default_ctor) 5613 << Class; 5614 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5615 << CD->getDeclName(); 5616 return; 5617 } 5618 LastExportedDefaultCtor = CD; 5619 } 5620 } 5621 5622 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5623 // Mark any compiler-generated routines with the implicit code_seg attribute. 5624 for (auto *Method : Class->methods()) { 5625 if (Method->isUserProvided()) 5626 continue; 5627 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5628 Method->addAttr(A); 5629 } 5630 } 5631 5632 /// Check class-level dllimport/dllexport attribute. 5633 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5634 Attr *ClassAttr = getDLLAttr(Class); 5635 5636 // MSVC inherits DLL attributes to partial class template specializations. 5637 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5638 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5639 if (Attr *TemplateAttr = 5640 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5641 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5642 A->setInherited(true); 5643 ClassAttr = A; 5644 } 5645 } 5646 } 5647 5648 if (!ClassAttr) 5649 return; 5650 5651 if (!Class->isExternallyVisible()) { 5652 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5653 << Class << ClassAttr; 5654 return; 5655 } 5656 5657 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5658 !ClassAttr->isInherited()) { 5659 // Diagnose dll attributes on members of class with dll attribute. 5660 for (Decl *Member : Class->decls()) { 5661 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5662 continue; 5663 InheritableAttr *MemberAttr = getDLLAttr(Member); 5664 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5665 continue; 5666 5667 Diag(MemberAttr->getLocation(), 5668 diag::err_attribute_dll_member_of_dll_class) 5669 << MemberAttr << ClassAttr; 5670 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5671 Member->setInvalidDecl(); 5672 } 5673 } 5674 5675 if (Class->getDescribedClassTemplate()) 5676 // Don't inherit dll attribute until the template is instantiated. 5677 return; 5678 5679 // The class is either imported or exported. 5680 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5681 5682 // Check if this was a dllimport attribute propagated from a derived class to 5683 // a base class template specialization. We don't apply these attributes to 5684 // static data members. 5685 const bool PropagatedImport = 5686 !ClassExported && 5687 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5688 5689 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5690 5691 // Ignore explicit dllexport on explicit class template instantiation declarations. 5692 if (ClassExported && !ClassAttr->isInherited() && 5693 TSK == TSK_ExplicitInstantiationDeclaration) { 5694 Class->dropAttr<DLLExportAttr>(); 5695 return; 5696 } 5697 5698 // Force declaration of implicit members so they can inherit the attribute. 5699 ForceDeclarationOfImplicitMembers(Class); 5700 5701 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5702 // seem to be true in practice? 5703 5704 for (Decl *Member : Class->decls()) { 5705 VarDecl *VD = dyn_cast<VarDecl>(Member); 5706 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5707 5708 // Only methods and static fields inherit the attributes. 5709 if (!VD && !MD) 5710 continue; 5711 5712 if (MD) { 5713 // Don't process deleted methods. 5714 if (MD->isDeleted()) 5715 continue; 5716 5717 if (MD->isInlined()) { 5718 // MinGW does not import or export inline methods. 5719 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5720 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5721 continue; 5722 5723 // MSVC versions before 2015 don't export the move assignment operators 5724 // and move constructor, so don't attempt to import/export them if 5725 // we have a definition. 5726 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5727 if ((MD->isMoveAssignmentOperator() || 5728 (Ctor && Ctor->isMoveConstructor())) && 5729 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5730 continue; 5731 5732 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5733 // operator is exported anyway. 5734 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5735 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5736 continue; 5737 } 5738 } 5739 5740 // Don't apply dllimport attributes to static data members of class template 5741 // instantiations when the attribute is propagated from a derived class. 5742 if (VD && PropagatedImport) 5743 continue; 5744 5745 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5746 continue; 5747 5748 if (!getDLLAttr(Member)) { 5749 InheritableAttr *NewAttr = nullptr; 5750 5751 // Do not export/import inline function when -fno-dllexport-inlines is 5752 // passed. But add attribute for later local static var check. 5753 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 5754 TSK != TSK_ExplicitInstantiationDeclaration && 5755 TSK != TSK_ExplicitInstantiationDefinition) { 5756 if (ClassExported) { 5757 NewAttr = ::new (getASTContext()) 5758 DLLExportStaticLocalAttr(ClassAttr->getRange(), 5759 getASTContext(), 5760 ClassAttr->getSpellingListIndex()); 5761 } else { 5762 NewAttr = ::new (getASTContext()) 5763 DLLImportStaticLocalAttr(ClassAttr->getRange(), 5764 getASTContext(), 5765 ClassAttr->getSpellingListIndex()); 5766 } 5767 } else { 5768 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5769 } 5770 5771 NewAttr->setInherited(true); 5772 Member->addAttr(NewAttr); 5773 5774 if (MD) { 5775 // Propagate DLLAttr to friend re-declarations of MD that have already 5776 // been constructed. 5777 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5778 FD = FD->getPreviousDecl()) { 5779 if (FD->getFriendObjectKind() == Decl::FOK_None) 5780 continue; 5781 assert(!getDLLAttr(FD) && 5782 "friend re-decl should not already have a DLLAttr"); 5783 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5784 NewAttr->setInherited(true); 5785 FD->addAttr(NewAttr); 5786 } 5787 } 5788 } 5789 } 5790 5791 if (ClassExported) 5792 DelayedDllExportClasses.push_back(Class); 5793 } 5794 5795 /// Perform propagation of DLL attributes from a derived class to a 5796 /// templated base class for MS compatibility. 5797 void Sema::propagateDLLAttrToBaseClassTemplate( 5798 CXXRecordDecl *Class, Attr *ClassAttr, 5799 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5800 if (getDLLAttr( 5801 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5802 // If the base class template has a DLL attribute, don't try to change it. 5803 return; 5804 } 5805 5806 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5807 if (!getDLLAttr(BaseTemplateSpec) && 5808 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5809 TSK == TSK_ImplicitInstantiation)) { 5810 // The template hasn't been instantiated yet (or it has, but only as an 5811 // explicit instantiation declaration or implicit instantiation, which means 5812 // we haven't codegenned any members yet), so propagate the attribute. 5813 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5814 NewAttr->setInherited(true); 5815 BaseTemplateSpec->addAttr(NewAttr); 5816 5817 // If this was an import, mark that we propagated it from a derived class to 5818 // a base class template specialization. 5819 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 5820 ImportAttr->setPropagatedToBaseTemplate(); 5821 5822 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5823 // needs to be run again to work see the new attribute. Otherwise this will 5824 // get run whenever the template is instantiated. 5825 if (TSK != TSK_Undeclared) 5826 checkClassLevelDLLAttribute(BaseTemplateSpec); 5827 5828 return; 5829 } 5830 5831 if (getDLLAttr(BaseTemplateSpec)) { 5832 // The template has already been specialized or instantiated with an 5833 // attribute, explicitly or through propagation. We should not try to change 5834 // it. 5835 return; 5836 } 5837 5838 // The template was previously instantiated or explicitly specialized without 5839 // a dll attribute, It's too late for us to add an attribute, so warn that 5840 // this is unsupported. 5841 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5842 << BaseTemplateSpec->isExplicitSpecialization(); 5843 Diag(ClassAttr->getLocation(), diag::note_attribute); 5844 if (BaseTemplateSpec->isExplicitSpecialization()) { 5845 Diag(BaseTemplateSpec->getLocation(), 5846 diag::note_template_class_explicit_specialization_was_here) 5847 << BaseTemplateSpec; 5848 } else { 5849 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5850 diag::note_template_class_instantiation_was_here) 5851 << BaseTemplateSpec; 5852 } 5853 } 5854 5855 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5856 SourceLocation DefaultLoc) { 5857 switch (S.getSpecialMember(MD)) { 5858 case Sema::CXXDefaultConstructor: 5859 S.DefineImplicitDefaultConstructor(DefaultLoc, 5860 cast<CXXConstructorDecl>(MD)); 5861 break; 5862 case Sema::CXXCopyConstructor: 5863 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5864 break; 5865 case Sema::CXXCopyAssignment: 5866 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5867 break; 5868 case Sema::CXXDestructor: 5869 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5870 break; 5871 case Sema::CXXMoveConstructor: 5872 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5873 break; 5874 case Sema::CXXMoveAssignment: 5875 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5876 break; 5877 case Sema::CXXInvalid: 5878 llvm_unreachable("Invalid special member."); 5879 } 5880 } 5881 5882 /// Determine whether a type is permitted to be passed or returned in 5883 /// registers, per C++ [class.temporary]p3. 5884 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 5885 TargetInfo::CallingConvKind CCK) { 5886 if (D->isDependentType() || D->isInvalidDecl()) 5887 return false; 5888 5889 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 5890 // The PS4 platform ABI follows the behavior of Clang 3.2. 5891 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 5892 return !D->hasNonTrivialDestructorForCall() && 5893 !D->hasNonTrivialCopyConstructorForCall(); 5894 5895 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 5896 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 5897 bool DtorIsTrivialForCall = false; 5898 5899 // If a class has at least one non-deleted, trivial copy constructor, it 5900 // is passed according to the C ABI. Otherwise, it is passed indirectly. 5901 // 5902 // Note: This permits classes with non-trivial copy or move ctors to be 5903 // passed in registers, so long as they *also* have a trivial copy ctor, 5904 // which is non-conforming. 5905 if (D->needsImplicitCopyConstructor()) { 5906 if (!D->defaultedCopyConstructorIsDeleted()) { 5907 if (D->hasTrivialCopyConstructor()) 5908 CopyCtorIsTrivial = true; 5909 if (D->hasTrivialCopyConstructorForCall()) 5910 CopyCtorIsTrivialForCall = true; 5911 } 5912 } else { 5913 for (const CXXConstructorDecl *CD : D->ctors()) { 5914 if (CD->isCopyConstructor() && !CD->isDeleted()) { 5915 if (CD->isTrivial()) 5916 CopyCtorIsTrivial = true; 5917 if (CD->isTrivialForCall()) 5918 CopyCtorIsTrivialForCall = true; 5919 } 5920 } 5921 } 5922 5923 if (D->needsImplicitDestructor()) { 5924 if (!D->defaultedDestructorIsDeleted() && 5925 D->hasTrivialDestructorForCall()) 5926 DtorIsTrivialForCall = true; 5927 } else if (const auto *DD = D->getDestructor()) { 5928 if (!DD->isDeleted() && DD->isTrivialForCall()) 5929 DtorIsTrivialForCall = true; 5930 } 5931 5932 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 5933 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 5934 return true; 5935 5936 // If a class has a destructor, we'd really like to pass it indirectly 5937 // because it allows us to elide copies. Unfortunately, MSVC makes that 5938 // impossible for small types, which it will pass in a single register or 5939 // stack slot. Most objects with dtors are large-ish, so handle that early. 5940 // We can't call out all large objects as being indirect because there are 5941 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 5942 // how we pass large POD types. 5943 5944 // Note: This permits small classes with nontrivial destructors to be 5945 // passed in registers, which is non-conforming. 5946 if (CopyCtorIsTrivial && 5947 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64) 5948 return true; 5949 return false; 5950 } 5951 5952 // Per C++ [class.temporary]p3, the relevant condition is: 5953 // each copy constructor, move constructor, and destructor of X is 5954 // either trivial or deleted, and X has at least one non-deleted copy 5955 // or move constructor 5956 bool HasNonDeletedCopyOrMove = false; 5957 5958 if (D->needsImplicitCopyConstructor() && 5959 !D->defaultedCopyConstructorIsDeleted()) { 5960 if (!D->hasTrivialCopyConstructorForCall()) 5961 return false; 5962 HasNonDeletedCopyOrMove = true; 5963 } 5964 5965 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5966 !D->defaultedMoveConstructorIsDeleted()) { 5967 if (!D->hasTrivialMoveConstructorForCall()) 5968 return false; 5969 HasNonDeletedCopyOrMove = true; 5970 } 5971 5972 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5973 !D->hasTrivialDestructorForCall()) 5974 return false; 5975 5976 for (const CXXMethodDecl *MD : D->methods()) { 5977 if (MD->isDeleted()) 5978 continue; 5979 5980 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5981 if (CD && CD->isCopyOrMoveConstructor()) 5982 HasNonDeletedCopyOrMove = true; 5983 else if (!isa<CXXDestructorDecl>(MD)) 5984 continue; 5985 5986 if (!MD->isTrivialForCall()) 5987 return false; 5988 } 5989 5990 return HasNonDeletedCopyOrMove; 5991 } 5992 5993 /// Perform semantic checks on a class definition that has been 5994 /// completing, introducing implicitly-declared members, checking for 5995 /// abstract types, etc. 5996 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5997 if (!Record) 5998 return; 5999 6000 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6001 AbstractUsageInfo Info(*this, Record); 6002 CheckAbstractClassUsage(Info, Record); 6003 } 6004 6005 // If this is not an aggregate type and has no user-declared constructor, 6006 // complain about any non-static data members of reference or const scalar 6007 // type, since they will never get initializers. 6008 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6009 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6010 !Record->isLambda()) { 6011 bool Complained = false; 6012 for (const auto *F : Record->fields()) { 6013 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6014 continue; 6015 6016 if (F->getType()->isReferenceType() || 6017 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6018 if (!Complained) { 6019 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6020 << Record->getTagKind() << Record; 6021 Complained = true; 6022 } 6023 6024 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6025 << F->getType()->isReferenceType() 6026 << F->getDeclName(); 6027 } 6028 } 6029 } 6030 6031 if (Record->getIdentifier()) { 6032 // C++ [class.mem]p13: 6033 // If T is the name of a class, then each of the following shall have a 6034 // name different from T: 6035 // - every member of every anonymous union that is a member of class T. 6036 // 6037 // C++ [class.mem]p14: 6038 // In addition, if class T has a user-declared constructor (12.1), every 6039 // non-static data member of class T shall have a name different from T. 6040 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6041 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6042 ++I) { 6043 NamedDecl *D = (*I)->getUnderlyingDecl(); 6044 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6045 Record->hasUserDeclaredConstructor()) || 6046 isa<IndirectFieldDecl>(D)) { 6047 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6048 << D->getDeclName(); 6049 break; 6050 } 6051 } 6052 } 6053 6054 // Warn if the class has virtual methods but non-virtual public destructor. 6055 if (Record->isPolymorphic() && !Record->isDependentType()) { 6056 CXXDestructorDecl *dtor = Record->getDestructor(); 6057 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6058 !Record->hasAttr<FinalAttr>()) 6059 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6060 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6061 } 6062 6063 if (Record->isAbstract()) { 6064 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6065 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6066 << FA->isSpelledAsSealed(); 6067 DiagnoseAbstractType(Record); 6068 } 6069 } 6070 6071 // See if trivial_abi has to be dropped. 6072 if (Record->hasAttr<TrivialABIAttr>()) 6073 checkIllFormedTrivialABIStruct(*Record); 6074 6075 // Set HasTrivialSpecialMemberForCall if the record has attribute 6076 // "trivial_abi". 6077 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6078 6079 if (HasTrivialABI) 6080 Record->setHasTrivialSpecialMemberForCall(); 6081 6082 bool HasMethodWithOverrideControl = false, 6083 HasOverridingMethodWithoutOverrideControl = false; 6084 if (!Record->isDependentType()) { 6085 for (auto *M : Record->methods()) { 6086 // See if a method overloads virtual methods in a base 6087 // class without overriding any. 6088 if (!M->isStatic()) 6089 DiagnoseHiddenVirtualMethods(M); 6090 if (M->hasAttr<OverrideAttr>()) 6091 HasMethodWithOverrideControl = true; 6092 else if (M->size_overridden_methods() > 0) 6093 HasOverridingMethodWithoutOverrideControl = true; 6094 // Check whether the explicitly-defaulted special members are valid. 6095 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6096 CheckExplicitlyDefaultedSpecialMember(M); 6097 6098 // For an explicitly defaulted or deleted special member, we defer 6099 // determining triviality until the class is complete. That time is now! 6100 CXXSpecialMember CSM = getSpecialMember(M); 6101 if (!M->isImplicit() && !M->isUserProvided()) { 6102 if (CSM != CXXInvalid) { 6103 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6104 // Inform the class that we've finished declaring this member. 6105 Record->finishedDefaultedOrDeletedMember(M); 6106 M->setTrivialForCall( 6107 HasTrivialABI || 6108 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6109 Record->setTrivialForCallFlags(M); 6110 } 6111 } 6112 6113 // Set triviality for the purpose of calls if this is a user-provided 6114 // copy/move constructor or destructor. 6115 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6116 CSM == CXXDestructor) && M->isUserProvided()) { 6117 M->setTrivialForCall(HasTrivialABI); 6118 Record->setTrivialForCallFlags(M); 6119 } 6120 6121 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6122 M->hasAttr<DLLExportAttr>()) { 6123 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6124 M->isTrivial() && 6125 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6126 CSM == CXXDestructor)) 6127 M->dropAttr<DLLExportAttr>(); 6128 6129 if (M->hasAttr<DLLExportAttr>()) { 6130 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6131 ActOnFinishInlineFunctionDef(M); 6132 } 6133 } 6134 } 6135 } 6136 6137 if (HasMethodWithOverrideControl && 6138 HasOverridingMethodWithoutOverrideControl) { 6139 // At least one method has the 'override' control declared. 6140 // Diagnose all other overridden methods which do not have 'override' specified on them. 6141 for (auto *M : Record->methods()) 6142 DiagnoseAbsenceOfOverrideControl(M); 6143 } 6144 6145 // ms_struct is a request to use the same ABI rules as MSVC. Check 6146 // whether this class uses any C++ features that are implemented 6147 // completely differently in MSVC, and if so, emit a diagnostic. 6148 // That diagnostic defaults to an error, but we allow projects to 6149 // map it down to a warning (or ignore it). It's a fairly common 6150 // practice among users of the ms_struct pragma to mass-annotate 6151 // headers, sweeping up a bunch of types that the project doesn't 6152 // really rely on MSVC-compatible layout for. We must therefore 6153 // support "ms_struct except for C++ stuff" as a secondary ABI. 6154 if (Record->isMsStruct(Context) && 6155 (Record->isPolymorphic() || Record->getNumBases())) { 6156 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6157 } 6158 6159 checkClassLevelDLLAttribute(Record); 6160 checkClassLevelCodeSegAttribute(Record); 6161 6162 bool ClangABICompat4 = 6163 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6164 TargetInfo::CallingConvKind CCK = 6165 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6166 bool CanPass = canPassInRegisters(*this, Record, CCK); 6167 6168 // Do not change ArgPassingRestrictions if it has already been set to 6169 // APK_CanNeverPassInRegs. 6170 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6171 Record->setArgPassingRestrictions(CanPass 6172 ? RecordDecl::APK_CanPassInRegs 6173 : RecordDecl::APK_CannotPassInRegs); 6174 6175 // If canPassInRegisters returns true despite the record having a non-trivial 6176 // destructor, the record is destructed in the callee. This happens only when 6177 // the record or one of its subobjects has a field annotated with trivial_abi 6178 // or a field qualified with ObjC __strong/__weak. 6179 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6180 Record->setParamDestroyedInCallee(true); 6181 else if (Record->hasNonTrivialDestructor()) 6182 Record->setParamDestroyedInCallee(CanPass); 6183 6184 if (getLangOpts().ForceEmitVTables) { 6185 // If we want to emit all the vtables, we need to mark it as used. This 6186 // is especially required for cases like vtable assumption loads. 6187 MarkVTableUsed(Record->getInnerLocStart(), Record); 6188 } 6189 } 6190 6191 /// Look up the special member function that would be called by a special 6192 /// member function for a subobject of class type. 6193 /// 6194 /// \param Class The class type of the subobject. 6195 /// \param CSM The kind of special member function. 6196 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6197 /// \param ConstRHS True if this is a copy operation with a const object 6198 /// on its RHS, that is, if the argument to the outer special member 6199 /// function is 'const' and this is not a field marked 'mutable'. 6200 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6201 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6202 unsigned FieldQuals, bool ConstRHS) { 6203 unsigned LHSQuals = 0; 6204 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6205 LHSQuals = FieldQuals; 6206 6207 unsigned RHSQuals = FieldQuals; 6208 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6209 RHSQuals = 0; 6210 else if (ConstRHS) 6211 RHSQuals |= Qualifiers::Const; 6212 6213 return S.LookupSpecialMember(Class, CSM, 6214 RHSQuals & Qualifiers::Const, 6215 RHSQuals & Qualifiers::Volatile, 6216 false, 6217 LHSQuals & Qualifiers::Const, 6218 LHSQuals & Qualifiers::Volatile); 6219 } 6220 6221 class Sema::InheritedConstructorInfo { 6222 Sema &S; 6223 SourceLocation UseLoc; 6224 6225 /// A mapping from the base classes through which the constructor was 6226 /// inherited to the using shadow declaration in that base class (or a null 6227 /// pointer if the constructor was declared in that base class). 6228 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6229 InheritedFromBases; 6230 6231 public: 6232 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6233 ConstructorUsingShadowDecl *Shadow) 6234 : S(S), UseLoc(UseLoc) { 6235 bool DiagnosedMultipleConstructedBases = false; 6236 CXXRecordDecl *ConstructedBase = nullptr; 6237 UsingDecl *ConstructedBaseUsing = nullptr; 6238 6239 // Find the set of such base class subobjects and check that there's a 6240 // unique constructed subobject. 6241 for (auto *D : Shadow->redecls()) { 6242 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6243 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6244 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6245 6246 InheritedFromBases.insert( 6247 std::make_pair(DNominatedBase->getCanonicalDecl(), 6248 DShadow->getNominatedBaseClassShadowDecl())); 6249 if (DShadow->constructsVirtualBase()) 6250 InheritedFromBases.insert( 6251 std::make_pair(DConstructedBase->getCanonicalDecl(), 6252 DShadow->getConstructedBaseClassShadowDecl())); 6253 else 6254 assert(DNominatedBase == DConstructedBase); 6255 6256 // [class.inhctor.init]p2: 6257 // If the constructor was inherited from multiple base class subobjects 6258 // of type B, the program is ill-formed. 6259 if (!ConstructedBase) { 6260 ConstructedBase = DConstructedBase; 6261 ConstructedBaseUsing = D->getUsingDecl(); 6262 } else if (ConstructedBase != DConstructedBase && 6263 !Shadow->isInvalidDecl()) { 6264 if (!DiagnosedMultipleConstructedBases) { 6265 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6266 << Shadow->getTargetDecl(); 6267 S.Diag(ConstructedBaseUsing->getLocation(), 6268 diag::note_ambiguous_inherited_constructor_using) 6269 << ConstructedBase; 6270 DiagnosedMultipleConstructedBases = true; 6271 } 6272 S.Diag(D->getUsingDecl()->getLocation(), 6273 diag::note_ambiguous_inherited_constructor_using) 6274 << DConstructedBase; 6275 } 6276 } 6277 6278 if (DiagnosedMultipleConstructedBases) 6279 Shadow->setInvalidDecl(); 6280 } 6281 6282 /// Find the constructor to use for inherited construction of a base class, 6283 /// and whether that base class constructor inherits the constructor from a 6284 /// virtual base class (in which case it won't actually invoke it). 6285 std::pair<CXXConstructorDecl *, bool> 6286 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6287 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6288 if (It == InheritedFromBases.end()) 6289 return std::make_pair(nullptr, false); 6290 6291 // This is an intermediary class. 6292 if (It->second) 6293 return std::make_pair( 6294 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6295 It->second->constructsVirtualBase()); 6296 6297 // This is the base class from which the constructor was inherited. 6298 return std::make_pair(Ctor, false); 6299 } 6300 }; 6301 6302 /// Is the special member function which would be selected to perform the 6303 /// specified operation on the specified class type a constexpr constructor? 6304 static bool 6305 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6306 Sema::CXXSpecialMember CSM, unsigned Quals, 6307 bool ConstRHS, 6308 CXXConstructorDecl *InheritedCtor = nullptr, 6309 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6310 // If we're inheriting a constructor, see if we need to call it for this base 6311 // class. 6312 if (InheritedCtor) { 6313 assert(CSM == Sema::CXXDefaultConstructor); 6314 auto BaseCtor = 6315 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6316 if (BaseCtor) 6317 return BaseCtor->isConstexpr(); 6318 } 6319 6320 if (CSM == Sema::CXXDefaultConstructor) 6321 return ClassDecl->hasConstexprDefaultConstructor(); 6322 6323 Sema::SpecialMemberOverloadResult SMOR = 6324 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6325 if (!SMOR.getMethod()) 6326 // A constructor we wouldn't select can't be "involved in initializing" 6327 // anything. 6328 return true; 6329 return SMOR.getMethod()->isConstexpr(); 6330 } 6331 6332 /// Determine whether the specified special member function would be constexpr 6333 /// if it were implicitly defined. 6334 static bool defaultedSpecialMemberIsConstexpr( 6335 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6336 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6337 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6338 if (!S.getLangOpts().CPlusPlus11) 6339 return false; 6340 6341 // C++11 [dcl.constexpr]p4: 6342 // In the definition of a constexpr constructor [...] 6343 bool Ctor = true; 6344 switch (CSM) { 6345 case Sema::CXXDefaultConstructor: 6346 if (Inherited) 6347 break; 6348 // Since default constructor lookup is essentially trivial (and cannot 6349 // involve, for instance, template instantiation), we compute whether a 6350 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6351 // 6352 // This is important for performance; we need to know whether the default 6353 // constructor is constexpr to determine whether the type is a literal type. 6354 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6355 6356 case Sema::CXXCopyConstructor: 6357 case Sema::CXXMoveConstructor: 6358 // For copy or move constructors, we need to perform overload resolution. 6359 break; 6360 6361 case Sema::CXXCopyAssignment: 6362 case Sema::CXXMoveAssignment: 6363 if (!S.getLangOpts().CPlusPlus14) 6364 return false; 6365 // In C++1y, we need to perform overload resolution. 6366 Ctor = false; 6367 break; 6368 6369 case Sema::CXXDestructor: 6370 case Sema::CXXInvalid: 6371 return false; 6372 } 6373 6374 // -- if the class is a non-empty union, or for each non-empty anonymous 6375 // union member of a non-union class, exactly one non-static data member 6376 // shall be initialized; [DR1359] 6377 // 6378 // If we squint, this is guaranteed, since exactly one non-static data member 6379 // will be initialized (if the constructor isn't deleted), we just don't know 6380 // which one. 6381 if (Ctor && ClassDecl->isUnion()) 6382 return CSM == Sema::CXXDefaultConstructor 6383 ? ClassDecl->hasInClassInitializer() || 6384 !ClassDecl->hasVariantMembers() 6385 : true; 6386 6387 // -- the class shall not have any virtual base classes; 6388 if (Ctor && ClassDecl->getNumVBases()) 6389 return false; 6390 6391 // C++1y [class.copy]p26: 6392 // -- [the class] is a literal type, and 6393 if (!Ctor && !ClassDecl->isLiteral()) 6394 return false; 6395 6396 // -- every constructor involved in initializing [...] base class 6397 // sub-objects shall be a constexpr constructor; 6398 // -- the assignment operator selected to copy/move each direct base 6399 // class is a constexpr function, and 6400 for (const auto &B : ClassDecl->bases()) { 6401 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6402 if (!BaseType) continue; 6403 6404 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6405 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6406 InheritedCtor, Inherited)) 6407 return false; 6408 } 6409 6410 // -- every constructor involved in initializing non-static data members 6411 // [...] shall be a constexpr constructor; 6412 // -- every non-static data member and base class sub-object shall be 6413 // initialized 6414 // -- for each non-static data member of X that is of class type (or array 6415 // thereof), the assignment operator selected to copy/move that member is 6416 // a constexpr function 6417 for (const auto *F : ClassDecl->fields()) { 6418 if (F->isInvalidDecl()) 6419 continue; 6420 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6421 continue; 6422 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6423 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6424 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6425 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6426 BaseType.getCVRQualifiers(), 6427 ConstArg && !F->isMutable())) 6428 return false; 6429 } else if (CSM == Sema::CXXDefaultConstructor) { 6430 return false; 6431 } 6432 } 6433 6434 // All OK, it's constexpr! 6435 return true; 6436 } 6437 6438 static Sema::ImplicitExceptionSpecification 6439 ComputeDefaultedSpecialMemberExceptionSpec( 6440 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6441 Sema::InheritedConstructorInfo *ICI); 6442 6443 static Sema::ImplicitExceptionSpecification 6444 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6445 auto CSM = S.getSpecialMember(MD); 6446 if (CSM != Sema::CXXInvalid) 6447 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6448 6449 auto *CD = cast<CXXConstructorDecl>(MD); 6450 assert(CD->getInheritedConstructor() && 6451 "only special members have implicit exception specs"); 6452 Sema::InheritedConstructorInfo ICI( 6453 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6454 return ComputeDefaultedSpecialMemberExceptionSpec( 6455 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6456 } 6457 6458 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6459 CXXMethodDecl *MD) { 6460 FunctionProtoType::ExtProtoInfo EPI; 6461 6462 // Build an exception specification pointing back at this member. 6463 EPI.ExceptionSpec.Type = EST_Unevaluated; 6464 EPI.ExceptionSpec.SourceDecl = MD; 6465 6466 // Set the calling convention to the default for C++ instance methods. 6467 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6468 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6469 /*IsCXXMethod=*/true)); 6470 return EPI; 6471 } 6472 6473 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6474 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6475 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6476 return; 6477 6478 // Evaluate the exception specification. 6479 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6480 auto ESI = IES.getExceptionSpec(); 6481 6482 // Update the type of the special member to use it. 6483 UpdateExceptionSpec(MD, ESI); 6484 6485 // A user-provided destructor can be defined outside the class. When that 6486 // happens, be sure to update the exception specification on both 6487 // declarations. 6488 const FunctionProtoType *CanonicalFPT = 6489 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6490 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6491 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6492 } 6493 6494 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6495 CXXRecordDecl *RD = MD->getParent(); 6496 CXXSpecialMember CSM = getSpecialMember(MD); 6497 6498 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6499 "not an explicitly-defaulted special member"); 6500 6501 // Whether this was the first-declared instance of the constructor. 6502 // This affects whether we implicitly add an exception spec and constexpr. 6503 bool First = MD == MD->getCanonicalDecl(); 6504 6505 bool HadError = false; 6506 6507 // C++11 [dcl.fct.def.default]p1: 6508 // A function that is explicitly defaulted shall 6509 // -- be a special member function (checked elsewhere), 6510 // -- have the same type (except for ref-qualifiers, and except that a 6511 // copy operation can take a non-const reference) as an implicit 6512 // declaration, and 6513 // -- not have default arguments. 6514 // C++2a changes the second bullet to instead delete the function if it's 6515 // defaulted on its first declaration, unless it's "an assignment operator, 6516 // and its return type differs or its parameter type is not a reference". 6517 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6518 bool ShouldDeleteForTypeMismatch = false; 6519 unsigned ExpectedParams = 1; 6520 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6521 ExpectedParams = 0; 6522 if (MD->getNumParams() != ExpectedParams) { 6523 // This checks for default arguments: a copy or move constructor with a 6524 // default argument is classified as a default constructor, and assignment 6525 // operations and destructors can't have default arguments. 6526 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6527 << CSM << MD->getSourceRange(); 6528 HadError = true; 6529 } else if (MD->isVariadic()) { 6530 if (DeleteOnTypeMismatch) 6531 ShouldDeleteForTypeMismatch = true; 6532 else { 6533 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6534 << CSM << MD->getSourceRange(); 6535 HadError = true; 6536 } 6537 } 6538 6539 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6540 6541 bool CanHaveConstParam = false; 6542 if (CSM == CXXCopyConstructor) 6543 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6544 else if (CSM == CXXCopyAssignment) 6545 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6546 6547 QualType ReturnType = Context.VoidTy; 6548 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6549 // Check for return type matching. 6550 ReturnType = Type->getReturnType(); 6551 QualType ExpectedReturnType = 6552 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6553 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6554 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6555 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6556 HadError = true; 6557 } 6558 6559 // A defaulted special member cannot have cv-qualifiers. 6560 if (Type->getTypeQuals()) { 6561 if (DeleteOnTypeMismatch) 6562 ShouldDeleteForTypeMismatch = true; 6563 else { 6564 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6565 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6566 HadError = true; 6567 } 6568 } 6569 } 6570 6571 // Check for parameter type matching. 6572 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6573 bool HasConstParam = false; 6574 if (ExpectedParams && ArgType->isReferenceType()) { 6575 // Argument must be reference to possibly-const T. 6576 QualType ReferentType = ArgType->getPointeeType(); 6577 HasConstParam = ReferentType.isConstQualified(); 6578 6579 if (ReferentType.isVolatileQualified()) { 6580 if (DeleteOnTypeMismatch) 6581 ShouldDeleteForTypeMismatch = true; 6582 else { 6583 Diag(MD->getLocation(), 6584 diag::err_defaulted_special_member_volatile_param) << CSM; 6585 HadError = true; 6586 } 6587 } 6588 6589 if (HasConstParam && !CanHaveConstParam) { 6590 if (DeleteOnTypeMismatch) 6591 ShouldDeleteForTypeMismatch = true; 6592 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6593 Diag(MD->getLocation(), 6594 diag::err_defaulted_special_member_copy_const_param) 6595 << (CSM == CXXCopyAssignment); 6596 // FIXME: Explain why this special member can't be const. 6597 HadError = true; 6598 } else { 6599 Diag(MD->getLocation(), 6600 diag::err_defaulted_special_member_move_const_param) 6601 << (CSM == CXXMoveAssignment); 6602 HadError = true; 6603 } 6604 } 6605 } else if (ExpectedParams) { 6606 // A copy assignment operator can take its argument by value, but a 6607 // defaulted one cannot. 6608 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6609 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6610 HadError = true; 6611 } 6612 6613 // C++11 [dcl.fct.def.default]p2: 6614 // An explicitly-defaulted function may be declared constexpr only if it 6615 // would have been implicitly declared as constexpr, 6616 // Do not apply this rule to members of class templates, since core issue 1358 6617 // makes such functions always instantiate to constexpr functions. For 6618 // functions which cannot be constexpr (for non-constructors in C++11 and for 6619 // destructors in C++1y), this is checked elsewhere. 6620 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6621 HasConstParam); 6622 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6623 : isa<CXXConstructorDecl>(MD)) && 6624 MD->isConstexpr() && !Constexpr && 6625 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6626 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM; 6627 // FIXME: Explain why the special member can't be constexpr. 6628 HadError = true; 6629 } 6630 6631 // and may have an explicit exception-specification only if it is compatible 6632 // with the exception-specification on the implicit declaration. 6633 if (Type->hasExceptionSpec()) { 6634 // Delay the check if this is the first declaration of the special member, 6635 // since we may not have parsed some necessary in-class initializers yet. 6636 if (First) { 6637 // If the exception specification needs to be instantiated, do so now, 6638 // before we clobber it with an EST_Unevaluated specification below. 6639 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6640 InstantiateExceptionSpec(MD->getBeginLoc(), MD); 6641 Type = MD->getType()->getAs<FunctionProtoType>(); 6642 } 6643 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6644 } else 6645 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6646 } 6647 6648 // If a function is explicitly defaulted on its first declaration, 6649 if (First) { 6650 // -- it is implicitly considered to be constexpr if the implicit 6651 // definition would be, 6652 MD->setConstexpr(Constexpr); 6653 6654 // -- it is implicitly considered to have the same exception-specification 6655 // as if it had been implicitly declared, 6656 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6657 EPI.ExceptionSpec.Type = EST_Unevaluated; 6658 EPI.ExceptionSpec.SourceDecl = MD; 6659 MD->setType(Context.getFunctionType(ReturnType, 6660 llvm::makeArrayRef(&ArgType, 6661 ExpectedParams), 6662 EPI)); 6663 } 6664 6665 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 6666 if (First) { 6667 SetDeclDeleted(MD, MD->getLocation()); 6668 if (!inTemplateInstantiation() && !HadError) { 6669 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 6670 if (ShouldDeleteForTypeMismatch) { 6671 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 6672 } else { 6673 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6674 } 6675 } 6676 if (ShouldDeleteForTypeMismatch && !HadError) { 6677 Diag(MD->getLocation(), 6678 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 6679 } 6680 } else { 6681 // C++11 [dcl.fct.def.default]p4: 6682 // [For a] user-provided explicitly-defaulted function [...] if such a 6683 // function is implicitly defined as deleted, the program is ill-formed. 6684 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6685 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 6686 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6687 HadError = true; 6688 } 6689 } 6690 6691 if (HadError) 6692 MD->setInvalidDecl(); 6693 } 6694 6695 /// Check whether the exception specification provided for an 6696 /// explicitly-defaulted special member matches the exception specification 6697 /// that would have been generated for an implicit special member, per 6698 /// C++11 [dcl.fct.def.default]p2. 6699 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6700 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6701 // If the exception specification was explicitly specified but hadn't been 6702 // parsed when the method was defaulted, grab it now. 6703 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6704 SpecifiedType = 6705 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6706 6707 // Compute the implicit exception specification. 6708 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6709 /*IsCXXMethod=*/true); 6710 FunctionProtoType::ExtProtoInfo EPI(CC); 6711 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6712 EPI.ExceptionSpec = IES.getExceptionSpec(); 6713 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6714 Context.getFunctionType(Context.VoidTy, None, EPI)); 6715 6716 // Ensure that it matches. 6717 CheckEquivalentExceptionSpec( 6718 PDiag(diag::err_incorrect_defaulted_exception_spec) 6719 << getSpecialMember(MD), PDiag(), 6720 ImplicitType, SourceLocation(), 6721 SpecifiedType, MD->getLocation()); 6722 } 6723 6724 void Sema::CheckDelayedMemberExceptionSpecs() { 6725 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 6726 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 6727 decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted; 6728 6729 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 6730 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 6731 std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs); 6732 6733 // Perform any deferred checking of exception specifications for virtual 6734 // destructors. 6735 for (auto &Check : Overriding) 6736 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6737 6738 // Perform any deferred checking of exception specifications for befriended 6739 // special members. 6740 for (auto &Check : Equivalent) 6741 CheckEquivalentExceptionSpec(Check.second, Check.first); 6742 6743 // Check that any explicitly-defaulted methods have exception specifications 6744 // compatible with their implicit exception specifications. 6745 for (auto &Spec : Defaulted) 6746 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6747 } 6748 6749 namespace { 6750 /// CRTP base class for visiting operations performed by a special member 6751 /// function (or inherited constructor). 6752 template<typename Derived> 6753 struct SpecialMemberVisitor { 6754 Sema &S; 6755 CXXMethodDecl *MD; 6756 Sema::CXXSpecialMember CSM; 6757 Sema::InheritedConstructorInfo *ICI; 6758 6759 // Properties of the special member, computed for convenience. 6760 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6761 6762 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6763 Sema::InheritedConstructorInfo *ICI) 6764 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6765 switch (CSM) { 6766 case Sema::CXXDefaultConstructor: 6767 case Sema::CXXCopyConstructor: 6768 case Sema::CXXMoveConstructor: 6769 IsConstructor = true; 6770 break; 6771 case Sema::CXXCopyAssignment: 6772 case Sema::CXXMoveAssignment: 6773 IsAssignment = true; 6774 break; 6775 case Sema::CXXDestructor: 6776 break; 6777 case Sema::CXXInvalid: 6778 llvm_unreachable("invalid special member kind"); 6779 } 6780 6781 if (MD->getNumParams()) { 6782 if (const ReferenceType *RT = 6783 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6784 ConstArg = RT->getPointeeType().isConstQualified(); 6785 } 6786 } 6787 6788 Derived &getDerived() { return static_cast<Derived&>(*this); } 6789 6790 /// Is this a "move" special member? 6791 bool isMove() const { 6792 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6793 } 6794 6795 /// Look up the corresponding special member in the given class. 6796 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6797 unsigned Quals, bool IsMutable) { 6798 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6799 ConstArg && !IsMutable); 6800 } 6801 6802 /// Look up the constructor for the specified base class to see if it's 6803 /// overridden due to this being an inherited constructor. 6804 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6805 if (!ICI) 6806 return {}; 6807 assert(CSM == Sema::CXXDefaultConstructor); 6808 auto *BaseCtor = 6809 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6810 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6811 return MD; 6812 return {}; 6813 } 6814 6815 /// A base or member subobject. 6816 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6817 6818 /// Get the location to use for a subobject in diagnostics. 6819 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6820 // FIXME: For an indirect virtual base, the direct base leading to 6821 // the indirect virtual base would be a more useful choice. 6822 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6823 return B->getBaseTypeLoc(); 6824 else 6825 return Subobj.get<FieldDecl*>()->getLocation(); 6826 } 6827 6828 enum BasesToVisit { 6829 /// Visit all non-virtual (direct) bases. 6830 VisitNonVirtualBases, 6831 /// Visit all direct bases, virtual or not. 6832 VisitDirectBases, 6833 /// Visit all non-virtual bases, and all virtual bases if the class 6834 /// is not abstract. 6835 VisitPotentiallyConstructedBases, 6836 /// Visit all direct or virtual bases. 6837 VisitAllBases 6838 }; 6839 6840 // Visit the bases and members of the class. 6841 bool visit(BasesToVisit Bases) { 6842 CXXRecordDecl *RD = MD->getParent(); 6843 6844 if (Bases == VisitPotentiallyConstructedBases) 6845 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6846 6847 for (auto &B : RD->bases()) 6848 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6849 getDerived().visitBase(&B)) 6850 return true; 6851 6852 if (Bases == VisitAllBases) 6853 for (auto &B : RD->vbases()) 6854 if (getDerived().visitBase(&B)) 6855 return true; 6856 6857 for (auto *F : RD->fields()) 6858 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6859 getDerived().visitField(F)) 6860 return true; 6861 6862 return false; 6863 } 6864 }; 6865 } 6866 6867 namespace { 6868 struct SpecialMemberDeletionInfo 6869 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6870 bool Diagnose; 6871 6872 SourceLocation Loc; 6873 6874 bool AllFieldsAreConst; 6875 6876 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6877 Sema::CXXSpecialMember CSM, 6878 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6879 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6880 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6881 6882 bool inUnion() const { return MD->getParent()->isUnion(); } 6883 6884 Sema::CXXSpecialMember getEffectiveCSM() { 6885 return ICI ? Sema::CXXInvalid : CSM; 6886 } 6887 6888 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6889 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6890 6891 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6892 bool shouldDeleteForField(FieldDecl *FD); 6893 bool shouldDeleteForAllConstMembers(); 6894 6895 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6896 unsigned Quals); 6897 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6898 Sema::SpecialMemberOverloadResult SMOR, 6899 bool IsDtorCallInCtor); 6900 6901 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6902 }; 6903 } 6904 6905 /// Is the given special member inaccessible when used on the given 6906 /// sub-object. 6907 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6908 CXXMethodDecl *target) { 6909 /// If we're operating on a base class, the object type is the 6910 /// type of this special member. 6911 QualType objectTy; 6912 AccessSpecifier access = target->getAccess(); 6913 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6914 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6915 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6916 6917 // If we're operating on a field, the object type is the type of the field. 6918 } else { 6919 objectTy = S.Context.getTypeDeclType(target->getParent()); 6920 } 6921 6922 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6923 } 6924 6925 /// Check whether we should delete a special member due to the implicit 6926 /// definition containing a call to a special member of a subobject. 6927 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6928 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6929 bool IsDtorCallInCtor) { 6930 CXXMethodDecl *Decl = SMOR.getMethod(); 6931 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6932 6933 int DiagKind = -1; 6934 6935 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6936 DiagKind = !Decl ? 0 : 1; 6937 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6938 DiagKind = 2; 6939 else if (!isAccessible(Subobj, Decl)) 6940 DiagKind = 3; 6941 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6942 !Decl->isTrivial()) { 6943 // A member of a union must have a trivial corresponding special member. 6944 // As a weird special case, a destructor call from a union's constructor 6945 // must be accessible and non-deleted, but need not be trivial. Such a 6946 // destructor is never actually called, but is semantically checked as 6947 // if it were. 6948 DiagKind = 4; 6949 } 6950 6951 if (DiagKind == -1) 6952 return false; 6953 6954 if (Diagnose) { 6955 if (Field) { 6956 S.Diag(Field->getLocation(), 6957 diag::note_deleted_special_member_class_subobject) 6958 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6959 << Field << DiagKind << IsDtorCallInCtor; 6960 } else { 6961 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6962 S.Diag(Base->getBeginLoc(), 6963 diag::note_deleted_special_member_class_subobject) 6964 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 6965 << Base->getType() << DiagKind << IsDtorCallInCtor; 6966 } 6967 6968 if (DiagKind == 1) 6969 S.NoteDeletedFunction(Decl); 6970 // FIXME: Explain inaccessibility if DiagKind == 3. 6971 } 6972 6973 return true; 6974 } 6975 6976 /// Check whether we should delete a special member function due to having a 6977 /// direct or virtual base class or non-static data member of class type M. 6978 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6979 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6980 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6981 bool IsMutable = Field && Field->isMutable(); 6982 6983 // C++11 [class.ctor]p5: 6984 // -- any direct or virtual base class, or non-static data member with no 6985 // brace-or-equal-initializer, has class type M (or array thereof) and 6986 // either M has no default constructor or overload resolution as applied 6987 // to M's default constructor results in an ambiguity or in a function 6988 // that is deleted or inaccessible 6989 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6990 // -- a direct or virtual base class B that cannot be copied/moved because 6991 // overload resolution, as applied to B's corresponding special member, 6992 // results in an ambiguity or a function that is deleted or inaccessible 6993 // from the defaulted special member 6994 // C++11 [class.dtor]p5: 6995 // -- any direct or virtual base class [...] has a type with a destructor 6996 // that is deleted or inaccessible 6997 if (!(CSM == Sema::CXXDefaultConstructor && 6998 Field && Field->hasInClassInitializer()) && 6999 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 7000 false)) 7001 return true; 7002 7003 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 7004 // -- any direct or virtual base class or non-static data member has a 7005 // type with a destructor that is deleted or inaccessible 7006 if (IsConstructor) { 7007 Sema::SpecialMemberOverloadResult SMOR = 7008 S.LookupSpecialMember(Class, Sema::CXXDestructor, 7009 false, false, false, false, false); 7010 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 7011 return true; 7012 } 7013 7014 return false; 7015 } 7016 7017 /// Check whether we should delete a special member function due to the class 7018 /// having a particular direct or virtual base class. 7019 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 7020 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 7021 // If program is correct, BaseClass cannot be null, but if it is, the error 7022 // must be reported elsewhere. 7023 if (!BaseClass) 7024 return false; 7025 // If we have an inheriting constructor, check whether we're calling an 7026 // inherited constructor instead of a default constructor. 7027 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 7028 if (auto *BaseCtor = SMOR.getMethod()) { 7029 // Note that we do not check access along this path; other than that, 7030 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 7031 // FIXME: Check that the base has a usable destructor! Sink this into 7032 // shouldDeleteForClassSubobject. 7033 if (BaseCtor->isDeleted() && Diagnose) { 7034 S.Diag(Base->getBeginLoc(), 7035 diag::note_deleted_special_member_class_subobject) 7036 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7037 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false; 7038 S.NoteDeletedFunction(BaseCtor); 7039 } 7040 return BaseCtor->isDeleted(); 7041 } 7042 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 7043 } 7044 7045 /// Check whether we should delete a special member function due to the class 7046 /// having a particular non-static data member. 7047 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 7048 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 7049 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 7050 7051 if (CSM == Sema::CXXDefaultConstructor) { 7052 // For a default constructor, all references must be initialized in-class 7053 // and, if a union, it must have a non-const member. 7054 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 7055 if (Diagnose) 7056 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7057 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 7058 return true; 7059 } 7060 // C++11 [class.ctor]p5: any non-variant non-static data member of 7061 // const-qualified type (or array thereof) with no 7062 // brace-or-equal-initializer does not have a user-provided default 7063 // constructor. 7064 if (!inUnion() && FieldType.isConstQualified() && 7065 !FD->hasInClassInitializer() && 7066 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 7067 if (Diagnose) 7068 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7069 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 7070 return true; 7071 } 7072 7073 if (inUnion() && !FieldType.isConstQualified()) 7074 AllFieldsAreConst = false; 7075 } else if (CSM == Sema::CXXCopyConstructor) { 7076 // For a copy constructor, data members must not be of rvalue reference 7077 // type. 7078 if (FieldType->isRValueReferenceType()) { 7079 if (Diagnose) 7080 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 7081 << MD->getParent() << FD << FieldType; 7082 return true; 7083 } 7084 } else if (IsAssignment) { 7085 // For an assignment operator, data members must not be of reference type. 7086 if (FieldType->isReferenceType()) { 7087 if (Diagnose) 7088 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7089 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 7090 return true; 7091 } 7092 if (!FieldRecord && FieldType.isConstQualified()) { 7093 // C++11 [class.copy]p23: 7094 // -- a non-static data member of const non-class type (or array thereof) 7095 if (Diagnose) 7096 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7097 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 7098 return true; 7099 } 7100 } 7101 7102 if (FieldRecord) { 7103 // Some additional restrictions exist on the variant members. 7104 if (!inUnion() && FieldRecord->isUnion() && 7105 FieldRecord->isAnonymousStructOrUnion()) { 7106 bool AllVariantFieldsAreConst = true; 7107 7108 // FIXME: Handle anonymous unions declared within anonymous unions. 7109 for (auto *UI : FieldRecord->fields()) { 7110 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7111 7112 if (!UnionFieldType.isConstQualified()) 7113 AllVariantFieldsAreConst = false; 7114 7115 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7116 if (UnionFieldRecord && 7117 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7118 UnionFieldType.getCVRQualifiers())) 7119 return true; 7120 } 7121 7122 // At least one member in each anonymous union must be non-const 7123 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7124 !FieldRecord->field_empty()) { 7125 if (Diagnose) 7126 S.Diag(FieldRecord->getLocation(), 7127 diag::note_deleted_default_ctor_all_const) 7128 << !!ICI << MD->getParent() << /*anonymous union*/1; 7129 return true; 7130 } 7131 7132 // Don't check the implicit member of the anonymous union type. 7133 // This is technically non-conformant, but sanity demands it. 7134 return false; 7135 } 7136 7137 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7138 FieldType.getCVRQualifiers())) 7139 return true; 7140 } 7141 7142 return false; 7143 } 7144 7145 /// C++11 [class.ctor] p5: 7146 /// A defaulted default constructor for a class X is defined as deleted if 7147 /// X is a union and all of its variant members are of const-qualified type. 7148 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7149 // This is a silly definition, because it gives an empty union a deleted 7150 // default constructor. Don't do that. 7151 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7152 bool AnyFields = false; 7153 for (auto *F : MD->getParent()->fields()) 7154 if ((AnyFields = !F->isUnnamedBitfield())) 7155 break; 7156 if (!AnyFields) 7157 return false; 7158 if (Diagnose) 7159 S.Diag(MD->getParent()->getLocation(), 7160 diag::note_deleted_default_ctor_all_const) 7161 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7162 return true; 7163 } 7164 return false; 7165 } 7166 7167 /// Determine whether a defaulted special member function should be defined as 7168 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7169 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7170 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7171 InheritedConstructorInfo *ICI, 7172 bool Diagnose) { 7173 if (MD->isInvalidDecl()) 7174 return false; 7175 CXXRecordDecl *RD = MD->getParent(); 7176 assert(!RD->isDependentType() && "do deletion after instantiation"); 7177 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7178 return false; 7179 7180 // C++11 [expr.lambda.prim]p19: 7181 // The closure type associated with a lambda-expression has a 7182 // deleted (8.4.3) default constructor and a deleted copy 7183 // assignment operator. 7184 // C++2a adds back these operators if the lambda has no capture-default. 7185 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 7186 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7187 if (Diagnose) 7188 Diag(RD->getLocation(), diag::note_lambda_decl); 7189 return true; 7190 } 7191 7192 // For an anonymous struct or union, the copy and assignment special members 7193 // will never be used, so skip the check. For an anonymous union declared at 7194 // namespace scope, the constructor and destructor are used. 7195 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7196 RD->isAnonymousStructOrUnion()) 7197 return false; 7198 7199 // C++11 [class.copy]p7, p18: 7200 // If the class definition declares a move constructor or move assignment 7201 // operator, an implicitly declared copy constructor or copy assignment 7202 // operator is defined as deleted. 7203 if (MD->isImplicit() && 7204 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7205 CXXMethodDecl *UserDeclaredMove = nullptr; 7206 7207 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7208 // deletion of the corresponding copy operation, not both copy operations. 7209 // MSVC 2015 has adopted the standards conforming behavior. 7210 bool DeletesOnlyMatchingCopy = 7211 getLangOpts().MSVCCompat && 7212 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7213 7214 if (RD->hasUserDeclaredMoveConstructor() && 7215 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7216 if (!Diagnose) return true; 7217 7218 // Find any user-declared move constructor. 7219 for (auto *I : RD->ctors()) { 7220 if (I->isMoveConstructor()) { 7221 UserDeclaredMove = I; 7222 break; 7223 } 7224 } 7225 assert(UserDeclaredMove); 7226 } else if (RD->hasUserDeclaredMoveAssignment() && 7227 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7228 if (!Diagnose) return true; 7229 7230 // Find any user-declared move assignment operator. 7231 for (auto *I : RD->methods()) { 7232 if (I->isMoveAssignmentOperator()) { 7233 UserDeclaredMove = I; 7234 break; 7235 } 7236 } 7237 assert(UserDeclaredMove); 7238 } 7239 7240 if (UserDeclaredMove) { 7241 Diag(UserDeclaredMove->getLocation(), 7242 diag::note_deleted_copy_user_declared_move) 7243 << (CSM == CXXCopyAssignment) << RD 7244 << UserDeclaredMove->isMoveAssignmentOperator(); 7245 return true; 7246 } 7247 } 7248 7249 // Do access control from the special member function 7250 ContextRAII MethodContext(*this, MD); 7251 7252 // C++11 [class.dtor]p5: 7253 // -- for a virtual destructor, lookup of the non-array deallocation function 7254 // results in an ambiguity or in a function that is deleted or inaccessible 7255 if (CSM == CXXDestructor && MD->isVirtual()) { 7256 FunctionDecl *OperatorDelete = nullptr; 7257 DeclarationName Name = 7258 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7259 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7260 OperatorDelete, /*Diagnose*/false)) { 7261 if (Diagnose) 7262 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7263 return true; 7264 } 7265 } 7266 7267 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7268 7269 // Per DR1611, do not consider virtual bases of constructors of abstract 7270 // classes, since we are not going to construct them. 7271 // Per DR1658, do not consider virtual bases of destructors of abstract 7272 // classes either. 7273 // Per DR2180, for assignment operators we only assign (and thus only 7274 // consider) direct bases. 7275 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7276 : SMI.VisitPotentiallyConstructedBases)) 7277 return true; 7278 7279 if (SMI.shouldDeleteForAllConstMembers()) 7280 return true; 7281 7282 if (getLangOpts().CUDA) { 7283 // We should delete the special member in CUDA mode if target inference 7284 // failed. 7285 // For inherited constructors (non-null ICI), CSM may be passed so that MD 7286 // is treated as certain special member, which may not reflect what special 7287 // member MD really is. However inferCUDATargetForImplicitSpecialMember 7288 // expects CSM to match MD, therefore recalculate CSM. 7289 assert(ICI || CSM == getSpecialMember(MD)); 7290 auto RealCSM = CSM; 7291 if (ICI) 7292 RealCSM = getSpecialMember(MD); 7293 7294 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 7295 SMI.ConstArg, Diagnose); 7296 } 7297 7298 return false; 7299 } 7300 7301 /// Perform lookup for a special member of the specified kind, and determine 7302 /// whether it is trivial. If the triviality can be determined without the 7303 /// lookup, skip it. This is intended for use when determining whether a 7304 /// special member of a containing object is trivial, and thus does not ever 7305 /// perform overload resolution for default constructors. 7306 /// 7307 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7308 /// member that was most likely to be intended to be trivial, if any. 7309 /// 7310 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7311 /// determine whether the special member is trivial. 7312 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7313 Sema::CXXSpecialMember CSM, unsigned Quals, 7314 bool ConstRHS, 7315 Sema::TrivialABIHandling TAH, 7316 CXXMethodDecl **Selected) { 7317 if (Selected) 7318 *Selected = nullptr; 7319 7320 switch (CSM) { 7321 case Sema::CXXInvalid: 7322 llvm_unreachable("not a special member"); 7323 7324 case Sema::CXXDefaultConstructor: 7325 // C++11 [class.ctor]p5: 7326 // A default constructor is trivial if: 7327 // - all the [direct subobjects] have trivial default constructors 7328 // 7329 // Note, no overload resolution is performed in this case. 7330 if (RD->hasTrivialDefaultConstructor()) 7331 return true; 7332 7333 if (Selected) { 7334 // If there's a default constructor which could have been trivial, dig it 7335 // out. Otherwise, if there's any user-provided default constructor, point 7336 // to that as an example of why there's not a trivial one. 7337 CXXConstructorDecl *DefCtor = nullptr; 7338 if (RD->needsImplicitDefaultConstructor()) 7339 S.DeclareImplicitDefaultConstructor(RD); 7340 for (auto *CI : RD->ctors()) { 7341 if (!CI->isDefaultConstructor()) 7342 continue; 7343 DefCtor = CI; 7344 if (!DefCtor->isUserProvided()) 7345 break; 7346 } 7347 7348 *Selected = DefCtor; 7349 } 7350 7351 return false; 7352 7353 case Sema::CXXDestructor: 7354 // C++11 [class.dtor]p5: 7355 // A destructor is trivial if: 7356 // - all the direct [subobjects] have trivial destructors 7357 if (RD->hasTrivialDestructor() || 7358 (TAH == Sema::TAH_ConsiderTrivialABI && 7359 RD->hasTrivialDestructorForCall())) 7360 return true; 7361 7362 if (Selected) { 7363 if (RD->needsImplicitDestructor()) 7364 S.DeclareImplicitDestructor(RD); 7365 *Selected = RD->getDestructor(); 7366 } 7367 7368 return false; 7369 7370 case Sema::CXXCopyConstructor: 7371 // C++11 [class.copy]p12: 7372 // A copy constructor is trivial if: 7373 // - the constructor selected to copy each direct [subobject] is trivial 7374 if (RD->hasTrivialCopyConstructor() || 7375 (TAH == Sema::TAH_ConsiderTrivialABI && 7376 RD->hasTrivialCopyConstructorForCall())) { 7377 if (Quals == Qualifiers::Const) 7378 // We must either select the trivial copy constructor or reach an 7379 // ambiguity; no need to actually perform overload resolution. 7380 return true; 7381 } else if (!Selected) { 7382 return false; 7383 } 7384 // In C++98, we are not supposed to perform overload resolution here, but we 7385 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7386 // cases like B as having a non-trivial copy constructor: 7387 // struct A { template<typename T> A(T&); }; 7388 // struct B { mutable A a; }; 7389 goto NeedOverloadResolution; 7390 7391 case Sema::CXXCopyAssignment: 7392 // C++11 [class.copy]p25: 7393 // A copy assignment operator is trivial if: 7394 // - the assignment operator selected to copy each direct [subobject] is 7395 // trivial 7396 if (RD->hasTrivialCopyAssignment()) { 7397 if (Quals == Qualifiers::Const) 7398 return true; 7399 } else if (!Selected) { 7400 return false; 7401 } 7402 // In C++98, we are not supposed to perform overload resolution here, but we 7403 // treat that as a language defect. 7404 goto NeedOverloadResolution; 7405 7406 case Sema::CXXMoveConstructor: 7407 case Sema::CXXMoveAssignment: 7408 NeedOverloadResolution: 7409 Sema::SpecialMemberOverloadResult SMOR = 7410 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7411 7412 // The standard doesn't describe how to behave if the lookup is ambiguous. 7413 // We treat it as not making the member non-trivial, just like the standard 7414 // mandates for the default constructor. This should rarely matter, because 7415 // the member will also be deleted. 7416 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7417 return true; 7418 7419 if (!SMOR.getMethod()) { 7420 assert(SMOR.getKind() == 7421 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7422 return false; 7423 } 7424 7425 // We deliberately don't check if we found a deleted special member. We're 7426 // not supposed to! 7427 if (Selected) 7428 *Selected = SMOR.getMethod(); 7429 7430 if (TAH == Sema::TAH_ConsiderTrivialABI && 7431 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7432 return SMOR.getMethod()->isTrivialForCall(); 7433 return SMOR.getMethod()->isTrivial(); 7434 } 7435 7436 llvm_unreachable("unknown special method kind"); 7437 } 7438 7439 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7440 for (auto *CI : RD->ctors()) 7441 if (!CI->isImplicit()) 7442 return CI; 7443 7444 // Look for constructor templates. 7445 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7446 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7447 if (CXXConstructorDecl *CD = 7448 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7449 return CD; 7450 } 7451 7452 return nullptr; 7453 } 7454 7455 /// The kind of subobject we are checking for triviality. The values of this 7456 /// enumeration are used in diagnostics. 7457 enum TrivialSubobjectKind { 7458 /// The subobject is a base class. 7459 TSK_BaseClass, 7460 /// The subobject is a non-static data member. 7461 TSK_Field, 7462 /// The object is actually the complete object. 7463 TSK_CompleteObject 7464 }; 7465 7466 /// Check whether the special member selected for a given type would be trivial. 7467 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7468 QualType SubType, bool ConstRHS, 7469 Sema::CXXSpecialMember CSM, 7470 TrivialSubobjectKind Kind, 7471 Sema::TrivialABIHandling TAH, bool Diagnose) { 7472 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7473 if (!SubRD) 7474 return true; 7475 7476 CXXMethodDecl *Selected; 7477 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7478 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7479 return true; 7480 7481 if (Diagnose) { 7482 if (ConstRHS) 7483 SubType.addConst(); 7484 7485 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7486 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7487 << Kind << SubType.getUnqualifiedType(); 7488 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7489 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7490 } else if (!Selected) 7491 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7492 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7493 else if (Selected->isUserProvided()) { 7494 if (Kind == TSK_CompleteObject) 7495 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7496 << Kind << SubType.getUnqualifiedType() << CSM; 7497 else { 7498 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7499 << Kind << SubType.getUnqualifiedType() << CSM; 7500 S.Diag(Selected->getLocation(), diag::note_declared_at); 7501 } 7502 } else { 7503 if (Kind != TSK_CompleteObject) 7504 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7505 << Kind << SubType.getUnqualifiedType() << CSM; 7506 7507 // Explain why the defaulted or deleted special member isn't trivial. 7508 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7509 Diagnose); 7510 } 7511 } 7512 7513 return false; 7514 } 7515 7516 /// Check whether the members of a class type allow a special member to be 7517 /// trivial. 7518 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7519 Sema::CXXSpecialMember CSM, 7520 bool ConstArg, 7521 Sema::TrivialABIHandling TAH, 7522 bool Diagnose) { 7523 for (const auto *FI : RD->fields()) { 7524 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7525 continue; 7526 7527 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7528 7529 // Pretend anonymous struct or union members are members of this class. 7530 if (FI->isAnonymousStructOrUnion()) { 7531 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7532 CSM, ConstArg, TAH, Diagnose)) 7533 return false; 7534 continue; 7535 } 7536 7537 // C++11 [class.ctor]p5: 7538 // A default constructor is trivial if [...] 7539 // -- no non-static data member of its class has a 7540 // brace-or-equal-initializer 7541 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7542 if (Diagnose) 7543 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7544 return false; 7545 } 7546 7547 // Objective C ARC 4.3.5: 7548 // [...] nontrivally ownership-qualified types are [...] not trivially 7549 // default constructible, copy constructible, move constructible, copy 7550 // assignable, move assignable, or destructible [...] 7551 if (FieldType.hasNonTrivialObjCLifetime()) { 7552 if (Diagnose) 7553 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7554 << RD << FieldType.getObjCLifetime(); 7555 return false; 7556 } 7557 7558 bool ConstRHS = ConstArg && !FI->isMutable(); 7559 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7560 CSM, TSK_Field, TAH, Diagnose)) 7561 return false; 7562 } 7563 7564 return true; 7565 } 7566 7567 /// Diagnose why the specified class does not have a trivial special member of 7568 /// the given kind. 7569 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7570 QualType Ty = Context.getRecordType(RD); 7571 7572 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7573 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7574 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7575 /*Diagnose*/true); 7576 } 7577 7578 /// Determine whether a defaulted or deleted special member function is trivial, 7579 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7580 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7581 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7582 TrivialABIHandling TAH, bool Diagnose) { 7583 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7584 7585 CXXRecordDecl *RD = MD->getParent(); 7586 7587 bool ConstArg = false; 7588 7589 // C++11 [class.copy]p12, p25: [DR1593] 7590 // A [special member] is trivial if [...] its parameter-type-list is 7591 // equivalent to the parameter-type-list of an implicit declaration [...] 7592 switch (CSM) { 7593 case CXXDefaultConstructor: 7594 case CXXDestructor: 7595 // Trivial default constructors and destructors cannot have parameters. 7596 break; 7597 7598 case CXXCopyConstructor: 7599 case CXXCopyAssignment: { 7600 // Trivial copy operations always have const, non-volatile parameter types. 7601 ConstArg = true; 7602 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7603 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7604 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7605 if (Diagnose) 7606 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7607 << Param0->getSourceRange() << Param0->getType() 7608 << Context.getLValueReferenceType( 7609 Context.getRecordType(RD).withConst()); 7610 return false; 7611 } 7612 break; 7613 } 7614 7615 case CXXMoveConstructor: 7616 case CXXMoveAssignment: { 7617 // Trivial move operations always have non-cv-qualified parameters. 7618 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7619 const RValueReferenceType *RT = 7620 Param0->getType()->getAs<RValueReferenceType>(); 7621 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7622 if (Diagnose) 7623 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7624 << Param0->getSourceRange() << Param0->getType() 7625 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7626 return false; 7627 } 7628 break; 7629 } 7630 7631 case CXXInvalid: 7632 llvm_unreachable("not a special member"); 7633 } 7634 7635 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7636 if (Diagnose) 7637 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7638 diag::note_nontrivial_default_arg) 7639 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7640 return false; 7641 } 7642 if (MD->isVariadic()) { 7643 if (Diagnose) 7644 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7645 return false; 7646 } 7647 7648 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7649 // A copy/move [constructor or assignment operator] is trivial if 7650 // -- the [member] selected to copy/move each direct base class subobject 7651 // is trivial 7652 // 7653 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7654 // A [default constructor or destructor] is trivial if 7655 // -- all the direct base classes have trivial [default constructors or 7656 // destructors] 7657 for (const auto &BI : RD->bases()) 7658 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 7659 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7660 return false; 7661 7662 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7663 // A copy/move [constructor or assignment operator] for a class X is 7664 // trivial if 7665 // -- for each non-static data member of X that is of class type (or array 7666 // thereof), the constructor selected to copy/move that member is 7667 // trivial 7668 // 7669 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7670 // A [default constructor or destructor] is trivial if 7671 // -- for all of the non-static data members of its class that are of class 7672 // type (or array thereof), each such class has a trivial [default 7673 // constructor or destructor] 7674 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7675 return false; 7676 7677 // C++11 [class.dtor]p5: 7678 // A destructor is trivial if [...] 7679 // -- the destructor is not virtual 7680 if (CSM == CXXDestructor && MD->isVirtual()) { 7681 if (Diagnose) 7682 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7683 return false; 7684 } 7685 7686 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7687 // A [special member] for class X is trivial if [...] 7688 // -- class X has no virtual functions and no virtual base classes 7689 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7690 if (!Diagnose) 7691 return false; 7692 7693 if (RD->getNumVBases()) { 7694 // Check for virtual bases. We already know that the corresponding 7695 // member in all bases is trivial, so vbases must all be direct. 7696 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7697 assert(BS.isVirtual()); 7698 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 7699 return false; 7700 } 7701 7702 // Must have a virtual method. 7703 for (const auto *MI : RD->methods()) { 7704 if (MI->isVirtual()) { 7705 SourceLocation MLoc = MI->getBeginLoc(); 7706 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7707 return false; 7708 } 7709 } 7710 7711 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7712 } 7713 7714 // Looks like it's trivial! 7715 return true; 7716 } 7717 7718 namespace { 7719 struct FindHiddenVirtualMethod { 7720 Sema *S; 7721 CXXMethodDecl *Method; 7722 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7723 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7724 7725 private: 7726 /// Check whether any most overridden method from MD in Methods 7727 static bool CheckMostOverridenMethods( 7728 const CXXMethodDecl *MD, 7729 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7730 if (MD->size_overridden_methods() == 0) 7731 return Methods.count(MD->getCanonicalDecl()); 7732 for (const CXXMethodDecl *O : MD->overridden_methods()) 7733 if (CheckMostOverridenMethods(O, Methods)) 7734 return true; 7735 return false; 7736 } 7737 7738 public: 7739 /// Member lookup function that determines whether a given C++ 7740 /// method overloads virtual methods in a base class without overriding any, 7741 /// to be used with CXXRecordDecl::lookupInBases(). 7742 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7743 RecordDecl *BaseRecord = 7744 Specifier->getType()->getAs<RecordType>()->getDecl(); 7745 7746 DeclarationName Name = Method->getDeclName(); 7747 assert(Name.getNameKind() == DeclarationName::Identifier); 7748 7749 bool foundSameNameMethod = false; 7750 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7751 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7752 Path.Decls = Path.Decls.slice(1)) { 7753 NamedDecl *D = Path.Decls.front(); 7754 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7755 MD = MD->getCanonicalDecl(); 7756 foundSameNameMethod = true; 7757 // Interested only in hidden virtual methods. 7758 if (!MD->isVirtual()) 7759 continue; 7760 // If the method we are checking overrides a method from its base 7761 // don't warn about the other overloaded methods. Clang deviates from 7762 // GCC by only diagnosing overloads of inherited virtual functions that 7763 // do not override any other virtual functions in the base. GCC's 7764 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7765 // function from a base class. These cases may be better served by a 7766 // warning (not specific to virtual functions) on call sites when the 7767 // call would select a different function from the base class, were it 7768 // visible. 7769 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7770 if (!S->IsOverload(Method, MD, false)) 7771 return true; 7772 // Collect the overload only if its hidden. 7773 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7774 overloadedMethods.push_back(MD); 7775 } 7776 } 7777 7778 if (foundSameNameMethod) 7779 OverloadedMethods.append(overloadedMethods.begin(), 7780 overloadedMethods.end()); 7781 return foundSameNameMethod; 7782 } 7783 }; 7784 } // end anonymous namespace 7785 7786 /// Add the most overriden methods from MD to Methods 7787 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7788 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7789 if (MD->size_overridden_methods() == 0) 7790 Methods.insert(MD->getCanonicalDecl()); 7791 else 7792 for (const CXXMethodDecl *O : MD->overridden_methods()) 7793 AddMostOverridenMethods(O, Methods); 7794 } 7795 7796 /// Check if a method overloads virtual methods in a base class without 7797 /// overriding any. 7798 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7799 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7800 if (!MD->getDeclName().isIdentifier()) 7801 return; 7802 7803 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7804 /*bool RecordPaths=*/false, 7805 /*bool DetectVirtual=*/false); 7806 FindHiddenVirtualMethod FHVM; 7807 FHVM.Method = MD; 7808 FHVM.S = this; 7809 7810 // Keep the base methods that were overridden or introduced in the subclass 7811 // by 'using' in a set. A base method not in this set is hidden. 7812 CXXRecordDecl *DC = MD->getParent(); 7813 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7814 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7815 NamedDecl *ND = *I; 7816 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7817 ND = shad->getTargetDecl(); 7818 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7819 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7820 } 7821 7822 if (DC->lookupInBases(FHVM, Paths)) 7823 OverloadedMethods = FHVM.OverloadedMethods; 7824 } 7825 7826 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7827 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7828 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7829 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7830 PartialDiagnostic PD = PDiag( 7831 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7832 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7833 Diag(overloadedMD->getLocation(), PD); 7834 } 7835 } 7836 7837 /// Diagnose methods which overload virtual methods in a base class 7838 /// without overriding any. 7839 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7840 if (MD->isInvalidDecl()) 7841 return; 7842 7843 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7844 return; 7845 7846 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7847 FindHiddenVirtualMethods(MD, OverloadedMethods); 7848 if (!OverloadedMethods.empty()) { 7849 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7850 << MD << (OverloadedMethods.size() > 1); 7851 7852 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7853 } 7854 } 7855 7856 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 7857 auto PrintDiagAndRemoveAttr = [&]() { 7858 // No diagnostics if this is a template instantiation. 7859 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 7860 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 7861 diag::ext_cannot_use_trivial_abi) << &RD; 7862 RD.dropAttr<TrivialABIAttr>(); 7863 }; 7864 7865 // Ill-formed if the struct has virtual functions. 7866 if (RD.isPolymorphic()) { 7867 PrintDiagAndRemoveAttr(); 7868 return; 7869 } 7870 7871 for (const auto &B : RD.bases()) { 7872 // Ill-formed if the base class is non-trivial for the purpose of calls or a 7873 // virtual base. 7874 if ((!B.getType()->isDependentType() && 7875 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 7876 B.isVirtual()) { 7877 PrintDiagAndRemoveAttr(); 7878 return; 7879 } 7880 } 7881 7882 for (const auto *FD : RD.fields()) { 7883 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 7884 // non-trivial for the purpose of calls. 7885 QualType FT = FD->getType(); 7886 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 7887 PrintDiagAndRemoveAttr(); 7888 return; 7889 } 7890 7891 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 7892 if (!RT->isDependentType() && 7893 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 7894 PrintDiagAndRemoveAttr(); 7895 return; 7896 } 7897 } 7898 } 7899 7900 void Sema::ActOnFinishCXXMemberSpecification( 7901 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 7902 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 7903 if (!TagDecl) 7904 return; 7905 7906 AdjustDeclIfTemplate(TagDecl); 7907 7908 for (const ParsedAttr &AL : AttrList) { 7909 if (AL.getKind() != ParsedAttr::AT_Visibility) 7910 continue; 7911 AL.setInvalid(); 7912 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) 7913 << AL.getName(); 7914 } 7915 7916 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7917 // strict aliasing violation! 7918 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7919 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7920 7921 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); 7922 } 7923 7924 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7925 /// special functions, such as the default constructor, copy 7926 /// constructor, or destructor, to the given C++ class (C++ 7927 /// [special]p1). This routine can only be executed just before the 7928 /// definition of the class is complete. 7929 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7930 if (ClassDecl->needsImplicitDefaultConstructor()) { 7931 ++ASTContext::NumImplicitDefaultConstructors; 7932 7933 if (ClassDecl->hasInheritedConstructor()) 7934 DeclareImplicitDefaultConstructor(ClassDecl); 7935 } 7936 7937 if (ClassDecl->needsImplicitCopyConstructor()) { 7938 ++ASTContext::NumImplicitCopyConstructors; 7939 7940 // If the properties or semantics of the copy constructor couldn't be 7941 // determined while the class was being declared, force a declaration 7942 // of it now. 7943 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7944 ClassDecl->hasInheritedConstructor()) 7945 DeclareImplicitCopyConstructor(ClassDecl); 7946 // For the MS ABI we need to know whether the copy ctor is deleted. A 7947 // prerequisite for deleting the implicit copy ctor is that the class has a 7948 // move ctor or move assignment that is either user-declared or whose 7949 // semantics are inherited from a subobject. FIXME: We should provide a more 7950 // direct way for CodeGen to ask whether the constructor was deleted. 7951 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7952 (ClassDecl->hasUserDeclaredMoveConstructor() || 7953 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7954 ClassDecl->hasUserDeclaredMoveAssignment() || 7955 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7956 DeclareImplicitCopyConstructor(ClassDecl); 7957 } 7958 7959 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7960 ++ASTContext::NumImplicitMoveConstructors; 7961 7962 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7963 ClassDecl->hasInheritedConstructor()) 7964 DeclareImplicitMoveConstructor(ClassDecl); 7965 } 7966 7967 if (ClassDecl->needsImplicitCopyAssignment()) { 7968 ++ASTContext::NumImplicitCopyAssignmentOperators; 7969 7970 // If we have a dynamic class, then the copy assignment operator may be 7971 // virtual, so we have to declare it immediately. This ensures that, e.g., 7972 // it shows up in the right place in the vtable and that we diagnose 7973 // problems with the implicit exception specification. 7974 if (ClassDecl->isDynamicClass() || 7975 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7976 ClassDecl->hasInheritedAssignment()) 7977 DeclareImplicitCopyAssignment(ClassDecl); 7978 } 7979 7980 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7981 ++ASTContext::NumImplicitMoveAssignmentOperators; 7982 7983 // Likewise for the move assignment operator. 7984 if (ClassDecl->isDynamicClass() || 7985 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7986 ClassDecl->hasInheritedAssignment()) 7987 DeclareImplicitMoveAssignment(ClassDecl); 7988 } 7989 7990 if (ClassDecl->needsImplicitDestructor()) { 7991 ++ASTContext::NumImplicitDestructors; 7992 7993 // If we have a dynamic class, then the destructor may be virtual, so we 7994 // have to declare the destructor immediately. This ensures that, e.g., it 7995 // shows up in the right place in the vtable and that we diagnose problems 7996 // with the implicit exception specification. 7997 if (ClassDecl->isDynamicClass() || 7998 ClassDecl->needsOverloadResolutionForDestructor()) 7999 DeclareImplicitDestructor(ClassDecl); 8000 } 8001 } 8002 8003 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 8004 if (!D) 8005 return 0; 8006 8007 // The order of template parameters is not important here. All names 8008 // get added to the same scope. 8009 SmallVector<TemplateParameterList *, 4> ParameterLists; 8010 8011 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8012 D = TD->getTemplatedDecl(); 8013 8014 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 8015 ParameterLists.push_back(PSD->getTemplateParameters()); 8016 8017 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 8018 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 8019 ParameterLists.push_back(DD->getTemplateParameterList(i)); 8020 8021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8022 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 8023 ParameterLists.push_back(FTD->getTemplateParameters()); 8024 } 8025 } 8026 8027 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 8028 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 8029 ParameterLists.push_back(TD->getTemplateParameterList(i)); 8030 8031 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 8032 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 8033 ParameterLists.push_back(CTD->getTemplateParameters()); 8034 } 8035 } 8036 8037 unsigned Count = 0; 8038 for (TemplateParameterList *Params : ParameterLists) { 8039 if (Params->size() > 0) 8040 // Ignore explicit specializations; they don't contribute to the template 8041 // depth. 8042 ++Count; 8043 for (NamedDecl *Param : *Params) { 8044 if (Param->getDeclName()) { 8045 S->AddDecl(Param); 8046 IdResolver.AddDecl(Param); 8047 } 8048 } 8049 } 8050 8051 return Count; 8052 } 8053 8054 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8055 if (!RecordD) return; 8056 AdjustDeclIfTemplate(RecordD); 8057 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 8058 PushDeclContext(S, Record); 8059 } 8060 8061 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8062 if (!RecordD) return; 8063 PopDeclContext(); 8064 } 8065 8066 /// This is used to implement the constant expression evaluation part of the 8067 /// attribute enable_if extension. There is nothing in standard C++ which would 8068 /// require reentering parameters. 8069 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 8070 if (!Param) 8071 return; 8072 8073 S->AddDecl(Param); 8074 if (Param->getDeclName()) 8075 IdResolver.AddDecl(Param); 8076 } 8077 8078 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 8079 /// parsing a top-level (non-nested) C++ class, and we are now 8080 /// parsing those parts of the given Method declaration that could 8081 /// not be parsed earlier (C++ [class.mem]p2), such as default 8082 /// arguments. This action should enter the scope of the given 8083 /// Method declaration as if we had just parsed the qualified method 8084 /// name. However, it should not bring the parameters into scope; 8085 /// that will be performed by ActOnDelayedCXXMethodParameter. 8086 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8087 } 8088 8089 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 8090 /// C++ method declaration. We're (re-)introducing the given 8091 /// function parameter into scope for use in parsing later parts of 8092 /// the method declaration. For example, we could see an 8093 /// ActOnParamDefaultArgument event for this parameter. 8094 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 8095 if (!ParamD) 8096 return; 8097 8098 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 8099 8100 // If this parameter has an unparsed default argument, clear it out 8101 // to make way for the parsed default argument. 8102 if (Param->hasUnparsedDefaultArg()) 8103 Param->setDefaultArg(nullptr); 8104 8105 S->AddDecl(Param); 8106 if (Param->getDeclName()) 8107 IdResolver.AddDecl(Param); 8108 } 8109 8110 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8111 /// processing the delayed method declaration for Method. The method 8112 /// declaration is now considered finished. There may be a separate 8113 /// ActOnStartOfFunctionDef action later (not necessarily 8114 /// immediately!) for this method, if it was also defined inside the 8115 /// class body. 8116 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8117 if (!MethodD) 8118 return; 8119 8120 AdjustDeclIfTemplate(MethodD); 8121 8122 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8123 8124 // Now that we have our default arguments, check the constructor 8125 // again. It could produce additional diagnostics or affect whether 8126 // the class has implicitly-declared destructors, among other 8127 // things. 8128 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8129 CheckConstructor(Constructor); 8130 8131 // Check the default arguments, which we may have added. 8132 if (!Method->isInvalidDecl()) 8133 CheckCXXDefaultArguments(Method); 8134 } 8135 8136 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8137 /// the well-formedness of the constructor declarator @p D with type @p 8138 /// R. If there are any errors in the declarator, this routine will 8139 /// emit diagnostics and set the invalid bit to true. In any case, the type 8140 /// will be updated to reflect a well-formed type for the constructor and 8141 /// returned. 8142 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8143 StorageClass &SC) { 8144 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8145 8146 // C++ [class.ctor]p3: 8147 // A constructor shall not be virtual (10.3) or static (9.4). A 8148 // constructor can be invoked for a const, volatile or const 8149 // volatile object. A constructor shall not be declared const, 8150 // volatile, or const volatile (9.3.2). 8151 if (isVirtual) { 8152 if (!D.isInvalidType()) 8153 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8154 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8155 << SourceRange(D.getIdentifierLoc()); 8156 D.setInvalidType(); 8157 } 8158 if (SC == SC_Static) { 8159 if (!D.isInvalidType()) 8160 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8161 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8162 << SourceRange(D.getIdentifierLoc()); 8163 D.setInvalidType(); 8164 SC = SC_None; 8165 } 8166 8167 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8168 diagnoseIgnoredQualifiers( 8169 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8170 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8171 D.getDeclSpec().getRestrictSpecLoc(), 8172 D.getDeclSpec().getAtomicSpecLoc()); 8173 D.setInvalidType(); 8174 } 8175 8176 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8177 if (FTI.hasMethodTypeQualifiers()) { 8178 FTI.MethodQualifiers->forEachQualifier( 8179 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { 8180 Diag(SL, diag::err_invalid_qualified_constructor) 8181 << QualName << SourceRange(SL); 8182 }); 8183 D.setInvalidType(); 8184 } 8185 8186 // C++0x [class.ctor]p4: 8187 // A constructor shall not be declared with a ref-qualifier. 8188 if (FTI.hasRefQualifier()) { 8189 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8190 << FTI.RefQualifierIsLValueRef 8191 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8192 D.setInvalidType(); 8193 } 8194 8195 // Rebuild the function type "R" without any type qualifiers (in 8196 // case any of the errors above fired) and with "void" as the 8197 // return type, since constructors don't have return types. 8198 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8199 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8200 return R; 8201 8202 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8203 EPI.TypeQuals = Qualifiers(); 8204 EPI.RefQualifier = RQ_None; 8205 8206 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8207 } 8208 8209 /// CheckConstructor - Checks a fully-formed constructor for 8210 /// well-formedness, issuing any diagnostics required. Returns true if 8211 /// the constructor declarator is invalid. 8212 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8213 CXXRecordDecl *ClassDecl 8214 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8215 if (!ClassDecl) 8216 return Constructor->setInvalidDecl(); 8217 8218 // C++ [class.copy]p3: 8219 // A declaration of a constructor for a class X is ill-formed if 8220 // its first parameter is of type (optionally cv-qualified) X and 8221 // either there are no other parameters or else all other 8222 // parameters have default arguments. 8223 if (!Constructor->isInvalidDecl() && 8224 ((Constructor->getNumParams() == 1) || 8225 (Constructor->getNumParams() > 1 && 8226 Constructor->getParamDecl(1)->hasDefaultArg())) && 8227 Constructor->getTemplateSpecializationKind() 8228 != TSK_ImplicitInstantiation) { 8229 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8230 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8231 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8232 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8233 const char *ConstRef 8234 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8235 : " const &"; 8236 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8237 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8238 8239 // FIXME: Rather that making the constructor invalid, we should endeavor 8240 // to fix the type. 8241 Constructor->setInvalidDecl(); 8242 } 8243 } 8244 } 8245 8246 /// CheckDestructor - Checks a fully-formed destructor definition for 8247 /// well-formedness, issuing any diagnostics required. Returns true 8248 /// on error. 8249 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8250 CXXRecordDecl *RD = Destructor->getParent(); 8251 8252 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8253 SourceLocation Loc; 8254 8255 if (!Destructor->isImplicit()) 8256 Loc = Destructor->getLocation(); 8257 else 8258 Loc = RD->getLocation(); 8259 8260 // If we have a virtual destructor, look up the deallocation function 8261 if (FunctionDecl *OperatorDelete = 8262 FindDeallocationFunctionForDestructor(Loc, RD)) { 8263 Expr *ThisArg = nullptr; 8264 8265 // If the notional 'delete this' expression requires a non-trivial 8266 // conversion from 'this' to the type of a destroying operator delete's 8267 // first parameter, perform that conversion now. 8268 if (OperatorDelete->isDestroyingOperatorDelete()) { 8269 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8270 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8271 // C++ [class.dtor]p13: 8272 // ... as if for the expression 'delete this' appearing in a 8273 // non-virtual destructor of the destructor's class. 8274 ContextRAII SwitchContext(*this, Destructor); 8275 ExprResult This = 8276 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8277 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8278 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8279 if (This.isInvalid()) { 8280 // FIXME: Register this as a context note so that it comes out 8281 // in the right order. 8282 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8283 return true; 8284 } 8285 ThisArg = This.get(); 8286 } 8287 } 8288 8289 DiagnoseUseOfDecl(OperatorDelete, Loc); 8290 MarkFunctionReferenced(Loc, OperatorDelete); 8291 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8292 } 8293 } 8294 8295 return false; 8296 } 8297 8298 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8299 /// the well-formednes of the destructor declarator @p D with type @p 8300 /// R. If there are any errors in the declarator, this routine will 8301 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8302 /// will be updated to reflect a well-formed type for the destructor and 8303 /// returned. 8304 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8305 StorageClass& SC) { 8306 // C++ [class.dtor]p1: 8307 // [...] A typedef-name that names a class is a class-name 8308 // (7.1.3); however, a typedef-name that names a class shall not 8309 // be used as the identifier in the declarator for a destructor 8310 // declaration. 8311 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8312 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8313 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8314 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8315 else if (const TemplateSpecializationType *TST = 8316 DeclaratorType->getAs<TemplateSpecializationType>()) 8317 if (TST->isTypeAlias()) 8318 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8319 << DeclaratorType << 1; 8320 8321 // C++ [class.dtor]p2: 8322 // A destructor is used to destroy objects of its class type. A 8323 // destructor takes no parameters, and no return type can be 8324 // specified for it (not even void). The address of a destructor 8325 // shall not be taken. A destructor shall not be static. A 8326 // destructor can be invoked for a const, volatile or const 8327 // volatile object. A destructor shall not be declared const, 8328 // volatile or const volatile (9.3.2). 8329 if (SC == SC_Static) { 8330 if (!D.isInvalidType()) 8331 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8332 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8333 << SourceRange(D.getIdentifierLoc()) 8334 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8335 8336 SC = SC_None; 8337 } 8338 if (!D.isInvalidType()) { 8339 // Destructors don't have return types, but the parser will 8340 // happily parse something like: 8341 // 8342 // class X { 8343 // float ~X(); 8344 // }; 8345 // 8346 // The return type will be eliminated later. 8347 if (D.getDeclSpec().hasTypeSpecifier()) 8348 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8349 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8350 << SourceRange(D.getIdentifierLoc()); 8351 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8352 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8353 SourceLocation(), 8354 D.getDeclSpec().getConstSpecLoc(), 8355 D.getDeclSpec().getVolatileSpecLoc(), 8356 D.getDeclSpec().getRestrictSpecLoc(), 8357 D.getDeclSpec().getAtomicSpecLoc()); 8358 D.setInvalidType(); 8359 } 8360 } 8361 8362 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8363 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 8364 FTI.MethodQualifiers->forEachQualifier( 8365 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { 8366 Diag(SL, diag::err_invalid_qualified_destructor) 8367 << QualName << SourceRange(SL); 8368 }); 8369 D.setInvalidType(); 8370 } 8371 8372 // C++0x [class.dtor]p2: 8373 // A destructor shall not be declared with a ref-qualifier. 8374 if (FTI.hasRefQualifier()) { 8375 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8376 << FTI.RefQualifierIsLValueRef 8377 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8378 D.setInvalidType(); 8379 } 8380 8381 // Make sure we don't have any parameters. 8382 if (FTIHasNonVoidParameters(FTI)) { 8383 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8384 8385 // Delete the parameters. 8386 FTI.freeParams(); 8387 D.setInvalidType(); 8388 } 8389 8390 // Make sure the destructor isn't variadic. 8391 if (FTI.isVariadic) { 8392 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8393 D.setInvalidType(); 8394 } 8395 8396 // Rebuild the function type "R" without any type qualifiers or 8397 // parameters (in case any of the errors above fired) and with 8398 // "void" as the return type, since destructors don't have return 8399 // types. 8400 if (!D.isInvalidType()) 8401 return R; 8402 8403 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8404 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8405 EPI.Variadic = false; 8406 EPI.TypeQuals = Qualifiers(); 8407 EPI.RefQualifier = RQ_None; 8408 return Context.getFunctionType(Context.VoidTy, None, EPI); 8409 } 8410 8411 static void extendLeft(SourceRange &R, SourceRange Before) { 8412 if (Before.isInvalid()) 8413 return; 8414 R.setBegin(Before.getBegin()); 8415 if (R.getEnd().isInvalid()) 8416 R.setEnd(Before.getEnd()); 8417 } 8418 8419 static void extendRight(SourceRange &R, SourceRange After) { 8420 if (After.isInvalid()) 8421 return; 8422 if (R.getBegin().isInvalid()) 8423 R.setBegin(After.getBegin()); 8424 R.setEnd(After.getEnd()); 8425 } 8426 8427 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8428 /// well-formednes of the conversion function declarator @p D with 8429 /// type @p R. If there are any errors in the declarator, this routine 8430 /// will emit diagnostics and return true. Otherwise, it will return 8431 /// false. Either way, the type @p R will be updated to reflect a 8432 /// well-formed type for the conversion operator. 8433 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8434 StorageClass& SC) { 8435 // C++ [class.conv.fct]p1: 8436 // Neither parameter types nor return type can be specified. The 8437 // type of a conversion function (8.3.5) is "function taking no 8438 // parameter returning conversion-type-id." 8439 if (SC == SC_Static) { 8440 if (!D.isInvalidType()) 8441 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8442 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8443 << D.getName().getSourceRange(); 8444 D.setInvalidType(); 8445 SC = SC_None; 8446 } 8447 8448 TypeSourceInfo *ConvTSI = nullptr; 8449 QualType ConvType = 8450 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8451 8452 const DeclSpec &DS = D.getDeclSpec(); 8453 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8454 // Conversion functions don't have return types, but the parser will 8455 // happily parse something like: 8456 // 8457 // class X { 8458 // float operator bool(); 8459 // }; 8460 // 8461 // The return type will be changed later anyway. 8462 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8463 << SourceRange(DS.getTypeSpecTypeLoc()) 8464 << SourceRange(D.getIdentifierLoc()); 8465 D.setInvalidType(); 8466 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8467 // It's also plausible that the user writes type qualifiers in the wrong 8468 // place, such as: 8469 // struct S { const operator int(); }; 8470 // FIXME: we could provide a fixit to move the qualifiers onto the 8471 // conversion type. 8472 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8473 << SourceRange(D.getIdentifierLoc()) << 0; 8474 D.setInvalidType(); 8475 } 8476 8477 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8478 8479 // Make sure we don't have any parameters. 8480 if (Proto->getNumParams() > 0) { 8481 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8482 8483 // Delete the parameters. 8484 D.getFunctionTypeInfo().freeParams(); 8485 D.setInvalidType(); 8486 } else if (Proto->isVariadic()) { 8487 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8488 D.setInvalidType(); 8489 } 8490 8491 // Diagnose "&operator bool()" and other such nonsense. This 8492 // is actually a gcc extension which we don't support. 8493 if (Proto->getReturnType() != ConvType) { 8494 bool NeedsTypedef = false; 8495 SourceRange Before, After; 8496 8497 // Walk the chunks and extract information on them for our diagnostic. 8498 bool PastFunctionChunk = false; 8499 for (auto &Chunk : D.type_objects()) { 8500 switch (Chunk.Kind) { 8501 case DeclaratorChunk::Function: 8502 if (!PastFunctionChunk) { 8503 if (Chunk.Fun.HasTrailingReturnType) { 8504 TypeSourceInfo *TRT = nullptr; 8505 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8506 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8507 } 8508 PastFunctionChunk = true; 8509 break; 8510 } 8511 LLVM_FALLTHROUGH; 8512 case DeclaratorChunk::Array: 8513 NeedsTypedef = true; 8514 extendRight(After, Chunk.getSourceRange()); 8515 break; 8516 8517 case DeclaratorChunk::Pointer: 8518 case DeclaratorChunk::BlockPointer: 8519 case DeclaratorChunk::Reference: 8520 case DeclaratorChunk::MemberPointer: 8521 case DeclaratorChunk::Pipe: 8522 extendLeft(Before, Chunk.getSourceRange()); 8523 break; 8524 8525 case DeclaratorChunk::Paren: 8526 extendLeft(Before, Chunk.Loc); 8527 extendRight(After, Chunk.EndLoc); 8528 break; 8529 } 8530 } 8531 8532 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8533 After.isValid() ? After.getBegin() : 8534 D.getIdentifierLoc(); 8535 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8536 DB << Before << After; 8537 8538 if (!NeedsTypedef) { 8539 DB << /*don't need a typedef*/0; 8540 8541 // If we can provide a correct fix-it hint, do so. 8542 if (After.isInvalid() && ConvTSI) { 8543 SourceLocation InsertLoc = 8544 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 8545 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8546 << FixItHint::CreateInsertionFromRange( 8547 InsertLoc, CharSourceRange::getTokenRange(Before)) 8548 << FixItHint::CreateRemoval(Before); 8549 } 8550 } else if (!Proto->getReturnType()->isDependentType()) { 8551 DB << /*typedef*/1 << Proto->getReturnType(); 8552 } else if (getLangOpts().CPlusPlus11) { 8553 DB << /*alias template*/2 << Proto->getReturnType(); 8554 } else { 8555 DB << /*might not be fixable*/3; 8556 } 8557 8558 // Recover by incorporating the other type chunks into the result type. 8559 // Note, this does *not* change the name of the function. This is compatible 8560 // with the GCC extension: 8561 // struct S { &operator int(); } s; 8562 // int &r = s.operator int(); // ok in GCC 8563 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8564 ConvType = Proto->getReturnType(); 8565 } 8566 8567 // C++ [class.conv.fct]p4: 8568 // The conversion-type-id shall not represent a function type nor 8569 // an array type. 8570 if (ConvType->isArrayType()) { 8571 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8572 ConvType = Context.getPointerType(ConvType); 8573 D.setInvalidType(); 8574 } else if (ConvType->isFunctionType()) { 8575 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8576 ConvType = Context.getPointerType(ConvType); 8577 D.setInvalidType(); 8578 } 8579 8580 // Rebuild the function type "R" without any parameters (in case any 8581 // of the errors above fired) and with the conversion type as the 8582 // return type. 8583 if (D.isInvalidType()) 8584 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8585 8586 // C++0x explicit conversion operators. 8587 if (DS.isExplicitSpecified()) 8588 Diag(DS.getExplicitSpecLoc(), 8589 getLangOpts().CPlusPlus11 8590 ? diag::warn_cxx98_compat_explicit_conversion_functions 8591 : diag::ext_explicit_conversion_functions) 8592 << SourceRange(DS.getExplicitSpecLoc()); 8593 } 8594 8595 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8596 /// the declaration of the given C++ conversion function. This routine 8597 /// is responsible for recording the conversion function in the C++ 8598 /// class, if possible. 8599 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8600 assert(Conversion && "Expected to receive a conversion function declaration"); 8601 8602 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8603 8604 // Make sure we aren't redeclaring the conversion function. 8605 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8606 8607 // C++ [class.conv.fct]p1: 8608 // [...] A conversion function is never used to convert a 8609 // (possibly cv-qualified) object to the (possibly cv-qualified) 8610 // same object type (or a reference to it), to a (possibly 8611 // cv-qualified) base class of that type (or a reference to it), 8612 // or to (possibly cv-qualified) void. 8613 // FIXME: Suppress this warning if the conversion function ends up being a 8614 // virtual function that overrides a virtual function in a base class. 8615 QualType ClassType 8616 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8617 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8618 ConvType = ConvTypeRef->getPointeeType(); 8619 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8620 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8621 /* Suppress diagnostics for instantiations. */; 8622 else if (ConvType->isRecordType()) { 8623 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8624 if (ConvType == ClassType) 8625 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8626 << ClassType; 8627 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8628 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8629 << ClassType << ConvType; 8630 } else if (ConvType->isVoidType()) { 8631 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8632 << ClassType << ConvType; 8633 } 8634 8635 if (FunctionTemplateDecl *ConversionTemplate 8636 = Conversion->getDescribedFunctionTemplate()) 8637 return ConversionTemplate; 8638 8639 return Conversion; 8640 } 8641 8642 namespace { 8643 /// Utility class to accumulate and print a diagnostic listing the invalid 8644 /// specifier(s) on a declaration. 8645 struct BadSpecifierDiagnoser { 8646 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8647 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8648 ~BadSpecifierDiagnoser() { 8649 Diagnostic << Specifiers; 8650 } 8651 8652 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8653 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8654 } 8655 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8656 return check(SpecLoc, 8657 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8658 } 8659 void check(SourceLocation SpecLoc, const char *Spec) { 8660 if (SpecLoc.isInvalid()) return; 8661 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8662 if (!Specifiers.empty()) Specifiers += " "; 8663 Specifiers += Spec; 8664 } 8665 8666 Sema &S; 8667 Sema::SemaDiagnosticBuilder Diagnostic; 8668 std::string Specifiers; 8669 }; 8670 } 8671 8672 /// Check the validity of a declarator that we parsed for a deduction-guide. 8673 /// These aren't actually declarators in the grammar, so we need to check that 8674 /// the user didn't specify any pieces that are not part of the deduction-guide 8675 /// grammar. 8676 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8677 StorageClass &SC) { 8678 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8679 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8680 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8681 8682 // C++ [temp.deduct.guide]p3: 8683 // A deduction-gide shall be declared in the same scope as the 8684 // corresponding class template. 8685 if (!CurContext->getRedeclContext()->Equals( 8686 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8687 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8688 << GuidedTemplateDecl; 8689 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8690 } 8691 8692 auto &DS = D.getMutableDeclSpec(); 8693 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8694 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8695 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8696 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8697 BadSpecifierDiagnoser Diagnoser( 8698 *this, D.getIdentifierLoc(), 8699 diag::err_deduction_guide_invalid_specifier); 8700 8701 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8702 DS.ClearStorageClassSpecs(); 8703 SC = SC_None; 8704 8705 // 'explicit' is permitted. 8706 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8707 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8708 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8709 DS.ClearConstexprSpec(); 8710 8711 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8712 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8713 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8714 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8715 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8716 DS.ClearTypeQualifiers(); 8717 8718 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8719 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8720 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8721 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8722 DS.ClearTypeSpecType(); 8723 } 8724 8725 if (D.isInvalidType()) 8726 return; 8727 8728 // Check the declarator is simple enough. 8729 bool FoundFunction = false; 8730 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8731 if (Chunk.Kind == DeclaratorChunk::Paren) 8732 continue; 8733 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8734 Diag(D.getDeclSpec().getBeginLoc(), 8735 diag::err_deduction_guide_with_complex_decl) 8736 << D.getSourceRange(); 8737 break; 8738 } 8739 if (!Chunk.Fun.hasTrailingReturnType()) { 8740 Diag(D.getName().getBeginLoc(), 8741 diag::err_deduction_guide_no_trailing_return_type); 8742 break; 8743 } 8744 8745 // Check that the return type is written as a specialization of 8746 // the template specified as the deduction-guide's name. 8747 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8748 TypeSourceInfo *TSI = nullptr; 8749 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8750 assert(TSI && "deduction guide has valid type but invalid return type?"); 8751 bool AcceptableReturnType = false; 8752 bool MightInstantiateToSpecialization = false; 8753 if (auto RetTST = 8754 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8755 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8756 bool TemplateMatches = 8757 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8758 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8759 AcceptableReturnType = true; 8760 else { 8761 // This could still instantiate to the right type, unless we know it 8762 // names the wrong class template. 8763 auto *TD = SpecifiedName.getAsTemplateDecl(); 8764 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8765 !TemplateMatches); 8766 } 8767 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8768 MightInstantiateToSpecialization = true; 8769 } 8770 8771 if (!AcceptableReturnType) { 8772 Diag(TSI->getTypeLoc().getBeginLoc(), 8773 diag::err_deduction_guide_bad_trailing_return_type) 8774 << GuidedTemplate << TSI->getType() 8775 << MightInstantiateToSpecialization 8776 << TSI->getTypeLoc().getSourceRange(); 8777 } 8778 8779 // Keep going to check that we don't have any inner declarator pieces (we 8780 // could still have a function returning a pointer to a function). 8781 FoundFunction = true; 8782 } 8783 8784 if (D.isFunctionDefinition()) 8785 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8786 } 8787 8788 //===----------------------------------------------------------------------===// 8789 // Namespace Handling 8790 //===----------------------------------------------------------------------===// 8791 8792 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 8793 /// reopened. 8794 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8795 SourceLocation Loc, 8796 IdentifierInfo *II, bool *IsInline, 8797 NamespaceDecl *PrevNS) { 8798 assert(*IsInline != PrevNS->isInline()); 8799 8800 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8801 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8802 // inline namespaces, with the intention of bringing names into namespace std. 8803 // 8804 // We support this just well enough to get that case working; this is not 8805 // sufficient to support reopening namespaces as inline in general. 8806 if (*IsInline && II && II->getName().startswith("__atomic") && 8807 S.getSourceManager().isInSystemHeader(Loc)) { 8808 // Mark all prior declarations of the namespace as inline. 8809 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8810 NS = NS->getPreviousDecl()) 8811 NS->setInline(*IsInline); 8812 // Patch up the lookup table for the containing namespace. This isn't really 8813 // correct, but it's good enough for this particular case. 8814 for (auto *I : PrevNS->decls()) 8815 if (auto *ND = dyn_cast<NamedDecl>(I)) 8816 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8817 return; 8818 } 8819 8820 if (PrevNS->isInline()) 8821 // The user probably just forgot the 'inline', so suggest that it 8822 // be added back. 8823 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8824 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8825 else 8826 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8827 8828 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8829 *IsInline = PrevNS->isInline(); 8830 } 8831 8832 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8833 /// definition. 8834 Decl *Sema::ActOnStartNamespaceDef( 8835 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 8836 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 8837 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 8838 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8839 // For anonymous namespace, take the location of the left brace. 8840 SourceLocation Loc = II ? IdentLoc : LBrace; 8841 bool IsInline = InlineLoc.isValid(); 8842 bool IsInvalid = false; 8843 bool IsStd = false; 8844 bool AddToKnown = false; 8845 Scope *DeclRegionScope = NamespcScope->getParent(); 8846 8847 NamespaceDecl *PrevNS = nullptr; 8848 if (II) { 8849 // C++ [namespace.def]p2: 8850 // The identifier in an original-namespace-definition shall not 8851 // have been previously defined in the declarative region in 8852 // which the original-namespace-definition appears. The 8853 // identifier in an original-namespace-definition is the name of 8854 // the namespace. Subsequently in that declarative region, it is 8855 // treated as an original-namespace-name. 8856 // 8857 // Since namespace names are unique in their scope, and we don't 8858 // look through using directives, just look for any ordinary names 8859 // as if by qualified name lookup. 8860 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8861 ForExternalRedeclaration); 8862 LookupQualifiedName(R, CurContext->getRedeclContext()); 8863 NamedDecl *PrevDecl = 8864 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8865 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8866 8867 if (PrevNS) { 8868 // This is an extended namespace definition. 8869 if (IsInline != PrevNS->isInline()) 8870 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8871 &IsInline, PrevNS); 8872 } else if (PrevDecl) { 8873 // This is an invalid name redefinition. 8874 Diag(Loc, diag::err_redefinition_different_kind) 8875 << II; 8876 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8877 IsInvalid = true; 8878 // Continue on to push Namespc as current DeclContext and return it. 8879 } else if (II->isStr("std") && 8880 CurContext->getRedeclContext()->isTranslationUnit()) { 8881 // This is the first "real" definition of the namespace "std", so update 8882 // our cache of the "std" namespace to point at this definition. 8883 PrevNS = getStdNamespace(); 8884 IsStd = true; 8885 AddToKnown = !IsInline; 8886 } else { 8887 // We've seen this namespace for the first time. 8888 AddToKnown = !IsInline; 8889 } 8890 } else { 8891 // Anonymous namespaces. 8892 8893 // Determine whether the parent already has an anonymous namespace. 8894 DeclContext *Parent = CurContext->getRedeclContext(); 8895 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8896 PrevNS = TU->getAnonymousNamespace(); 8897 } else { 8898 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8899 PrevNS = ND->getAnonymousNamespace(); 8900 } 8901 8902 if (PrevNS && IsInline != PrevNS->isInline()) 8903 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8904 &IsInline, PrevNS); 8905 } 8906 8907 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8908 StartLoc, Loc, II, PrevNS); 8909 if (IsInvalid) 8910 Namespc->setInvalidDecl(); 8911 8912 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8913 AddPragmaAttributes(DeclRegionScope, Namespc); 8914 8915 // FIXME: Should we be merging attributes? 8916 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8917 PushNamespaceVisibilityAttr(Attr, Loc); 8918 8919 if (IsStd) 8920 StdNamespace = Namespc; 8921 if (AddToKnown) 8922 KnownNamespaces[Namespc] = false; 8923 8924 if (II) { 8925 PushOnScopeChains(Namespc, DeclRegionScope); 8926 } else { 8927 // Link the anonymous namespace into its parent. 8928 DeclContext *Parent = CurContext->getRedeclContext(); 8929 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8930 TU->setAnonymousNamespace(Namespc); 8931 } else { 8932 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8933 } 8934 8935 CurContext->addDecl(Namespc); 8936 8937 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8938 // behaves as if it were replaced by 8939 // namespace unique { /* empty body */ } 8940 // using namespace unique; 8941 // namespace unique { namespace-body } 8942 // where all occurrences of 'unique' in a translation unit are 8943 // replaced by the same identifier and this identifier differs 8944 // from all other identifiers in the entire program. 8945 8946 // We just create the namespace with an empty name and then add an 8947 // implicit using declaration, just like the standard suggests. 8948 // 8949 // CodeGen enforces the "universally unique" aspect by giving all 8950 // declarations semantically contained within an anonymous 8951 // namespace internal linkage. 8952 8953 if (!PrevNS) { 8954 UD = UsingDirectiveDecl::Create(Context, Parent, 8955 /* 'using' */ LBrace, 8956 /* 'namespace' */ SourceLocation(), 8957 /* qualifier */ NestedNameSpecifierLoc(), 8958 /* identifier */ SourceLocation(), 8959 Namespc, 8960 /* Ancestor */ Parent); 8961 UD->setImplicit(); 8962 Parent->addDecl(UD); 8963 } 8964 } 8965 8966 ActOnDocumentableDecl(Namespc); 8967 8968 // Although we could have an invalid decl (i.e. the namespace name is a 8969 // redefinition), push it as current DeclContext and try to continue parsing. 8970 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8971 // for the namespace has the declarations that showed up in that particular 8972 // namespace definition. 8973 PushDeclContext(NamespcScope, Namespc); 8974 return Namespc; 8975 } 8976 8977 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8978 /// is a namespace alias, returns the namespace it points to. 8979 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8980 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8981 return AD->getNamespace(); 8982 return dyn_cast_or_null<NamespaceDecl>(D); 8983 } 8984 8985 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8986 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8987 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8988 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8989 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8990 Namespc->setRBraceLoc(RBrace); 8991 PopDeclContext(); 8992 if (Namespc->hasAttr<VisibilityAttr>()) 8993 PopPragmaVisibility(true, RBrace); 8994 } 8995 8996 CXXRecordDecl *Sema::getStdBadAlloc() const { 8997 return cast_or_null<CXXRecordDecl>( 8998 StdBadAlloc.get(Context.getExternalSource())); 8999 } 9000 9001 EnumDecl *Sema::getStdAlignValT() const { 9002 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 9003 } 9004 9005 NamespaceDecl *Sema::getStdNamespace() const { 9006 return cast_or_null<NamespaceDecl>( 9007 StdNamespace.get(Context.getExternalSource())); 9008 } 9009 9010 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 9011 if (!StdExperimentalNamespaceCache) { 9012 if (auto Std = getStdNamespace()) { 9013 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 9014 SourceLocation(), LookupNamespaceName); 9015 if (!LookupQualifiedName(Result, Std) || 9016 !(StdExperimentalNamespaceCache = 9017 Result.getAsSingle<NamespaceDecl>())) 9018 Result.suppressDiagnostics(); 9019 } 9020 } 9021 return StdExperimentalNamespaceCache; 9022 } 9023 9024 namespace { 9025 9026 enum UnsupportedSTLSelect { 9027 USS_InvalidMember, 9028 USS_MissingMember, 9029 USS_NonTrivial, 9030 USS_Other 9031 }; 9032 9033 struct InvalidSTLDiagnoser { 9034 Sema &S; 9035 SourceLocation Loc; 9036 QualType TyForDiags; 9037 9038 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 9039 const VarDecl *VD = nullptr) { 9040 { 9041 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 9042 << TyForDiags << ((int)Sel); 9043 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 9044 assert(!Name.empty()); 9045 D << Name; 9046 } 9047 } 9048 if (Sel == USS_InvalidMember) { 9049 S.Diag(VD->getLocation(), diag::note_var_declared_here) 9050 << VD << VD->getSourceRange(); 9051 } 9052 return QualType(); 9053 } 9054 }; 9055 } // namespace 9056 9057 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 9058 SourceLocation Loc) { 9059 assert(getLangOpts().CPlusPlus && 9060 "Looking for comparison category type outside of C++."); 9061 9062 // Check if we've already successfully checked the comparison category type 9063 // before. If so, skip checking it again. 9064 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 9065 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 9066 return Info->getType(); 9067 9068 // If lookup failed 9069 if (!Info) { 9070 std::string NameForDiags = "std::"; 9071 NameForDiags += ComparisonCategories::getCategoryString(Kind); 9072 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 9073 << NameForDiags; 9074 return QualType(); 9075 } 9076 9077 assert(Info->Kind == Kind); 9078 assert(Info->Record); 9079 9080 // Update the Record decl in case we encountered a forward declaration on our 9081 // first pass. FIXME: This is a bit of a hack. 9082 if (Info->Record->hasDefinition()) 9083 Info->Record = Info->Record->getDefinition(); 9084 9085 // Use an elaborated type for diagnostics which has a name containing the 9086 // prepended 'std' namespace but not any inline namespace names. 9087 QualType TyForDiags = [&]() { 9088 auto *NNS = 9089 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 9090 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 9091 }(); 9092 9093 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 9094 return QualType(); 9095 9096 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 9097 9098 if (!Info->Record->isTriviallyCopyable()) 9099 return UnsupportedSTLError(USS_NonTrivial); 9100 9101 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 9102 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 9103 // Tolerate empty base classes. 9104 if (Base->isEmpty()) 9105 continue; 9106 // Reject STL implementations which have at least one non-empty base. 9107 return UnsupportedSTLError(); 9108 } 9109 9110 // Check that the STL has implemented the types using a single integer field. 9111 // This expectation allows better codegen for builtin operators. We require: 9112 // (1) The class has exactly one field. 9113 // (2) The field is an integral or enumeration type. 9114 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9115 if (std::distance(FIt, FEnd) != 1 || 9116 !FIt->getType()->isIntegralOrEnumerationType()) { 9117 return UnsupportedSTLError(); 9118 } 9119 9120 // Build each of the require values and store them in Info. 9121 for (ComparisonCategoryResult CCR : 9122 ComparisonCategories::getPossibleResultsForType(Kind)) { 9123 StringRef MemName = ComparisonCategories::getResultString(CCR); 9124 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9125 9126 if (!ValInfo) 9127 return UnsupportedSTLError(USS_MissingMember, MemName); 9128 9129 VarDecl *VD = ValInfo->VD; 9130 assert(VD && "should not be null!"); 9131 9132 // Attempt to diagnose reasons why the STL definition of this type 9133 // might be foobar, including it failing to be a constant expression. 9134 // TODO Handle more ways the lookup or result can be invalid. 9135 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9136 !VD->checkInitIsICE()) 9137 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9138 9139 // Attempt to evaluate the var decl as a constant expression and extract 9140 // the value of its first field as a ICE. If this fails, the STL 9141 // implementation is not supported. 9142 if (!ValInfo->hasValidIntValue()) 9143 return UnsupportedSTLError(); 9144 9145 MarkVariableReferenced(Loc, VD); 9146 } 9147 9148 // We've successfully built the required types and expressions. Update 9149 // the cache and return the newly cached value. 9150 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9151 return Info->getType(); 9152 } 9153 9154 /// Retrieve the special "std" namespace, which may require us to 9155 /// implicitly define the namespace. 9156 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9157 if (!StdNamespace) { 9158 // The "std" namespace has not yet been defined, so build one implicitly. 9159 StdNamespace = NamespaceDecl::Create(Context, 9160 Context.getTranslationUnitDecl(), 9161 /*Inline=*/false, 9162 SourceLocation(), SourceLocation(), 9163 &PP.getIdentifierTable().get("std"), 9164 /*PrevDecl=*/nullptr); 9165 getStdNamespace()->setImplicit(true); 9166 } 9167 9168 return getStdNamespace(); 9169 } 9170 9171 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9172 assert(getLangOpts().CPlusPlus && 9173 "Looking for std::initializer_list outside of C++."); 9174 9175 // We're looking for implicit instantiations of 9176 // template <typename E> class std::initializer_list. 9177 9178 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9179 return false; 9180 9181 ClassTemplateDecl *Template = nullptr; 9182 const TemplateArgument *Arguments = nullptr; 9183 9184 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9185 9186 ClassTemplateSpecializationDecl *Specialization = 9187 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9188 if (!Specialization) 9189 return false; 9190 9191 Template = Specialization->getSpecializedTemplate(); 9192 Arguments = Specialization->getTemplateArgs().data(); 9193 } else if (const TemplateSpecializationType *TST = 9194 Ty->getAs<TemplateSpecializationType>()) { 9195 Template = dyn_cast_or_null<ClassTemplateDecl>( 9196 TST->getTemplateName().getAsTemplateDecl()); 9197 Arguments = TST->getArgs(); 9198 } 9199 if (!Template) 9200 return false; 9201 9202 if (!StdInitializerList) { 9203 // Haven't recognized std::initializer_list yet, maybe this is it. 9204 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9205 if (TemplateClass->getIdentifier() != 9206 &PP.getIdentifierTable().get("initializer_list") || 9207 !getStdNamespace()->InEnclosingNamespaceSetOf( 9208 TemplateClass->getDeclContext())) 9209 return false; 9210 // This is a template called std::initializer_list, but is it the right 9211 // template? 9212 TemplateParameterList *Params = Template->getTemplateParameters(); 9213 if (Params->getMinRequiredArguments() != 1) 9214 return false; 9215 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9216 return false; 9217 9218 // It's the right template. 9219 StdInitializerList = Template; 9220 } 9221 9222 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9223 return false; 9224 9225 // This is an instance of std::initializer_list. Find the argument type. 9226 if (Element) 9227 *Element = Arguments[0].getAsType(); 9228 return true; 9229 } 9230 9231 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9232 NamespaceDecl *Std = S.getStdNamespace(); 9233 if (!Std) { 9234 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9235 return nullptr; 9236 } 9237 9238 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9239 Loc, Sema::LookupOrdinaryName); 9240 if (!S.LookupQualifiedName(Result, Std)) { 9241 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9242 return nullptr; 9243 } 9244 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9245 if (!Template) { 9246 Result.suppressDiagnostics(); 9247 // We found something weird. Complain about the first thing we found. 9248 NamedDecl *Found = *Result.begin(); 9249 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9250 return nullptr; 9251 } 9252 9253 // We found some template called std::initializer_list. Now verify that it's 9254 // correct. 9255 TemplateParameterList *Params = Template->getTemplateParameters(); 9256 if (Params->getMinRequiredArguments() != 1 || 9257 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9258 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9259 return nullptr; 9260 } 9261 9262 return Template; 9263 } 9264 9265 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9266 if (!StdInitializerList) { 9267 StdInitializerList = LookupStdInitializerList(*this, Loc); 9268 if (!StdInitializerList) 9269 return QualType(); 9270 } 9271 9272 TemplateArgumentListInfo Args(Loc, Loc); 9273 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9274 Context.getTrivialTypeSourceInfo(Element, 9275 Loc))); 9276 return Context.getCanonicalType( 9277 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9278 } 9279 9280 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9281 // C++ [dcl.init.list]p2: 9282 // A constructor is an initializer-list constructor if its first parameter 9283 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9284 // std::initializer_list<E> for some type E, and either there are no other 9285 // parameters or else all other parameters have default arguments. 9286 if (Ctor->getNumParams() < 1 || 9287 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9288 return false; 9289 9290 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9291 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9292 ArgType = RT->getPointeeType().getUnqualifiedType(); 9293 9294 return isStdInitializerList(ArgType, nullptr); 9295 } 9296 9297 /// Determine whether a using statement is in a context where it will be 9298 /// apply in all contexts. 9299 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9300 switch (CurContext->getDeclKind()) { 9301 case Decl::TranslationUnit: 9302 return true; 9303 case Decl::LinkageSpec: 9304 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9305 default: 9306 return false; 9307 } 9308 } 9309 9310 namespace { 9311 9312 // Callback to only accept typo corrections that are namespaces. 9313 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 9314 public: 9315 bool ValidateCandidate(const TypoCorrection &candidate) override { 9316 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9317 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9318 return false; 9319 } 9320 }; 9321 9322 } 9323 9324 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9325 CXXScopeSpec &SS, 9326 SourceLocation IdentLoc, 9327 IdentifierInfo *Ident) { 9328 R.clear(); 9329 if (TypoCorrection Corrected = 9330 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 9331 llvm::make_unique<NamespaceValidatorCCC>(), 9332 Sema::CTK_ErrorRecovery)) { 9333 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9334 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9335 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9336 Ident->getName().equals(CorrectedStr); 9337 S.diagnoseTypo(Corrected, 9338 S.PDiag(diag::err_using_directive_member_suggest) 9339 << Ident << DC << DroppedSpecifier << SS.getRange(), 9340 S.PDiag(diag::note_namespace_defined_here)); 9341 } else { 9342 S.diagnoseTypo(Corrected, 9343 S.PDiag(diag::err_using_directive_suggest) << Ident, 9344 S.PDiag(diag::note_namespace_defined_here)); 9345 } 9346 R.addDecl(Corrected.getFoundDecl()); 9347 return true; 9348 } 9349 return false; 9350 } 9351 9352 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 9353 SourceLocation NamespcLoc, CXXScopeSpec &SS, 9354 SourceLocation IdentLoc, 9355 IdentifierInfo *NamespcName, 9356 const ParsedAttributesView &AttrList) { 9357 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9358 assert(NamespcName && "Invalid NamespcName."); 9359 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9360 9361 // This can only happen along a recovery path. 9362 while (S->isTemplateParamScope()) 9363 S = S->getParent(); 9364 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9365 9366 UsingDirectiveDecl *UDir = nullptr; 9367 NestedNameSpecifier *Qualifier = nullptr; 9368 if (SS.isSet()) 9369 Qualifier = SS.getScopeRep(); 9370 9371 // Lookup namespace name. 9372 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9373 LookupParsedName(R, S, &SS); 9374 if (R.isAmbiguous()) 9375 return nullptr; 9376 9377 if (R.empty()) { 9378 R.clear(); 9379 // Allow "using namespace std;" or "using namespace ::std;" even if 9380 // "std" hasn't been defined yet, for GCC compatibility. 9381 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9382 NamespcName->isStr("std")) { 9383 Diag(IdentLoc, diag::ext_using_undefined_std); 9384 R.addDecl(getOrCreateStdNamespace()); 9385 R.resolveKind(); 9386 } 9387 // Otherwise, attempt typo correction. 9388 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9389 } 9390 9391 if (!R.empty()) { 9392 NamedDecl *Named = R.getRepresentativeDecl(); 9393 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9394 assert(NS && "expected namespace decl"); 9395 9396 // The use of a nested name specifier may trigger deprecation warnings. 9397 DiagnoseUseOfDecl(Named, IdentLoc); 9398 9399 // C++ [namespace.udir]p1: 9400 // A using-directive specifies that the names in the nominated 9401 // namespace can be used in the scope in which the 9402 // using-directive appears after the using-directive. During 9403 // unqualified name lookup (3.4.1), the names appear as if they 9404 // were declared in the nearest enclosing namespace which 9405 // contains both the using-directive and the nominated 9406 // namespace. [Note: in this context, "contains" means "contains 9407 // directly or indirectly". ] 9408 9409 // Find enclosing context containing both using-directive and 9410 // nominated namespace. 9411 DeclContext *CommonAncestor = NS; 9412 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9413 CommonAncestor = CommonAncestor->getParent(); 9414 9415 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9416 SS.getWithLocInContext(Context), 9417 IdentLoc, Named, CommonAncestor); 9418 9419 if (IsUsingDirectiveInToplevelContext(CurContext) && 9420 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9421 Diag(IdentLoc, diag::warn_using_directive_in_header); 9422 } 9423 9424 PushUsingDirective(S, UDir); 9425 } else { 9426 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9427 } 9428 9429 if (UDir) 9430 ProcessDeclAttributeList(S, UDir, AttrList); 9431 9432 return UDir; 9433 } 9434 9435 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9436 // If the scope has an associated entity and the using directive is at 9437 // namespace or translation unit scope, add the UsingDirectiveDecl into 9438 // its lookup structure so qualified name lookup can find it. 9439 DeclContext *Ctx = S->getEntity(); 9440 if (Ctx && !Ctx->isFunctionOrMethod()) 9441 Ctx->addDecl(UDir); 9442 else 9443 // Otherwise, it is at block scope. The using-directives will affect lookup 9444 // only to the end of the scope. 9445 S->PushUsingDirective(UDir); 9446 } 9447 9448 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 9449 SourceLocation UsingLoc, 9450 SourceLocation TypenameLoc, CXXScopeSpec &SS, 9451 UnqualifiedId &Name, 9452 SourceLocation EllipsisLoc, 9453 const ParsedAttributesView &AttrList) { 9454 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9455 9456 if (SS.isEmpty()) { 9457 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 9458 return nullptr; 9459 } 9460 9461 switch (Name.getKind()) { 9462 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9463 case UnqualifiedIdKind::IK_Identifier: 9464 case UnqualifiedIdKind::IK_OperatorFunctionId: 9465 case UnqualifiedIdKind::IK_LiteralOperatorId: 9466 case UnqualifiedIdKind::IK_ConversionFunctionId: 9467 break; 9468 9469 case UnqualifiedIdKind::IK_ConstructorName: 9470 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9471 // C++11 inheriting constructors. 9472 Diag(Name.getBeginLoc(), 9473 getLangOpts().CPlusPlus11 9474 ? diag::warn_cxx98_compat_using_decl_constructor 9475 : diag::err_using_decl_constructor) 9476 << SS.getRange(); 9477 9478 if (getLangOpts().CPlusPlus11) break; 9479 9480 return nullptr; 9481 9482 case UnqualifiedIdKind::IK_DestructorName: 9483 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 9484 return nullptr; 9485 9486 case UnqualifiedIdKind::IK_TemplateId: 9487 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 9488 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9489 return nullptr; 9490 9491 case UnqualifiedIdKind::IK_DeductionGuideName: 9492 llvm_unreachable("cannot parse qualified deduction guide name"); 9493 } 9494 9495 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9496 DeclarationName TargetName = TargetNameInfo.getName(); 9497 if (!TargetName) 9498 return nullptr; 9499 9500 // Warn about access declarations. 9501 if (UsingLoc.isInvalid()) { 9502 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 9503 ? diag::err_access_decl 9504 : diag::warn_access_decl_deprecated) 9505 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9506 } 9507 9508 if (EllipsisLoc.isInvalid()) { 9509 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9510 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9511 return nullptr; 9512 } else { 9513 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9514 !TargetNameInfo.containsUnexpandedParameterPack()) { 9515 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9516 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9517 EllipsisLoc = SourceLocation(); 9518 } 9519 } 9520 9521 NamedDecl *UD = 9522 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9523 SS, TargetNameInfo, EllipsisLoc, AttrList, 9524 /*IsInstantiation*/false); 9525 if (UD) 9526 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9527 9528 return UD; 9529 } 9530 9531 /// Determine whether a using declaration considers the given 9532 /// declarations as "equivalent", e.g., if they are redeclarations of 9533 /// the same entity or are both typedefs of the same type. 9534 static bool 9535 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9536 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9537 return true; 9538 9539 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9540 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9541 return Context.hasSameType(TD1->getUnderlyingType(), 9542 TD2->getUnderlyingType()); 9543 9544 return false; 9545 } 9546 9547 9548 /// Determines whether to create a using shadow decl for a particular 9549 /// decl, given the set of decls existing prior to this using lookup. 9550 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9551 const LookupResult &Previous, 9552 UsingShadowDecl *&PrevShadow) { 9553 // Diagnose finding a decl which is not from a base class of the 9554 // current class. We do this now because there are cases where this 9555 // function will silently decide not to build a shadow decl, which 9556 // will pre-empt further diagnostics. 9557 // 9558 // We don't need to do this in C++11 because we do the check once on 9559 // the qualifier. 9560 // 9561 // FIXME: diagnose the following if we care enough: 9562 // struct A { int foo; }; 9563 // struct B : A { using A::foo; }; 9564 // template <class T> struct C : A {}; 9565 // template <class T> struct D : C<T> { using B::foo; } // <--- 9566 // This is invalid (during instantiation) in C++03 because B::foo 9567 // resolves to the using decl in B, which is not a base class of D<T>. 9568 // We can't diagnose it immediately because C<T> is an unknown 9569 // specialization. The UsingShadowDecl in D<T> then points directly 9570 // to A::foo, which will look well-formed when we instantiate. 9571 // The right solution is to not collapse the shadow-decl chain. 9572 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9573 DeclContext *OrigDC = Orig->getDeclContext(); 9574 9575 // Handle enums and anonymous structs. 9576 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9577 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9578 while (OrigRec->isAnonymousStructOrUnion()) 9579 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9580 9581 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9582 if (OrigDC == CurContext) { 9583 Diag(Using->getLocation(), 9584 diag::err_using_decl_nested_name_specifier_is_current_class) 9585 << Using->getQualifierLoc().getSourceRange(); 9586 Diag(Orig->getLocation(), diag::note_using_decl_target); 9587 Using->setInvalidDecl(); 9588 return true; 9589 } 9590 9591 Diag(Using->getQualifierLoc().getBeginLoc(), 9592 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9593 << Using->getQualifier() 9594 << cast<CXXRecordDecl>(CurContext) 9595 << Using->getQualifierLoc().getSourceRange(); 9596 Diag(Orig->getLocation(), diag::note_using_decl_target); 9597 Using->setInvalidDecl(); 9598 return true; 9599 } 9600 } 9601 9602 if (Previous.empty()) return false; 9603 9604 NamedDecl *Target = Orig; 9605 if (isa<UsingShadowDecl>(Target)) 9606 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9607 9608 // If the target happens to be one of the previous declarations, we 9609 // don't have a conflict. 9610 // 9611 // FIXME: but we might be increasing its access, in which case we 9612 // should redeclare it. 9613 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9614 bool FoundEquivalentDecl = false; 9615 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9616 I != E; ++I) { 9617 NamedDecl *D = (*I)->getUnderlyingDecl(); 9618 // We can have UsingDecls in our Previous results because we use the same 9619 // LookupResult for checking whether the UsingDecl itself is a valid 9620 // redeclaration. 9621 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9622 continue; 9623 9624 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9625 // C++ [class.mem]p19: 9626 // If T is the name of a class, then [every named member other than 9627 // a non-static data member] shall have a name different from T 9628 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 9629 !isa<IndirectFieldDecl>(Target) && 9630 !isa<UnresolvedUsingValueDecl>(Target) && 9631 DiagnoseClassNameShadow( 9632 CurContext, 9633 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 9634 return true; 9635 } 9636 9637 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9638 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9639 PrevShadow = Shadow; 9640 FoundEquivalentDecl = true; 9641 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9642 // We don't conflict with an existing using shadow decl of an equivalent 9643 // declaration, but we're not a redeclaration of it. 9644 FoundEquivalentDecl = true; 9645 } 9646 9647 if (isVisible(D)) 9648 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9649 } 9650 9651 if (FoundEquivalentDecl) 9652 return false; 9653 9654 if (FunctionDecl *FD = Target->getAsFunction()) { 9655 NamedDecl *OldDecl = nullptr; 9656 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9657 /*IsForUsingDecl*/ true)) { 9658 case Ovl_Overload: 9659 return false; 9660 9661 case Ovl_NonFunction: 9662 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9663 break; 9664 9665 // We found a decl with the exact signature. 9666 case Ovl_Match: 9667 // If we're in a record, we want to hide the target, so we 9668 // return true (without a diagnostic) to tell the caller not to 9669 // build a shadow decl. 9670 if (CurContext->isRecord()) 9671 return true; 9672 9673 // If we're not in a record, this is an error. 9674 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9675 break; 9676 } 9677 9678 Diag(Target->getLocation(), diag::note_using_decl_target); 9679 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9680 Using->setInvalidDecl(); 9681 return true; 9682 } 9683 9684 // Target is not a function. 9685 9686 if (isa<TagDecl>(Target)) { 9687 // No conflict between a tag and a non-tag. 9688 if (!Tag) return false; 9689 9690 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9691 Diag(Target->getLocation(), diag::note_using_decl_target); 9692 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9693 Using->setInvalidDecl(); 9694 return true; 9695 } 9696 9697 // No conflict between a tag and a non-tag. 9698 if (!NonTag) return false; 9699 9700 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9701 Diag(Target->getLocation(), diag::note_using_decl_target); 9702 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9703 Using->setInvalidDecl(); 9704 return true; 9705 } 9706 9707 /// Determine whether a direct base class is a virtual base class. 9708 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9709 if (!Derived->getNumVBases()) 9710 return false; 9711 for (auto &B : Derived->bases()) 9712 if (B.getType()->getAsCXXRecordDecl() == Base) 9713 return B.isVirtual(); 9714 llvm_unreachable("not a direct base class"); 9715 } 9716 9717 /// Builds a shadow declaration corresponding to a 'using' declaration. 9718 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9719 UsingDecl *UD, 9720 NamedDecl *Orig, 9721 UsingShadowDecl *PrevDecl) { 9722 // If we resolved to another shadow declaration, just coalesce them. 9723 NamedDecl *Target = Orig; 9724 if (isa<UsingShadowDecl>(Target)) { 9725 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9726 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9727 } 9728 9729 NamedDecl *NonTemplateTarget = Target; 9730 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9731 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9732 9733 UsingShadowDecl *Shadow; 9734 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9735 bool IsVirtualBase = 9736 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9737 UD->getQualifier()->getAsRecordDecl()); 9738 Shadow = ConstructorUsingShadowDecl::Create( 9739 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9740 } else { 9741 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9742 Target); 9743 } 9744 UD->addShadowDecl(Shadow); 9745 9746 Shadow->setAccess(UD->getAccess()); 9747 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9748 Shadow->setInvalidDecl(); 9749 9750 Shadow->setPreviousDecl(PrevDecl); 9751 9752 if (S) 9753 PushOnScopeChains(Shadow, S); 9754 else 9755 CurContext->addDecl(Shadow); 9756 9757 9758 return Shadow; 9759 } 9760 9761 /// Hides a using shadow declaration. This is required by the current 9762 /// using-decl implementation when a resolvable using declaration in a 9763 /// class is followed by a declaration which would hide or override 9764 /// one or more of the using decl's targets; for example: 9765 /// 9766 /// struct Base { void foo(int); }; 9767 /// struct Derived : Base { 9768 /// using Base::foo; 9769 /// void foo(int); 9770 /// }; 9771 /// 9772 /// The governing language is C++03 [namespace.udecl]p12: 9773 /// 9774 /// When a using-declaration brings names from a base class into a 9775 /// derived class scope, member functions in the derived class 9776 /// override and/or hide member functions with the same name and 9777 /// parameter types in a base class (rather than conflicting). 9778 /// 9779 /// There are two ways to implement this: 9780 /// (1) optimistically create shadow decls when they're not hidden 9781 /// by existing declarations, or 9782 /// (2) don't create any shadow decls (or at least don't make them 9783 /// visible) until we've fully parsed/instantiated the class. 9784 /// The problem with (1) is that we might have to retroactively remove 9785 /// a shadow decl, which requires several O(n) operations because the 9786 /// decl structures are (very reasonably) not designed for removal. 9787 /// (2) avoids this but is very fiddly and phase-dependent. 9788 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9789 if (Shadow->getDeclName().getNameKind() == 9790 DeclarationName::CXXConversionFunctionName) 9791 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9792 9793 // Remove it from the DeclContext... 9794 Shadow->getDeclContext()->removeDecl(Shadow); 9795 9796 // ...and the scope, if applicable... 9797 if (S) { 9798 S->RemoveDecl(Shadow); 9799 IdResolver.RemoveDecl(Shadow); 9800 } 9801 9802 // ...and the using decl. 9803 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9804 9805 // TODO: complain somehow if Shadow was used. It shouldn't 9806 // be possible for this to happen, because...? 9807 } 9808 9809 /// Find the base specifier for a base class with the given type. 9810 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9811 QualType DesiredBase, 9812 bool &AnyDependentBases) { 9813 // Check whether the named type is a direct base class. 9814 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9815 for (auto &Base : Derived->bases()) { 9816 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9817 if (CanonicalDesiredBase == BaseType) 9818 return &Base; 9819 if (BaseType->isDependentType()) 9820 AnyDependentBases = true; 9821 } 9822 return nullptr; 9823 } 9824 9825 namespace { 9826 class UsingValidatorCCC : public CorrectionCandidateCallback { 9827 public: 9828 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9829 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9830 : HasTypenameKeyword(HasTypenameKeyword), 9831 IsInstantiation(IsInstantiation), OldNNS(NNS), 9832 RequireMemberOf(RequireMemberOf) {} 9833 9834 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9835 NamedDecl *ND = Candidate.getCorrectionDecl(); 9836 9837 // Keywords are not valid here. 9838 if (!ND || isa<NamespaceDecl>(ND)) 9839 return false; 9840 9841 // Completely unqualified names are invalid for a 'using' declaration. 9842 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9843 return false; 9844 9845 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9846 // reject. 9847 9848 if (RequireMemberOf) { 9849 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9850 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9851 // No-one ever wants a using-declaration to name an injected-class-name 9852 // of a base class, unless they're declaring an inheriting constructor. 9853 ASTContext &Ctx = ND->getASTContext(); 9854 if (!Ctx.getLangOpts().CPlusPlus11) 9855 return false; 9856 QualType FoundType = Ctx.getRecordType(FoundRecord); 9857 9858 // Check that the injected-class-name is named as a member of its own 9859 // type; we don't want to suggest 'using Derived::Base;', since that 9860 // means something else. 9861 NestedNameSpecifier *Specifier = 9862 Candidate.WillReplaceSpecifier() 9863 ? Candidate.getCorrectionSpecifier() 9864 : OldNNS; 9865 if (!Specifier->getAsType() || 9866 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9867 return false; 9868 9869 // Check that this inheriting constructor declaration actually names a 9870 // direct base class of the current class. 9871 bool AnyDependentBases = false; 9872 if (!findDirectBaseWithType(RequireMemberOf, 9873 Ctx.getRecordType(FoundRecord), 9874 AnyDependentBases) && 9875 !AnyDependentBases) 9876 return false; 9877 } else { 9878 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9879 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9880 return false; 9881 9882 // FIXME: Check that the base class member is accessible? 9883 } 9884 } else { 9885 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9886 if (FoundRecord && FoundRecord->isInjectedClassName()) 9887 return false; 9888 } 9889 9890 if (isa<TypeDecl>(ND)) 9891 return HasTypenameKeyword || !IsInstantiation; 9892 9893 return !HasTypenameKeyword; 9894 } 9895 9896 private: 9897 bool HasTypenameKeyword; 9898 bool IsInstantiation; 9899 NestedNameSpecifier *OldNNS; 9900 CXXRecordDecl *RequireMemberOf; 9901 }; 9902 } // end anonymous namespace 9903 9904 /// Builds a using declaration. 9905 /// 9906 /// \param IsInstantiation - Whether this call arises from an 9907 /// instantiation of an unresolved using declaration. We treat 9908 /// the lookup differently for these declarations. 9909 NamedDecl *Sema::BuildUsingDeclaration( 9910 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 9911 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 9912 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 9913 const ParsedAttributesView &AttrList, bool IsInstantiation) { 9914 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9915 SourceLocation IdentLoc = NameInfo.getLoc(); 9916 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9917 9918 // FIXME: We ignore attributes for now. 9919 9920 // For an inheriting constructor declaration, the name of the using 9921 // declaration is the name of a constructor in this class, not in the 9922 // base class. 9923 DeclarationNameInfo UsingName = NameInfo; 9924 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9925 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9926 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9927 Context.getCanonicalType(Context.getRecordType(RD)))); 9928 9929 // Do the redeclaration lookup in the current scope. 9930 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9931 ForVisibleRedeclaration); 9932 Previous.setHideTags(false); 9933 if (S) { 9934 LookupName(Previous, S); 9935 9936 // It is really dumb that we have to do this. 9937 LookupResult::Filter F = Previous.makeFilter(); 9938 while (F.hasNext()) { 9939 NamedDecl *D = F.next(); 9940 if (!isDeclInScope(D, CurContext, S)) 9941 F.erase(); 9942 // If we found a local extern declaration that's not ordinarily visible, 9943 // and this declaration is being added to a non-block scope, ignore it. 9944 // We're only checking for scope conflicts here, not also for violations 9945 // of the linkage rules. 9946 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9947 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9948 F.erase(); 9949 } 9950 F.done(); 9951 } else { 9952 assert(IsInstantiation && "no scope in non-instantiation"); 9953 if (CurContext->isRecord()) 9954 LookupQualifiedName(Previous, CurContext); 9955 else { 9956 // No redeclaration check is needed here; in non-member contexts we 9957 // diagnosed all possible conflicts with other using-declarations when 9958 // building the template: 9959 // 9960 // For a dependent non-type using declaration, the only valid case is 9961 // if we instantiate to a single enumerator. We check for conflicts 9962 // between shadow declarations we introduce, and we check in the template 9963 // definition for conflicts between a non-type using declaration and any 9964 // other declaration, which together covers all cases. 9965 // 9966 // A dependent typename using declaration will never successfully 9967 // instantiate, since it will always name a class member, so we reject 9968 // that in the template definition. 9969 } 9970 } 9971 9972 // Check for invalid redeclarations. 9973 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9974 SS, IdentLoc, Previous)) 9975 return nullptr; 9976 9977 // Check for bad qualifiers. 9978 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9979 IdentLoc)) 9980 return nullptr; 9981 9982 DeclContext *LookupContext = computeDeclContext(SS); 9983 NamedDecl *D; 9984 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9985 if (!LookupContext || EllipsisLoc.isValid()) { 9986 if (HasTypenameKeyword) { 9987 // FIXME: not all declaration name kinds are legal here 9988 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9989 UsingLoc, TypenameLoc, 9990 QualifierLoc, 9991 IdentLoc, NameInfo.getName(), 9992 EllipsisLoc); 9993 } else { 9994 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9995 QualifierLoc, NameInfo, EllipsisLoc); 9996 } 9997 D->setAccess(AS); 9998 CurContext->addDecl(D); 9999 return D; 10000 } 10001 10002 auto Build = [&](bool Invalid) { 10003 UsingDecl *UD = 10004 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 10005 UsingName, HasTypenameKeyword); 10006 UD->setAccess(AS); 10007 CurContext->addDecl(UD); 10008 UD->setInvalidDecl(Invalid); 10009 return UD; 10010 }; 10011 auto BuildInvalid = [&]{ return Build(true); }; 10012 auto BuildValid = [&]{ return Build(false); }; 10013 10014 if (RequireCompleteDeclContext(SS, LookupContext)) 10015 return BuildInvalid(); 10016 10017 // Look up the target name. 10018 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10019 10020 // Unlike most lookups, we don't always want to hide tag 10021 // declarations: tag names are visible through the using declaration 10022 // even if hidden by ordinary names, *except* in a dependent context 10023 // where it's important for the sanity of two-phase lookup. 10024 if (!IsInstantiation) 10025 R.setHideTags(false); 10026 10027 // For the purposes of this lookup, we have a base object type 10028 // equal to that of the current context. 10029 if (CurContext->isRecord()) { 10030 R.setBaseObjectType( 10031 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 10032 } 10033 10034 LookupQualifiedName(R, LookupContext); 10035 10036 // Try to correct typos if possible. If constructor name lookup finds no 10037 // results, that means the named class has no explicit constructors, and we 10038 // suppressed declaring implicit ones (probably because it's dependent or 10039 // invalid). 10040 if (R.empty() && 10041 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 10042 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 10043 // it will believe that glibc provides a ::gets in cases where it does not, 10044 // and will try to pull it into namespace std with a using-declaration. 10045 // Just ignore the using-declaration in that case. 10046 auto *II = NameInfo.getName().getAsIdentifierInfo(); 10047 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 10048 CurContext->isStdNamespace() && 10049 isa<TranslationUnitDecl>(LookupContext) && 10050 getSourceManager().isInSystemHeader(UsingLoc)) 10051 return nullptr; 10052 if (TypoCorrection Corrected = CorrectTypo( 10053 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 10054 llvm::make_unique<UsingValidatorCCC>( 10055 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 10056 dyn_cast<CXXRecordDecl>(CurContext)), 10057 CTK_ErrorRecovery)) { 10058 // We reject candidates where DroppedSpecifier == true, hence the 10059 // literal '0' below. 10060 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 10061 << NameInfo.getName() << LookupContext << 0 10062 << SS.getRange()); 10063 10064 // If we picked a correction with no attached Decl we can't do anything 10065 // useful with it, bail out. 10066 NamedDecl *ND = Corrected.getCorrectionDecl(); 10067 if (!ND) 10068 return BuildInvalid(); 10069 10070 // If we corrected to an inheriting constructor, handle it as one. 10071 auto *RD = dyn_cast<CXXRecordDecl>(ND); 10072 if (RD && RD->isInjectedClassName()) { 10073 // The parent of the injected class name is the class itself. 10074 RD = cast<CXXRecordDecl>(RD->getParent()); 10075 10076 // Fix up the information we'll use to build the using declaration. 10077 if (Corrected.WillReplaceSpecifier()) { 10078 NestedNameSpecifierLocBuilder Builder; 10079 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 10080 QualifierLoc.getSourceRange()); 10081 QualifierLoc = Builder.getWithLocInContext(Context); 10082 } 10083 10084 // In this case, the name we introduce is the name of a derived class 10085 // constructor. 10086 auto *CurClass = cast<CXXRecordDecl>(CurContext); 10087 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10088 Context.getCanonicalType(Context.getRecordType(CurClass)))); 10089 UsingName.setNamedTypeInfo(nullptr); 10090 for (auto *Ctor : LookupConstructors(RD)) 10091 R.addDecl(Ctor); 10092 R.resolveKind(); 10093 } else { 10094 // FIXME: Pick up all the declarations if we found an overloaded 10095 // function. 10096 UsingName.setName(ND->getDeclName()); 10097 R.addDecl(ND); 10098 } 10099 } else { 10100 Diag(IdentLoc, diag::err_no_member) 10101 << NameInfo.getName() << LookupContext << SS.getRange(); 10102 return BuildInvalid(); 10103 } 10104 } 10105 10106 if (R.isAmbiguous()) 10107 return BuildInvalid(); 10108 10109 if (HasTypenameKeyword) { 10110 // If we asked for a typename and got a non-type decl, error out. 10111 if (!R.getAsSingle<TypeDecl>()) { 10112 Diag(IdentLoc, diag::err_using_typename_non_type); 10113 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10114 Diag((*I)->getUnderlyingDecl()->getLocation(), 10115 diag::note_using_decl_target); 10116 return BuildInvalid(); 10117 } 10118 } else { 10119 // If we asked for a non-typename and we got a type, error out, 10120 // but only if this is an instantiation of an unresolved using 10121 // decl. Otherwise just silently find the type name. 10122 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10123 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10124 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10125 return BuildInvalid(); 10126 } 10127 } 10128 10129 // C++14 [namespace.udecl]p6: 10130 // A using-declaration shall not name a namespace. 10131 if (R.getAsSingle<NamespaceDecl>()) { 10132 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10133 << SS.getRange(); 10134 return BuildInvalid(); 10135 } 10136 10137 // C++14 [namespace.udecl]p7: 10138 // A using-declaration shall not name a scoped enumerator. 10139 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10140 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10141 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10142 << SS.getRange(); 10143 return BuildInvalid(); 10144 } 10145 } 10146 10147 UsingDecl *UD = BuildValid(); 10148 10149 // Some additional rules apply to inheriting constructors. 10150 if (UsingName.getName().getNameKind() == 10151 DeclarationName::CXXConstructorName) { 10152 // Suppress access diagnostics; the access check is instead performed at the 10153 // point of use for an inheriting constructor. 10154 R.suppressDiagnostics(); 10155 if (CheckInheritingConstructorUsingDecl(UD)) 10156 return UD; 10157 } 10158 10159 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10160 UsingShadowDecl *PrevDecl = nullptr; 10161 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10162 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10163 } 10164 10165 return UD; 10166 } 10167 10168 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10169 ArrayRef<NamedDecl *> Expansions) { 10170 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10171 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10172 isa<UsingPackDecl>(InstantiatedFrom)); 10173 10174 auto *UPD = 10175 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10176 UPD->setAccess(InstantiatedFrom->getAccess()); 10177 CurContext->addDecl(UPD); 10178 return UPD; 10179 } 10180 10181 /// Additional checks for a using declaration referring to a constructor name. 10182 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10183 assert(!UD->hasTypename() && "expecting a constructor name"); 10184 10185 const Type *SourceType = UD->getQualifier()->getAsType(); 10186 assert(SourceType && 10187 "Using decl naming constructor doesn't have type in scope spec."); 10188 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10189 10190 // Check whether the named type is a direct base class. 10191 bool AnyDependentBases = false; 10192 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10193 AnyDependentBases); 10194 if (!Base && !AnyDependentBases) { 10195 Diag(UD->getUsingLoc(), 10196 diag::err_using_decl_constructor_not_in_direct_base) 10197 << UD->getNameInfo().getSourceRange() 10198 << QualType(SourceType, 0) << TargetClass; 10199 UD->setInvalidDecl(); 10200 return true; 10201 } 10202 10203 if (Base) 10204 Base->setInheritConstructors(); 10205 10206 return false; 10207 } 10208 10209 /// Checks that the given using declaration is not an invalid 10210 /// redeclaration. Note that this is checking only for the using decl 10211 /// itself, not for any ill-formedness among the UsingShadowDecls. 10212 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10213 bool HasTypenameKeyword, 10214 const CXXScopeSpec &SS, 10215 SourceLocation NameLoc, 10216 const LookupResult &Prev) { 10217 NestedNameSpecifier *Qual = SS.getScopeRep(); 10218 10219 // C++03 [namespace.udecl]p8: 10220 // C++0x [namespace.udecl]p10: 10221 // A using-declaration is a declaration and can therefore be used 10222 // repeatedly where (and only where) multiple declarations are 10223 // allowed. 10224 // 10225 // That's in non-member contexts. 10226 if (!CurContext->getRedeclContext()->isRecord()) { 10227 // A dependent qualifier outside a class can only ever resolve to an 10228 // enumeration type. Therefore it conflicts with any other non-type 10229 // declaration in the same scope. 10230 // FIXME: How should we check for dependent type-type conflicts at block 10231 // scope? 10232 if (Qual->isDependent() && !HasTypenameKeyword) { 10233 for (auto *D : Prev) { 10234 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10235 bool OldCouldBeEnumerator = 10236 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10237 Diag(NameLoc, 10238 OldCouldBeEnumerator ? diag::err_redefinition 10239 : diag::err_redefinition_different_kind) 10240 << Prev.getLookupName(); 10241 Diag(D->getLocation(), diag::note_previous_definition); 10242 return true; 10243 } 10244 } 10245 } 10246 return false; 10247 } 10248 10249 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10250 NamedDecl *D = *I; 10251 10252 bool DTypename; 10253 NestedNameSpecifier *DQual; 10254 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10255 DTypename = UD->hasTypename(); 10256 DQual = UD->getQualifier(); 10257 } else if (UnresolvedUsingValueDecl *UD 10258 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10259 DTypename = false; 10260 DQual = UD->getQualifier(); 10261 } else if (UnresolvedUsingTypenameDecl *UD 10262 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10263 DTypename = true; 10264 DQual = UD->getQualifier(); 10265 } else continue; 10266 10267 // using decls differ if one says 'typename' and the other doesn't. 10268 // FIXME: non-dependent using decls? 10269 if (HasTypenameKeyword != DTypename) continue; 10270 10271 // using decls differ if they name different scopes (but note that 10272 // template instantiation can cause this check to trigger when it 10273 // didn't before instantiation). 10274 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10275 Context.getCanonicalNestedNameSpecifier(DQual)) 10276 continue; 10277 10278 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10279 Diag(D->getLocation(), diag::note_using_decl) << 1; 10280 return true; 10281 } 10282 10283 return false; 10284 } 10285 10286 10287 /// Checks that the given nested-name qualifier used in a using decl 10288 /// in the current context is appropriately related to the current 10289 /// scope. If an error is found, diagnoses it and returns true. 10290 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10291 bool HasTypename, 10292 const CXXScopeSpec &SS, 10293 const DeclarationNameInfo &NameInfo, 10294 SourceLocation NameLoc) { 10295 DeclContext *NamedContext = computeDeclContext(SS); 10296 10297 if (!CurContext->isRecord()) { 10298 // C++03 [namespace.udecl]p3: 10299 // C++0x [namespace.udecl]p8: 10300 // A using-declaration for a class member shall be a member-declaration. 10301 10302 // If we weren't able to compute a valid scope, it might validly be a 10303 // dependent class scope or a dependent enumeration unscoped scope. If 10304 // we have a 'typename' keyword, the scope must resolve to a class type. 10305 if ((HasTypename && !NamedContext) || 10306 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10307 auto *RD = NamedContext 10308 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10309 : nullptr; 10310 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10311 RD = nullptr; 10312 10313 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10314 << SS.getRange(); 10315 10316 // If we have a complete, non-dependent source type, try to suggest a 10317 // way to get the same effect. 10318 if (!RD) 10319 return true; 10320 10321 // Find what this using-declaration was referring to. 10322 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10323 R.setHideTags(false); 10324 R.suppressDiagnostics(); 10325 LookupQualifiedName(R, RD); 10326 10327 if (R.getAsSingle<TypeDecl>()) { 10328 if (getLangOpts().CPlusPlus11) { 10329 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10330 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10331 << 0 // alias declaration 10332 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10333 NameInfo.getName().getAsString() + 10334 " = "); 10335 } else { 10336 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10337 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 10338 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10339 << 1 // typedef declaration 10340 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10341 << FixItHint::CreateInsertion( 10342 InsertLoc, " " + NameInfo.getName().getAsString()); 10343 } 10344 } else if (R.getAsSingle<VarDecl>()) { 10345 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10346 // repeating the type of the static data member here. 10347 FixItHint FixIt; 10348 if (getLangOpts().CPlusPlus11) { 10349 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10350 FixIt = FixItHint::CreateReplacement( 10351 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10352 } 10353 10354 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10355 << 2 // reference declaration 10356 << FixIt; 10357 } else if (R.getAsSingle<EnumConstantDecl>()) { 10358 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10359 // repeating the type of the enumeration here, and we can't do so if 10360 // the type is anonymous. 10361 FixItHint FixIt; 10362 if (getLangOpts().CPlusPlus11) { 10363 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10364 FixIt = FixItHint::CreateReplacement( 10365 UsingLoc, 10366 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10367 } 10368 10369 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10370 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10371 << FixIt; 10372 } 10373 return true; 10374 } 10375 10376 // Otherwise, this might be valid. 10377 return false; 10378 } 10379 10380 // The current scope is a record. 10381 10382 // If the named context is dependent, we can't decide much. 10383 if (!NamedContext) { 10384 // FIXME: in C++0x, we can diagnose if we can prove that the 10385 // nested-name-specifier does not refer to a base class, which is 10386 // still possible in some cases. 10387 10388 // Otherwise we have to conservatively report that things might be 10389 // okay. 10390 return false; 10391 } 10392 10393 if (!NamedContext->isRecord()) { 10394 // Ideally this would point at the last name in the specifier, 10395 // but we don't have that level of source info. 10396 Diag(SS.getRange().getBegin(), 10397 diag::err_using_decl_nested_name_specifier_is_not_class) 10398 << SS.getScopeRep() << SS.getRange(); 10399 return true; 10400 } 10401 10402 if (!NamedContext->isDependentContext() && 10403 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10404 return true; 10405 10406 if (getLangOpts().CPlusPlus11) { 10407 // C++11 [namespace.udecl]p3: 10408 // In a using-declaration used as a member-declaration, the 10409 // nested-name-specifier shall name a base class of the class 10410 // being defined. 10411 10412 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10413 cast<CXXRecordDecl>(NamedContext))) { 10414 if (CurContext == NamedContext) { 10415 Diag(NameLoc, 10416 diag::err_using_decl_nested_name_specifier_is_current_class) 10417 << SS.getRange(); 10418 return true; 10419 } 10420 10421 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10422 Diag(SS.getRange().getBegin(), 10423 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10424 << SS.getScopeRep() 10425 << cast<CXXRecordDecl>(CurContext) 10426 << SS.getRange(); 10427 } 10428 return true; 10429 } 10430 10431 return false; 10432 } 10433 10434 // C++03 [namespace.udecl]p4: 10435 // A using-declaration used as a member-declaration shall refer 10436 // to a member of a base class of the class being defined [etc.]. 10437 10438 // Salient point: SS doesn't have to name a base class as long as 10439 // lookup only finds members from base classes. Therefore we can 10440 // diagnose here only if we can prove that that can't happen, 10441 // i.e. if the class hierarchies provably don't intersect. 10442 10443 // TODO: it would be nice if "definitely valid" results were cached 10444 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10445 // need to be repeated. 10446 10447 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10448 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10449 Bases.insert(Base); 10450 return true; 10451 }; 10452 10453 // Collect all bases. Return false if we find a dependent base. 10454 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10455 return false; 10456 10457 // Returns true if the base is dependent or is one of the accumulated base 10458 // classes. 10459 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10460 return !Bases.count(Base); 10461 }; 10462 10463 // Return false if the class has a dependent base or if it or one 10464 // of its bases is present in the base set of the current context. 10465 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10466 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10467 return false; 10468 10469 Diag(SS.getRange().getBegin(), 10470 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10471 << SS.getScopeRep() 10472 << cast<CXXRecordDecl>(CurContext) 10473 << SS.getRange(); 10474 10475 return true; 10476 } 10477 10478 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 10479 MultiTemplateParamsArg TemplateParamLists, 10480 SourceLocation UsingLoc, UnqualifiedId &Name, 10481 const ParsedAttributesView &AttrList, 10482 TypeResult Type, Decl *DeclFromDeclSpec) { 10483 // Skip up to the relevant declaration scope. 10484 while (S->isTemplateParamScope()) 10485 S = S->getParent(); 10486 assert((S->getFlags() & Scope::DeclScope) && 10487 "got alias-declaration outside of declaration scope"); 10488 10489 if (Type.isInvalid()) 10490 return nullptr; 10491 10492 bool Invalid = false; 10493 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10494 TypeSourceInfo *TInfo = nullptr; 10495 GetTypeFromParser(Type.get(), &TInfo); 10496 10497 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10498 return nullptr; 10499 10500 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10501 UPPC_DeclarationType)) { 10502 Invalid = true; 10503 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10504 TInfo->getTypeLoc().getBeginLoc()); 10505 } 10506 10507 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10508 TemplateParamLists.size() 10509 ? forRedeclarationInCurContext() 10510 : ForVisibleRedeclaration); 10511 LookupName(Previous, S); 10512 10513 // Warn about shadowing the name of a template parameter. 10514 if (Previous.isSingleResult() && 10515 Previous.getFoundDecl()->isTemplateParameter()) { 10516 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10517 Previous.clear(); 10518 } 10519 10520 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10521 "name in alias declaration must be an identifier"); 10522 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10523 Name.StartLocation, 10524 Name.Identifier, TInfo); 10525 10526 NewTD->setAccess(AS); 10527 10528 if (Invalid) 10529 NewTD->setInvalidDecl(); 10530 10531 ProcessDeclAttributeList(S, NewTD, AttrList); 10532 AddPragmaAttributes(S, NewTD); 10533 10534 CheckTypedefForVariablyModifiedType(S, NewTD); 10535 Invalid |= NewTD->isInvalidDecl(); 10536 10537 bool Redeclaration = false; 10538 10539 NamedDecl *NewND; 10540 if (TemplateParamLists.size()) { 10541 TypeAliasTemplateDecl *OldDecl = nullptr; 10542 TemplateParameterList *OldTemplateParams = nullptr; 10543 10544 if (TemplateParamLists.size() != 1) { 10545 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10546 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10547 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10548 } 10549 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10550 10551 // Check that we can declare a template here. 10552 if (CheckTemplateDeclScope(S, TemplateParams)) 10553 return nullptr; 10554 10555 // Only consider previous declarations in the same scope. 10556 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10557 /*ExplicitInstantiationOrSpecialization*/false); 10558 if (!Previous.empty()) { 10559 Redeclaration = true; 10560 10561 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10562 if (!OldDecl && !Invalid) { 10563 Diag(UsingLoc, diag::err_redefinition_different_kind) 10564 << Name.Identifier; 10565 10566 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10567 if (OldD->getLocation().isValid()) 10568 Diag(OldD->getLocation(), diag::note_previous_definition); 10569 10570 Invalid = true; 10571 } 10572 10573 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10574 if (TemplateParameterListsAreEqual(TemplateParams, 10575 OldDecl->getTemplateParameters(), 10576 /*Complain=*/true, 10577 TPL_TemplateMatch)) 10578 OldTemplateParams = 10579 OldDecl->getMostRecentDecl()->getTemplateParameters(); 10580 else 10581 Invalid = true; 10582 10583 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10584 if (!Invalid && 10585 !Context.hasSameType(OldTD->getUnderlyingType(), 10586 NewTD->getUnderlyingType())) { 10587 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10588 // but we can't reasonably accept it. 10589 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10590 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10591 if (OldTD->getLocation().isValid()) 10592 Diag(OldTD->getLocation(), diag::note_previous_definition); 10593 Invalid = true; 10594 } 10595 } 10596 } 10597 10598 // Merge any previous default template arguments into our parameters, 10599 // and check the parameter list. 10600 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10601 TPC_TypeAliasTemplate)) 10602 return nullptr; 10603 10604 TypeAliasTemplateDecl *NewDecl = 10605 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10606 Name.Identifier, TemplateParams, 10607 NewTD); 10608 NewTD->setDescribedAliasTemplate(NewDecl); 10609 10610 NewDecl->setAccess(AS); 10611 10612 if (Invalid) 10613 NewDecl->setInvalidDecl(); 10614 else if (OldDecl) { 10615 NewDecl->setPreviousDecl(OldDecl); 10616 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10617 } 10618 10619 NewND = NewDecl; 10620 } else { 10621 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10622 setTagNameForLinkagePurposes(TD, NewTD); 10623 handleTagNumbering(TD, S); 10624 } 10625 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10626 NewND = NewTD; 10627 } 10628 10629 PushOnScopeChains(NewND, S); 10630 ActOnDocumentableDecl(NewND); 10631 return NewND; 10632 } 10633 10634 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10635 SourceLocation AliasLoc, 10636 IdentifierInfo *Alias, CXXScopeSpec &SS, 10637 SourceLocation IdentLoc, 10638 IdentifierInfo *Ident) { 10639 10640 // Lookup the namespace name. 10641 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10642 LookupParsedName(R, S, &SS); 10643 10644 if (R.isAmbiguous()) 10645 return nullptr; 10646 10647 if (R.empty()) { 10648 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10649 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10650 return nullptr; 10651 } 10652 } 10653 assert(!R.isAmbiguous() && !R.empty()); 10654 NamedDecl *ND = R.getRepresentativeDecl(); 10655 10656 // Check if we have a previous declaration with the same name. 10657 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10658 ForVisibleRedeclaration); 10659 LookupName(PrevR, S); 10660 10661 // Check we're not shadowing a template parameter. 10662 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10663 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10664 PrevR.clear(); 10665 } 10666 10667 // Filter out any other lookup result from an enclosing scope. 10668 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10669 /*AllowInlineNamespace*/false); 10670 10671 // Find the previous declaration and check that we can redeclare it. 10672 NamespaceAliasDecl *Prev = nullptr; 10673 if (PrevR.isSingleResult()) { 10674 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10675 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10676 // We already have an alias with the same name that points to the same 10677 // namespace; check that it matches. 10678 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10679 Prev = AD; 10680 } else if (isVisible(PrevDecl)) { 10681 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10682 << Alias; 10683 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10684 << AD->getNamespace(); 10685 return nullptr; 10686 } 10687 } else if (isVisible(PrevDecl)) { 10688 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10689 ? diag::err_redefinition 10690 : diag::err_redefinition_different_kind; 10691 Diag(AliasLoc, DiagID) << Alias; 10692 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10693 return nullptr; 10694 } 10695 } 10696 10697 // The use of a nested name specifier may trigger deprecation warnings. 10698 DiagnoseUseOfDecl(ND, IdentLoc); 10699 10700 NamespaceAliasDecl *AliasDecl = 10701 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10702 Alias, SS.getWithLocInContext(Context), 10703 IdentLoc, ND); 10704 if (Prev) 10705 AliasDecl->setPreviousDecl(Prev); 10706 10707 PushOnScopeChains(AliasDecl, S); 10708 return AliasDecl; 10709 } 10710 10711 namespace { 10712 struct SpecialMemberExceptionSpecInfo 10713 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10714 SourceLocation Loc; 10715 Sema::ImplicitExceptionSpecification ExceptSpec; 10716 10717 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10718 Sema::CXXSpecialMember CSM, 10719 Sema::InheritedConstructorInfo *ICI, 10720 SourceLocation Loc) 10721 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10722 10723 bool visitBase(CXXBaseSpecifier *Base); 10724 bool visitField(FieldDecl *FD); 10725 10726 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10727 unsigned Quals); 10728 10729 void visitSubobjectCall(Subobject Subobj, 10730 Sema::SpecialMemberOverloadResult SMOR); 10731 }; 10732 } 10733 10734 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10735 auto *RT = Base->getType()->getAs<RecordType>(); 10736 if (!RT) 10737 return false; 10738 10739 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10740 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10741 if (auto *BaseCtor = SMOR.getMethod()) { 10742 visitSubobjectCall(Base, BaseCtor); 10743 return false; 10744 } 10745 10746 visitClassSubobject(BaseClass, Base, 0); 10747 return false; 10748 } 10749 10750 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10751 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10752 Expr *E = FD->getInClassInitializer(); 10753 if (!E) 10754 // FIXME: It's a little wasteful to build and throw away a 10755 // CXXDefaultInitExpr here. 10756 // FIXME: We should have a single context note pointing at Loc, and 10757 // this location should be MD->getLocation() instead, since that's 10758 // the location where we actually use the default init expression. 10759 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10760 if (E) 10761 ExceptSpec.CalledExpr(E); 10762 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10763 ->getAs<RecordType>()) { 10764 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10765 FD->getType().getCVRQualifiers()); 10766 } 10767 return false; 10768 } 10769 10770 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10771 Subobject Subobj, 10772 unsigned Quals) { 10773 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10774 bool IsMutable = Field && Field->isMutable(); 10775 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10776 } 10777 10778 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10779 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10780 // Note, if lookup fails, it doesn't matter what exception specification we 10781 // choose because the special member will be deleted. 10782 if (CXXMethodDecl *MD = SMOR.getMethod()) 10783 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10784 } 10785 10786 namespace { 10787 /// RAII object to register a special member as being currently declared. 10788 struct ComputingExceptionSpec { 10789 Sema &S; 10790 10791 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) 10792 : S(S) { 10793 Sema::CodeSynthesisContext Ctx; 10794 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 10795 Ctx.PointOfInstantiation = Loc; 10796 Ctx.Entity = MD; 10797 S.pushCodeSynthesisContext(Ctx); 10798 } 10799 ~ComputingExceptionSpec() { 10800 S.popCodeSynthesisContext(); 10801 } 10802 }; 10803 } 10804 10805 static Sema::ImplicitExceptionSpecification 10806 ComputeDefaultedSpecialMemberExceptionSpec( 10807 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10808 Sema::InheritedConstructorInfo *ICI) { 10809 ComputingExceptionSpec CES(S, MD, Loc); 10810 10811 CXXRecordDecl *ClassDecl = MD->getParent(); 10812 10813 // C++ [except.spec]p14: 10814 // An implicitly declared special member function (Clause 12) shall have an 10815 // exception-specification. [...] 10816 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 10817 if (ClassDecl->isInvalidDecl()) 10818 return Info.ExceptSpec; 10819 10820 // FIXME: If this diagnostic fires, we're probably missing a check for 10821 // attempting to resolve an exception specification before it's known 10822 // at a higher level. 10823 if (S.RequireCompleteType(MD->getLocation(), 10824 S.Context.getRecordType(ClassDecl), 10825 diag::err_exception_spec_incomplete_type)) 10826 return Info.ExceptSpec; 10827 10828 // C++1z [except.spec]p7: 10829 // [Look for exceptions thrown by] a constructor selected [...] to 10830 // initialize a potentially constructed subobject, 10831 // C++1z [except.spec]p8: 10832 // The exception specification for an implicitly-declared destructor, or a 10833 // destructor without a noexcept-specifier, is potentially-throwing if and 10834 // only if any of the destructors for any of its potentially constructed 10835 // subojects is potentially throwing. 10836 // FIXME: We respect the first rule but ignore the "potentially constructed" 10837 // in the second rule to resolve a core issue (no number yet) that would have 10838 // us reject: 10839 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10840 // struct B : A {}; 10841 // struct C : B { void f(); }; 10842 // ... due to giving B::~B() a non-throwing exception specification. 10843 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10844 : Info.VisitAllBases); 10845 10846 return Info.ExceptSpec; 10847 } 10848 10849 namespace { 10850 /// RAII object to register a special member as being currently declared. 10851 struct DeclaringSpecialMember { 10852 Sema &S; 10853 Sema::SpecialMemberDecl D; 10854 Sema::ContextRAII SavedContext; 10855 bool WasAlreadyBeingDeclared; 10856 10857 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10858 : S(S), D(RD, CSM), SavedContext(S, RD) { 10859 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10860 if (WasAlreadyBeingDeclared) 10861 // This almost never happens, but if it does, ensure that our cache 10862 // doesn't contain a stale result. 10863 S.SpecialMemberCache.clear(); 10864 else { 10865 // Register a note to be produced if we encounter an error while 10866 // declaring the special member. 10867 Sema::CodeSynthesisContext Ctx; 10868 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10869 // FIXME: We don't have a location to use here. Using the class's 10870 // location maintains the fiction that we declare all special members 10871 // with the class, but (1) it's not clear that lying about that helps our 10872 // users understand what's going on, and (2) there may be outer contexts 10873 // on the stack (some of which are relevant) and printing them exposes 10874 // our lies. 10875 Ctx.PointOfInstantiation = RD->getLocation(); 10876 Ctx.Entity = RD; 10877 Ctx.SpecialMember = CSM; 10878 S.pushCodeSynthesisContext(Ctx); 10879 } 10880 } 10881 ~DeclaringSpecialMember() { 10882 if (!WasAlreadyBeingDeclared) { 10883 S.SpecialMembersBeingDeclared.erase(D); 10884 S.popCodeSynthesisContext(); 10885 } 10886 } 10887 10888 /// Are we already trying to declare this special member? 10889 bool isAlreadyBeingDeclared() const { 10890 return WasAlreadyBeingDeclared; 10891 } 10892 }; 10893 } 10894 10895 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10896 // Look up any existing declarations, but don't trigger declaration of all 10897 // implicit special members with this name. 10898 DeclarationName Name = FD->getDeclName(); 10899 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10900 ForExternalRedeclaration); 10901 for (auto *D : FD->getParent()->lookup(Name)) 10902 if (auto *Acceptable = R.getAcceptableDecl(D)) 10903 R.addDecl(Acceptable); 10904 R.resolveKind(); 10905 R.suppressDiagnostics(); 10906 10907 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10908 } 10909 10910 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10911 CXXRecordDecl *ClassDecl) { 10912 // C++ [class.ctor]p5: 10913 // A default constructor for a class X is a constructor of class X 10914 // that can be called without an argument. If there is no 10915 // user-declared constructor for class X, a default constructor is 10916 // implicitly declared. An implicitly-declared default constructor 10917 // is an inline public member of its class. 10918 assert(ClassDecl->needsImplicitDefaultConstructor() && 10919 "Should not build implicit default constructor!"); 10920 10921 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10922 if (DSM.isAlreadyBeingDeclared()) 10923 return nullptr; 10924 10925 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10926 CXXDefaultConstructor, 10927 false); 10928 10929 // Create the actual constructor declaration. 10930 CanQualType ClassType 10931 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10932 SourceLocation ClassLoc = ClassDecl->getLocation(); 10933 DeclarationName Name 10934 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10935 DeclarationNameInfo NameInfo(Name, ClassLoc); 10936 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10937 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10938 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10939 /*isImplicitlyDeclared=*/true, Constexpr); 10940 DefaultCon->setAccess(AS_public); 10941 DefaultCon->setDefaulted(); 10942 10943 if (getLangOpts().CUDA) { 10944 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10945 DefaultCon, 10946 /* ConstRHS */ false, 10947 /* Diagnose */ false); 10948 } 10949 10950 // Build an exception specification pointing back at this constructor. 10951 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10952 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10953 10954 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10955 // constructors is easy to compute. 10956 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10957 10958 // Note that we have declared this constructor. 10959 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10960 10961 Scope *S = getScopeForContext(ClassDecl); 10962 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10963 10964 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10965 SetDeclDeleted(DefaultCon, ClassLoc); 10966 10967 if (S) 10968 PushOnScopeChains(DefaultCon, S, false); 10969 ClassDecl->addDecl(DefaultCon); 10970 10971 return DefaultCon; 10972 } 10973 10974 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10975 CXXConstructorDecl *Constructor) { 10976 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10977 !Constructor->doesThisDeclarationHaveABody() && 10978 !Constructor->isDeleted()) && 10979 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10980 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10981 return; 10982 10983 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10984 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10985 10986 SynthesizedFunctionScope Scope(*this, Constructor); 10987 10988 // The exception specification is needed because we are defining the 10989 // function. 10990 ResolveExceptionSpec(CurrentLocation, 10991 Constructor->getType()->castAs<FunctionProtoType>()); 10992 MarkVTableUsed(CurrentLocation, ClassDecl); 10993 10994 // Add a context note for diagnostics produced after this point. 10995 Scope.addContextNote(CurrentLocation); 10996 10997 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10998 Constructor->setInvalidDecl(); 10999 return; 11000 } 11001 11002 SourceLocation Loc = Constructor->getEndLoc().isValid() 11003 ? Constructor->getEndLoc() 11004 : Constructor->getLocation(); 11005 Constructor->setBody(new (Context) CompoundStmt(Loc)); 11006 Constructor->markUsed(Context); 11007 11008 if (ASTMutationListener *L = getASTMutationListener()) { 11009 L->CompletedImplicitDefinition(Constructor); 11010 } 11011 11012 DiagnoseUninitializedFields(*this, Constructor); 11013 } 11014 11015 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 11016 // Perform any delayed checks on exception specifications. 11017 CheckDelayedMemberExceptionSpecs(); 11018 } 11019 11020 /// Find or create the fake constructor we synthesize to model constructing an 11021 /// object of a derived class via a constructor of a base class. 11022 CXXConstructorDecl * 11023 Sema::findInheritingConstructor(SourceLocation Loc, 11024 CXXConstructorDecl *BaseCtor, 11025 ConstructorUsingShadowDecl *Shadow) { 11026 CXXRecordDecl *Derived = Shadow->getParent(); 11027 SourceLocation UsingLoc = Shadow->getLocation(); 11028 11029 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 11030 // For now we use the name of the base class constructor as a member of the 11031 // derived class to indicate a (fake) inherited constructor name. 11032 DeclarationName Name = BaseCtor->getDeclName(); 11033 11034 // Check to see if we already have a fake constructor for this inherited 11035 // constructor call. 11036 for (NamedDecl *Ctor : Derived->lookup(Name)) 11037 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 11038 ->getInheritedConstructor() 11039 .getConstructor(), 11040 BaseCtor)) 11041 return cast<CXXConstructorDecl>(Ctor); 11042 11043 DeclarationNameInfo NameInfo(Name, UsingLoc); 11044 TypeSourceInfo *TInfo = 11045 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 11046 FunctionProtoTypeLoc ProtoLoc = 11047 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 11048 11049 // Check the inherited constructor is valid and find the list of base classes 11050 // from which it was inherited. 11051 InheritedConstructorInfo ICI(*this, Loc, Shadow); 11052 11053 bool Constexpr = 11054 BaseCtor->isConstexpr() && 11055 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 11056 false, BaseCtor, &ICI); 11057 11058 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 11059 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 11060 BaseCtor->isExplicit(), /*Inline=*/true, 11061 /*ImplicitlyDeclared=*/true, Constexpr, 11062 InheritedConstructor(Shadow, BaseCtor)); 11063 if (Shadow->isInvalidDecl()) 11064 DerivedCtor->setInvalidDecl(); 11065 11066 // Build an unevaluated exception specification for this fake constructor. 11067 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 11068 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11069 EPI.ExceptionSpec.Type = EST_Unevaluated; 11070 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 11071 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 11072 FPT->getParamTypes(), EPI)); 11073 11074 // Build the parameter declarations. 11075 SmallVector<ParmVarDecl *, 16> ParamDecls; 11076 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 11077 TypeSourceInfo *TInfo = 11078 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 11079 ParmVarDecl *PD = ParmVarDecl::Create( 11080 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 11081 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 11082 PD->setScopeInfo(0, I); 11083 PD->setImplicit(); 11084 // Ensure attributes are propagated onto parameters (this matters for 11085 // format, pass_object_size, ...). 11086 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 11087 ParamDecls.push_back(PD); 11088 ProtoLoc.setParam(I, PD); 11089 } 11090 11091 // Set up the new constructor. 11092 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 11093 DerivedCtor->setAccess(BaseCtor->getAccess()); 11094 DerivedCtor->setParams(ParamDecls); 11095 Derived->addDecl(DerivedCtor); 11096 11097 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 11098 SetDeclDeleted(DerivedCtor, UsingLoc); 11099 11100 return DerivedCtor; 11101 } 11102 11103 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 11104 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 11105 Ctor->getInheritedConstructor().getShadowDecl()); 11106 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 11107 /*Diagnose*/true); 11108 } 11109 11110 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 11111 CXXConstructorDecl *Constructor) { 11112 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11113 assert(Constructor->getInheritedConstructor() && 11114 !Constructor->doesThisDeclarationHaveABody() && 11115 !Constructor->isDeleted()); 11116 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11117 return; 11118 11119 // Initializations are performed "as if by a defaulted default constructor", 11120 // so enter the appropriate scope. 11121 SynthesizedFunctionScope Scope(*this, Constructor); 11122 11123 // The exception specification is needed because we are defining the 11124 // function. 11125 ResolveExceptionSpec(CurrentLocation, 11126 Constructor->getType()->castAs<FunctionProtoType>()); 11127 MarkVTableUsed(CurrentLocation, ClassDecl); 11128 11129 // Add a context note for diagnostics produced after this point. 11130 Scope.addContextNote(CurrentLocation); 11131 11132 ConstructorUsingShadowDecl *Shadow = 11133 Constructor->getInheritedConstructor().getShadowDecl(); 11134 CXXConstructorDecl *InheritedCtor = 11135 Constructor->getInheritedConstructor().getConstructor(); 11136 11137 // [class.inhctor.init]p1: 11138 // initialization proceeds as if a defaulted default constructor is used to 11139 // initialize the D object and each base class subobject from which the 11140 // constructor was inherited 11141 11142 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11143 CXXRecordDecl *RD = Shadow->getParent(); 11144 SourceLocation InitLoc = Shadow->getLocation(); 11145 11146 // Build explicit initializers for all base classes from which the 11147 // constructor was inherited. 11148 SmallVector<CXXCtorInitializer*, 8> Inits; 11149 for (bool VBase : {false, true}) { 11150 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11151 if (B.isVirtual() != VBase) 11152 continue; 11153 11154 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11155 if (!BaseRD) 11156 continue; 11157 11158 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11159 if (!BaseCtor.first) 11160 continue; 11161 11162 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11163 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11164 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11165 11166 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11167 Inits.push_back(new (Context) CXXCtorInitializer( 11168 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11169 SourceLocation())); 11170 } 11171 } 11172 11173 // We now proceed as if for a defaulted default constructor, with the relevant 11174 // initializers replaced. 11175 11176 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11177 Constructor->setInvalidDecl(); 11178 return; 11179 } 11180 11181 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11182 Constructor->markUsed(Context); 11183 11184 if (ASTMutationListener *L = getASTMutationListener()) { 11185 L->CompletedImplicitDefinition(Constructor); 11186 } 11187 11188 DiagnoseUninitializedFields(*this, Constructor); 11189 } 11190 11191 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11192 // C++ [class.dtor]p2: 11193 // If a class has no user-declared destructor, a destructor is 11194 // declared implicitly. An implicitly-declared destructor is an 11195 // inline public member of its class. 11196 assert(ClassDecl->needsImplicitDestructor()); 11197 11198 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11199 if (DSM.isAlreadyBeingDeclared()) 11200 return nullptr; 11201 11202 // Create the actual destructor declaration. 11203 CanQualType ClassType 11204 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11205 SourceLocation ClassLoc = ClassDecl->getLocation(); 11206 DeclarationName Name 11207 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11208 DeclarationNameInfo NameInfo(Name, ClassLoc); 11209 CXXDestructorDecl *Destructor 11210 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11211 QualType(), nullptr, /*isInline=*/true, 11212 /*isImplicitlyDeclared=*/true); 11213 Destructor->setAccess(AS_public); 11214 Destructor->setDefaulted(); 11215 11216 if (getLangOpts().CUDA) { 11217 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11218 Destructor, 11219 /* ConstRHS */ false, 11220 /* Diagnose */ false); 11221 } 11222 11223 // Build an exception specification pointing back at this destructor. 11224 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 11225 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11226 11227 // We don't need to use SpecialMemberIsTrivial here; triviality for 11228 // destructors is easy to compute. 11229 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11230 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11231 ClassDecl->hasTrivialDestructorForCall()); 11232 11233 // Note that we have declared this destructor. 11234 ++ASTContext::NumImplicitDestructorsDeclared; 11235 11236 Scope *S = getScopeForContext(ClassDecl); 11237 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11238 11239 // We can't check whether an implicit destructor is deleted before we complete 11240 // the definition of the class, because its validity depends on the alignment 11241 // of the class. We'll check this from ActOnFields once the class is complete. 11242 if (ClassDecl->isCompleteDefinition() && 11243 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11244 SetDeclDeleted(Destructor, ClassLoc); 11245 11246 // Introduce this destructor into its scope. 11247 if (S) 11248 PushOnScopeChains(Destructor, S, false); 11249 ClassDecl->addDecl(Destructor); 11250 11251 return Destructor; 11252 } 11253 11254 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11255 CXXDestructorDecl *Destructor) { 11256 assert((Destructor->isDefaulted() && 11257 !Destructor->doesThisDeclarationHaveABody() && 11258 !Destructor->isDeleted()) && 11259 "DefineImplicitDestructor - call it for implicit default dtor"); 11260 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11261 return; 11262 11263 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11264 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11265 11266 SynthesizedFunctionScope Scope(*this, Destructor); 11267 11268 // The exception specification is needed because we are defining the 11269 // function. 11270 ResolveExceptionSpec(CurrentLocation, 11271 Destructor->getType()->castAs<FunctionProtoType>()); 11272 MarkVTableUsed(CurrentLocation, ClassDecl); 11273 11274 // Add a context note for diagnostics produced after this point. 11275 Scope.addContextNote(CurrentLocation); 11276 11277 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11278 Destructor->getParent()); 11279 11280 if (CheckDestructor(Destructor)) { 11281 Destructor->setInvalidDecl(); 11282 return; 11283 } 11284 11285 SourceLocation Loc = Destructor->getEndLoc().isValid() 11286 ? Destructor->getEndLoc() 11287 : Destructor->getLocation(); 11288 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11289 Destructor->markUsed(Context); 11290 11291 if (ASTMutationListener *L = getASTMutationListener()) { 11292 L->CompletedImplicitDefinition(Destructor); 11293 } 11294 } 11295 11296 /// Perform any semantic analysis which needs to be delayed until all 11297 /// pending class member declarations have been parsed. 11298 void Sema::ActOnFinishCXXMemberDecls() { 11299 // If the context is an invalid C++ class, just suppress these checks. 11300 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11301 if (Record->isInvalidDecl()) { 11302 DelayedOverridingExceptionSpecChecks.clear(); 11303 DelayedEquivalentExceptionSpecChecks.clear(); 11304 DelayedDefaultedMemberExceptionSpecs.clear(); 11305 return; 11306 } 11307 checkForMultipleExportedDefaultConstructors(*this, Record); 11308 } 11309 } 11310 11311 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11312 referenceDLLExportedClassMethods(); 11313 } 11314 11315 void Sema::referenceDLLExportedClassMethods() { 11316 if (!DelayedDllExportClasses.empty()) { 11317 // Calling ReferenceDllExportedMembers might cause the current function to 11318 // be called again, so use a local copy of DelayedDllExportClasses. 11319 SmallVector<CXXRecordDecl *, 4> WorkList; 11320 std::swap(DelayedDllExportClasses, WorkList); 11321 for (CXXRecordDecl *Class : WorkList) 11322 ReferenceDllExportedMembers(*this, Class); 11323 } 11324 } 11325 11326 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 11327 assert(getLangOpts().CPlusPlus11 && 11328 "adjusting dtor exception specs was introduced in c++11"); 11329 11330 if (Destructor->isDependentContext()) 11331 return; 11332 11333 // C++11 [class.dtor]p3: 11334 // A declaration of a destructor that does not have an exception- 11335 // specification is implicitly considered to have the same exception- 11336 // specification as an implicit declaration. 11337 const FunctionProtoType *DtorType = Destructor->getType()-> 11338 getAs<FunctionProtoType>(); 11339 if (DtorType->hasExceptionSpec()) 11340 return; 11341 11342 // Replace the destructor's type, building off the existing one. Fortunately, 11343 // the only thing of interest in the destructor type is its extended info. 11344 // The return and arguments are fixed. 11345 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11346 EPI.ExceptionSpec.Type = EST_Unevaluated; 11347 EPI.ExceptionSpec.SourceDecl = Destructor; 11348 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11349 11350 // FIXME: If the destructor has a body that could throw, and the newly created 11351 // spec doesn't allow exceptions, we should emit a warning, because this 11352 // change in behavior can break conforming C++03 programs at runtime. 11353 // However, we don't have a body or an exception specification yet, so it 11354 // needs to be done somewhere else. 11355 } 11356 11357 namespace { 11358 /// An abstract base class for all helper classes used in building the 11359 // copy/move operators. These classes serve as factory functions and help us 11360 // avoid using the same Expr* in the AST twice. 11361 class ExprBuilder { 11362 ExprBuilder(const ExprBuilder&) = delete; 11363 ExprBuilder &operator=(const ExprBuilder&) = delete; 11364 11365 protected: 11366 static Expr *assertNotNull(Expr *E) { 11367 assert(E && "Expression construction must not fail."); 11368 return E; 11369 } 11370 11371 public: 11372 ExprBuilder() {} 11373 virtual ~ExprBuilder() {} 11374 11375 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11376 }; 11377 11378 class RefBuilder: public ExprBuilder { 11379 VarDecl *Var; 11380 QualType VarType; 11381 11382 public: 11383 Expr *build(Sema &S, SourceLocation Loc) const override { 11384 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 11385 } 11386 11387 RefBuilder(VarDecl *Var, QualType VarType) 11388 : Var(Var), VarType(VarType) {} 11389 }; 11390 11391 class ThisBuilder: public ExprBuilder { 11392 public: 11393 Expr *build(Sema &S, SourceLocation Loc) const override { 11394 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11395 } 11396 }; 11397 11398 class CastBuilder: public ExprBuilder { 11399 const ExprBuilder &Builder; 11400 QualType Type; 11401 ExprValueKind Kind; 11402 const CXXCastPath &Path; 11403 11404 public: 11405 Expr *build(Sema &S, SourceLocation Loc) const override { 11406 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11407 CK_UncheckedDerivedToBase, Kind, 11408 &Path).get()); 11409 } 11410 11411 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11412 const CXXCastPath &Path) 11413 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11414 }; 11415 11416 class DerefBuilder: public ExprBuilder { 11417 const ExprBuilder &Builder; 11418 11419 public: 11420 Expr *build(Sema &S, SourceLocation Loc) const override { 11421 return assertNotNull( 11422 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11423 } 11424 11425 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11426 }; 11427 11428 class MemberBuilder: public ExprBuilder { 11429 const ExprBuilder &Builder; 11430 QualType Type; 11431 CXXScopeSpec SS; 11432 bool IsArrow; 11433 LookupResult &MemberLookup; 11434 11435 public: 11436 Expr *build(Sema &S, SourceLocation Loc) const override { 11437 return assertNotNull(S.BuildMemberReferenceExpr( 11438 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11439 nullptr, MemberLookup, nullptr, nullptr).get()); 11440 } 11441 11442 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11443 LookupResult &MemberLookup) 11444 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11445 MemberLookup(MemberLookup) {} 11446 }; 11447 11448 class MoveCastBuilder: public ExprBuilder { 11449 const ExprBuilder &Builder; 11450 11451 public: 11452 Expr *build(Sema &S, SourceLocation Loc) const override { 11453 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11454 } 11455 11456 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11457 }; 11458 11459 class LvalueConvBuilder: public ExprBuilder { 11460 const ExprBuilder &Builder; 11461 11462 public: 11463 Expr *build(Sema &S, SourceLocation Loc) const override { 11464 return assertNotNull( 11465 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11466 } 11467 11468 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11469 }; 11470 11471 class SubscriptBuilder: public ExprBuilder { 11472 const ExprBuilder &Base; 11473 const ExprBuilder &Index; 11474 11475 public: 11476 Expr *build(Sema &S, SourceLocation Loc) const override { 11477 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11478 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11479 } 11480 11481 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11482 : Base(Base), Index(Index) {} 11483 }; 11484 11485 } // end anonymous namespace 11486 11487 /// When generating a defaulted copy or move assignment operator, if a field 11488 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11489 /// do so. This optimization only applies for arrays of scalars, and for arrays 11490 /// of class type where the selected copy/move-assignment operator is trivial. 11491 static StmtResult 11492 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11493 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11494 // Compute the size of the memory buffer to be copied. 11495 QualType SizeType = S.Context.getSizeType(); 11496 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11497 S.Context.getTypeSizeInChars(T).getQuantity()); 11498 11499 // Take the address of the field references for "from" and "to". We 11500 // directly construct UnaryOperators here because semantic analysis 11501 // does not permit us to take the address of an xvalue. 11502 Expr *From = FromB.build(S, Loc); 11503 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11504 S.Context.getPointerType(From->getType()), 11505 VK_RValue, OK_Ordinary, Loc, false); 11506 Expr *To = ToB.build(S, Loc); 11507 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11508 S.Context.getPointerType(To->getType()), 11509 VK_RValue, OK_Ordinary, Loc, false); 11510 11511 const Type *E = T->getBaseElementTypeUnsafe(); 11512 bool NeedsCollectableMemCpy = 11513 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11514 11515 // Create a reference to the __builtin_objc_memmove_collectable function 11516 StringRef MemCpyName = NeedsCollectableMemCpy ? 11517 "__builtin_objc_memmove_collectable" : 11518 "__builtin_memcpy"; 11519 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11520 Sema::LookupOrdinaryName); 11521 S.LookupName(R, S.TUScope, true); 11522 11523 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11524 if (!MemCpy) 11525 // Something went horribly wrong earlier, and we will have complained 11526 // about it. 11527 return StmtError(); 11528 11529 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11530 VK_RValue, Loc, nullptr); 11531 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11532 11533 Expr *CallArgs[] = { 11534 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11535 }; 11536 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11537 Loc, CallArgs, Loc); 11538 11539 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11540 return Call.getAs<Stmt>(); 11541 } 11542 11543 /// Builds a statement that copies/moves the given entity from \p From to 11544 /// \c To. 11545 /// 11546 /// This routine is used to copy/move the members of a class with an 11547 /// implicitly-declared copy/move assignment operator. When the entities being 11548 /// copied are arrays, this routine builds for loops to copy them. 11549 /// 11550 /// \param S The Sema object used for type-checking. 11551 /// 11552 /// \param Loc The location where the implicit copy/move is being generated. 11553 /// 11554 /// \param T The type of the expressions being copied/moved. Both expressions 11555 /// must have this type. 11556 /// 11557 /// \param To The expression we are copying/moving to. 11558 /// 11559 /// \param From The expression we are copying/moving from. 11560 /// 11561 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11562 /// Otherwise, it's a non-static member subobject. 11563 /// 11564 /// \param Copying Whether we're copying or moving. 11565 /// 11566 /// \param Depth Internal parameter recording the depth of the recursion. 11567 /// 11568 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11569 /// if a memcpy should be used instead. 11570 static StmtResult 11571 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11572 const ExprBuilder &To, const ExprBuilder &From, 11573 bool CopyingBaseSubobject, bool Copying, 11574 unsigned Depth = 0) { 11575 // C++11 [class.copy]p28: 11576 // Each subobject is assigned in the manner appropriate to its type: 11577 // 11578 // - if the subobject is of class type, as if by a call to operator= with 11579 // the subobject as the object expression and the corresponding 11580 // subobject of x as a single function argument (as if by explicit 11581 // qualification; that is, ignoring any possible virtual overriding 11582 // functions in more derived classes); 11583 // 11584 // C++03 [class.copy]p13: 11585 // - if the subobject is of class type, the copy assignment operator for 11586 // the class is used (as if by explicit qualification; that is, 11587 // ignoring any possible virtual overriding functions in more derived 11588 // classes); 11589 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11590 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11591 11592 // Look for operator=. 11593 DeclarationName Name 11594 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11595 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11596 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11597 11598 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11599 // operator. 11600 if (!S.getLangOpts().CPlusPlus11) { 11601 LookupResult::Filter F = OpLookup.makeFilter(); 11602 while (F.hasNext()) { 11603 NamedDecl *D = F.next(); 11604 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11605 if (Method->isCopyAssignmentOperator() || 11606 (!Copying && Method->isMoveAssignmentOperator())) 11607 continue; 11608 11609 F.erase(); 11610 } 11611 F.done(); 11612 } 11613 11614 // Suppress the protected check (C++ [class.protected]) for each of the 11615 // assignment operators we found. This strange dance is required when 11616 // we're assigning via a base classes's copy-assignment operator. To 11617 // ensure that we're getting the right base class subobject (without 11618 // ambiguities), we need to cast "this" to that subobject type; to 11619 // ensure that we don't go through the virtual call mechanism, we need 11620 // to qualify the operator= name with the base class (see below). However, 11621 // this means that if the base class has a protected copy assignment 11622 // operator, the protected member access check will fail. So, we 11623 // rewrite "protected" access to "public" access in this case, since we 11624 // know by construction that we're calling from a derived class. 11625 if (CopyingBaseSubobject) { 11626 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11627 L != LEnd; ++L) { 11628 if (L.getAccess() == AS_protected) 11629 L.setAccess(AS_public); 11630 } 11631 } 11632 11633 // Create the nested-name-specifier that will be used to qualify the 11634 // reference to operator=; this is required to suppress the virtual 11635 // call mechanism. 11636 CXXScopeSpec SS; 11637 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11638 SS.MakeTrivial(S.Context, 11639 NestedNameSpecifier::Create(S.Context, nullptr, false, 11640 CanonicalT), 11641 Loc); 11642 11643 // Create the reference to operator=. 11644 ExprResult OpEqualRef 11645 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11646 SS, /*TemplateKWLoc=*/SourceLocation(), 11647 /*FirstQualifierInScope=*/nullptr, 11648 OpLookup, 11649 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11650 /*SuppressQualifierCheck=*/true); 11651 if (OpEqualRef.isInvalid()) 11652 return StmtError(); 11653 11654 // Build the call to the assignment operator. 11655 11656 Expr *FromInst = From.build(S, Loc); 11657 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11658 OpEqualRef.getAs<Expr>(), 11659 Loc, FromInst, Loc); 11660 if (Call.isInvalid()) 11661 return StmtError(); 11662 11663 // If we built a call to a trivial 'operator=' while copying an array, 11664 // bail out. We'll replace the whole shebang with a memcpy. 11665 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11666 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11667 return StmtResult((Stmt*)nullptr); 11668 11669 // Convert to an expression-statement, and clean up any produced 11670 // temporaries. 11671 return S.ActOnExprStmt(Call); 11672 } 11673 11674 // - if the subobject is of scalar type, the built-in assignment 11675 // operator is used. 11676 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11677 if (!ArrayTy) { 11678 ExprResult Assignment = S.CreateBuiltinBinOp( 11679 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11680 if (Assignment.isInvalid()) 11681 return StmtError(); 11682 return S.ActOnExprStmt(Assignment); 11683 } 11684 11685 // - if the subobject is an array, each element is assigned, in the 11686 // manner appropriate to the element type; 11687 11688 // Construct a loop over the array bounds, e.g., 11689 // 11690 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11691 // 11692 // that will copy each of the array elements. 11693 QualType SizeType = S.Context.getSizeType(); 11694 11695 // Create the iteration variable. 11696 IdentifierInfo *IterationVarName = nullptr; 11697 { 11698 SmallString<8> Str; 11699 llvm::raw_svector_ostream OS(Str); 11700 OS << "__i" << Depth; 11701 IterationVarName = &S.Context.Idents.get(OS.str()); 11702 } 11703 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11704 IterationVarName, SizeType, 11705 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11706 SC_None); 11707 11708 // Initialize the iteration variable to zero. 11709 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11710 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11711 11712 // Creates a reference to the iteration variable. 11713 RefBuilder IterationVarRef(IterationVar, SizeType); 11714 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11715 11716 // Create the DeclStmt that holds the iteration variable. 11717 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11718 11719 // Subscript the "from" and "to" expressions with the iteration variable. 11720 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11721 MoveCastBuilder FromIndexMove(FromIndexCopy); 11722 const ExprBuilder *FromIndex; 11723 if (Copying) 11724 FromIndex = &FromIndexCopy; 11725 else 11726 FromIndex = &FromIndexMove; 11727 11728 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11729 11730 // Build the copy/move for an individual element of the array. 11731 StmtResult Copy = 11732 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11733 ToIndex, *FromIndex, CopyingBaseSubobject, 11734 Copying, Depth + 1); 11735 // Bail out if copying fails or if we determined that we should use memcpy. 11736 if (Copy.isInvalid() || !Copy.get()) 11737 return Copy; 11738 11739 // Create the comparison against the array bound. 11740 llvm::APInt Upper 11741 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11742 Expr *Comparison 11743 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11744 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11745 BO_NE, S.Context.BoolTy, 11746 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11747 11748 // Create the pre-increment of the iteration variable. We can determine 11749 // whether the increment will overflow based on the value of the array 11750 // bound. 11751 Expr *Increment = new (S.Context) 11752 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11753 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11754 11755 // Construct the loop that copies all elements of this array. 11756 return S.ActOnForStmt( 11757 Loc, Loc, InitStmt, 11758 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11759 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11760 } 11761 11762 static StmtResult 11763 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11764 const ExprBuilder &To, const ExprBuilder &From, 11765 bool CopyingBaseSubobject, bool Copying) { 11766 // Maybe we should use a memcpy? 11767 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11768 T.isTriviallyCopyableType(S.Context)) 11769 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11770 11771 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11772 CopyingBaseSubobject, 11773 Copying, 0)); 11774 11775 // If we ended up picking a trivial assignment operator for an array of a 11776 // non-trivially-copyable class type, just emit a memcpy. 11777 if (!Result.isInvalid() && !Result.get()) 11778 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11779 11780 return Result; 11781 } 11782 11783 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11784 // Note: The following rules are largely analoguous to the copy 11785 // constructor rules. Note that virtual bases are not taken into account 11786 // for determining the argument type of the operator. Note also that 11787 // operators taking an object instead of a reference are allowed. 11788 assert(ClassDecl->needsImplicitCopyAssignment()); 11789 11790 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11791 if (DSM.isAlreadyBeingDeclared()) 11792 return nullptr; 11793 11794 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11795 QualType RetType = Context.getLValueReferenceType(ArgType); 11796 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11797 if (Const) 11798 ArgType = ArgType.withConst(); 11799 ArgType = Context.getLValueReferenceType(ArgType); 11800 11801 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11802 CXXCopyAssignment, 11803 Const); 11804 11805 // An implicitly-declared copy assignment operator is an inline public 11806 // member of its class. 11807 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11808 SourceLocation ClassLoc = ClassDecl->getLocation(); 11809 DeclarationNameInfo NameInfo(Name, ClassLoc); 11810 CXXMethodDecl *CopyAssignment = 11811 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11812 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11813 /*isInline=*/true, Constexpr, SourceLocation()); 11814 CopyAssignment->setAccess(AS_public); 11815 CopyAssignment->setDefaulted(); 11816 CopyAssignment->setImplicit(); 11817 11818 if (getLangOpts().CUDA) { 11819 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11820 CopyAssignment, 11821 /* ConstRHS */ Const, 11822 /* Diagnose */ false); 11823 } 11824 11825 // Build an exception specification pointing back at this member. 11826 FunctionProtoType::ExtProtoInfo EPI = 11827 getImplicitMethodEPI(*this, CopyAssignment); 11828 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11829 11830 // Add the parameter to the operator. 11831 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11832 ClassLoc, ClassLoc, 11833 /*Id=*/nullptr, ArgType, 11834 /*TInfo=*/nullptr, SC_None, 11835 nullptr); 11836 CopyAssignment->setParams(FromParam); 11837 11838 CopyAssignment->setTrivial( 11839 ClassDecl->needsOverloadResolutionForCopyAssignment() 11840 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11841 : ClassDecl->hasTrivialCopyAssignment()); 11842 11843 // Note that we have added this copy-assignment operator. 11844 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11845 11846 Scope *S = getScopeForContext(ClassDecl); 11847 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11848 11849 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11850 SetDeclDeleted(CopyAssignment, ClassLoc); 11851 11852 if (S) 11853 PushOnScopeChains(CopyAssignment, S, false); 11854 ClassDecl->addDecl(CopyAssignment); 11855 11856 return CopyAssignment; 11857 } 11858 11859 /// Diagnose an implicit copy operation for a class which is odr-used, but 11860 /// which is deprecated because the class has a user-declared copy constructor, 11861 /// copy assignment operator, or destructor. 11862 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11863 assert(CopyOp->isImplicit()); 11864 11865 CXXRecordDecl *RD = CopyOp->getParent(); 11866 CXXMethodDecl *UserDeclaredOperation = nullptr; 11867 11868 // In Microsoft mode, assignment operations don't affect constructors and 11869 // vice versa. 11870 if (RD->hasUserDeclaredDestructor()) { 11871 UserDeclaredOperation = RD->getDestructor(); 11872 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11873 RD->hasUserDeclaredCopyConstructor() && 11874 !S.getLangOpts().MSVCCompat) { 11875 // Find any user-declared copy constructor. 11876 for (auto *I : RD->ctors()) { 11877 if (I->isCopyConstructor()) { 11878 UserDeclaredOperation = I; 11879 break; 11880 } 11881 } 11882 assert(UserDeclaredOperation); 11883 } else if (isa<CXXConstructorDecl>(CopyOp) && 11884 RD->hasUserDeclaredCopyAssignment() && 11885 !S.getLangOpts().MSVCCompat) { 11886 // Find any user-declared move assignment operator. 11887 for (auto *I : RD->methods()) { 11888 if (I->isCopyAssignmentOperator()) { 11889 UserDeclaredOperation = I; 11890 break; 11891 } 11892 } 11893 assert(UserDeclaredOperation); 11894 } 11895 11896 if (UserDeclaredOperation) { 11897 S.Diag(UserDeclaredOperation->getLocation(), 11898 diag::warn_deprecated_copy_operation) 11899 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11900 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11901 } 11902 } 11903 11904 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11905 CXXMethodDecl *CopyAssignOperator) { 11906 assert((CopyAssignOperator->isDefaulted() && 11907 CopyAssignOperator->isOverloadedOperator() && 11908 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11909 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11910 !CopyAssignOperator->isDeleted()) && 11911 "DefineImplicitCopyAssignment called for wrong function"); 11912 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11913 return; 11914 11915 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11916 if (ClassDecl->isInvalidDecl()) { 11917 CopyAssignOperator->setInvalidDecl(); 11918 return; 11919 } 11920 11921 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11922 11923 // The exception specification is needed because we are defining the 11924 // function. 11925 ResolveExceptionSpec(CurrentLocation, 11926 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11927 11928 // Add a context note for diagnostics produced after this point. 11929 Scope.addContextNote(CurrentLocation); 11930 11931 // C++11 [class.copy]p18: 11932 // The [definition of an implicitly declared copy assignment operator] is 11933 // deprecated if the class has a user-declared copy constructor or a 11934 // user-declared destructor. 11935 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11936 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11937 11938 // C++0x [class.copy]p30: 11939 // The implicitly-defined or explicitly-defaulted copy assignment operator 11940 // for a non-union class X performs memberwise copy assignment of its 11941 // subobjects. The direct base classes of X are assigned first, in the 11942 // order of their declaration in the base-specifier-list, and then the 11943 // immediate non-static data members of X are assigned, in the order in 11944 // which they were declared in the class definition. 11945 11946 // The statements that form the synthesized function body. 11947 SmallVector<Stmt*, 8> Statements; 11948 11949 // The parameter for the "other" object, which we are copying from. 11950 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11951 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11952 QualType OtherRefType = Other->getType(); 11953 if (const LValueReferenceType *OtherRef 11954 = OtherRefType->getAs<LValueReferenceType>()) { 11955 OtherRefType = OtherRef->getPointeeType(); 11956 OtherQuals = OtherRefType.getQualifiers(); 11957 } 11958 11959 // Our location for everything implicitly-generated. 11960 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 11961 ? CopyAssignOperator->getEndLoc() 11962 : CopyAssignOperator->getLocation(); 11963 11964 // Builds a DeclRefExpr for the "other" object. 11965 RefBuilder OtherRef(Other, OtherRefType); 11966 11967 // Builds the "this" pointer. 11968 ThisBuilder This; 11969 11970 // Assign base classes. 11971 bool Invalid = false; 11972 for (auto &Base : ClassDecl->bases()) { 11973 // Form the assignment: 11974 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11975 QualType BaseType = Base.getType().getUnqualifiedType(); 11976 if (!BaseType->isRecordType()) { 11977 Invalid = true; 11978 continue; 11979 } 11980 11981 CXXCastPath BasePath; 11982 BasePath.push_back(&Base); 11983 11984 // Construct the "from" expression, which is an implicit cast to the 11985 // appropriately-qualified base type. 11986 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11987 VK_LValue, BasePath); 11988 11989 // Dereference "this". 11990 DerefBuilder DerefThis(This); 11991 CastBuilder To(DerefThis, 11992 Context.getQualifiedType( 11993 BaseType, CopyAssignOperator->getTypeQualifiers()), 11994 VK_LValue, BasePath); 11995 11996 // Build the copy. 11997 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11998 To, From, 11999 /*CopyingBaseSubobject=*/true, 12000 /*Copying=*/true); 12001 if (Copy.isInvalid()) { 12002 CopyAssignOperator->setInvalidDecl(); 12003 return; 12004 } 12005 12006 // Success! Record the copy. 12007 Statements.push_back(Copy.getAs<Expr>()); 12008 } 12009 12010 // Assign non-static members. 12011 for (auto *Field : ClassDecl->fields()) { 12012 // FIXME: We should form some kind of AST representation for the implied 12013 // memcpy in a union copy operation. 12014 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12015 continue; 12016 12017 if (Field->isInvalidDecl()) { 12018 Invalid = true; 12019 continue; 12020 } 12021 12022 // Check for members of reference type; we can't copy those. 12023 if (Field->getType()->isReferenceType()) { 12024 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12025 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12026 Diag(Field->getLocation(), diag::note_declared_at); 12027 Invalid = true; 12028 continue; 12029 } 12030 12031 // Check for members of const-qualified, non-class type. 12032 QualType BaseType = Context.getBaseElementType(Field->getType()); 12033 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12034 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12035 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12036 Diag(Field->getLocation(), diag::note_declared_at); 12037 Invalid = true; 12038 continue; 12039 } 12040 12041 // Suppress assigning zero-width bitfields. 12042 if (Field->isZeroLengthBitField(Context)) 12043 continue; 12044 12045 QualType FieldType = Field->getType().getNonReferenceType(); 12046 if (FieldType->isIncompleteArrayType()) { 12047 assert(ClassDecl->hasFlexibleArrayMember() && 12048 "Incomplete array type is not valid"); 12049 continue; 12050 } 12051 12052 // Build references to the field in the object we're copying from and to. 12053 CXXScopeSpec SS; // Intentionally empty 12054 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12055 LookupMemberName); 12056 MemberLookup.addDecl(Field); 12057 MemberLookup.resolveKind(); 12058 12059 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 12060 12061 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 12062 12063 // Build the copy of this field. 12064 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 12065 To, From, 12066 /*CopyingBaseSubobject=*/false, 12067 /*Copying=*/true); 12068 if (Copy.isInvalid()) { 12069 CopyAssignOperator->setInvalidDecl(); 12070 return; 12071 } 12072 12073 // Success! Record the copy. 12074 Statements.push_back(Copy.getAs<Stmt>()); 12075 } 12076 12077 if (!Invalid) { 12078 // Add a "return *this;" 12079 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12080 12081 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12082 if (Return.isInvalid()) 12083 Invalid = true; 12084 else 12085 Statements.push_back(Return.getAs<Stmt>()); 12086 } 12087 12088 if (Invalid) { 12089 CopyAssignOperator->setInvalidDecl(); 12090 return; 12091 } 12092 12093 StmtResult Body; 12094 { 12095 CompoundScopeRAII CompoundScope(*this); 12096 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12097 /*isStmtExpr=*/false); 12098 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12099 } 12100 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 12101 CopyAssignOperator->markUsed(Context); 12102 12103 if (ASTMutationListener *L = getASTMutationListener()) { 12104 L->CompletedImplicitDefinition(CopyAssignOperator); 12105 } 12106 } 12107 12108 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 12109 assert(ClassDecl->needsImplicitMoveAssignment()); 12110 12111 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 12112 if (DSM.isAlreadyBeingDeclared()) 12113 return nullptr; 12114 12115 // Note: The following rules are largely analoguous to the move 12116 // constructor rules. 12117 12118 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12119 QualType RetType = Context.getLValueReferenceType(ArgType); 12120 ArgType = Context.getRValueReferenceType(ArgType); 12121 12122 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12123 CXXMoveAssignment, 12124 false); 12125 12126 // An implicitly-declared move assignment operator is an inline public 12127 // member of its class. 12128 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12129 SourceLocation ClassLoc = ClassDecl->getLocation(); 12130 DeclarationNameInfo NameInfo(Name, ClassLoc); 12131 CXXMethodDecl *MoveAssignment = 12132 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12133 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12134 /*isInline=*/true, Constexpr, SourceLocation()); 12135 MoveAssignment->setAccess(AS_public); 12136 MoveAssignment->setDefaulted(); 12137 MoveAssignment->setImplicit(); 12138 12139 if (getLangOpts().CUDA) { 12140 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12141 MoveAssignment, 12142 /* ConstRHS */ false, 12143 /* Diagnose */ false); 12144 } 12145 12146 // Build an exception specification pointing back at this member. 12147 FunctionProtoType::ExtProtoInfo EPI = 12148 getImplicitMethodEPI(*this, MoveAssignment); 12149 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12150 12151 // Add the parameter to the operator. 12152 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12153 ClassLoc, ClassLoc, 12154 /*Id=*/nullptr, ArgType, 12155 /*TInfo=*/nullptr, SC_None, 12156 nullptr); 12157 MoveAssignment->setParams(FromParam); 12158 12159 MoveAssignment->setTrivial( 12160 ClassDecl->needsOverloadResolutionForMoveAssignment() 12161 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12162 : ClassDecl->hasTrivialMoveAssignment()); 12163 12164 // Note that we have added this copy-assignment operator. 12165 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 12166 12167 Scope *S = getScopeForContext(ClassDecl); 12168 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12169 12170 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12171 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12172 SetDeclDeleted(MoveAssignment, ClassLoc); 12173 } 12174 12175 if (S) 12176 PushOnScopeChains(MoveAssignment, S, false); 12177 ClassDecl->addDecl(MoveAssignment); 12178 12179 return MoveAssignment; 12180 } 12181 12182 /// Check if we're implicitly defining a move assignment operator for a class 12183 /// with virtual bases. Such a move assignment might move-assign the virtual 12184 /// base multiple times. 12185 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12186 SourceLocation CurrentLocation) { 12187 assert(!Class->isDependentContext() && "should not define dependent move"); 12188 12189 // Only a virtual base could get implicitly move-assigned multiple times. 12190 // Only a non-trivial move assignment can observe this. We only want to 12191 // diagnose if we implicitly define an assignment operator that assigns 12192 // two base classes, both of which move-assign the same virtual base. 12193 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12194 Class->getNumBases() < 2) 12195 return; 12196 12197 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12198 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12199 VBaseMap VBases; 12200 12201 for (auto &BI : Class->bases()) { 12202 Worklist.push_back(&BI); 12203 while (!Worklist.empty()) { 12204 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12205 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12206 12207 // If the base has no non-trivial move assignment operators, 12208 // we don't care about moves from it. 12209 if (!Base->hasNonTrivialMoveAssignment()) 12210 continue; 12211 12212 // If there's nothing virtual here, skip it. 12213 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12214 continue; 12215 12216 // If we're not actually going to call a move assignment for this base, 12217 // or the selected move assignment is trivial, skip it. 12218 Sema::SpecialMemberOverloadResult SMOR = 12219 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12220 /*ConstArg*/false, /*VolatileArg*/false, 12221 /*RValueThis*/true, /*ConstThis*/false, 12222 /*VolatileThis*/false); 12223 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12224 !SMOR.getMethod()->isMoveAssignmentOperator()) 12225 continue; 12226 12227 if (BaseSpec->isVirtual()) { 12228 // We're going to move-assign this virtual base, and its move 12229 // assignment operator is not trivial. If this can happen for 12230 // multiple distinct direct bases of Class, diagnose it. (If it 12231 // only happens in one base, we'll diagnose it when synthesizing 12232 // that base class's move assignment operator.) 12233 CXXBaseSpecifier *&Existing = 12234 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12235 .first->second; 12236 if (Existing && Existing != &BI) { 12237 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12238 << Class << Base; 12239 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 12240 << (Base->getCanonicalDecl() == 12241 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12242 << Base << Existing->getType() << Existing->getSourceRange(); 12243 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 12244 << (Base->getCanonicalDecl() == 12245 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12246 << Base << BI.getType() << BaseSpec->getSourceRange(); 12247 12248 // Only diagnose each vbase once. 12249 Existing = nullptr; 12250 } 12251 } else { 12252 // Only walk over bases that have defaulted move assignment operators. 12253 // We assume that any user-provided move assignment operator handles 12254 // the multiple-moves-of-vbase case itself somehow. 12255 if (!SMOR.getMethod()->isDefaulted()) 12256 continue; 12257 12258 // We're going to move the base classes of Base. Add them to the list. 12259 for (auto &BI : Base->bases()) 12260 Worklist.push_back(&BI); 12261 } 12262 } 12263 } 12264 } 12265 12266 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12267 CXXMethodDecl *MoveAssignOperator) { 12268 assert((MoveAssignOperator->isDefaulted() && 12269 MoveAssignOperator->isOverloadedOperator() && 12270 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12271 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12272 !MoveAssignOperator->isDeleted()) && 12273 "DefineImplicitMoveAssignment called for wrong function"); 12274 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12275 return; 12276 12277 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12278 if (ClassDecl->isInvalidDecl()) { 12279 MoveAssignOperator->setInvalidDecl(); 12280 return; 12281 } 12282 12283 // C++0x [class.copy]p28: 12284 // The implicitly-defined or move assignment operator for a non-union class 12285 // X performs memberwise move assignment of its subobjects. The direct base 12286 // classes of X are assigned first, in the order of their declaration in the 12287 // base-specifier-list, and then the immediate non-static data members of X 12288 // are assigned, in the order in which they were declared in the class 12289 // definition. 12290 12291 // Issue a warning if our implicit move assignment operator will move 12292 // from a virtual base more than once. 12293 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12294 12295 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12296 12297 // The exception specification is needed because we are defining the 12298 // function. 12299 ResolveExceptionSpec(CurrentLocation, 12300 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12301 12302 // Add a context note for diagnostics produced after this point. 12303 Scope.addContextNote(CurrentLocation); 12304 12305 // The statements that form the synthesized function body. 12306 SmallVector<Stmt*, 8> Statements; 12307 12308 // The parameter for the "other" object, which we are move from. 12309 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12310 QualType OtherRefType = Other->getType()-> 12311 getAs<RValueReferenceType>()->getPointeeType(); 12312 assert(!OtherRefType.getQualifiers() && 12313 "Bad argument type of defaulted move assignment"); 12314 12315 // Our location for everything implicitly-generated. 12316 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 12317 ? MoveAssignOperator->getEndLoc() 12318 : MoveAssignOperator->getLocation(); 12319 12320 // Builds a reference to the "other" object. 12321 RefBuilder OtherRef(Other, OtherRefType); 12322 // Cast to rvalue. 12323 MoveCastBuilder MoveOther(OtherRef); 12324 12325 // Builds the "this" pointer. 12326 ThisBuilder This; 12327 12328 // Assign base classes. 12329 bool Invalid = false; 12330 for (auto &Base : ClassDecl->bases()) { 12331 // C++11 [class.copy]p28: 12332 // It is unspecified whether subobjects representing virtual base classes 12333 // are assigned more than once by the implicitly-defined copy assignment 12334 // operator. 12335 // FIXME: Do not assign to a vbase that will be assigned by some other base 12336 // class. For a move-assignment, this can result in the vbase being moved 12337 // multiple times. 12338 12339 // Form the assignment: 12340 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12341 QualType BaseType = Base.getType().getUnqualifiedType(); 12342 if (!BaseType->isRecordType()) { 12343 Invalid = true; 12344 continue; 12345 } 12346 12347 CXXCastPath BasePath; 12348 BasePath.push_back(&Base); 12349 12350 // Construct the "from" expression, which is an implicit cast to the 12351 // appropriately-qualified base type. 12352 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12353 12354 // Dereference "this". 12355 DerefBuilder DerefThis(This); 12356 12357 // Implicitly cast "this" to the appropriately-qualified base type. 12358 CastBuilder To(DerefThis, 12359 Context.getQualifiedType( 12360 BaseType, MoveAssignOperator->getTypeQualifiers()), 12361 VK_LValue, BasePath); 12362 12363 // Build the move. 12364 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12365 To, From, 12366 /*CopyingBaseSubobject=*/true, 12367 /*Copying=*/false); 12368 if (Move.isInvalid()) { 12369 MoveAssignOperator->setInvalidDecl(); 12370 return; 12371 } 12372 12373 // Success! Record the move. 12374 Statements.push_back(Move.getAs<Expr>()); 12375 } 12376 12377 // Assign non-static members. 12378 for (auto *Field : ClassDecl->fields()) { 12379 // FIXME: We should form some kind of AST representation for the implied 12380 // memcpy in a union copy operation. 12381 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12382 continue; 12383 12384 if (Field->isInvalidDecl()) { 12385 Invalid = true; 12386 continue; 12387 } 12388 12389 // Check for members of reference type; we can't move those. 12390 if (Field->getType()->isReferenceType()) { 12391 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12392 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12393 Diag(Field->getLocation(), diag::note_declared_at); 12394 Invalid = true; 12395 continue; 12396 } 12397 12398 // Check for members of const-qualified, non-class type. 12399 QualType BaseType = Context.getBaseElementType(Field->getType()); 12400 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12401 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12402 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12403 Diag(Field->getLocation(), diag::note_declared_at); 12404 Invalid = true; 12405 continue; 12406 } 12407 12408 // Suppress assigning zero-width bitfields. 12409 if (Field->isZeroLengthBitField(Context)) 12410 continue; 12411 12412 QualType FieldType = Field->getType().getNonReferenceType(); 12413 if (FieldType->isIncompleteArrayType()) { 12414 assert(ClassDecl->hasFlexibleArrayMember() && 12415 "Incomplete array type is not valid"); 12416 continue; 12417 } 12418 12419 // Build references to the field in the object we're copying from and to. 12420 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12421 LookupMemberName); 12422 MemberLookup.addDecl(Field); 12423 MemberLookup.resolveKind(); 12424 MemberBuilder From(MoveOther, OtherRefType, 12425 /*IsArrow=*/false, MemberLookup); 12426 MemberBuilder To(This, getCurrentThisType(), 12427 /*IsArrow=*/true, MemberLookup); 12428 12429 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12430 "Member reference with rvalue base must be rvalue except for reference " 12431 "members, which aren't allowed for move assignment."); 12432 12433 // Build the move of this field. 12434 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12435 To, From, 12436 /*CopyingBaseSubobject=*/false, 12437 /*Copying=*/false); 12438 if (Move.isInvalid()) { 12439 MoveAssignOperator->setInvalidDecl(); 12440 return; 12441 } 12442 12443 // Success! Record the copy. 12444 Statements.push_back(Move.getAs<Stmt>()); 12445 } 12446 12447 if (!Invalid) { 12448 // Add a "return *this;" 12449 ExprResult ThisObj = 12450 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12451 12452 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12453 if (Return.isInvalid()) 12454 Invalid = true; 12455 else 12456 Statements.push_back(Return.getAs<Stmt>()); 12457 } 12458 12459 if (Invalid) { 12460 MoveAssignOperator->setInvalidDecl(); 12461 return; 12462 } 12463 12464 StmtResult Body; 12465 { 12466 CompoundScopeRAII CompoundScope(*this); 12467 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12468 /*isStmtExpr=*/false); 12469 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12470 } 12471 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12472 MoveAssignOperator->markUsed(Context); 12473 12474 if (ASTMutationListener *L = getASTMutationListener()) { 12475 L->CompletedImplicitDefinition(MoveAssignOperator); 12476 } 12477 } 12478 12479 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12480 CXXRecordDecl *ClassDecl) { 12481 // C++ [class.copy]p4: 12482 // If the class definition does not explicitly declare a copy 12483 // constructor, one is declared implicitly. 12484 assert(ClassDecl->needsImplicitCopyConstructor()); 12485 12486 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12487 if (DSM.isAlreadyBeingDeclared()) 12488 return nullptr; 12489 12490 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12491 QualType ArgType = ClassType; 12492 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12493 if (Const) 12494 ArgType = ArgType.withConst(); 12495 ArgType = Context.getLValueReferenceType(ArgType); 12496 12497 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12498 CXXCopyConstructor, 12499 Const); 12500 12501 DeclarationName Name 12502 = Context.DeclarationNames.getCXXConstructorName( 12503 Context.getCanonicalType(ClassType)); 12504 SourceLocation ClassLoc = ClassDecl->getLocation(); 12505 DeclarationNameInfo NameInfo(Name, ClassLoc); 12506 12507 // An implicitly-declared copy constructor is an inline public 12508 // member of its class. 12509 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12510 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12511 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12512 Constexpr); 12513 CopyConstructor->setAccess(AS_public); 12514 CopyConstructor->setDefaulted(); 12515 12516 if (getLangOpts().CUDA) { 12517 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12518 CopyConstructor, 12519 /* ConstRHS */ Const, 12520 /* Diagnose */ false); 12521 } 12522 12523 // Build an exception specification pointing back at this member. 12524 FunctionProtoType::ExtProtoInfo EPI = 12525 getImplicitMethodEPI(*this, CopyConstructor); 12526 CopyConstructor->setType( 12527 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12528 12529 // Add the parameter to the constructor. 12530 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12531 ClassLoc, ClassLoc, 12532 /*IdentifierInfo=*/nullptr, 12533 ArgType, /*TInfo=*/nullptr, 12534 SC_None, nullptr); 12535 CopyConstructor->setParams(FromParam); 12536 12537 CopyConstructor->setTrivial( 12538 ClassDecl->needsOverloadResolutionForCopyConstructor() 12539 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12540 : ClassDecl->hasTrivialCopyConstructor()); 12541 12542 CopyConstructor->setTrivialForCall( 12543 ClassDecl->hasAttr<TrivialABIAttr>() || 12544 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12545 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12546 TAH_ConsiderTrivialABI) 12547 : ClassDecl->hasTrivialCopyConstructorForCall())); 12548 12549 // Note that we have declared this constructor. 12550 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12551 12552 Scope *S = getScopeForContext(ClassDecl); 12553 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12554 12555 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12556 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12557 SetDeclDeleted(CopyConstructor, ClassLoc); 12558 } 12559 12560 if (S) 12561 PushOnScopeChains(CopyConstructor, S, false); 12562 ClassDecl->addDecl(CopyConstructor); 12563 12564 return CopyConstructor; 12565 } 12566 12567 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12568 CXXConstructorDecl *CopyConstructor) { 12569 assert((CopyConstructor->isDefaulted() && 12570 CopyConstructor->isCopyConstructor() && 12571 !CopyConstructor->doesThisDeclarationHaveABody() && 12572 !CopyConstructor->isDeleted()) && 12573 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12574 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12575 return; 12576 12577 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12578 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12579 12580 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12581 12582 // The exception specification is needed because we are defining the 12583 // function. 12584 ResolveExceptionSpec(CurrentLocation, 12585 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12586 MarkVTableUsed(CurrentLocation, ClassDecl); 12587 12588 // Add a context note for diagnostics produced after this point. 12589 Scope.addContextNote(CurrentLocation); 12590 12591 // C++11 [class.copy]p7: 12592 // The [definition of an implicitly declared copy constructor] is 12593 // deprecated if the class has a user-declared copy assignment operator 12594 // or a user-declared destructor. 12595 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12596 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12597 12598 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12599 CopyConstructor->setInvalidDecl(); 12600 } else { 12601 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 12602 ? CopyConstructor->getEndLoc() 12603 : CopyConstructor->getLocation(); 12604 Sema::CompoundScopeRAII CompoundScope(*this); 12605 CopyConstructor->setBody( 12606 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12607 CopyConstructor->markUsed(Context); 12608 } 12609 12610 if (ASTMutationListener *L = getASTMutationListener()) { 12611 L->CompletedImplicitDefinition(CopyConstructor); 12612 } 12613 } 12614 12615 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12616 CXXRecordDecl *ClassDecl) { 12617 assert(ClassDecl->needsImplicitMoveConstructor()); 12618 12619 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12620 if (DSM.isAlreadyBeingDeclared()) 12621 return nullptr; 12622 12623 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12624 QualType ArgType = Context.getRValueReferenceType(ClassType); 12625 12626 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12627 CXXMoveConstructor, 12628 false); 12629 12630 DeclarationName Name 12631 = Context.DeclarationNames.getCXXConstructorName( 12632 Context.getCanonicalType(ClassType)); 12633 SourceLocation ClassLoc = ClassDecl->getLocation(); 12634 DeclarationNameInfo NameInfo(Name, ClassLoc); 12635 12636 // C++11 [class.copy]p11: 12637 // An implicitly-declared copy/move constructor is an inline public 12638 // member of its class. 12639 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12640 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12641 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12642 Constexpr); 12643 MoveConstructor->setAccess(AS_public); 12644 MoveConstructor->setDefaulted(); 12645 12646 if (getLangOpts().CUDA) { 12647 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12648 MoveConstructor, 12649 /* ConstRHS */ false, 12650 /* Diagnose */ false); 12651 } 12652 12653 // Build an exception specification pointing back at this member. 12654 FunctionProtoType::ExtProtoInfo EPI = 12655 getImplicitMethodEPI(*this, MoveConstructor); 12656 MoveConstructor->setType( 12657 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12658 12659 // Add the parameter to the constructor. 12660 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12661 ClassLoc, ClassLoc, 12662 /*IdentifierInfo=*/nullptr, 12663 ArgType, /*TInfo=*/nullptr, 12664 SC_None, nullptr); 12665 MoveConstructor->setParams(FromParam); 12666 12667 MoveConstructor->setTrivial( 12668 ClassDecl->needsOverloadResolutionForMoveConstructor() 12669 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12670 : ClassDecl->hasTrivialMoveConstructor()); 12671 12672 MoveConstructor->setTrivialForCall( 12673 ClassDecl->hasAttr<TrivialABIAttr>() || 12674 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12675 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12676 TAH_ConsiderTrivialABI) 12677 : ClassDecl->hasTrivialMoveConstructorForCall())); 12678 12679 // Note that we have declared this constructor. 12680 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12681 12682 Scope *S = getScopeForContext(ClassDecl); 12683 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12684 12685 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12686 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12687 SetDeclDeleted(MoveConstructor, ClassLoc); 12688 } 12689 12690 if (S) 12691 PushOnScopeChains(MoveConstructor, S, false); 12692 ClassDecl->addDecl(MoveConstructor); 12693 12694 return MoveConstructor; 12695 } 12696 12697 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12698 CXXConstructorDecl *MoveConstructor) { 12699 assert((MoveConstructor->isDefaulted() && 12700 MoveConstructor->isMoveConstructor() && 12701 !MoveConstructor->doesThisDeclarationHaveABody() && 12702 !MoveConstructor->isDeleted()) && 12703 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12704 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12705 return; 12706 12707 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12708 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12709 12710 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12711 12712 // The exception specification is needed because we are defining the 12713 // function. 12714 ResolveExceptionSpec(CurrentLocation, 12715 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12716 MarkVTableUsed(CurrentLocation, ClassDecl); 12717 12718 // Add a context note for diagnostics produced after this point. 12719 Scope.addContextNote(CurrentLocation); 12720 12721 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12722 MoveConstructor->setInvalidDecl(); 12723 } else { 12724 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 12725 ? MoveConstructor->getEndLoc() 12726 : MoveConstructor->getLocation(); 12727 Sema::CompoundScopeRAII CompoundScope(*this); 12728 MoveConstructor->setBody(ActOnCompoundStmt( 12729 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12730 MoveConstructor->markUsed(Context); 12731 } 12732 12733 if (ASTMutationListener *L = getASTMutationListener()) { 12734 L->CompletedImplicitDefinition(MoveConstructor); 12735 } 12736 } 12737 12738 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12739 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12740 } 12741 12742 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12743 SourceLocation CurrentLocation, 12744 CXXConversionDecl *Conv) { 12745 SynthesizedFunctionScope Scope(*this, Conv); 12746 assert(!Conv->getReturnType()->isUndeducedType()); 12747 12748 CXXRecordDecl *Lambda = Conv->getParent(); 12749 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12750 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12751 12752 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 12753 CallOp = InstantiateFunctionDeclaration( 12754 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12755 if (!CallOp) 12756 return; 12757 12758 Invoker = InstantiateFunctionDeclaration( 12759 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12760 if (!Invoker) 12761 return; 12762 } 12763 12764 if (CallOp->isInvalidDecl()) 12765 return; 12766 12767 // Mark the call operator referenced (and add to pending instantiations 12768 // if necessary). 12769 // For both the conversion and static-invoker template specializations 12770 // we construct their body's in this function, so no need to add them 12771 // to the PendingInstantiations. 12772 MarkFunctionReferenced(CurrentLocation, CallOp); 12773 12774 // Fill in the __invoke function with a dummy implementation. IR generation 12775 // will fill in the actual details. Update its type in case it contained 12776 // an 'auto'. 12777 Invoker->markUsed(Context); 12778 Invoker->setReferenced(); 12779 Invoker->setType(Conv->getReturnType()->getPointeeType()); 12780 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12781 12782 // Construct the body of the conversion function { return __invoke; }. 12783 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12784 VK_LValue, Conv->getLocation()).get(); 12785 assert(FunctionRef && "Can't refer to __invoke function?"); 12786 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12787 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 12788 Conv->getLocation())); 12789 Conv->markUsed(Context); 12790 Conv->setReferenced(); 12791 12792 if (ASTMutationListener *L = getASTMutationListener()) { 12793 L->CompletedImplicitDefinition(Conv); 12794 L->CompletedImplicitDefinition(Invoker); 12795 } 12796 } 12797 12798 12799 12800 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12801 SourceLocation CurrentLocation, 12802 CXXConversionDecl *Conv) 12803 { 12804 assert(!Conv->getParent()->isGenericLambda()); 12805 12806 SynthesizedFunctionScope Scope(*this, Conv); 12807 12808 // Copy-initialize the lambda object as needed to capture it. 12809 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12810 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12811 12812 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12813 Conv->getLocation(), 12814 Conv, DerefThis); 12815 12816 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12817 // behavior. Note that only the general conversion function does this 12818 // (since it's unusable otherwise); in the case where we inline the 12819 // block literal, it has block literal lifetime semantics. 12820 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12821 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12822 CK_CopyAndAutoreleaseBlockObject, 12823 BuildBlock.get(), nullptr, VK_RValue); 12824 12825 if (BuildBlock.isInvalid()) { 12826 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12827 Conv->setInvalidDecl(); 12828 return; 12829 } 12830 12831 // Create the return statement that returns the block from the conversion 12832 // function. 12833 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12834 if (Return.isInvalid()) { 12835 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12836 Conv->setInvalidDecl(); 12837 return; 12838 } 12839 12840 // Set the body of the conversion function. 12841 Stmt *ReturnS = Return.get(); 12842 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 12843 Conv->getLocation())); 12844 Conv->markUsed(Context); 12845 12846 // We're done; notify the mutation listener, if any. 12847 if (ASTMutationListener *L = getASTMutationListener()) { 12848 L->CompletedImplicitDefinition(Conv); 12849 } 12850 } 12851 12852 /// Determine whether the given list arguments contains exactly one 12853 /// "real" (non-default) argument. 12854 static bool hasOneRealArgument(MultiExprArg Args) { 12855 switch (Args.size()) { 12856 case 0: 12857 return false; 12858 12859 default: 12860 if (!Args[1]->isDefaultArgument()) 12861 return false; 12862 12863 LLVM_FALLTHROUGH; 12864 case 1: 12865 return !Args[0]->isDefaultArgument(); 12866 } 12867 12868 return false; 12869 } 12870 12871 ExprResult 12872 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12873 NamedDecl *FoundDecl, 12874 CXXConstructorDecl *Constructor, 12875 MultiExprArg ExprArgs, 12876 bool HadMultipleCandidates, 12877 bool IsListInitialization, 12878 bool IsStdInitListInitialization, 12879 bool RequiresZeroInit, 12880 unsigned ConstructKind, 12881 SourceRange ParenRange) { 12882 bool Elidable = false; 12883 12884 // C++0x [class.copy]p34: 12885 // When certain criteria are met, an implementation is allowed to 12886 // omit the copy/move construction of a class object, even if the 12887 // copy/move constructor and/or destructor for the object have 12888 // side effects. [...] 12889 // - when a temporary class object that has not been bound to a 12890 // reference (12.2) would be copied/moved to a class object 12891 // with the same cv-unqualified type, the copy/move operation 12892 // can be omitted by constructing the temporary object 12893 // directly into the target of the omitted copy/move 12894 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12895 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12896 Expr *SubExpr = ExprArgs[0]; 12897 Elidable = SubExpr->isTemporaryObject( 12898 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12899 } 12900 12901 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12902 FoundDecl, Constructor, 12903 Elidable, ExprArgs, HadMultipleCandidates, 12904 IsListInitialization, 12905 IsStdInitListInitialization, RequiresZeroInit, 12906 ConstructKind, ParenRange); 12907 } 12908 12909 ExprResult 12910 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12911 NamedDecl *FoundDecl, 12912 CXXConstructorDecl *Constructor, 12913 bool Elidable, 12914 MultiExprArg ExprArgs, 12915 bool HadMultipleCandidates, 12916 bool IsListInitialization, 12917 bool IsStdInitListInitialization, 12918 bool RequiresZeroInit, 12919 unsigned ConstructKind, 12920 SourceRange ParenRange) { 12921 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12922 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12923 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12924 return ExprError(); 12925 } 12926 12927 return BuildCXXConstructExpr( 12928 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12929 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12930 RequiresZeroInit, ConstructKind, ParenRange); 12931 } 12932 12933 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12934 /// including handling of its default argument expressions. 12935 ExprResult 12936 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12937 CXXConstructorDecl *Constructor, 12938 bool Elidable, 12939 MultiExprArg ExprArgs, 12940 bool HadMultipleCandidates, 12941 bool IsListInitialization, 12942 bool IsStdInitListInitialization, 12943 bool RequiresZeroInit, 12944 unsigned ConstructKind, 12945 SourceRange ParenRange) { 12946 assert(declaresSameEntity( 12947 Constructor->getParent(), 12948 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12949 "given constructor for wrong type"); 12950 MarkFunctionReferenced(ConstructLoc, Constructor); 12951 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12952 return ExprError(); 12953 12954 return CXXConstructExpr::Create( 12955 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12956 ExprArgs, HadMultipleCandidates, IsListInitialization, 12957 IsStdInitListInitialization, RequiresZeroInit, 12958 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12959 ParenRange); 12960 } 12961 12962 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12963 assert(Field->hasInClassInitializer()); 12964 12965 // If we already have the in-class initializer nothing needs to be done. 12966 if (Field->getInClassInitializer()) 12967 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12968 12969 // If we might have already tried and failed to instantiate, don't try again. 12970 if (Field->isInvalidDecl()) 12971 return ExprError(); 12972 12973 // Maybe we haven't instantiated the in-class initializer. Go check the 12974 // pattern FieldDecl to see if it has one. 12975 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12976 12977 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12978 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12979 DeclContext::lookup_result Lookup = 12980 ClassPattern->lookup(Field->getDeclName()); 12981 12982 // Lookup can return at most two results: the pattern for the field, or the 12983 // injected class name of the parent record. No other member can have the 12984 // same name as the field. 12985 // In modules mode, lookup can return multiple results (coming from 12986 // different modules). 12987 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12988 "more than two lookup results for field name"); 12989 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12990 if (!Pattern) { 12991 assert(isa<CXXRecordDecl>(Lookup[0]) && 12992 "cannot have other non-field member with same name"); 12993 for (auto L : Lookup) 12994 if (isa<FieldDecl>(L)) { 12995 Pattern = cast<FieldDecl>(L); 12996 break; 12997 } 12998 assert(Pattern && "We must have set the Pattern!"); 12999 } 13000 13001 if (!Pattern->hasInClassInitializer() || 13002 InstantiateInClassInitializer(Loc, Field, Pattern, 13003 getTemplateInstantiationArgs(Field))) { 13004 // Don't diagnose this again. 13005 Field->setInvalidDecl(); 13006 return ExprError(); 13007 } 13008 return CXXDefaultInitExpr::Create(Context, Loc, Field); 13009 } 13010 13011 // DR1351: 13012 // If the brace-or-equal-initializer of a non-static data member 13013 // invokes a defaulted default constructor of its class or of an 13014 // enclosing class in a potentially evaluated subexpression, the 13015 // program is ill-formed. 13016 // 13017 // This resolution is unworkable: the exception specification of the 13018 // default constructor can be needed in an unevaluated context, in 13019 // particular, in the operand of a noexcept-expression, and we can be 13020 // unable to compute an exception specification for an enclosed class. 13021 // 13022 // Any attempt to resolve the exception specification of a defaulted default 13023 // constructor before the initializer is lexically complete will ultimately 13024 // come here at which point we can diagnose it. 13025 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 13026 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 13027 << OutermostClass << Field; 13028 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 13029 // Recover by marking the field invalid, unless we're in a SFINAE context. 13030 if (!isSFINAEContext()) 13031 Field->setInvalidDecl(); 13032 return ExprError(); 13033 } 13034 13035 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 13036 if (VD->isInvalidDecl()) return; 13037 13038 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 13039 if (ClassDecl->isInvalidDecl()) return; 13040 if (ClassDecl->hasIrrelevantDestructor()) return; 13041 if (ClassDecl->isDependentContext()) return; 13042 13043 if (VD->isNoDestroy(getASTContext())) 13044 return; 13045 13046 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13047 MarkFunctionReferenced(VD->getLocation(), Destructor); 13048 CheckDestructorAccess(VD->getLocation(), Destructor, 13049 PDiag(diag::err_access_dtor_var) 13050 << VD->getDeclName() 13051 << VD->getType()); 13052 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 13053 13054 if (Destructor->isTrivial()) return; 13055 if (!VD->hasGlobalStorage()) return; 13056 13057 // Emit warning for non-trivial dtor in global scope (a real global, 13058 // class-static, function-static). 13059 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 13060 13061 // TODO: this should be re-enabled for static locals by !CXAAtExit 13062 if (!VD->isStaticLocal()) 13063 Diag(VD->getLocation(), diag::warn_global_destructor); 13064 } 13065 13066 /// Given a constructor and the set of arguments provided for the 13067 /// constructor, convert the arguments and add any required default arguments 13068 /// to form a proper call to this constructor. 13069 /// 13070 /// \returns true if an error occurred, false otherwise. 13071 bool 13072 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 13073 MultiExprArg ArgsPtr, 13074 SourceLocation Loc, 13075 SmallVectorImpl<Expr*> &ConvertedArgs, 13076 bool AllowExplicit, 13077 bool IsListInitialization) { 13078 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 13079 unsigned NumArgs = ArgsPtr.size(); 13080 Expr **Args = ArgsPtr.data(); 13081 13082 const FunctionProtoType *Proto 13083 = Constructor->getType()->getAs<FunctionProtoType>(); 13084 assert(Proto && "Constructor without a prototype?"); 13085 unsigned NumParams = Proto->getNumParams(); 13086 13087 // If too few arguments are available, we'll fill in the rest with defaults. 13088 if (NumArgs < NumParams) 13089 ConvertedArgs.reserve(NumParams); 13090 else 13091 ConvertedArgs.reserve(NumArgs); 13092 13093 VariadicCallType CallType = 13094 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 13095 SmallVector<Expr *, 8> AllArgs; 13096 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 13097 Proto, 0, 13098 llvm::makeArrayRef(Args, NumArgs), 13099 AllArgs, 13100 CallType, AllowExplicit, 13101 IsListInitialization); 13102 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 13103 13104 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 13105 13106 CheckConstructorCall(Constructor, 13107 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 13108 Proto, Loc); 13109 13110 return Invalid; 13111 } 13112 13113 static inline bool 13114 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 13115 const FunctionDecl *FnDecl) { 13116 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 13117 if (isa<NamespaceDecl>(DC)) { 13118 return SemaRef.Diag(FnDecl->getLocation(), 13119 diag::err_operator_new_delete_declared_in_namespace) 13120 << FnDecl->getDeclName(); 13121 } 13122 13123 if (isa<TranslationUnitDecl>(DC) && 13124 FnDecl->getStorageClass() == SC_Static) { 13125 return SemaRef.Diag(FnDecl->getLocation(), 13126 diag::err_operator_new_delete_declared_static) 13127 << FnDecl->getDeclName(); 13128 } 13129 13130 return false; 13131 } 13132 13133 static QualType 13134 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 13135 QualType QTy = PtrTy->getPointeeType(); 13136 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 13137 return SemaRef.Context.getPointerType(QTy); 13138 } 13139 13140 static inline bool 13141 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13142 CanQualType ExpectedResultType, 13143 CanQualType ExpectedFirstParamType, 13144 unsigned DependentParamTypeDiag, 13145 unsigned InvalidParamTypeDiag) { 13146 QualType ResultType = 13147 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13148 13149 // Check that the result type is not dependent. 13150 if (ResultType->isDependentType()) 13151 return SemaRef.Diag(FnDecl->getLocation(), 13152 diag::err_operator_new_delete_dependent_result_type) 13153 << FnDecl->getDeclName() << ExpectedResultType; 13154 13155 // OpenCL C++: the operator is valid on any address space. 13156 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13157 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13158 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13159 } 13160 } 13161 13162 // Check that the result type is what we expect. 13163 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13164 return SemaRef.Diag(FnDecl->getLocation(), 13165 diag::err_operator_new_delete_invalid_result_type) 13166 << FnDecl->getDeclName() << ExpectedResultType; 13167 13168 // A function template must have at least 2 parameters. 13169 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13170 return SemaRef.Diag(FnDecl->getLocation(), 13171 diag::err_operator_new_delete_template_too_few_parameters) 13172 << FnDecl->getDeclName(); 13173 13174 // The function decl must have at least 1 parameter. 13175 if (FnDecl->getNumParams() == 0) 13176 return SemaRef.Diag(FnDecl->getLocation(), 13177 diag::err_operator_new_delete_too_few_parameters) 13178 << FnDecl->getDeclName(); 13179 13180 // Check the first parameter type is not dependent. 13181 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13182 if (FirstParamType->isDependentType()) 13183 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13184 << FnDecl->getDeclName() << ExpectedFirstParamType; 13185 13186 // Check that the first parameter type is what we expect. 13187 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13188 // OpenCL C++: the operator is valid on any address space. 13189 if (auto *PtrTy = 13190 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13191 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13192 } 13193 } 13194 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13195 ExpectedFirstParamType) 13196 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13197 << FnDecl->getDeclName() << ExpectedFirstParamType; 13198 13199 return false; 13200 } 13201 13202 static bool 13203 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13204 // C++ [basic.stc.dynamic.allocation]p1: 13205 // A program is ill-formed if an allocation function is declared in a 13206 // namespace scope other than global scope or declared static in global 13207 // scope. 13208 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13209 return true; 13210 13211 CanQualType SizeTy = 13212 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13213 13214 // C++ [basic.stc.dynamic.allocation]p1: 13215 // The return type shall be void*. The first parameter shall have type 13216 // std::size_t. 13217 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13218 SizeTy, 13219 diag::err_operator_new_dependent_param_type, 13220 diag::err_operator_new_param_type)) 13221 return true; 13222 13223 // C++ [basic.stc.dynamic.allocation]p1: 13224 // The first parameter shall not have an associated default argument. 13225 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13226 return SemaRef.Diag(FnDecl->getLocation(), 13227 diag::err_operator_new_default_arg) 13228 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13229 13230 return false; 13231 } 13232 13233 static bool 13234 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13235 // C++ [basic.stc.dynamic.deallocation]p1: 13236 // A program is ill-formed if deallocation functions are declared in a 13237 // namespace scope other than global scope or declared static in global 13238 // scope. 13239 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13240 return true; 13241 13242 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13243 13244 // C++ P0722: 13245 // Within a class C, the first parameter of a destroying operator delete 13246 // shall be of type C *. The first parameter of any other deallocation 13247 // function shall be of type void *. 13248 CanQualType ExpectedFirstParamType = 13249 MD && MD->isDestroyingOperatorDelete() 13250 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13251 SemaRef.Context.getRecordType(MD->getParent()))) 13252 : SemaRef.Context.VoidPtrTy; 13253 13254 // C++ [basic.stc.dynamic.deallocation]p2: 13255 // Each deallocation function shall return void 13256 if (CheckOperatorNewDeleteTypes( 13257 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13258 diag::err_operator_delete_dependent_param_type, 13259 diag::err_operator_delete_param_type)) 13260 return true; 13261 13262 // C++ P0722: 13263 // A destroying operator delete shall be a usual deallocation function. 13264 if (MD && !MD->getParent()->isDependentContext() && 13265 MD->isDestroyingOperatorDelete() && 13266 !SemaRef.isUsualDeallocationFunction(MD)) { 13267 SemaRef.Diag(MD->getLocation(), 13268 diag::err_destroying_operator_delete_not_usual); 13269 return true; 13270 } 13271 13272 return false; 13273 } 13274 13275 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13276 /// of this overloaded operator is well-formed. If so, returns false; 13277 /// otherwise, emits appropriate diagnostics and returns true. 13278 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13279 assert(FnDecl && FnDecl->isOverloadedOperator() && 13280 "Expected an overloaded operator declaration"); 13281 13282 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13283 13284 // C++ [over.oper]p5: 13285 // The allocation and deallocation functions, operator new, 13286 // operator new[], operator delete and operator delete[], are 13287 // described completely in 3.7.3. The attributes and restrictions 13288 // found in the rest of this subclause do not apply to them unless 13289 // explicitly stated in 3.7.3. 13290 if (Op == OO_Delete || Op == OO_Array_Delete) 13291 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13292 13293 if (Op == OO_New || Op == OO_Array_New) 13294 return CheckOperatorNewDeclaration(*this, FnDecl); 13295 13296 // C++ [over.oper]p6: 13297 // An operator function shall either be a non-static member 13298 // function or be a non-member function and have at least one 13299 // parameter whose type is a class, a reference to a class, an 13300 // enumeration, or a reference to an enumeration. 13301 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13302 if (MethodDecl->isStatic()) 13303 return Diag(FnDecl->getLocation(), 13304 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13305 } else { 13306 bool ClassOrEnumParam = false; 13307 for (auto Param : FnDecl->parameters()) { 13308 QualType ParamType = Param->getType().getNonReferenceType(); 13309 if (ParamType->isDependentType() || ParamType->isRecordType() || 13310 ParamType->isEnumeralType()) { 13311 ClassOrEnumParam = true; 13312 break; 13313 } 13314 } 13315 13316 if (!ClassOrEnumParam) 13317 return Diag(FnDecl->getLocation(), 13318 diag::err_operator_overload_needs_class_or_enum) 13319 << FnDecl->getDeclName(); 13320 } 13321 13322 // C++ [over.oper]p8: 13323 // An operator function cannot have default arguments (8.3.6), 13324 // except where explicitly stated below. 13325 // 13326 // Only the function-call operator allows default arguments 13327 // (C++ [over.call]p1). 13328 if (Op != OO_Call) { 13329 for (auto Param : FnDecl->parameters()) { 13330 if (Param->hasDefaultArg()) 13331 return Diag(Param->getLocation(), 13332 diag::err_operator_overload_default_arg) 13333 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13334 } 13335 } 13336 13337 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13338 { false, false, false } 13339 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13340 , { Unary, Binary, MemberOnly } 13341 #include "clang/Basic/OperatorKinds.def" 13342 }; 13343 13344 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13345 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13346 bool MustBeMemberOperator = OperatorUses[Op][2]; 13347 13348 // C++ [over.oper]p8: 13349 // [...] Operator functions cannot have more or fewer parameters 13350 // than the number required for the corresponding operator, as 13351 // described in the rest of this subclause. 13352 unsigned NumParams = FnDecl->getNumParams() 13353 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13354 if (Op != OO_Call && 13355 ((NumParams == 1 && !CanBeUnaryOperator) || 13356 (NumParams == 2 && !CanBeBinaryOperator) || 13357 (NumParams < 1) || (NumParams > 2))) { 13358 // We have the wrong number of parameters. 13359 unsigned ErrorKind; 13360 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13361 ErrorKind = 2; // 2 -> unary or binary. 13362 } else if (CanBeUnaryOperator) { 13363 ErrorKind = 0; // 0 -> unary 13364 } else { 13365 assert(CanBeBinaryOperator && 13366 "All non-call overloaded operators are unary or binary!"); 13367 ErrorKind = 1; // 1 -> binary 13368 } 13369 13370 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13371 << FnDecl->getDeclName() << NumParams << ErrorKind; 13372 } 13373 13374 // Overloaded operators other than operator() cannot be variadic. 13375 if (Op != OO_Call && 13376 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13377 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13378 << FnDecl->getDeclName(); 13379 } 13380 13381 // Some operators must be non-static member functions. 13382 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13383 return Diag(FnDecl->getLocation(), 13384 diag::err_operator_overload_must_be_member) 13385 << FnDecl->getDeclName(); 13386 } 13387 13388 // C++ [over.inc]p1: 13389 // The user-defined function called operator++ implements the 13390 // prefix and postfix ++ operator. If this function is a member 13391 // function with no parameters, or a non-member function with one 13392 // parameter of class or enumeration type, it defines the prefix 13393 // increment operator ++ for objects of that type. If the function 13394 // is a member function with one parameter (which shall be of type 13395 // int) or a non-member function with two parameters (the second 13396 // of which shall be of type int), it defines the postfix 13397 // increment operator ++ for objects of that type. 13398 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13399 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13400 QualType ParamType = LastParam->getType(); 13401 13402 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13403 !ParamType->isDependentType()) 13404 return Diag(LastParam->getLocation(), 13405 diag::err_operator_overload_post_incdec_must_be_int) 13406 << LastParam->getType() << (Op == OO_MinusMinus); 13407 } 13408 13409 return false; 13410 } 13411 13412 static bool 13413 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13414 FunctionTemplateDecl *TpDecl) { 13415 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13416 13417 // Must have one or two template parameters. 13418 if (TemplateParams->size() == 1) { 13419 NonTypeTemplateParmDecl *PmDecl = 13420 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13421 13422 // The template parameter must be a char parameter pack. 13423 if (PmDecl && PmDecl->isTemplateParameterPack() && 13424 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13425 return false; 13426 13427 } else if (TemplateParams->size() == 2) { 13428 TemplateTypeParmDecl *PmType = 13429 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13430 NonTypeTemplateParmDecl *PmArgs = 13431 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13432 13433 // The second template parameter must be a parameter pack with the 13434 // first template parameter as its type. 13435 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13436 PmArgs->isTemplateParameterPack()) { 13437 const TemplateTypeParmType *TArgs = 13438 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13439 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13440 TArgs->getIndex() == PmType->getIndex()) { 13441 if (!SemaRef.inTemplateInstantiation()) 13442 SemaRef.Diag(TpDecl->getLocation(), 13443 diag::ext_string_literal_operator_template); 13444 return false; 13445 } 13446 } 13447 } 13448 13449 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13450 diag::err_literal_operator_template) 13451 << TpDecl->getTemplateParameters()->getSourceRange(); 13452 return true; 13453 } 13454 13455 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13456 /// of this literal operator function is well-formed. If so, returns 13457 /// false; otherwise, emits appropriate diagnostics and returns true. 13458 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13459 if (isa<CXXMethodDecl>(FnDecl)) { 13460 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13461 << FnDecl->getDeclName(); 13462 return true; 13463 } 13464 13465 if (FnDecl->isExternC()) { 13466 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13467 if (const LinkageSpecDecl *LSD = 13468 FnDecl->getDeclContext()->getExternCContext()) 13469 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13470 return true; 13471 } 13472 13473 // This might be the definition of a literal operator template. 13474 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13475 13476 // This might be a specialization of a literal operator template. 13477 if (!TpDecl) 13478 TpDecl = FnDecl->getPrimaryTemplate(); 13479 13480 // template <char...> type operator "" name() and 13481 // template <class T, T...> type operator "" name() are the only valid 13482 // template signatures, and the only valid signatures with no parameters. 13483 if (TpDecl) { 13484 if (FnDecl->param_size() != 0) { 13485 Diag(FnDecl->getLocation(), 13486 diag::err_literal_operator_template_with_params); 13487 return true; 13488 } 13489 13490 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13491 return true; 13492 13493 } else if (FnDecl->param_size() == 1) { 13494 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13495 13496 QualType ParamType = Param->getType().getUnqualifiedType(); 13497 13498 // Only unsigned long long int, long double, any character type, and const 13499 // char * are allowed as the only parameters. 13500 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13501 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13502 Context.hasSameType(ParamType, Context.CharTy) || 13503 Context.hasSameType(ParamType, Context.WideCharTy) || 13504 Context.hasSameType(ParamType, Context.Char8Ty) || 13505 Context.hasSameType(ParamType, Context.Char16Ty) || 13506 Context.hasSameType(ParamType, Context.Char32Ty)) { 13507 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13508 QualType InnerType = Ptr->getPointeeType(); 13509 13510 // Pointer parameter must be a const char *. 13511 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13512 Context.CharTy) && 13513 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13514 Diag(Param->getSourceRange().getBegin(), 13515 diag::err_literal_operator_param) 13516 << ParamType << "'const char *'" << Param->getSourceRange(); 13517 return true; 13518 } 13519 13520 } else if (ParamType->isRealFloatingType()) { 13521 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13522 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13523 return true; 13524 13525 } else if (ParamType->isIntegerType()) { 13526 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13527 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13528 return true; 13529 13530 } else { 13531 Diag(Param->getSourceRange().getBegin(), 13532 diag::err_literal_operator_invalid_param) 13533 << ParamType << Param->getSourceRange(); 13534 return true; 13535 } 13536 13537 } else if (FnDecl->param_size() == 2) { 13538 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13539 13540 // First, verify that the first parameter is correct. 13541 13542 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13543 13544 // Two parameter function must have a pointer to const as a 13545 // first parameter; let's strip those qualifiers. 13546 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13547 13548 if (!PT) { 13549 Diag((*Param)->getSourceRange().getBegin(), 13550 diag::err_literal_operator_param) 13551 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13552 return true; 13553 } 13554 13555 QualType PointeeType = PT->getPointeeType(); 13556 // First parameter must be const 13557 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13558 Diag((*Param)->getSourceRange().getBegin(), 13559 diag::err_literal_operator_param) 13560 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13561 return true; 13562 } 13563 13564 QualType InnerType = PointeeType.getUnqualifiedType(); 13565 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13566 // const char32_t* are allowed as the first parameter to a two-parameter 13567 // function 13568 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13569 Context.hasSameType(InnerType, Context.WideCharTy) || 13570 Context.hasSameType(InnerType, Context.Char8Ty) || 13571 Context.hasSameType(InnerType, Context.Char16Ty) || 13572 Context.hasSameType(InnerType, Context.Char32Ty))) { 13573 Diag((*Param)->getSourceRange().getBegin(), 13574 diag::err_literal_operator_param) 13575 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13576 return true; 13577 } 13578 13579 // Move on to the second and final parameter. 13580 ++Param; 13581 13582 // The second parameter must be a std::size_t. 13583 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13584 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13585 Diag((*Param)->getSourceRange().getBegin(), 13586 diag::err_literal_operator_param) 13587 << SecondParamType << Context.getSizeType() 13588 << (*Param)->getSourceRange(); 13589 return true; 13590 } 13591 } else { 13592 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13593 return true; 13594 } 13595 13596 // Parameters are good. 13597 13598 // A parameter-declaration-clause containing a default argument is not 13599 // equivalent to any of the permitted forms. 13600 for (auto Param : FnDecl->parameters()) { 13601 if (Param->hasDefaultArg()) { 13602 Diag(Param->getDefaultArgRange().getBegin(), 13603 diag::err_literal_operator_default_argument) 13604 << Param->getDefaultArgRange(); 13605 break; 13606 } 13607 } 13608 13609 StringRef LiteralName 13610 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13611 if (LiteralName[0] != '_' && 13612 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13613 // C++11 [usrlit.suffix]p1: 13614 // Literal suffix identifiers that do not start with an underscore 13615 // are reserved for future standardization. 13616 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13617 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13618 } 13619 13620 return false; 13621 } 13622 13623 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13624 /// linkage specification, including the language and (if present) 13625 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13626 /// language string literal. LBraceLoc, if valid, provides the location of 13627 /// the '{' brace. Otherwise, this linkage specification does not 13628 /// have any braces. 13629 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13630 Expr *LangStr, 13631 SourceLocation LBraceLoc) { 13632 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13633 if (!Lit->isAscii()) { 13634 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13635 << LangStr->getSourceRange(); 13636 return nullptr; 13637 } 13638 13639 StringRef Lang = Lit->getString(); 13640 LinkageSpecDecl::LanguageIDs Language; 13641 if (Lang == "C") 13642 Language = LinkageSpecDecl::lang_c; 13643 else if (Lang == "C++") 13644 Language = LinkageSpecDecl::lang_cxx; 13645 else { 13646 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13647 << LangStr->getSourceRange(); 13648 return nullptr; 13649 } 13650 13651 // FIXME: Add all the various semantics of linkage specifications 13652 13653 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13654 LangStr->getExprLoc(), Language, 13655 LBraceLoc.isValid()); 13656 CurContext->addDecl(D); 13657 PushDeclContext(S, D); 13658 return D; 13659 } 13660 13661 /// ActOnFinishLinkageSpecification - Complete the definition of 13662 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13663 /// valid, it's the position of the closing '}' brace in a linkage 13664 /// specification that uses braces. 13665 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13666 Decl *LinkageSpec, 13667 SourceLocation RBraceLoc) { 13668 if (RBraceLoc.isValid()) { 13669 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13670 LSDecl->setRBraceLoc(RBraceLoc); 13671 } 13672 PopDeclContext(); 13673 return LinkageSpec; 13674 } 13675 13676 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13677 const ParsedAttributesView &AttrList, 13678 SourceLocation SemiLoc) { 13679 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13680 // Attribute declarations appertain to empty declaration so we handle 13681 // them here. 13682 ProcessDeclAttributeList(S, ED, AttrList); 13683 13684 CurContext->addDecl(ED); 13685 return ED; 13686 } 13687 13688 /// Perform semantic analysis for the variable declaration that 13689 /// occurs within a C++ catch clause, returning the newly-created 13690 /// variable. 13691 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13692 TypeSourceInfo *TInfo, 13693 SourceLocation StartLoc, 13694 SourceLocation Loc, 13695 IdentifierInfo *Name) { 13696 bool Invalid = false; 13697 QualType ExDeclType = TInfo->getType(); 13698 13699 // Arrays and functions decay. 13700 if (ExDeclType->isArrayType()) 13701 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13702 else if (ExDeclType->isFunctionType()) 13703 ExDeclType = Context.getPointerType(ExDeclType); 13704 13705 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13706 // The exception-declaration shall not denote a pointer or reference to an 13707 // incomplete type, other than [cv] void*. 13708 // N2844 forbids rvalue references. 13709 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13710 Diag(Loc, diag::err_catch_rvalue_ref); 13711 Invalid = true; 13712 } 13713 13714 if (ExDeclType->isVariablyModifiedType()) { 13715 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13716 Invalid = true; 13717 } 13718 13719 QualType BaseType = ExDeclType; 13720 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13721 unsigned DK = diag::err_catch_incomplete; 13722 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13723 BaseType = Ptr->getPointeeType(); 13724 Mode = 1; 13725 DK = diag::err_catch_incomplete_ptr; 13726 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13727 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13728 BaseType = Ref->getPointeeType(); 13729 Mode = 2; 13730 DK = diag::err_catch_incomplete_ref; 13731 } 13732 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13733 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13734 Invalid = true; 13735 13736 if (!Invalid && !ExDeclType->isDependentType() && 13737 RequireNonAbstractType(Loc, ExDeclType, 13738 diag::err_abstract_type_in_decl, 13739 AbstractVariableType)) 13740 Invalid = true; 13741 13742 // Only the non-fragile NeXT runtime currently supports C++ catches 13743 // of ObjC types, and no runtime supports catching ObjC types by value. 13744 if (!Invalid && getLangOpts().ObjC) { 13745 QualType T = ExDeclType; 13746 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13747 T = RT->getPointeeType(); 13748 13749 if (T->isObjCObjectType()) { 13750 Diag(Loc, diag::err_objc_object_catch); 13751 Invalid = true; 13752 } else if (T->isObjCObjectPointerType()) { 13753 // FIXME: should this be a test for macosx-fragile specifically? 13754 if (getLangOpts().ObjCRuntime.isFragile()) 13755 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13756 } 13757 } 13758 13759 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13760 ExDeclType, TInfo, SC_None); 13761 ExDecl->setExceptionVariable(true); 13762 13763 // In ARC, infer 'retaining' for variables of retainable type. 13764 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13765 Invalid = true; 13766 13767 if (!Invalid && !ExDeclType->isDependentType()) { 13768 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13769 // Insulate this from anything else we might currently be parsing. 13770 EnterExpressionEvaluationContext scope( 13771 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13772 13773 // C++ [except.handle]p16: 13774 // The object declared in an exception-declaration or, if the 13775 // exception-declaration does not specify a name, a temporary (12.2) is 13776 // copy-initialized (8.5) from the exception object. [...] 13777 // The object is destroyed when the handler exits, after the destruction 13778 // of any automatic objects initialized within the handler. 13779 // 13780 // We just pretend to initialize the object with itself, then make sure 13781 // it can be destroyed later. 13782 QualType initType = Context.getExceptionObjectType(ExDeclType); 13783 13784 InitializedEntity entity = 13785 InitializedEntity::InitializeVariable(ExDecl); 13786 InitializationKind initKind = 13787 InitializationKind::CreateCopy(Loc, SourceLocation()); 13788 13789 Expr *opaqueValue = 13790 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13791 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13792 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13793 if (result.isInvalid()) 13794 Invalid = true; 13795 else { 13796 // If the constructor used was non-trivial, set this as the 13797 // "initializer". 13798 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13799 if (!construct->getConstructor()->isTrivial()) { 13800 Expr *init = MaybeCreateExprWithCleanups(construct); 13801 ExDecl->setInit(init); 13802 } 13803 13804 // And make sure it's destructable. 13805 FinalizeVarWithDestructor(ExDecl, recordType); 13806 } 13807 } 13808 } 13809 13810 if (Invalid) 13811 ExDecl->setInvalidDecl(); 13812 13813 return ExDecl; 13814 } 13815 13816 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13817 /// handler. 13818 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13819 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13820 bool Invalid = D.isInvalidType(); 13821 13822 // Check for unexpanded parameter packs. 13823 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13824 UPPC_ExceptionType)) { 13825 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13826 D.getIdentifierLoc()); 13827 Invalid = true; 13828 } 13829 13830 IdentifierInfo *II = D.getIdentifier(); 13831 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13832 LookupOrdinaryName, 13833 ForVisibleRedeclaration)) { 13834 // The scope should be freshly made just for us. There is just no way 13835 // it contains any previous declaration, except for function parameters in 13836 // a function-try-block's catch statement. 13837 assert(!S->isDeclScope(PrevDecl)); 13838 if (isDeclInScope(PrevDecl, CurContext, S)) { 13839 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13840 << D.getIdentifier(); 13841 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13842 Invalid = true; 13843 } else if (PrevDecl->isTemplateParameter()) 13844 // Maybe we will complain about the shadowed template parameter. 13845 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13846 } 13847 13848 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13849 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13850 << D.getCXXScopeSpec().getRange(); 13851 Invalid = true; 13852 } 13853 13854 VarDecl *ExDecl = BuildExceptionDeclaration( 13855 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 13856 if (Invalid) 13857 ExDecl->setInvalidDecl(); 13858 13859 // Add the exception declaration into this scope. 13860 if (II) 13861 PushOnScopeChains(ExDecl, S); 13862 else 13863 CurContext->addDecl(ExDecl); 13864 13865 ProcessDeclAttributes(S, ExDecl, D); 13866 return ExDecl; 13867 } 13868 13869 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13870 Expr *AssertExpr, 13871 Expr *AssertMessageExpr, 13872 SourceLocation RParenLoc) { 13873 StringLiteral *AssertMessage = 13874 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13875 13876 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13877 return nullptr; 13878 13879 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13880 AssertMessage, RParenLoc, false); 13881 } 13882 13883 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13884 Expr *AssertExpr, 13885 StringLiteral *AssertMessage, 13886 SourceLocation RParenLoc, 13887 bool Failed) { 13888 assert(AssertExpr != nullptr && "Expected non-null condition"); 13889 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13890 !Failed) { 13891 // In a static_assert-declaration, the constant-expression shall be a 13892 // constant expression that can be contextually converted to bool. 13893 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13894 if (Converted.isInvalid()) 13895 Failed = true; 13896 else 13897 Converted = ConstantExpr::Create(Context, Converted.get()); 13898 13899 llvm::APSInt Cond; 13900 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13901 diag::err_static_assert_expression_is_not_constant, 13902 /*AllowFold=*/false).isInvalid()) 13903 Failed = true; 13904 13905 if (!Failed && !Cond) { 13906 SmallString<256> MsgBuffer; 13907 llvm::raw_svector_ostream Msg(MsgBuffer); 13908 if (AssertMessage) 13909 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13910 13911 Expr *InnerCond = nullptr; 13912 std::string InnerCondDescription; 13913 std::tie(InnerCond, InnerCondDescription) = 13914 findFailedBooleanCondition(Converted.get()); 13915 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 13916 && !isa<IntegerLiteral>(InnerCond)) { 13917 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13918 << InnerCondDescription << !AssertMessage 13919 << Msg.str() << InnerCond->getSourceRange(); 13920 } else { 13921 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13922 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13923 } 13924 Failed = true; 13925 } 13926 } 13927 13928 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13929 /*DiscardedValue*/false, 13930 /*IsConstexpr*/true); 13931 if (FullAssertExpr.isInvalid()) 13932 Failed = true; 13933 else 13934 AssertExpr = FullAssertExpr.get(); 13935 13936 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13937 AssertExpr, AssertMessage, RParenLoc, 13938 Failed); 13939 13940 CurContext->addDecl(Decl); 13941 return Decl; 13942 } 13943 13944 /// Perform semantic analysis of the given friend type declaration. 13945 /// 13946 /// \returns A friend declaration that. 13947 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13948 SourceLocation FriendLoc, 13949 TypeSourceInfo *TSInfo) { 13950 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13951 13952 QualType T = TSInfo->getType(); 13953 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13954 13955 // C++03 [class.friend]p2: 13956 // An elaborated-type-specifier shall be used in a friend declaration 13957 // for a class.* 13958 // 13959 // * The class-key of the elaborated-type-specifier is required. 13960 if (!CodeSynthesisContexts.empty()) { 13961 // Do not complain about the form of friend template types during any kind 13962 // of code synthesis. For template instantiation, we will have complained 13963 // when the template was defined. 13964 } else { 13965 if (!T->isElaboratedTypeSpecifier()) { 13966 // If we evaluated the type to a record type, suggest putting 13967 // a tag in front. 13968 if (const RecordType *RT = T->getAs<RecordType>()) { 13969 RecordDecl *RD = RT->getDecl(); 13970 13971 SmallString<16> InsertionText(" "); 13972 InsertionText += RD->getKindName(); 13973 13974 Diag(TypeRange.getBegin(), 13975 getLangOpts().CPlusPlus11 ? 13976 diag::warn_cxx98_compat_unelaborated_friend_type : 13977 diag::ext_unelaborated_friend_type) 13978 << (unsigned) RD->getTagKind() 13979 << T 13980 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13981 InsertionText); 13982 } else { 13983 Diag(FriendLoc, 13984 getLangOpts().CPlusPlus11 ? 13985 diag::warn_cxx98_compat_nonclass_type_friend : 13986 diag::ext_nonclass_type_friend) 13987 << T 13988 << TypeRange; 13989 } 13990 } else if (T->getAs<EnumType>()) { 13991 Diag(FriendLoc, 13992 getLangOpts().CPlusPlus11 ? 13993 diag::warn_cxx98_compat_enum_friend : 13994 diag::ext_enum_friend) 13995 << T 13996 << TypeRange; 13997 } 13998 13999 // C++11 [class.friend]p3: 14000 // A friend declaration that does not declare a function shall have one 14001 // of the following forms: 14002 // friend elaborated-type-specifier ; 14003 // friend simple-type-specifier ; 14004 // friend typename-specifier ; 14005 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 14006 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 14007 } 14008 14009 // If the type specifier in a friend declaration designates a (possibly 14010 // cv-qualified) class type, that class is declared as a friend; otherwise, 14011 // the friend declaration is ignored. 14012 return FriendDecl::Create(Context, CurContext, 14013 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 14014 FriendLoc); 14015 } 14016 14017 /// Handle a friend tag declaration where the scope specifier was 14018 /// templated. 14019 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 14020 unsigned TagSpec, SourceLocation TagLoc, 14021 CXXScopeSpec &SS, IdentifierInfo *Name, 14022 SourceLocation NameLoc, 14023 const ParsedAttributesView &Attr, 14024 MultiTemplateParamsArg TempParamLists) { 14025 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14026 14027 bool IsMemberSpecialization = false; 14028 bool Invalid = false; 14029 14030 if (TemplateParameterList *TemplateParams = 14031 MatchTemplateParametersToScopeSpecifier( 14032 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 14033 IsMemberSpecialization, Invalid)) { 14034 if (TemplateParams->size() > 0) { 14035 // This is a declaration of a class template. 14036 if (Invalid) 14037 return nullptr; 14038 14039 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 14040 NameLoc, Attr, TemplateParams, AS_public, 14041 /*ModulePrivateLoc=*/SourceLocation(), 14042 FriendLoc, TempParamLists.size() - 1, 14043 TempParamLists.data()).get(); 14044 } else { 14045 // The "template<>" header is extraneous. 14046 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14047 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14048 IsMemberSpecialization = true; 14049 } 14050 } 14051 14052 if (Invalid) return nullptr; 14053 14054 bool isAllExplicitSpecializations = true; 14055 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 14056 if (TempParamLists[I]->size()) { 14057 isAllExplicitSpecializations = false; 14058 break; 14059 } 14060 } 14061 14062 // FIXME: don't ignore attributes. 14063 14064 // If it's explicit specializations all the way down, just forget 14065 // about the template header and build an appropriate non-templated 14066 // friend. TODO: for source fidelity, remember the headers. 14067 if (isAllExplicitSpecializations) { 14068 if (SS.isEmpty()) { 14069 bool Owned = false; 14070 bool IsDependent = false; 14071 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 14072 Attr, AS_public, 14073 /*ModulePrivateLoc=*/SourceLocation(), 14074 MultiTemplateParamsArg(), Owned, IsDependent, 14075 /*ScopedEnumKWLoc=*/SourceLocation(), 14076 /*ScopedEnumUsesClassTag=*/false, 14077 /*UnderlyingType=*/TypeResult(), 14078 /*IsTypeSpecifier=*/false, 14079 /*IsTemplateParamOrArg=*/false); 14080 } 14081 14082 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 14083 ElaboratedTypeKeyword Keyword 14084 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14085 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 14086 *Name, NameLoc); 14087 if (T.isNull()) 14088 return nullptr; 14089 14090 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14091 if (isa<DependentNameType>(T)) { 14092 DependentNameTypeLoc TL = 14093 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14094 TL.setElaboratedKeywordLoc(TagLoc); 14095 TL.setQualifierLoc(QualifierLoc); 14096 TL.setNameLoc(NameLoc); 14097 } else { 14098 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 14099 TL.setElaboratedKeywordLoc(TagLoc); 14100 TL.setQualifierLoc(QualifierLoc); 14101 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 14102 } 14103 14104 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14105 TSI, FriendLoc, TempParamLists); 14106 Friend->setAccess(AS_public); 14107 CurContext->addDecl(Friend); 14108 return Friend; 14109 } 14110 14111 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 14112 14113 14114 14115 // Handle the case of a templated-scope friend class. e.g. 14116 // template <class T> class A<T>::B; 14117 // FIXME: we don't support these right now. 14118 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 14119 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 14120 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14121 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 14122 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14123 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14124 TL.setElaboratedKeywordLoc(TagLoc); 14125 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 14126 TL.setNameLoc(NameLoc); 14127 14128 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14129 TSI, FriendLoc, TempParamLists); 14130 Friend->setAccess(AS_public); 14131 Friend->setUnsupportedFriend(true); 14132 CurContext->addDecl(Friend); 14133 return Friend; 14134 } 14135 14136 /// Handle a friend type declaration. This works in tandem with 14137 /// ActOnTag. 14138 /// 14139 /// Notes on friend class templates: 14140 /// 14141 /// We generally treat friend class declarations as if they were 14142 /// declaring a class. So, for example, the elaborated type specifier 14143 /// in a friend declaration is required to obey the restrictions of a 14144 /// class-head (i.e. no typedefs in the scope chain), template 14145 /// parameters are required to match up with simple template-ids, &c. 14146 /// However, unlike when declaring a template specialization, it's 14147 /// okay to refer to a template specialization without an empty 14148 /// template parameter declaration, e.g. 14149 /// friend class A<T>::B<unsigned>; 14150 /// We permit this as a special case; if there are any template 14151 /// parameters present at all, require proper matching, i.e. 14152 /// template <> template \<class T> friend class A<int>::B; 14153 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14154 MultiTemplateParamsArg TempParams) { 14155 SourceLocation Loc = DS.getBeginLoc(); 14156 14157 assert(DS.isFriendSpecified()); 14158 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14159 14160 // C++ [class.friend]p3: 14161 // A friend declaration that does not declare a function shall have one of 14162 // the following forms: 14163 // friend elaborated-type-specifier ; 14164 // friend simple-type-specifier ; 14165 // friend typename-specifier ; 14166 // 14167 // Any declaration with a type qualifier does not have that form. (It's 14168 // legal to specify a qualified type as a friend, you just can't write the 14169 // keywords.) 14170 if (DS.getTypeQualifiers()) { 14171 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 14172 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 14173 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 14174 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 14175 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 14176 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 14177 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 14178 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 14179 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 14180 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 14181 } 14182 14183 // Try to convert the decl specifier to a type. This works for 14184 // friend templates because ActOnTag never produces a ClassTemplateDecl 14185 // for a TUK_Friend. 14186 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14187 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14188 QualType T = TSI->getType(); 14189 if (TheDeclarator.isInvalidType()) 14190 return nullptr; 14191 14192 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14193 return nullptr; 14194 14195 // This is definitely an error in C++98. It's probably meant to 14196 // be forbidden in C++0x, too, but the specification is just 14197 // poorly written. 14198 // 14199 // The problem is with declarations like the following: 14200 // template <T> friend A<T>::foo; 14201 // where deciding whether a class C is a friend or not now hinges 14202 // on whether there exists an instantiation of A that causes 14203 // 'foo' to equal C. There are restrictions on class-heads 14204 // (which we declare (by fiat) elaborated friend declarations to 14205 // be) that makes this tractable. 14206 // 14207 // FIXME: handle "template <> friend class A<T>;", which 14208 // is possibly well-formed? Who even knows? 14209 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14210 Diag(Loc, diag::err_tagless_friend_type_template) 14211 << DS.getSourceRange(); 14212 return nullptr; 14213 } 14214 14215 // C++98 [class.friend]p1: A friend of a class is a function 14216 // or class that is not a member of the class . . . 14217 // This is fixed in DR77, which just barely didn't make the C++03 14218 // deadline. It's also a very silly restriction that seriously 14219 // affects inner classes and which nobody else seems to implement; 14220 // thus we never diagnose it, not even in -pedantic. 14221 // 14222 // But note that we could warn about it: it's always useless to 14223 // friend one of your own members (it's not, however, worthless to 14224 // friend a member of an arbitrary specialization of your template). 14225 14226 Decl *D; 14227 if (!TempParams.empty()) 14228 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14229 TempParams, 14230 TSI, 14231 DS.getFriendSpecLoc()); 14232 else 14233 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14234 14235 if (!D) 14236 return nullptr; 14237 14238 D->setAccess(AS_public); 14239 CurContext->addDecl(D); 14240 14241 return D; 14242 } 14243 14244 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14245 MultiTemplateParamsArg TemplateParams) { 14246 const DeclSpec &DS = D.getDeclSpec(); 14247 14248 assert(DS.isFriendSpecified()); 14249 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14250 14251 SourceLocation Loc = D.getIdentifierLoc(); 14252 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14253 14254 // C++ [class.friend]p1 14255 // A friend of a class is a function or class.... 14256 // Note that this sees through typedefs, which is intended. 14257 // It *doesn't* see through dependent types, which is correct 14258 // according to [temp.arg.type]p3: 14259 // If a declaration acquires a function type through a 14260 // type dependent on a template-parameter and this causes 14261 // a declaration that does not use the syntactic form of a 14262 // function declarator to have a function type, the program 14263 // is ill-formed. 14264 if (!TInfo->getType()->isFunctionType()) { 14265 Diag(Loc, diag::err_unexpected_friend); 14266 14267 // It might be worthwhile to try to recover by creating an 14268 // appropriate declaration. 14269 return nullptr; 14270 } 14271 14272 // C++ [namespace.memdef]p3 14273 // - If a friend declaration in a non-local class first declares a 14274 // class or function, the friend class or function is a member 14275 // of the innermost enclosing namespace. 14276 // - The name of the friend is not found by simple name lookup 14277 // until a matching declaration is provided in that namespace 14278 // scope (either before or after the class declaration granting 14279 // friendship). 14280 // - If a friend function is called, its name may be found by the 14281 // name lookup that considers functions from namespaces and 14282 // classes associated with the types of the function arguments. 14283 // - When looking for a prior declaration of a class or a function 14284 // declared as a friend, scopes outside the innermost enclosing 14285 // namespace scope are not considered. 14286 14287 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14288 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14289 assert(NameInfo.getName()); 14290 14291 // Check for unexpanded parameter packs. 14292 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14293 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14294 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14295 return nullptr; 14296 14297 // The context we found the declaration in, or in which we should 14298 // create the declaration. 14299 DeclContext *DC; 14300 Scope *DCScope = S; 14301 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14302 ForExternalRedeclaration); 14303 14304 // There are five cases here. 14305 // - There's no scope specifier and we're in a local class. Only look 14306 // for functions declared in the immediately-enclosing block scope. 14307 // We recover from invalid scope qualifiers as if they just weren't there. 14308 FunctionDecl *FunctionContainingLocalClass = nullptr; 14309 if ((SS.isInvalid() || !SS.isSet()) && 14310 (FunctionContainingLocalClass = 14311 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14312 // C++11 [class.friend]p11: 14313 // If a friend declaration appears in a local class and the name 14314 // specified is an unqualified name, a prior declaration is 14315 // looked up without considering scopes that are outside the 14316 // innermost enclosing non-class scope. For a friend function 14317 // declaration, if there is no prior declaration, the program is 14318 // ill-formed. 14319 14320 // Find the innermost enclosing non-class scope. This is the block 14321 // scope containing the local class definition (or for a nested class, 14322 // the outer local class). 14323 DCScope = S->getFnParent(); 14324 14325 // Look up the function name in the scope. 14326 Previous.clear(LookupLocalFriendName); 14327 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14328 14329 if (!Previous.empty()) { 14330 // All possible previous declarations must have the same context: 14331 // either they were declared at block scope or they are members of 14332 // one of the enclosing local classes. 14333 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14334 } else { 14335 // This is ill-formed, but provide the context that we would have 14336 // declared the function in, if we were permitted to, for error recovery. 14337 DC = FunctionContainingLocalClass; 14338 } 14339 adjustContextForLocalExternDecl(DC); 14340 14341 // C++ [class.friend]p6: 14342 // A function can be defined in a friend declaration of a class if and 14343 // only if the class is a non-local class (9.8), the function name is 14344 // unqualified, and the function has namespace scope. 14345 if (D.isFunctionDefinition()) { 14346 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14347 } 14348 14349 // - There's no scope specifier, in which case we just go to the 14350 // appropriate scope and look for a function or function template 14351 // there as appropriate. 14352 } else if (SS.isInvalid() || !SS.isSet()) { 14353 // C++11 [namespace.memdef]p3: 14354 // If the name in a friend declaration is neither qualified nor 14355 // a template-id and the declaration is a function or an 14356 // elaborated-type-specifier, the lookup to determine whether 14357 // the entity has been previously declared shall not consider 14358 // any scopes outside the innermost enclosing namespace. 14359 bool isTemplateId = 14360 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14361 14362 // Find the appropriate context according to the above. 14363 DC = CurContext; 14364 14365 // Skip class contexts. If someone can cite chapter and verse 14366 // for this behavior, that would be nice --- it's what GCC and 14367 // EDG do, and it seems like a reasonable intent, but the spec 14368 // really only says that checks for unqualified existing 14369 // declarations should stop at the nearest enclosing namespace, 14370 // not that they should only consider the nearest enclosing 14371 // namespace. 14372 while (DC->isRecord()) 14373 DC = DC->getParent(); 14374 14375 DeclContext *LookupDC = DC; 14376 while (LookupDC->isTransparentContext()) 14377 LookupDC = LookupDC->getParent(); 14378 14379 while (true) { 14380 LookupQualifiedName(Previous, LookupDC); 14381 14382 if (!Previous.empty()) { 14383 DC = LookupDC; 14384 break; 14385 } 14386 14387 if (isTemplateId) { 14388 if (isa<TranslationUnitDecl>(LookupDC)) break; 14389 } else { 14390 if (LookupDC->isFileContext()) break; 14391 } 14392 LookupDC = LookupDC->getParent(); 14393 } 14394 14395 DCScope = getScopeForDeclContext(S, DC); 14396 14397 // - There's a non-dependent scope specifier, in which case we 14398 // compute it and do a previous lookup there for a function 14399 // or function template. 14400 } else if (!SS.getScopeRep()->isDependent()) { 14401 DC = computeDeclContext(SS); 14402 if (!DC) return nullptr; 14403 14404 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14405 14406 LookupQualifiedName(Previous, DC); 14407 14408 // C++ [class.friend]p1: A friend of a class is a function or 14409 // class that is not a member of the class . . . 14410 if (DC->Equals(CurContext)) 14411 Diag(DS.getFriendSpecLoc(), 14412 getLangOpts().CPlusPlus11 ? 14413 diag::warn_cxx98_compat_friend_is_member : 14414 diag::err_friend_is_member); 14415 14416 if (D.isFunctionDefinition()) { 14417 // C++ [class.friend]p6: 14418 // A function can be defined in a friend declaration of a class if and 14419 // only if the class is a non-local class (9.8), the function name is 14420 // unqualified, and the function has namespace scope. 14421 // 14422 // FIXME: We should only do this if the scope specifier names the 14423 // innermost enclosing namespace; otherwise the fixit changes the 14424 // meaning of the code. 14425 SemaDiagnosticBuilder DB 14426 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14427 14428 DB << SS.getScopeRep(); 14429 if (DC->isFileContext()) 14430 DB << FixItHint::CreateRemoval(SS.getRange()); 14431 SS.clear(); 14432 } 14433 14434 // - There's a scope specifier that does not match any template 14435 // parameter lists, in which case we use some arbitrary context, 14436 // create a method or method template, and wait for instantiation. 14437 // - There's a scope specifier that does match some template 14438 // parameter lists, which we don't handle right now. 14439 } else { 14440 if (D.isFunctionDefinition()) { 14441 // C++ [class.friend]p6: 14442 // A function can be defined in a friend declaration of a class if and 14443 // only if the class is a non-local class (9.8), the function name is 14444 // unqualified, and the function has namespace scope. 14445 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14446 << SS.getScopeRep(); 14447 } 14448 14449 DC = CurContext; 14450 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14451 } 14452 14453 if (!DC->isRecord()) { 14454 int DiagArg = -1; 14455 switch (D.getName().getKind()) { 14456 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14457 case UnqualifiedIdKind::IK_ConstructorName: 14458 DiagArg = 0; 14459 break; 14460 case UnqualifiedIdKind::IK_DestructorName: 14461 DiagArg = 1; 14462 break; 14463 case UnqualifiedIdKind::IK_ConversionFunctionId: 14464 DiagArg = 2; 14465 break; 14466 case UnqualifiedIdKind::IK_DeductionGuideName: 14467 DiagArg = 3; 14468 break; 14469 case UnqualifiedIdKind::IK_Identifier: 14470 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14471 case UnqualifiedIdKind::IK_LiteralOperatorId: 14472 case UnqualifiedIdKind::IK_OperatorFunctionId: 14473 case UnqualifiedIdKind::IK_TemplateId: 14474 break; 14475 } 14476 // This implies that it has to be an operator or function. 14477 if (DiagArg >= 0) { 14478 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14479 return nullptr; 14480 } 14481 } 14482 14483 // FIXME: This is an egregious hack to cope with cases where the scope stack 14484 // does not contain the declaration context, i.e., in an out-of-line 14485 // definition of a class. 14486 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14487 if (!DCScope) { 14488 FakeDCScope.setEntity(DC); 14489 DCScope = &FakeDCScope; 14490 } 14491 14492 bool AddToScope = true; 14493 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14494 TemplateParams, AddToScope); 14495 if (!ND) return nullptr; 14496 14497 assert(ND->getLexicalDeclContext() == CurContext); 14498 14499 // If we performed typo correction, we might have added a scope specifier 14500 // and changed the decl context. 14501 DC = ND->getDeclContext(); 14502 14503 // Add the function declaration to the appropriate lookup tables, 14504 // adjusting the redeclarations list as necessary. We don't 14505 // want to do this yet if the friending class is dependent. 14506 // 14507 // Also update the scope-based lookup if the target context's 14508 // lookup context is in lexical scope. 14509 if (!CurContext->isDependentContext()) { 14510 DC = DC->getRedeclContext(); 14511 DC->makeDeclVisibleInContext(ND); 14512 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14513 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14514 } 14515 14516 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14517 D.getIdentifierLoc(), ND, 14518 DS.getFriendSpecLoc()); 14519 FrD->setAccess(AS_public); 14520 CurContext->addDecl(FrD); 14521 14522 if (ND->isInvalidDecl()) { 14523 FrD->setInvalidDecl(); 14524 } else { 14525 if (DC->isRecord()) CheckFriendAccess(ND); 14526 14527 FunctionDecl *FD; 14528 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14529 FD = FTD->getTemplatedDecl(); 14530 else 14531 FD = cast<FunctionDecl>(ND); 14532 14533 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14534 // default argument expression, that declaration shall be a definition 14535 // and shall be the only declaration of the function or function 14536 // template in the translation unit. 14537 if (functionDeclHasDefaultArgument(FD)) { 14538 // We can't look at FD->getPreviousDecl() because it may not have been set 14539 // if we're in a dependent context. If the function is known to be a 14540 // redeclaration, we will have narrowed Previous down to the right decl. 14541 if (D.isRedeclaration()) { 14542 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14543 Diag(Previous.getRepresentativeDecl()->getLocation(), 14544 diag::note_previous_declaration); 14545 } else if (!D.isFunctionDefinition()) 14546 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14547 } 14548 14549 // Mark templated-scope function declarations as unsupported. 14550 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14551 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14552 << SS.getScopeRep() << SS.getRange() 14553 << cast<CXXRecordDecl>(CurContext); 14554 FrD->setUnsupportedFriend(true); 14555 } 14556 } 14557 14558 return ND; 14559 } 14560 14561 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14562 AdjustDeclIfTemplate(Dcl); 14563 14564 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14565 if (!Fn) { 14566 Diag(DelLoc, diag::err_deleted_non_function); 14567 return; 14568 } 14569 14570 // Deleted function does not have a body. 14571 Fn->setWillHaveBody(false); 14572 14573 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14574 // Don't consider the implicit declaration we generate for explicit 14575 // specializations. FIXME: Do not generate these implicit declarations. 14576 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14577 Prev->getPreviousDecl()) && 14578 !Prev->isDefined()) { 14579 Diag(DelLoc, diag::err_deleted_decl_not_first); 14580 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14581 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14582 : diag::note_previous_declaration); 14583 } 14584 // If the declaration wasn't the first, we delete the function anyway for 14585 // recovery. 14586 Fn = Fn->getCanonicalDecl(); 14587 } 14588 14589 // dllimport/dllexport cannot be deleted. 14590 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14591 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14592 Fn->setInvalidDecl(); 14593 } 14594 14595 if (Fn->isDeleted()) 14596 return; 14597 14598 // See if we're deleting a function which is already known to override a 14599 // non-deleted virtual function. 14600 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14601 bool IssuedDiagnostic = false; 14602 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14603 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14604 if (!IssuedDiagnostic) { 14605 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14606 IssuedDiagnostic = true; 14607 } 14608 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14609 } 14610 } 14611 // If this function was implicitly deleted because it was defaulted, 14612 // explain why it was deleted. 14613 if (IssuedDiagnostic && MD->isDefaulted()) 14614 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14615 /*Diagnose*/true); 14616 } 14617 14618 // C++11 [basic.start.main]p3: 14619 // A program that defines main as deleted [...] is ill-formed. 14620 if (Fn->isMain()) 14621 Diag(DelLoc, diag::err_deleted_main); 14622 14623 // C++11 [dcl.fct.def.delete]p4: 14624 // A deleted function is implicitly inline. 14625 Fn->setImplicitlyInline(); 14626 Fn->setDeletedAsWritten(); 14627 } 14628 14629 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14630 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14631 14632 if (MD) { 14633 if (MD->getParent()->isDependentType()) { 14634 MD->setDefaulted(); 14635 MD->setExplicitlyDefaulted(); 14636 return; 14637 } 14638 14639 CXXSpecialMember Member = getSpecialMember(MD); 14640 if (Member == CXXInvalid) { 14641 if (!MD->isInvalidDecl()) 14642 Diag(DefaultLoc, diag::err_default_special_members); 14643 return; 14644 } 14645 14646 MD->setDefaulted(); 14647 MD->setExplicitlyDefaulted(); 14648 14649 // Unset that we will have a body for this function. We might not, 14650 // if it turns out to be trivial, and we don't need this marking now 14651 // that we've marked it as defaulted. 14652 MD->setWillHaveBody(false); 14653 14654 // If this definition appears within the record, do the checking when 14655 // the record is complete. 14656 const FunctionDecl *Primary = MD; 14657 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14658 // Ask the template instantiation pattern that actually had the 14659 // '= default' on it. 14660 Primary = Pattern; 14661 14662 // If the method was defaulted on its first declaration, we will have 14663 // already performed the checking in CheckCompletedCXXClass. Such a 14664 // declaration doesn't trigger an implicit definition. 14665 if (Primary->getCanonicalDecl()->isDefaulted()) 14666 return; 14667 14668 CheckExplicitlyDefaultedSpecialMember(MD); 14669 14670 if (!MD->isInvalidDecl()) 14671 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14672 } else { 14673 Diag(DefaultLoc, diag::err_default_special_members); 14674 } 14675 } 14676 14677 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14678 for (Stmt *SubStmt : S->children()) { 14679 if (!SubStmt) 14680 continue; 14681 if (isa<ReturnStmt>(SubStmt)) 14682 Self.Diag(SubStmt->getBeginLoc(), 14683 diag::err_return_in_constructor_handler); 14684 if (!isa<Expr>(SubStmt)) 14685 SearchForReturnInStmt(Self, SubStmt); 14686 } 14687 } 14688 14689 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14690 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14691 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14692 SearchForReturnInStmt(*this, Handler); 14693 } 14694 } 14695 14696 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14697 const CXXMethodDecl *Old) { 14698 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14699 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14700 14701 if (OldFT->hasExtParameterInfos()) { 14702 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14703 // A parameter of the overriding method should be annotated with noescape 14704 // if the corresponding parameter of the overridden method is annotated. 14705 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14706 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14707 Diag(New->getParamDecl(I)->getLocation(), 14708 diag::warn_overriding_method_missing_noescape); 14709 Diag(Old->getParamDecl(I)->getLocation(), 14710 diag::note_overridden_marked_noescape); 14711 } 14712 } 14713 14714 // Virtual overrides must have the same code_seg. 14715 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 14716 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 14717 if ((NewCSA || OldCSA) && 14718 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 14719 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 14720 Diag(Old->getLocation(), diag::note_previous_declaration); 14721 return true; 14722 } 14723 14724 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14725 14726 // If the calling conventions match, everything is fine 14727 if (NewCC == OldCC) 14728 return false; 14729 14730 // If the calling conventions mismatch because the new function is static, 14731 // suppress the calling convention mismatch error; the error about static 14732 // function override (err_static_overrides_virtual from 14733 // Sema::CheckFunctionDeclaration) is more clear. 14734 if (New->getStorageClass() == SC_Static) 14735 return false; 14736 14737 Diag(New->getLocation(), 14738 diag::err_conflicting_overriding_cc_attributes) 14739 << New->getDeclName() << New->getType() << Old->getType(); 14740 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14741 return true; 14742 } 14743 14744 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14745 const CXXMethodDecl *Old) { 14746 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14747 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14748 14749 if (Context.hasSameType(NewTy, OldTy) || 14750 NewTy->isDependentType() || OldTy->isDependentType()) 14751 return false; 14752 14753 // Check if the return types are covariant 14754 QualType NewClassTy, OldClassTy; 14755 14756 /// Both types must be pointers or references to classes. 14757 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14758 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14759 NewClassTy = NewPT->getPointeeType(); 14760 OldClassTy = OldPT->getPointeeType(); 14761 } 14762 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14763 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14764 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14765 NewClassTy = NewRT->getPointeeType(); 14766 OldClassTy = OldRT->getPointeeType(); 14767 } 14768 } 14769 } 14770 14771 // The return types aren't either both pointers or references to a class type. 14772 if (NewClassTy.isNull()) { 14773 Diag(New->getLocation(), 14774 diag::err_different_return_type_for_overriding_virtual_function) 14775 << New->getDeclName() << NewTy << OldTy 14776 << New->getReturnTypeSourceRange(); 14777 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14778 << Old->getReturnTypeSourceRange(); 14779 14780 return true; 14781 } 14782 14783 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14784 // C++14 [class.virtual]p8: 14785 // If the class type in the covariant return type of D::f differs from 14786 // that of B::f, the class type in the return type of D::f shall be 14787 // complete at the point of declaration of D::f or shall be the class 14788 // type D. 14789 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14790 if (!RT->isBeingDefined() && 14791 RequireCompleteType(New->getLocation(), NewClassTy, 14792 diag::err_covariant_return_incomplete, 14793 New->getDeclName())) 14794 return true; 14795 } 14796 14797 // Check if the new class derives from the old class. 14798 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14799 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14800 << New->getDeclName() << NewTy << OldTy 14801 << New->getReturnTypeSourceRange(); 14802 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14803 << Old->getReturnTypeSourceRange(); 14804 return true; 14805 } 14806 14807 // Check if we the conversion from derived to base is valid. 14808 if (CheckDerivedToBaseConversion( 14809 NewClassTy, OldClassTy, 14810 diag::err_covariant_return_inaccessible_base, 14811 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14812 New->getLocation(), New->getReturnTypeSourceRange(), 14813 New->getDeclName(), nullptr)) { 14814 // FIXME: this note won't trigger for delayed access control 14815 // diagnostics, and it's impossible to get an undelayed error 14816 // here from access control during the original parse because 14817 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14818 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14819 << Old->getReturnTypeSourceRange(); 14820 return true; 14821 } 14822 } 14823 14824 // The qualifiers of the return types must be the same. 14825 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14826 Diag(New->getLocation(), 14827 diag::err_covariant_return_type_different_qualifications) 14828 << New->getDeclName() << NewTy << OldTy 14829 << New->getReturnTypeSourceRange(); 14830 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14831 << Old->getReturnTypeSourceRange(); 14832 return true; 14833 } 14834 14835 14836 // The new class type must have the same or less qualifiers as the old type. 14837 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14838 Diag(New->getLocation(), 14839 diag::err_covariant_return_type_class_type_more_qualified) 14840 << New->getDeclName() << NewTy << OldTy 14841 << New->getReturnTypeSourceRange(); 14842 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14843 << Old->getReturnTypeSourceRange(); 14844 return true; 14845 } 14846 14847 return false; 14848 } 14849 14850 /// Mark the given method pure. 14851 /// 14852 /// \param Method the method to be marked pure. 14853 /// 14854 /// \param InitRange the source range that covers the "0" initializer. 14855 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14856 SourceLocation EndLoc = InitRange.getEnd(); 14857 if (EndLoc.isValid()) 14858 Method->setRangeEnd(EndLoc); 14859 14860 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14861 Method->setPure(); 14862 return false; 14863 } 14864 14865 if (!Method->isInvalidDecl()) 14866 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14867 << Method->getDeclName() << InitRange; 14868 return true; 14869 } 14870 14871 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14872 if (D->getFriendObjectKind()) 14873 Diag(D->getLocation(), diag::err_pure_friend); 14874 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14875 CheckPureMethod(M, ZeroLoc); 14876 else 14877 Diag(D->getLocation(), diag::err_illegal_initializer); 14878 } 14879 14880 /// Determine whether the given declaration is a global variable or 14881 /// static data member. 14882 static bool isNonlocalVariable(const Decl *D) { 14883 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14884 return Var->hasGlobalStorage(); 14885 14886 return false; 14887 } 14888 14889 /// Invoked when we are about to parse an initializer for the declaration 14890 /// 'Dcl'. 14891 /// 14892 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14893 /// static data member of class X, names should be looked up in the scope of 14894 /// class X. If the declaration had a scope specifier, a scope will have 14895 /// been created and passed in for this purpose. Otherwise, S will be null. 14896 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14897 // If there is no declaration, there was an error parsing it. 14898 if (!D || D->isInvalidDecl()) 14899 return; 14900 14901 // We will always have a nested name specifier here, but this declaration 14902 // might not be out of line if the specifier names the current namespace: 14903 // extern int n; 14904 // int ::n = 0; 14905 if (S && D->isOutOfLine()) 14906 EnterDeclaratorContext(S, D->getDeclContext()); 14907 14908 // If we are parsing the initializer for a static data member, push a 14909 // new expression evaluation context that is associated with this static 14910 // data member. 14911 if (isNonlocalVariable(D)) 14912 PushExpressionEvaluationContext( 14913 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14914 } 14915 14916 /// Invoked after we are finished parsing an initializer for the declaration D. 14917 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14918 // If there is no declaration, there was an error parsing it. 14919 if (!D || D->isInvalidDecl()) 14920 return; 14921 14922 if (isNonlocalVariable(D)) 14923 PopExpressionEvaluationContext(); 14924 14925 if (S && D->isOutOfLine()) 14926 ExitDeclaratorContext(S); 14927 } 14928 14929 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14930 /// C++ if/switch/while/for statement. 14931 /// e.g: "if (int x = f()) {...}" 14932 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14933 // C++ 6.4p2: 14934 // The declarator shall not specify a function or an array. 14935 // The type-specifier-seq shall not contain typedef and shall not declare a 14936 // new class or enumeration. 14937 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14938 "Parser allowed 'typedef' as storage class of condition decl."); 14939 14940 Decl *Dcl = ActOnDeclarator(S, D); 14941 if (!Dcl) 14942 return true; 14943 14944 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14945 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14946 << D.getSourceRange(); 14947 return true; 14948 } 14949 14950 return Dcl; 14951 } 14952 14953 void Sema::LoadExternalVTableUses() { 14954 if (!ExternalSource) 14955 return; 14956 14957 SmallVector<ExternalVTableUse, 4> VTables; 14958 ExternalSource->ReadUsedVTables(VTables); 14959 SmallVector<VTableUse, 4> NewUses; 14960 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14961 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14962 = VTablesUsed.find(VTables[I].Record); 14963 // Even if a definition wasn't required before, it may be required now. 14964 if (Pos != VTablesUsed.end()) { 14965 if (!Pos->second && VTables[I].DefinitionRequired) 14966 Pos->second = true; 14967 continue; 14968 } 14969 14970 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14971 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14972 } 14973 14974 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14975 } 14976 14977 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14978 bool DefinitionRequired) { 14979 // Ignore any vtable uses in unevaluated operands or for classes that do 14980 // not have a vtable. 14981 if (!Class->isDynamicClass() || Class->isDependentContext() || 14982 CurContext->isDependentContext() || isUnevaluatedContext()) 14983 return; 14984 // Do not mark as used if compiling for the device outside of the target 14985 // region. 14986 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 14987 !isInOpenMPDeclareTargetContext() && 14988 !isInOpenMPTargetExecutionDirective()) { 14989 if (!DefinitionRequired) 14990 MarkVirtualMembersReferenced(Loc, Class); 14991 return; 14992 } 14993 14994 // Try to insert this class into the map. 14995 LoadExternalVTableUses(); 14996 Class = Class->getCanonicalDecl(); 14997 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14998 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14999 if (!Pos.second) { 15000 // If we already had an entry, check to see if we are promoting this vtable 15001 // to require a definition. If so, we need to reappend to the VTableUses 15002 // list, since we may have already processed the first entry. 15003 if (DefinitionRequired && !Pos.first->second) { 15004 Pos.first->second = true; 15005 } else { 15006 // Otherwise, we can early exit. 15007 return; 15008 } 15009 } else { 15010 // The Microsoft ABI requires that we perform the destructor body 15011 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 15012 // the deleting destructor is emitted with the vtable, not with the 15013 // destructor definition as in the Itanium ABI. 15014 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15015 CXXDestructorDecl *DD = Class->getDestructor(); 15016 if (DD && DD->isVirtual() && !DD->isDeleted()) { 15017 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 15018 // If this is an out-of-line declaration, marking it referenced will 15019 // not do anything. Manually call CheckDestructor to look up operator 15020 // delete(). 15021 ContextRAII SavedContext(*this, DD); 15022 CheckDestructor(DD); 15023 } else { 15024 MarkFunctionReferenced(Loc, Class->getDestructor()); 15025 } 15026 } 15027 } 15028 } 15029 15030 // Local classes need to have their virtual members marked 15031 // immediately. For all other classes, we mark their virtual members 15032 // at the end of the translation unit. 15033 if (Class->isLocalClass()) 15034 MarkVirtualMembersReferenced(Loc, Class); 15035 else 15036 VTableUses.push_back(std::make_pair(Class, Loc)); 15037 } 15038 15039 bool Sema::DefineUsedVTables() { 15040 LoadExternalVTableUses(); 15041 if (VTableUses.empty()) 15042 return false; 15043 15044 // Note: The VTableUses vector could grow as a result of marking 15045 // the members of a class as "used", so we check the size each 15046 // time through the loop and prefer indices (which are stable) to 15047 // iterators (which are not). 15048 bool DefinedAnything = false; 15049 for (unsigned I = 0; I != VTableUses.size(); ++I) { 15050 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 15051 if (!Class) 15052 continue; 15053 TemplateSpecializationKind ClassTSK = 15054 Class->getTemplateSpecializationKind(); 15055 15056 SourceLocation Loc = VTableUses[I].second; 15057 15058 bool DefineVTable = true; 15059 15060 // If this class has a key function, but that key function is 15061 // defined in another translation unit, we don't need to emit the 15062 // vtable even though we're using it. 15063 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 15064 if (KeyFunction && !KeyFunction->hasBody()) { 15065 // The key function is in another translation unit. 15066 DefineVTable = false; 15067 TemplateSpecializationKind TSK = 15068 KeyFunction->getTemplateSpecializationKind(); 15069 assert(TSK != TSK_ExplicitInstantiationDefinition && 15070 TSK != TSK_ImplicitInstantiation && 15071 "Instantiations don't have key functions"); 15072 (void)TSK; 15073 } else if (!KeyFunction) { 15074 // If we have a class with no key function that is the subject 15075 // of an explicit instantiation declaration, suppress the 15076 // vtable; it will live with the explicit instantiation 15077 // definition. 15078 bool IsExplicitInstantiationDeclaration = 15079 ClassTSK == TSK_ExplicitInstantiationDeclaration; 15080 for (auto R : Class->redecls()) { 15081 TemplateSpecializationKind TSK 15082 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 15083 if (TSK == TSK_ExplicitInstantiationDeclaration) 15084 IsExplicitInstantiationDeclaration = true; 15085 else if (TSK == TSK_ExplicitInstantiationDefinition) { 15086 IsExplicitInstantiationDeclaration = false; 15087 break; 15088 } 15089 } 15090 15091 if (IsExplicitInstantiationDeclaration) 15092 DefineVTable = false; 15093 } 15094 15095 // The exception specifications for all virtual members may be needed even 15096 // if we are not providing an authoritative form of the vtable in this TU. 15097 // We may choose to emit it available_externally anyway. 15098 if (!DefineVTable) { 15099 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 15100 continue; 15101 } 15102 15103 // Mark all of the virtual members of this class as referenced, so 15104 // that we can build a vtable. Then, tell the AST consumer that a 15105 // vtable for this class is required. 15106 DefinedAnything = true; 15107 MarkVirtualMembersReferenced(Loc, Class); 15108 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 15109 if (VTablesUsed[Canonical]) 15110 Consumer.HandleVTable(Class); 15111 15112 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 15113 // no key function or the key function is inlined. Don't warn in C++ ABIs 15114 // that lack key functions, since the user won't be able to make one. 15115 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 15116 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 15117 const FunctionDecl *KeyFunctionDef = nullptr; 15118 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 15119 KeyFunctionDef->isInlined())) { 15120 Diag(Class->getLocation(), 15121 ClassTSK == TSK_ExplicitInstantiationDefinition 15122 ? diag::warn_weak_template_vtable 15123 : diag::warn_weak_vtable) 15124 << Class; 15125 } 15126 } 15127 } 15128 VTableUses.clear(); 15129 15130 return DefinedAnything; 15131 } 15132 15133 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 15134 const CXXRecordDecl *RD) { 15135 for (const auto *I : RD->methods()) 15136 if (I->isVirtual() && !I->isPure()) 15137 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 15138 } 15139 15140 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 15141 const CXXRecordDecl *RD) { 15142 // Mark all functions which will appear in RD's vtable as used. 15143 CXXFinalOverriderMap FinalOverriders; 15144 RD->getFinalOverriders(FinalOverriders); 15145 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 15146 E = FinalOverriders.end(); 15147 I != E; ++I) { 15148 for (OverridingMethods::const_iterator OI = I->second.begin(), 15149 OE = I->second.end(); 15150 OI != OE; ++OI) { 15151 assert(OI->second.size() > 0 && "no final overrider"); 15152 CXXMethodDecl *Overrider = OI->second.front().Method; 15153 15154 // C++ [basic.def.odr]p2: 15155 // [...] A virtual member function is used if it is not pure. [...] 15156 if (!Overrider->isPure()) 15157 MarkFunctionReferenced(Loc, Overrider); 15158 } 15159 } 15160 15161 // Only classes that have virtual bases need a VTT. 15162 if (RD->getNumVBases() == 0) 15163 return; 15164 15165 for (const auto &I : RD->bases()) { 15166 const CXXRecordDecl *Base = 15167 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15168 if (Base->getNumVBases() == 0) 15169 continue; 15170 MarkVirtualMembersReferenced(Loc, Base); 15171 } 15172 } 15173 15174 /// SetIvarInitializers - This routine builds initialization ASTs for the 15175 /// Objective-C implementation whose ivars need be initialized. 15176 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15177 if (!getLangOpts().CPlusPlus) 15178 return; 15179 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15180 SmallVector<ObjCIvarDecl*, 8> ivars; 15181 CollectIvarsToConstructOrDestruct(OID, ivars); 15182 if (ivars.empty()) 15183 return; 15184 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15185 for (unsigned i = 0; i < ivars.size(); i++) { 15186 FieldDecl *Field = ivars[i]; 15187 if (Field->isInvalidDecl()) 15188 continue; 15189 15190 CXXCtorInitializer *Member; 15191 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15192 InitializationKind InitKind = 15193 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15194 15195 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15196 ExprResult MemberInit = 15197 InitSeq.Perform(*this, InitEntity, InitKind, None); 15198 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15199 // Note, MemberInit could actually come back empty if no initialization 15200 // is required (e.g., because it would call a trivial default constructor) 15201 if (!MemberInit.get() || MemberInit.isInvalid()) 15202 continue; 15203 15204 Member = 15205 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15206 SourceLocation(), 15207 MemberInit.getAs<Expr>(), 15208 SourceLocation()); 15209 AllToInit.push_back(Member); 15210 15211 // Be sure that the destructor is accessible and is marked as referenced. 15212 if (const RecordType *RecordTy = 15213 Context.getBaseElementType(Field->getType()) 15214 ->getAs<RecordType>()) { 15215 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15216 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15217 MarkFunctionReferenced(Field->getLocation(), Destructor); 15218 CheckDestructorAccess(Field->getLocation(), Destructor, 15219 PDiag(diag::err_access_dtor_ivar) 15220 << Context.getBaseElementType(Field->getType())); 15221 } 15222 } 15223 } 15224 ObjCImplementation->setIvarInitializers(Context, 15225 AllToInit.data(), AllToInit.size()); 15226 } 15227 } 15228 15229 static 15230 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15231 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15232 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15233 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15234 Sema &S) { 15235 if (Ctor->isInvalidDecl()) 15236 return; 15237 15238 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15239 15240 // Target may not be determinable yet, for instance if this is a dependent 15241 // call in an uninstantiated template. 15242 if (Target) { 15243 const FunctionDecl *FNTarget = nullptr; 15244 (void)Target->hasBody(FNTarget); 15245 Target = const_cast<CXXConstructorDecl*>( 15246 cast_or_null<CXXConstructorDecl>(FNTarget)); 15247 } 15248 15249 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15250 // Avoid dereferencing a null pointer here. 15251 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15252 15253 if (!Current.insert(Canonical).second) 15254 return; 15255 15256 // We know that beyond here, we aren't chaining into a cycle. 15257 if (!Target || !Target->isDelegatingConstructor() || 15258 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15259 Valid.insert(Current.begin(), Current.end()); 15260 Current.clear(); 15261 // We've hit a cycle. 15262 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15263 Current.count(TCanonical)) { 15264 // If we haven't diagnosed this cycle yet, do so now. 15265 if (!Invalid.count(TCanonical)) { 15266 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15267 diag::warn_delegating_ctor_cycle) 15268 << Ctor; 15269 15270 // Don't add a note for a function delegating directly to itself. 15271 if (TCanonical != Canonical) 15272 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15273 15274 CXXConstructorDecl *C = Target; 15275 while (C->getCanonicalDecl() != Canonical) { 15276 const FunctionDecl *FNTarget = nullptr; 15277 (void)C->getTargetConstructor()->hasBody(FNTarget); 15278 assert(FNTarget && "Ctor cycle through bodiless function"); 15279 15280 C = const_cast<CXXConstructorDecl*>( 15281 cast<CXXConstructorDecl>(FNTarget)); 15282 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15283 } 15284 } 15285 15286 Invalid.insert(Current.begin(), Current.end()); 15287 Current.clear(); 15288 } else { 15289 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15290 } 15291 } 15292 15293 15294 void Sema::CheckDelegatingCtorCycles() { 15295 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15296 15297 for (DelegatingCtorDeclsType::iterator 15298 I = DelegatingCtorDecls.begin(ExternalSource), 15299 E = DelegatingCtorDecls.end(); 15300 I != E; ++I) 15301 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15302 15303 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15304 (*CI)->setInvalidDecl(); 15305 } 15306 15307 namespace { 15308 /// AST visitor that finds references to the 'this' expression. 15309 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15310 Sema &S; 15311 15312 public: 15313 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15314 15315 bool VisitCXXThisExpr(CXXThisExpr *E) { 15316 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15317 << E->isImplicit(); 15318 return false; 15319 } 15320 }; 15321 } 15322 15323 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15324 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15325 if (!TSInfo) 15326 return false; 15327 15328 TypeLoc TL = TSInfo->getTypeLoc(); 15329 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15330 if (!ProtoTL) 15331 return false; 15332 15333 // C++11 [expr.prim.general]p3: 15334 // [The expression this] shall not appear before the optional 15335 // cv-qualifier-seq and it shall not appear within the declaration of a 15336 // static member function (although its type and value category are defined 15337 // within a static member function as they are within a non-static member 15338 // function). [ Note: this is because declaration matching does not occur 15339 // until the complete declarator is known. - end note ] 15340 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15341 FindCXXThisExpr Finder(*this); 15342 15343 // If the return type came after the cv-qualifier-seq, check it now. 15344 if (Proto->hasTrailingReturn() && 15345 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15346 return true; 15347 15348 // Check the exception specification. 15349 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15350 return true; 15351 15352 return checkThisInStaticMemberFunctionAttributes(Method); 15353 } 15354 15355 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15356 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15357 if (!TSInfo) 15358 return false; 15359 15360 TypeLoc TL = TSInfo->getTypeLoc(); 15361 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15362 if (!ProtoTL) 15363 return false; 15364 15365 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15366 FindCXXThisExpr Finder(*this); 15367 15368 switch (Proto->getExceptionSpecType()) { 15369 case EST_Unparsed: 15370 case EST_Uninstantiated: 15371 case EST_Unevaluated: 15372 case EST_BasicNoexcept: 15373 case EST_DynamicNone: 15374 case EST_MSAny: 15375 case EST_None: 15376 break; 15377 15378 case EST_DependentNoexcept: 15379 case EST_NoexceptFalse: 15380 case EST_NoexceptTrue: 15381 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15382 return true; 15383 LLVM_FALLTHROUGH; 15384 15385 case EST_Dynamic: 15386 for (const auto &E : Proto->exceptions()) { 15387 if (!Finder.TraverseType(E)) 15388 return true; 15389 } 15390 break; 15391 } 15392 15393 return false; 15394 } 15395 15396 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15397 FindCXXThisExpr Finder(*this); 15398 15399 // Check attributes. 15400 for (const auto *A : Method->attrs()) { 15401 // FIXME: This should be emitted by tblgen. 15402 Expr *Arg = nullptr; 15403 ArrayRef<Expr *> Args; 15404 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15405 Arg = G->getArg(); 15406 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15407 Arg = G->getArg(); 15408 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15409 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15410 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15411 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15412 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15413 Arg = ETLF->getSuccessValue(); 15414 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15415 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15416 Arg = STLF->getSuccessValue(); 15417 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15418 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15419 Arg = LR->getArg(); 15420 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15421 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15422 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15423 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15424 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15425 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15426 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15427 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15428 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15429 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15430 15431 if (Arg && !Finder.TraverseStmt(Arg)) 15432 return true; 15433 15434 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15435 if (!Finder.TraverseStmt(Args[I])) 15436 return true; 15437 } 15438 } 15439 15440 return false; 15441 } 15442 15443 void Sema::checkExceptionSpecification( 15444 bool IsTopLevel, ExceptionSpecificationType EST, 15445 ArrayRef<ParsedType> DynamicExceptions, 15446 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15447 SmallVectorImpl<QualType> &Exceptions, 15448 FunctionProtoType::ExceptionSpecInfo &ESI) { 15449 Exceptions.clear(); 15450 ESI.Type = EST; 15451 if (EST == EST_Dynamic) { 15452 Exceptions.reserve(DynamicExceptions.size()); 15453 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15454 // FIXME: Preserve type source info. 15455 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15456 15457 if (IsTopLevel) { 15458 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15459 collectUnexpandedParameterPacks(ET, Unexpanded); 15460 if (!Unexpanded.empty()) { 15461 DiagnoseUnexpandedParameterPacks( 15462 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15463 Unexpanded); 15464 continue; 15465 } 15466 } 15467 15468 // Check that the type is valid for an exception spec, and 15469 // drop it if not. 15470 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15471 Exceptions.push_back(ET); 15472 } 15473 ESI.Exceptions = Exceptions; 15474 return; 15475 } 15476 15477 if (isComputedNoexcept(EST)) { 15478 assert((NoexceptExpr->isTypeDependent() || 15479 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15480 Context.BoolTy) && 15481 "Parser should have made sure that the expression is boolean"); 15482 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15483 ESI.Type = EST_BasicNoexcept; 15484 return; 15485 } 15486 15487 ESI.NoexceptExpr = NoexceptExpr; 15488 return; 15489 } 15490 } 15491 15492 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15493 ExceptionSpecificationType EST, 15494 SourceRange SpecificationRange, 15495 ArrayRef<ParsedType> DynamicExceptions, 15496 ArrayRef<SourceRange> DynamicExceptionRanges, 15497 Expr *NoexceptExpr) { 15498 if (!MethodD) 15499 return; 15500 15501 // Dig out the method we're referring to. 15502 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15503 MethodD = FunTmpl->getTemplatedDecl(); 15504 15505 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15506 if (!Method) 15507 return; 15508 15509 // Check the exception specification. 15510 llvm::SmallVector<QualType, 4> Exceptions; 15511 FunctionProtoType::ExceptionSpecInfo ESI; 15512 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15513 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15514 ESI); 15515 15516 // Update the exception specification on the function type. 15517 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15518 15519 if (Method->isStatic()) 15520 checkThisInStaticMemberFunctionExceptionSpec(Method); 15521 15522 if (Method->isVirtual()) { 15523 // Check overrides, which we previously had to delay. 15524 for (const CXXMethodDecl *O : Method->overridden_methods()) 15525 CheckOverridingFunctionExceptionSpec(Method, O); 15526 } 15527 } 15528 15529 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15530 /// 15531 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15532 SourceLocation DeclStart, Declarator &D, 15533 Expr *BitWidth, 15534 InClassInitStyle InitStyle, 15535 AccessSpecifier AS, 15536 const ParsedAttr &MSPropertyAttr) { 15537 IdentifierInfo *II = D.getIdentifier(); 15538 if (!II) { 15539 Diag(DeclStart, diag::err_anonymous_property); 15540 return nullptr; 15541 } 15542 SourceLocation Loc = D.getIdentifierLoc(); 15543 15544 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15545 QualType T = TInfo->getType(); 15546 if (getLangOpts().CPlusPlus) { 15547 CheckExtraCXXDefaultArguments(D); 15548 15549 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15550 UPPC_DataMemberType)) { 15551 D.setInvalidType(); 15552 T = Context.IntTy; 15553 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15554 } 15555 } 15556 15557 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15558 15559 if (D.getDeclSpec().isInlineSpecified()) 15560 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15561 << getLangOpts().CPlusPlus17; 15562 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15563 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15564 diag::err_invalid_thread) 15565 << DeclSpec::getSpecifierName(TSCS); 15566 15567 // Check to see if this name was declared as a member previously 15568 NamedDecl *PrevDecl = nullptr; 15569 LookupResult Previous(*this, II, Loc, LookupMemberName, 15570 ForVisibleRedeclaration); 15571 LookupName(Previous, S); 15572 switch (Previous.getResultKind()) { 15573 case LookupResult::Found: 15574 case LookupResult::FoundUnresolvedValue: 15575 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15576 break; 15577 15578 case LookupResult::FoundOverloaded: 15579 PrevDecl = Previous.getRepresentativeDecl(); 15580 break; 15581 15582 case LookupResult::NotFound: 15583 case LookupResult::NotFoundInCurrentInstantiation: 15584 case LookupResult::Ambiguous: 15585 break; 15586 } 15587 15588 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15589 // Maybe we will complain about the shadowed template parameter. 15590 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15591 // Just pretend that we didn't see the previous declaration. 15592 PrevDecl = nullptr; 15593 } 15594 15595 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15596 PrevDecl = nullptr; 15597 15598 SourceLocation TSSL = D.getBeginLoc(); 15599 MSPropertyDecl *NewPD = 15600 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 15601 MSPropertyAttr.getPropertyDataGetter(), 15602 MSPropertyAttr.getPropertyDataSetter()); 15603 ProcessDeclAttributes(TUScope, NewPD, D); 15604 NewPD->setAccess(AS); 15605 15606 if (NewPD->isInvalidDecl()) 15607 Record->setInvalidDecl(); 15608 15609 if (D.getDeclSpec().isModulePrivateSpecified()) 15610 NewPD->setModulePrivate(); 15611 15612 if (NewPD->isInvalidDecl() && PrevDecl) { 15613 // Don't introduce NewFD into scope; there's already something 15614 // with the same name in the same scope. 15615 } else if (II) { 15616 PushOnScopeChains(NewPD, S); 15617 } else 15618 Record->addDecl(NewPD); 15619 15620 return NewPD; 15621 } 15622