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 if (D->hasAttr<TrivialABIAttr>()) 5890 return true; 5891 5892 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 5893 // The PS4 platform ABI follows the behavior of Clang 3.2. 5894 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 5895 return !D->hasNonTrivialDestructorForCall() && 5896 !D->hasNonTrivialCopyConstructorForCall(); 5897 5898 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 5899 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 5900 bool DtorIsTrivialForCall = false; 5901 5902 // If a class has at least one non-deleted, trivial copy constructor, it 5903 // is passed according to the C ABI. Otherwise, it is passed indirectly. 5904 // 5905 // Note: This permits classes with non-trivial copy or move ctors to be 5906 // passed in registers, so long as they *also* have a trivial copy ctor, 5907 // which is non-conforming. 5908 if (D->needsImplicitCopyConstructor()) { 5909 if (!D->defaultedCopyConstructorIsDeleted()) { 5910 if (D->hasTrivialCopyConstructor()) 5911 CopyCtorIsTrivial = true; 5912 if (D->hasTrivialCopyConstructorForCall()) 5913 CopyCtorIsTrivialForCall = true; 5914 } 5915 } else { 5916 for (const CXXConstructorDecl *CD : D->ctors()) { 5917 if (CD->isCopyConstructor() && !CD->isDeleted()) { 5918 if (CD->isTrivial()) 5919 CopyCtorIsTrivial = true; 5920 if (CD->isTrivialForCall()) 5921 CopyCtorIsTrivialForCall = true; 5922 } 5923 } 5924 } 5925 5926 if (D->needsImplicitDestructor()) { 5927 if (!D->defaultedDestructorIsDeleted() && 5928 D->hasTrivialDestructorForCall()) 5929 DtorIsTrivialForCall = true; 5930 } else if (const auto *DD = D->getDestructor()) { 5931 if (!DD->isDeleted() && DD->isTrivialForCall()) 5932 DtorIsTrivialForCall = true; 5933 } 5934 5935 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 5936 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 5937 return true; 5938 5939 // If a class has a destructor, we'd really like to pass it indirectly 5940 // because it allows us to elide copies. Unfortunately, MSVC makes that 5941 // impossible for small types, which it will pass in a single register or 5942 // stack slot. Most objects with dtors are large-ish, so handle that early. 5943 // We can't call out all large objects as being indirect because there are 5944 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 5945 // how we pass large POD types. 5946 5947 // Note: This permits small classes with nontrivial destructors to be 5948 // passed in registers, which is non-conforming. 5949 if (CopyCtorIsTrivial && 5950 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64) 5951 return true; 5952 return false; 5953 } 5954 5955 // Per C++ [class.temporary]p3, the relevant condition is: 5956 // each copy constructor, move constructor, and destructor of X is 5957 // either trivial or deleted, and X has at least one non-deleted copy 5958 // or move constructor 5959 bool HasNonDeletedCopyOrMove = false; 5960 5961 if (D->needsImplicitCopyConstructor() && 5962 !D->defaultedCopyConstructorIsDeleted()) { 5963 if (!D->hasTrivialCopyConstructorForCall()) 5964 return false; 5965 HasNonDeletedCopyOrMove = true; 5966 } 5967 5968 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5969 !D->defaultedMoveConstructorIsDeleted()) { 5970 if (!D->hasTrivialMoveConstructorForCall()) 5971 return false; 5972 HasNonDeletedCopyOrMove = true; 5973 } 5974 5975 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5976 !D->hasTrivialDestructorForCall()) 5977 return false; 5978 5979 for (const CXXMethodDecl *MD : D->methods()) { 5980 if (MD->isDeleted()) 5981 continue; 5982 5983 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5984 if (CD && CD->isCopyOrMoveConstructor()) 5985 HasNonDeletedCopyOrMove = true; 5986 else if (!isa<CXXDestructorDecl>(MD)) 5987 continue; 5988 5989 if (!MD->isTrivialForCall()) 5990 return false; 5991 } 5992 5993 return HasNonDeletedCopyOrMove; 5994 } 5995 5996 /// Perform semantic checks on a class definition that has been 5997 /// completing, introducing implicitly-declared members, checking for 5998 /// abstract types, etc. 5999 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 6000 if (!Record) 6001 return; 6002 6003 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6004 AbstractUsageInfo Info(*this, Record); 6005 CheckAbstractClassUsage(Info, Record); 6006 } 6007 6008 // If this is not an aggregate type and has no user-declared constructor, 6009 // complain about any non-static data members of reference or const scalar 6010 // type, since they will never get initializers. 6011 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6012 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6013 !Record->isLambda()) { 6014 bool Complained = false; 6015 for (const auto *F : Record->fields()) { 6016 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6017 continue; 6018 6019 if (F->getType()->isReferenceType() || 6020 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6021 if (!Complained) { 6022 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6023 << Record->getTagKind() << Record; 6024 Complained = true; 6025 } 6026 6027 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6028 << F->getType()->isReferenceType() 6029 << F->getDeclName(); 6030 } 6031 } 6032 } 6033 6034 if (Record->getIdentifier()) { 6035 // C++ [class.mem]p13: 6036 // If T is the name of a class, then each of the following shall have a 6037 // name different from T: 6038 // - every member of every anonymous union that is a member of class T. 6039 // 6040 // C++ [class.mem]p14: 6041 // In addition, if class T has a user-declared constructor (12.1), every 6042 // non-static data member of class T shall have a name different from T. 6043 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6044 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6045 ++I) { 6046 NamedDecl *D = (*I)->getUnderlyingDecl(); 6047 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6048 Record->hasUserDeclaredConstructor()) || 6049 isa<IndirectFieldDecl>(D)) { 6050 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6051 << D->getDeclName(); 6052 break; 6053 } 6054 } 6055 } 6056 6057 // Warn if the class has virtual methods but non-virtual public destructor. 6058 if (Record->isPolymorphic() && !Record->isDependentType()) { 6059 CXXDestructorDecl *dtor = Record->getDestructor(); 6060 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6061 !Record->hasAttr<FinalAttr>()) 6062 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6063 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6064 } 6065 6066 if (Record->isAbstract()) { 6067 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6068 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6069 << FA->isSpelledAsSealed(); 6070 DiagnoseAbstractType(Record); 6071 } 6072 } 6073 6074 // See if trivial_abi has to be dropped. 6075 if (Record->hasAttr<TrivialABIAttr>()) 6076 checkIllFormedTrivialABIStruct(*Record); 6077 6078 // Set HasTrivialSpecialMemberForCall if the record has attribute 6079 // "trivial_abi". 6080 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6081 6082 if (HasTrivialABI) 6083 Record->setHasTrivialSpecialMemberForCall(); 6084 6085 bool HasMethodWithOverrideControl = false, 6086 HasOverridingMethodWithoutOverrideControl = false; 6087 if (!Record->isDependentType()) { 6088 for (auto *M : Record->methods()) { 6089 // See if a method overloads virtual methods in a base 6090 // class without overriding any. 6091 if (!M->isStatic()) 6092 DiagnoseHiddenVirtualMethods(M); 6093 if (M->hasAttr<OverrideAttr>()) 6094 HasMethodWithOverrideControl = true; 6095 else if (M->size_overridden_methods() > 0) 6096 HasOverridingMethodWithoutOverrideControl = true; 6097 // Check whether the explicitly-defaulted special members are valid. 6098 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6099 CheckExplicitlyDefaultedSpecialMember(M); 6100 6101 // For an explicitly defaulted or deleted special member, we defer 6102 // determining triviality until the class is complete. That time is now! 6103 CXXSpecialMember CSM = getSpecialMember(M); 6104 if (!M->isImplicit() && !M->isUserProvided()) { 6105 if (CSM != CXXInvalid) { 6106 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6107 // Inform the class that we've finished declaring this member. 6108 Record->finishedDefaultedOrDeletedMember(M); 6109 M->setTrivialForCall( 6110 HasTrivialABI || 6111 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6112 Record->setTrivialForCallFlags(M); 6113 } 6114 } 6115 6116 // Set triviality for the purpose of calls if this is a user-provided 6117 // copy/move constructor or destructor. 6118 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6119 CSM == CXXDestructor) && M->isUserProvided()) { 6120 M->setTrivialForCall(HasTrivialABI); 6121 Record->setTrivialForCallFlags(M); 6122 } 6123 6124 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6125 M->hasAttr<DLLExportAttr>()) { 6126 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6127 M->isTrivial() && 6128 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6129 CSM == CXXDestructor)) 6130 M->dropAttr<DLLExportAttr>(); 6131 6132 if (M->hasAttr<DLLExportAttr>()) { 6133 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6134 ActOnFinishInlineFunctionDef(M); 6135 } 6136 } 6137 } 6138 } 6139 6140 if (HasMethodWithOverrideControl && 6141 HasOverridingMethodWithoutOverrideControl) { 6142 // At least one method has the 'override' control declared. 6143 // Diagnose all other overridden methods which do not have 'override' specified on them. 6144 for (auto *M : Record->methods()) 6145 DiagnoseAbsenceOfOverrideControl(M); 6146 } 6147 6148 // ms_struct is a request to use the same ABI rules as MSVC. Check 6149 // whether this class uses any C++ features that are implemented 6150 // completely differently in MSVC, and if so, emit a diagnostic. 6151 // That diagnostic defaults to an error, but we allow projects to 6152 // map it down to a warning (or ignore it). It's a fairly common 6153 // practice among users of the ms_struct pragma to mass-annotate 6154 // headers, sweeping up a bunch of types that the project doesn't 6155 // really rely on MSVC-compatible layout for. We must therefore 6156 // support "ms_struct except for C++ stuff" as a secondary ABI. 6157 if (Record->isMsStruct(Context) && 6158 (Record->isPolymorphic() || Record->getNumBases())) { 6159 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6160 } 6161 6162 checkClassLevelDLLAttribute(Record); 6163 checkClassLevelCodeSegAttribute(Record); 6164 6165 bool ClangABICompat4 = 6166 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6167 TargetInfo::CallingConvKind CCK = 6168 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6169 bool CanPass = canPassInRegisters(*this, Record, CCK); 6170 6171 // Do not change ArgPassingRestrictions if it has already been set to 6172 // APK_CanNeverPassInRegs. 6173 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6174 Record->setArgPassingRestrictions(CanPass 6175 ? RecordDecl::APK_CanPassInRegs 6176 : RecordDecl::APK_CannotPassInRegs); 6177 6178 // If canPassInRegisters returns true despite the record having a non-trivial 6179 // destructor, the record is destructed in the callee. This happens only when 6180 // the record or one of its subobjects has a field annotated with trivial_abi 6181 // or a field qualified with ObjC __strong/__weak. 6182 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6183 Record->setParamDestroyedInCallee(true); 6184 else if (Record->hasNonTrivialDestructor()) 6185 Record->setParamDestroyedInCallee(CanPass); 6186 6187 if (getLangOpts().ForceEmitVTables) { 6188 // If we want to emit all the vtables, we need to mark it as used. This 6189 // is especially required for cases like vtable assumption loads. 6190 MarkVTableUsed(Record->getInnerLocStart(), Record); 6191 } 6192 } 6193 6194 /// Look up the special member function that would be called by a special 6195 /// member function for a subobject of class type. 6196 /// 6197 /// \param Class The class type of the subobject. 6198 /// \param CSM The kind of special member function. 6199 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6200 /// \param ConstRHS True if this is a copy operation with a const object 6201 /// on its RHS, that is, if the argument to the outer special member 6202 /// function is 'const' and this is not a field marked 'mutable'. 6203 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6204 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6205 unsigned FieldQuals, bool ConstRHS) { 6206 unsigned LHSQuals = 0; 6207 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6208 LHSQuals = FieldQuals; 6209 6210 unsigned RHSQuals = FieldQuals; 6211 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6212 RHSQuals = 0; 6213 else if (ConstRHS) 6214 RHSQuals |= Qualifiers::Const; 6215 6216 return S.LookupSpecialMember(Class, CSM, 6217 RHSQuals & Qualifiers::Const, 6218 RHSQuals & Qualifiers::Volatile, 6219 false, 6220 LHSQuals & Qualifiers::Const, 6221 LHSQuals & Qualifiers::Volatile); 6222 } 6223 6224 class Sema::InheritedConstructorInfo { 6225 Sema &S; 6226 SourceLocation UseLoc; 6227 6228 /// A mapping from the base classes through which the constructor was 6229 /// inherited to the using shadow declaration in that base class (or a null 6230 /// pointer if the constructor was declared in that base class). 6231 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6232 InheritedFromBases; 6233 6234 public: 6235 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6236 ConstructorUsingShadowDecl *Shadow) 6237 : S(S), UseLoc(UseLoc) { 6238 bool DiagnosedMultipleConstructedBases = false; 6239 CXXRecordDecl *ConstructedBase = nullptr; 6240 UsingDecl *ConstructedBaseUsing = nullptr; 6241 6242 // Find the set of such base class subobjects and check that there's a 6243 // unique constructed subobject. 6244 for (auto *D : Shadow->redecls()) { 6245 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6246 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6247 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6248 6249 InheritedFromBases.insert( 6250 std::make_pair(DNominatedBase->getCanonicalDecl(), 6251 DShadow->getNominatedBaseClassShadowDecl())); 6252 if (DShadow->constructsVirtualBase()) 6253 InheritedFromBases.insert( 6254 std::make_pair(DConstructedBase->getCanonicalDecl(), 6255 DShadow->getConstructedBaseClassShadowDecl())); 6256 else 6257 assert(DNominatedBase == DConstructedBase); 6258 6259 // [class.inhctor.init]p2: 6260 // If the constructor was inherited from multiple base class subobjects 6261 // of type B, the program is ill-formed. 6262 if (!ConstructedBase) { 6263 ConstructedBase = DConstructedBase; 6264 ConstructedBaseUsing = D->getUsingDecl(); 6265 } else if (ConstructedBase != DConstructedBase && 6266 !Shadow->isInvalidDecl()) { 6267 if (!DiagnosedMultipleConstructedBases) { 6268 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6269 << Shadow->getTargetDecl(); 6270 S.Diag(ConstructedBaseUsing->getLocation(), 6271 diag::note_ambiguous_inherited_constructor_using) 6272 << ConstructedBase; 6273 DiagnosedMultipleConstructedBases = true; 6274 } 6275 S.Diag(D->getUsingDecl()->getLocation(), 6276 diag::note_ambiguous_inherited_constructor_using) 6277 << DConstructedBase; 6278 } 6279 } 6280 6281 if (DiagnosedMultipleConstructedBases) 6282 Shadow->setInvalidDecl(); 6283 } 6284 6285 /// Find the constructor to use for inherited construction of a base class, 6286 /// and whether that base class constructor inherits the constructor from a 6287 /// virtual base class (in which case it won't actually invoke it). 6288 std::pair<CXXConstructorDecl *, bool> 6289 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6290 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6291 if (It == InheritedFromBases.end()) 6292 return std::make_pair(nullptr, false); 6293 6294 // This is an intermediary class. 6295 if (It->second) 6296 return std::make_pair( 6297 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6298 It->second->constructsVirtualBase()); 6299 6300 // This is the base class from which the constructor was inherited. 6301 return std::make_pair(Ctor, false); 6302 } 6303 }; 6304 6305 /// Is the special member function which would be selected to perform the 6306 /// specified operation on the specified class type a constexpr constructor? 6307 static bool 6308 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6309 Sema::CXXSpecialMember CSM, unsigned Quals, 6310 bool ConstRHS, 6311 CXXConstructorDecl *InheritedCtor = nullptr, 6312 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6313 // If we're inheriting a constructor, see if we need to call it for this base 6314 // class. 6315 if (InheritedCtor) { 6316 assert(CSM == Sema::CXXDefaultConstructor); 6317 auto BaseCtor = 6318 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6319 if (BaseCtor) 6320 return BaseCtor->isConstexpr(); 6321 } 6322 6323 if (CSM == Sema::CXXDefaultConstructor) 6324 return ClassDecl->hasConstexprDefaultConstructor(); 6325 6326 Sema::SpecialMemberOverloadResult SMOR = 6327 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6328 if (!SMOR.getMethod()) 6329 // A constructor we wouldn't select can't be "involved in initializing" 6330 // anything. 6331 return true; 6332 return SMOR.getMethod()->isConstexpr(); 6333 } 6334 6335 /// Determine whether the specified special member function would be constexpr 6336 /// if it were implicitly defined. 6337 static bool defaultedSpecialMemberIsConstexpr( 6338 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6339 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6340 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6341 if (!S.getLangOpts().CPlusPlus11) 6342 return false; 6343 6344 // C++11 [dcl.constexpr]p4: 6345 // In the definition of a constexpr constructor [...] 6346 bool Ctor = true; 6347 switch (CSM) { 6348 case Sema::CXXDefaultConstructor: 6349 if (Inherited) 6350 break; 6351 // Since default constructor lookup is essentially trivial (and cannot 6352 // involve, for instance, template instantiation), we compute whether a 6353 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6354 // 6355 // This is important for performance; we need to know whether the default 6356 // constructor is constexpr to determine whether the type is a literal type. 6357 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6358 6359 case Sema::CXXCopyConstructor: 6360 case Sema::CXXMoveConstructor: 6361 // For copy or move constructors, we need to perform overload resolution. 6362 break; 6363 6364 case Sema::CXXCopyAssignment: 6365 case Sema::CXXMoveAssignment: 6366 if (!S.getLangOpts().CPlusPlus14) 6367 return false; 6368 // In C++1y, we need to perform overload resolution. 6369 Ctor = false; 6370 break; 6371 6372 case Sema::CXXDestructor: 6373 case Sema::CXXInvalid: 6374 return false; 6375 } 6376 6377 // -- if the class is a non-empty union, or for each non-empty anonymous 6378 // union member of a non-union class, exactly one non-static data member 6379 // shall be initialized; [DR1359] 6380 // 6381 // If we squint, this is guaranteed, since exactly one non-static data member 6382 // will be initialized (if the constructor isn't deleted), we just don't know 6383 // which one. 6384 if (Ctor && ClassDecl->isUnion()) 6385 return CSM == Sema::CXXDefaultConstructor 6386 ? ClassDecl->hasInClassInitializer() || 6387 !ClassDecl->hasVariantMembers() 6388 : true; 6389 6390 // -- the class shall not have any virtual base classes; 6391 if (Ctor && ClassDecl->getNumVBases()) 6392 return false; 6393 6394 // C++1y [class.copy]p26: 6395 // -- [the class] is a literal type, and 6396 if (!Ctor && !ClassDecl->isLiteral()) 6397 return false; 6398 6399 // -- every constructor involved in initializing [...] base class 6400 // sub-objects shall be a constexpr constructor; 6401 // -- the assignment operator selected to copy/move each direct base 6402 // class is a constexpr function, and 6403 for (const auto &B : ClassDecl->bases()) { 6404 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6405 if (!BaseType) continue; 6406 6407 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6408 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6409 InheritedCtor, Inherited)) 6410 return false; 6411 } 6412 6413 // -- every constructor involved in initializing non-static data members 6414 // [...] shall be a constexpr constructor; 6415 // -- every non-static data member and base class sub-object shall be 6416 // initialized 6417 // -- for each non-static data member of X that is of class type (or array 6418 // thereof), the assignment operator selected to copy/move that member is 6419 // a constexpr function 6420 for (const auto *F : ClassDecl->fields()) { 6421 if (F->isInvalidDecl()) 6422 continue; 6423 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6424 continue; 6425 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6426 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6427 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6428 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6429 BaseType.getCVRQualifiers(), 6430 ConstArg && !F->isMutable())) 6431 return false; 6432 } else if (CSM == Sema::CXXDefaultConstructor) { 6433 return false; 6434 } 6435 } 6436 6437 // All OK, it's constexpr! 6438 return true; 6439 } 6440 6441 static Sema::ImplicitExceptionSpecification 6442 ComputeDefaultedSpecialMemberExceptionSpec( 6443 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6444 Sema::InheritedConstructorInfo *ICI); 6445 6446 static Sema::ImplicitExceptionSpecification 6447 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6448 auto CSM = S.getSpecialMember(MD); 6449 if (CSM != Sema::CXXInvalid) 6450 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6451 6452 auto *CD = cast<CXXConstructorDecl>(MD); 6453 assert(CD->getInheritedConstructor() && 6454 "only special members have implicit exception specs"); 6455 Sema::InheritedConstructorInfo ICI( 6456 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6457 return ComputeDefaultedSpecialMemberExceptionSpec( 6458 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6459 } 6460 6461 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6462 CXXMethodDecl *MD) { 6463 FunctionProtoType::ExtProtoInfo EPI; 6464 6465 // Build an exception specification pointing back at this member. 6466 EPI.ExceptionSpec.Type = EST_Unevaluated; 6467 EPI.ExceptionSpec.SourceDecl = MD; 6468 6469 // Set the calling convention to the default for C++ instance methods. 6470 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6471 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6472 /*IsCXXMethod=*/true)); 6473 return EPI; 6474 } 6475 6476 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6477 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6478 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6479 return; 6480 6481 // Evaluate the exception specification. 6482 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6483 auto ESI = IES.getExceptionSpec(); 6484 6485 // Update the type of the special member to use it. 6486 UpdateExceptionSpec(MD, ESI); 6487 6488 // A user-provided destructor can be defined outside the class. When that 6489 // happens, be sure to update the exception specification on both 6490 // declarations. 6491 const FunctionProtoType *CanonicalFPT = 6492 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6493 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6494 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6495 } 6496 6497 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6498 CXXRecordDecl *RD = MD->getParent(); 6499 CXXSpecialMember CSM = getSpecialMember(MD); 6500 6501 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6502 "not an explicitly-defaulted special member"); 6503 6504 // Whether this was the first-declared instance of the constructor. 6505 // This affects whether we implicitly add an exception spec and constexpr. 6506 bool First = MD == MD->getCanonicalDecl(); 6507 6508 bool HadError = false; 6509 6510 // C++11 [dcl.fct.def.default]p1: 6511 // A function that is explicitly defaulted shall 6512 // -- be a special member function (checked elsewhere), 6513 // -- have the same type (except for ref-qualifiers, and except that a 6514 // copy operation can take a non-const reference) as an implicit 6515 // declaration, and 6516 // -- not have default arguments. 6517 // C++2a changes the second bullet to instead delete the function if it's 6518 // defaulted on its first declaration, unless it's "an assignment operator, 6519 // and its return type differs or its parameter type is not a reference". 6520 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6521 bool ShouldDeleteForTypeMismatch = false; 6522 unsigned ExpectedParams = 1; 6523 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6524 ExpectedParams = 0; 6525 if (MD->getNumParams() != ExpectedParams) { 6526 // This checks for default arguments: a copy or move constructor with a 6527 // default argument is classified as a default constructor, and assignment 6528 // operations and destructors can't have default arguments. 6529 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6530 << CSM << MD->getSourceRange(); 6531 HadError = true; 6532 } else if (MD->isVariadic()) { 6533 if (DeleteOnTypeMismatch) 6534 ShouldDeleteForTypeMismatch = true; 6535 else { 6536 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6537 << CSM << MD->getSourceRange(); 6538 HadError = true; 6539 } 6540 } 6541 6542 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6543 6544 bool CanHaveConstParam = false; 6545 if (CSM == CXXCopyConstructor) 6546 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6547 else if (CSM == CXXCopyAssignment) 6548 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6549 6550 QualType ReturnType = Context.VoidTy; 6551 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6552 // Check for return type matching. 6553 ReturnType = Type->getReturnType(); 6554 6555 QualType DeclType = Context.getTypeDeclType(RD); 6556 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getTypeQualifiers().getAddressSpace()); 6557 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 6558 6559 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6560 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6561 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6562 HadError = true; 6563 } 6564 6565 // A defaulted special member cannot have cv-qualifiers. 6566 if (Type->getTypeQuals().hasConst() || Type->getTypeQuals().hasVolatile()) { 6567 if (DeleteOnTypeMismatch) 6568 ShouldDeleteForTypeMismatch = true; 6569 else { 6570 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6571 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6572 HadError = true; 6573 } 6574 } 6575 } 6576 6577 // Check for parameter type matching. 6578 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6579 bool HasConstParam = false; 6580 if (ExpectedParams && ArgType->isReferenceType()) { 6581 // Argument must be reference to possibly-const T. 6582 QualType ReferentType = ArgType->getPointeeType(); 6583 HasConstParam = ReferentType.isConstQualified(); 6584 6585 if (ReferentType.isVolatileQualified()) { 6586 if (DeleteOnTypeMismatch) 6587 ShouldDeleteForTypeMismatch = true; 6588 else { 6589 Diag(MD->getLocation(), 6590 diag::err_defaulted_special_member_volatile_param) << CSM; 6591 HadError = true; 6592 } 6593 } 6594 6595 if (HasConstParam && !CanHaveConstParam) { 6596 if (DeleteOnTypeMismatch) 6597 ShouldDeleteForTypeMismatch = true; 6598 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6599 Diag(MD->getLocation(), 6600 diag::err_defaulted_special_member_copy_const_param) 6601 << (CSM == CXXCopyAssignment); 6602 // FIXME: Explain why this special member can't be const. 6603 HadError = true; 6604 } else { 6605 Diag(MD->getLocation(), 6606 diag::err_defaulted_special_member_move_const_param) 6607 << (CSM == CXXMoveAssignment); 6608 HadError = true; 6609 } 6610 } 6611 } else if (ExpectedParams) { 6612 // A copy assignment operator can take its argument by value, but a 6613 // defaulted one cannot. 6614 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6615 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6616 HadError = true; 6617 } 6618 6619 // C++11 [dcl.fct.def.default]p2: 6620 // An explicitly-defaulted function may be declared constexpr only if it 6621 // would have been implicitly declared as constexpr, 6622 // Do not apply this rule to members of class templates, since core issue 1358 6623 // makes such functions always instantiate to constexpr functions. For 6624 // functions which cannot be constexpr (for non-constructors in C++11 and for 6625 // destructors in C++1y), this is checked elsewhere. 6626 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6627 HasConstParam); 6628 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6629 : isa<CXXConstructorDecl>(MD)) && 6630 MD->isConstexpr() && !Constexpr && 6631 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6632 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM; 6633 // FIXME: Explain why the special member can't be constexpr. 6634 HadError = true; 6635 } 6636 6637 // and may have an explicit exception-specification only if it is compatible 6638 // with the exception-specification on the implicit declaration. 6639 if (Type->hasExceptionSpec()) { 6640 // Delay the check if this is the first declaration of the special member, 6641 // since we may not have parsed some necessary in-class initializers yet. 6642 if (First) { 6643 // If the exception specification needs to be instantiated, do so now, 6644 // before we clobber it with an EST_Unevaluated specification below. 6645 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6646 InstantiateExceptionSpec(MD->getBeginLoc(), MD); 6647 Type = MD->getType()->getAs<FunctionProtoType>(); 6648 } 6649 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6650 } else 6651 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6652 } 6653 6654 // If a function is explicitly defaulted on its first declaration, 6655 if (First) { 6656 // -- it is implicitly considered to be constexpr if the implicit 6657 // definition would be, 6658 MD->setConstexpr(Constexpr); 6659 6660 // -- it is implicitly considered to have the same exception-specification 6661 // as if it had been implicitly declared, 6662 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6663 EPI.ExceptionSpec.Type = EST_Unevaluated; 6664 EPI.ExceptionSpec.SourceDecl = MD; 6665 MD->setType(Context.getFunctionType(ReturnType, 6666 llvm::makeArrayRef(&ArgType, 6667 ExpectedParams), 6668 EPI)); 6669 } 6670 6671 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 6672 if (First) { 6673 SetDeclDeleted(MD, MD->getLocation()); 6674 if (!inTemplateInstantiation() && !HadError) { 6675 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 6676 if (ShouldDeleteForTypeMismatch) { 6677 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 6678 } else { 6679 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6680 } 6681 } 6682 if (ShouldDeleteForTypeMismatch && !HadError) { 6683 Diag(MD->getLocation(), 6684 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 6685 } 6686 } else { 6687 // C++11 [dcl.fct.def.default]p4: 6688 // [For a] user-provided explicitly-defaulted function [...] if such a 6689 // function is implicitly defined as deleted, the program is ill-formed. 6690 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6691 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 6692 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6693 HadError = true; 6694 } 6695 } 6696 6697 if (HadError) 6698 MD->setInvalidDecl(); 6699 } 6700 6701 /// Check whether the exception specification provided for an 6702 /// explicitly-defaulted special member matches the exception specification 6703 /// that would have been generated for an implicit special member, per 6704 /// C++11 [dcl.fct.def.default]p2. 6705 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6706 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6707 // If the exception specification was explicitly specified but hadn't been 6708 // parsed when the method was defaulted, grab it now. 6709 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6710 SpecifiedType = 6711 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6712 6713 // Compute the implicit exception specification. 6714 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6715 /*IsCXXMethod=*/true); 6716 FunctionProtoType::ExtProtoInfo EPI(CC); 6717 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6718 EPI.ExceptionSpec = IES.getExceptionSpec(); 6719 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6720 Context.getFunctionType(Context.VoidTy, None, EPI)); 6721 6722 // Ensure that it matches. 6723 CheckEquivalentExceptionSpec( 6724 PDiag(diag::err_incorrect_defaulted_exception_spec) 6725 << getSpecialMember(MD), PDiag(), 6726 ImplicitType, SourceLocation(), 6727 SpecifiedType, MD->getLocation()); 6728 } 6729 6730 void Sema::CheckDelayedMemberExceptionSpecs() { 6731 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 6732 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 6733 decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted; 6734 6735 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 6736 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 6737 std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs); 6738 6739 // Perform any deferred checking of exception specifications for virtual 6740 // destructors. 6741 for (auto &Check : Overriding) 6742 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6743 6744 // Perform any deferred checking of exception specifications for befriended 6745 // special members. 6746 for (auto &Check : Equivalent) 6747 CheckEquivalentExceptionSpec(Check.second, Check.first); 6748 6749 // Check that any explicitly-defaulted methods have exception specifications 6750 // compatible with their implicit exception specifications. 6751 for (auto &Spec : Defaulted) 6752 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6753 } 6754 6755 namespace { 6756 /// CRTP base class for visiting operations performed by a special member 6757 /// function (or inherited constructor). 6758 template<typename Derived> 6759 struct SpecialMemberVisitor { 6760 Sema &S; 6761 CXXMethodDecl *MD; 6762 Sema::CXXSpecialMember CSM; 6763 Sema::InheritedConstructorInfo *ICI; 6764 6765 // Properties of the special member, computed for convenience. 6766 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6767 6768 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6769 Sema::InheritedConstructorInfo *ICI) 6770 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6771 switch (CSM) { 6772 case Sema::CXXDefaultConstructor: 6773 case Sema::CXXCopyConstructor: 6774 case Sema::CXXMoveConstructor: 6775 IsConstructor = true; 6776 break; 6777 case Sema::CXXCopyAssignment: 6778 case Sema::CXXMoveAssignment: 6779 IsAssignment = true; 6780 break; 6781 case Sema::CXXDestructor: 6782 break; 6783 case Sema::CXXInvalid: 6784 llvm_unreachable("invalid special member kind"); 6785 } 6786 6787 if (MD->getNumParams()) { 6788 if (const ReferenceType *RT = 6789 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6790 ConstArg = RT->getPointeeType().isConstQualified(); 6791 } 6792 } 6793 6794 Derived &getDerived() { return static_cast<Derived&>(*this); } 6795 6796 /// Is this a "move" special member? 6797 bool isMove() const { 6798 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6799 } 6800 6801 /// Look up the corresponding special member in the given class. 6802 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6803 unsigned Quals, bool IsMutable) { 6804 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6805 ConstArg && !IsMutable); 6806 } 6807 6808 /// Look up the constructor for the specified base class to see if it's 6809 /// overridden due to this being an inherited constructor. 6810 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6811 if (!ICI) 6812 return {}; 6813 assert(CSM == Sema::CXXDefaultConstructor); 6814 auto *BaseCtor = 6815 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6816 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6817 return MD; 6818 return {}; 6819 } 6820 6821 /// A base or member subobject. 6822 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6823 6824 /// Get the location to use for a subobject in diagnostics. 6825 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6826 // FIXME: For an indirect virtual base, the direct base leading to 6827 // the indirect virtual base would be a more useful choice. 6828 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6829 return B->getBaseTypeLoc(); 6830 else 6831 return Subobj.get<FieldDecl*>()->getLocation(); 6832 } 6833 6834 enum BasesToVisit { 6835 /// Visit all non-virtual (direct) bases. 6836 VisitNonVirtualBases, 6837 /// Visit all direct bases, virtual or not. 6838 VisitDirectBases, 6839 /// Visit all non-virtual bases, and all virtual bases if the class 6840 /// is not abstract. 6841 VisitPotentiallyConstructedBases, 6842 /// Visit all direct or virtual bases. 6843 VisitAllBases 6844 }; 6845 6846 // Visit the bases and members of the class. 6847 bool visit(BasesToVisit Bases) { 6848 CXXRecordDecl *RD = MD->getParent(); 6849 6850 if (Bases == VisitPotentiallyConstructedBases) 6851 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6852 6853 for (auto &B : RD->bases()) 6854 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6855 getDerived().visitBase(&B)) 6856 return true; 6857 6858 if (Bases == VisitAllBases) 6859 for (auto &B : RD->vbases()) 6860 if (getDerived().visitBase(&B)) 6861 return true; 6862 6863 for (auto *F : RD->fields()) 6864 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6865 getDerived().visitField(F)) 6866 return true; 6867 6868 return false; 6869 } 6870 }; 6871 } 6872 6873 namespace { 6874 struct SpecialMemberDeletionInfo 6875 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6876 bool Diagnose; 6877 6878 SourceLocation Loc; 6879 6880 bool AllFieldsAreConst; 6881 6882 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6883 Sema::CXXSpecialMember CSM, 6884 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6885 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6886 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6887 6888 bool inUnion() const { return MD->getParent()->isUnion(); } 6889 6890 Sema::CXXSpecialMember getEffectiveCSM() { 6891 return ICI ? Sema::CXXInvalid : CSM; 6892 } 6893 6894 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6895 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6896 6897 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6898 bool shouldDeleteForField(FieldDecl *FD); 6899 bool shouldDeleteForAllConstMembers(); 6900 6901 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6902 unsigned Quals); 6903 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6904 Sema::SpecialMemberOverloadResult SMOR, 6905 bool IsDtorCallInCtor); 6906 6907 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6908 }; 6909 } 6910 6911 /// Is the given special member inaccessible when used on the given 6912 /// sub-object. 6913 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6914 CXXMethodDecl *target) { 6915 /// If we're operating on a base class, the object type is the 6916 /// type of this special member. 6917 QualType objectTy; 6918 AccessSpecifier access = target->getAccess(); 6919 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6920 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6921 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6922 6923 // If we're operating on a field, the object type is the type of the field. 6924 } else { 6925 objectTy = S.Context.getTypeDeclType(target->getParent()); 6926 } 6927 6928 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6929 } 6930 6931 /// Check whether we should delete a special member due to the implicit 6932 /// definition containing a call to a special member of a subobject. 6933 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6934 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6935 bool IsDtorCallInCtor) { 6936 CXXMethodDecl *Decl = SMOR.getMethod(); 6937 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6938 6939 int DiagKind = -1; 6940 6941 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6942 DiagKind = !Decl ? 0 : 1; 6943 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6944 DiagKind = 2; 6945 else if (!isAccessible(Subobj, Decl)) 6946 DiagKind = 3; 6947 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6948 !Decl->isTrivial()) { 6949 // A member of a union must have a trivial corresponding special member. 6950 // As a weird special case, a destructor call from a union's constructor 6951 // must be accessible and non-deleted, but need not be trivial. Such a 6952 // destructor is never actually called, but is semantically checked as 6953 // if it were. 6954 DiagKind = 4; 6955 } 6956 6957 if (DiagKind == -1) 6958 return false; 6959 6960 if (Diagnose) { 6961 if (Field) { 6962 S.Diag(Field->getLocation(), 6963 diag::note_deleted_special_member_class_subobject) 6964 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6965 << Field << DiagKind << IsDtorCallInCtor; 6966 } else { 6967 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6968 S.Diag(Base->getBeginLoc(), 6969 diag::note_deleted_special_member_class_subobject) 6970 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 6971 << Base->getType() << DiagKind << IsDtorCallInCtor; 6972 } 6973 6974 if (DiagKind == 1) 6975 S.NoteDeletedFunction(Decl); 6976 // FIXME: Explain inaccessibility if DiagKind == 3. 6977 } 6978 6979 return true; 6980 } 6981 6982 /// Check whether we should delete a special member function due to having a 6983 /// direct or virtual base class or non-static data member of class type M. 6984 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6985 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6986 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6987 bool IsMutable = Field && Field->isMutable(); 6988 6989 // C++11 [class.ctor]p5: 6990 // -- any direct or virtual base class, or non-static data member with no 6991 // brace-or-equal-initializer, has class type M (or array thereof) and 6992 // either M has no default constructor or overload resolution as applied 6993 // to M's default constructor results in an ambiguity or in a function 6994 // that is deleted or inaccessible 6995 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6996 // -- a direct or virtual base class B that cannot be copied/moved because 6997 // overload resolution, as applied to B's corresponding special member, 6998 // results in an ambiguity or a function that is deleted or inaccessible 6999 // from the defaulted special member 7000 // C++11 [class.dtor]p5: 7001 // -- any direct or virtual base class [...] has a type with a destructor 7002 // that is deleted or inaccessible 7003 if (!(CSM == Sema::CXXDefaultConstructor && 7004 Field && Field->hasInClassInitializer()) && 7005 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 7006 false)) 7007 return true; 7008 7009 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 7010 // -- any direct or virtual base class or non-static data member has a 7011 // type with a destructor that is deleted or inaccessible 7012 if (IsConstructor) { 7013 Sema::SpecialMemberOverloadResult SMOR = 7014 S.LookupSpecialMember(Class, Sema::CXXDestructor, 7015 false, false, false, false, false); 7016 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 7017 return true; 7018 } 7019 7020 return false; 7021 } 7022 7023 /// Check whether we should delete a special member function due to the class 7024 /// having a particular direct or virtual base class. 7025 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 7026 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 7027 // If program is correct, BaseClass cannot be null, but if it is, the error 7028 // must be reported elsewhere. 7029 if (!BaseClass) 7030 return false; 7031 // If we have an inheriting constructor, check whether we're calling an 7032 // inherited constructor instead of a default constructor. 7033 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 7034 if (auto *BaseCtor = SMOR.getMethod()) { 7035 // Note that we do not check access along this path; other than that, 7036 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 7037 // FIXME: Check that the base has a usable destructor! Sink this into 7038 // shouldDeleteForClassSubobject. 7039 if (BaseCtor->isDeleted() && Diagnose) { 7040 S.Diag(Base->getBeginLoc(), 7041 diag::note_deleted_special_member_class_subobject) 7042 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7043 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false; 7044 S.NoteDeletedFunction(BaseCtor); 7045 } 7046 return BaseCtor->isDeleted(); 7047 } 7048 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 7049 } 7050 7051 /// Check whether we should delete a special member function due to the class 7052 /// having a particular non-static data member. 7053 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 7054 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 7055 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 7056 7057 if (CSM == Sema::CXXDefaultConstructor) { 7058 // For a default constructor, all references must be initialized in-class 7059 // and, if a union, it must have a non-const member. 7060 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 7061 if (Diagnose) 7062 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7063 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 7064 return true; 7065 } 7066 // C++11 [class.ctor]p5: any non-variant non-static data member of 7067 // const-qualified type (or array thereof) with no 7068 // brace-or-equal-initializer does not have a user-provided default 7069 // constructor. 7070 if (!inUnion() && FieldType.isConstQualified() && 7071 !FD->hasInClassInitializer() && 7072 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 7073 if (Diagnose) 7074 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7075 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 7076 return true; 7077 } 7078 7079 if (inUnion() && !FieldType.isConstQualified()) 7080 AllFieldsAreConst = false; 7081 } else if (CSM == Sema::CXXCopyConstructor) { 7082 // For a copy constructor, data members must not be of rvalue reference 7083 // type. 7084 if (FieldType->isRValueReferenceType()) { 7085 if (Diagnose) 7086 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 7087 << MD->getParent() << FD << FieldType; 7088 return true; 7089 } 7090 } else if (IsAssignment) { 7091 // For an assignment operator, data members must not be of reference type. 7092 if (FieldType->isReferenceType()) { 7093 if (Diagnose) 7094 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7095 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 7096 return true; 7097 } 7098 if (!FieldRecord && FieldType.isConstQualified()) { 7099 // C++11 [class.copy]p23: 7100 // -- a non-static data member of const non-class type (or array thereof) 7101 if (Diagnose) 7102 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7103 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 7104 return true; 7105 } 7106 } 7107 7108 if (FieldRecord) { 7109 // Some additional restrictions exist on the variant members. 7110 if (!inUnion() && FieldRecord->isUnion() && 7111 FieldRecord->isAnonymousStructOrUnion()) { 7112 bool AllVariantFieldsAreConst = true; 7113 7114 // FIXME: Handle anonymous unions declared within anonymous unions. 7115 for (auto *UI : FieldRecord->fields()) { 7116 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7117 7118 if (!UnionFieldType.isConstQualified()) 7119 AllVariantFieldsAreConst = false; 7120 7121 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7122 if (UnionFieldRecord && 7123 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7124 UnionFieldType.getCVRQualifiers())) 7125 return true; 7126 } 7127 7128 // At least one member in each anonymous union must be non-const 7129 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7130 !FieldRecord->field_empty()) { 7131 if (Diagnose) 7132 S.Diag(FieldRecord->getLocation(), 7133 diag::note_deleted_default_ctor_all_const) 7134 << !!ICI << MD->getParent() << /*anonymous union*/1; 7135 return true; 7136 } 7137 7138 // Don't check the implicit member of the anonymous union type. 7139 // This is technically non-conformant, but sanity demands it. 7140 return false; 7141 } 7142 7143 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7144 FieldType.getCVRQualifiers())) 7145 return true; 7146 } 7147 7148 return false; 7149 } 7150 7151 /// C++11 [class.ctor] p5: 7152 /// A defaulted default constructor for a class X is defined as deleted if 7153 /// X is a union and all of its variant members are of const-qualified type. 7154 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7155 // This is a silly definition, because it gives an empty union a deleted 7156 // default constructor. Don't do that. 7157 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7158 bool AnyFields = false; 7159 for (auto *F : MD->getParent()->fields()) 7160 if ((AnyFields = !F->isUnnamedBitfield())) 7161 break; 7162 if (!AnyFields) 7163 return false; 7164 if (Diagnose) 7165 S.Diag(MD->getParent()->getLocation(), 7166 diag::note_deleted_default_ctor_all_const) 7167 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7168 return true; 7169 } 7170 return false; 7171 } 7172 7173 /// Determine whether a defaulted special member function should be defined as 7174 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7175 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7176 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7177 InheritedConstructorInfo *ICI, 7178 bool Diagnose) { 7179 if (MD->isInvalidDecl()) 7180 return false; 7181 CXXRecordDecl *RD = MD->getParent(); 7182 assert(!RD->isDependentType() && "do deletion after instantiation"); 7183 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7184 return false; 7185 7186 // C++11 [expr.lambda.prim]p19: 7187 // The closure type associated with a lambda-expression has a 7188 // deleted (8.4.3) default constructor and a deleted copy 7189 // assignment operator. 7190 // C++2a adds back these operators if the lambda has no capture-default. 7191 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 7192 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7193 if (Diagnose) 7194 Diag(RD->getLocation(), diag::note_lambda_decl); 7195 return true; 7196 } 7197 7198 // For an anonymous struct or union, the copy and assignment special members 7199 // will never be used, so skip the check. For an anonymous union declared at 7200 // namespace scope, the constructor and destructor are used. 7201 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7202 RD->isAnonymousStructOrUnion()) 7203 return false; 7204 7205 // C++11 [class.copy]p7, p18: 7206 // If the class definition declares a move constructor or move assignment 7207 // operator, an implicitly declared copy constructor or copy assignment 7208 // operator is defined as deleted. 7209 if (MD->isImplicit() && 7210 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7211 CXXMethodDecl *UserDeclaredMove = nullptr; 7212 7213 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7214 // deletion of the corresponding copy operation, not both copy operations. 7215 // MSVC 2015 has adopted the standards conforming behavior. 7216 bool DeletesOnlyMatchingCopy = 7217 getLangOpts().MSVCCompat && 7218 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7219 7220 if (RD->hasUserDeclaredMoveConstructor() && 7221 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7222 if (!Diagnose) return true; 7223 7224 // Find any user-declared move constructor. 7225 for (auto *I : RD->ctors()) { 7226 if (I->isMoveConstructor()) { 7227 UserDeclaredMove = I; 7228 break; 7229 } 7230 } 7231 assert(UserDeclaredMove); 7232 } else if (RD->hasUserDeclaredMoveAssignment() && 7233 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7234 if (!Diagnose) return true; 7235 7236 // Find any user-declared move assignment operator. 7237 for (auto *I : RD->methods()) { 7238 if (I->isMoveAssignmentOperator()) { 7239 UserDeclaredMove = I; 7240 break; 7241 } 7242 } 7243 assert(UserDeclaredMove); 7244 } 7245 7246 if (UserDeclaredMove) { 7247 Diag(UserDeclaredMove->getLocation(), 7248 diag::note_deleted_copy_user_declared_move) 7249 << (CSM == CXXCopyAssignment) << RD 7250 << UserDeclaredMove->isMoveAssignmentOperator(); 7251 return true; 7252 } 7253 } 7254 7255 // Do access control from the special member function 7256 ContextRAII MethodContext(*this, MD); 7257 7258 // C++11 [class.dtor]p5: 7259 // -- for a virtual destructor, lookup of the non-array deallocation function 7260 // results in an ambiguity or in a function that is deleted or inaccessible 7261 if (CSM == CXXDestructor && MD->isVirtual()) { 7262 FunctionDecl *OperatorDelete = nullptr; 7263 DeclarationName Name = 7264 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7265 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7266 OperatorDelete, /*Diagnose*/false)) { 7267 if (Diagnose) 7268 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7269 return true; 7270 } 7271 } 7272 7273 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7274 7275 // Per DR1611, do not consider virtual bases of constructors of abstract 7276 // classes, since we are not going to construct them. 7277 // Per DR1658, do not consider virtual bases of destructors of abstract 7278 // classes either. 7279 // Per DR2180, for assignment operators we only assign (and thus only 7280 // consider) direct bases. 7281 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7282 : SMI.VisitPotentiallyConstructedBases)) 7283 return true; 7284 7285 if (SMI.shouldDeleteForAllConstMembers()) 7286 return true; 7287 7288 if (getLangOpts().CUDA) { 7289 // We should delete the special member in CUDA mode if target inference 7290 // failed. 7291 // For inherited constructors (non-null ICI), CSM may be passed so that MD 7292 // is treated as certain special member, which may not reflect what special 7293 // member MD really is. However inferCUDATargetForImplicitSpecialMember 7294 // expects CSM to match MD, therefore recalculate CSM. 7295 assert(ICI || CSM == getSpecialMember(MD)); 7296 auto RealCSM = CSM; 7297 if (ICI) 7298 RealCSM = getSpecialMember(MD); 7299 7300 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 7301 SMI.ConstArg, Diagnose); 7302 } 7303 7304 return false; 7305 } 7306 7307 /// Perform lookup for a special member of the specified kind, and determine 7308 /// whether it is trivial. If the triviality can be determined without the 7309 /// lookup, skip it. This is intended for use when determining whether a 7310 /// special member of a containing object is trivial, and thus does not ever 7311 /// perform overload resolution for default constructors. 7312 /// 7313 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7314 /// member that was most likely to be intended to be trivial, if any. 7315 /// 7316 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7317 /// determine whether the special member is trivial. 7318 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7319 Sema::CXXSpecialMember CSM, unsigned Quals, 7320 bool ConstRHS, 7321 Sema::TrivialABIHandling TAH, 7322 CXXMethodDecl **Selected) { 7323 if (Selected) 7324 *Selected = nullptr; 7325 7326 switch (CSM) { 7327 case Sema::CXXInvalid: 7328 llvm_unreachable("not a special member"); 7329 7330 case Sema::CXXDefaultConstructor: 7331 // C++11 [class.ctor]p5: 7332 // A default constructor is trivial if: 7333 // - all the [direct subobjects] have trivial default constructors 7334 // 7335 // Note, no overload resolution is performed in this case. 7336 if (RD->hasTrivialDefaultConstructor()) 7337 return true; 7338 7339 if (Selected) { 7340 // If there's a default constructor which could have been trivial, dig it 7341 // out. Otherwise, if there's any user-provided default constructor, point 7342 // to that as an example of why there's not a trivial one. 7343 CXXConstructorDecl *DefCtor = nullptr; 7344 if (RD->needsImplicitDefaultConstructor()) 7345 S.DeclareImplicitDefaultConstructor(RD); 7346 for (auto *CI : RD->ctors()) { 7347 if (!CI->isDefaultConstructor()) 7348 continue; 7349 DefCtor = CI; 7350 if (!DefCtor->isUserProvided()) 7351 break; 7352 } 7353 7354 *Selected = DefCtor; 7355 } 7356 7357 return false; 7358 7359 case Sema::CXXDestructor: 7360 // C++11 [class.dtor]p5: 7361 // A destructor is trivial if: 7362 // - all the direct [subobjects] have trivial destructors 7363 if (RD->hasTrivialDestructor() || 7364 (TAH == Sema::TAH_ConsiderTrivialABI && 7365 RD->hasTrivialDestructorForCall())) 7366 return true; 7367 7368 if (Selected) { 7369 if (RD->needsImplicitDestructor()) 7370 S.DeclareImplicitDestructor(RD); 7371 *Selected = RD->getDestructor(); 7372 } 7373 7374 return false; 7375 7376 case Sema::CXXCopyConstructor: 7377 // C++11 [class.copy]p12: 7378 // A copy constructor is trivial if: 7379 // - the constructor selected to copy each direct [subobject] is trivial 7380 if (RD->hasTrivialCopyConstructor() || 7381 (TAH == Sema::TAH_ConsiderTrivialABI && 7382 RD->hasTrivialCopyConstructorForCall())) { 7383 if (Quals == Qualifiers::Const) 7384 // We must either select the trivial copy constructor or reach an 7385 // ambiguity; no need to actually perform overload resolution. 7386 return true; 7387 } else if (!Selected) { 7388 return false; 7389 } 7390 // In C++98, we are not supposed to perform overload resolution here, but we 7391 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7392 // cases like B as having a non-trivial copy constructor: 7393 // struct A { template<typename T> A(T&); }; 7394 // struct B { mutable A a; }; 7395 goto NeedOverloadResolution; 7396 7397 case Sema::CXXCopyAssignment: 7398 // C++11 [class.copy]p25: 7399 // A copy assignment operator is trivial if: 7400 // - the assignment operator selected to copy each direct [subobject] is 7401 // trivial 7402 if (RD->hasTrivialCopyAssignment()) { 7403 if (Quals == Qualifiers::Const) 7404 return true; 7405 } else if (!Selected) { 7406 return false; 7407 } 7408 // In C++98, we are not supposed to perform overload resolution here, but we 7409 // treat that as a language defect. 7410 goto NeedOverloadResolution; 7411 7412 case Sema::CXXMoveConstructor: 7413 case Sema::CXXMoveAssignment: 7414 NeedOverloadResolution: 7415 Sema::SpecialMemberOverloadResult SMOR = 7416 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7417 7418 // The standard doesn't describe how to behave if the lookup is ambiguous. 7419 // We treat it as not making the member non-trivial, just like the standard 7420 // mandates for the default constructor. This should rarely matter, because 7421 // the member will also be deleted. 7422 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7423 return true; 7424 7425 if (!SMOR.getMethod()) { 7426 assert(SMOR.getKind() == 7427 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7428 return false; 7429 } 7430 7431 // We deliberately don't check if we found a deleted special member. We're 7432 // not supposed to! 7433 if (Selected) 7434 *Selected = SMOR.getMethod(); 7435 7436 if (TAH == Sema::TAH_ConsiderTrivialABI && 7437 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7438 return SMOR.getMethod()->isTrivialForCall(); 7439 return SMOR.getMethod()->isTrivial(); 7440 } 7441 7442 llvm_unreachable("unknown special method kind"); 7443 } 7444 7445 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7446 for (auto *CI : RD->ctors()) 7447 if (!CI->isImplicit()) 7448 return CI; 7449 7450 // Look for constructor templates. 7451 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7452 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7453 if (CXXConstructorDecl *CD = 7454 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7455 return CD; 7456 } 7457 7458 return nullptr; 7459 } 7460 7461 /// The kind of subobject we are checking for triviality. The values of this 7462 /// enumeration are used in diagnostics. 7463 enum TrivialSubobjectKind { 7464 /// The subobject is a base class. 7465 TSK_BaseClass, 7466 /// The subobject is a non-static data member. 7467 TSK_Field, 7468 /// The object is actually the complete object. 7469 TSK_CompleteObject 7470 }; 7471 7472 /// Check whether the special member selected for a given type would be trivial. 7473 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7474 QualType SubType, bool ConstRHS, 7475 Sema::CXXSpecialMember CSM, 7476 TrivialSubobjectKind Kind, 7477 Sema::TrivialABIHandling TAH, bool Diagnose) { 7478 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7479 if (!SubRD) 7480 return true; 7481 7482 CXXMethodDecl *Selected; 7483 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7484 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7485 return true; 7486 7487 if (Diagnose) { 7488 if (ConstRHS) 7489 SubType.addConst(); 7490 7491 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7492 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7493 << Kind << SubType.getUnqualifiedType(); 7494 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7495 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7496 } else if (!Selected) 7497 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7498 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7499 else if (Selected->isUserProvided()) { 7500 if (Kind == TSK_CompleteObject) 7501 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7502 << Kind << SubType.getUnqualifiedType() << CSM; 7503 else { 7504 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7505 << Kind << SubType.getUnqualifiedType() << CSM; 7506 S.Diag(Selected->getLocation(), diag::note_declared_at); 7507 } 7508 } else { 7509 if (Kind != TSK_CompleteObject) 7510 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7511 << Kind << SubType.getUnqualifiedType() << CSM; 7512 7513 // Explain why the defaulted or deleted special member isn't trivial. 7514 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7515 Diagnose); 7516 } 7517 } 7518 7519 return false; 7520 } 7521 7522 /// Check whether the members of a class type allow a special member to be 7523 /// trivial. 7524 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7525 Sema::CXXSpecialMember CSM, 7526 bool ConstArg, 7527 Sema::TrivialABIHandling TAH, 7528 bool Diagnose) { 7529 for (const auto *FI : RD->fields()) { 7530 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7531 continue; 7532 7533 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7534 7535 // Pretend anonymous struct or union members are members of this class. 7536 if (FI->isAnonymousStructOrUnion()) { 7537 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7538 CSM, ConstArg, TAH, Diagnose)) 7539 return false; 7540 continue; 7541 } 7542 7543 // C++11 [class.ctor]p5: 7544 // A default constructor is trivial if [...] 7545 // -- no non-static data member of its class has a 7546 // brace-or-equal-initializer 7547 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7548 if (Diagnose) 7549 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7550 return false; 7551 } 7552 7553 // Objective C ARC 4.3.5: 7554 // [...] nontrivally ownership-qualified types are [...] not trivially 7555 // default constructible, copy constructible, move constructible, copy 7556 // assignable, move assignable, or destructible [...] 7557 if (FieldType.hasNonTrivialObjCLifetime()) { 7558 if (Diagnose) 7559 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7560 << RD << FieldType.getObjCLifetime(); 7561 return false; 7562 } 7563 7564 bool ConstRHS = ConstArg && !FI->isMutable(); 7565 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7566 CSM, TSK_Field, TAH, Diagnose)) 7567 return false; 7568 } 7569 7570 return true; 7571 } 7572 7573 /// Diagnose why the specified class does not have a trivial special member of 7574 /// the given kind. 7575 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7576 QualType Ty = Context.getRecordType(RD); 7577 7578 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7579 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7580 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7581 /*Diagnose*/true); 7582 } 7583 7584 /// Determine whether a defaulted or deleted special member function is trivial, 7585 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7586 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7587 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7588 TrivialABIHandling TAH, bool Diagnose) { 7589 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7590 7591 CXXRecordDecl *RD = MD->getParent(); 7592 7593 bool ConstArg = false; 7594 7595 // C++11 [class.copy]p12, p25: [DR1593] 7596 // A [special member] is trivial if [...] its parameter-type-list is 7597 // equivalent to the parameter-type-list of an implicit declaration [...] 7598 switch (CSM) { 7599 case CXXDefaultConstructor: 7600 case CXXDestructor: 7601 // Trivial default constructors and destructors cannot have parameters. 7602 break; 7603 7604 case CXXCopyConstructor: 7605 case CXXCopyAssignment: { 7606 // Trivial copy operations always have const, non-volatile parameter types. 7607 ConstArg = true; 7608 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7609 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7610 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7611 if (Diagnose) 7612 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7613 << Param0->getSourceRange() << Param0->getType() 7614 << Context.getLValueReferenceType( 7615 Context.getRecordType(RD).withConst()); 7616 return false; 7617 } 7618 break; 7619 } 7620 7621 case CXXMoveConstructor: 7622 case CXXMoveAssignment: { 7623 // Trivial move operations always have non-cv-qualified parameters. 7624 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7625 const RValueReferenceType *RT = 7626 Param0->getType()->getAs<RValueReferenceType>(); 7627 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7628 if (Diagnose) 7629 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7630 << Param0->getSourceRange() << Param0->getType() 7631 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7632 return false; 7633 } 7634 break; 7635 } 7636 7637 case CXXInvalid: 7638 llvm_unreachable("not a special member"); 7639 } 7640 7641 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7642 if (Diagnose) 7643 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7644 diag::note_nontrivial_default_arg) 7645 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7646 return false; 7647 } 7648 if (MD->isVariadic()) { 7649 if (Diagnose) 7650 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7651 return false; 7652 } 7653 7654 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7655 // A copy/move [constructor or assignment operator] is trivial if 7656 // -- the [member] selected to copy/move each direct base class subobject 7657 // is trivial 7658 // 7659 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7660 // A [default constructor or destructor] is trivial if 7661 // -- all the direct base classes have trivial [default constructors or 7662 // destructors] 7663 for (const auto &BI : RD->bases()) 7664 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 7665 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7666 return false; 7667 7668 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7669 // A copy/move [constructor or assignment operator] for a class X is 7670 // trivial if 7671 // -- for each non-static data member of X that is of class type (or array 7672 // thereof), the constructor selected to copy/move that member is 7673 // trivial 7674 // 7675 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7676 // A [default constructor or destructor] is trivial if 7677 // -- for all of the non-static data members of its class that are of class 7678 // type (or array thereof), each such class has a trivial [default 7679 // constructor or destructor] 7680 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7681 return false; 7682 7683 // C++11 [class.dtor]p5: 7684 // A destructor is trivial if [...] 7685 // -- the destructor is not virtual 7686 if (CSM == CXXDestructor && MD->isVirtual()) { 7687 if (Diagnose) 7688 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7689 return false; 7690 } 7691 7692 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7693 // A [special member] for class X is trivial if [...] 7694 // -- class X has no virtual functions and no virtual base classes 7695 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7696 if (!Diagnose) 7697 return false; 7698 7699 if (RD->getNumVBases()) { 7700 // Check for virtual bases. We already know that the corresponding 7701 // member in all bases is trivial, so vbases must all be direct. 7702 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7703 assert(BS.isVirtual()); 7704 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 7705 return false; 7706 } 7707 7708 // Must have a virtual method. 7709 for (const auto *MI : RD->methods()) { 7710 if (MI->isVirtual()) { 7711 SourceLocation MLoc = MI->getBeginLoc(); 7712 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7713 return false; 7714 } 7715 } 7716 7717 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7718 } 7719 7720 // Looks like it's trivial! 7721 return true; 7722 } 7723 7724 namespace { 7725 struct FindHiddenVirtualMethod { 7726 Sema *S; 7727 CXXMethodDecl *Method; 7728 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7729 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7730 7731 private: 7732 /// Check whether any most overridden method from MD in Methods 7733 static bool CheckMostOverridenMethods( 7734 const CXXMethodDecl *MD, 7735 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7736 if (MD->size_overridden_methods() == 0) 7737 return Methods.count(MD->getCanonicalDecl()); 7738 for (const CXXMethodDecl *O : MD->overridden_methods()) 7739 if (CheckMostOverridenMethods(O, Methods)) 7740 return true; 7741 return false; 7742 } 7743 7744 public: 7745 /// Member lookup function that determines whether a given C++ 7746 /// method overloads virtual methods in a base class without overriding any, 7747 /// to be used with CXXRecordDecl::lookupInBases(). 7748 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7749 RecordDecl *BaseRecord = 7750 Specifier->getType()->getAs<RecordType>()->getDecl(); 7751 7752 DeclarationName Name = Method->getDeclName(); 7753 assert(Name.getNameKind() == DeclarationName::Identifier); 7754 7755 bool foundSameNameMethod = false; 7756 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7757 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7758 Path.Decls = Path.Decls.slice(1)) { 7759 NamedDecl *D = Path.Decls.front(); 7760 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7761 MD = MD->getCanonicalDecl(); 7762 foundSameNameMethod = true; 7763 // Interested only in hidden virtual methods. 7764 if (!MD->isVirtual()) 7765 continue; 7766 // If the method we are checking overrides a method from its base 7767 // don't warn about the other overloaded methods. Clang deviates from 7768 // GCC by only diagnosing overloads of inherited virtual functions that 7769 // do not override any other virtual functions in the base. GCC's 7770 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7771 // function from a base class. These cases may be better served by a 7772 // warning (not specific to virtual functions) on call sites when the 7773 // call would select a different function from the base class, were it 7774 // visible. 7775 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7776 if (!S->IsOverload(Method, MD, false)) 7777 return true; 7778 // Collect the overload only if its hidden. 7779 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7780 overloadedMethods.push_back(MD); 7781 } 7782 } 7783 7784 if (foundSameNameMethod) 7785 OverloadedMethods.append(overloadedMethods.begin(), 7786 overloadedMethods.end()); 7787 return foundSameNameMethod; 7788 } 7789 }; 7790 } // end anonymous namespace 7791 7792 /// Add the most overriden methods from MD to Methods 7793 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7794 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7795 if (MD->size_overridden_methods() == 0) 7796 Methods.insert(MD->getCanonicalDecl()); 7797 else 7798 for (const CXXMethodDecl *O : MD->overridden_methods()) 7799 AddMostOverridenMethods(O, Methods); 7800 } 7801 7802 /// Check if a method overloads virtual methods in a base class without 7803 /// overriding any. 7804 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7805 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7806 if (!MD->getDeclName().isIdentifier()) 7807 return; 7808 7809 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7810 /*bool RecordPaths=*/false, 7811 /*bool DetectVirtual=*/false); 7812 FindHiddenVirtualMethod FHVM; 7813 FHVM.Method = MD; 7814 FHVM.S = this; 7815 7816 // Keep the base methods that were overridden or introduced in the subclass 7817 // by 'using' in a set. A base method not in this set is hidden. 7818 CXXRecordDecl *DC = MD->getParent(); 7819 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7820 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7821 NamedDecl *ND = *I; 7822 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7823 ND = shad->getTargetDecl(); 7824 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7825 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7826 } 7827 7828 if (DC->lookupInBases(FHVM, Paths)) 7829 OverloadedMethods = FHVM.OverloadedMethods; 7830 } 7831 7832 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7833 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7834 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7835 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7836 PartialDiagnostic PD = PDiag( 7837 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7838 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7839 Diag(overloadedMD->getLocation(), PD); 7840 } 7841 } 7842 7843 /// Diagnose methods which overload virtual methods in a base class 7844 /// without overriding any. 7845 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7846 if (MD->isInvalidDecl()) 7847 return; 7848 7849 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7850 return; 7851 7852 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7853 FindHiddenVirtualMethods(MD, OverloadedMethods); 7854 if (!OverloadedMethods.empty()) { 7855 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7856 << MD << (OverloadedMethods.size() > 1); 7857 7858 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7859 } 7860 } 7861 7862 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 7863 auto PrintDiagAndRemoveAttr = [&]() { 7864 // No diagnostics if this is a template instantiation. 7865 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 7866 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 7867 diag::ext_cannot_use_trivial_abi) << &RD; 7868 RD.dropAttr<TrivialABIAttr>(); 7869 }; 7870 7871 // Ill-formed if the struct has virtual functions. 7872 if (RD.isPolymorphic()) { 7873 PrintDiagAndRemoveAttr(); 7874 return; 7875 } 7876 7877 for (const auto &B : RD.bases()) { 7878 // Ill-formed if the base class is non-trivial for the purpose of calls or a 7879 // virtual base. 7880 if ((!B.getType()->isDependentType() && 7881 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 7882 B.isVirtual()) { 7883 PrintDiagAndRemoveAttr(); 7884 return; 7885 } 7886 } 7887 7888 for (const auto *FD : RD.fields()) { 7889 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 7890 // non-trivial for the purpose of calls. 7891 QualType FT = FD->getType(); 7892 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 7893 PrintDiagAndRemoveAttr(); 7894 return; 7895 } 7896 7897 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 7898 if (!RT->isDependentType() && 7899 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 7900 PrintDiagAndRemoveAttr(); 7901 return; 7902 } 7903 } 7904 } 7905 7906 void Sema::ActOnFinishCXXMemberSpecification( 7907 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 7908 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 7909 if (!TagDecl) 7910 return; 7911 7912 AdjustDeclIfTemplate(TagDecl); 7913 7914 for (const ParsedAttr &AL : AttrList) { 7915 if (AL.getKind() != ParsedAttr::AT_Visibility) 7916 continue; 7917 AL.setInvalid(); 7918 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) 7919 << AL.getName(); 7920 } 7921 7922 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7923 // strict aliasing violation! 7924 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7925 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7926 7927 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); 7928 } 7929 7930 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7931 /// special functions, such as the default constructor, copy 7932 /// constructor, or destructor, to the given C++ class (C++ 7933 /// [special]p1). This routine can only be executed just before the 7934 /// definition of the class is complete. 7935 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7936 if (ClassDecl->needsImplicitDefaultConstructor()) { 7937 ++ASTContext::NumImplicitDefaultConstructors; 7938 7939 if (ClassDecl->hasInheritedConstructor()) 7940 DeclareImplicitDefaultConstructor(ClassDecl); 7941 } 7942 7943 if (ClassDecl->needsImplicitCopyConstructor()) { 7944 ++ASTContext::NumImplicitCopyConstructors; 7945 7946 // If the properties or semantics of the copy constructor couldn't be 7947 // determined while the class was being declared, force a declaration 7948 // of it now. 7949 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7950 ClassDecl->hasInheritedConstructor()) 7951 DeclareImplicitCopyConstructor(ClassDecl); 7952 // For the MS ABI we need to know whether the copy ctor is deleted. A 7953 // prerequisite for deleting the implicit copy ctor is that the class has a 7954 // move ctor or move assignment that is either user-declared or whose 7955 // semantics are inherited from a subobject. FIXME: We should provide a more 7956 // direct way for CodeGen to ask whether the constructor was deleted. 7957 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7958 (ClassDecl->hasUserDeclaredMoveConstructor() || 7959 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7960 ClassDecl->hasUserDeclaredMoveAssignment() || 7961 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7962 DeclareImplicitCopyConstructor(ClassDecl); 7963 } 7964 7965 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7966 ++ASTContext::NumImplicitMoveConstructors; 7967 7968 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7969 ClassDecl->hasInheritedConstructor()) 7970 DeclareImplicitMoveConstructor(ClassDecl); 7971 } 7972 7973 if (ClassDecl->needsImplicitCopyAssignment()) { 7974 ++ASTContext::NumImplicitCopyAssignmentOperators; 7975 7976 // If we have a dynamic class, then the copy assignment operator may be 7977 // virtual, so we have to declare it immediately. This ensures that, e.g., 7978 // it shows up in the right place in the vtable and that we diagnose 7979 // problems with the implicit exception specification. 7980 if (ClassDecl->isDynamicClass() || 7981 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7982 ClassDecl->hasInheritedAssignment()) 7983 DeclareImplicitCopyAssignment(ClassDecl); 7984 } 7985 7986 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7987 ++ASTContext::NumImplicitMoveAssignmentOperators; 7988 7989 // Likewise for the move assignment operator. 7990 if (ClassDecl->isDynamicClass() || 7991 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7992 ClassDecl->hasInheritedAssignment()) 7993 DeclareImplicitMoveAssignment(ClassDecl); 7994 } 7995 7996 if (ClassDecl->needsImplicitDestructor()) { 7997 ++ASTContext::NumImplicitDestructors; 7998 7999 // If we have a dynamic class, then the destructor may be virtual, so we 8000 // have to declare the destructor immediately. This ensures that, e.g., it 8001 // shows up in the right place in the vtable and that we diagnose problems 8002 // with the implicit exception specification. 8003 if (ClassDecl->isDynamicClass() || 8004 ClassDecl->needsOverloadResolutionForDestructor()) 8005 DeclareImplicitDestructor(ClassDecl); 8006 } 8007 } 8008 8009 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 8010 if (!D) 8011 return 0; 8012 8013 // The order of template parameters is not important here. All names 8014 // get added to the same scope. 8015 SmallVector<TemplateParameterList *, 4> ParameterLists; 8016 8017 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8018 D = TD->getTemplatedDecl(); 8019 8020 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 8021 ParameterLists.push_back(PSD->getTemplateParameters()); 8022 8023 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 8024 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 8025 ParameterLists.push_back(DD->getTemplateParameterList(i)); 8026 8027 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8028 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 8029 ParameterLists.push_back(FTD->getTemplateParameters()); 8030 } 8031 } 8032 8033 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 8034 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 8035 ParameterLists.push_back(TD->getTemplateParameterList(i)); 8036 8037 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 8038 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 8039 ParameterLists.push_back(CTD->getTemplateParameters()); 8040 } 8041 } 8042 8043 unsigned Count = 0; 8044 for (TemplateParameterList *Params : ParameterLists) { 8045 if (Params->size() > 0) 8046 // Ignore explicit specializations; they don't contribute to the template 8047 // depth. 8048 ++Count; 8049 for (NamedDecl *Param : *Params) { 8050 if (Param->getDeclName()) { 8051 S->AddDecl(Param); 8052 IdResolver.AddDecl(Param); 8053 } 8054 } 8055 } 8056 8057 return Count; 8058 } 8059 8060 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8061 if (!RecordD) return; 8062 AdjustDeclIfTemplate(RecordD); 8063 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 8064 PushDeclContext(S, Record); 8065 } 8066 8067 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8068 if (!RecordD) return; 8069 PopDeclContext(); 8070 } 8071 8072 /// This is used to implement the constant expression evaluation part of the 8073 /// attribute enable_if extension. There is nothing in standard C++ which would 8074 /// require reentering parameters. 8075 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 8076 if (!Param) 8077 return; 8078 8079 S->AddDecl(Param); 8080 if (Param->getDeclName()) 8081 IdResolver.AddDecl(Param); 8082 } 8083 8084 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 8085 /// parsing a top-level (non-nested) C++ class, and we are now 8086 /// parsing those parts of the given Method declaration that could 8087 /// not be parsed earlier (C++ [class.mem]p2), such as default 8088 /// arguments. This action should enter the scope of the given 8089 /// Method declaration as if we had just parsed the qualified method 8090 /// name. However, it should not bring the parameters into scope; 8091 /// that will be performed by ActOnDelayedCXXMethodParameter. 8092 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8093 } 8094 8095 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 8096 /// C++ method declaration. We're (re-)introducing the given 8097 /// function parameter into scope for use in parsing later parts of 8098 /// the method declaration. For example, we could see an 8099 /// ActOnParamDefaultArgument event for this parameter. 8100 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 8101 if (!ParamD) 8102 return; 8103 8104 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 8105 8106 // If this parameter has an unparsed default argument, clear it out 8107 // to make way for the parsed default argument. 8108 if (Param->hasUnparsedDefaultArg()) 8109 Param->setDefaultArg(nullptr); 8110 8111 S->AddDecl(Param); 8112 if (Param->getDeclName()) 8113 IdResolver.AddDecl(Param); 8114 } 8115 8116 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8117 /// processing the delayed method declaration for Method. The method 8118 /// declaration is now considered finished. There may be a separate 8119 /// ActOnStartOfFunctionDef action later (not necessarily 8120 /// immediately!) for this method, if it was also defined inside the 8121 /// class body. 8122 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8123 if (!MethodD) 8124 return; 8125 8126 AdjustDeclIfTemplate(MethodD); 8127 8128 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8129 8130 // Now that we have our default arguments, check the constructor 8131 // again. It could produce additional diagnostics or affect whether 8132 // the class has implicitly-declared destructors, among other 8133 // things. 8134 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8135 CheckConstructor(Constructor); 8136 8137 // Check the default arguments, which we may have added. 8138 if (!Method->isInvalidDecl()) 8139 CheckCXXDefaultArguments(Method); 8140 } 8141 8142 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8143 /// the well-formedness of the constructor declarator @p D with type @p 8144 /// R. If there are any errors in the declarator, this routine will 8145 /// emit diagnostics and set the invalid bit to true. In any case, the type 8146 /// will be updated to reflect a well-formed type for the constructor and 8147 /// returned. 8148 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8149 StorageClass &SC) { 8150 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8151 8152 // C++ [class.ctor]p3: 8153 // A constructor shall not be virtual (10.3) or static (9.4). A 8154 // constructor can be invoked for a const, volatile or const 8155 // volatile object. A constructor shall not be declared const, 8156 // volatile, or const volatile (9.3.2). 8157 if (isVirtual) { 8158 if (!D.isInvalidType()) 8159 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8160 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8161 << SourceRange(D.getIdentifierLoc()); 8162 D.setInvalidType(); 8163 } 8164 if (SC == SC_Static) { 8165 if (!D.isInvalidType()) 8166 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8167 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8168 << SourceRange(D.getIdentifierLoc()); 8169 D.setInvalidType(); 8170 SC = SC_None; 8171 } 8172 8173 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8174 diagnoseIgnoredQualifiers( 8175 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8176 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8177 D.getDeclSpec().getRestrictSpecLoc(), 8178 D.getDeclSpec().getAtomicSpecLoc()); 8179 D.setInvalidType(); 8180 } 8181 8182 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8183 if (FTI.hasMethodTypeQualifiers()) { 8184 FTI.MethodQualifiers->forEachQualifier( 8185 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { 8186 Diag(SL, diag::err_invalid_qualified_constructor) 8187 << QualName << SourceRange(SL); 8188 }); 8189 D.setInvalidType(); 8190 } 8191 8192 // C++0x [class.ctor]p4: 8193 // A constructor shall not be declared with a ref-qualifier. 8194 if (FTI.hasRefQualifier()) { 8195 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8196 << FTI.RefQualifierIsLValueRef 8197 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8198 D.setInvalidType(); 8199 } 8200 8201 // Rebuild the function type "R" without any type qualifiers (in 8202 // case any of the errors above fired) and with "void" as the 8203 // return type, since constructors don't have return types. 8204 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8205 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8206 return R; 8207 8208 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8209 EPI.TypeQuals = Qualifiers(); 8210 EPI.RefQualifier = RQ_None; 8211 8212 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8213 } 8214 8215 /// CheckConstructor - Checks a fully-formed constructor for 8216 /// well-formedness, issuing any diagnostics required. Returns true if 8217 /// the constructor declarator is invalid. 8218 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8219 CXXRecordDecl *ClassDecl 8220 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8221 if (!ClassDecl) 8222 return Constructor->setInvalidDecl(); 8223 8224 // C++ [class.copy]p3: 8225 // A declaration of a constructor for a class X is ill-formed if 8226 // its first parameter is of type (optionally cv-qualified) X and 8227 // either there are no other parameters or else all other 8228 // parameters have default arguments. 8229 if (!Constructor->isInvalidDecl() && 8230 ((Constructor->getNumParams() == 1) || 8231 (Constructor->getNumParams() > 1 && 8232 Constructor->getParamDecl(1)->hasDefaultArg())) && 8233 Constructor->getTemplateSpecializationKind() 8234 != TSK_ImplicitInstantiation) { 8235 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8236 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8237 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8238 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8239 const char *ConstRef 8240 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8241 : " const &"; 8242 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8243 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8244 8245 // FIXME: Rather that making the constructor invalid, we should endeavor 8246 // to fix the type. 8247 Constructor->setInvalidDecl(); 8248 } 8249 } 8250 } 8251 8252 /// CheckDestructor - Checks a fully-formed destructor definition for 8253 /// well-formedness, issuing any diagnostics required. Returns true 8254 /// on error. 8255 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8256 CXXRecordDecl *RD = Destructor->getParent(); 8257 8258 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8259 SourceLocation Loc; 8260 8261 if (!Destructor->isImplicit()) 8262 Loc = Destructor->getLocation(); 8263 else 8264 Loc = RD->getLocation(); 8265 8266 // If we have a virtual destructor, look up the deallocation function 8267 if (FunctionDecl *OperatorDelete = 8268 FindDeallocationFunctionForDestructor(Loc, RD)) { 8269 Expr *ThisArg = nullptr; 8270 8271 // If the notional 'delete this' expression requires a non-trivial 8272 // conversion from 'this' to the type of a destroying operator delete's 8273 // first parameter, perform that conversion now. 8274 if (OperatorDelete->isDestroyingOperatorDelete()) { 8275 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8276 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8277 // C++ [class.dtor]p13: 8278 // ... as if for the expression 'delete this' appearing in a 8279 // non-virtual destructor of the destructor's class. 8280 ContextRAII SwitchContext(*this, Destructor); 8281 ExprResult This = 8282 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8283 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8284 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8285 if (This.isInvalid()) { 8286 // FIXME: Register this as a context note so that it comes out 8287 // in the right order. 8288 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8289 return true; 8290 } 8291 ThisArg = This.get(); 8292 } 8293 } 8294 8295 DiagnoseUseOfDecl(OperatorDelete, Loc); 8296 MarkFunctionReferenced(Loc, OperatorDelete); 8297 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8298 } 8299 } 8300 8301 return false; 8302 } 8303 8304 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8305 /// the well-formednes of the destructor declarator @p D with type @p 8306 /// R. If there are any errors in the declarator, this routine will 8307 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8308 /// will be updated to reflect a well-formed type for the destructor and 8309 /// returned. 8310 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8311 StorageClass& SC) { 8312 // C++ [class.dtor]p1: 8313 // [...] A typedef-name that names a class is a class-name 8314 // (7.1.3); however, a typedef-name that names a class shall not 8315 // be used as the identifier in the declarator for a destructor 8316 // declaration. 8317 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8318 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8319 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8320 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8321 else if (const TemplateSpecializationType *TST = 8322 DeclaratorType->getAs<TemplateSpecializationType>()) 8323 if (TST->isTypeAlias()) 8324 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8325 << DeclaratorType << 1; 8326 8327 // C++ [class.dtor]p2: 8328 // A destructor is used to destroy objects of its class type. A 8329 // destructor takes no parameters, and no return type can be 8330 // specified for it (not even void). The address of a destructor 8331 // shall not be taken. A destructor shall not be static. A 8332 // destructor can be invoked for a const, volatile or const 8333 // volatile object. A destructor shall not be declared const, 8334 // volatile or const volatile (9.3.2). 8335 if (SC == SC_Static) { 8336 if (!D.isInvalidType()) 8337 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8338 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8339 << SourceRange(D.getIdentifierLoc()) 8340 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8341 8342 SC = SC_None; 8343 } 8344 if (!D.isInvalidType()) { 8345 // Destructors don't have return types, but the parser will 8346 // happily parse something like: 8347 // 8348 // class X { 8349 // float ~X(); 8350 // }; 8351 // 8352 // The return type will be eliminated later. 8353 if (D.getDeclSpec().hasTypeSpecifier()) 8354 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8355 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8356 << SourceRange(D.getIdentifierLoc()); 8357 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8358 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8359 SourceLocation(), 8360 D.getDeclSpec().getConstSpecLoc(), 8361 D.getDeclSpec().getVolatileSpecLoc(), 8362 D.getDeclSpec().getRestrictSpecLoc(), 8363 D.getDeclSpec().getAtomicSpecLoc()); 8364 D.setInvalidType(); 8365 } 8366 } 8367 8368 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8369 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 8370 FTI.MethodQualifiers->forEachQualifier( 8371 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { 8372 Diag(SL, diag::err_invalid_qualified_destructor) 8373 << QualName << SourceRange(SL); 8374 }); 8375 D.setInvalidType(); 8376 } 8377 8378 // C++0x [class.dtor]p2: 8379 // A destructor shall not be declared with a ref-qualifier. 8380 if (FTI.hasRefQualifier()) { 8381 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8382 << FTI.RefQualifierIsLValueRef 8383 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8384 D.setInvalidType(); 8385 } 8386 8387 // Make sure we don't have any parameters. 8388 if (FTIHasNonVoidParameters(FTI)) { 8389 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8390 8391 // Delete the parameters. 8392 FTI.freeParams(); 8393 D.setInvalidType(); 8394 } 8395 8396 // Make sure the destructor isn't variadic. 8397 if (FTI.isVariadic) { 8398 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8399 D.setInvalidType(); 8400 } 8401 8402 // Rebuild the function type "R" without any type qualifiers or 8403 // parameters (in case any of the errors above fired) and with 8404 // "void" as the return type, since destructors don't have return 8405 // types. 8406 if (!D.isInvalidType()) 8407 return R; 8408 8409 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8410 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8411 EPI.Variadic = false; 8412 EPI.TypeQuals = Qualifiers(); 8413 EPI.RefQualifier = RQ_None; 8414 return Context.getFunctionType(Context.VoidTy, None, EPI); 8415 } 8416 8417 static void extendLeft(SourceRange &R, SourceRange Before) { 8418 if (Before.isInvalid()) 8419 return; 8420 R.setBegin(Before.getBegin()); 8421 if (R.getEnd().isInvalid()) 8422 R.setEnd(Before.getEnd()); 8423 } 8424 8425 static void extendRight(SourceRange &R, SourceRange After) { 8426 if (After.isInvalid()) 8427 return; 8428 if (R.getBegin().isInvalid()) 8429 R.setBegin(After.getBegin()); 8430 R.setEnd(After.getEnd()); 8431 } 8432 8433 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8434 /// well-formednes of the conversion function declarator @p D with 8435 /// type @p R. If there are any errors in the declarator, this routine 8436 /// will emit diagnostics and return true. Otherwise, it will return 8437 /// false. Either way, the type @p R will be updated to reflect a 8438 /// well-formed type for the conversion operator. 8439 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8440 StorageClass& SC) { 8441 // C++ [class.conv.fct]p1: 8442 // Neither parameter types nor return type can be specified. The 8443 // type of a conversion function (8.3.5) is "function taking no 8444 // parameter returning conversion-type-id." 8445 if (SC == SC_Static) { 8446 if (!D.isInvalidType()) 8447 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8448 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8449 << D.getName().getSourceRange(); 8450 D.setInvalidType(); 8451 SC = SC_None; 8452 } 8453 8454 TypeSourceInfo *ConvTSI = nullptr; 8455 QualType ConvType = 8456 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8457 8458 const DeclSpec &DS = D.getDeclSpec(); 8459 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8460 // Conversion functions don't have return types, but the parser will 8461 // happily parse something like: 8462 // 8463 // class X { 8464 // float operator bool(); 8465 // }; 8466 // 8467 // The return type will be changed later anyway. 8468 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8469 << SourceRange(DS.getTypeSpecTypeLoc()) 8470 << SourceRange(D.getIdentifierLoc()); 8471 D.setInvalidType(); 8472 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8473 // It's also plausible that the user writes type qualifiers in the wrong 8474 // place, such as: 8475 // struct S { const operator int(); }; 8476 // FIXME: we could provide a fixit to move the qualifiers onto the 8477 // conversion type. 8478 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8479 << SourceRange(D.getIdentifierLoc()) << 0; 8480 D.setInvalidType(); 8481 } 8482 8483 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8484 8485 // Make sure we don't have any parameters. 8486 if (Proto->getNumParams() > 0) { 8487 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8488 8489 // Delete the parameters. 8490 D.getFunctionTypeInfo().freeParams(); 8491 D.setInvalidType(); 8492 } else if (Proto->isVariadic()) { 8493 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8494 D.setInvalidType(); 8495 } 8496 8497 // Diagnose "&operator bool()" and other such nonsense. This 8498 // is actually a gcc extension which we don't support. 8499 if (Proto->getReturnType() != ConvType) { 8500 bool NeedsTypedef = false; 8501 SourceRange Before, After; 8502 8503 // Walk the chunks and extract information on them for our diagnostic. 8504 bool PastFunctionChunk = false; 8505 for (auto &Chunk : D.type_objects()) { 8506 switch (Chunk.Kind) { 8507 case DeclaratorChunk::Function: 8508 if (!PastFunctionChunk) { 8509 if (Chunk.Fun.HasTrailingReturnType) { 8510 TypeSourceInfo *TRT = nullptr; 8511 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8512 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8513 } 8514 PastFunctionChunk = true; 8515 break; 8516 } 8517 LLVM_FALLTHROUGH; 8518 case DeclaratorChunk::Array: 8519 NeedsTypedef = true; 8520 extendRight(After, Chunk.getSourceRange()); 8521 break; 8522 8523 case DeclaratorChunk::Pointer: 8524 case DeclaratorChunk::BlockPointer: 8525 case DeclaratorChunk::Reference: 8526 case DeclaratorChunk::MemberPointer: 8527 case DeclaratorChunk::Pipe: 8528 extendLeft(Before, Chunk.getSourceRange()); 8529 break; 8530 8531 case DeclaratorChunk::Paren: 8532 extendLeft(Before, Chunk.Loc); 8533 extendRight(After, Chunk.EndLoc); 8534 break; 8535 } 8536 } 8537 8538 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8539 After.isValid() ? After.getBegin() : 8540 D.getIdentifierLoc(); 8541 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8542 DB << Before << After; 8543 8544 if (!NeedsTypedef) { 8545 DB << /*don't need a typedef*/0; 8546 8547 // If we can provide a correct fix-it hint, do so. 8548 if (After.isInvalid() && ConvTSI) { 8549 SourceLocation InsertLoc = 8550 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 8551 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8552 << FixItHint::CreateInsertionFromRange( 8553 InsertLoc, CharSourceRange::getTokenRange(Before)) 8554 << FixItHint::CreateRemoval(Before); 8555 } 8556 } else if (!Proto->getReturnType()->isDependentType()) { 8557 DB << /*typedef*/1 << Proto->getReturnType(); 8558 } else if (getLangOpts().CPlusPlus11) { 8559 DB << /*alias template*/2 << Proto->getReturnType(); 8560 } else { 8561 DB << /*might not be fixable*/3; 8562 } 8563 8564 // Recover by incorporating the other type chunks into the result type. 8565 // Note, this does *not* change the name of the function. This is compatible 8566 // with the GCC extension: 8567 // struct S { &operator int(); } s; 8568 // int &r = s.operator int(); // ok in GCC 8569 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8570 ConvType = Proto->getReturnType(); 8571 } 8572 8573 // C++ [class.conv.fct]p4: 8574 // The conversion-type-id shall not represent a function type nor 8575 // an array type. 8576 if (ConvType->isArrayType()) { 8577 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8578 ConvType = Context.getPointerType(ConvType); 8579 D.setInvalidType(); 8580 } else if (ConvType->isFunctionType()) { 8581 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8582 ConvType = Context.getPointerType(ConvType); 8583 D.setInvalidType(); 8584 } 8585 8586 // Rebuild the function type "R" without any parameters (in case any 8587 // of the errors above fired) and with the conversion type as the 8588 // return type. 8589 if (D.isInvalidType()) 8590 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8591 8592 // C++0x explicit conversion operators. 8593 if (DS.isExplicitSpecified()) 8594 Diag(DS.getExplicitSpecLoc(), 8595 getLangOpts().CPlusPlus11 8596 ? diag::warn_cxx98_compat_explicit_conversion_functions 8597 : diag::ext_explicit_conversion_functions) 8598 << SourceRange(DS.getExplicitSpecLoc()); 8599 } 8600 8601 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8602 /// the declaration of the given C++ conversion function. This routine 8603 /// is responsible for recording the conversion function in the C++ 8604 /// class, if possible. 8605 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8606 assert(Conversion && "Expected to receive a conversion function declaration"); 8607 8608 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8609 8610 // Make sure we aren't redeclaring the conversion function. 8611 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8612 8613 // C++ [class.conv.fct]p1: 8614 // [...] A conversion function is never used to convert a 8615 // (possibly cv-qualified) object to the (possibly cv-qualified) 8616 // same object type (or a reference to it), to a (possibly 8617 // cv-qualified) base class of that type (or a reference to it), 8618 // or to (possibly cv-qualified) void. 8619 // FIXME: Suppress this warning if the conversion function ends up being a 8620 // virtual function that overrides a virtual function in a base class. 8621 QualType ClassType 8622 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8623 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8624 ConvType = ConvTypeRef->getPointeeType(); 8625 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8626 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8627 /* Suppress diagnostics for instantiations. */; 8628 else if (ConvType->isRecordType()) { 8629 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8630 if (ConvType == ClassType) 8631 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8632 << ClassType; 8633 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8634 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8635 << ClassType << ConvType; 8636 } else if (ConvType->isVoidType()) { 8637 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8638 << ClassType << ConvType; 8639 } 8640 8641 if (FunctionTemplateDecl *ConversionTemplate 8642 = Conversion->getDescribedFunctionTemplate()) 8643 return ConversionTemplate; 8644 8645 return Conversion; 8646 } 8647 8648 namespace { 8649 /// Utility class to accumulate and print a diagnostic listing the invalid 8650 /// specifier(s) on a declaration. 8651 struct BadSpecifierDiagnoser { 8652 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8653 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8654 ~BadSpecifierDiagnoser() { 8655 Diagnostic << Specifiers; 8656 } 8657 8658 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8659 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8660 } 8661 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8662 return check(SpecLoc, 8663 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8664 } 8665 void check(SourceLocation SpecLoc, const char *Spec) { 8666 if (SpecLoc.isInvalid()) return; 8667 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8668 if (!Specifiers.empty()) Specifiers += " "; 8669 Specifiers += Spec; 8670 } 8671 8672 Sema &S; 8673 Sema::SemaDiagnosticBuilder Diagnostic; 8674 std::string Specifiers; 8675 }; 8676 } 8677 8678 /// Check the validity of a declarator that we parsed for a deduction-guide. 8679 /// These aren't actually declarators in the grammar, so we need to check that 8680 /// the user didn't specify any pieces that are not part of the deduction-guide 8681 /// grammar. 8682 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8683 StorageClass &SC) { 8684 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8685 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8686 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8687 8688 // C++ [temp.deduct.guide]p3: 8689 // A deduction-gide shall be declared in the same scope as the 8690 // corresponding class template. 8691 if (!CurContext->getRedeclContext()->Equals( 8692 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8693 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8694 << GuidedTemplateDecl; 8695 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8696 } 8697 8698 auto &DS = D.getMutableDeclSpec(); 8699 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8700 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8701 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8702 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8703 BadSpecifierDiagnoser Diagnoser( 8704 *this, D.getIdentifierLoc(), 8705 diag::err_deduction_guide_invalid_specifier); 8706 8707 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8708 DS.ClearStorageClassSpecs(); 8709 SC = SC_None; 8710 8711 // 'explicit' is permitted. 8712 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8713 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8714 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8715 DS.ClearConstexprSpec(); 8716 8717 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8718 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8719 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8720 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8721 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8722 DS.ClearTypeQualifiers(); 8723 8724 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8725 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8726 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8727 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8728 DS.ClearTypeSpecType(); 8729 } 8730 8731 if (D.isInvalidType()) 8732 return; 8733 8734 // Check the declarator is simple enough. 8735 bool FoundFunction = false; 8736 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8737 if (Chunk.Kind == DeclaratorChunk::Paren) 8738 continue; 8739 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8740 Diag(D.getDeclSpec().getBeginLoc(), 8741 diag::err_deduction_guide_with_complex_decl) 8742 << D.getSourceRange(); 8743 break; 8744 } 8745 if (!Chunk.Fun.hasTrailingReturnType()) { 8746 Diag(D.getName().getBeginLoc(), 8747 diag::err_deduction_guide_no_trailing_return_type); 8748 break; 8749 } 8750 8751 // Check that the return type is written as a specialization of 8752 // the template specified as the deduction-guide's name. 8753 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8754 TypeSourceInfo *TSI = nullptr; 8755 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8756 assert(TSI && "deduction guide has valid type but invalid return type?"); 8757 bool AcceptableReturnType = false; 8758 bool MightInstantiateToSpecialization = false; 8759 if (auto RetTST = 8760 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8761 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8762 bool TemplateMatches = 8763 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8764 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8765 AcceptableReturnType = true; 8766 else { 8767 // This could still instantiate to the right type, unless we know it 8768 // names the wrong class template. 8769 auto *TD = SpecifiedName.getAsTemplateDecl(); 8770 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8771 !TemplateMatches); 8772 } 8773 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8774 MightInstantiateToSpecialization = true; 8775 } 8776 8777 if (!AcceptableReturnType) { 8778 Diag(TSI->getTypeLoc().getBeginLoc(), 8779 diag::err_deduction_guide_bad_trailing_return_type) 8780 << GuidedTemplate << TSI->getType() 8781 << MightInstantiateToSpecialization 8782 << TSI->getTypeLoc().getSourceRange(); 8783 } 8784 8785 // Keep going to check that we don't have any inner declarator pieces (we 8786 // could still have a function returning a pointer to a function). 8787 FoundFunction = true; 8788 } 8789 8790 if (D.isFunctionDefinition()) 8791 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8792 } 8793 8794 //===----------------------------------------------------------------------===// 8795 // Namespace Handling 8796 //===----------------------------------------------------------------------===// 8797 8798 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 8799 /// reopened. 8800 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8801 SourceLocation Loc, 8802 IdentifierInfo *II, bool *IsInline, 8803 NamespaceDecl *PrevNS) { 8804 assert(*IsInline != PrevNS->isInline()); 8805 8806 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8807 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8808 // inline namespaces, with the intention of bringing names into namespace std. 8809 // 8810 // We support this just well enough to get that case working; this is not 8811 // sufficient to support reopening namespaces as inline in general. 8812 if (*IsInline && II && II->getName().startswith("__atomic") && 8813 S.getSourceManager().isInSystemHeader(Loc)) { 8814 // Mark all prior declarations of the namespace as inline. 8815 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8816 NS = NS->getPreviousDecl()) 8817 NS->setInline(*IsInline); 8818 // Patch up the lookup table for the containing namespace. This isn't really 8819 // correct, but it's good enough for this particular case. 8820 for (auto *I : PrevNS->decls()) 8821 if (auto *ND = dyn_cast<NamedDecl>(I)) 8822 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8823 return; 8824 } 8825 8826 if (PrevNS->isInline()) 8827 // The user probably just forgot the 'inline', so suggest that it 8828 // be added back. 8829 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8830 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8831 else 8832 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8833 8834 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8835 *IsInline = PrevNS->isInline(); 8836 } 8837 8838 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8839 /// definition. 8840 Decl *Sema::ActOnStartNamespaceDef( 8841 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 8842 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 8843 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 8844 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8845 // For anonymous namespace, take the location of the left brace. 8846 SourceLocation Loc = II ? IdentLoc : LBrace; 8847 bool IsInline = InlineLoc.isValid(); 8848 bool IsInvalid = false; 8849 bool IsStd = false; 8850 bool AddToKnown = false; 8851 Scope *DeclRegionScope = NamespcScope->getParent(); 8852 8853 NamespaceDecl *PrevNS = nullptr; 8854 if (II) { 8855 // C++ [namespace.def]p2: 8856 // The identifier in an original-namespace-definition shall not 8857 // have been previously defined in the declarative region in 8858 // which the original-namespace-definition appears. The 8859 // identifier in an original-namespace-definition is the name of 8860 // the namespace. Subsequently in that declarative region, it is 8861 // treated as an original-namespace-name. 8862 // 8863 // Since namespace names are unique in their scope, and we don't 8864 // look through using directives, just look for any ordinary names 8865 // as if by qualified name lookup. 8866 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8867 ForExternalRedeclaration); 8868 LookupQualifiedName(R, CurContext->getRedeclContext()); 8869 NamedDecl *PrevDecl = 8870 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8871 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8872 8873 if (PrevNS) { 8874 // This is an extended namespace definition. 8875 if (IsInline != PrevNS->isInline()) 8876 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8877 &IsInline, PrevNS); 8878 } else if (PrevDecl) { 8879 // This is an invalid name redefinition. 8880 Diag(Loc, diag::err_redefinition_different_kind) 8881 << II; 8882 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8883 IsInvalid = true; 8884 // Continue on to push Namespc as current DeclContext and return it. 8885 } else if (II->isStr("std") && 8886 CurContext->getRedeclContext()->isTranslationUnit()) { 8887 // This is the first "real" definition of the namespace "std", so update 8888 // our cache of the "std" namespace to point at this definition. 8889 PrevNS = getStdNamespace(); 8890 IsStd = true; 8891 AddToKnown = !IsInline; 8892 } else { 8893 // We've seen this namespace for the first time. 8894 AddToKnown = !IsInline; 8895 } 8896 } else { 8897 // Anonymous namespaces. 8898 8899 // Determine whether the parent already has an anonymous namespace. 8900 DeclContext *Parent = CurContext->getRedeclContext(); 8901 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8902 PrevNS = TU->getAnonymousNamespace(); 8903 } else { 8904 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8905 PrevNS = ND->getAnonymousNamespace(); 8906 } 8907 8908 if (PrevNS && IsInline != PrevNS->isInline()) 8909 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8910 &IsInline, PrevNS); 8911 } 8912 8913 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8914 StartLoc, Loc, II, PrevNS); 8915 if (IsInvalid) 8916 Namespc->setInvalidDecl(); 8917 8918 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8919 AddPragmaAttributes(DeclRegionScope, Namespc); 8920 8921 // FIXME: Should we be merging attributes? 8922 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8923 PushNamespaceVisibilityAttr(Attr, Loc); 8924 8925 if (IsStd) 8926 StdNamespace = Namespc; 8927 if (AddToKnown) 8928 KnownNamespaces[Namespc] = false; 8929 8930 if (II) { 8931 PushOnScopeChains(Namespc, DeclRegionScope); 8932 } else { 8933 // Link the anonymous namespace into its parent. 8934 DeclContext *Parent = CurContext->getRedeclContext(); 8935 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8936 TU->setAnonymousNamespace(Namespc); 8937 } else { 8938 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8939 } 8940 8941 CurContext->addDecl(Namespc); 8942 8943 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8944 // behaves as if it were replaced by 8945 // namespace unique { /* empty body */ } 8946 // using namespace unique; 8947 // namespace unique { namespace-body } 8948 // where all occurrences of 'unique' in a translation unit are 8949 // replaced by the same identifier and this identifier differs 8950 // from all other identifiers in the entire program. 8951 8952 // We just create the namespace with an empty name and then add an 8953 // implicit using declaration, just like the standard suggests. 8954 // 8955 // CodeGen enforces the "universally unique" aspect by giving all 8956 // declarations semantically contained within an anonymous 8957 // namespace internal linkage. 8958 8959 if (!PrevNS) { 8960 UD = UsingDirectiveDecl::Create(Context, Parent, 8961 /* 'using' */ LBrace, 8962 /* 'namespace' */ SourceLocation(), 8963 /* qualifier */ NestedNameSpecifierLoc(), 8964 /* identifier */ SourceLocation(), 8965 Namespc, 8966 /* Ancestor */ Parent); 8967 UD->setImplicit(); 8968 Parent->addDecl(UD); 8969 } 8970 } 8971 8972 ActOnDocumentableDecl(Namespc); 8973 8974 // Although we could have an invalid decl (i.e. the namespace name is a 8975 // redefinition), push it as current DeclContext and try to continue parsing. 8976 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8977 // for the namespace has the declarations that showed up in that particular 8978 // namespace definition. 8979 PushDeclContext(NamespcScope, Namespc); 8980 return Namespc; 8981 } 8982 8983 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8984 /// is a namespace alias, returns the namespace it points to. 8985 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8986 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8987 return AD->getNamespace(); 8988 return dyn_cast_or_null<NamespaceDecl>(D); 8989 } 8990 8991 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8992 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8993 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8994 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8995 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8996 Namespc->setRBraceLoc(RBrace); 8997 PopDeclContext(); 8998 if (Namespc->hasAttr<VisibilityAttr>()) 8999 PopPragmaVisibility(true, RBrace); 9000 } 9001 9002 CXXRecordDecl *Sema::getStdBadAlloc() const { 9003 return cast_or_null<CXXRecordDecl>( 9004 StdBadAlloc.get(Context.getExternalSource())); 9005 } 9006 9007 EnumDecl *Sema::getStdAlignValT() const { 9008 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 9009 } 9010 9011 NamespaceDecl *Sema::getStdNamespace() const { 9012 return cast_or_null<NamespaceDecl>( 9013 StdNamespace.get(Context.getExternalSource())); 9014 } 9015 9016 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 9017 if (!StdExperimentalNamespaceCache) { 9018 if (auto Std = getStdNamespace()) { 9019 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 9020 SourceLocation(), LookupNamespaceName); 9021 if (!LookupQualifiedName(Result, Std) || 9022 !(StdExperimentalNamespaceCache = 9023 Result.getAsSingle<NamespaceDecl>())) 9024 Result.suppressDiagnostics(); 9025 } 9026 } 9027 return StdExperimentalNamespaceCache; 9028 } 9029 9030 namespace { 9031 9032 enum UnsupportedSTLSelect { 9033 USS_InvalidMember, 9034 USS_MissingMember, 9035 USS_NonTrivial, 9036 USS_Other 9037 }; 9038 9039 struct InvalidSTLDiagnoser { 9040 Sema &S; 9041 SourceLocation Loc; 9042 QualType TyForDiags; 9043 9044 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 9045 const VarDecl *VD = nullptr) { 9046 { 9047 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 9048 << TyForDiags << ((int)Sel); 9049 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 9050 assert(!Name.empty()); 9051 D << Name; 9052 } 9053 } 9054 if (Sel == USS_InvalidMember) { 9055 S.Diag(VD->getLocation(), diag::note_var_declared_here) 9056 << VD << VD->getSourceRange(); 9057 } 9058 return QualType(); 9059 } 9060 }; 9061 } // namespace 9062 9063 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 9064 SourceLocation Loc) { 9065 assert(getLangOpts().CPlusPlus && 9066 "Looking for comparison category type outside of C++."); 9067 9068 // Check if we've already successfully checked the comparison category type 9069 // before. If so, skip checking it again. 9070 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 9071 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 9072 return Info->getType(); 9073 9074 // If lookup failed 9075 if (!Info) { 9076 std::string NameForDiags = "std::"; 9077 NameForDiags += ComparisonCategories::getCategoryString(Kind); 9078 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 9079 << NameForDiags; 9080 return QualType(); 9081 } 9082 9083 assert(Info->Kind == Kind); 9084 assert(Info->Record); 9085 9086 // Update the Record decl in case we encountered a forward declaration on our 9087 // first pass. FIXME: This is a bit of a hack. 9088 if (Info->Record->hasDefinition()) 9089 Info->Record = Info->Record->getDefinition(); 9090 9091 // Use an elaborated type for diagnostics which has a name containing the 9092 // prepended 'std' namespace but not any inline namespace names. 9093 QualType TyForDiags = [&]() { 9094 auto *NNS = 9095 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 9096 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 9097 }(); 9098 9099 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 9100 return QualType(); 9101 9102 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 9103 9104 if (!Info->Record->isTriviallyCopyable()) 9105 return UnsupportedSTLError(USS_NonTrivial); 9106 9107 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 9108 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 9109 // Tolerate empty base classes. 9110 if (Base->isEmpty()) 9111 continue; 9112 // Reject STL implementations which have at least one non-empty base. 9113 return UnsupportedSTLError(); 9114 } 9115 9116 // Check that the STL has implemented the types using a single integer field. 9117 // This expectation allows better codegen for builtin operators. We require: 9118 // (1) The class has exactly one field. 9119 // (2) The field is an integral or enumeration type. 9120 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9121 if (std::distance(FIt, FEnd) != 1 || 9122 !FIt->getType()->isIntegralOrEnumerationType()) { 9123 return UnsupportedSTLError(); 9124 } 9125 9126 // Build each of the require values and store them in Info. 9127 for (ComparisonCategoryResult CCR : 9128 ComparisonCategories::getPossibleResultsForType(Kind)) { 9129 StringRef MemName = ComparisonCategories::getResultString(CCR); 9130 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9131 9132 if (!ValInfo) 9133 return UnsupportedSTLError(USS_MissingMember, MemName); 9134 9135 VarDecl *VD = ValInfo->VD; 9136 assert(VD && "should not be null!"); 9137 9138 // Attempt to diagnose reasons why the STL definition of this type 9139 // might be foobar, including it failing to be a constant expression. 9140 // TODO Handle more ways the lookup or result can be invalid. 9141 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9142 !VD->checkInitIsICE()) 9143 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9144 9145 // Attempt to evaluate the var decl as a constant expression and extract 9146 // the value of its first field as a ICE. If this fails, the STL 9147 // implementation is not supported. 9148 if (!ValInfo->hasValidIntValue()) 9149 return UnsupportedSTLError(); 9150 9151 MarkVariableReferenced(Loc, VD); 9152 } 9153 9154 // We've successfully built the required types and expressions. Update 9155 // the cache and return the newly cached value. 9156 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9157 return Info->getType(); 9158 } 9159 9160 /// Retrieve the special "std" namespace, which may require us to 9161 /// implicitly define the namespace. 9162 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9163 if (!StdNamespace) { 9164 // The "std" namespace has not yet been defined, so build one implicitly. 9165 StdNamespace = NamespaceDecl::Create(Context, 9166 Context.getTranslationUnitDecl(), 9167 /*Inline=*/false, 9168 SourceLocation(), SourceLocation(), 9169 &PP.getIdentifierTable().get("std"), 9170 /*PrevDecl=*/nullptr); 9171 getStdNamespace()->setImplicit(true); 9172 } 9173 9174 return getStdNamespace(); 9175 } 9176 9177 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9178 assert(getLangOpts().CPlusPlus && 9179 "Looking for std::initializer_list outside of C++."); 9180 9181 // We're looking for implicit instantiations of 9182 // template <typename E> class std::initializer_list. 9183 9184 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9185 return false; 9186 9187 ClassTemplateDecl *Template = nullptr; 9188 const TemplateArgument *Arguments = nullptr; 9189 9190 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9191 9192 ClassTemplateSpecializationDecl *Specialization = 9193 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9194 if (!Specialization) 9195 return false; 9196 9197 Template = Specialization->getSpecializedTemplate(); 9198 Arguments = Specialization->getTemplateArgs().data(); 9199 } else if (const TemplateSpecializationType *TST = 9200 Ty->getAs<TemplateSpecializationType>()) { 9201 Template = dyn_cast_or_null<ClassTemplateDecl>( 9202 TST->getTemplateName().getAsTemplateDecl()); 9203 Arguments = TST->getArgs(); 9204 } 9205 if (!Template) 9206 return false; 9207 9208 if (!StdInitializerList) { 9209 // Haven't recognized std::initializer_list yet, maybe this is it. 9210 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9211 if (TemplateClass->getIdentifier() != 9212 &PP.getIdentifierTable().get("initializer_list") || 9213 !getStdNamespace()->InEnclosingNamespaceSetOf( 9214 TemplateClass->getDeclContext())) 9215 return false; 9216 // This is a template called std::initializer_list, but is it the right 9217 // template? 9218 TemplateParameterList *Params = Template->getTemplateParameters(); 9219 if (Params->getMinRequiredArguments() != 1) 9220 return false; 9221 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9222 return false; 9223 9224 // It's the right template. 9225 StdInitializerList = Template; 9226 } 9227 9228 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9229 return false; 9230 9231 // This is an instance of std::initializer_list. Find the argument type. 9232 if (Element) 9233 *Element = Arguments[0].getAsType(); 9234 return true; 9235 } 9236 9237 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9238 NamespaceDecl *Std = S.getStdNamespace(); 9239 if (!Std) { 9240 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9241 return nullptr; 9242 } 9243 9244 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9245 Loc, Sema::LookupOrdinaryName); 9246 if (!S.LookupQualifiedName(Result, Std)) { 9247 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9248 return nullptr; 9249 } 9250 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9251 if (!Template) { 9252 Result.suppressDiagnostics(); 9253 // We found something weird. Complain about the first thing we found. 9254 NamedDecl *Found = *Result.begin(); 9255 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9256 return nullptr; 9257 } 9258 9259 // We found some template called std::initializer_list. Now verify that it's 9260 // correct. 9261 TemplateParameterList *Params = Template->getTemplateParameters(); 9262 if (Params->getMinRequiredArguments() != 1 || 9263 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9264 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9265 return nullptr; 9266 } 9267 9268 return Template; 9269 } 9270 9271 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9272 if (!StdInitializerList) { 9273 StdInitializerList = LookupStdInitializerList(*this, Loc); 9274 if (!StdInitializerList) 9275 return QualType(); 9276 } 9277 9278 TemplateArgumentListInfo Args(Loc, Loc); 9279 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9280 Context.getTrivialTypeSourceInfo(Element, 9281 Loc))); 9282 return Context.getCanonicalType( 9283 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9284 } 9285 9286 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9287 // C++ [dcl.init.list]p2: 9288 // A constructor is an initializer-list constructor if its first parameter 9289 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9290 // std::initializer_list<E> for some type E, and either there are no other 9291 // parameters or else all other parameters have default arguments. 9292 if (Ctor->getNumParams() < 1 || 9293 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9294 return false; 9295 9296 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9297 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9298 ArgType = RT->getPointeeType().getUnqualifiedType(); 9299 9300 return isStdInitializerList(ArgType, nullptr); 9301 } 9302 9303 /// Determine whether a using statement is in a context where it will be 9304 /// apply in all contexts. 9305 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9306 switch (CurContext->getDeclKind()) { 9307 case Decl::TranslationUnit: 9308 return true; 9309 case Decl::LinkageSpec: 9310 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9311 default: 9312 return false; 9313 } 9314 } 9315 9316 namespace { 9317 9318 // Callback to only accept typo corrections that are namespaces. 9319 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 9320 public: 9321 bool ValidateCandidate(const TypoCorrection &candidate) override { 9322 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9323 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9324 return false; 9325 } 9326 }; 9327 9328 } 9329 9330 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9331 CXXScopeSpec &SS, 9332 SourceLocation IdentLoc, 9333 IdentifierInfo *Ident) { 9334 R.clear(); 9335 if (TypoCorrection Corrected = 9336 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 9337 llvm::make_unique<NamespaceValidatorCCC>(), 9338 Sema::CTK_ErrorRecovery)) { 9339 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9340 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9341 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9342 Ident->getName().equals(CorrectedStr); 9343 S.diagnoseTypo(Corrected, 9344 S.PDiag(diag::err_using_directive_member_suggest) 9345 << Ident << DC << DroppedSpecifier << SS.getRange(), 9346 S.PDiag(diag::note_namespace_defined_here)); 9347 } else { 9348 S.diagnoseTypo(Corrected, 9349 S.PDiag(diag::err_using_directive_suggest) << Ident, 9350 S.PDiag(diag::note_namespace_defined_here)); 9351 } 9352 R.addDecl(Corrected.getFoundDecl()); 9353 return true; 9354 } 9355 return false; 9356 } 9357 9358 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 9359 SourceLocation NamespcLoc, CXXScopeSpec &SS, 9360 SourceLocation IdentLoc, 9361 IdentifierInfo *NamespcName, 9362 const ParsedAttributesView &AttrList) { 9363 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9364 assert(NamespcName && "Invalid NamespcName."); 9365 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9366 9367 // This can only happen along a recovery path. 9368 while (S->isTemplateParamScope()) 9369 S = S->getParent(); 9370 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9371 9372 UsingDirectiveDecl *UDir = nullptr; 9373 NestedNameSpecifier *Qualifier = nullptr; 9374 if (SS.isSet()) 9375 Qualifier = SS.getScopeRep(); 9376 9377 // Lookup namespace name. 9378 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9379 LookupParsedName(R, S, &SS); 9380 if (R.isAmbiguous()) 9381 return nullptr; 9382 9383 if (R.empty()) { 9384 R.clear(); 9385 // Allow "using namespace std;" or "using namespace ::std;" even if 9386 // "std" hasn't been defined yet, for GCC compatibility. 9387 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9388 NamespcName->isStr("std")) { 9389 Diag(IdentLoc, diag::ext_using_undefined_std); 9390 R.addDecl(getOrCreateStdNamespace()); 9391 R.resolveKind(); 9392 } 9393 // Otherwise, attempt typo correction. 9394 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9395 } 9396 9397 if (!R.empty()) { 9398 NamedDecl *Named = R.getRepresentativeDecl(); 9399 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9400 assert(NS && "expected namespace decl"); 9401 9402 // The use of a nested name specifier may trigger deprecation warnings. 9403 DiagnoseUseOfDecl(Named, IdentLoc); 9404 9405 // C++ [namespace.udir]p1: 9406 // A using-directive specifies that the names in the nominated 9407 // namespace can be used in the scope in which the 9408 // using-directive appears after the using-directive. During 9409 // unqualified name lookup (3.4.1), the names appear as if they 9410 // were declared in the nearest enclosing namespace which 9411 // contains both the using-directive and the nominated 9412 // namespace. [Note: in this context, "contains" means "contains 9413 // directly or indirectly". ] 9414 9415 // Find enclosing context containing both using-directive and 9416 // nominated namespace. 9417 DeclContext *CommonAncestor = NS; 9418 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9419 CommonAncestor = CommonAncestor->getParent(); 9420 9421 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9422 SS.getWithLocInContext(Context), 9423 IdentLoc, Named, CommonAncestor); 9424 9425 if (IsUsingDirectiveInToplevelContext(CurContext) && 9426 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9427 Diag(IdentLoc, diag::warn_using_directive_in_header); 9428 } 9429 9430 PushUsingDirective(S, UDir); 9431 } else { 9432 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9433 } 9434 9435 if (UDir) 9436 ProcessDeclAttributeList(S, UDir, AttrList); 9437 9438 return UDir; 9439 } 9440 9441 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9442 // If the scope has an associated entity and the using directive is at 9443 // namespace or translation unit scope, add the UsingDirectiveDecl into 9444 // its lookup structure so qualified name lookup can find it. 9445 DeclContext *Ctx = S->getEntity(); 9446 if (Ctx && !Ctx->isFunctionOrMethod()) 9447 Ctx->addDecl(UDir); 9448 else 9449 // Otherwise, it is at block scope. The using-directives will affect lookup 9450 // only to the end of the scope. 9451 S->PushUsingDirective(UDir); 9452 } 9453 9454 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 9455 SourceLocation UsingLoc, 9456 SourceLocation TypenameLoc, CXXScopeSpec &SS, 9457 UnqualifiedId &Name, 9458 SourceLocation EllipsisLoc, 9459 const ParsedAttributesView &AttrList) { 9460 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9461 9462 if (SS.isEmpty()) { 9463 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 9464 return nullptr; 9465 } 9466 9467 switch (Name.getKind()) { 9468 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9469 case UnqualifiedIdKind::IK_Identifier: 9470 case UnqualifiedIdKind::IK_OperatorFunctionId: 9471 case UnqualifiedIdKind::IK_LiteralOperatorId: 9472 case UnqualifiedIdKind::IK_ConversionFunctionId: 9473 break; 9474 9475 case UnqualifiedIdKind::IK_ConstructorName: 9476 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9477 // C++11 inheriting constructors. 9478 Diag(Name.getBeginLoc(), 9479 getLangOpts().CPlusPlus11 9480 ? diag::warn_cxx98_compat_using_decl_constructor 9481 : diag::err_using_decl_constructor) 9482 << SS.getRange(); 9483 9484 if (getLangOpts().CPlusPlus11) break; 9485 9486 return nullptr; 9487 9488 case UnqualifiedIdKind::IK_DestructorName: 9489 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 9490 return nullptr; 9491 9492 case UnqualifiedIdKind::IK_TemplateId: 9493 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 9494 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9495 return nullptr; 9496 9497 case UnqualifiedIdKind::IK_DeductionGuideName: 9498 llvm_unreachable("cannot parse qualified deduction guide name"); 9499 } 9500 9501 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9502 DeclarationName TargetName = TargetNameInfo.getName(); 9503 if (!TargetName) 9504 return nullptr; 9505 9506 // Warn about access declarations. 9507 if (UsingLoc.isInvalid()) { 9508 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 9509 ? diag::err_access_decl 9510 : diag::warn_access_decl_deprecated) 9511 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9512 } 9513 9514 if (EllipsisLoc.isInvalid()) { 9515 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9516 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9517 return nullptr; 9518 } else { 9519 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9520 !TargetNameInfo.containsUnexpandedParameterPack()) { 9521 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9522 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9523 EllipsisLoc = SourceLocation(); 9524 } 9525 } 9526 9527 NamedDecl *UD = 9528 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9529 SS, TargetNameInfo, EllipsisLoc, AttrList, 9530 /*IsInstantiation*/false); 9531 if (UD) 9532 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9533 9534 return UD; 9535 } 9536 9537 /// Determine whether a using declaration considers the given 9538 /// declarations as "equivalent", e.g., if they are redeclarations of 9539 /// the same entity or are both typedefs of the same type. 9540 static bool 9541 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9542 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9543 return true; 9544 9545 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9546 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9547 return Context.hasSameType(TD1->getUnderlyingType(), 9548 TD2->getUnderlyingType()); 9549 9550 return false; 9551 } 9552 9553 9554 /// Determines whether to create a using shadow decl for a particular 9555 /// decl, given the set of decls existing prior to this using lookup. 9556 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9557 const LookupResult &Previous, 9558 UsingShadowDecl *&PrevShadow) { 9559 // Diagnose finding a decl which is not from a base class of the 9560 // current class. We do this now because there are cases where this 9561 // function will silently decide not to build a shadow decl, which 9562 // will pre-empt further diagnostics. 9563 // 9564 // We don't need to do this in C++11 because we do the check once on 9565 // the qualifier. 9566 // 9567 // FIXME: diagnose the following if we care enough: 9568 // struct A { int foo; }; 9569 // struct B : A { using A::foo; }; 9570 // template <class T> struct C : A {}; 9571 // template <class T> struct D : C<T> { using B::foo; } // <--- 9572 // This is invalid (during instantiation) in C++03 because B::foo 9573 // resolves to the using decl in B, which is not a base class of D<T>. 9574 // We can't diagnose it immediately because C<T> is an unknown 9575 // specialization. The UsingShadowDecl in D<T> then points directly 9576 // to A::foo, which will look well-formed when we instantiate. 9577 // The right solution is to not collapse the shadow-decl chain. 9578 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9579 DeclContext *OrigDC = Orig->getDeclContext(); 9580 9581 // Handle enums and anonymous structs. 9582 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9583 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9584 while (OrigRec->isAnonymousStructOrUnion()) 9585 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9586 9587 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9588 if (OrigDC == CurContext) { 9589 Diag(Using->getLocation(), 9590 diag::err_using_decl_nested_name_specifier_is_current_class) 9591 << Using->getQualifierLoc().getSourceRange(); 9592 Diag(Orig->getLocation(), diag::note_using_decl_target); 9593 Using->setInvalidDecl(); 9594 return true; 9595 } 9596 9597 Diag(Using->getQualifierLoc().getBeginLoc(), 9598 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9599 << Using->getQualifier() 9600 << cast<CXXRecordDecl>(CurContext) 9601 << Using->getQualifierLoc().getSourceRange(); 9602 Diag(Orig->getLocation(), diag::note_using_decl_target); 9603 Using->setInvalidDecl(); 9604 return true; 9605 } 9606 } 9607 9608 if (Previous.empty()) return false; 9609 9610 NamedDecl *Target = Orig; 9611 if (isa<UsingShadowDecl>(Target)) 9612 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9613 9614 // If the target happens to be one of the previous declarations, we 9615 // don't have a conflict. 9616 // 9617 // FIXME: but we might be increasing its access, in which case we 9618 // should redeclare it. 9619 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9620 bool FoundEquivalentDecl = false; 9621 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9622 I != E; ++I) { 9623 NamedDecl *D = (*I)->getUnderlyingDecl(); 9624 // We can have UsingDecls in our Previous results because we use the same 9625 // LookupResult for checking whether the UsingDecl itself is a valid 9626 // redeclaration. 9627 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9628 continue; 9629 9630 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9631 // C++ [class.mem]p19: 9632 // If T is the name of a class, then [every named member other than 9633 // a non-static data member] shall have a name different from T 9634 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 9635 !isa<IndirectFieldDecl>(Target) && 9636 !isa<UnresolvedUsingValueDecl>(Target) && 9637 DiagnoseClassNameShadow( 9638 CurContext, 9639 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 9640 return true; 9641 } 9642 9643 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9644 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9645 PrevShadow = Shadow; 9646 FoundEquivalentDecl = true; 9647 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9648 // We don't conflict with an existing using shadow decl of an equivalent 9649 // declaration, but we're not a redeclaration of it. 9650 FoundEquivalentDecl = true; 9651 } 9652 9653 if (isVisible(D)) 9654 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9655 } 9656 9657 if (FoundEquivalentDecl) 9658 return false; 9659 9660 if (FunctionDecl *FD = Target->getAsFunction()) { 9661 NamedDecl *OldDecl = nullptr; 9662 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9663 /*IsForUsingDecl*/ true)) { 9664 case Ovl_Overload: 9665 return false; 9666 9667 case Ovl_NonFunction: 9668 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9669 break; 9670 9671 // We found a decl with the exact signature. 9672 case Ovl_Match: 9673 // If we're in a record, we want to hide the target, so we 9674 // return true (without a diagnostic) to tell the caller not to 9675 // build a shadow decl. 9676 if (CurContext->isRecord()) 9677 return true; 9678 9679 // If we're not in a record, this is an error. 9680 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9681 break; 9682 } 9683 9684 Diag(Target->getLocation(), diag::note_using_decl_target); 9685 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9686 Using->setInvalidDecl(); 9687 return true; 9688 } 9689 9690 // Target is not a function. 9691 9692 if (isa<TagDecl>(Target)) { 9693 // No conflict between a tag and a non-tag. 9694 if (!Tag) return false; 9695 9696 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9697 Diag(Target->getLocation(), diag::note_using_decl_target); 9698 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9699 Using->setInvalidDecl(); 9700 return true; 9701 } 9702 9703 // No conflict between a tag and a non-tag. 9704 if (!NonTag) return false; 9705 9706 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9707 Diag(Target->getLocation(), diag::note_using_decl_target); 9708 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9709 Using->setInvalidDecl(); 9710 return true; 9711 } 9712 9713 /// Determine whether a direct base class is a virtual base class. 9714 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9715 if (!Derived->getNumVBases()) 9716 return false; 9717 for (auto &B : Derived->bases()) 9718 if (B.getType()->getAsCXXRecordDecl() == Base) 9719 return B.isVirtual(); 9720 llvm_unreachable("not a direct base class"); 9721 } 9722 9723 /// Builds a shadow declaration corresponding to a 'using' declaration. 9724 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9725 UsingDecl *UD, 9726 NamedDecl *Orig, 9727 UsingShadowDecl *PrevDecl) { 9728 // If we resolved to another shadow declaration, just coalesce them. 9729 NamedDecl *Target = Orig; 9730 if (isa<UsingShadowDecl>(Target)) { 9731 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9732 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9733 } 9734 9735 NamedDecl *NonTemplateTarget = Target; 9736 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9737 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9738 9739 UsingShadowDecl *Shadow; 9740 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9741 bool IsVirtualBase = 9742 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9743 UD->getQualifier()->getAsRecordDecl()); 9744 Shadow = ConstructorUsingShadowDecl::Create( 9745 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9746 } else { 9747 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9748 Target); 9749 } 9750 UD->addShadowDecl(Shadow); 9751 9752 Shadow->setAccess(UD->getAccess()); 9753 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9754 Shadow->setInvalidDecl(); 9755 9756 Shadow->setPreviousDecl(PrevDecl); 9757 9758 if (S) 9759 PushOnScopeChains(Shadow, S); 9760 else 9761 CurContext->addDecl(Shadow); 9762 9763 9764 return Shadow; 9765 } 9766 9767 /// Hides a using shadow declaration. This is required by the current 9768 /// using-decl implementation when a resolvable using declaration in a 9769 /// class is followed by a declaration which would hide or override 9770 /// one or more of the using decl's targets; for example: 9771 /// 9772 /// struct Base { void foo(int); }; 9773 /// struct Derived : Base { 9774 /// using Base::foo; 9775 /// void foo(int); 9776 /// }; 9777 /// 9778 /// The governing language is C++03 [namespace.udecl]p12: 9779 /// 9780 /// When a using-declaration brings names from a base class into a 9781 /// derived class scope, member functions in the derived class 9782 /// override and/or hide member functions with the same name and 9783 /// parameter types in a base class (rather than conflicting). 9784 /// 9785 /// There are two ways to implement this: 9786 /// (1) optimistically create shadow decls when they're not hidden 9787 /// by existing declarations, or 9788 /// (2) don't create any shadow decls (or at least don't make them 9789 /// visible) until we've fully parsed/instantiated the class. 9790 /// The problem with (1) is that we might have to retroactively remove 9791 /// a shadow decl, which requires several O(n) operations because the 9792 /// decl structures are (very reasonably) not designed for removal. 9793 /// (2) avoids this but is very fiddly and phase-dependent. 9794 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9795 if (Shadow->getDeclName().getNameKind() == 9796 DeclarationName::CXXConversionFunctionName) 9797 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9798 9799 // Remove it from the DeclContext... 9800 Shadow->getDeclContext()->removeDecl(Shadow); 9801 9802 // ...and the scope, if applicable... 9803 if (S) { 9804 S->RemoveDecl(Shadow); 9805 IdResolver.RemoveDecl(Shadow); 9806 } 9807 9808 // ...and the using decl. 9809 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9810 9811 // TODO: complain somehow if Shadow was used. It shouldn't 9812 // be possible for this to happen, because...? 9813 } 9814 9815 /// Find the base specifier for a base class with the given type. 9816 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9817 QualType DesiredBase, 9818 bool &AnyDependentBases) { 9819 // Check whether the named type is a direct base class. 9820 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9821 for (auto &Base : Derived->bases()) { 9822 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9823 if (CanonicalDesiredBase == BaseType) 9824 return &Base; 9825 if (BaseType->isDependentType()) 9826 AnyDependentBases = true; 9827 } 9828 return nullptr; 9829 } 9830 9831 namespace { 9832 class UsingValidatorCCC : public CorrectionCandidateCallback { 9833 public: 9834 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9835 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9836 : HasTypenameKeyword(HasTypenameKeyword), 9837 IsInstantiation(IsInstantiation), OldNNS(NNS), 9838 RequireMemberOf(RequireMemberOf) {} 9839 9840 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9841 NamedDecl *ND = Candidate.getCorrectionDecl(); 9842 9843 // Keywords are not valid here. 9844 if (!ND || isa<NamespaceDecl>(ND)) 9845 return false; 9846 9847 // Completely unqualified names are invalid for a 'using' declaration. 9848 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9849 return false; 9850 9851 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9852 // reject. 9853 9854 if (RequireMemberOf) { 9855 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9856 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9857 // No-one ever wants a using-declaration to name an injected-class-name 9858 // of a base class, unless they're declaring an inheriting constructor. 9859 ASTContext &Ctx = ND->getASTContext(); 9860 if (!Ctx.getLangOpts().CPlusPlus11) 9861 return false; 9862 QualType FoundType = Ctx.getRecordType(FoundRecord); 9863 9864 // Check that the injected-class-name is named as a member of its own 9865 // type; we don't want to suggest 'using Derived::Base;', since that 9866 // means something else. 9867 NestedNameSpecifier *Specifier = 9868 Candidate.WillReplaceSpecifier() 9869 ? Candidate.getCorrectionSpecifier() 9870 : OldNNS; 9871 if (!Specifier->getAsType() || 9872 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9873 return false; 9874 9875 // Check that this inheriting constructor declaration actually names a 9876 // direct base class of the current class. 9877 bool AnyDependentBases = false; 9878 if (!findDirectBaseWithType(RequireMemberOf, 9879 Ctx.getRecordType(FoundRecord), 9880 AnyDependentBases) && 9881 !AnyDependentBases) 9882 return false; 9883 } else { 9884 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9885 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9886 return false; 9887 9888 // FIXME: Check that the base class member is accessible? 9889 } 9890 } else { 9891 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9892 if (FoundRecord && FoundRecord->isInjectedClassName()) 9893 return false; 9894 } 9895 9896 if (isa<TypeDecl>(ND)) 9897 return HasTypenameKeyword || !IsInstantiation; 9898 9899 return !HasTypenameKeyword; 9900 } 9901 9902 private: 9903 bool HasTypenameKeyword; 9904 bool IsInstantiation; 9905 NestedNameSpecifier *OldNNS; 9906 CXXRecordDecl *RequireMemberOf; 9907 }; 9908 } // end anonymous namespace 9909 9910 /// Builds a using declaration. 9911 /// 9912 /// \param IsInstantiation - Whether this call arises from an 9913 /// instantiation of an unresolved using declaration. We treat 9914 /// the lookup differently for these declarations. 9915 NamedDecl *Sema::BuildUsingDeclaration( 9916 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 9917 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 9918 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 9919 const ParsedAttributesView &AttrList, bool IsInstantiation) { 9920 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9921 SourceLocation IdentLoc = NameInfo.getLoc(); 9922 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9923 9924 // FIXME: We ignore attributes for now. 9925 9926 // For an inheriting constructor declaration, the name of the using 9927 // declaration is the name of a constructor in this class, not in the 9928 // base class. 9929 DeclarationNameInfo UsingName = NameInfo; 9930 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9931 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9932 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9933 Context.getCanonicalType(Context.getRecordType(RD)))); 9934 9935 // Do the redeclaration lookup in the current scope. 9936 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9937 ForVisibleRedeclaration); 9938 Previous.setHideTags(false); 9939 if (S) { 9940 LookupName(Previous, S); 9941 9942 // It is really dumb that we have to do this. 9943 LookupResult::Filter F = Previous.makeFilter(); 9944 while (F.hasNext()) { 9945 NamedDecl *D = F.next(); 9946 if (!isDeclInScope(D, CurContext, S)) 9947 F.erase(); 9948 // If we found a local extern declaration that's not ordinarily visible, 9949 // and this declaration is being added to a non-block scope, ignore it. 9950 // We're only checking for scope conflicts here, not also for violations 9951 // of the linkage rules. 9952 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9953 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9954 F.erase(); 9955 } 9956 F.done(); 9957 } else { 9958 assert(IsInstantiation && "no scope in non-instantiation"); 9959 if (CurContext->isRecord()) 9960 LookupQualifiedName(Previous, CurContext); 9961 else { 9962 // No redeclaration check is needed here; in non-member contexts we 9963 // diagnosed all possible conflicts with other using-declarations when 9964 // building the template: 9965 // 9966 // For a dependent non-type using declaration, the only valid case is 9967 // if we instantiate to a single enumerator. We check for conflicts 9968 // between shadow declarations we introduce, and we check in the template 9969 // definition for conflicts between a non-type using declaration and any 9970 // other declaration, which together covers all cases. 9971 // 9972 // A dependent typename using declaration will never successfully 9973 // instantiate, since it will always name a class member, so we reject 9974 // that in the template definition. 9975 } 9976 } 9977 9978 // Check for invalid redeclarations. 9979 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9980 SS, IdentLoc, Previous)) 9981 return nullptr; 9982 9983 // Check for bad qualifiers. 9984 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9985 IdentLoc)) 9986 return nullptr; 9987 9988 DeclContext *LookupContext = computeDeclContext(SS); 9989 NamedDecl *D; 9990 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9991 if (!LookupContext || EllipsisLoc.isValid()) { 9992 if (HasTypenameKeyword) { 9993 // FIXME: not all declaration name kinds are legal here 9994 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9995 UsingLoc, TypenameLoc, 9996 QualifierLoc, 9997 IdentLoc, NameInfo.getName(), 9998 EllipsisLoc); 9999 } else { 10000 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 10001 QualifierLoc, NameInfo, EllipsisLoc); 10002 } 10003 D->setAccess(AS); 10004 CurContext->addDecl(D); 10005 return D; 10006 } 10007 10008 auto Build = [&](bool Invalid) { 10009 UsingDecl *UD = 10010 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 10011 UsingName, HasTypenameKeyword); 10012 UD->setAccess(AS); 10013 CurContext->addDecl(UD); 10014 UD->setInvalidDecl(Invalid); 10015 return UD; 10016 }; 10017 auto BuildInvalid = [&]{ return Build(true); }; 10018 auto BuildValid = [&]{ return Build(false); }; 10019 10020 if (RequireCompleteDeclContext(SS, LookupContext)) 10021 return BuildInvalid(); 10022 10023 // Look up the target name. 10024 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10025 10026 // Unlike most lookups, we don't always want to hide tag 10027 // declarations: tag names are visible through the using declaration 10028 // even if hidden by ordinary names, *except* in a dependent context 10029 // where it's important for the sanity of two-phase lookup. 10030 if (!IsInstantiation) 10031 R.setHideTags(false); 10032 10033 // For the purposes of this lookup, we have a base object type 10034 // equal to that of the current context. 10035 if (CurContext->isRecord()) { 10036 R.setBaseObjectType( 10037 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 10038 } 10039 10040 LookupQualifiedName(R, LookupContext); 10041 10042 // Try to correct typos if possible. If constructor name lookup finds no 10043 // results, that means the named class has no explicit constructors, and we 10044 // suppressed declaring implicit ones (probably because it's dependent or 10045 // invalid). 10046 if (R.empty() && 10047 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 10048 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 10049 // it will believe that glibc provides a ::gets in cases where it does not, 10050 // and will try to pull it into namespace std with a using-declaration. 10051 // Just ignore the using-declaration in that case. 10052 auto *II = NameInfo.getName().getAsIdentifierInfo(); 10053 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 10054 CurContext->isStdNamespace() && 10055 isa<TranslationUnitDecl>(LookupContext) && 10056 getSourceManager().isInSystemHeader(UsingLoc)) 10057 return nullptr; 10058 if (TypoCorrection Corrected = CorrectTypo( 10059 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 10060 llvm::make_unique<UsingValidatorCCC>( 10061 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 10062 dyn_cast<CXXRecordDecl>(CurContext)), 10063 CTK_ErrorRecovery)) { 10064 // We reject candidates where DroppedSpecifier == true, hence the 10065 // literal '0' below. 10066 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 10067 << NameInfo.getName() << LookupContext << 0 10068 << SS.getRange()); 10069 10070 // If we picked a correction with no attached Decl we can't do anything 10071 // useful with it, bail out. 10072 NamedDecl *ND = Corrected.getCorrectionDecl(); 10073 if (!ND) 10074 return BuildInvalid(); 10075 10076 // If we corrected to an inheriting constructor, handle it as one. 10077 auto *RD = dyn_cast<CXXRecordDecl>(ND); 10078 if (RD && RD->isInjectedClassName()) { 10079 // The parent of the injected class name is the class itself. 10080 RD = cast<CXXRecordDecl>(RD->getParent()); 10081 10082 // Fix up the information we'll use to build the using declaration. 10083 if (Corrected.WillReplaceSpecifier()) { 10084 NestedNameSpecifierLocBuilder Builder; 10085 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 10086 QualifierLoc.getSourceRange()); 10087 QualifierLoc = Builder.getWithLocInContext(Context); 10088 } 10089 10090 // In this case, the name we introduce is the name of a derived class 10091 // constructor. 10092 auto *CurClass = cast<CXXRecordDecl>(CurContext); 10093 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10094 Context.getCanonicalType(Context.getRecordType(CurClass)))); 10095 UsingName.setNamedTypeInfo(nullptr); 10096 for (auto *Ctor : LookupConstructors(RD)) 10097 R.addDecl(Ctor); 10098 R.resolveKind(); 10099 } else { 10100 // FIXME: Pick up all the declarations if we found an overloaded 10101 // function. 10102 UsingName.setName(ND->getDeclName()); 10103 R.addDecl(ND); 10104 } 10105 } else { 10106 Diag(IdentLoc, diag::err_no_member) 10107 << NameInfo.getName() << LookupContext << SS.getRange(); 10108 return BuildInvalid(); 10109 } 10110 } 10111 10112 if (R.isAmbiguous()) 10113 return BuildInvalid(); 10114 10115 if (HasTypenameKeyword) { 10116 // If we asked for a typename and got a non-type decl, error out. 10117 if (!R.getAsSingle<TypeDecl>()) { 10118 Diag(IdentLoc, diag::err_using_typename_non_type); 10119 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10120 Diag((*I)->getUnderlyingDecl()->getLocation(), 10121 diag::note_using_decl_target); 10122 return BuildInvalid(); 10123 } 10124 } else { 10125 // If we asked for a non-typename and we got a type, error out, 10126 // but only if this is an instantiation of an unresolved using 10127 // decl. Otherwise just silently find the type name. 10128 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10129 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10130 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10131 return BuildInvalid(); 10132 } 10133 } 10134 10135 // C++14 [namespace.udecl]p6: 10136 // A using-declaration shall not name a namespace. 10137 if (R.getAsSingle<NamespaceDecl>()) { 10138 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10139 << SS.getRange(); 10140 return BuildInvalid(); 10141 } 10142 10143 // C++14 [namespace.udecl]p7: 10144 // A using-declaration shall not name a scoped enumerator. 10145 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10146 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10147 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10148 << SS.getRange(); 10149 return BuildInvalid(); 10150 } 10151 } 10152 10153 UsingDecl *UD = BuildValid(); 10154 10155 // Some additional rules apply to inheriting constructors. 10156 if (UsingName.getName().getNameKind() == 10157 DeclarationName::CXXConstructorName) { 10158 // Suppress access diagnostics; the access check is instead performed at the 10159 // point of use for an inheriting constructor. 10160 R.suppressDiagnostics(); 10161 if (CheckInheritingConstructorUsingDecl(UD)) 10162 return UD; 10163 } 10164 10165 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10166 UsingShadowDecl *PrevDecl = nullptr; 10167 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10168 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10169 } 10170 10171 return UD; 10172 } 10173 10174 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10175 ArrayRef<NamedDecl *> Expansions) { 10176 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10177 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10178 isa<UsingPackDecl>(InstantiatedFrom)); 10179 10180 auto *UPD = 10181 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10182 UPD->setAccess(InstantiatedFrom->getAccess()); 10183 CurContext->addDecl(UPD); 10184 return UPD; 10185 } 10186 10187 /// Additional checks for a using declaration referring to a constructor name. 10188 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10189 assert(!UD->hasTypename() && "expecting a constructor name"); 10190 10191 const Type *SourceType = UD->getQualifier()->getAsType(); 10192 assert(SourceType && 10193 "Using decl naming constructor doesn't have type in scope spec."); 10194 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10195 10196 // Check whether the named type is a direct base class. 10197 bool AnyDependentBases = false; 10198 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10199 AnyDependentBases); 10200 if (!Base && !AnyDependentBases) { 10201 Diag(UD->getUsingLoc(), 10202 diag::err_using_decl_constructor_not_in_direct_base) 10203 << UD->getNameInfo().getSourceRange() 10204 << QualType(SourceType, 0) << TargetClass; 10205 UD->setInvalidDecl(); 10206 return true; 10207 } 10208 10209 if (Base) 10210 Base->setInheritConstructors(); 10211 10212 return false; 10213 } 10214 10215 /// Checks that the given using declaration is not an invalid 10216 /// redeclaration. Note that this is checking only for the using decl 10217 /// itself, not for any ill-formedness among the UsingShadowDecls. 10218 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10219 bool HasTypenameKeyword, 10220 const CXXScopeSpec &SS, 10221 SourceLocation NameLoc, 10222 const LookupResult &Prev) { 10223 NestedNameSpecifier *Qual = SS.getScopeRep(); 10224 10225 // C++03 [namespace.udecl]p8: 10226 // C++0x [namespace.udecl]p10: 10227 // A using-declaration is a declaration and can therefore be used 10228 // repeatedly where (and only where) multiple declarations are 10229 // allowed. 10230 // 10231 // That's in non-member contexts. 10232 if (!CurContext->getRedeclContext()->isRecord()) { 10233 // A dependent qualifier outside a class can only ever resolve to an 10234 // enumeration type. Therefore it conflicts with any other non-type 10235 // declaration in the same scope. 10236 // FIXME: How should we check for dependent type-type conflicts at block 10237 // scope? 10238 if (Qual->isDependent() && !HasTypenameKeyword) { 10239 for (auto *D : Prev) { 10240 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10241 bool OldCouldBeEnumerator = 10242 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10243 Diag(NameLoc, 10244 OldCouldBeEnumerator ? diag::err_redefinition 10245 : diag::err_redefinition_different_kind) 10246 << Prev.getLookupName(); 10247 Diag(D->getLocation(), diag::note_previous_definition); 10248 return true; 10249 } 10250 } 10251 } 10252 return false; 10253 } 10254 10255 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10256 NamedDecl *D = *I; 10257 10258 bool DTypename; 10259 NestedNameSpecifier *DQual; 10260 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10261 DTypename = UD->hasTypename(); 10262 DQual = UD->getQualifier(); 10263 } else if (UnresolvedUsingValueDecl *UD 10264 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10265 DTypename = false; 10266 DQual = UD->getQualifier(); 10267 } else if (UnresolvedUsingTypenameDecl *UD 10268 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10269 DTypename = true; 10270 DQual = UD->getQualifier(); 10271 } else continue; 10272 10273 // using decls differ if one says 'typename' and the other doesn't. 10274 // FIXME: non-dependent using decls? 10275 if (HasTypenameKeyword != DTypename) continue; 10276 10277 // using decls differ if they name different scopes (but note that 10278 // template instantiation can cause this check to trigger when it 10279 // didn't before instantiation). 10280 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10281 Context.getCanonicalNestedNameSpecifier(DQual)) 10282 continue; 10283 10284 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10285 Diag(D->getLocation(), diag::note_using_decl) << 1; 10286 return true; 10287 } 10288 10289 return false; 10290 } 10291 10292 10293 /// Checks that the given nested-name qualifier used in a using decl 10294 /// in the current context is appropriately related to the current 10295 /// scope. If an error is found, diagnoses it and returns true. 10296 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10297 bool HasTypename, 10298 const CXXScopeSpec &SS, 10299 const DeclarationNameInfo &NameInfo, 10300 SourceLocation NameLoc) { 10301 DeclContext *NamedContext = computeDeclContext(SS); 10302 10303 if (!CurContext->isRecord()) { 10304 // C++03 [namespace.udecl]p3: 10305 // C++0x [namespace.udecl]p8: 10306 // A using-declaration for a class member shall be a member-declaration. 10307 10308 // If we weren't able to compute a valid scope, it might validly be a 10309 // dependent class scope or a dependent enumeration unscoped scope. If 10310 // we have a 'typename' keyword, the scope must resolve to a class type. 10311 if ((HasTypename && !NamedContext) || 10312 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10313 auto *RD = NamedContext 10314 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10315 : nullptr; 10316 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10317 RD = nullptr; 10318 10319 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10320 << SS.getRange(); 10321 10322 // If we have a complete, non-dependent source type, try to suggest a 10323 // way to get the same effect. 10324 if (!RD) 10325 return true; 10326 10327 // Find what this using-declaration was referring to. 10328 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10329 R.setHideTags(false); 10330 R.suppressDiagnostics(); 10331 LookupQualifiedName(R, RD); 10332 10333 if (R.getAsSingle<TypeDecl>()) { 10334 if (getLangOpts().CPlusPlus11) { 10335 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10336 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10337 << 0 // alias declaration 10338 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10339 NameInfo.getName().getAsString() + 10340 " = "); 10341 } else { 10342 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10343 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 10344 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10345 << 1 // typedef declaration 10346 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10347 << FixItHint::CreateInsertion( 10348 InsertLoc, " " + NameInfo.getName().getAsString()); 10349 } 10350 } else if (R.getAsSingle<VarDecl>()) { 10351 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10352 // repeating the type of the static data member here. 10353 FixItHint FixIt; 10354 if (getLangOpts().CPlusPlus11) { 10355 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10356 FixIt = FixItHint::CreateReplacement( 10357 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10358 } 10359 10360 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10361 << 2 // reference declaration 10362 << FixIt; 10363 } else if (R.getAsSingle<EnumConstantDecl>()) { 10364 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10365 // repeating the type of the enumeration here, and we can't do so if 10366 // the type is anonymous. 10367 FixItHint FixIt; 10368 if (getLangOpts().CPlusPlus11) { 10369 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10370 FixIt = FixItHint::CreateReplacement( 10371 UsingLoc, 10372 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10373 } 10374 10375 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10376 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10377 << FixIt; 10378 } 10379 return true; 10380 } 10381 10382 // Otherwise, this might be valid. 10383 return false; 10384 } 10385 10386 // The current scope is a record. 10387 10388 // If the named context is dependent, we can't decide much. 10389 if (!NamedContext) { 10390 // FIXME: in C++0x, we can diagnose if we can prove that the 10391 // nested-name-specifier does not refer to a base class, which is 10392 // still possible in some cases. 10393 10394 // Otherwise we have to conservatively report that things might be 10395 // okay. 10396 return false; 10397 } 10398 10399 if (!NamedContext->isRecord()) { 10400 // Ideally this would point at the last name in the specifier, 10401 // but we don't have that level of source info. 10402 Diag(SS.getRange().getBegin(), 10403 diag::err_using_decl_nested_name_specifier_is_not_class) 10404 << SS.getScopeRep() << SS.getRange(); 10405 return true; 10406 } 10407 10408 if (!NamedContext->isDependentContext() && 10409 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10410 return true; 10411 10412 if (getLangOpts().CPlusPlus11) { 10413 // C++11 [namespace.udecl]p3: 10414 // In a using-declaration used as a member-declaration, the 10415 // nested-name-specifier shall name a base class of the class 10416 // being defined. 10417 10418 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10419 cast<CXXRecordDecl>(NamedContext))) { 10420 if (CurContext == NamedContext) { 10421 Diag(NameLoc, 10422 diag::err_using_decl_nested_name_specifier_is_current_class) 10423 << SS.getRange(); 10424 return true; 10425 } 10426 10427 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10428 Diag(SS.getRange().getBegin(), 10429 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10430 << SS.getScopeRep() 10431 << cast<CXXRecordDecl>(CurContext) 10432 << SS.getRange(); 10433 } 10434 return true; 10435 } 10436 10437 return false; 10438 } 10439 10440 // C++03 [namespace.udecl]p4: 10441 // A using-declaration used as a member-declaration shall refer 10442 // to a member of a base class of the class being defined [etc.]. 10443 10444 // Salient point: SS doesn't have to name a base class as long as 10445 // lookup only finds members from base classes. Therefore we can 10446 // diagnose here only if we can prove that that can't happen, 10447 // i.e. if the class hierarchies provably don't intersect. 10448 10449 // TODO: it would be nice if "definitely valid" results were cached 10450 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10451 // need to be repeated. 10452 10453 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10454 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10455 Bases.insert(Base); 10456 return true; 10457 }; 10458 10459 // Collect all bases. Return false if we find a dependent base. 10460 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10461 return false; 10462 10463 // Returns true if the base is dependent or is one of the accumulated base 10464 // classes. 10465 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10466 return !Bases.count(Base); 10467 }; 10468 10469 // Return false if the class has a dependent base or if it or one 10470 // of its bases is present in the base set of the current context. 10471 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10472 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10473 return false; 10474 10475 Diag(SS.getRange().getBegin(), 10476 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10477 << SS.getScopeRep() 10478 << cast<CXXRecordDecl>(CurContext) 10479 << SS.getRange(); 10480 10481 return true; 10482 } 10483 10484 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 10485 MultiTemplateParamsArg TemplateParamLists, 10486 SourceLocation UsingLoc, UnqualifiedId &Name, 10487 const ParsedAttributesView &AttrList, 10488 TypeResult Type, Decl *DeclFromDeclSpec) { 10489 // Skip up to the relevant declaration scope. 10490 while (S->isTemplateParamScope()) 10491 S = S->getParent(); 10492 assert((S->getFlags() & Scope::DeclScope) && 10493 "got alias-declaration outside of declaration scope"); 10494 10495 if (Type.isInvalid()) 10496 return nullptr; 10497 10498 bool Invalid = false; 10499 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10500 TypeSourceInfo *TInfo = nullptr; 10501 GetTypeFromParser(Type.get(), &TInfo); 10502 10503 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10504 return nullptr; 10505 10506 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10507 UPPC_DeclarationType)) { 10508 Invalid = true; 10509 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10510 TInfo->getTypeLoc().getBeginLoc()); 10511 } 10512 10513 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10514 TemplateParamLists.size() 10515 ? forRedeclarationInCurContext() 10516 : ForVisibleRedeclaration); 10517 LookupName(Previous, S); 10518 10519 // Warn about shadowing the name of a template parameter. 10520 if (Previous.isSingleResult() && 10521 Previous.getFoundDecl()->isTemplateParameter()) { 10522 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10523 Previous.clear(); 10524 } 10525 10526 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10527 "name in alias declaration must be an identifier"); 10528 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10529 Name.StartLocation, 10530 Name.Identifier, TInfo); 10531 10532 NewTD->setAccess(AS); 10533 10534 if (Invalid) 10535 NewTD->setInvalidDecl(); 10536 10537 ProcessDeclAttributeList(S, NewTD, AttrList); 10538 AddPragmaAttributes(S, NewTD); 10539 10540 CheckTypedefForVariablyModifiedType(S, NewTD); 10541 Invalid |= NewTD->isInvalidDecl(); 10542 10543 bool Redeclaration = false; 10544 10545 NamedDecl *NewND; 10546 if (TemplateParamLists.size()) { 10547 TypeAliasTemplateDecl *OldDecl = nullptr; 10548 TemplateParameterList *OldTemplateParams = nullptr; 10549 10550 if (TemplateParamLists.size() != 1) { 10551 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10552 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10553 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10554 } 10555 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10556 10557 // Check that we can declare a template here. 10558 if (CheckTemplateDeclScope(S, TemplateParams)) 10559 return nullptr; 10560 10561 // Only consider previous declarations in the same scope. 10562 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10563 /*ExplicitInstantiationOrSpecialization*/false); 10564 if (!Previous.empty()) { 10565 Redeclaration = true; 10566 10567 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10568 if (!OldDecl && !Invalid) { 10569 Diag(UsingLoc, diag::err_redefinition_different_kind) 10570 << Name.Identifier; 10571 10572 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10573 if (OldD->getLocation().isValid()) 10574 Diag(OldD->getLocation(), diag::note_previous_definition); 10575 10576 Invalid = true; 10577 } 10578 10579 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10580 if (TemplateParameterListsAreEqual(TemplateParams, 10581 OldDecl->getTemplateParameters(), 10582 /*Complain=*/true, 10583 TPL_TemplateMatch)) 10584 OldTemplateParams = 10585 OldDecl->getMostRecentDecl()->getTemplateParameters(); 10586 else 10587 Invalid = true; 10588 10589 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10590 if (!Invalid && 10591 !Context.hasSameType(OldTD->getUnderlyingType(), 10592 NewTD->getUnderlyingType())) { 10593 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10594 // but we can't reasonably accept it. 10595 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10596 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10597 if (OldTD->getLocation().isValid()) 10598 Diag(OldTD->getLocation(), diag::note_previous_definition); 10599 Invalid = true; 10600 } 10601 } 10602 } 10603 10604 // Merge any previous default template arguments into our parameters, 10605 // and check the parameter list. 10606 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10607 TPC_TypeAliasTemplate)) 10608 return nullptr; 10609 10610 TypeAliasTemplateDecl *NewDecl = 10611 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10612 Name.Identifier, TemplateParams, 10613 NewTD); 10614 NewTD->setDescribedAliasTemplate(NewDecl); 10615 10616 NewDecl->setAccess(AS); 10617 10618 if (Invalid) 10619 NewDecl->setInvalidDecl(); 10620 else if (OldDecl) { 10621 NewDecl->setPreviousDecl(OldDecl); 10622 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10623 } 10624 10625 NewND = NewDecl; 10626 } else { 10627 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10628 setTagNameForLinkagePurposes(TD, NewTD); 10629 handleTagNumbering(TD, S); 10630 } 10631 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10632 NewND = NewTD; 10633 } 10634 10635 PushOnScopeChains(NewND, S); 10636 ActOnDocumentableDecl(NewND); 10637 return NewND; 10638 } 10639 10640 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10641 SourceLocation AliasLoc, 10642 IdentifierInfo *Alias, CXXScopeSpec &SS, 10643 SourceLocation IdentLoc, 10644 IdentifierInfo *Ident) { 10645 10646 // Lookup the namespace name. 10647 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10648 LookupParsedName(R, S, &SS); 10649 10650 if (R.isAmbiguous()) 10651 return nullptr; 10652 10653 if (R.empty()) { 10654 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10655 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10656 return nullptr; 10657 } 10658 } 10659 assert(!R.isAmbiguous() && !R.empty()); 10660 NamedDecl *ND = R.getRepresentativeDecl(); 10661 10662 // Check if we have a previous declaration with the same name. 10663 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10664 ForVisibleRedeclaration); 10665 LookupName(PrevR, S); 10666 10667 // Check we're not shadowing a template parameter. 10668 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10669 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10670 PrevR.clear(); 10671 } 10672 10673 // Filter out any other lookup result from an enclosing scope. 10674 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10675 /*AllowInlineNamespace*/false); 10676 10677 // Find the previous declaration and check that we can redeclare it. 10678 NamespaceAliasDecl *Prev = nullptr; 10679 if (PrevR.isSingleResult()) { 10680 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10681 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10682 // We already have an alias with the same name that points to the same 10683 // namespace; check that it matches. 10684 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10685 Prev = AD; 10686 } else if (isVisible(PrevDecl)) { 10687 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10688 << Alias; 10689 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10690 << AD->getNamespace(); 10691 return nullptr; 10692 } 10693 } else if (isVisible(PrevDecl)) { 10694 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10695 ? diag::err_redefinition 10696 : diag::err_redefinition_different_kind; 10697 Diag(AliasLoc, DiagID) << Alias; 10698 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10699 return nullptr; 10700 } 10701 } 10702 10703 // The use of a nested name specifier may trigger deprecation warnings. 10704 DiagnoseUseOfDecl(ND, IdentLoc); 10705 10706 NamespaceAliasDecl *AliasDecl = 10707 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10708 Alias, SS.getWithLocInContext(Context), 10709 IdentLoc, ND); 10710 if (Prev) 10711 AliasDecl->setPreviousDecl(Prev); 10712 10713 PushOnScopeChains(AliasDecl, S); 10714 return AliasDecl; 10715 } 10716 10717 namespace { 10718 struct SpecialMemberExceptionSpecInfo 10719 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10720 SourceLocation Loc; 10721 Sema::ImplicitExceptionSpecification ExceptSpec; 10722 10723 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10724 Sema::CXXSpecialMember CSM, 10725 Sema::InheritedConstructorInfo *ICI, 10726 SourceLocation Loc) 10727 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10728 10729 bool visitBase(CXXBaseSpecifier *Base); 10730 bool visitField(FieldDecl *FD); 10731 10732 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10733 unsigned Quals); 10734 10735 void visitSubobjectCall(Subobject Subobj, 10736 Sema::SpecialMemberOverloadResult SMOR); 10737 }; 10738 } 10739 10740 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10741 auto *RT = Base->getType()->getAs<RecordType>(); 10742 if (!RT) 10743 return false; 10744 10745 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10746 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10747 if (auto *BaseCtor = SMOR.getMethod()) { 10748 visitSubobjectCall(Base, BaseCtor); 10749 return false; 10750 } 10751 10752 visitClassSubobject(BaseClass, Base, 0); 10753 return false; 10754 } 10755 10756 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10757 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10758 Expr *E = FD->getInClassInitializer(); 10759 if (!E) 10760 // FIXME: It's a little wasteful to build and throw away a 10761 // CXXDefaultInitExpr here. 10762 // FIXME: We should have a single context note pointing at Loc, and 10763 // this location should be MD->getLocation() instead, since that's 10764 // the location where we actually use the default init expression. 10765 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10766 if (E) 10767 ExceptSpec.CalledExpr(E); 10768 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10769 ->getAs<RecordType>()) { 10770 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10771 FD->getType().getCVRQualifiers()); 10772 } 10773 return false; 10774 } 10775 10776 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10777 Subobject Subobj, 10778 unsigned Quals) { 10779 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10780 bool IsMutable = Field && Field->isMutable(); 10781 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10782 } 10783 10784 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10785 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10786 // Note, if lookup fails, it doesn't matter what exception specification we 10787 // choose because the special member will be deleted. 10788 if (CXXMethodDecl *MD = SMOR.getMethod()) 10789 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10790 } 10791 10792 namespace { 10793 /// RAII object to register a special member as being currently declared. 10794 struct ComputingExceptionSpec { 10795 Sema &S; 10796 10797 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) 10798 : S(S) { 10799 Sema::CodeSynthesisContext Ctx; 10800 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 10801 Ctx.PointOfInstantiation = Loc; 10802 Ctx.Entity = MD; 10803 S.pushCodeSynthesisContext(Ctx); 10804 } 10805 ~ComputingExceptionSpec() { 10806 S.popCodeSynthesisContext(); 10807 } 10808 }; 10809 } 10810 10811 static Sema::ImplicitExceptionSpecification 10812 ComputeDefaultedSpecialMemberExceptionSpec( 10813 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10814 Sema::InheritedConstructorInfo *ICI) { 10815 ComputingExceptionSpec CES(S, MD, Loc); 10816 10817 CXXRecordDecl *ClassDecl = MD->getParent(); 10818 10819 // C++ [except.spec]p14: 10820 // An implicitly declared special member function (Clause 12) shall have an 10821 // exception-specification. [...] 10822 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 10823 if (ClassDecl->isInvalidDecl()) 10824 return Info.ExceptSpec; 10825 10826 // FIXME: If this diagnostic fires, we're probably missing a check for 10827 // attempting to resolve an exception specification before it's known 10828 // at a higher level. 10829 if (S.RequireCompleteType(MD->getLocation(), 10830 S.Context.getRecordType(ClassDecl), 10831 diag::err_exception_spec_incomplete_type)) 10832 return Info.ExceptSpec; 10833 10834 // C++1z [except.spec]p7: 10835 // [Look for exceptions thrown by] a constructor selected [...] to 10836 // initialize a potentially constructed subobject, 10837 // C++1z [except.spec]p8: 10838 // The exception specification for an implicitly-declared destructor, or a 10839 // destructor without a noexcept-specifier, is potentially-throwing if and 10840 // only if any of the destructors for any of its potentially constructed 10841 // subojects is potentially throwing. 10842 // FIXME: We respect the first rule but ignore the "potentially constructed" 10843 // in the second rule to resolve a core issue (no number yet) that would have 10844 // us reject: 10845 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10846 // struct B : A {}; 10847 // struct C : B { void f(); }; 10848 // ... due to giving B::~B() a non-throwing exception specification. 10849 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10850 : Info.VisitAllBases); 10851 10852 return Info.ExceptSpec; 10853 } 10854 10855 namespace { 10856 /// RAII object to register a special member as being currently declared. 10857 struct DeclaringSpecialMember { 10858 Sema &S; 10859 Sema::SpecialMemberDecl D; 10860 Sema::ContextRAII SavedContext; 10861 bool WasAlreadyBeingDeclared; 10862 10863 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10864 : S(S), D(RD, CSM), SavedContext(S, RD) { 10865 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10866 if (WasAlreadyBeingDeclared) 10867 // This almost never happens, but if it does, ensure that our cache 10868 // doesn't contain a stale result. 10869 S.SpecialMemberCache.clear(); 10870 else { 10871 // Register a note to be produced if we encounter an error while 10872 // declaring the special member. 10873 Sema::CodeSynthesisContext Ctx; 10874 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10875 // FIXME: We don't have a location to use here. Using the class's 10876 // location maintains the fiction that we declare all special members 10877 // with the class, but (1) it's not clear that lying about that helps our 10878 // users understand what's going on, and (2) there may be outer contexts 10879 // on the stack (some of which are relevant) and printing them exposes 10880 // our lies. 10881 Ctx.PointOfInstantiation = RD->getLocation(); 10882 Ctx.Entity = RD; 10883 Ctx.SpecialMember = CSM; 10884 S.pushCodeSynthesisContext(Ctx); 10885 } 10886 } 10887 ~DeclaringSpecialMember() { 10888 if (!WasAlreadyBeingDeclared) { 10889 S.SpecialMembersBeingDeclared.erase(D); 10890 S.popCodeSynthesisContext(); 10891 } 10892 } 10893 10894 /// Are we already trying to declare this special member? 10895 bool isAlreadyBeingDeclared() const { 10896 return WasAlreadyBeingDeclared; 10897 } 10898 }; 10899 } 10900 10901 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10902 // Look up any existing declarations, but don't trigger declaration of all 10903 // implicit special members with this name. 10904 DeclarationName Name = FD->getDeclName(); 10905 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10906 ForExternalRedeclaration); 10907 for (auto *D : FD->getParent()->lookup(Name)) 10908 if (auto *Acceptable = R.getAcceptableDecl(D)) 10909 R.addDecl(Acceptable); 10910 R.resolveKind(); 10911 R.suppressDiagnostics(); 10912 10913 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10914 } 10915 10916 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 10917 QualType ResultTy, 10918 ArrayRef<QualType> Args) { 10919 // Build an exception specification pointing back at this constructor. 10920 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 10921 10922 if (getLangOpts().OpenCLCPlusPlus) { 10923 // OpenCL: Implicitly defaulted special member are of the generic address 10924 // space. 10925 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic); 10926 } 10927 10928 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 10929 SpecialMem->setType(QT); 10930 } 10931 10932 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10933 CXXRecordDecl *ClassDecl) { 10934 // C++ [class.ctor]p5: 10935 // A default constructor for a class X is a constructor of class X 10936 // that can be called without an argument. If there is no 10937 // user-declared constructor for class X, a default constructor is 10938 // implicitly declared. An implicitly-declared default constructor 10939 // is an inline public member of its class. 10940 assert(ClassDecl->needsImplicitDefaultConstructor() && 10941 "Should not build implicit default constructor!"); 10942 10943 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10944 if (DSM.isAlreadyBeingDeclared()) 10945 return nullptr; 10946 10947 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10948 CXXDefaultConstructor, 10949 false); 10950 10951 // Create the actual constructor declaration. 10952 CanQualType ClassType 10953 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10954 SourceLocation ClassLoc = ClassDecl->getLocation(); 10955 DeclarationName Name 10956 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10957 DeclarationNameInfo NameInfo(Name, ClassLoc); 10958 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10959 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10960 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10961 /*isImplicitlyDeclared=*/true, Constexpr); 10962 DefaultCon->setAccess(AS_public); 10963 DefaultCon->setDefaulted(); 10964 10965 if (getLangOpts().CUDA) { 10966 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10967 DefaultCon, 10968 /* ConstRHS */ false, 10969 /* Diagnose */ false); 10970 } 10971 10972 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 10973 10974 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10975 // constructors is easy to compute. 10976 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10977 10978 // Note that we have declared this constructor. 10979 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10980 10981 Scope *S = getScopeForContext(ClassDecl); 10982 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10983 10984 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10985 SetDeclDeleted(DefaultCon, ClassLoc); 10986 10987 if (S) 10988 PushOnScopeChains(DefaultCon, S, false); 10989 ClassDecl->addDecl(DefaultCon); 10990 10991 return DefaultCon; 10992 } 10993 10994 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10995 CXXConstructorDecl *Constructor) { 10996 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10997 !Constructor->doesThisDeclarationHaveABody() && 10998 !Constructor->isDeleted()) && 10999 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 11000 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11001 return; 11002 11003 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11004 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 11005 11006 SynthesizedFunctionScope Scope(*this, Constructor); 11007 11008 // The exception specification is needed because we are defining the 11009 // function. 11010 ResolveExceptionSpec(CurrentLocation, 11011 Constructor->getType()->castAs<FunctionProtoType>()); 11012 MarkVTableUsed(CurrentLocation, ClassDecl); 11013 11014 // Add a context note for diagnostics produced after this point. 11015 Scope.addContextNote(CurrentLocation); 11016 11017 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 11018 Constructor->setInvalidDecl(); 11019 return; 11020 } 11021 11022 SourceLocation Loc = Constructor->getEndLoc().isValid() 11023 ? Constructor->getEndLoc() 11024 : Constructor->getLocation(); 11025 Constructor->setBody(new (Context) CompoundStmt(Loc)); 11026 Constructor->markUsed(Context); 11027 11028 if (ASTMutationListener *L = getASTMutationListener()) { 11029 L->CompletedImplicitDefinition(Constructor); 11030 } 11031 11032 DiagnoseUninitializedFields(*this, Constructor); 11033 } 11034 11035 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 11036 // Perform any delayed checks on exception specifications. 11037 CheckDelayedMemberExceptionSpecs(); 11038 } 11039 11040 /// Find or create the fake constructor we synthesize to model constructing an 11041 /// object of a derived class via a constructor of a base class. 11042 CXXConstructorDecl * 11043 Sema::findInheritingConstructor(SourceLocation Loc, 11044 CXXConstructorDecl *BaseCtor, 11045 ConstructorUsingShadowDecl *Shadow) { 11046 CXXRecordDecl *Derived = Shadow->getParent(); 11047 SourceLocation UsingLoc = Shadow->getLocation(); 11048 11049 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 11050 // For now we use the name of the base class constructor as a member of the 11051 // derived class to indicate a (fake) inherited constructor name. 11052 DeclarationName Name = BaseCtor->getDeclName(); 11053 11054 // Check to see if we already have a fake constructor for this inherited 11055 // constructor call. 11056 for (NamedDecl *Ctor : Derived->lookup(Name)) 11057 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 11058 ->getInheritedConstructor() 11059 .getConstructor(), 11060 BaseCtor)) 11061 return cast<CXXConstructorDecl>(Ctor); 11062 11063 DeclarationNameInfo NameInfo(Name, UsingLoc); 11064 TypeSourceInfo *TInfo = 11065 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 11066 FunctionProtoTypeLoc ProtoLoc = 11067 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 11068 11069 // Check the inherited constructor is valid and find the list of base classes 11070 // from which it was inherited. 11071 InheritedConstructorInfo ICI(*this, Loc, Shadow); 11072 11073 bool Constexpr = 11074 BaseCtor->isConstexpr() && 11075 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 11076 false, BaseCtor, &ICI); 11077 11078 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 11079 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 11080 BaseCtor->isExplicit(), /*Inline=*/true, 11081 /*ImplicitlyDeclared=*/true, Constexpr, 11082 InheritedConstructor(Shadow, BaseCtor)); 11083 if (Shadow->isInvalidDecl()) 11084 DerivedCtor->setInvalidDecl(); 11085 11086 // Build an unevaluated exception specification for this fake constructor. 11087 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 11088 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11089 EPI.ExceptionSpec.Type = EST_Unevaluated; 11090 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 11091 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 11092 FPT->getParamTypes(), EPI)); 11093 11094 // Build the parameter declarations. 11095 SmallVector<ParmVarDecl *, 16> ParamDecls; 11096 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 11097 TypeSourceInfo *TInfo = 11098 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 11099 ParmVarDecl *PD = ParmVarDecl::Create( 11100 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 11101 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 11102 PD->setScopeInfo(0, I); 11103 PD->setImplicit(); 11104 // Ensure attributes are propagated onto parameters (this matters for 11105 // format, pass_object_size, ...). 11106 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 11107 ParamDecls.push_back(PD); 11108 ProtoLoc.setParam(I, PD); 11109 } 11110 11111 // Set up the new constructor. 11112 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 11113 DerivedCtor->setAccess(BaseCtor->getAccess()); 11114 DerivedCtor->setParams(ParamDecls); 11115 Derived->addDecl(DerivedCtor); 11116 11117 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 11118 SetDeclDeleted(DerivedCtor, UsingLoc); 11119 11120 return DerivedCtor; 11121 } 11122 11123 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 11124 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 11125 Ctor->getInheritedConstructor().getShadowDecl()); 11126 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 11127 /*Diagnose*/true); 11128 } 11129 11130 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 11131 CXXConstructorDecl *Constructor) { 11132 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11133 assert(Constructor->getInheritedConstructor() && 11134 !Constructor->doesThisDeclarationHaveABody() && 11135 !Constructor->isDeleted()); 11136 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11137 return; 11138 11139 // Initializations are performed "as if by a defaulted default constructor", 11140 // so enter the appropriate scope. 11141 SynthesizedFunctionScope Scope(*this, Constructor); 11142 11143 // The exception specification is needed because we are defining the 11144 // function. 11145 ResolveExceptionSpec(CurrentLocation, 11146 Constructor->getType()->castAs<FunctionProtoType>()); 11147 MarkVTableUsed(CurrentLocation, ClassDecl); 11148 11149 // Add a context note for diagnostics produced after this point. 11150 Scope.addContextNote(CurrentLocation); 11151 11152 ConstructorUsingShadowDecl *Shadow = 11153 Constructor->getInheritedConstructor().getShadowDecl(); 11154 CXXConstructorDecl *InheritedCtor = 11155 Constructor->getInheritedConstructor().getConstructor(); 11156 11157 // [class.inhctor.init]p1: 11158 // initialization proceeds as if a defaulted default constructor is used to 11159 // initialize the D object and each base class subobject from which the 11160 // constructor was inherited 11161 11162 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11163 CXXRecordDecl *RD = Shadow->getParent(); 11164 SourceLocation InitLoc = Shadow->getLocation(); 11165 11166 // Build explicit initializers for all base classes from which the 11167 // constructor was inherited. 11168 SmallVector<CXXCtorInitializer*, 8> Inits; 11169 for (bool VBase : {false, true}) { 11170 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11171 if (B.isVirtual() != VBase) 11172 continue; 11173 11174 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11175 if (!BaseRD) 11176 continue; 11177 11178 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11179 if (!BaseCtor.first) 11180 continue; 11181 11182 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11183 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11184 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11185 11186 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11187 Inits.push_back(new (Context) CXXCtorInitializer( 11188 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11189 SourceLocation())); 11190 } 11191 } 11192 11193 // We now proceed as if for a defaulted default constructor, with the relevant 11194 // initializers replaced. 11195 11196 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11197 Constructor->setInvalidDecl(); 11198 return; 11199 } 11200 11201 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11202 Constructor->markUsed(Context); 11203 11204 if (ASTMutationListener *L = getASTMutationListener()) { 11205 L->CompletedImplicitDefinition(Constructor); 11206 } 11207 11208 DiagnoseUninitializedFields(*this, Constructor); 11209 } 11210 11211 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11212 // C++ [class.dtor]p2: 11213 // If a class has no user-declared destructor, a destructor is 11214 // declared implicitly. An implicitly-declared destructor is an 11215 // inline public member of its class. 11216 assert(ClassDecl->needsImplicitDestructor()); 11217 11218 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11219 if (DSM.isAlreadyBeingDeclared()) 11220 return nullptr; 11221 11222 // Create the actual destructor declaration. 11223 CanQualType ClassType 11224 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11225 SourceLocation ClassLoc = ClassDecl->getLocation(); 11226 DeclarationName Name 11227 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11228 DeclarationNameInfo NameInfo(Name, ClassLoc); 11229 CXXDestructorDecl *Destructor 11230 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11231 QualType(), nullptr, /*isInline=*/true, 11232 /*isImplicitlyDeclared=*/true); 11233 Destructor->setAccess(AS_public); 11234 Destructor->setDefaulted(); 11235 11236 if (getLangOpts().CUDA) { 11237 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11238 Destructor, 11239 /* ConstRHS */ false, 11240 /* Diagnose */ false); 11241 } 11242 11243 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 11244 11245 // We don't need to use SpecialMemberIsTrivial here; triviality for 11246 // destructors is easy to compute. 11247 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11248 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11249 ClassDecl->hasTrivialDestructorForCall()); 11250 11251 // Note that we have declared this destructor. 11252 ++ASTContext::NumImplicitDestructorsDeclared; 11253 11254 Scope *S = getScopeForContext(ClassDecl); 11255 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11256 11257 // We can't check whether an implicit destructor is deleted before we complete 11258 // the definition of the class, because its validity depends on the alignment 11259 // of the class. We'll check this from ActOnFields once the class is complete. 11260 if (ClassDecl->isCompleteDefinition() && 11261 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11262 SetDeclDeleted(Destructor, ClassLoc); 11263 11264 // Introduce this destructor into its scope. 11265 if (S) 11266 PushOnScopeChains(Destructor, S, false); 11267 ClassDecl->addDecl(Destructor); 11268 11269 return Destructor; 11270 } 11271 11272 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11273 CXXDestructorDecl *Destructor) { 11274 assert((Destructor->isDefaulted() && 11275 !Destructor->doesThisDeclarationHaveABody() && 11276 !Destructor->isDeleted()) && 11277 "DefineImplicitDestructor - call it for implicit default dtor"); 11278 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11279 return; 11280 11281 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11282 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11283 11284 SynthesizedFunctionScope Scope(*this, Destructor); 11285 11286 // The exception specification is needed because we are defining the 11287 // function. 11288 ResolveExceptionSpec(CurrentLocation, 11289 Destructor->getType()->castAs<FunctionProtoType>()); 11290 MarkVTableUsed(CurrentLocation, ClassDecl); 11291 11292 // Add a context note for diagnostics produced after this point. 11293 Scope.addContextNote(CurrentLocation); 11294 11295 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11296 Destructor->getParent()); 11297 11298 if (CheckDestructor(Destructor)) { 11299 Destructor->setInvalidDecl(); 11300 return; 11301 } 11302 11303 SourceLocation Loc = Destructor->getEndLoc().isValid() 11304 ? Destructor->getEndLoc() 11305 : Destructor->getLocation(); 11306 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11307 Destructor->markUsed(Context); 11308 11309 if (ASTMutationListener *L = getASTMutationListener()) { 11310 L->CompletedImplicitDefinition(Destructor); 11311 } 11312 } 11313 11314 /// Perform any semantic analysis which needs to be delayed until all 11315 /// pending class member declarations have been parsed. 11316 void Sema::ActOnFinishCXXMemberDecls() { 11317 // If the context is an invalid C++ class, just suppress these checks. 11318 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11319 if (Record->isInvalidDecl()) { 11320 DelayedOverridingExceptionSpecChecks.clear(); 11321 DelayedEquivalentExceptionSpecChecks.clear(); 11322 DelayedDefaultedMemberExceptionSpecs.clear(); 11323 return; 11324 } 11325 checkForMultipleExportedDefaultConstructors(*this, Record); 11326 } 11327 } 11328 11329 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11330 referenceDLLExportedClassMethods(); 11331 } 11332 11333 void Sema::referenceDLLExportedClassMethods() { 11334 if (!DelayedDllExportClasses.empty()) { 11335 // Calling ReferenceDllExportedMembers might cause the current function to 11336 // be called again, so use a local copy of DelayedDllExportClasses. 11337 SmallVector<CXXRecordDecl *, 4> WorkList; 11338 std::swap(DelayedDllExportClasses, WorkList); 11339 for (CXXRecordDecl *Class : WorkList) 11340 ReferenceDllExportedMembers(*this, Class); 11341 } 11342 } 11343 11344 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 11345 assert(getLangOpts().CPlusPlus11 && 11346 "adjusting dtor exception specs was introduced in c++11"); 11347 11348 if (Destructor->isDependentContext()) 11349 return; 11350 11351 // C++11 [class.dtor]p3: 11352 // A declaration of a destructor that does not have an exception- 11353 // specification is implicitly considered to have the same exception- 11354 // specification as an implicit declaration. 11355 const FunctionProtoType *DtorType = Destructor->getType()-> 11356 getAs<FunctionProtoType>(); 11357 if (DtorType->hasExceptionSpec()) 11358 return; 11359 11360 // Replace the destructor's type, building off the existing one. Fortunately, 11361 // the only thing of interest in the destructor type is its extended info. 11362 // The return and arguments are fixed. 11363 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11364 EPI.ExceptionSpec.Type = EST_Unevaluated; 11365 EPI.ExceptionSpec.SourceDecl = Destructor; 11366 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11367 11368 // FIXME: If the destructor has a body that could throw, and the newly created 11369 // spec doesn't allow exceptions, we should emit a warning, because this 11370 // change in behavior can break conforming C++03 programs at runtime. 11371 // However, we don't have a body or an exception specification yet, so it 11372 // needs to be done somewhere else. 11373 } 11374 11375 namespace { 11376 /// An abstract base class for all helper classes used in building the 11377 // copy/move operators. These classes serve as factory functions and help us 11378 // avoid using the same Expr* in the AST twice. 11379 class ExprBuilder { 11380 ExprBuilder(const ExprBuilder&) = delete; 11381 ExprBuilder &operator=(const ExprBuilder&) = delete; 11382 11383 protected: 11384 static Expr *assertNotNull(Expr *E) { 11385 assert(E && "Expression construction must not fail."); 11386 return E; 11387 } 11388 11389 public: 11390 ExprBuilder() {} 11391 virtual ~ExprBuilder() {} 11392 11393 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11394 }; 11395 11396 class RefBuilder: public ExprBuilder { 11397 VarDecl *Var; 11398 QualType VarType; 11399 11400 public: 11401 Expr *build(Sema &S, SourceLocation Loc) const override { 11402 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 11403 } 11404 11405 RefBuilder(VarDecl *Var, QualType VarType) 11406 : Var(Var), VarType(VarType) {} 11407 }; 11408 11409 class ThisBuilder: public ExprBuilder { 11410 public: 11411 Expr *build(Sema &S, SourceLocation Loc) const override { 11412 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11413 } 11414 }; 11415 11416 class CastBuilder: public ExprBuilder { 11417 const ExprBuilder &Builder; 11418 QualType Type; 11419 ExprValueKind Kind; 11420 const CXXCastPath &Path; 11421 11422 public: 11423 Expr *build(Sema &S, SourceLocation Loc) const override { 11424 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11425 CK_UncheckedDerivedToBase, Kind, 11426 &Path).get()); 11427 } 11428 11429 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11430 const CXXCastPath &Path) 11431 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11432 }; 11433 11434 class DerefBuilder: public ExprBuilder { 11435 const ExprBuilder &Builder; 11436 11437 public: 11438 Expr *build(Sema &S, SourceLocation Loc) const override { 11439 return assertNotNull( 11440 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11441 } 11442 11443 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11444 }; 11445 11446 class MemberBuilder: public ExprBuilder { 11447 const ExprBuilder &Builder; 11448 QualType Type; 11449 CXXScopeSpec SS; 11450 bool IsArrow; 11451 LookupResult &MemberLookup; 11452 11453 public: 11454 Expr *build(Sema &S, SourceLocation Loc) const override { 11455 return assertNotNull(S.BuildMemberReferenceExpr( 11456 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11457 nullptr, MemberLookup, nullptr, nullptr).get()); 11458 } 11459 11460 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11461 LookupResult &MemberLookup) 11462 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11463 MemberLookup(MemberLookup) {} 11464 }; 11465 11466 class MoveCastBuilder: public ExprBuilder { 11467 const ExprBuilder &Builder; 11468 11469 public: 11470 Expr *build(Sema &S, SourceLocation Loc) const override { 11471 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11472 } 11473 11474 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11475 }; 11476 11477 class LvalueConvBuilder: public ExprBuilder { 11478 const ExprBuilder &Builder; 11479 11480 public: 11481 Expr *build(Sema &S, SourceLocation Loc) const override { 11482 return assertNotNull( 11483 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11484 } 11485 11486 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11487 }; 11488 11489 class SubscriptBuilder: public ExprBuilder { 11490 const ExprBuilder &Base; 11491 const ExprBuilder &Index; 11492 11493 public: 11494 Expr *build(Sema &S, SourceLocation Loc) const override { 11495 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11496 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11497 } 11498 11499 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11500 : Base(Base), Index(Index) {} 11501 }; 11502 11503 } // end anonymous namespace 11504 11505 /// When generating a defaulted copy or move assignment operator, if a field 11506 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11507 /// do so. This optimization only applies for arrays of scalars, and for arrays 11508 /// of class type where the selected copy/move-assignment operator is trivial. 11509 static StmtResult 11510 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11511 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11512 // Compute the size of the memory buffer to be copied. 11513 QualType SizeType = S.Context.getSizeType(); 11514 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11515 S.Context.getTypeSizeInChars(T).getQuantity()); 11516 11517 // Take the address of the field references for "from" and "to". We 11518 // directly construct UnaryOperators here because semantic analysis 11519 // does not permit us to take the address of an xvalue. 11520 Expr *From = FromB.build(S, Loc); 11521 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11522 S.Context.getPointerType(From->getType()), 11523 VK_RValue, OK_Ordinary, Loc, false); 11524 Expr *To = ToB.build(S, Loc); 11525 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11526 S.Context.getPointerType(To->getType()), 11527 VK_RValue, OK_Ordinary, Loc, false); 11528 11529 const Type *E = T->getBaseElementTypeUnsafe(); 11530 bool NeedsCollectableMemCpy = 11531 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11532 11533 // Create a reference to the __builtin_objc_memmove_collectable function 11534 StringRef MemCpyName = NeedsCollectableMemCpy ? 11535 "__builtin_objc_memmove_collectable" : 11536 "__builtin_memcpy"; 11537 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11538 Sema::LookupOrdinaryName); 11539 S.LookupName(R, S.TUScope, true); 11540 11541 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11542 if (!MemCpy) 11543 // Something went horribly wrong earlier, and we will have complained 11544 // about it. 11545 return StmtError(); 11546 11547 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11548 VK_RValue, Loc, nullptr); 11549 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11550 11551 Expr *CallArgs[] = { 11552 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11553 }; 11554 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11555 Loc, CallArgs, Loc); 11556 11557 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11558 return Call.getAs<Stmt>(); 11559 } 11560 11561 /// Builds a statement that copies/moves the given entity from \p From to 11562 /// \c To. 11563 /// 11564 /// This routine is used to copy/move the members of a class with an 11565 /// implicitly-declared copy/move assignment operator. When the entities being 11566 /// copied are arrays, this routine builds for loops to copy them. 11567 /// 11568 /// \param S The Sema object used for type-checking. 11569 /// 11570 /// \param Loc The location where the implicit copy/move is being generated. 11571 /// 11572 /// \param T The type of the expressions being copied/moved. Both expressions 11573 /// must have this type. 11574 /// 11575 /// \param To The expression we are copying/moving to. 11576 /// 11577 /// \param From The expression we are copying/moving from. 11578 /// 11579 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11580 /// Otherwise, it's a non-static member subobject. 11581 /// 11582 /// \param Copying Whether we're copying or moving. 11583 /// 11584 /// \param Depth Internal parameter recording the depth of the recursion. 11585 /// 11586 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11587 /// if a memcpy should be used instead. 11588 static StmtResult 11589 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11590 const ExprBuilder &To, const ExprBuilder &From, 11591 bool CopyingBaseSubobject, bool Copying, 11592 unsigned Depth = 0) { 11593 // C++11 [class.copy]p28: 11594 // Each subobject is assigned in the manner appropriate to its type: 11595 // 11596 // - if the subobject is of class type, as if by a call to operator= with 11597 // the subobject as the object expression and the corresponding 11598 // subobject of x as a single function argument (as if by explicit 11599 // qualification; that is, ignoring any possible virtual overriding 11600 // functions in more derived classes); 11601 // 11602 // C++03 [class.copy]p13: 11603 // - if the subobject is of class type, the copy assignment operator for 11604 // the class is used (as if by explicit qualification; that is, 11605 // ignoring any possible virtual overriding functions in more derived 11606 // classes); 11607 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11608 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11609 11610 // Look for operator=. 11611 DeclarationName Name 11612 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11613 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11614 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11615 11616 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11617 // operator. 11618 if (!S.getLangOpts().CPlusPlus11) { 11619 LookupResult::Filter F = OpLookup.makeFilter(); 11620 while (F.hasNext()) { 11621 NamedDecl *D = F.next(); 11622 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11623 if (Method->isCopyAssignmentOperator() || 11624 (!Copying && Method->isMoveAssignmentOperator())) 11625 continue; 11626 11627 F.erase(); 11628 } 11629 F.done(); 11630 } 11631 11632 // Suppress the protected check (C++ [class.protected]) for each of the 11633 // assignment operators we found. This strange dance is required when 11634 // we're assigning via a base classes's copy-assignment operator. To 11635 // ensure that we're getting the right base class subobject (without 11636 // ambiguities), we need to cast "this" to that subobject type; to 11637 // ensure that we don't go through the virtual call mechanism, we need 11638 // to qualify the operator= name with the base class (see below). However, 11639 // this means that if the base class has a protected copy assignment 11640 // operator, the protected member access check will fail. So, we 11641 // rewrite "protected" access to "public" access in this case, since we 11642 // know by construction that we're calling from a derived class. 11643 if (CopyingBaseSubobject) { 11644 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11645 L != LEnd; ++L) { 11646 if (L.getAccess() == AS_protected) 11647 L.setAccess(AS_public); 11648 } 11649 } 11650 11651 // Create the nested-name-specifier that will be used to qualify the 11652 // reference to operator=; this is required to suppress the virtual 11653 // call mechanism. 11654 CXXScopeSpec SS; 11655 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11656 SS.MakeTrivial(S.Context, 11657 NestedNameSpecifier::Create(S.Context, nullptr, false, 11658 CanonicalT), 11659 Loc); 11660 11661 // Create the reference to operator=. 11662 ExprResult OpEqualRef 11663 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11664 SS, /*TemplateKWLoc=*/SourceLocation(), 11665 /*FirstQualifierInScope=*/nullptr, 11666 OpLookup, 11667 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11668 /*SuppressQualifierCheck=*/true); 11669 if (OpEqualRef.isInvalid()) 11670 return StmtError(); 11671 11672 // Build the call to the assignment operator. 11673 11674 Expr *FromInst = From.build(S, Loc); 11675 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11676 OpEqualRef.getAs<Expr>(), 11677 Loc, FromInst, Loc); 11678 if (Call.isInvalid()) 11679 return StmtError(); 11680 11681 // If we built a call to a trivial 'operator=' while copying an array, 11682 // bail out. We'll replace the whole shebang with a memcpy. 11683 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11684 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11685 return StmtResult((Stmt*)nullptr); 11686 11687 // Convert to an expression-statement, and clean up any produced 11688 // temporaries. 11689 return S.ActOnExprStmt(Call); 11690 } 11691 11692 // - if the subobject is of scalar type, the built-in assignment 11693 // operator is used. 11694 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11695 if (!ArrayTy) { 11696 ExprResult Assignment = S.CreateBuiltinBinOp( 11697 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11698 if (Assignment.isInvalid()) 11699 return StmtError(); 11700 return S.ActOnExprStmt(Assignment); 11701 } 11702 11703 // - if the subobject is an array, each element is assigned, in the 11704 // manner appropriate to the element type; 11705 11706 // Construct a loop over the array bounds, e.g., 11707 // 11708 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11709 // 11710 // that will copy each of the array elements. 11711 QualType SizeType = S.Context.getSizeType(); 11712 11713 // Create the iteration variable. 11714 IdentifierInfo *IterationVarName = nullptr; 11715 { 11716 SmallString<8> Str; 11717 llvm::raw_svector_ostream OS(Str); 11718 OS << "__i" << Depth; 11719 IterationVarName = &S.Context.Idents.get(OS.str()); 11720 } 11721 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11722 IterationVarName, SizeType, 11723 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11724 SC_None); 11725 11726 // Initialize the iteration variable to zero. 11727 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11728 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11729 11730 // Creates a reference to the iteration variable. 11731 RefBuilder IterationVarRef(IterationVar, SizeType); 11732 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11733 11734 // Create the DeclStmt that holds the iteration variable. 11735 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11736 11737 // Subscript the "from" and "to" expressions with the iteration variable. 11738 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11739 MoveCastBuilder FromIndexMove(FromIndexCopy); 11740 const ExprBuilder *FromIndex; 11741 if (Copying) 11742 FromIndex = &FromIndexCopy; 11743 else 11744 FromIndex = &FromIndexMove; 11745 11746 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11747 11748 // Build the copy/move for an individual element of the array. 11749 StmtResult Copy = 11750 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11751 ToIndex, *FromIndex, CopyingBaseSubobject, 11752 Copying, Depth + 1); 11753 // Bail out if copying fails or if we determined that we should use memcpy. 11754 if (Copy.isInvalid() || !Copy.get()) 11755 return Copy; 11756 11757 // Create the comparison against the array bound. 11758 llvm::APInt Upper 11759 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11760 Expr *Comparison 11761 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11762 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11763 BO_NE, S.Context.BoolTy, 11764 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11765 11766 // Create the pre-increment of the iteration variable. We can determine 11767 // whether the increment will overflow based on the value of the array 11768 // bound. 11769 Expr *Increment = new (S.Context) 11770 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11771 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11772 11773 // Construct the loop that copies all elements of this array. 11774 return S.ActOnForStmt( 11775 Loc, Loc, InitStmt, 11776 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11777 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11778 } 11779 11780 static StmtResult 11781 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11782 const ExprBuilder &To, const ExprBuilder &From, 11783 bool CopyingBaseSubobject, bool Copying) { 11784 // Maybe we should use a memcpy? 11785 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11786 T.isTriviallyCopyableType(S.Context)) 11787 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11788 11789 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11790 CopyingBaseSubobject, 11791 Copying, 0)); 11792 11793 // If we ended up picking a trivial assignment operator for an array of a 11794 // non-trivially-copyable class type, just emit a memcpy. 11795 if (!Result.isInvalid() && !Result.get()) 11796 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11797 11798 return Result; 11799 } 11800 11801 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11802 // Note: The following rules are largely analoguous to the copy 11803 // constructor rules. Note that virtual bases are not taken into account 11804 // for determining the argument type of the operator. Note also that 11805 // operators taking an object instead of a reference are allowed. 11806 assert(ClassDecl->needsImplicitCopyAssignment()); 11807 11808 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11809 if (DSM.isAlreadyBeingDeclared()) 11810 return nullptr; 11811 11812 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11813 QualType RetType = Context.getLValueReferenceType(ArgType); 11814 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11815 if (Const) 11816 ArgType = ArgType.withConst(); 11817 11818 if (Context.getLangOpts().OpenCLCPlusPlus) 11819 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 11820 11821 ArgType = Context.getLValueReferenceType(ArgType); 11822 11823 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11824 CXXCopyAssignment, 11825 Const); 11826 11827 // An implicitly-declared copy assignment operator is an inline public 11828 // member of its class. 11829 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11830 SourceLocation ClassLoc = ClassDecl->getLocation(); 11831 DeclarationNameInfo NameInfo(Name, ClassLoc); 11832 CXXMethodDecl *CopyAssignment = 11833 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11834 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11835 /*isInline=*/true, Constexpr, SourceLocation()); 11836 CopyAssignment->setAccess(AS_public); 11837 CopyAssignment->setDefaulted(); 11838 CopyAssignment->setImplicit(); 11839 11840 if (getLangOpts().CUDA) { 11841 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11842 CopyAssignment, 11843 /* ConstRHS */ Const, 11844 /* Diagnose */ false); 11845 } 11846 11847 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 11848 11849 // Add the parameter to the operator. 11850 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11851 ClassLoc, ClassLoc, 11852 /*Id=*/nullptr, ArgType, 11853 /*TInfo=*/nullptr, SC_None, 11854 nullptr); 11855 CopyAssignment->setParams(FromParam); 11856 11857 CopyAssignment->setTrivial( 11858 ClassDecl->needsOverloadResolutionForCopyAssignment() 11859 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11860 : ClassDecl->hasTrivialCopyAssignment()); 11861 11862 // Note that we have added this copy-assignment operator. 11863 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11864 11865 Scope *S = getScopeForContext(ClassDecl); 11866 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11867 11868 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11869 SetDeclDeleted(CopyAssignment, ClassLoc); 11870 11871 if (S) 11872 PushOnScopeChains(CopyAssignment, S, false); 11873 ClassDecl->addDecl(CopyAssignment); 11874 11875 return CopyAssignment; 11876 } 11877 11878 /// Diagnose an implicit copy operation for a class which is odr-used, but 11879 /// which is deprecated because the class has a user-declared copy constructor, 11880 /// copy assignment operator, or destructor. 11881 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11882 assert(CopyOp->isImplicit()); 11883 11884 CXXRecordDecl *RD = CopyOp->getParent(); 11885 CXXMethodDecl *UserDeclaredOperation = nullptr; 11886 11887 // In Microsoft mode, assignment operations don't affect constructors and 11888 // vice versa. 11889 if (RD->hasUserDeclaredDestructor()) { 11890 UserDeclaredOperation = RD->getDestructor(); 11891 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11892 RD->hasUserDeclaredCopyConstructor() && 11893 !S.getLangOpts().MSVCCompat) { 11894 // Find any user-declared copy constructor. 11895 for (auto *I : RD->ctors()) { 11896 if (I->isCopyConstructor()) { 11897 UserDeclaredOperation = I; 11898 break; 11899 } 11900 } 11901 assert(UserDeclaredOperation); 11902 } else if (isa<CXXConstructorDecl>(CopyOp) && 11903 RD->hasUserDeclaredCopyAssignment() && 11904 !S.getLangOpts().MSVCCompat) { 11905 // Find any user-declared move assignment operator. 11906 for (auto *I : RD->methods()) { 11907 if (I->isCopyAssignmentOperator()) { 11908 UserDeclaredOperation = I; 11909 break; 11910 } 11911 } 11912 assert(UserDeclaredOperation); 11913 } 11914 11915 if (UserDeclaredOperation) { 11916 S.Diag(UserDeclaredOperation->getLocation(), 11917 diag::warn_deprecated_copy_operation) 11918 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11919 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11920 } 11921 } 11922 11923 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11924 CXXMethodDecl *CopyAssignOperator) { 11925 assert((CopyAssignOperator->isDefaulted() && 11926 CopyAssignOperator->isOverloadedOperator() && 11927 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11928 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11929 !CopyAssignOperator->isDeleted()) && 11930 "DefineImplicitCopyAssignment called for wrong function"); 11931 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11932 return; 11933 11934 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11935 if (ClassDecl->isInvalidDecl()) { 11936 CopyAssignOperator->setInvalidDecl(); 11937 return; 11938 } 11939 11940 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11941 11942 // The exception specification is needed because we are defining the 11943 // function. 11944 ResolveExceptionSpec(CurrentLocation, 11945 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11946 11947 // Add a context note for diagnostics produced after this point. 11948 Scope.addContextNote(CurrentLocation); 11949 11950 // C++11 [class.copy]p18: 11951 // The [definition of an implicitly declared copy assignment operator] is 11952 // deprecated if the class has a user-declared copy constructor or a 11953 // user-declared destructor. 11954 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11955 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11956 11957 // C++0x [class.copy]p30: 11958 // The implicitly-defined or explicitly-defaulted copy assignment operator 11959 // for a non-union class X performs memberwise copy assignment of its 11960 // subobjects. The direct base classes of X are assigned first, in the 11961 // order of their declaration in the base-specifier-list, and then the 11962 // immediate non-static data members of X are assigned, in the order in 11963 // which they were declared in the class definition. 11964 11965 // The statements that form the synthesized function body. 11966 SmallVector<Stmt*, 8> Statements; 11967 11968 // The parameter for the "other" object, which we are copying from. 11969 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11970 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11971 QualType OtherRefType = Other->getType(); 11972 if (const LValueReferenceType *OtherRef 11973 = OtherRefType->getAs<LValueReferenceType>()) { 11974 OtherRefType = OtherRef->getPointeeType(); 11975 OtherQuals = OtherRefType.getQualifiers(); 11976 } 11977 11978 // Our location for everything implicitly-generated. 11979 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 11980 ? CopyAssignOperator->getEndLoc() 11981 : CopyAssignOperator->getLocation(); 11982 11983 // Builds a DeclRefExpr for the "other" object. 11984 RefBuilder OtherRef(Other, OtherRefType); 11985 11986 // Builds the "this" pointer. 11987 ThisBuilder This; 11988 11989 // Assign base classes. 11990 bool Invalid = false; 11991 for (auto &Base : ClassDecl->bases()) { 11992 // Form the assignment: 11993 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11994 QualType BaseType = Base.getType().getUnqualifiedType(); 11995 if (!BaseType->isRecordType()) { 11996 Invalid = true; 11997 continue; 11998 } 11999 12000 CXXCastPath BasePath; 12001 BasePath.push_back(&Base); 12002 12003 // Construct the "from" expression, which is an implicit cast to the 12004 // appropriately-qualified base type. 12005 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 12006 VK_LValue, BasePath); 12007 12008 // Dereference "this". 12009 DerefBuilder DerefThis(This); 12010 CastBuilder To(DerefThis, 12011 Context.getQualifiedType( 12012 BaseType, CopyAssignOperator->getTypeQualifiers()), 12013 VK_LValue, BasePath); 12014 12015 // Build the copy. 12016 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 12017 To, From, 12018 /*CopyingBaseSubobject=*/true, 12019 /*Copying=*/true); 12020 if (Copy.isInvalid()) { 12021 CopyAssignOperator->setInvalidDecl(); 12022 return; 12023 } 12024 12025 // Success! Record the copy. 12026 Statements.push_back(Copy.getAs<Expr>()); 12027 } 12028 12029 // Assign non-static members. 12030 for (auto *Field : ClassDecl->fields()) { 12031 // FIXME: We should form some kind of AST representation for the implied 12032 // memcpy in a union copy operation. 12033 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12034 continue; 12035 12036 if (Field->isInvalidDecl()) { 12037 Invalid = true; 12038 continue; 12039 } 12040 12041 // Check for members of reference type; we can't copy those. 12042 if (Field->getType()->isReferenceType()) { 12043 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12044 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12045 Diag(Field->getLocation(), diag::note_declared_at); 12046 Invalid = true; 12047 continue; 12048 } 12049 12050 // Check for members of const-qualified, non-class type. 12051 QualType BaseType = Context.getBaseElementType(Field->getType()); 12052 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12053 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12054 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12055 Diag(Field->getLocation(), diag::note_declared_at); 12056 Invalid = true; 12057 continue; 12058 } 12059 12060 // Suppress assigning zero-width bitfields. 12061 if (Field->isZeroLengthBitField(Context)) 12062 continue; 12063 12064 QualType FieldType = Field->getType().getNonReferenceType(); 12065 if (FieldType->isIncompleteArrayType()) { 12066 assert(ClassDecl->hasFlexibleArrayMember() && 12067 "Incomplete array type is not valid"); 12068 continue; 12069 } 12070 12071 // Build references to the field in the object we're copying from and to. 12072 CXXScopeSpec SS; // Intentionally empty 12073 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12074 LookupMemberName); 12075 MemberLookup.addDecl(Field); 12076 MemberLookup.resolveKind(); 12077 12078 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 12079 12080 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 12081 12082 // Build the copy of this field. 12083 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 12084 To, From, 12085 /*CopyingBaseSubobject=*/false, 12086 /*Copying=*/true); 12087 if (Copy.isInvalid()) { 12088 CopyAssignOperator->setInvalidDecl(); 12089 return; 12090 } 12091 12092 // Success! Record the copy. 12093 Statements.push_back(Copy.getAs<Stmt>()); 12094 } 12095 12096 if (!Invalid) { 12097 // Add a "return *this;" 12098 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12099 12100 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12101 if (Return.isInvalid()) 12102 Invalid = true; 12103 else 12104 Statements.push_back(Return.getAs<Stmt>()); 12105 } 12106 12107 if (Invalid) { 12108 CopyAssignOperator->setInvalidDecl(); 12109 return; 12110 } 12111 12112 StmtResult Body; 12113 { 12114 CompoundScopeRAII CompoundScope(*this); 12115 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12116 /*isStmtExpr=*/false); 12117 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12118 } 12119 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 12120 CopyAssignOperator->markUsed(Context); 12121 12122 if (ASTMutationListener *L = getASTMutationListener()) { 12123 L->CompletedImplicitDefinition(CopyAssignOperator); 12124 } 12125 } 12126 12127 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 12128 assert(ClassDecl->needsImplicitMoveAssignment()); 12129 12130 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 12131 if (DSM.isAlreadyBeingDeclared()) 12132 return nullptr; 12133 12134 // Note: The following rules are largely analoguous to the move 12135 // constructor rules. 12136 12137 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12138 QualType RetType = Context.getLValueReferenceType(ArgType); 12139 ArgType = Context.getRValueReferenceType(ArgType); 12140 12141 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12142 CXXMoveAssignment, 12143 false); 12144 12145 // An implicitly-declared move assignment operator is an inline public 12146 // member of its class. 12147 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12148 SourceLocation ClassLoc = ClassDecl->getLocation(); 12149 DeclarationNameInfo NameInfo(Name, ClassLoc); 12150 CXXMethodDecl *MoveAssignment = 12151 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12152 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12153 /*isInline=*/true, Constexpr, SourceLocation()); 12154 MoveAssignment->setAccess(AS_public); 12155 MoveAssignment->setDefaulted(); 12156 MoveAssignment->setImplicit(); 12157 12158 if (getLangOpts().CUDA) { 12159 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12160 MoveAssignment, 12161 /* ConstRHS */ false, 12162 /* Diagnose */ false); 12163 } 12164 12165 // Build an exception specification pointing back at this member. 12166 FunctionProtoType::ExtProtoInfo EPI = 12167 getImplicitMethodEPI(*this, MoveAssignment); 12168 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12169 12170 // Add the parameter to the operator. 12171 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12172 ClassLoc, ClassLoc, 12173 /*Id=*/nullptr, ArgType, 12174 /*TInfo=*/nullptr, SC_None, 12175 nullptr); 12176 MoveAssignment->setParams(FromParam); 12177 12178 MoveAssignment->setTrivial( 12179 ClassDecl->needsOverloadResolutionForMoveAssignment() 12180 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12181 : ClassDecl->hasTrivialMoveAssignment()); 12182 12183 // Note that we have added this copy-assignment operator. 12184 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 12185 12186 Scope *S = getScopeForContext(ClassDecl); 12187 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12188 12189 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12190 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12191 SetDeclDeleted(MoveAssignment, ClassLoc); 12192 } 12193 12194 if (S) 12195 PushOnScopeChains(MoveAssignment, S, false); 12196 ClassDecl->addDecl(MoveAssignment); 12197 12198 return MoveAssignment; 12199 } 12200 12201 /// Check if we're implicitly defining a move assignment operator for a class 12202 /// with virtual bases. Such a move assignment might move-assign the virtual 12203 /// base multiple times. 12204 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12205 SourceLocation CurrentLocation) { 12206 assert(!Class->isDependentContext() && "should not define dependent move"); 12207 12208 // Only a virtual base could get implicitly move-assigned multiple times. 12209 // Only a non-trivial move assignment can observe this. We only want to 12210 // diagnose if we implicitly define an assignment operator that assigns 12211 // two base classes, both of which move-assign the same virtual base. 12212 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12213 Class->getNumBases() < 2) 12214 return; 12215 12216 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12217 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12218 VBaseMap VBases; 12219 12220 for (auto &BI : Class->bases()) { 12221 Worklist.push_back(&BI); 12222 while (!Worklist.empty()) { 12223 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12224 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12225 12226 // If the base has no non-trivial move assignment operators, 12227 // we don't care about moves from it. 12228 if (!Base->hasNonTrivialMoveAssignment()) 12229 continue; 12230 12231 // If there's nothing virtual here, skip it. 12232 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12233 continue; 12234 12235 // If we're not actually going to call a move assignment for this base, 12236 // or the selected move assignment is trivial, skip it. 12237 Sema::SpecialMemberOverloadResult SMOR = 12238 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12239 /*ConstArg*/false, /*VolatileArg*/false, 12240 /*RValueThis*/true, /*ConstThis*/false, 12241 /*VolatileThis*/false); 12242 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12243 !SMOR.getMethod()->isMoveAssignmentOperator()) 12244 continue; 12245 12246 if (BaseSpec->isVirtual()) { 12247 // We're going to move-assign this virtual base, and its move 12248 // assignment operator is not trivial. If this can happen for 12249 // multiple distinct direct bases of Class, diagnose it. (If it 12250 // only happens in one base, we'll diagnose it when synthesizing 12251 // that base class's move assignment operator.) 12252 CXXBaseSpecifier *&Existing = 12253 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12254 .first->second; 12255 if (Existing && Existing != &BI) { 12256 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12257 << Class << Base; 12258 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 12259 << (Base->getCanonicalDecl() == 12260 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12261 << Base << Existing->getType() << Existing->getSourceRange(); 12262 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 12263 << (Base->getCanonicalDecl() == 12264 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12265 << Base << BI.getType() << BaseSpec->getSourceRange(); 12266 12267 // Only diagnose each vbase once. 12268 Existing = nullptr; 12269 } 12270 } else { 12271 // Only walk over bases that have defaulted move assignment operators. 12272 // We assume that any user-provided move assignment operator handles 12273 // the multiple-moves-of-vbase case itself somehow. 12274 if (!SMOR.getMethod()->isDefaulted()) 12275 continue; 12276 12277 // We're going to move the base classes of Base. Add them to the list. 12278 for (auto &BI : Base->bases()) 12279 Worklist.push_back(&BI); 12280 } 12281 } 12282 } 12283 } 12284 12285 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12286 CXXMethodDecl *MoveAssignOperator) { 12287 assert((MoveAssignOperator->isDefaulted() && 12288 MoveAssignOperator->isOverloadedOperator() && 12289 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12290 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12291 !MoveAssignOperator->isDeleted()) && 12292 "DefineImplicitMoveAssignment called for wrong function"); 12293 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12294 return; 12295 12296 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12297 if (ClassDecl->isInvalidDecl()) { 12298 MoveAssignOperator->setInvalidDecl(); 12299 return; 12300 } 12301 12302 // C++0x [class.copy]p28: 12303 // The implicitly-defined or move assignment operator for a non-union class 12304 // X performs memberwise move assignment of its subobjects. The direct base 12305 // classes of X are assigned first, in the order of their declaration in the 12306 // base-specifier-list, and then the immediate non-static data members of X 12307 // are assigned, in the order in which they were declared in the class 12308 // definition. 12309 12310 // Issue a warning if our implicit move assignment operator will move 12311 // from a virtual base more than once. 12312 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12313 12314 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12315 12316 // The exception specification is needed because we are defining the 12317 // function. 12318 ResolveExceptionSpec(CurrentLocation, 12319 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12320 12321 // Add a context note for diagnostics produced after this point. 12322 Scope.addContextNote(CurrentLocation); 12323 12324 // The statements that form the synthesized function body. 12325 SmallVector<Stmt*, 8> Statements; 12326 12327 // The parameter for the "other" object, which we are move from. 12328 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12329 QualType OtherRefType = Other->getType()-> 12330 getAs<RValueReferenceType>()->getPointeeType(); 12331 12332 // Our location for everything implicitly-generated. 12333 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 12334 ? MoveAssignOperator->getEndLoc() 12335 : MoveAssignOperator->getLocation(); 12336 12337 // Builds a reference to the "other" object. 12338 RefBuilder OtherRef(Other, OtherRefType); 12339 // Cast to rvalue. 12340 MoveCastBuilder MoveOther(OtherRef); 12341 12342 // Builds the "this" pointer. 12343 ThisBuilder This; 12344 12345 // Assign base classes. 12346 bool Invalid = false; 12347 for (auto &Base : ClassDecl->bases()) { 12348 // C++11 [class.copy]p28: 12349 // It is unspecified whether subobjects representing virtual base classes 12350 // are assigned more than once by the implicitly-defined copy assignment 12351 // operator. 12352 // FIXME: Do not assign to a vbase that will be assigned by some other base 12353 // class. For a move-assignment, this can result in the vbase being moved 12354 // multiple times. 12355 12356 // Form the assignment: 12357 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12358 QualType BaseType = Base.getType().getUnqualifiedType(); 12359 if (!BaseType->isRecordType()) { 12360 Invalid = true; 12361 continue; 12362 } 12363 12364 CXXCastPath BasePath; 12365 BasePath.push_back(&Base); 12366 12367 // Construct the "from" expression, which is an implicit cast to the 12368 // appropriately-qualified base type. 12369 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12370 12371 // Dereference "this". 12372 DerefBuilder DerefThis(This); 12373 12374 // Implicitly cast "this" to the appropriately-qualified base type. 12375 CastBuilder To(DerefThis, 12376 Context.getQualifiedType( 12377 BaseType, MoveAssignOperator->getTypeQualifiers()), 12378 VK_LValue, BasePath); 12379 12380 // Build the move. 12381 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12382 To, From, 12383 /*CopyingBaseSubobject=*/true, 12384 /*Copying=*/false); 12385 if (Move.isInvalid()) { 12386 MoveAssignOperator->setInvalidDecl(); 12387 return; 12388 } 12389 12390 // Success! Record the move. 12391 Statements.push_back(Move.getAs<Expr>()); 12392 } 12393 12394 // Assign non-static members. 12395 for (auto *Field : ClassDecl->fields()) { 12396 // FIXME: We should form some kind of AST representation for the implied 12397 // memcpy in a union copy operation. 12398 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12399 continue; 12400 12401 if (Field->isInvalidDecl()) { 12402 Invalid = true; 12403 continue; 12404 } 12405 12406 // Check for members of reference type; we can't move those. 12407 if (Field->getType()->isReferenceType()) { 12408 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12409 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12410 Diag(Field->getLocation(), diag::note_declared_at); 12411 Invalid = true; 12412 continue; 12413 } 12414 12415 // Check for members of const-qualified, non-class type. 12416 QualType BaseType = Context.getBaseElementType(Field->getType()); 12417 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12418 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12419 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12420 Diag(Field->getLocation(), diag::note_declared_at); 12421 Invalid = true; 12422 continue; 12423 } 12424 12425 // Suppress assigning zero-width bitfields. 12426 if (Field->isZeroLengthBitField(Context)) 12427 continue; 12428 12429 QualType FieldType = Field->getType().getNonReferenceType(); 12430 if (FieldType->isIncompleteArrayType()) { 12431 assert(ClassDecl->hasFlexibleArrayMember() && 12432 "Incomplete array type is not valid"); 12433 continue; 12434 } 12435 12436 // Build references to the field in the object we're copying from and to. 12437 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12438 LookupMemberName); 12439 MemberLookup.addDecl(Field); 12440 MemberLookup.resolveKind(); 12441 MemberBuilder From(MoveOther, OtherRefType, 12442 /*IsArrow=*/false, MemberLookup); 12443 MemberBuilder To(This, getCurrentThisType(), 12444 /*IsArrow=*/true, MemberLookup); 12445 12446 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12447 "Member reference with rvalue base must be rvalue except for reference " 12448 "members, which aren't allowed for move assignment."); 12449 12450 // Build the move of this field. 12451 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12452 To, From, 12453 /*CopyingBaseSubobject=*/false, 12454 /*Copying=*/false); 12455 if (Move.isInvalid()) { 12456 MoveAssignOperator->setInvalidDecl(); 12457 return; 12458 } 12459 12460 // Success! Record the copy. 12461 Statements.push_back(Move.getAs<Stmt>()); 12462 } 12463 12464 if (!Invalid) { 12465 // Add a "return *this;" 12466 ExprResult ThisObj = 12467 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12468 12469 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12470 if (Return.isInvalid()) 12471 Invalid = true; 12472 else 12473 Statements.push_back(Return.getAs<Stmt>()); 12474 } 12475 12476 if (Invalid) { 12477 MoveAssignOperator->setInvalidDecl(); 12478 return; 12479 } 12480 12481 StmtResult Body; 12482 { 12483 CompoundScopeRAII CompoundScope(*this); 12484 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12485 /*isStmtExpr=*/false); 12486 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12487 } 12488 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12489 MoveAssignOperator->markUsed(Context); 12490 12491 if (ASTMutationListener *L = getASTMutationListener()) { 12492 L->CompletedImplicitDefinition(MoveAssignOperator); 12493 } 12494 } 12495 12496 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12497 CXXRecordDecl *ClassDecl) { 12498 // C++ [class.copy]p4: 12499 // If the class definition does not explicitly declare a copy 12500 // constructor, one is declared implicitly. 12501 assert(ClassDecl->needsImplicitCopyConstructor()); 12502 12503 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12504 if (DSM.isAlreadyBeingDeclared()) 12505 return nullptr; 12506 12507 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12508 QualType ArgType = ClassType; 12509 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12510 if (Const) 12511 ArgType = ArgType.withConst(); 12512 12513 if (Context.getLangOpts().OpenCLCPlusPlus) 12514 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12515 12516 ArgType = Context.getLValueReferenceType(ArgType); 12517 12518 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12519 CXXCopyConstructor, 12520 Const); 12521 12522 DeclarationName Name 12523 = Context.DeclarationNames.getCXXConstructorName( 12524 Context.getCanonicalType(ClassType)); 12525 SourceLocation ClassLoc = ClassDecl->getLocation(); 12526 DeclarationNameInfo NameInfo(Name, ClassLoc); 12527 12528 // An implicitly-declared copy constructor is an inline public 12529 // member of its class. 12530 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12531 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12532 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12533 Constexpr); 12534 CopyConstructor->setAccess(AS_public); 12535 CopyConstructor->setDefaulted(); 12536 12537 if (getLangOpts().CUDA) { 12538 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12539 CopyConstructor, 12540 /* ConstRHS */ Const, 12541 /* Diagnose */ false); 12542 } 12543 12544 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 12545 12546 // Add the parameter to the constructor. 12547 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12548 ClassLoc, ClassLoc, 12549 /*IdentifierInfo=*/nullptr, 12550 ArgType, /*TInfo=*/nullptr, 12551 SC_None, nullptr); 12552 CopyConstructor->setParams(FromParam); 12553 12554 CopyConstructor->setTrivial( 12555 ClassDecl->needsOverloadResolutionForCopyConstructor() 12556 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12557 : ClassDecl->hasTrivialCopyConstructor()); 12558 12559 CopyConstructor->setTrivialForCall( 12560 ClassDecl->hasAttr<TrivialABIAttr>() || 12561 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12562 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12563 TAH_ConsiderTrivialABI) 12564 : ClassDecl->hasTrivialCopyConstructorForCall())); 12565 12566 // Note that we have declared this constructor. 12567 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12568 12569 Scope *S = getScopeForContext(ClassDecl); 12570 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12571 12572 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12573 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12574 SetDeclDeleted(CopyConstructor, ClassLoc); 12575 } 12576 12577 if (S) 12578 PushOnScopeChains(CopyConstructor, S, false); 12579 ClassDecl->addDecl(CopyConstructor); 12580 12581 return CopyConstructor; 12582 } 12583 12584 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12585 CXXConstructorDecl *CopyConstructor) { 12586 assert((CopyConstructor->isDefaulted() && 12587 CopyConstructor->isCopyConstructor() && 12588 !CopyConstructor->doesThisDeclarationHaveABody() && 12589 !CopyConstructor->isDeleted()) && 12590 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12591 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12592 return; 12593 12594 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12595 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12596 12597 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12598 12599 // The exception specification is needed because we are defining the 12600 // function. 12601 ResolveExceptionSpec(CurrentLocation, 12602 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12603 MarkVTableUsed(CurrentLocation, ClassDecl); 12604 12605 // Add a context note for diagnostics produced after this point. 12606 Scope.addContextNote(CurrentLocation); 12607 12608 // C++11 [class.copy]p7: 12609 // The [definition of an implicitly declared copy constructor] is 12610 // deprecated if the class has a user-declared copy assignment operator 12611 // or a user-declared destructor. 12612 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12613 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12614 12615 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12616 CopyConstructor->setInvalidDecl(); 12617 } else { 12618 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 12619 ? CopyConstructor->getEndLoc() 12620 : CopyConstructor->getLocation(); 12621 Sema::CompoundScopeRAII CompoundScope(*this); 12622 CopyConstructor->setBody( 12623 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12624 CopyConstructor->markUsed(Context); 12625 } 12626 12627 if (ASTMutationListener *L = getASTMutationListener()) { 12628 L->CompletedImplicitDefinition(CopyConstructor); 12629 } 12630 } 12631 12632 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12633 CXXRecordDecl *ClassDecl) { 12634 assert(ClassDecl->needsImplicitMoveConstructor()); 12635 12636 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12637 if (DSM.isAlreadyBeingDeclared()) 12638 return nullptr; 12639 12640 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12641 12642 QualType ArgType = ClassType; 12643 if (Context.getLangOpts().OpenCLCPlusPlus) 12644 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic); 12645 ArgType = Context.getRValueReferenceType(ArgType); 12646 12647 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12648 CXXMoveConstructor, 12649 false); 12650 12651 DeclarationName Name 12652 = Context.DeclarationNames.getCXXConstructorName( 12653 Context.getCanonicalType(ClassType)); 12654 SourceLocation ClassLoc = ClassDecl->getLocation(); 12655 DeclarationNameInfo NameInfo(Name, ClassLoc); 12656 12657 // C++11 [class.copy]p11: 12658 // An implicitly-declared copy/move constructor is an inline public 12659 // member of its class. 12660 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12661 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12662 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12663 Constexpr); 12664 MoveConstructor->setAccess(AS_public); 12665 MoveConstructor->setDefaulted(); 12666 12667 if (getLangOpts().CUDA) { 12668 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12669 MoveConstructor, 12670 /* ConstRHS */ false, 12671 /* Diagnose */ false); 12672 } 12673 12674 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 12675 12676 // Add the parameter to the constructor. 12677 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12678 ClassLoc, ClassLoc, 12679 /*IdentifierInfo=*/nullptr, 12680 ArgType, /*TInfo=*/nullptr, 12681 SC_None, nullptr); 12682 MoveConstructor->setParams(FromParam); 12683 12684 MoveConstructor->setTrivial( 12685 ClassDecl->needsOverloadResolutionForMoveConstructor() 12686 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12687 : ClassDecl->hasTrivialMoveConstructor()); 12688 12689 MoveConstructor->setTrivialForCall( 12690 ClassDecl->hasAttr<TrivialABIAttr>() || 12691 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12692 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12693 TAH_ConsiderTrivialABI) 12694 : ClassDecl->hasTrivialMoveConstructorForCall())); 12695 12696 // Note that we have declared this constructor. 12697 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12698 12699 Scope *S = getScopeForContext(ClassDecl); 12700 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12701 12702 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12703 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12704 SetDeclDeleted(MoveConstructor, ClassLoc); 12705 } 12706 12707 if (S) 12708 PushOnScopeChains(MoveConstructor, S, false); 12709 ClassDecl->addDecl(MoveConstructor); 12710 12711 return MoveConstructor; 12712 } 12713 12714 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12715 CXXConstructorDecl *MoveConstructor) { 12716 assert((MoveConstructor->isDefaulted() && 12717 MoveConstructor->isMoveConstructor() && 12718 !MoveConstructor->doesThisDeclarationHaveABody() && 12719 !MoveConstructor->isDeleted()) && 12720 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12721 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12722 return; 12723 12724 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12725 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12726 12727 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12728 12729 // The exception specification is needed because we are defining the 12730 // function. 12731 ResolveExceptionSpec(CurrentLocation, 12732 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12733 MarkVTableUsed(CurrentLocation, ClassDecl); 12734 12735 // Add a context note for diagnostics produced after this point. 12736 Scope.addContextNote(CurrentLocation); 12737 12738 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12739 MoveConstructor->setInvalidDecl(); 12740 } else { 12741 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 12742 ? MoveConstructor->getEndLoc() 12743 : MoveConstructor->getLocation(); 12744 Sema::CompoundScopeRAII CompoundScope(*this); 12745 MoveConstructor->setBody(ActOnCompoundStmt( 12746 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12747 MoveConstructor->markUsed(Context); 12748 } 12749 12750 if (ASTMutationListener *L = getASTMutationListener()) { 12751 L->CompletedImplicitDefinition(MoveConstructor); 12752 } 12753 } 12754 12755 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12756 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12757 } 12758 12759 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12760 SourceLocation CurrentLocation, 12761 CXXConversionDecl *Conv) { 12762 SynthesizedFunctionScope Scope(*this, Conv); 12763 assert(!Conv->getReturnType()->isUndeducedType()); 12764 12765 CXXRecordDecl *Lambda = Conv->getParent(); 12766 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12767 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12768 12769 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 12770 CallOp = InstantiateFunctionDeclaration( 12771 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12772 if (!CallOp) 12773 return; 12774 12775 Invoker = InstantiateFunctionDeclaration( 12776 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12777 if (!Invoker) 12778 return; 12779 } 12780 12781 if (CallOp->isInvalidDecl()) 12782 return; 12783 12784 // Mark the call operator referenced (and add to pending instantiations 12785 // if necessary). 12786 // For both the conversion and static-invoker template specializations 12787 // we construct their body's in this function, so no need to add them 12788 // to the PendingInstantiations. 12789 MarkFunctionReferenced(CurrentLocation, CallOp); 12790 12791 // Fill in the __invoke function with a dummy implementation. IR generation 12792 // will fill in the actual details. Update its type in case it contained 12793 // an 'auto'. 12794 Invoker->markUsed(Context); 12795 Invoker->setReferenced(); 12796 Invoker->setType(Conv->getReturnType()->getPointeeType()); 12797 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12798 12799 // Construct the body of the conversion function { return __invoke; }. 12800 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12801 VK_LValue, Conv->getLocation()).get(); 12802 assert(FunctionRef && "Can't refer to __invoke function?"); 12803 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12804 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 12805 Conv->getLocation())); 12806 Conv->markUsed(Context); 12807 Conv->setReferenced(); 12808 12809 if (ASTMutationListener *L = getASTMutationListener()) { 12810 L->CompletedImplicitDefinition(Conv); 12811 L->CompletedImplicitDefinition(Invoker); 12812 } 12813 } 12814 12815 12816 12817 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12818 SourceLocation CurrentLocation, 12819 CXXConversionDecl *Conv) 12820 { 12821 assert(!Conv->getParent()->isGenericLambda()); 12822 12823 SynthesizedFunctionScope Scope(*this, Conv); 12824 12825 // Copy-initialize the lambda object as needed to capture it. 12826 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12827 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12828 12829 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12830 Conv->getLocation(), 12831 Conv, DerefThis); 12832 12833 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12834 // behavior. Note that only the general conversion function does this 12835 // (since it's unusable otherwise); in the case where we inline the 12836 // block literal, it has block literal lifetime semantics. 12837 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12838 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12839 CK_CopyAndAutoreleaseBlockObject, 12840 BuildBlock.get(), nullptr, VK_RValue); 12841 12842 if (BuildBlock.isInvalid()) { 12843 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12844 Conv->setInvalidDecl(); 12845 return; 12846 } 12847 12848 // Create the return statement that returns the block from the conversion 12849 // function. 12850 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12851 if (Return.isInvalid()) { 12852 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12853 Conv->setInvalidDecl(); 12854 return; 12855 } 12856 12857 // Set the body of the conversion function. 12858 Stmt *ReturnS = Return.get(); 12859 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 12860 Conv->getLocation())); 12861 Conv->markUsed(Context); 12862 12863 // We're done; notify the mutation listener, if any. 12864 if (ASTMutationListener *L = getASTMutationListener()) { 12865 L->CompletedImplicitDefinition(Conv); 12866 } 12867 } 12868 12869 /// Determine whether the given list arguments contains exactly one 12870 /// "real" (non-default) argument. 12871 static bool hasOneRealArgument(MultiExprArg Args) { 12872 switch (Args.size()) { 12873 case 0: 12874 return false; 12875 12876 default: 12877 if (!Args[1]->isDefaultArgument()) 12878 return false; 12879 12880 LLVM_FALLTHROUGH; 12881 case 1: 12882 return !Args[0]->isDefaultArgument(); 12883 } 12884 12885 return false; 12886 } 12887 12888 ExprResult 12889 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12890 NamedDecl *FoundDecl, 12891 CXXConstructorDecl *Constructor, 12892 MultiExprArg ExprArgs, 12893 bool HadMultipleCandidates, 12894 bool IsListInitialization, 12895 bool IsStdInitListInitialization, 12896 bool RequiresZeroInit, 12897 unsigned ConstructKind, 12898 SourceRange ParenRange) { 12899 bool Elidable = false; 12900 12901 // C++0x [class.copy]p34: 12902 // When certain criteria are met, an implementation is allowed to 12903 // omit the copy/move construction of a class object, even if the 12904 // copy/move constructor and/or destructor for the object have 12905 // side effects. [...] 12906 // - when a temporary class object that has not been bound to a 12907 // reference (12.2) would be copied/moved to a class object 12908 // with the same cv-unqualified type, the copy/move operation 12909 // can be omitted by constructing the temporary object 12910 // directly into the target of the omitted copy/move 12911 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12912 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12913 Expr *SubExpr = ExprArgs[0]; 12914 Elidable = SubExpr->isTemporaryObject( 12915 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12916 } 12917 12918 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12919 FoundDecl, Constructor, 12920 Elidable, ExprArgs, HadMultipleCandidates, 12921 IsListInitialization, 12922 IsStdInitListInitialization, RequiresZeroInit, 12923 ConstructKind, ParenRange); 12924 } 12925 12926 ExprResult 12927 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12928 NamedDecl *FoundDecl, 12929 CXXConstructorDecl *Constructor, 12930 bool Elidable, 12931 MultiExprArg ExprArgs, 12932 bool HadMultipleCandidates, 12933 bool IsListInitialization, 12934 bool IsStdInitListInitialization, 12935 bool RequiresZeroInit, 12936 unsigned ConstructKind, 12937 SourceRange ParenRange) { 12938 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12939 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12940 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12941 return ExprError(); 12942 } 12943 12944 return BuildCXXConstructExpr( 12945 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12946 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12947 RequiresZeroInit, ConstructKind, ParenRange); 12948 } 12949 12950 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12951 /// including handling of its default argument expressions. 12952 ExprResult 12953 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12954 CXXConstructorDecl *Constructor, 12955 bool Elidable, 12956 MultiExprArg ExprArgs, 12957 bool HadMultipleCandidates, 12958 bool IsListInitialization, 12959 bool IsStdInitListInitialization, 12960 bool RequiresZeroInit, 12961 unsigned ConstructKind, 12962 SourceRange ParenRange) { 12963 assert(declaresSameEntity( 12964 Constructor->getParent(), 12965 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12966 "given constructor for wrong type"); 12967 MarkFunctionReferenced(ConstructLoc, Constructor); 12968 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12969 return ExprError(); 12970 12971 return CXXConstructExpr::Create( 12972 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12973 ExprArgs, HadMultipleCandidates, IsListInitialization, 12974 IsStdInitListInitialization, RequiresZeroInit, 12975 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12976 ParenRange); 12977 } 12978 12979 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12980 assert(Field->hasInClassInitializer()); 12981 12982 // If we already have the in-class initializer nothing needs to be done. 12983 if (Field->getInClassInitializer()) 12984 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12985 12986 // If we might have already tried and failed to instantiate, don't try again. 12987 if (Field->isInvalidDecl()) 12988 return ExprError(); 12989 12990 // Maybe we haven't instantiated the in-class initializer. Go check the 12991 // pattern FieldDecl to see if it has one. 12992 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12993 12994 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12995 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12996 DeclContext::lookup_result Lookup = 12997 ClassPattern->lookup(Field->getDeclName()); 12998 12999 // Lookup can return at most two results: the pattern for the field, or the 13000 // injected class name of the parent record. No other member can have the 13001 // same name as the field. 13002 // In modules mode, lookup can return multiple results (coming from 13003 // different modules). 13004 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 13005 "more than two lookup results for field name"); 13006 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 13007 if (!Pattern) { 13008 assert(isa<CXXRecordDecl>(Lookup[0]) && 13009 "cannot have other non-field member with same name"); 13010 for (auto L : Lookup) 13011 if (isa<FieldDecl>(L)) { 13012 Pattern = cast<FieldDecl>(L); 13013 break; 13014 } 13015 assert(Pattern && "We must have set the Pattern!"); 13016 } 13017 13018 if (!Pattern->hasInClassInitializer() || 13019 InstantiateInClassInitializer(Loc, Field, Pattern, 13020 getTemplateInstantiationArgs(Field))) { 13021 // Don't diagnose this again. 13022 Field->setInvalidDecl(); 13023 return ExprError(); 13024 } 13025 return CXXDefaultInitExpr::Create(Context, Loc, Field); 13026 } 13027 13028 // DR1351: 13029 // If the brace-or-equal-initializer of a non-static data member 13030 // invokes a defaulted default constructor of its class or of an 13031 // enclosing class in a potentially evaluated subexpression, the 13032 // program is ill-formed. 13033 // 13034 // This resolution is unworkable: the exception specification of the 13035 // default constructor can be needed in an unevaluated context, in 13036 // particular, in the operand of a noexcept-expression, and we can be 13037 // unable to compute an exception specification for an enclosed class. 13038 // 13039 // Any attempt to resolve the exception specification of a defaulted default 13040 // constructor before the initializer is lexically complete will ultimately 13041 // come here at which point we can diagnose it. 13042 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 13043 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 13044 << OutermostClass << Field; 13045 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 13046 // Recover by marking the field invalid, unless we're in a SFINAE context. 13047 if (!isSFINAEContext()) 13048 Field->setInvalidDecl(); 13049 return ExprError(); 13050 } 13051 13052 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 13053 if (VD->isInvalidDecl()) return; 13054 13055 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 13056 if (ClassDecl->isInvalidDecl()) return; 13057 if (ClassDecl->hasIrrelevantDestructor()) return; 13058 if (ClassDecl->isDependentContext()) return; 13059 13060 if (VD->isNoDestroy(getASTContext())) 13061 return; 13062 13063 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13064 MarkFunctionReferenced(VD->getLocation(), Destructor); 13065 CheckDestructorAccess(VD->getLocation(), Destructor, 13066 PDiag(diag::err_access_dtor_var) 13067 << VD->getDeclName() 13068 << VD->getType()); 13069 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 13070 13071 if (Destructor->isTrivial()) return; 13072 if (!VD->hasGlobalStorage()) return; 13073 13074 // Emit warning for non-trivial dtor in global scope (a real global, 13075 // class-static, function-static). 13076 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 13077 13078 // TODO: this should be re-enabled for static locals by !CXAAtExit 13079 if (!VD->isStaticLocal()) 13080 Diag(VD->getLocation(), diag::warn_global_destructor); 13081 } 13082 13083 /// Given a constructor and the set of arguments provided for the 13084 /// constructor, convert the arguments and add any required default arguments 13085 /// to form a proper call to this constructor. 13086 /// 13087 /// \returns true if an error occurred, false otherwise. 13088 bool 13089 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 13090 MultiExprArg ArgsPtr, 13091 SourceLocation Loc, 13092 SmallVectorImpl<Expr*> &ConvertedArgs, 13093 bool AllowExplicit, 13094 bool IsListInitialization) { 13095 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 13096 unsigned NumArgs = ArgsPtr.size(); 13097 Expr **Args = ArgsPtr.data(); 13098 13099 const FunctionProtoType *Proto 13100 = Constructor->getType()->getAs<FunctionProtoType>(); 13101 assert(Proto && "Constructor without a prototype?"); 13102 unsigned NumParams = Proto->getNumParams(); 13103 13104 // If too few arguments are available, we'll fill in the rest with defaults. 13105 if (NumArgs < NumParams) 13106 ConvertedArgs.reserve(NumParams); 13107 else 13108 ConvertedArgs.reserve(NumArgs); 13109 13110 VariadicCallType CallType = 13111 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 13112 SmallVector<Expr *, 8> AllArgs; 13113 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 13114 Proto, 0, 13115 llvm::makeArrayRef(Args, NumArgs), 13116 AllArgs, 13117 CallType, AllowExplicit, 13118 IsListInitialization); 13119 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 13120 13121 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 13122 13123 CheckConstructorCall(Constructor, 13124 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 13125 Proto, Loc); 13126 13127 return Invalid; 13128 } 13129 13130 static inline bool 13131 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 13132 const FunctionDecl *FnDecl) { 13133 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 13134 if (isa<NamespaceDecl>(DC)) { 13135 return SemaRef.Diag(FnDecl->getLocation(), 13136 diag::err_operator_new_delete_declared_in_namespace) 13137 << FnDecl->getDeclName(); 13138 } 13139 13140 if (isa<TranslationUnitDecl>(DC) && 13141 FnDecl->getStorageClass() == SC_Static) { 13142 return SemaRef.Diag(FnDecl->getLocation(), 13143 diag::err_operator_new_delete_declared_static) 13144 << FnDecl->getDeclName(); 13145 } 13146 13147 return false; 13148 } 13149 13150 static QualType 13151 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 13152 QualType QTy = PtrTy->getPointeeType(); 13153 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 13154 return SemaRef.Context.getPointerType(QTy); 13155 } 13156 13157 static inline bool 13158 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13159 CanQualType ExpectedResultType, 13160 CanQualType ExpectedFirstParamType, 13161 unsigned DependentParamTypeDiag, 13162 unsigned InvalidParamTypeDiag) { 13163 QualType ResultType = 13164 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13165 13166 // Check that the result type is not dependent. 13167 if (ResultType->isDependentType()) 13168 return SemaRef.Diag(FnDecl->getLocation(), 13169 diag::err_operator_new_delete_dependent_result_type) 13170 << FnDecl->getDeclName() << ExpectedResultType; 13171 13172 // OpenCL C++: the operator is valid on any address space. 13173 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13174 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13175 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13176 } 13177 } 13178 13179 // Check that the result type is what we expect. 13180 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13181 return SemaRef.Diag(FnDecl->getLocation(), 13182 diag::err_operator_new_delete_invalid_result_type) 13183 << FnDecl->getDeclName() << ExpectedResultType; 13184 13185 // A function template must have at least 2 parameters. 13186 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13187 return SemaRef.Diag(FnDecl->getLocation(), 13188 diag::err_operator_new_delete_template_too_few_parameters) 13189 << FnDecl->getDeclName(); 13190 13191 // The function decl must have at least 1 parameter. 13192 if (FnDecl->getNumParams() == 0) 13193 return SemaRef.Diag(FnDecl->getLocation(), 13194 diag::err_operator_new_delete_too_few_parameters) 13195 << FnDecl->getDeclName(); 13196 13197 // Check the first parameter type is not dependent. 13198 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13199 if (FirstParamType->isDependentType()) 13200 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13201 << FnDecl->getDeclName() << ExpectedFirstParamType; 13202 13203 // Check that the first parameter type is what we expect. 13204 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13205 // OpenCL C++: the operator is valid on any address space. 13206 if (auto *PtrTy = 13207 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13208 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13209 } 13210 } 13211 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13212 ExpectedFirstParamType) 13213 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13214 << FnDecl->getDeclName() << ExpectedFirstParamType; 13215 13216 return false; 13217 } 13218 13219 static bool 13220 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13221 // C++ [basic.stc.dynamic.allocation]p1: 13222 // A program is ill-formed if an allocation function is declared in a 13223 // namespace scope other than global scope or declared static in global 13224 // scope. 13225 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13226 return true; 13227 13228 CanQualType SizeTy = 13229 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13230 13231 // C++ [basic.stc.dynamic.allocation]p1: 13232 // The return type shall be void*. The first parameter shall have type 13233 // std::size_t. 13234 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13235 SizeTy, 13236 diag::err_operator_new_dependent_param_type, 13237 diag::err_operator_new_param_type)) 13238 return true; 13239 13240 // C++ [basic.stc.dynamic.allocation]p1: 13241 // The first parameter shall not have an associated default argument. 13242 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13243 return SemaRef.Diag(FnDecl->getLocation(), 13244 diag::err_operator_new_default_arg) 13245 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13246 13247 return false; 13248 } 13249 13250 static bool 13251 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13252 // C++ [basic.stc.dynamic.deallocation]p1: 13253 // A program is ill-formed if deallocation functions are declared in a 13254 // namespace scope other than global scope or declared static in global 13255 // scope. 13256 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13257 return true; 13258 13259 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13260 13261 // C++ P0722: 13262 // Within a class C, the first parameter of a destroying operator delete 13263 // shall be of type C *. The first parameter of any other deallocation 13264 // function shall be of type void *. 13265 CanQualType ExpectedFirstParamType = 13266 MD && MD->isDestroyingOperatorDelete() 13267 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13268 SemaRef.Context.getRecordType(MD->getParent()))) 13269 : SemaRef.Context.VoidPtrTy; 13270 13271 // C++ [basic.stc.dynamic.deallocation]p2: 13272 // Each deallocation function shall return void 13273 if (CheckOperatorNewDeleteTypes( 13274 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13275 diag::err_operator_delete_dependent_param_type, 13276 diag::err_operator_delete_param_type)) 13277 return true; 13278 13279 // C++ P0722: 13280 // A destroying operator delete shall be a usual deallocation function. 13281 if (MD && !MD->getParent()->isDependentContext() && 13282 MD->isDestroyingOperatorDelete() && 13283 !SemaRef.isUsualDeallocationFunction(MD)) { 13284 SemaRef.Diag(MD->getLocation(), 13285 diag::err_destroying_operator_delete_not_usual); 13286 return true; 13287 } 13288 13289 return false; 13290 } 13291 13292 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13293 /// of this overloaded operator is well-formed. If so, returns false; 13294 /// otherwise, emits appropriate diagnostics and returns true. 13295 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13296 assert(FnDecl && FnDecl->isOverloadedOperator() && 13297 "Expected an overloaded operator declaration"); 13298 13299 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13300 13301 // C++ [over.oper]p5: 13302 // The allocation and deallocation functions, operator new, 13303 // operator new[], operator delete and operator delete[], are 13304 // described completely in 3.7.3. The attributes and restrictions 13305 // found in the rest of this subclause do not apply to them unless 13306 // explicitly stated in 3.7.3. 13307 if (Op == OO_Delete || Op == OO_Array_Delete) 13308 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13309 13310 if (Op == OO_New || Op == OO_Array_New) 13311 return CheckOperatorNewDeclaration(*this, FnDecl); 13312 13313 // C++ [over.oper]p6: 13314 // An operator function shall either be a non-static member 13315 // function or be a non-member function and have at least one 13316 // parameter whose type is a class, a reference to a class, an 13317 // enumeration, or a reference to an enumeration. 13318 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13319 if (MethodDecl->isStatic()) 13320 return Diag(FnDecl->getLocation(), 13321 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13322 } else { 13323 bool ClassOrEnumParam = false; 13324 for (auto Param : FnDecl->parameters()) { 13325 QualType ParamType = Param->getType().getNonReferenceType(); 13326 if (ParamType->isDependentType() || ParamType->isRecordType() || 13327 ParamType->isEnumeralType()) { 13328 ClassOrEnumParam = true; 13329 break; 13330 } 13331 } 13332 13333 if (!ClassOrEnumParam) 13334 return Diag(FnDecl->getLocation(), 13335 diag::err_operator_overload_needs_class_or_enum) 13336 << FnDecl->getDeclName(); 13337 } 13338 13339 // C++ [over.oper]p8: 13340 // An operator function cannot have default arguments (8.3.6), 13341 // except where explicitly stated below. 13342 // 13343 // Only the function-call operator allows default arguments 13344 // (C++ [over.call]p1). 13345 if (Op != OO_Call) { 13346 for (auto Param : FnDecl->parameters()) { 13347 if (Param->hasDefaultArg()) 13348 return Diag(Param->getLocation(), 13349 diag::err_operator_overload_default_arg) 13350 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13351 } 13352 } 13353 13354 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13355 { false, false, false } 13356 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13357 , { Unary, Binary, MemberOnly } 13358 #include "clang/Basic/OperatorKinds.def" 13359 }; 13360 13361 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13362 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13363 bool MustBeMemberOperator = OperatorUses[Op][2]; 13364 13365 // C++ [over.oper]p8: 13366 // [...] Operator functions cannot have more or fewer parameters 13367 // than the number required for the corresponding operator, as 13368 // described in the rest of this subclause. 13369 unsigned NumParams = FnDecl->getNumParams() 13370 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13371 if (Op != OO_Call && 13372 ((NumParams == 1 && !CanBeUnaryOperator) || 13373 (NumParams == 2 && !CanBeBinaryOperator) || 13374 (NumParams < 1) || (NumParams > 2))) { 13375 // We have the wrong number of parameters. 13376 unsigned ErrorKind; 13377 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13378 ErrorKind = 2; // 2 -> unary or binary. 13379 } else if (CanBeUnaryOperator) { 13380 ErrorKind = 0; // 0 -> unary 13381 } else { 13382 assert(CanBeBinaryOperator && 13383 "All non-call overloaded operators are unary or binary!"); 13384 ErrorKind = 1; // 1 -> binary 13385 } 13386 13387 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13388 << FnDecl->getDeclName() << NumParams << ErrorKind; 13389 } 13390 13391 // Overloaded operators other than operator() cannot be variadic. 13392 if (Op != OO_Call && 13393 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13394 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13395 << FnDecl->getDeclName(); 13396 } 13397 13398 // Some operators must be non-static member functions. 13399 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13400 return Diag(FnDecl->getLocation(), 13401 diag::err_operator_overload_must_be_member) 13402 << FnDecl->getDeclName(); 13403 } 13404 13405 // C++ [over.inc]p1: 13406 // The user-defined function called operator++ implements the 13407 // prefix and postfix ++ operator. If this function is a member 13408 // function with no parameters, or a non-member function with one 13409 // parameter of class or enumeration type, it defines the prefix 13410 // increment operator ++ for objects of that type. If the function 13411 // is a member function with one parameter (which shall be of type 13412 // int) or a non-member function with two parameters (the second 13413 // of which shall be of type int), it defines the postfix 13414 // increment operator ++ for objects of that type. 13415 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13416 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13417 QualType ParamType = LastParam->getType(); 13418 13419 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13420 !ParamType->isDependentType()) 13421 return Diag(LastParam->getLocation(), 13422 diag::err_operator_overload_post_incdec_must_be_int) 13423 << LastParam->getType() << (Op == OO_MinusMinus); 13424 } 13425 13426 return false; 13427 } 13428 13429 static bool 13430 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13431 FunctionTemplateDecl *TpDecl) { 13432 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13433 13434 // Must have one or two template parameters. 13435 if (TemplateParams->size() == 1) { 13436 NonTypeTemplateParmDecl *PmDecl = 13437 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13438 13439 // The template parameter must be a char parameter pack. 13440 if (PmDecl && PmDecl->isTemplateParameterPack() && 13441 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13442 return false; 13443 13444 } else if (TemplateParams->size() == 2) { 13445 TemplateTypeParmDecl *PmType = 13446 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13447 NonTypeTemplateParmDecl *PmArgs = 13448 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13449 13450 // The second template parameter must be a parameter pack with the 13451 // first template parameter as its type. 13452 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13453 PmArgs->isTemplateParameterPack()) { 13454 const TemplateTypeParmType *TArgs = 13455 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13456 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13457 TArgs->getIndex() == PmType->getIndex()) { 13458 if (!SemaRef.inTemplateInstantiation()) 13459 SemaRef.Diag(TpDecl->getLocation(), 13460 diag::ext_string_literal_operator_template); 13461 return false; 13462 } 13463 } 13464 } 13465 13466 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13467 diag::err_literal_operator_template) 13468 << TpDecl->getTemplateParameters()->getSourceRange(); 13469 return true; 13470 } 13471 13472 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13473 /// of this literal operator function is well-formed. If so, returns 13474 /// false; otherwise, emits appropriate diagnostics and returns true. 13475 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13476 if (isa<CXXMethodDecl>(FnDecl)) { 13477 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13478 << FnDecl->getDeclName(); 13479 return true; 13480 } 13481 13482 if (FnDecl->isExternC()) { 13483 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13484 if (const LinkageSpecDecl *LSD = 13485 FnDecl->getDeclContext()->getExternCContext()) 13486 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13487 return true; 13488 } 13489 13490 // This might be the definition of a literal operator template. 13491 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13492 13493 // This might be a specialization of a literal operator template. 13494 if (!TpDecl) 13495 TpDecl = FnDecl->getPrimaryTemplate(); 13496 13497 // template <char...> type operator "" name() and 13498 // template <class T, T...> type operator "" name() are the only valid 13499 // template signatures, and the only valid signatures with no parameters. 13500 if (TpDecl) { 13501 if (FnDecl->param_size() != 0) { 13502 Diag(FnDecl->getLocation(), 13503 diag::err_literal_operator_template_with_params); 13504 return true; 13505 } 13506 13507 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13508 return true; 13509 13510 } else if (FnDecl->param_size() == 1) { 13511 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13512 13513 QualType ParamType = Param->getType().getUnqualifiedType(); 13514 13515 // Only unsigned long long int, long double, any character type, and const 13516 // char * are allowed as the only parameters. 13517 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13518 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13519 Context.hasSameType(ParamType, Context.CharTy) || 13520 Context.hasSameType(ParamType, Context.WideCharTy) || 13521 Context.hasSameType(ParamType, Context.Char8Ty) || 13522 Context.hasSameType(ParamType, Context.Char16Ty) || 13523 Context.hasSameType(ParamType, Context.Char32Ty)) { 13524 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13525 QualType InnerType = Ptr->getPointeeType(); 13526 13527 // Pointer parameter must be a const char *. 13528 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13529 Context.CharTy) && 13530 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13531 Diag(Param->getSourceRange().getBegin(), 13532 diag::err_literal_operator_param) 13533 << ParamType << "'const char *'" << Param->getSourceRange(); 13534 return true; 13535 } 13536 13537 } else if (ParamType->isRealFloatingType()) { 13538 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13539 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13540 return true; 13541 13542 } else if (ParamType->isIntegerType()) { 13543 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13544 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13545 return true; 13546 13547 } else { 13548 Diag(Param->getSourceRange().getBegin(), 13549 diag::err_literal_operator_invalid_param) 13550 << ParamType << Param->getSourceRange(); 13551 return true; 13552 } 13553 13554 } else if (FnDecl->param_size() == 2) { 13555 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13556 13557 // First, verify that the first parameter is correct. 13558 13559 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13560 13561 // Two parameter function must have a pointer to const as a 13562 // first parameter; let's strip those qualifiers. 13563 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13564 13565 if (!PT) { 13566 Diag((*Param)->getSourceRange().getBegin(), 13567 diag::err_literal_operator_param) 13568 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13569 return true; 13570 } 13571 13572 QualType PointeeType = PT->getPointeeType(); 13573 // First parameter must be const 13574 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13575 Diag((*Param)->getSourceRange().getBegin(), 13576 diag::err_literal_operator_param) 13577 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13578 return true; 13579 } 13580 13581 QualType InnerType = PointeeType.getUnqualifiedType(); 13582 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13583 // const char32_t* are allowed as the first parameter to a two-parameter 13584 // function 13585 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13586 Context.hasSameType(InnerType, Context.WideCharTy) || 13587 Context.hasSameType(InnerType, Context.Char8Ty) || 13588 Context.hasSameType(InnerType, Context.Char16Ty) || 13589 Context.hasSameType(InnerType, Context.Char32Ty))) { 13590 Diag((*Param)->getSourceRange().getBegin(), 13591 diag::err_literal_operator_param) 13592 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13593 return true; 13594 } 13595 13596 // Move on to the second and final parameter. 13597 ++Param; 13598 13599 // The second parameter must be a std::size_t. 13600 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13601 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13602 Diag((*Param)->getSourceRange().getBegin(), 13603 diag::err_literal_operator_param) 13604 << SecondParamType << Context.getSizeType() 13605 << (*Param)->getSourceRange(); 13606 return true; 13607 } 13608 } else { 13609 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13610 return true; 13611 } 13612 13613 // Parameters are good. 13614 13615 // A parameter-declaration-clause containing a default argument is not 13616 // equivalent to any of the permitted forms. 13617 for (auto Param : FnDecl->parameters()) { 13618 if (Param->hasDefaultArg()) { 13619 Diag(Param->getDefaultArgRange().getBegin(), 13620 diag::err_literal_operator_default_argument) 13621 << Param->getDefaultArgRange(); 13622 break; 13623 } 13624 } 13625 13626 StringRef LiteralName 13627 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13628 if (LiteralName[0] != '_' && 13629 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13630 // C++11 [usrlit.suffix]p1: 13631 // Literal suffix identifiers that do not start with an underscore 13632 // are reserved for future standardization. 13633 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13634 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13635 } 13636 13637 return false; 13638 } 13639 13640 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13641 /// linkage specification, including the language and (if present) 13642 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13643 /// language string literal. LBraceLoc, if valid, provides the location of 13644 /// the '{' brace. Otherwise, this linkage specification does not 13645 /// have any braces. 13646 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13647 Expr *LangStr, 13648 SourceLocation LBraceLoc) { 13649 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13650 if (!Lit->isAscii()) { 13651 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13652 << LangStr->getSourceRange(); 13653 return nullptr; 13654 } 13655 13656 StringRef Lang = Lit->getString(); 13657 LinkageSpecDecl::LanguageIDs Language; 13658 if (Lang == "C") 13659 Language = LinkageSpecDecl::lang_c; 13660 else if (Lang == "C++") 13661 Language = LinkageSpecDecl::lang_cxx; 13662 else { 13663 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13664 << LangStr->getSourceRange(); 13665 return nullptr; 13666 } 13667 13668 // FIXME: Add all the various semantics of linkage specifications 13669 13670 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13671 LangStr->getExprLoc(), Language, 13672 LBraceLoc.isValid()); 13673 CurContext->addDecl(D); 13674 PushDeclContext(S, D); 13675 return D; 13676 } 13677 13678 /// ActOnFinishLinkageSpecification - Complete the definition of 13679 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13680 /// valid, it's the position of the closing '}' brace in a linkage 13681 /// specification that uses braces. 13682 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13683 Decl *LinkageSpec, 13684 SourceLocation RBraceLoc) { 13685 if (RBraceLoc.isValid()) { 13686 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13687 LSDecl->setRBraceLoc(RBraceLoc); 13688 } 13689 PopDeclContext(); 13690 return LinkageSpec; 13691 } 13692 13693 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13694 const ParsedAttributesView &AttrList, 13695 SourceLocation SemiLoc) { 13696 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13697 // Attribute declarations appertain to empty declaration so we handle 13698 // them here. 13699 ProcessDeclAttributeList(S, ED, AttrList); 13700 13701 CurContext->addDecl(ED); 13702 return ED; 13703 } 13704 13705 /// Perform semantic analysis for the variable declaration that 13706 /// occurs within a C++ catch clause, returning the newly-created 13707 /// variable. 13708 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13709 TypeSourceInfo *TInfo, 13710 SourceLocation StartLoc, 13711 SourceLocation Loc, 13712 IdentifierInfo *Name) { 13713 bool Invalid = false; 13714 QualType ExDeclType = TInfo->getType(); 13715 13716 // Arrays and functions decay. 13717 if (ExDeclType->isArrayType()) 13718 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13719 else if (ExDeclType->isFunctionType()) 13720 ExDeclType = Context.getPointerType(ExDeclType); 13721 13722 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13723 // The exception-declaration shall not denote a pointer or reference to an 13724 // incomplete type, other than [cv] void*. 13725 // N2844 forbids rvalue references. 13726 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13727 Diag(Loc, diag::err_catch_rvalue_ref); 13728 Invalid = true; 13729 } 13730 13731 if (ExDeclType->isVariablyModifiedType()) { 13732 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13733 Invalid = true; 13734 } 13735 13736 QualType BaseType = ExDeclType; 13737 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13738 unsigned DK = diag::err_catch_incomplete; 13739 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13740 BaseType = Ptr->getPointeeType(); 13741 Mode = 1; 13742 DK = diag::err_catch_incomplete_ptr; 13743 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13744 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13745 BaseType = Ref->getPointeeType(); 13746 Mode = 2; 13747 DK = diag::err_catch_incomplete_ref; 13748 } 13749 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13750 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13751 Invalid = true; 13752 13753 if (!Invalid && !ExDeclType->isDependentType() && 13754 RequireNonAbstractType(Loc, ExDeclType, 13755 diag::err_abstract_type_in_decl, 13756 AbstractVariableType)) 13757 Invalid = true; 13758 13759 // Only the non-fragile NeXT runtime currently supports C++ catches 13760 // of ObjC types, and no runtime supports catching ObjC types by value. 13761 if (!Invalid && getLangOpts().ObjC) { 13762 QualType T = ExDeclType; 13763 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13764 T = RT->getPointeeType(); 13765 13766 if (T->isObjCObjectType()) { 13767 Diag(Loc, diag::err_objc_object_catch); 13768 Invalid = true; 13769 } else if (T->isObjCObjectPointerType()) { 13770 // FIXME: should this be a test for macosx-fragile specifically? 13771 if (getLangOpts().ObjCRuntime.isFragile()) 13772 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13773 } 13774 } 13775 13776 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13777 ExDeclType, TInfo, SC_None); 13778 ExDecl->setExceptionVariable(true); 13779 13780 // In ARC, infer 'retaining' for variables of retainable type. 13781 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13782 Invalid = true; 13783 13784 if (!Invalid && !ExDeclType->isDependentType()) { 13785 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13786 // Insulate this from anything else we might currently be parsing. 13787 EnterExpressionEvaluationContext scope( 13788 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13789 13790 // C++ [except.handle]p16: 13791 // The object declared in an exception-declaration or, if the 13792 // exception-declaration does not specify a name, a temporary (12.2) is 13793 // copy-initialized (8.5) from the exception object. [...] 13794 // The object is destroyed when the handler exits, after the destruction 13795 // of any automatic objects initialized within the handler. 13796 // 13797 // We just pretend to initialize the object with itself, then make sure 13798 // it can be destroyed later. 13799 QualType initType = Context.getExceptionObjectType(ExDeclType); 13800 13801 InitializedEntity entity = 13802 InitializedEntity::InitializeVariable(ExDecl); 13803 InitializationKind initKind = 13804 InitializationKind::CreateCopy(Loc, SourceLocation()); 13805 13806 Expr *opaqueValue = 13807 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13808 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13809 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13810 if (result.isInvalid()) 13811 Invalid = true; 13812 else { 13813 // If the constructor used was non-trivial, set this as the 13814 // "initializer". 13815 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13816 if (!construct->getConstructor()->isTrivial()) { 13817 Expr *init = MaybeCreateExprWithCleanups(construct); 13818 ExDecl->setInit(init); 13819 } 13820 13821 // And make sure it's destructable. 13822 FinalizeVarWithDestructor(ExDecl, recordType); 13823 } 13824 } 13825 } 13826 13827 if (Invalid) 13828 ExDecl->setInvalidDecl(); 13829 13830 return ExDecl; 13831 } 13832 13833 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13834 /// handler. 13835 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13836 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13837 bool Invalid = D.isInvalidType(); 13838 13839 // Check for unexpanded parameter packs. 13840 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13841 UPPC_ExceptionType)) { 13842 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13843 D.getIdentifierLoc()); 13844 Invalid = true; 13845 } 13846 13847 IdentifierInfo *II = D.getIdentifier(); 13848 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13849 LookupOrdinaryName, 13850 ForVisibleRedeclaration)) { 13851 // The scope should be freshly made just for us. There is just no way 13852 // it contains any previous declaration, except for function parameters in 13853 // a function-try-block's catch statement. 13854 assert(!S->isDeclScope(PrevDecl)); 13855 if (isDeclInScope(PrevDecl, CurContext, S)) { 13856 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13857 << D.getIdentifier(); 13858 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13859 Invalid = true; 13860 } else if (PrevDecl->isTemplateParameter()) 13861 // Maybe we will complain about the shadowed template parameter. 13862 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13863 } 13864 13865 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13866 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13867 << D.getCXXScopeSpec().getRange(); 13868 Invalid = true; 13869 } 13870 13871 VarDecl *ExDecl = BuildExceptionDeclaration( 13872 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 13873 if (Invalid) 13874 ExDecl->setInvalidDecl(); 13875 13876 // Add the exception declaration into this scope. 13877 if (II) 13878 PushOnScopeChains(ExDecl, S); 13879 else 13880 CurContext->addDecl(ExDecl); 13881 13882 ProcessDeclAttributes(S, ExDecl, D); 13883 return ExDecl; 13884 } 13885 13886 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13887 Expr *AssertExpr, 13888 Expr *AssertMessageExpr, 13889 SourceLocation RParenLoc) { 13890 StringLiteral *AssertMessage = 13891 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13892 13893 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13894 return nullptr; 13895 13896 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13897 AssertMessage, RParenLoc, false); 13898 } 13899 13900 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13901 Expr *AssertExpr, 13902 StringLiteral *AssertMessage, 13903 SourceLocation RParenLoc, 13904 bool Failed) { 13905 assert(AssertExpr != nullptr && "Expected non-null condition"); 13906 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13907 !Failed) { 13908 // In a static_assert-declaration, the constant-expression shall be a 13909 // constant expression that can be contextually converted to bool. 13910 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13911 if (Converted.isInvalid()) 13912 Failed = true; 13913 else 13914 Converted = ConstantExpr::Create(Context, Converted.get()); 13915 13916 llvm::APSInt Cond; 13917 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13918 diag::err_static_assert_expression_is_not_constant, 13919 /*AllowFold=*/false).isInvalid()) 13920 Failed = true; 13921 13922 if (!Failed && !Cond) { 13923 SmallString<256> MsgBuffer; 13924 llvm::raw_svector_ostream Msg(MsgBuffer); 13925 if (AssertMessage) 13926 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13927 13928 Expr *InnerCond = nullptr; 13929 std::string InnerCondDescription; 13930 std::tie(InnerCond, InnerCondDescription) = 13931 findFailedBooleanCondition(Converted.get()); 13932 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 13933 && !isa<IntegerLiteral>(InnerCond)) { 13934 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13935 << InnerCondDescription << !AssertMessage 13936 << Msg.str() << InnerCond->getSourceRange(); 13937 } else { 13938 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13939 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13940 } 13941 Failed = true; 13942 } 13943 } 13944 13945 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13946 /*DiscardedValue*/false, 13947 /*IsConstexpr*/true); 13948 if (FullAssertExpr.isInvalid()) 13949 Failed = true; 13950 else 13951 AssertExpr = FullAssertExpr.get(); 13952 13953 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13954 AssertExpr, AssertMessage, RParenLoc, 13955 Failed); 13956 13957 CurContext->addDecl(Decl); 13958 return Decl; 13959 } 13960 13961 /// Perform semantic analysis of the given friend type declaration. 13962 /// 13963 /// \returns A friend declaration that. 13964 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13965 SourceLocation FriendLoc, 13966 TypeSourceInfo *TSInfo) { 13967 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13968 13969 QualType T = TSInfo->getType(); 13970 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13971 13972 // C++03 [class.friend]p2: 13973 // An elaborated-type-specifier shall be used in a friend declaration 13974 // for a class.* 13975 // 13976 // * The class-key of the elaborated-type-specifier is required. 13977 if (!CodeSynthesisContexts.empty()) { 13978 // Do not complain about the form of friend template types during any kind 13979 // of code synthesis. For template instantiation, we will have complained 13980 // when the template was defined. 13981 } else { 13982 if (!T->isElaboratedTypeSpecifier()) { 13983 // If we evaluated the type to a record type, suggest putting 13984 // a tag in front. 13985 if (const RecordType *RT = T->getAs<RecordType>()) { 13986 RecordDecl *RD = RT->getDecl(); 13987 13988 SmallString<16> InsertionText(" "); 13989 InsertionText += RD->getKindName(); 13990 13991 Diag(TypeRange.getBegin(), 13992 getLangOpts().CPlusPlus11 ? 13993 diag::warn_cxx98_compat_unelaborated_friend_type : 13994 diag::ext_unelaborated_friend_type) 13995 << (unsigned) RD->getTagKind() 13996 << T 13997 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13998 InsertionText); 13999 } else { 14000 Diag(FriendLoc, 14001 getLangOpts().CPlusPlus11 ? 14002 diag::warn_cxx98_compat_nonclass_type_friend : 14003 diag::ext_nonclass_type_friend) 14004 << T 14005 << TypeRange; 14006 } 14007 } else if (T->getAs<EnumType>()) { 14008 Diag(FriendLoc, 14009 getLangOpts().CPlusPlus11 ? 14010 diag::warn_cxx98_compat_enum_friend : 14011 diag::ext_enum_friend) 14012 << T 14013 << TypeRange; 14014 } 14015 14016 // C++11 [class.friend]p3: 14017 // A friend declaration that does not declare a function shall have one 14018 // of the following forms: 14019 // friend elaborated-type-specifier ; 14020 // friend simple-type-specifier ; 14021 // friend typename-specifier ; 14022 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 14023 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 14024 } 14025 14026 // If the type specifier in a friend declaration designates a (possibly 14027 // cv-qualified) class type, that class is declared as a friend; otherwise, 14028 // the friend declaration is ignored. 14029 return FriendDecl::Create(Context, CurContext, 14030 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 14031 FriendLoc); 14032 } 14033 14034 /// Handle a friend tag declaration where the scope specifier was 14035 /// templated. 14036 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 14037 unsigned TagSpec, SourceLocation TagLoc, 14038 CXXScopeSpec &SS, IdentifierInfo *Name, 14039 SourceLocation NameLoc, 14040 const ParsedAttributesView &Attr, 14041 MultiTemplateParamsArg TempParamLists) { 14042 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14043 14044 bool IsMemberSpecialization = false; 14045 bool Invalid = false; 14046 14047 if (TemplateParameterList *TemplateParams = 14048 MatchTemplateParametersToScopeSpecifier( 14049 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 14050 IsMemberSpecialization, Invalid)) { 14051 if (TemplateParams->size() > 0) { 14052 // This is a declaration of a class template. 14053 if (Invalid) 14054 return nullptr; 14055 14056 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 14057 NameLoc, Attr, TemplateParams, AS_public, 14058 /*ModulePrivateLoc=*/SourceLocation(), 14059 FriendLoc, TempParamLists.size() - 1, 14060 TempParamLists.data()).get(); 14061 } else { 14062 // The "template<>" header is extraneous. 14063 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14064 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14065 IsMemberSpecialization = true; 14066 } 14067 } 14068 14069 if (Invalid) return nullptr; 14070 14071 bool isAllExplicitSpecializations = true; 14072 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 14073 if (TempParamLists[I]->size()) { 14074 isAllExplicitSpecializations = false; 14075 break; 14076 } 14077 } 14078 14079 // FIXME: don't ignore attributes. 14080 14081 // If it's explicit specializations all the way down, just forget 14082 // about the template header and build an appropriate non-templated 14083 // friend. TODO: for source fidelity, remember the headers. 14084 if (isAllExplicitSpecializations) { 14085 if (SS.isEmpty()) { 14086 bool Owned = false; 14087 bool IsDependent = false; 14088 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 14089 Attr, AS_public, 14090 /*ModulePrivateLoc=*/SourceLocation(), 14091 MultiTemplateParamsArg(), Owned, IsDependent, 14092 /*ScopedEnumKWLoc=*/SourceLocation(), 14093 /*ScopedEnumUsesClassTag=*/false, 14094 /*UnderlyingType=*/TypeResult(), 14095 /*IsTypeSpecifier=*/false, 14096 /*IsTemplateParamOrArg=*/false); 14097 } 14098 14099 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 14100 ElaboratedTypeKeyword Keyword 14101 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14102 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 14103 *Name, NameLoc); 14104 if (T.isNull()) 14105 return nullptr; 14106 14107 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14108 if (isa<DependentNameType>(T)) { 14109 DependentNameTypeLoc TL = 14110 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14111 TL.setElaboratedKeywordLoc(TagLoc); 14112 TL.setQualifierLoc(QualifierLoc); 14113 TL.setNameLoc(NameLoc); 14114 } else { 14115 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 14116 TL.setElaboratedKeywordLoc(TagLoc); 14117 TL.setQualifierLoc(QualifierLoc); 14118 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 14119 } 14120 14121 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14122 TSI, FriendLoc, TempParamLists); 14123 Friend->setAccess(AS_public); 14124 CurContext->addDecl(Friend); 14125 return Friend; 14126 } 14127 14128 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 14129 14130 14131 14132 // Handle the case of a templated-scope friend class. e.g. 14133 // template <class T> class A<T>::B; 14134 // FIXME: we don't support these right now. 14135 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 14136 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 14137 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14138 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 14139 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14140 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14141 TL.setElaboratedKeywordLoc(TagLoc); 14142 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 14143 TL.setNameLoc(NameLoc); 14144 14145 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14146 TSI, FriendLoc, TempParamLists); 14147 Friend->setAccess(AS_public); 14148 Friend->setUnsupportedFriend(true); 14149 CurContext->addDecl(Friend); 14150 return Friend; 14151 } 14152 14153 /// Handle a friend type declaration. This works in tandem with 14154 /// ActOnTag. 14155 /// 14156 /// Notes on friend class templates: 14157 /// 14158 /// We generally treat friend class declarations as if they were 14159 /// declaring a class. So, for example, the elaborated type specifier 14160 /// in a friend declaration is required to obey the restrictions of a 14161 /// class-head (i.e. no typedefs in the scope chain), template 14162 /// parameters are required to match up with simple template-ids, &c. 14163 /// However, unlike when declaring a template specialization, it's 14164 /// okay to refer to a template specialization without an empty 14165 /// template parameter declaration, e.g. 14166 /// friend class A<T>::B<unsigned>; 14167 /// We permit this as a special case; if there are any template 14168 /// parameters present at all, require proper matching, i.e. 14169 /// template <> template \<class T> friend class A<int>::B; 14170 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14171 MultiTemplateParamsArg TempParams) { 14172 SourceLocation Loc = DS.getBeginLoc(); 14173 14174 assert(DS.isFriendSpecified()); 14175 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14176 14177 // C++ [class.friend]p3: 14178 // A friend declaration that does not declare a function shall have one of 14179 // the following forms: 14180 // friend elaborated-type-specifier ; 14181 // friend simple-type-specifier ; 14182 // friend typename-specifier ; 14183 // 14184 // Any declaration with a type qualifier does not have that form. (It's 14185 // legal to specify a qualified type as a friend, you just can't write the 14186 // keywords.) 14187 if (DS.getTypeQualifiers()) { 14188 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 14189 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 14190 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 14191 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 14192 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 14193 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 14194 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 14195 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 14196 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 14197 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 14198 } 14199 14200 // Try to convert the decl specifier to a type. This works for 14201 // friend templates because ActOnTag never produces a ClassTemplateDecl 14202 // for a TUK_Friend. 14203 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14204 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14205 QualType T = TSI->getType(); 14206 if (TheDeclarator.isInvalidType()) 14207 return nullptr; 14208 14209 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14210 return nullptr; 14211 14212 // This is definitely an error in C++98. It's probably meant to 14213 // be forbidden in C++0x, too, but the specification is just 14214 // poorly written. 14215 // 14216 // The problem is with declarations like the following: 14217 // template <T> friend A<T>::foo; 14218 // where deciding whether a class C is a friend or not now hinges 14219 // on whether there exists an instantiation of A that causes 14220 // 'foo' to equal C. There are restrictions on class-heads 14221 // (which we declare (by fiat) elaborated friend declarations to 14222 // be) that makes this tractable. 14223 // 14224 // FIXME: handle "template <> friend class A<T>;", which 14225 // is possibly well-formed? Who even knows? 14226 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14227 Diag(Loc, diag::err_tagless_friend_type_template) 14228 << DS.getSourceRange(); 14229 return nullptr; 14230 } 14231 14232 // C++98 [class.friend]p1: A friend of a class is a function 14233 // or class that is not a member of the class . . . 14234 // This is fixed in DR77, which just barely didn't make the C++03 14235 // deadline. It's also a very silly restriction that seriously 14236 // affects inner classes and which nobody else seems to implement; 14237 // thus we never diagnose it, not even in -pedantic. 14238 // 14239 // But note that we could warn about it: it's always useless to 14240 // friend one of your own members (it's not, however, worthless to 14241 // friend a member of an arbitrary specialization of your template). 14242 14243 Decl *D; 14244 if (!TempParams.empty()) 14245 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14246 TempParams, 14247 TSI, 14248 DS.getFriendSpecLoc()); 14249 else 14250 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14251 14252 if (!D) 14253 return nullptr; 14254 14255 D->setAccess(AS_public); 14256 CurContext->addDecl(D); 14257 14258 return D; 14259 } 14260 14261 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14262 MultiTemplateParamsArg TemplateParams) { 14263 const DeclSpec &DS = D.getDeclSpec(); 14264 14265 assert(DS.isFriendSpecified()); 14266 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14267 14268 SourceLocation Loc = D.getIdentifierLoc(); 14269 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14270 14271 // C++ [class.friend]p1 14272 // A friend of a class is a function or class.... 14273 // Note that this sees through typedefs, which is intended. 14274 // It *doesn't* see through dependent types, which is correct 14275 // according to [temp.arg.type]p3: 14276 // If a declaration acquires a function type through a 14277 // type dependent on a template-parameter and this causes 14278 // a declaration that does not use the syntactic form of a 14279 // function declarator to have a function type, the program 14280 // is ill-formed. 14281 if (!TInfo->getType()->isFunctionType()) { 14282 Diag(Loc, diag::err_unexpected_friend); 14283 14284 // It might be worthwhile to try to recover by creating an 14285 // appropriate declaration. 14286 return nullptr; 14287 } 14288 14289 // C++ [namespace.memdef]p3 14290 // - If a friend declaration in a non-local class first declares a 14291 // class or function, the friend class or function is a member 14292 // of the innermost enclosing namespace. 14293 // - The name of the friend is not found by simple name lookup 14294 // until a matching declaration is provided in that namespace 14295 // scope (either before or after the class declaration granting 14296 // friendship). 14297 // - If a friend function is called, its name may be found by the 14298 // name lookup that considers functions from namespaces and 14299 // classes associated with the types of the function arguments. 14300 // - When looking for a prior declaration of a class or a function 14301 // declared as a friend, scopes outside the innermost enclosing 14302 // namespace scope are not considered. 14303 14304 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14305 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14306 assert(NameInfo.getName()); 14307 14308 // Check for unexpanded parameter packs. 14309 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14310 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14311 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14312 return nullptr; 14313 14314 // The context we found the declaration in, or in which we should 14315 // create the declaration. 14316 DeclContext *DC; 14317 Scope *DCScope = S; 14318 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14319 ForExternalRedeclaration); 14320 14321 // There are five cases here. 14322 // - There's no scope specifier and we're in a local class. Only look 14323 // for functions declared in the immediately-enclosing block scope. 14324 // We recover from invalid scope qualifiers as if they just weren't there. 14325 FunctionDecl *FunctionContainingLocalClass = nullptr; 14326 if ((SS.isInvalid() || !SS.isSet()) && 14327 (FunctionContainingLocalClass = 14328 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14329 // C++11 [class.friend]p11: 14330 // If a friend declaration appears in a local class and the name 14331 // specified is an unqualified name, a prior declaration is 14332 // looked up without considering scopes that are outside the 14333 // innermost enclosing non-class scope. For a friend function 14334 // declaration, if there is no prior declaration, the program is 14335 // ill-formed. 14336 14337 // Find the innermost enclosing non-class scope. This is the block 14338 // scope containing the local class definition (or for a nested class, 14339 // the outer local class). 14340 DCScope = S->getFnParent(); 14341 14342 // Look up the function name in the scope. 14343 Previous.clear(LookupLocalFriendName); 14344 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14345 14346 if (!Previous.empty()) { 14347 // All possible previous declarations must have the same context: 14348 // either they were declared at block scope or they are members of 14349 // one of the enclosing local classes. 14350 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14351 } else { 14352 // This is ill-formed, but provide the context that we would have 14353 // declared the function in, if we were permitted to, for error recovery. 14354 DC = FunctionContainingLocalClass; 14355 } 14356 adjustContextForLocalExternDecl(DC); 14357 14358 // C++ [class.friend]p6: 14359 // A function can be defined in a friend declaration of a class if and 14360 // only if the class is a non-local class (9.8), the function name is 14361 // unqualified, and the function has namespace scope. 14362 if (D.isFunctionDefinition()) { 14363 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14364 } 14365 14366 // - There's no scope specifier, in which case we just go to the 14367 // appropriate scope and look for a function or function template 14368 // there as appropriate. 14369 } else if (SS.isInvalid() || !SS.isSet()) { 14370 // C++11 [namespace.memdef]p3: 14371 // If the name in a friend declaration is neither qualified nor 14372 // a template-id and the declaration is a function or an 14373 // elaborated-type-specifier, the lookup to determine whether 14374 // the entity has been previously declared shall not consider 14375 // any scopes outside the innermost enclosing namespace. 14376 bool isTemplateId = 14377 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14378 14379 // Find the appropriate context according to the above. 14380 DC = CurContext; 14381 14382 // Skip class contexts. If someone can cite chapter and verse 14383 // for this behavior, that would be nice --- it's what GCC and 14384 // EDG do, and it seems like a reasonable intent, but the spec 14385 // really only says that checks for unqualified existing 14386 // declarations should stop at the nearest enclosing namespace, 14387 // not that they should only consider the nearest enclosing 14388 // namespace. 14389 while (DC->isRecord()) 14390 DC = DC->getParent(); 14391 14392 DeclContext *LookupDC = DC; 14393 while (LookupDC->isTransparentContext()) 14394 LookupDC = LookupDC->getParent(); 14395 14396 while (true) { 14397 LookupQualifiedName(Previous, LookupDC); 14398 14399 if (!Previous.empty()) { 14400 DC = LookupDC; 14401 break; 14402 } 14403 14404 if (isTemplateId) { 14405 if (isa<TranslationUnitDecl>(LookupDC)) break; 14406 } else { 14407 if (LookupDC->isFileContext()) break; 14408 } 14409 LookupDC = LookupDC->getParent(); 14410 } 14411 14412 DCScope = getScopeForDeclContext(S, DC); 14413 14414 // - There's a non-dependent scope specifier, in which case we 14415 // compute it and do a previous lookup there for a function 14416 // or function template. 14417 } else if (!SS.getScopeRep()->isDependent()) { 14418 DC = computeDeclContext(SS); 14419 if (!DC) return nullptr; 14420 14421 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14422 14423 LookupQualifiedName(Previous, DC); 14424 14425 // C++ [class.friend]p1: A friend of a class is a function or 14426 // class that is not a member of the class . . . 14427 if (DC->Equals(CurContext)) 14428 Diag(DS.getFriendSpecLoc(), 14429 getLangOpts().CPlusPlus11 ? 14430 diag::warn_cxx98_compat_friend_is_member : 14431 diag::err_friend_is_member); 14432 14433 if (D.isFunctionDefinition()) { 14434 // C++ [class.friend]p6: 14435 // A function can be defined in a friend declaration of a class if and 14436 // only if the class is a non-local class (9.8), the function name is 14437 // unqualified, and the function has namespace scope. 14438 // 14439 // FIXME: We should only do this if the scope specifier names the 14440 // innermost enclosing namespace; otherwise the fixit changes the 14441 // meaning of the code. 14442 SemaDiagnosticBuilder DB 14443 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14444 14445 DB << SS.getScopeRep(); 14446 if (DC->isFileContext()) 14447 DB << FixItHint::CreateRemoval(SS.getRange()); 14448 SS.clear(); 14449 } 14450 14451 // - There's a scope specifier that does not match any template 14452 // parameter lists, in which case we use some arbitrary context, 14453 // create a method or method template, and wait for instantiation. 14454 // - There's a scope specifier that does match some template 14455 // parameter lists, which we don't handle right now. 14456 } else { 14457 if (D.isFunctionDefinition()) { 14458 // C++ [class.friend]p6: 14459 // A function can be defined in a friend declaration of a class if and 14460 // only if the class is a non-local class (9.8), the function name is 14461 // unqualified, and the function has namespace scope. 14462 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14463 << SS.getScopeRep(); 14464 } 14465 14466 DC = CurContext; 14467 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14468 } 14469 14470 if (!DC->isRecord()) { 14471 int DiagArg = -1; 14472 switch (D.getName().getKind()) { 14473 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14474 case UnqualifiedIdKind::IK_ConstructorName: 14475 DiagArg = 0; 14476 break; 14477 case UnqualifiedIdKind::IK_DestructorName: 14478 DiagArg = 1; 14479 break; 14480 case UnqualifiedIdKind::IK_ConversionFunctionId: 14481 DiagArg = 2; 14482 break; 14483 case UnqualifiedIdKind::IK_DeductionGuideName: 14484 DiagArg = 3; 14485 break; 14486 case UnqualifiedIdKind::IK_Identifier: 14487 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14488 case UnqualifiedIdKind::IK_LiteralOperatorId: 14489 case UnqualifiedIdKind::IK_OperatorFunctionId: 14490 case UnqualifiedIdKind::IK_TemplateId: 14491 break; 14492 } 14493 // This implies that it has to be an operator or function. 14494 if (DiagArg >= 0) { 14495 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14496 return nullptr; 14497 } 14498 } 14499 14500 // FIXME: This is an egregious hack to cope with cases where the scope stack 14501 // does not contain the declaration context, i.e., in an out-of-line 14502 // definition of a class. 14503 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14504 if (!DCScope) { 14505 FakeDCScope.setEntity(DC); 14506 DCScope = &FakeDCScope; 14507 } 14508 14509 bool AddToScope = true; 14510 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14511 TemplateParams, AddToScope); 14512 if (!ND) return nullptr; 14513 14514 assert(ND->getLexicalDeclContext() == CurContext); 14515 14516 // If we performed typo correction, we might have added a scope specifier 14517 // and changed the decl context. 14518 DC = ND->getDeclContext(); 14519 14520 // Add the function declaration to the appropriate lookup tables, 14521 // adjusting the redeclarations list as necessary. We don't 14522 // want to do this yet if the friending class is dependent. 14523 // 14524 // Also update the scope-based lookup if the target context's 14525 // lookup context is in lexical scope. 14526 if (!CurContext->isDependentContext()) { 14527 DC = DC->getRedeclContext(); 14528 DC->makeDeclVisibleInContext(ND); 14529 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14530 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14531 } 14532 14533 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14534 D.getIdentifierLoc(), ND, 14535 DS.getFriendSpecLoc()); 14536 FrD->setAccess(AS_public); 14537 CurContext->addDecl(FrD); 14538 14539 if (ND->isInvalidDecl()) { 14540 FrD->setInvalidDecl(); 14541 } else { 14542 if (DC->isRecord()) CheckFriendAccess(ND); 14543 14544 FunctionDecl *FD; 14545 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14546 FD = FTD->getTemplatedDecl(); 14547 else 14548 FD = cast<FunctionDecl>(ND); 14549 14550 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14551 // default argument expression, that declaration shall be a definition 14552 // and shall be the only declaration of the function or function 14553 // template in the translation unit. 14554 if (functionDeclHasDefaultArgument(FD)) { 14555 // We can't look at FD->getPreviousDecl() because it may not have been set 14556 // if we're in a dependent context. If the function is known to be a 14557 // redeclaration, we will have narrowed Previous down to the right decl. 14558 if (D.isRedeclaration()) { 14559 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14560 Diag(Previous.getRepresentativeDecl()->getLocation(), 14561 diag::note_previous_declaration); 14562 } else if (!D.isFunctionDefinition()) 14563 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14564 } 14565 14566 // Mark templated-scope function declarations as unsupported. 14567 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14568 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14569 << SS.getScopeRep() << SS.getRange() 14570 << cast<CXXRecordDecl>(CurContext); 14571 FrD->setUnsupportedFriend(true); 14572 } 14573 } 14574 14575 return ND; 14576 } 14577 14578 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14579 AdjustDeclIfTemplate(Dcl); 14580 14581 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14582 if (!Fn) { 14583 Diag(DelLoc, diag::err_deleted_non_function); 14584 return; 14585 } 14586 14587 // Deleted function does not have a body. 14588 Fn->setWillHaveBody(false); 14589 14590 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14591 // Don't consider the implicit declaration we generate for explicit 14592 // specializations. FIXME: Do not generate these implicit declarations. 14593 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14594 Prev->getPreviousDecl()) && 14595 !Prev->isDefined()) { 14596 Diag(DelLoc, diag::err_deleted_decl_not_first); 14597 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14598 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14599 : diag::note_previous_declaration); 14600 } 14601 // If the declaration wasn't the first, we delete the function anyway for 14602 // recovery. 14603 Fn = Fn->getCanonicalDecl(); 14604 } 14605 14606 // dllimport/dllexport cannot be deleted. 14607 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14608 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14609 Fn->setInvalidDecl(); 14610 } 14611 14612 if (Fn->isDeleted()) 14613 return; 14614 14615 // See if we're deleting a function which is already known to override a 14616 // non-deleted virtual function. 14617 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14618 bool IssuedDiagnostic = false; 14619 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14620 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14621 if (!IssuedDiagnostic) { 14622 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14623 IssuedDiagnostic = true; 14624 } 14625 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14626 } 14627 } 14628 // If this function was implicitly deleted because it was defaulted, 14629 // explain why it was deleted. 14630 if (IssuedDiagnostic && MD->isDefaulted()) 14631 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14632 /*Diagnose*/true); 14633 } 14634 14635 // C++11 [basic.start.main]p3: 14636 // A program that defines main as deleted [...] is ill-formed. 14637 if (Fn->isMain()) 14638 Diag(DelLoc, diag::err_deleted_main); 14639 14640 // C++11 [dcl.fct.def.delete]p4: 14641 // A deleted function is implicitly inline. 14642 Fn->setImplicitlyInline(); 14643 Fn->setDeletedAsWritten(); 14644 } 14645 14646 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14647 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14648 14649 if (MD) { 14650 if (MD->getParent()->isDependentType()) { 14651 MD->setDefaulted(); 14652 MD->setExplicitlyDefaulted(); 14653 return; 14654 } 14655 14656 CXXSpecialMember Member = getSpecialMember(MD); 14657 if (Member == CXXInvalid) { 14658 if (!MD->isInvalidDecl()) 14659 Diag(DefaultLoc, diag::err_default_special_members); 14660 return; 14661 } 14662 14663 MD->setDefaulted(); 14664 MD->setExplicitlyDefaulted(); 14665 14666 // Unset that we will have a body for this function. We might not, 14667 // if it turns out to be trivial, and we don't need this marking now 14668 // that we've marked it as defaulted. 14669 MD->setWillHaveBody(false); 14670 14671 // If this definition appears within the record, do the checking when 14672 // the record is complete. 14673 const FunctionDecl *Primary = MD; 14674 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14675 // Ask the template instantiation pattern that actually had the 14676 // '= default' on it. 14677 Primary = Pattern; 14678 14679 // If the method was defaulted on its first declaration, we will have 14680 // already performed the checking in CheckCompletedCXXClass. Such a 14681 // declaration doesn't trigger an implicit definition. 14682 if (Primary->getCanonicalDecl()->isDefaulted()) 14683 return; 14684 14685 CheckExplicitlyDefaultedSpecialMember(MD); 14686 14687 if (!MD->isInvalidDecl()) 14688 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14689 } else { 14690 Diag(DefaultLoc, diag::err_default_special_members); 14691 } 14692 } 14693 14694 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14695 for (Stmt *SubStmt : S->children()) { 14696 if (!SubStmt) 14697 continue; 14698 if (isa<ReturnStmt>(SubStmt)) 14699 Self.Diag(SubStmt->getBeginLoc(), 14700 diag::err_return_in_constructor_handler); 14701 if (!isa<Expr>(SubStmt)) 14702 SearchForReturnInStmt(Self, SubStmt); 14703 } 14704 } 14705 14706 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14707 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14708 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14709 SearchForReturnInStmt(*this, Handler); 14710 } 14711 } 14712 14713 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14714 const CXXMethodDecl *Old) { 14715 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14716 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14717 14718 if (OldFT->hasExtParameterInfos()) { 14719 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14720 // A parameter of the overriding method should be annotated with noescape 14721 // if the corresponding parameter of the overridden method is annotated. 14722 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14723 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14724 Diag(New->getParamDecl(I)->getLocation(), 14725 diag::warn_overriding_method_missing_noescape); 14726 Diag(Old->getParamDecl(I)->getLocation(), 14727 diag::note_overridden_marked_noescape); 14728 } 14729 } 14730 14731 // Virtual overrides must have the same code_seg. 14732 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 14733 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 14734 if ((NewCSA || OldCSA) && 14735 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 14736 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 14737 Diag(Old->getLocation(), diag::note_previous_declaration); 14738 return true; 14739 } 14740 14741 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14742 14743 // If the calling conventions match, everything is fine 14744 if (NewCC == OldCC) 14745 return false; 14746 14747 // If the calling conventions mismatch because the new function is static, 14748 // suppress the calling convention mismatch error; the error about static 14749 // function override (err_static_overrides_virtual from 14750 // Sema::CheckFunctionDeclaration) is more clear. 14751 if (New->getStorageClass() == SC_Static) 14752 return false; 14753 14754 Diag(New->getLocation(), 14755 diag::err_conflicting_overriding_cc_attributes) 14756 << New->getDeclName() << New->getType() << Old->getType(); 14757 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14758 return true; 14759 } 14760 14761 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14762 const CXXMethodDecl *Old) { 14763 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14764 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14765 14766 if (Context.hasSameType(NewTy, OldTy) || 14767 NewTy->isDependentType() || OldTy->isDependentType()) 14768 return false; 14769 14770 // Check if the return types are covariant 14771 QualType NewClassTy, OldClassTy; 14772 14773 /// Both types must be pointers or references to classes. 14774 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14775 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14776 NewClassTy = NewPT->getPointeeType(); 14777 OldClassTy = OldPT->getPointeeType(); 14778 } 14779 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14780 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14781 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14782 NewClassTy = NewRT->getPointeeType(); 14783 OldClassTy = OldRT->getPointeeType(); 14784 } 14785 } 14786 } 14787 14788 // The return types aren't either both pointers or references to a class type. 14789 if (NewClassTy.isNull()) { 14790 Diag(New->getLocation(), 14791 diag::err_different_return_type_for_overriding_virtual_function) 14792 << New->getDeclName() << NewTy << OldTy 14793 << New->getReturnTypeSourceRange(); 14794 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14795 << Old->getReturnTypeSourceRange(); 14796 14797 return true; 14798 } 14799 14800 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14801 // C++14 [class.virtual]p8: 14802 // If the class type in the covariant return type of D::f differs from 14803 // that of B::f, the class type in the return type of D::f shall be 14804 // complete at the point of declaration of D::f or shall be the class 14805 // type D. 14806 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14807 if (!RT->isBeingDefined() && 14808 RequireCompleteType(New->getLocation(), NewClassTy, 14809 diag::err_covariant_return_incomplete, 14810 New->getDeclName())) 14811 return true; 14812 } 14813 14814 // Check if the new class derives from the old class. 14815 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14816 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14817 << New->getDeclName() << NewTy << OldTy 14818 << New->getReturnTypeSourceRange(); 14819 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14820 << Old->getReturnTypeSourceRange(); 14821 return true; 14822 } 14823 14824 // Check if we the conversion from derived to base is valid. 14825 if (CheckDerivedToBaseConversion( 14826 NewClassTy, OldClassTy, 14827 diag::err_covariant_return_inaccessible_base, 14828 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14829 New->getLocation(), New->getReturnTypeSourceRange(), 14830 New->getDeclName(), nullptr)) { 14831 // FIXME: this note won't trigger for delayed access control 14832 // diagnostics, and it's impossible to get an undelayed error 14833 // here from access control during the original parse because 14834 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14835 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14836 << Old->getReturnTypeSourceRange(); 14837 return true; 14838 } 14839 } 14840 14841 // The qualifiers of the return types must be the same. 14842 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14843 Diag(New->getLocation(), 14844 diag::err_covariant_return_type_different_qualifications) 14845 << New->getDeclName() << NewTy << OldTy 14846 << New->getReturnTypeSourceRange(); 14847 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14848 << Old->getReturnTypeSourceRange(); 14849 return true; 14850 } 14851 14852 14853 // The new class type must have the same or less qualifiers as the old type. 14854 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14855 Diag(New->getLocation(), 14856 diag::err_covariant_return_type_class_type_more_qualified) 14857 << New->getDeclName() << NewTy << OldTy 14858 << New->getReturnTypeSourceRange(); 14859 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14860 << Old->getReturnTypeSourceRange(); 14861 return true; 14862 } 14863 14864 return false; 14865 } 14866 14867 /// Mark the given method pure. 14868 /// 14869 /// \param Method the method to be marked pure. 14870 /// 14871 /// \param InitRange the source range that covers the "0" initializer. 14872 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14873 SourceLocation EndLoc = InitRange.getEnd(); 14874 if (EndLoc.isValid()) 14875 Method->setRangeEnd(EndLoc); 14876 14877 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14878 Method->setPure(); 14879 return false; 14880 } 14881 14882 if (!Method->isInvalidDecl()) 14883 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14884 << Method->getDeclName() << InitRange; 14885 return true; 14886 } 14887 14888 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14889 if (D->getFriendObjectKind()) 14890 Diag(D->getLocation(), diag::err_pure_friend); 14891 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14892 CheckPureMethod(M, ZeroLoc); 14893 else 14894 Diag(D->getLocation(), diag::err_illegal_initializer); 14895 } 14896 14897 /// Determine whether the given declaration is a global variable or 14898 /// static data member. 14899 static bool isNonlocalVariable(const Decl *D) { 14900 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14901 return Var->hasGlobalStorage(); 14902 14903 return false; 14904 } 14905 14906 /// Invoked when we are about to parse an initializer for the declaration 14907 /// 'Dcl'. 14908 /// 14909 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14910 /// static data member of class X, names should be looked up in the scope of 14911 /// class X. If the declaration had a scope specifier, a scope will have 14912 /// been created and passed in for this purpose. Otherwise, S will be null. 14913 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14914 // If there is no declaration, there was an error parsing it. 14915 if (!D || D->isInvalidDecl()) 14916 return; 14917 14918 // We will always have a nested name specifier here, but this declaration 14919 // might not be out of line if the specifier names the current namespace: 14920 // extern int n; 14921 // int ::n = 0; 14922 if (S && D->isOutOfLine()) 14923 EnterDeclaratorContext(S, D->getDeclContext()); 14924 14925 // If we are parsing the initializer for a static data member, push a 14926 // new expression evaluation context that is associated with this static 14927 // data member. 14928 if (isNonlocalVariable(D)) 14929 PushExpressionEvaluationContext( 14930 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14931 } 14932 14933 /// Invoked after we are finished parsing an initializer for the declaration D. 14934 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14935 // If there is no declaration, there was an error parsing it. 14936 if (!D || D->isInvalidDecl()) 14937 return; 14938 14939 if (isNonlocalVariable(D)) 14940 PopExpressionEvaluationContext(); 14941 14942 if (S && D->isOutOfLine()) 14943 ExitDeclaratorContext(S); 14944 } 14945 14946 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14947 /// C++ if/switch/while/for statement. 14948 /// e.g: "if (int x = f()) {...}" 14949 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14950 // C++ 6.4p2: 14951 // The declarator shall not specify a function or an array. 14952 // The type-specifier-seq shall not contain typedef and shall not declare a 14953 // new class or enumeration. 14954 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14955 "Parser allowed 'typedef' as storage class of condition decl."); 14956 14957 Decl *Dcl = ActOnDeclarator(S, D); 14958 if (!Dcl) 14959 return true; 14960 14961 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14962 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14963 << D.getSourceRange(); 14964 return true; 14965 } 14966 14967 return Dcl; 14968 } 14969 14970 void Sema::LoadExternalVTableUses() { 14971 if (!ExternalSource) 14972 return; 14973 14974 SmallVector<ExternalVTableUse, 4> VTables; 14975 ExternalSource->ReadUsedVTables(VTables); 14976 SmallVector<VTableUse, 4> NewUses; 14977 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14978 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14979 = VTablesUsed.find(VTables[I].Record); 14980 // Even if a definition wasn't required before, it may be required now. 14981 if (Pos != VTablesUsed.end()) { 14982 if (!Pos->second && VTables[I].DefinitionRequired) 14983 Pos->second = true; 14984 continue; 14985 } 14986 14987 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14988 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14989 } 14990 14991 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14992 } 14993 14994 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14995 bool DefinitionRequired) { 14996 // Ignore any vtable uses in unevaluated operands or for classes that do 14997 // not have a vtable. 14998 if (!Class->isDynamicClass() || Class->isDependentContext() || 14999 CurContext->isDependentContext() || isUnevaluatedContext()) 15000 return; 15001 // Do not mark as used if compiling for the device outside of the target 15002 // region. 15003 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 15004 !isInOpenMPDeclareTargetContext() && 15005 !isInOpenMPTargetExecutionDirective()) { 15006 if (!DefinitionRequired) 15007 MarkVirtualMembersReferenced(Loc, Class); 15008 return; 15009 } 15010 15011 // Try to insert this class into the map. 15012 LoadExternalVTableUses(); 15013 Class = Class->getCanonicalDecl(); 15014 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 15015 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 15016 if (!Pos.second) { 15017 // If we already had an entry, check to see if we are promoting this vtable 15018 // to require a definition. If so, we need to reappend to the VTableUses 15019 // list, since we may have already processed the first entry. 15020 if (DefinitionRequired && !Pos.first->second) { 15021 Pos.first->second = true; 15022 } else { 15023 // Otherwise, we can early exit. 15024 return; 15025 } 15026 } else { 15027 // The Microsoft ABI requires that we perform the destructor body 15028 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 15029 // the deleting destructor is emitted with the vtable, not with the 15030 // destructor definition as in the Itanium ABI. 15031 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15032 CXXDestructorDecl *DD = Class->getDestructor(); 15033 if (DD && DD->isVirtual() && !DD->isDeleted()) { 15034 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 15035 // If this is an out-of-line declaration, marking it referenced will 15036 // not do anything. Manually call CheckDestructor to look up operator 15037 // delete(). 15038 ContextRAII SavedContext(*this, DD); 15039 CheckDestructor(DD); 15040 } else { 15041 MarkFunctionReferenced(Loc, Class->getDestructor()); 15042 } 15043 } 15044 } 15045 } 15046 15047 // Local classes need to have their virtual members marked 15048 // immediately. For all other classes, we mark their virtual members 15049 // at the end of the translation unit. 15050 if (Class->isLocalClass()) 15051 MarkVirtualMembersReferenced(Loc, Class); 15052 else 15053 VTableUses.push_back(std::make_pair(Class, Loc)); 15054 } 15055 15056 bool Sema::DefineUsedVTables() { 15057 LoadExternalVTableUses(); 15058 if (VTableUses.empty()) 15059 return false; 15060 15061 // Note: The VTableUses vector could grow as a result of marking 15062 // the members of a class as "used", so we check the size each 15063 // time through the loop and prefer indices (which are stable) to 15064 // iterators (which are not). 15065 bool DefinedAnything = false; 15066 for (unsigned I = 0; I != VTableUses.size(); ++I) { 15067 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 15068 if (!Class) 15069 continue; 15070 TemplateSpecializationKind ClassTSK = 15071 Class->getTemplateSpecializationKind(); 15072 15073 SourceLocation Loc = VTableUses[I].second; 15074 15075 bool DefineVTable = true; 15076 15077 // If this class has a key function, but that key function is 15078 // defined in another translation unit, we don't need to emit the 15079 // vtable even though we're using it. 15080 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 15081 if (KeyFunction && !KeyFunction->hasBody()) { 15082 // The key function is in another translation unit. 15083 DefineVTable = false; 15084 TemplateSpecializationKind TSK = 15085 KeyFunction->getTemplateSpecializationKind(); 15086 assert(TSK != TSK_ExplicitInstantiationDefinition && 15087 TSK != TSK_ImplicitInstantiation && 15088 "Instantiations don't have key functions"); 15089 (void)TSK; 15090 } else if (!KeyFunction) { 15091 // If we have a class with no key function that is the subject 15092 // of an explicit instantiation declaration, suppress the 15093 // vtable; it will live with the explicit instantiation 15094 // definition. 15095 bool IsExplicitInstantiationDeclaration = 15096 ClassTSK == TSK_ExplicitInstantiationDeclaration; 15097 for (auto R : Class->redecls()) { 15098 TemplateSpecializationKind TSK 15099 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 15100 if (TSK == TSK_ExplicitInstantiationDeclaration) 15101 IsExplicitInstantiationDeclaration = true; 15102 else if (TSK == TSK_ExplicitInstantiationDefinition) { 15103 IsExplicitInstantiationDeclaration = false; 15104 break; 15105 } 15106 } 15107 15108 if (IsExplicitInstantiationDeclaration) 15109 DefineVTable = false; 15110 } 15111 15112 // The exception specifications for all virtual members may be needed even 15113 // if we are not providing an authoritative form of the vtable in this TU. 15114 // We may choose to emit it available_externally anyway. 15115 if (!DefineVTable) { 15116 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 15117 continue; 15118 } 15119 15120 // Mark all of the virtual members of this class as referenced, so 15121 // that we can build a vtable. Then, tell the AST consumer that a 15122 // vtable for this class is required. 15123 DefinedAnything = true; 15124 MarkVirtualMembersReferenced(Loc, Class); 15125 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 15126 if (VTablesUsed[Canonical]) 15127 Consumer.HandleVTable(Class); 15128 15129 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 15130 // no key function or the key function is inlined. Don't warn in C++ ABIs 15131 // that lack key functions, since the user won't be able to make one. 15132 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 15133 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 15134 const FunctionDecl *KeyFunctionDef = nullptr; 15135 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 15136 KeyFunctionDef->isInlined())) { 15137 Diag(Class->getLocation(), 15138 ClassTSK == TSK_ExplicitInstantiationDefinition 15139 ? diag::warn_weak_template_vtable 15140 : diag::warn_weak_vtable) 15141 << Class; 15142 } 15143 } 15144 } 15145 VTableUses.clear(); 15146 15147 return DefinedAnything; 15148 } 15149 15150 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 15151 const CXXRecordDecl *RD) { 15152 for (const auto *I : RD->methods()) 15153 if (I->isVirtual() && !I->isPure()) 15154 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 15155 } 15156 15157 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 15158 const CXXRecordDecl *RD) { 15159 // Mark all functions which will appear in RD's vtable as used. 15160 CXXFinalOverriderMap FinalOverriders; 15161 RD->getFinalOverriders(FinalOverriders); 15162 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 15163 E = FinalOverriders.end(); 15164 I != E; ++I) { 15165 for (OverridingMethods::const_iterator OI = I->second.begin(), 15166 OE = I->second.end(); 15167 OI != OE; ++OI) { 15168 assert(OI->second.size() > 0 && "no final overrider"); 15169 CXXMethodDecl *Overrider = OI->second.front().Method; 15170 15171 // C++ [basic.def.odr]p2: 15172 // [...] A virtual member function is used if it is not pure. [...] 15173 if (!Overrider->isPure()) 15174 MarkFunctionReferenced(Loc, Overrider); 15175 } 15176 } 15177 15178 // Only classes that have virtual bases need a VTT. 15179 if (RD->getNumVBases() == 0) 15180 return; 15181 15182 for (const auto &I : RD->bases()) { 15183 const CXXRecordDecl *Base = 15184 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15185 if (Base->getNumVBases() == 0) 15186 continue; 15187 MarkVirtualMembersReferenced(Loc, Base); 15188 } 15189 } 15190 15191 /// SetIvarInitializers - This routine builds initialization ASTs for the 15192 /// Objective-C implementation whose ivars need be initialized. 15193 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15194 if (!getLangOpts().CPlusPlus) 15195 return; 15196 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15197 SmallVector<ObjCIvarDecl*, 8> ivars; 15198 CollectIvarsToConstructOrDestruct(OID, ivars); 15199 if (ivars.empty()) 15200 return; 15201 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15202 for (unsigned i = 0; i < ivars.size(); i++) { 15203 FieldDecl *Field = ivars[i]; 15204 if (Field->isInvalidDecl()) 15205 continue; 15206 15207 CXXCtorInitializer *Member; 15208 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15209 InitializationKind InitKind = 15210 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15211 15212 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15213 ExprResult MemberInit = 15214 InitSeq.Perform(*this, InitEntity, InitKind, None); 15215 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15216 // Note, MemberInit could actually come back empty if no initialization 15217 // is required (e.g., because it would call a trivial default constructor) 15218 if (!MemberInit.get() || MemberInit.isInvalid()) 15219 continue; 15220 15221 Member = 15222 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15223 SourceLocation(), 15224 MemberInit.getAs<Expr>(), 15225 SourceLocation()); 15226 AllToInit.push_back(Member); 15227 15228 // Be sure that the destructor is accessible and is marked as referenced. 15229 if (const RecordType *RecordTy = 15230 Context.getBaseElementType(Field->getType()) 15231 ->getAs<RecordType>()) { 15232 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15233 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15234 MarkFunctionReferenced(Field->getLocation(), Destructor); 15235 CheckDestructorAccess(Field->getLocation(), Destructor, 15236 PDiag(diag::err_access_dtor_ivar) 15237 << Context.getBaseElementType(Field->getType())); 15238 } 15239 } 15240 } 15241 ObjCImplementation->setIvarInitializers(Context, 15242 AllToInit.data(), AllToInit.size()); 15243 } 15244 } 15245 15246 static 15247 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15248 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15249 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15250 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15251 Sema &S) { 15252 if (Ctor->isInvalidDecl()) 15253 return; 15254 15255 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15256 15257 // Target may not be determinable yet, for instance if this is a dependent 15258 // call in an uninstantiated template. 15259 if (Target) { 15260 const FunctionDecl *FNTarget = nullptr; 15261 (void)Target->hasBody(FNTarget); 15262 Target = const_cast<CXXConstructorDecl*>( 15263 cast_or_null<CXXConstructorDecl>(FNTarget)); 15264 } 15265 15266 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15267 // Avoid dereferencing a null pointer here. 15268 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15269 15270 if (!Current.insert(Canonical).second) 15271 return; 15272 15273 // We know that beyond here, we aren't chaining into a cycle. 15274 if (!Target || !Target->isDelegatingConstructor() || 15275 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15276 Valid.insert(Current.begin(), Current.end()); 15277 Current.clear(); 15278 // We've hit a cycle. 15279 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15280 Current.count(TCanonical)) { 15281 // If we haven't diagnosed this cycle yet, do so now. 15282 if (!Invalid.count(TCanonical)) { 15283 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15284 diag::warn_delegating_ctor_cycle) 15285 << Ctor; 15286 15287 // Don't add a note for a function delegating directly to itself. 15288 if (TCanonical != Canonical) 15289 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15290 15291 CXXConstructorDecl *C = Target; 15292 while (C->getCanonicalDecl() != Canonical) { 15293 const FunctionDecl *FNTarget = nullptr; 15294 (void)C->getTargetConstructor()->hasBody(FNTarget); 15295 assert(FNTarget && "Ctor cycle through bodiless function"); 15296 15297 C = const_cast<CXXConstructorDecl*>( 15298 cast<CXXConstructorDecl>(FNTarget)); 15299 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15300 } 15301 } 15302 15303 Invalid.insert(Current.begin(), Current.end()); 15304 Current.clear(); 15305 } else { 15306 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15307 } 15308 } 15309 15310 15311 void Sema::CheckDelegatingCtorCycles() { 15312 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15313 15314 for (DelegatingCtorDeclsType::iterator 15315 I = DelegatingCtorDecls.begin(ExternalSource), 15316 E = DelegatingCtorDecls.end(); 15317 I != E; ++I) 15318 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15319 15320 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15321 (*CI)->setInvalidDecl(); 15322 } 15323 15324 namespace { 15325 /// AST visitor that finds references to the 'this' expression. 15326 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15327 Sema &S; 15328 15329 public: 15330 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15331 15332 bool VisitCXXThisExpr(CXXThisExpr *E) { 15333 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15334 << E->isImplicit(); 15335 return false; 15336 } 15337 }; 15338 } 15339 15340 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15341 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15342 if (!TSInfo) 15343 return false; 15344 15345 TypeLoc TL = TSInfo->getTypeLoc(); 15346 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15347 if (!ProtoTL) 15348 return false; 15349 15350 // C++11 [expr.prim.general]p3: 15351 // [The expression this] shall not appear before the optional 15352 // cv-qualifier-seq and it shall not appear within the declaration of a 15353 // static member function (although its type and value category are defined 15354 // within a static member function as they are within a non-static member 15355 // function). [ Note: this is because declaration matching does not occur 15356 // until the complete declarator is known. - end note ] 15357 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15358 FindCXXThisExpr Finder(*this); 15359 15360 // If the return type came after the cv-qualifier-seq, check it now. 15361 if (Proto->hasTrailingReturn() && 15362 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15363 return true; 15364 15365 // Check the exception specification. 15366 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15367 return true; 15368 15369 return checkThisInStaticMemberFunctionAttributes(Method); 15370 } 15371 15372 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15373 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15374 if (!TSInfo) 15375 return false; 15376 15377 TypeLoc TL = TSInfo->getTypeLoc(); 15378 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15379 if (!ProtoTL) 15380 return false; 15381 15382 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15383 FindCXXThisExpr Finder(*this); 15384 15385 switch (Proto->getExceptionSpecType()) { 15386 case EST_Unparsed: 15387 case EST_Uninstantiated: 15388 case EST_Unevaluated: 15389 case EST_BasicNoexcept: 15390 case EST_DynamicNone: 15391 case EST_MSAny: 15392 case EST_None: 15393 break; 15394 15395 case EST_DependentNoexcept: 15396 case EST_NoexceptFalse: 15397 case EST_NoexceptTrue: 15398 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15399 return true; 15400 LLVM_FALLTHROUGH; 15401 15402 case EST_Dynamic: 15403 for (const auto &E : Proto->exceptions()) { 15404 if (!Finder.TraverseType(E)) 15405 return true; 15406 } 15407 break; 15408 } 15409 15410 return false; 15411 } 15412 15413 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15414 FindCXXThisExpr Finder(*this); 15415 15416 // Check attributes. 15417 for (const auto *A : Method->attrs()) { 15418 // FIXME: This should be emitted by tblgen. 15419 Expr *Arg = nullptr; 15420 ArrayRef<Expr *> Args; 15421 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15422 Arg = G->getArg(); 15423 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15424 Arg = G->getArg(); 15425 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15426 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15427 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15428 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15429 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15430 Arg = ETLF->getSuccessValue(); 15431 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15432 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15433 Arg = STLF->getSuccessValue(); 15434 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15435 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15436 Arg = LR->getArg(); 15437 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15438 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15439 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15440 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15441 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15442 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15443 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15444 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15445 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15446 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15447 15448 if (Arg && !Finder.TraverseStmt(Arg)) 15449 return true; 15450 15451 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15452 if (!Finder.TraverseStmt(Args[I])) 15453 return true; 15454 } 15455 } 15456 15457 return false; 15458 } 15459 15460 void Sema::checkExceptionSpecification( 15461 bool IsTopLevel, ExceptionSpecificationType EST, 15462 ArrayRef<ParsedType> DynamicExceptions, 15463 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15464 SmallVectorImpl<QualType> &Exceptions, 15465 FunctionProtoType::ExceptionSpecInfo &ESI) { 15466 Exceptions.clear(); 15467 ESI.Type = EST; 15468 if (EST == EST_Dynamic) { 15469 Exceptions.reserve(DynamicExceptions.size()); 15470 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15471 // FIXME: Preserve type source info. 15472 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15473 15474 if (IsTopLevel) { 15475 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15476 collectUnexpandedParameterPacks(ET, Unexpanded); 15477 if (!Unexpanded.empty()) { 15478 DiagnoseUnexpandedParameterPacks( 15479 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15480 Unexpanded); 15481 continue; 15482 } 15483 } 15484 15485 // Check that the type is valid for an exception spec, and 15486 // drop it if not. 15487 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15488 Exceptions.push_back(ET); 15489 } 15490 ESI.Exceptions = Exceptions; 15491 return; 15492 } 15493 15494 if (isComputedNoexcept(EST)) { 15495 assert((NoexceptExpr->isTypeDependent() || 15496 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15497 Context.BoolTy) && 15498 "Parser should have made sure that the expression is boolean"); 15499 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15500 ESI.Type = EST_BasicNoexcept; 15501 return; 15502 } 15503 15504 ESI.NoexceptExpr = NoexceptExpr; 15505 return; 15506 } 15507 } 15508 15509 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15510 ExceptionSpecificationType EST, 15511 SourceRange SpecificationRange, 15512 ArrayRef<ParsedType> DynamicExceptions, 15513 ArrayRef<SourceRange> DynamicExceptionRanges, 15514 Expr *NoexceptExpr) { 15515 if (!MethodD) 15516 return; 15517 15518 // Dig out the method we're referring to. 15519 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15520 MethodD = FunTmpl->getTemplatedDecl(); 15521 15522 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15523 if (!Method) 15524 return; 15525 15526 // Check the exception specification. 15527 llvm::SmallVector<QualType, 4> Exceptions; 15528 FunctionProtoType::ExceptionSpecInfo ESI; 15529 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15530 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15531 ESI); 15532 15533 // Update the exception specification on the function type. 15534 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15535 15536 if (Method->isStatic()) 15537 checkThisInStaticMemberFunctionExceptionSpec(Method); 15538 15539 if (Method->isVirtual()) { 15540 // Check overrides, which we previously had to delay. 15541 for (const CXXMethodDecl *O : Method->overridden_methods()) 15542 CheckOverridingFunctionExceptionSpec(Method, O); 15543 } 15544 } 15545 15546 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15547 /// 15548 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15549 SourceLocation DeclStart, Declarator &D, 15550 Expr *BitWidth, 15551 InClassInitStyle InitStyle, 15552 AccessSpecifier AS, 15553 const ParsedAttr &MSPropertyAttr) { 15554 IdentifierInfo *II = D.getIdentifier(); 15555 if (!II) { 15556 Diag(DeclStart, diag::err_anonymous_property); 15557 return nullptr; 15558 } 15559 SourceLocation Loc = D.getIdentifierLoc(); 15560 15561 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15562 QualType T = TInfo->getType(); 15563 if (getLangOpts().CPlusPlus) { 15564 CheckExtraCXXDefaultArguments(D); 15565 15566 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15567 UPPC_DataMemberType)) { 15568 D.setInvalidType(); 15569 T = Context.IntTy; 15570 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15571 } 15572 } 15573 15574 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15575 15576 if (D.getDeclSpec().isInlineSpecified()) 15577 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15578 << getLangOpts().CPlusPlus17; 15579 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15580 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15581 diag::err_invalid_thread) 15582 << DeclSpec::getSpecifierName(TSCS); 15583 15584 // Check to see if this name was declared as a member previously 15585 NamedDecl *PrevDecl = nullptr; 15586 LookupResult Previous(*this, II, Loc, LookupMemberName, 15587 ForVisibleRedeclaration); 15588 LookupName(Previous, S); 15589 switch (Previous.getResultKind()) { 15590 case LookupResult::Found: 15591 case LookupResult::FoundUnresolvedValue: 15592 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15593 break; 15594 15595 case LookupResult::FoundOverloaded: 15596 PrevDecl = Previous.getRepresentativeDecl(); 15597 break; 15598 15599 case LookupResult::NotFound: 15600 case LookupResult::NotFoundInCurrentInstantiation: 15601 case LookupResult::Ambiguous: 15602 break; 15603 } 15604 15605 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15606 // Maybe we will complain about the shadowed template parameter. 15607 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15608 // Just pretend that we didn't see the previous declaration. 15609 PrevDecl = nullptr; 15610 } 15611 15612 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15613 PrevDecl = nullptr; 15614 15615 SourceLocation TSSL = D.getBeginLoc(); 15616 MSPropertyDecl *NewPD = 15617 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 15618 MSPropertyAttr.getPropertyDataGetter(), 15619 MSPropertyAttr.getPropertyDataSetter()); 15620 ProcessDeclAttributes(TUScope, NewPD, D); 15621 NewPD->setAccess(AS); 15622 15623 if (NewPD->isInvalidDecl()) 15624 Record->setInvalidDecl(); 15625 15626 if (D.getDeclSpec().isModulePrivateSpecified()) 15627 NewPD->setModulePrivate(); 15628 15629 if (NewPD->isInvalidDecl() && PrevDecl) { 15630 // Don't introduce NewFD into scope; there's already something 15631 // with the same name in the same scope. 15632 } else if (II) { 15633 PushOnScopeChains(NewPD, S); 15634 } else 15635 Record->addDecl(NewPD); 15636 15637 return NewPD; 15638 } 15639