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/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.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/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.getAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // C++11 [dcl.fct.default]p3 322 // A default argument expression [...] shall not be specified for a 323 // parameter pack. 324 if (Param->isParameterPack()) { 325 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 326 << DefaultArg->getSourceRange(); 327 return; 328 } 329 330 // Check that the default argument is well-formed 331 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 332 if (DefaultArgChecker.Visit(DefaultArg)) { 333 Param->setInvalidDecl(); 334 return; 335 } 336 337 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 338 } 339 340 /// ActOnParamUnparsedDefaultArgument - We've seen a default 341 /// argument for a function parameter, but we can't parse it yet 342 /// because we're inside a class definition. Note that this default 343 /// argument will be parsed later. 344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 345 SourceLocation EqualLoc, 346 SourceLocation ArgLoc) { 347 if (!param) 348 return; 349 350 ParmVarDecl *Param = cast<ParmVarDecl>(param); 351 Param->setUnparsedDefaultArg(); 352 UnparsedDefaultArgLocs[Param] = ArgLoc; 353 } 354 355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 356 /// the default argument for the parameter param failed. 357 void Sema::ActOnParamDefaultArgumentError(Decl *param, 358 SourceLocation EqualLoc) { 359 if (!param) 360 return; 361 362 ParmVarDecl *Param = cast<ParmVarDecl>(param); 363 Param->setInvalidDecl(); 364 UnparsedDefaultArgLocs.erase(Param); 365 Param->setDefaultArg(new(Context) 366 OpaqueValueExpr(EqualLoc, 367 Param->getType().getNonReferenceType(), 368 VK_RValue)); 369 } 370 371 /// CheckExtraCXXDefaultArguments - Check for any extra default 372 /// arguments in the declarator, which is not a function declaration 373 /// or definition and therefore is not permitted to have default 374 /// arguments. This routine should be invoked for every declarator 375 /// that is not a function declaration or definition. 376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 377 // C++ [dcl.fct.default]p3 378 // A default argument expression shall be specified only in the 379 // parameter-declaration-clause of a function declaration or in a 380 // template-parameter (14.1). It shall not be specified for a 381 // parameter pack. If it is specified in a 382 // parameter-declaration-clause, it shall not occur within a 383 // declarator or abstract-declarator of a parameter-declaration. 384 bool MightBeFunction = D.isFunctionDeclarationContext(); 385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 386 DeclaratorChunk &chunk = D.getTypeObject(i); 387 if (chunk.Kind == DeclaratorChunk::Function) { 388 if (MightBeFunction) { 389 // This is a function declaration. It can have default arguments, but 390 // keep looking in case its return type is a function type with default 391 // arguments. 392 MightBeFunction = false; 393 continue; 394 } 395 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 396 ++argIdx) { 397 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 398 if (Param->hasUnparsedDefaultArg()) { 399 CachedTokens *Toks = 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 delete Toks; 409 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 410 } else if (Param->getDefaultArg()) { 411 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 412 << Param->getDefaultArg()->getSourceRange(); 413 Param->setDefaultArg(nullptr); 414 } 415 } 416 } else if (chunk.Kind != DeclaratorChunk::Paren) { 417 MightBeFunction = false; 418 } 419 } 420 } 421 422 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 423 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 424 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 425 if (!PVD->hasDefaultArg()) 426 return false; 427 if (!PVD->hasInheritedDefaultArg()) 428 return true; 429 } 430 return false; 431 } 432 433 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 434 /// function, once we already know that they have the same 435 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 436 /// error, false otherwise. 437 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 438 Scope *S) { 439 bool Invalid = false; 440 441 // C++ [dcl.fct.default]p4: 442 // For non-template functions, default arguments can be added in 443 // later declarations of a function in the same 444 // scope. Declarations in different scopes have completely 445 // distinct sets of default arguments. That is, declarations in 446 // inner scopes do not acquire default arguments from 447 // declarations in outer scopes, and vice versa. In a given 448 // function declaration, all parameters subsequent to a 449 // parameter with a default argument shall have default 450 // arguments supplied in this or previous declarations. A 451 // default argument shall not be redefined by a later 452 // declaration (not even to the same value). 453 // 454 // C++ [dcl.fct.default]p6: 455 // Except for member functions of class templates, the default arguments 456 // in a member function definition that appears outside of the class 457 // definition are added to the set of default arguments provided by the 458 // member function declaration in the class definition. 459 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 460 ParmVarDecl *OldParam = Old->getParamDecl(p); 461 ParmVarDecl *NewParam = New->getParamDecl(p); 462 463 bool OldParamHasDfl = OldParam->hasDefaultArg(); 464 bool NewParamHasDfl = NewParam->hasDefaultArg(); 465 466 // The declaration context corresponding to the scope is the semantic 467 // parent, unless this is a local function declaration, in which case 468 // it is that surrounding function. 469 DeclContext *ScopeDC = New->isLocalExternDecl() 470 ? New->getLexicalDeclContext() 471 : New->getDeclContext(); 472 if (S && !isDeclInScope(Old, ScopeDC, S) && 473 !New->getDeclContext()->isRecord()) 474 // Ignore default parameters of old decl if they are not in 475 // the same scope and this is not an out-of-line definition of 476 // a member function. 477 OldParamHasDfl = false; 478 if (New->isLocalExternDecl() != Old->isLocalExternDecl()) 479 // If only one of these is a local function declaration, then they are 480 // declared in different scopes, even though isDeclInScope may think 481 // they're in the same scope. (If both are local, the scope check is 482 // sufficent, and if neither is local, then they are in the same scope.) 483 OldParamHasDfl = false; 484 485 if (OldParamHasDfl && NewParamHasDfl) { 486 487 unsigned DiagDefaultParamID = 488 diag::err_param_default_argument_redefinition; 489 490 // MSVC accepts that default parameters be redefined for member functions 491 // of template class. The new default parameter's value is ignored. 492 Invalid = true; 493 if (getLangOpts().MicrosoftExt) { 494 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 495 if (MD && MD->getParent()->getDescribedClassTemplate()) { 496 // Merge the old default argument into the new parameter. 497 NewParam->setHasInheritedDefaultArg(); 498 if (OldParam->hasUninstantiatedDefaultArg()) 499 NewParam->setUninstantiatedDefaultArg( 500 OldParam->getUninstantiatedDefaultArg()); 501 else 502 NewParam->setDefaultArg(OldParam->getInit()); 503 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 504 Invalid = false; 505 } 506 } 507 508 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 509 // hint here. Alternatively, we could walk the type-source information 510 // for NewParam to find the last source location in the type... but it 511 // isn't worth the effort right now. This is the kind of test case that 512 // is hard to get right: 513 // int f(int); 514 // void g(int (*fp)(int) = f); 515 // void g(int (*fp)(int) = &f); 516 Diag(NewParam->getLocation(), DiagDefaultParamID) 517 << NewParam->getDefaultArgRange(); 518 519 // Look for the function declaration where the default argument was 520 // actually written, which may be a declaration prior to Old. 521 for (auto Older = Old; OldParam->hasInheritedDefaultArg();) { 522 Older = Older->getPreviousDecl(); 523 OldParam = Older->getParamDecl(p); 524 } 525 526 Diag(OldParam->getLocation(), diag::note_previous_definition) 527 << OldParam->getDefaultArgRange(); 528 } else if (OldParamHasDfl) { 529 // Merge the old default argument into the new parameter. 530 // It's important to use getInit() here; getDefaultArg() 531 // strips off any top-level ExprWithCleanups. 532 NewParam->setHasInheritedDefaultArg(); 533 if (OldParam->hasUnparsedDefaultArg()) 534 NewParam->setUnparsedDefaultArg(); 535 else if (OldParam->hasUninstantiatedDefaultArg()) 536 NewParam->setUninstantiatedDefaultArg( 537 OldParam->getUninstantiatedDefaultArg()); 538 else 539 NewParam->setDefaultArg(OldParam->getInit()); 540 } else if (NewParamHasDfl) { 541 if (New->getDescribedFunctionTemplate()) { 542 // Paragraph 4, quoted above, only applies to non-template functions. 543 Diag(NewParam->getLocation(), 544 diag::err_param_default_argument_template_redecl) 545 << NewParam->getDefaultArgRange(); 546 Diag(Old->getLocation(), diag::note_template_prev_declaration) 547 << false; 548 } else if (New->getTemplateSpecializationKind() 549 != TSK_ImplicitInstantiation && 550 New->getTemplateSpecializationKind() != TSK_Undeclared) { 551 // C++ [temp.expr.spec]p21: 552 // Default function arguments shall not be specified in a declaration 553 // or a definition for one of the following explicit specializations: 554 // - the explicit specialization of a function template; 555 // - the explicit specialization of a member function template; 556 // - the explicit specialization of a member function of a class 557 // template where the class template specialization to which the 558 // member function specialization belongs is implicitly 559 // instantiated. 560 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 561 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 562 << New->getDeclName() 563 << NewParam->getDefaultArgRange(); 564 } else if (New->getDeclContext()->isDependentContext()) { 565 // C++ [dcl.fct.default]p6 (DR217): 566 // Default arguments for a member function of a class template shall 567 // be specified on the initial declaration of the member function 568 // within the class template. 569 // 570 // Reading the tea leaves a bit in DR217 and its reference to DR205 571 // leads me to the conclusion that one cannot add default function 572 // arguments for an out-of-line definition of a member function of a 573 // dependent type. 574 int WhichKind = 2; 575 if (CXXRecordDecl *Record 576 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 577 if (Record->getDescribedClassTemplate()) 578 WhichKind = 0; 579 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 580 WhichKind = 1; 581 else 582 WhichKind = 2; 583 } 584 585 Diag(NewParam->getLocation(), 586 diag::err_param_default_argument_member_template_redecl) 587 << WhichKind 588 << NewParam->getDefaultArgRange(); 589 } 590 } 591 } 592 593 // DR1344: If a default argument is added outside a class definition and that 594 // default argument makes the function a special member function, the program 595 // is ill-formed. This can only happen for constructors. 596 if (isa<CXXConstructorDecl>(New) && 597 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 598 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 599 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 600 if (NewSM != OldSM) { 601 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 602 assert(NewParam->hasDefaultArg()); 603 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 604 << NewParam->getDefaultArgRange() << NewSM; 605 Diag(Old->getLocation(), diag::note_previous_declaration); 606 } 607 } 608 609 const FunctionDecl *Def; 610 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 611 // template has a constexpr specifier then all its declarations shall 612 // contain the constexpr specifier. 613 if (New->isConstexpr() != Old->isConstexpr()) { 614 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 615 << New << New->isConstexpr(); 616 Diag(Old->getLocation(), diag::note_previous_declaration); 617 Invalid = true; 618 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 619 Old->isDefined(Def)) { 620 // C++11 [dcl.fcn.spec]p4: 621 // If the definition of a function appears in a translation unit before its 622 // first declaration as inline, the program is ill-formed. 623 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 624 Diag(Def->getLocation(), diag::note_previous_definition); 625 Invalid = true; 626 } 627 628 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 629 // argument expression, that declaration shall be a definition and shall be 630 // the only declaration of the function or function template in the 631 // translation unit. 632 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 633 functionDeclHasDefaultArgument(Old)) { 634 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 635 Diag(Old->getLocation(), diag::note_previous_declaration); 636 Invalid = true; 637 } 638 639 if (CheckEquivalentExceptionSpec(Old, New)) 640 Invalid = true; 641 642 return Invalid; 643 } 644 645 /// \brief Merge the exception specifications of two variable declarations. 646 /// 647 /// This is called when there's a redeclaration of a VarDecl. The function 648 /// checks if the redeclaration might have an exception specification and 649 /// validates compatibility and merges the specs if necessary. 650 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 651 // Shortcut if exceptions are disabled. 652 if (!getLangOpts().CXXExceptions) 653 return; 654 655 assert(Context.hasSameType(New->getType(), Old->getType()) && 656 "Should only be called if types are otherwise the same."); 657 658 QualType NewType = New->getType(); 659 QualType OldType = Old->getType(); 660 661 // We're only interested in pointers and references to functions, as well 662 // as pointers to member functions. 663 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 664 NewType = R->getPointeeType(); 665 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 666 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 667 NewType = P->getPointeeType(); 668 OldType = OldType->getAs<PointerType>()->getPointeeType(); 669 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 670 NewType = M->getPointeeType(); 671 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 672 } 673 674 if (!NewType->isFunctionProtoType()) 675 return; 676 677 // There's lots of special cases for functions. For function pointers, system 678 // libraries are hopefully not as broken so that we don't need these 679 // workarounds. 680 if (CheckEquivalentExceptionSpec( 681 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 682 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 683 New->setInvalidDecl(); 684 } 685 } 686 687 /// CheckCXXDefaultArguments - Verify that the default arguments for a 688 /// function declaration are well-formed according to C++ 689 /// [dcl.fct.default]. 690 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 691 unsigned NumParams = FD->getNumParams(); 692 unsigned p; 693 694 // Find first parameter with a default argument 695 for (p = 0; p < NumParams; ++p) { 696 ParmVarDecl *Param = FD->getParamDecl(p); 697 if (Param->hasDefaultArg()) 698 break; 699 } 700 701 // C++11 [dcl.fct.default]p4: 702 // In a given function declaration, each parameter subsequent to a parameter 703 // with a default argument shall have a default argument supplied in this or 704 // a previous declaration or shall be a function parameter pack. A default 705 // argument shall not be redefined by a later declaration (not even to the 706 // same value). 707 unsigned LastMissingDefaultArg = 0; 708 for (; p < NumParams; ++p) { 709 ParmVarDecl *Param = FD->getParamDecl(p); 710 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 711 if (Param->isInvalidDecl()) 712 /* We already complained about this parameter. */; 713 else if (Param->getIdentifier()) 714 Diag(Param->getLocation(), 715 diag::err_param_default_argument_missing_name) 716 << Param->getIdentifier(); 717 else 718 Diag(Param->getLocation(), 719 diag::err_param_default_argument_missing); 720 721 LastMissingDefaultArg = p; 722 } 723 } 724 725 if (LastMissingDefaultArg > 0) { 726 // Some default arguments were missing. Clear out all of the 727 // default arguments up to (and including) the last missing 728 // default argument, so that we leave the function parameters 729 // in a semantically valid state. 730 for (p = 0; p <= LastMissingDefaultArg; ++p) { 731 ParmVarDecl *Param = FD->getParamDecl(p); 732 if (Param->hasDefaultArg()) { 733 Param->setDefaultArg(nullptr); 734 } 735 } 736 } 737 } 738 739 // CheckConstexprParameterTypes - Check whether a function's parameter types 740 // are all literal types. If so, return true. If not, produce a suitable 741 // diagnostic and return false. 742 static bool CheckConstexprParameterTypes(Sema &SemaRef, 743 const FunctionDecl *FD) { 744 unsigned ArgIndex = 0; 745 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 746 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 747 e = FT->param_type_end(); 748 i != e; ++i, ++ArgIndex) { 749 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 750 SourceLocation ParamLoc = PD->getLocation(); 751 if (!(*i)->isDependentType() && 752 SemaRef.RequireLiteralType(ParamLoc, *i, 753 diag::err_constexpr_non_literal_param, 754 ArgIndex+1, PD->getSourceRange(), 755 isa<CXXConstructorDecl>(FD))) 756 return false; 757 } 758 return true; 759 } 760 761 /// \brief Get diagnostic %select index for tag kind for 762 /// record diagnostic message. 763 /// WARNING: Indexes apply to particular diagnostics only! 764 /// 765 /// \returns diagnostic %select index. 766 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 767 switch (Tag) { 768 case TTK_Struct: return 0; 769 case TTK_Interface: return 1; 770 case TTK_Class: return 2; 771 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 772 } 773 } 774 775 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 776 // the requirements of a constexpr function definition or a constexpr 777 // constructor definition. If so, return true. If not, produce appropriate 778 // diagnostics and return false. 779 // 780 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 781 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 782 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 783 if (MD && MD->isInstance()) { 784 // C++11 [dcl.constexpr]p4: 785 // The definition of a constexpr constructor shall satisfy the following 786 // constraints: 787 // - the class shall not have any virtual base classes; 788 const CXXRecordDecl *RD = MD->getParent(); 789 if (RD->getNumVBases()) { 790 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 791 << isa<CXXConstructorDecl>(NewFD) 792 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 793 for (const auto &I : RD->vbases()) 794 Diag(I.getLocStart(), 795 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 796 return false; 797 } 798 } 799 800 if (!isa<CXXConstructorDecl>(NewFD)) { 801 // C++11 [dcl.constexpr]p3: 802 // The definition of a constexpr function shall satisfy the following 803 // constraints: 804 // - it shall not be virtual; 805 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 806 if (Method && Method->isVirtual()) { 807 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 808 809 // If it's not obvious why this function is virtual, find an overridden 810 // function which uses the 'virtual' keyword. 811 const CXXMethodDecl *WrittenVirtual = Method; 812 while (!WrittenVirtual->isVirtualAsWritten()) 813 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 814 if (WrittenVirtual != Method) 815 Diag(WrittenVirtual->getLocation(), 816 diag::note_overridden_virtual_function); 817 return false; 818 } 819 820 // - its return type shall be a literal type; 821 QualType RT = NewFD->getReturnType(); 822 if (!RT->isDependentType() && 823 RequireLiteralType(NewFD->getLocation(), RT, 824 diag::err_constexpr_non_literal_return)) 825 return false; 826 } 827 828 // - each of its parameter types shall be a literal type; 829 if (!CheckConstexprParameterTypes(*this, NewFD)) 830 return false; 831 832 return true; 833 } 834 835 /// Check the given declaration statement is legal within a constexpr function 836 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 837 /// 838 /// \return true if the body is OK (maybe only as an extension), false if we 839 /// have diagnosed a problem. 840 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 841 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 842 // C++11 [dcl.constexpr]p3 and p4: 843 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 844 // contain only 845 for (const auto *DclIt : DS->decls()) { 846 switch (DclIt->getKind()) { 847 case Decl::StaticAssert: 848 case Decl::Using: 849 case Decl::UsingShadow: 850 case Decl::UsingDirective: 851 case Decl::UnresolvedUsingTypename: 852 case Decl::UnresolvedUsingValue: 853 // - static_assert-declarations 854 // - using-declarations, 855 // - using-directives, 856 continue; 857 858 case Decl::Typedef: 859 case Decl::TypeAlias: { 860 // - typedef declarations and alias-declarations that do not define 861 // classes or enumerations, 862 const auto *TN = cast<TypedefNameDecl>(DclIt); 863 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 864 // Don't allow variably-modified types in constexpr functions. 865 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 866 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 867 << TL.getSourceRange() << TL.getType() 868 << isa<CXXConstructorDecl>(Dcl); 869 return false; 870 } 871 continue; 872 } 873 874 case Decl::Enum: 875 case Decl::CXXRecord: 876 // C++1y allows types to be defined, not just declared. 877 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 878 SemaRef.Diag(DS->getLocStart(), 879 SemaRef.getLangOpts().CPlusPlus14 880 ? diag::warn_cxx11_compat_constexpr_type_definition 881 : diag::ext_constexpr_type_definition) 882 << isa<CXXConstructorDecl>(Dcl); 883 continue; 884 885 case Decl::EnumConstant: 886 case Decl::IndirectField: 887 case Decl::ParmVar: 888 // These can only appear with other declarations which are banned in 889 // C++11 and permitted in C++1y, so ignore them. 890 continue; 891 892 case Decl::Var: { 893 // C++1y [dcl.constexpr]p3 allows anything except: 894 // a definition of a variable of non-literal type or of static or 895 // thread storage duration or for which no initialization is performed. 896 const auto *VD = cast<VarDecl>(DclIt); 897 if (VD->isThisDeclarationADefinition()) { 898 if (VD->isStaticLocal()) { 899 SemaRef.Diag(VD->getLocation(), 900 diag::err_constexpr_local_var_static) 901 << isa<CXXConstructorDecl>(Dcl) 902 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 903 return false; 904 } 905 if (!VD->getType()->isDependentType() && 906 SemaRef.RequireLiteralType( 907 VD->getLocation(), VD->getType(), 908 diag::err_constexpr_local_var_non_literal_type, 909 isa<CXXConstructorDecl>(Dcl))) 910 return false; 911 if (!VD->getType()->isDependentType() && 912 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 913 SemaRef.Diag(VD->getLocation(), 914 diag::err_constexpr_local_var_no_init) 915 << isa<CXXConstructorDecl>(Dcl); 916 return false; 917 } 918 } 919 SemaRef.Diag(VD->getLocation(), 920 SemaRef.getLangOpts().CPlusPlus14 921 ? diag::warn_cxx11_compat_constexpr_local_var 922 : diag::ext_constexpr_local_var) 923 << isa<CXXConstructorDecl>(Dcl); 924 continue; 925 } 926 927 case Decl::NamespaceAlias: 928 case Decl::Function: 929 // These are disallowed in C++11 and permitted in C++1y. Allow them 930 // everywhere as an extension. 931 if (!Cxx1yLoc.isValid()) 932 Cxx1yLoc = DS->getLocStart(); 933 continue; 934 935 default: 936 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 937 << isa<CXXConstructorDecl>(Dcl); 938 return false; 939 } 940 } 941 942 return true; 943 } 944 945 /// Check that the given field is initialized within a constexpr constructor. 946 /// 947 /// \param Dcl The constexpr constructor being checked. 948 /// \param Field The field being checked. This may be a member of an anonymous 949 /// struct or union nested within the class being checked. 950 /// \param Inits All declarations, including anonymous struct/union members and 951 /// indirect members, for which any initialization was provided. 952 /// \param Diagnosed Set to true if an error is produced. 953 static void CheckConstexprCtorInitializer(Sema &SemaRef, 954 const FunctionDecl *Dcl, 955 FieldDecl *Field, 956 llvm::SmallSet<Decl*, 16> &Inits, 957 bool &Diagnosed) { 958 if (Field->isInvalidDecl()) 959 return; 960 961 if (Field->isUnnamedBitfield()) 962 return; 963 964 // Anonymous unions with no variant members and empty anonymous structs do not 965 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 966 // indirect fields don't need initializing. 967 if (Field->isAnonymousStructOrUnion() && 968 (Field->getType()->isUnionType() 969 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 970 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 971 return; 972 973 if (!Inits.count(Field)) { 974 if (!Diagnosed) { 975 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 976 Diagnosed = true; 977 } 978 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 979 } else if (Field->isAnonymousStructOrUnion()) { 980 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 981 for (auto *I : RD->fields()) 982 // If an anonymous union contains an anonymous struct of which any member 983 // is initialized, all members must be initialized. 984 if (!RD->isUnion() || Inits.count(I)) 985 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 986 } 987 } 988 989 /// Check the provided statement is allowed in a constexpr function 990 /// definition. 991 static bool 992 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 993 SmallVectorImpl<SourceLocation> &ReturnStmts, 994 SourceLocation &Cxx1yLoc) { 995 // - its function-body shall be [...] a compound-statement that contains only 996 switch (S->getStmtClass()) { 997 case Stmt::NullStmtClass: 998 // - null statements, 999 return true; 1000 1001 case Stmt::DeclStmtClass: 1002 // - static_assert-declarations 1003 // - using-declarations, 1004 // - using-directives, 1005 // - typedef declarations and alias-declarations that do not define 1006 // classes or enumerations, 1007 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1008 return false; 1009 return true; 1010 1011 case Stmt::ReturnStmtClass: 1012 // - and exactly one return statement; 1013 if (isa<CXXConstructorDecl>(Dcl)) { 1014 // C++1y allows return statements in constexpr constructors. 1015 if (!Cxx1yLoc.isValid()) 1016 Cxx1yLoc = S->getLocStart(); 1017 return true; 1018 } 1019 1020 ReturnStmts.push_back(S->getLocStart()); 1021 return true; 1022 1023 case Stmt::CompoundStmtClass: { 1024 // C++1y allows compound-statements. 1025 if (!Cxx1yLoc.isValid()) 1026 Cxx1yLoc = S->getLocStart(); 1027 1028 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1029 for (auto *BodyIt : CompStmt->body()) { 1030 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1031 Cxx1yLoc)) 1032 return false; 1033 } 1034 return true; 1035 } 1036 1037 case Stmt::AttributedStmtClass: 1038 if (!Cxx1yLoc.isValid()) 1039 Cxx1yLoc = S->getLocStart(); 1040 return true; 1041 1042 case Stmt::IfStmtClass: { 1043 // C++1y allows if-statements. 1044 if (!Cxx1yLoc.isValid()) 1045 Cxx1yLoc = S->getLocStart(); 1046 1047 IfStmt *If = cast<IfStmt>(S); 1048 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1049 Cxx1yLoc)) 1050 return false; 1051 if (If->getElse() && 1052 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1053 Cxx1yLoc)) 1054 return false; 1055 return true; 1056 } 1057 1058 case Stmt::WhileStmtClass: 1059 case Stmt::DoStmtClass: 1060 case Stmt::ForStmtClass: 1061 case Stmt::CXXForRangeStmtClass: 1062 case Stmt::ContinueStmtClass: 1063 // C++1y allows all of these. We don't allow them as extensions in C++11, 1064 // because they don't make sense without variable mutation. 1065 if (!SemaRef.getLangOpts().CPlusPlus14) 1066 break; 1067 if (!Cxx1yLoc.isValid()) 1068 Cxx1yLoc = S->getLocStart(); 1069 for (Stmt::child_range Children = S->children(); Children; ++Children) 1070 if (*Children && 1071 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1072 Cxx1yLoc)) 1073 return false; 1074 return true; 1075 1076 case Stmt::SwitchStmtClass: 1077 case Stmt::CaseStmtClass: 1078 case Stmt::DefaultStmtClass: 1079 case Stmt::BreakStmtClass: 1080 // C++1y allows switch-statements, and since they don't need variable 1081 // mutation, we can reasonably allow them in C++11 as an extension. 1082 if (!Cxx1yLoc.isValid()) 1083 Cxx1yLoc = S->getLocStart(); 1084 for (Stmt::child_range Children = S->children(); Children; ++Children) 1085 if (*Children && 1086 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1087 Cxx1yLoc)) 1088 return false; 1089 return true; 1090 1091 default: 1092 if (!isa<Expr>(S)) 1093 break; 1094 1095 // C++1y allows expression-statements. 1096 if (!Cxx1yLoc.isValid()) 1097 Cxx1yLoc = S->getLocStart(); 1098 return true; 1099 } 1100 1101 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1102 << isa<CXXConstructorDecl>(Dcl); 1103 return false; 1104 } 1105 1106 /// Check the body for the given constexpr function declaration only contains 1107 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1108 /// 1109 /// \return true if the body is OK, false if we have diagnosed a problem. 1110 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1111 if (isa<CXXTryStmt>(Body)) { 1112 // C++11 [dcl.constexpr]p3: 1113 // The definition of a constexpr function shall satisfy the following 1114 // constraints: [...] 1115 // - its function-body shall be = delete, = default, or a 1116 // compound-statement 1117 // 1118 // C++11 [dcl.constexpr]p4: 1119 // In the definition of a constexpr constructor, [...] 1120 // - its function-body shall not be a function-try-block; 1121 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1122 << isa<CXXConstructorDecl>(Dcl); 1123 return false; 1124 } 1125 1126 SmallVector<SourceLocation, 4> ReturnStmts; 1127 1128 // - its function-body shall be [...] a compound-statement that contains only 1129 // [... list of cases ...] 1130 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1131 SourceLocation Cxx1yLoc; 1132 for (auto *BodyIt : CompBody->body()) { 1133 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1134 return false; 1135 } 1136 1137 if (Cxx1yLoc.isValid()) 1138 Diag(Cxx1yLoc, 1139 getLangOpts().CPlusPlus14 1140 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1141 : diag::ext_constexpr_body_invalid_stmt) 1142 << isa<CXXConstructorDecl>(Dcl); 1143 1144 if (const CXXConstructorDecl *Constructor 1145 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1146 const CXXRecordDecl *RD = Constructor->getParent(); 1147 // DR1359: 1148 // - every non-variant non-static data member and base class sub-object 1149 // shall be initialized; 1150 // DR1460: 1151 // - if the class is a union having variant members, exactly one of them 1152 // shall be initialized; 1153 if (RD->isUnion()) { 1154 if (Constructor->getNumCtorInitializers() == 0 && 1155 RD->hasVariantMembers()) { 1156 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1157 return false; 1158 } 1159 } else if (!Constructor->isDependentContext() && 1160 !Constructor->isDelegatingConstructor()) { 1161 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1162 1163 // Skip detailed checking if we have enough initializers, and we would 1164 // allow at most one initializer per member. 1165 bool AnyAnonStructUnionMembers = false; 1166 unsigned Fields = 0; 1167 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1168 E = RD->field_end(); I != E; ++I, ++Fields) { 1169 if (I->isAnonymousStructOrUnion()) { 1170 AnyAnonStructUnionMembers = true; 1171 break; 1172 } 1173 } 1174 // DR1460: 1175 // - if the class is a union-like class, but is not a union, for each of 1176 // its anonymous union members having variant members, exactly one of 1177 // them shall be initialized; 1178 if (AnyAnonStructUnionMembers || 1179 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1180 // Check initialization of non-static data members. Base classes are 1181 // always initialized so do not need to be checked. Dependent bases 1182 // might not have initializers in the member initializer list. 1183 llvm::SmallSet<Decl*, 16> Inits; 1184 for (const auto *I: Constructor->inits()) { 1185 if (FieldDecl *FD = I->getMember()) 1186 Inits.insert(FD); 1187 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1188 Inits.insert(ID->chain_begin(), ID->chain_end()); 1189 } 1190 1191 bool Diagnosed = false; 1192 for (auto *I : RD->fields()) 1193 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1194 if (Diagnosed) 1195 return false; 1196 } 1197 } 1198 } else { 1199 if (ReturnStmts.empty()) { 1200 // C++1y doesn't require constexpr functions to contain a 'return' 1201 // statement. We still do, unless the return type might be void, because 1202 // otherwise if there's no return statement, the function cannot 1203 // be used in a core constant expression. 1204 bool OK = getLangOpts().CPlusPlus14 && 1205 (Dcl->getReturnType()->isVoidType() || 1206 Dcl->getReturnType()->isDependentType()); 1207 Diag(Dcl->getLocation(), 1208 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1209 : diag::err_constexpr_body_no_return); 1210 return OK; 1211 } 1212 if (ReturnStmts.size() > 1) { 1213 Diag(ReturnStmts.back(), 1214 getLangOpts().CPlusPlus14 1215 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1216 : diag::ext_constexpr_body_multiple_return); 1217 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1218 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1219 } 1220 } 1221 1222 // C++11 [dcl.constexpr]p5: 1223 // if no function argument values exist such that the function invocation 1224 // substitution would produce a constant expression, the program is 1225 // ill-formed; no diagnostic required. 1226 // C++11 [dcl.constexpr]p3: 1227 // - every constructor call and implicit conversion used in initializing the 1228 // return value shall be one of those allowed in a constant expression. 1229 // C++11 [dcl.constexpr]p4: 1230 // - every constructor involved in initializing non-static data members and 1231 // base class sub-objects shall be a constexpr constructor. 1232 SmallVector<PartialDiagnosticAt, 8> Diags; 1233 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1234 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1235 << isa<CXXConstructorDecl>(Dcl); 1236 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1237 Diag(Diags[I].first, Diags[I].second); 1238 // Don't return false here: we allow this for compatibility in 1239 // system headers. 1240 } 1241 1242 return true; 1243 } 1244 1245 /// isCurrentClassName - Determine whether the identifier II is the 1246 /// name of the class type currently being defined. In the case of 1247 /// nested classes, this will only return true if II is the name of 1248 /// the innermost class. 1249 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1250 const CXXScopeSpec *SS) { 1251 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1252 1253 CXXRecordDecl *CurDecl; 1254 if (SS && SS->isSet() && !SS->isInvalid()) { 1255 DeclContext *DC = computeDeclContext(*SS, true); 1256 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1257 } else 1258 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1259 1260 if (CurDecl && CurDecl->getIdentifier()) 1261 return &II == CurDecl->getIdentifier(); 1262 return false; 1263 } 1264 1265 /// \brief Determine whether the identifier II is a typo for the name of 1266 /// the class type currently being defined. If so, update it to the identifier 1267 /// that should have been used. 1268 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1269 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1270 1271 if (!getLangOpts().SpellChecking) 1272 return false; 1273 1274 CXXRecordDecl *CurDecl; 1275 if (SS && SS->isSet() && !SS->isInvalid()) { 1276 DeclContext *DC = computeDeclContext(*SS, true); 1277 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1278 } else 1279 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1280 1281 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1282 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1283 < II->getLength()) { 1284 II = CurDecl->getIdentifier(); 1285 return true; 1286 } 1287 1288 return false; 1289 } 1290 1291 /// \brief Determine whether the given class is a base class of the given 1292 /// class, including looking at dependent bases. 1293 static bool findCircularInheritance(const CXXRecordDecl *Class, 1294 const CXXRecordDecl *Current) { 1295 SmallVector<const CXXRecordDecl*, 8> Queue; 1296 1297 Class = Class->getCanonicalDecl(); 1298 while (true) { 1299 for (const auto &I : Current->bases()) { 1300 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1301 if (!Base) 1302 continue; 1303 1304 Base = Base->getDefinition(); 1305 if (!Base) 1306 continue; 1307 1308 if (Base->getCanonicalDecl() == Class) 1309 return true; 1310 1311 Queue.push_back(Base); 1312 } 1313 1314 if (Queue.empty()) 1315 return false; 1316 1317 Current = Queue.pop_back_val(); 1318 } 1319 1320 return false; 1321 } 1322 1323 /// \brief Perform propagation of DLL attributes from a derived class to a 1324 /// templated base class for MS compatibility. 1325 static void propagateDLLAttrToBaseClassTemplate( 1326 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1327 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1328 if (getDLLAttr( 1329 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1330 // If the base class template has a DLL attribute, don't try to change it. 1331 return; 1332 } 1333 1334 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1335 // If the base class is not already specialized, we can do the propagation. 1336 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1337 NewAttr->setInherited(true); 1338 BaseTemplateSpec->addAttr(NewAttr); 1339 return; 1340 } 1341 1342 bool DifferentAttribute = false; 1343 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1344 if (!SpecializationAttr->isInherited()) { 1345 // The template has previously been specialized or instantiated with an 1346 // explicit attribute. We should not try to change it. 1347 return; 1348 } 1349 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1350 // The specialization already has the right attribute. 1351 return; 1352 } 1353 DifferentAttribute = true; 1354 } 1355 1356 // The template was previously instantiated or explicitly specialized without 1357 // a dll attribute, or the template was previously instantiated with a 1358 // different inherited attribute. It's too late for us to change the 1359 // attribute, so warn that this is unsupported. 1360 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1361 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1362 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1363 if (BaseTemplateSpec->isExplicitSpecialization()) { 1364 S.Diag(BaseTemplateSpec->getLocation(), 1365 diag::note_template_class_explicit_specialization_was_here) 1366 << BaseTemplateSpec; 1367 } else { 1368 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1369 diag::note_template_class_instantiation_was_here) 1370 << BaseTemplateSpec; 1371 } 1372 } 1373 1374 /// \brief Check the validity of a C++ base class specifier. 1375 /// 1376 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1377 /// and returns NULL otherwise. 1378 CXXBaseSpecifier * 1379 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1380 SourceRange SpecifierRange, 1381 bool Virtual, AccessSpecifier Access, 1382 TypeSourceInfo *TInfo, 1383 SourceLocation EllipsisLoc) { 1384 QualType BaseType = TInfo->getType(); 1385 1386 // C++ [class.union]p1: 1387 // A union shall not have base classes. 1388 if (Class->isUnion()) { 1389 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1390 << SpecifierRange; 1391 return nullptr; 1392 } 1393 1394 if (EllipsisLoc.isValid() && 1395 !TInfo->getType()->containsUnexpandedParameterPack()) { 1396 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1397 << TInfo->getTypeLoc().getSourceRange(); 1398 EllipsisLoc = SourceLocation(); 1399 } 1400 1401 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1402 1403 if (BaseType->isDependentType()) { 1404 // Make sure that we don't have circular inheritance among our dependent 1405 // bases. For non-dependent bases, the check for completeness below handles 1406 // this. 1407 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1408 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1409 ((BaseDecl = BaseDecl->getDefinition()) && 1410 findCircularInheritance(Class, BaseDecl))) { 1411 Diag(BaseLoc, diag::err_circular_inheritance) 1412 << BaseType << Context.getTypeDeclType(Class); 1413 1414 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1415 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1416 << BaseType; 1417 1418 return nullptr; 1419 } 1420 } 1421 1422 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1423 Class->getTagKind() == TTK_Class, 1424 Access, TInfo, EllipsisLoc); 1425 } 1426 1427 // Base specifiers must be record types. 1428 if (!BaseType->isRecordType()) { 1429 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1430 return nullptr; 1431 } 1432 1433 // C++ [class.union]p1: 1434 // A union shall not be used as a base class. 1435 if (BaseType->isUnionType()) { 1436 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1437 return nullptr; 1438 } 1439 1440 // For the MS ABI, propagate DLL attributes to base class templates. 1441 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1442 if (Attr *ClassAttr = getDLLAttr(Class)) { 1443 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1444 BaseType->getAsCXXRecordDecl())) { 1445 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1446 BaseTemplate, BaseLoc); 1447 } 1448 } 1449 } 1450 1451 // C++ [class.derived]p2: 1452 // The class-name in a base-specifier shall not be an incompletely 1453 // defined class. 1454 if (RequireCompleteType(BaseLoc, BaseType, 1455 diag::err_incomplete_base_class, SpecifierRange)) { 1456 Class->setInvalidDecl(); 1457 return nullptr; 1458 } 1459 1460 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1461 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1462 assert(BaseDecl && "Record type has no declaration"); 1463 BaseDecl = BaseDecl->getDefinition(); 1464 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1465 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1466 assert(CXXBaseDecl && "Base type is not a C++ type"); 1467 1468 // A class which contains a flexible array member is not suitable for use as a 1469 // base class: 1470 // - If the layout determines that a base comes before another base, 1471 // the flexible array member would index into the subsequent base. 1472 // - If the layout determines that base comes before the derived class, 1473 // the flexible array member would index into the derived class. 1474 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1475 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1476 << CXXBaseDecl->getDeclName(); 1477 return nullptr; 1478 } 1479 1480 // C++ [class]p3: 1481 // If a class is marked final and it appears as a base-type-specifier in 1482 // base-clause, the program is ill-formed. 1483 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1484 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1485 << CXXBaseDecl->getDeclName() 1486 << FA->isSpelledAsSealed(); 1487 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1488 << CXXBaseDecl->getDeclName() << FA->getRange(); 1489 return nullptr; 1490 } 1491 1492 if (BaseDecl->isInvalidDecl()) 1493 Class->setInvalidDecl(); 1494 1495 // Create the base specifier. 1496 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1497 Class->getTagKind() == TTK_Class, 1498 Access, TInfo, EllipsisLoc); 1499 } 1500 1501 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1502 /// one entry in the base class list of a class specifier, for 1503 /// example: 1504 /// class foo : public bar, virtual private baz { 1505 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1506 BaseResult 1507 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1508 ParsedAttributes &Attributes, 1509 bool Virtual, AccessSpecifier Access, 1510 ParsedType basetype, SourceLocation BaseLoc, 1511 SourceLocation EllipsisLoc) { 1512 if (!classdecl) 1513 return true; 1514 1515 AdjustDeclIfTemplate(classdecl); 1516 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1517 if (!Class) 1518 return true; 1519 1520 // We haven't yet attached the base specifiers. 1521 Class->setIsParsingBaseSpecifiers(); 1522 1523 // We do not support any C++11 attributes on base-specifiers yet. 1524 // Diagnose any attributes we see. 1525 if (!Attributes.empty()) { 1526 for (AttributeList *Attr = Attributes.getList(); Attr; 1527 Attr = Attr->getNext()) { 1528 if (Attr->isInvalid() || 1529 Attr->getKind() == AttributeList::IgnoredAttribute) 1530 continue; 1531 Diag(Attr->getLoc(), 1532 Attr->getKind() == AttributeList::UnknownAttribute 1533 ? diag::warn_unknown_attribute_ignored 1534 : diag::err_base_specifier_attribute) 1535 << Attr->getName(); 1536 } 1537 } 1538 1539 TypeSourceInfo *TInfo = nullptr; 1540 GetTypeFromParser(basetype, &TInfo); 1541 1542 if (EllipsisLoc.isInvalid() && 1543 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1544 UPPC_BaseType)) 1545 return true; 1546 1547 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1548 Virtual, Access, TInfo, 1549 EllipsisLoc)) 1550 return BaseSpec; 1551 else 1552 Class->setInvalidDecl(); 1553 1554 return true; 1555 } 1556 1557 /// Use small set to collect indirect bases. As this is only used 1558 /// locally, there's no need to abstract the small size parameter. 1559 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 1560 1561 /// \brief Recursively add the bases of Type. Don't add Type itself. 1562 static void 1563 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 1564 const QualType &Type) 1565 { 1566 // Even though the incoming type is a base, it might not be 1567 // a class -- it could be a template parm, for instance. 1568 if (auto Rec = Type->getAs<RecordType>()) { 1569 auto Decl = Rec->getAsCXXRecordDecl(); 1570 1571 // Iterate over its bases. 1572 for (const auto &BaseSpec : Decl->bases()) { 1573 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 1574 .getUnqualifiedType(); 1575 if (Set.insert(Base).second) 1576 // If we've not already seen it, recurse. 1577 NoteIndirectBases(Context, Set, Base); 1578 } 1579 } 1580 } 1581 1582 /// \brief Performs the actual work of attaching the given base class 1583 /// specifiers to a C++ class. 1584 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1585 unsigned NumBases) { 1586 if (NumBases == 0) 1587 return false; 1588 1589 // Used to keep track of which base types we have already seen, so 1590 // that we can properly diagnose redundant direct base types. Note 1591 // that the key is always the unqualified canonical type of the base 1592 // class. 1593 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1594 1595 // Used to track indirect bases so we can see if a direct base is 1596 // ambiguous. 1597 IndirectBaseSet IndirectBaseTypes; 1598 1599 // Copy non-redundant base specifiers into permanent storage. 1600 unsigned NumGoodBases = 0; 1601 bool Invalid = false; 1602 for (unsigned idx = 0; idx < NumBases; ++idx) { 1603 QualType NewBaseType 1604 = Context.getCanonicalType(Bases[idx]->getType()); 1605 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1606 1607 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1608 if (KnownBase) { 1609 // C++ [class.mi]p3: 1610 // A class shall not be specified as a direct base class of a 1611 // derived class more than once. 1612 Diag(Bases[idx]->getLocStart(), 1613 diag::err_duplicate_base_class) 1614 << KnownBase->getType() 1615 << Bases[idx]->getSourceRange(); 1616 1617 // Delete the duplicate base class specifier; we're going to 1618 // overwrite its pointer later. 1619 Context.Deallocate(Bases[idx]); 1620 1621 Invalid = true; 1622 } else { 1623 // Okay, add this new base class. 1624 KnownBase = Bases[idx]; 1625 Bases[NumGoodBases++] = Bases[idx]; 1626 1627 // Note this base's direct & indirect bases, if there could be ambiguity. 1628 if (NumBases > 1) 1629 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 1630 1631 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1632 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1633 if (Class->isInterface() && 1634 (!RD->isInterface() || 1635 KnownBase->getAccessSpecifier() != AS_public)) { 1636 // The Microsoft extension __interface does not permit bases that 1637 // are not themselves public interfaces. 1638 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1639 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1640 << RD->getSourceRange(); 1641 Invalid = true; 1642 } 1643 if (RD->hasAttr<WeakAttr>()) 1644 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1645 } 1646 } 1647 } 1648 1649 // Attach the remaining base class specifiers to the derived class. 1650 Class->setBases(Bases, NumGoodBases); 1651 1652 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 1653 // Check whether this direct base is inaccessible due to ambiguity. 1654 QualType BaseType = Bases[idx]->getType(); 1655 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 1656 .getUnqualifiedType(); 1657 1658 if (IndirectBaseTypes.count(CanonicalBase)) { 1659 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1660 /*DetectVirtual=*/true); 1661 bool found 1662 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 1663 assert(found); 1664 (void)found; 1665 1666 if (Paths.isAmbiguous(CanonicalBase)) 1667 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 1668 << BaseType << getAmbiguousPathsDisplayString(Paths) 1669 << Bases[idx]->getSourceRange(); 1670 else 1671 assert(Bases[idx]->isVirtual()); 1672 } 1673 1674 // Delete the base class specifier, since its data has been copied 1675 // into the CXXRecordDecl. 1676 Context.Deallocate(Bases[idx]); 1677 } 1678 1679 return Invalid; 1680 } 1681 1682 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1683 /// class, after checking whether there are any duplicate base 1684 /// classes. 1685 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1686 unsigned NumBases) { 1687 if (!ClassDecl || !Bases || !NumBases) 1688 return; 1689 1690 AdjustDeclIfTemplate(ClassDecl); 1691 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1692 } 1693 1694 /// \brief Determine whether the type \p Derived is a C++ class that is 1695 /// derived from the type \p Base. 1696 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1697 if (!getLangOpts().CPlusPlus) 1698 return false; 1699 1700 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1701 if (!DerivedRD) 1702 return false; 1703 1704 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1705 if (!BaseRD) 1706 return false; 1707 1708 // If either the base or the derived type is invalid, don't try to 1709 // check whether one is derived from the other. 1710 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1711 return false; 1712 1713 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1714 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1715 } 1716 1717 /// \brief Determine whether the type \p Derived is a C++ class that is 1718 /// derived from the type \p Base. 1719 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1720 if (!getLangOpts().CPlusPlus) 1721 return false; 1722 1723 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1724 if (!DerivedRD) 1725 return false; 1726 1727 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1728 if (!BaseRD) 1729 return false; 1730 1731 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1732 } 1733 1734 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1735 CXXCastPath &BasePathArray) { 1736 assert(BasePathArray.empty() && "Base path array must be empty!"); 1737 assert(Paths.isRecordingPaths() && "Must record paths!"); 1738 1739 const CXXBasePath &Path = Paths.front(); 1740 1741 // We first go backward and check if we have a virtual base. 1742 // FIXME: It would be better if CXXBasePath had the base specifier for 1743 // the nearest virtual base. 1744 unsigned Start = 0; 1745 for (unsigned I = Path.size(); I != 0; --I) { 1746 if (Path[I - 1].Base->isVirtual()) { 1747 Start = I - 1; 1748 break; 1749 } 1750 } 1751 1752 // Now add all bases. 1753 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1754 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1755 } 1756 1757 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1758 /// conversion (where Derived and Base are class types) is 1759 /// well-formed, meaning that the conversion is unambiguous (and 1760 /// that all of the base classes are accessible). Returns true 1761 /// and emits a diagnostic if the code is ill-formed, returns false 1762 /// otherwise. Loc is the location where this routine should point to 1763 /// if there is an error, and Range is the source range to highlight 1764 /// if there is an error. 1765 bool 1766 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1767 unsigned InaccessibleBaseID, 1768 unsigned AmbigiousBaseConvID, 1769 SourceLocation Loc, SourceRange Range, 1770 DeclarationName Name, 1771 CXXCastPath *BasePath) { 1772 // First, determine whether the path from Derived to Base is 1773 // ambiguous. This is slightly more expensive than checking whether 1774 // the Derived to Base conversion exists, because here we need to 1775 // explore multiple paths to determine if there is an ambiguity. 1776 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1777 /*DetectVirtual=*/false); 1778 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1779 assert(DerivationOkay && 1780 "Can only be used with a derived-to-base conversion"); 1781 (void)DerivationOkay; 1782 1783 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1784 if (InaccessibleBaseID) { 1785 // Check that the base class can be accessed. 1786 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1787 InaccessibleBaseID)) { 1788 case AR_inaccessible: 1789 return true; 1790 case AR_accessible: 1791 case AR_dependent: 1792 case AR_delayed: 1793 break; 1794 } 1795 } 1796 1797 // Build a base path if necessary. 1798 if (BasePath) 1799 BuildBasePathArray(Paths, *BasePath); 1800 return false; 1801 } 1802 1803 if (AmbigiousBaseConvID) { 1804 // We know that the derived-to-base conversion is ambiguous, and 1805 // we're going to produce a diagnostic. Perform the derived-to-base 1806 // search just one more time to compute all of the possible paths so 1807 // that we can print them out. This is more expensive than any of 1808 // the previous derived-to-base checks we've done, but at this point 1809 // performance isn't as much of an issue. 1810 Paths.clear(); 1811 Paths.setRecordingPaths(true); 1812 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1813 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1814 (void)StillOkay; 1815 1816 // Build up a textual representation of the ambiguous paths, e.g., 1817 // D -> B -> A, that will be used to illustrate the ambiguous 1818 // conversions in the diagnostic. We only print one of the paths 1819 // to each base class subobject. 1820 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1821 1822 Diag(Loc, AmbigiousBaseConvID) 1823 << Derived << Base << PathDisplayStr << Range << Name; 1824 } 1825 return true; 1826 } 1827 1828 bool 1829 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1830 SourceLocation Loc, SourceRange Range, 1831 CXXCastPath *BasePath, 1832 bool IgnoreAccess) { 1833 return CheckDerivedToBaseConversion(Derived, Base, 1834 IgnoreAccess ? 0 1835 : diag::err_upcast_to_inaccessible_base, 1836 diag::err_ambiguous_derived_to_base_conv, 1837 Loc, Range, DeclarationName(), 1838 BasePath); 1839 } 1840 1841 1842 /// @brief Builds a string representing ambiguous paths from a 1843 /// specific derived class to different subobjects of the same base 1844 /// class. 1845 /// 1846 /// This function builds a string that can be used in error messages 1847 /// to show the different paths that one can take through the 1848 /// inheritance hierarchy to go from the derived class to different 1849 /// subobjects of a base class. The result looks something like this: 1850 /// @code 1851 /// struct D -> struct B -> struct A 1852 /// struct D -> struct C -> struct A 1853 /// @endcode 1854 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1855 std::string PathDisplayStr; 1856 std::set<unsigned> DisplayedPaths; 1857 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1858 Path != Paths.end(); ++Path) { 1859 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1860 // We haven't displayed a path to this particular base 1861 // class subobject yet. 1862 PathDisplayStr += "\n "; 1863 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1864 for (CXXBasePath::const_iterator Element = Path->begin(); 1865 Element != Path->end(); ++Element) 1866 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1867 } 1868 } 1869 1870 return PathDisplayStr; 1871 } 1872 1873 //===----------------------------------------------------------------------===// 1874 // C++ class member Handling 1875 //===----------------------------------------------------------------------===// 1876 1877 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1878 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1879 SourceLocation ASLoc, 1880 SourceLocation ColonLoc, 1881 AttributeList *Attrs) { 1882 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1883 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1884 ASLoc, ColonLoc); 1885 CurContext->addHiddenDecl(ASDecl); 1886 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1887 } 1888 1889 /// CheckOverrideControl - Check C++11 override control semantics. 1890 void Sema::CheckOverrideControl(NamedDecl *D) { 1891 if (D->isInvalidDecl()) 1892 return; 1893 1894 // We only care about "override" and "final" declarations. 1895 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1896 return; 1897 1898 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1899 1900 // We can't check dependent instance methods. 1901 if (MD && MD->isInstance() && 1902 (MD->getParent()->hasAnyDependentBases() || 1903 MD->getType()->isDependentType())) 1904 return; 1905 1906 if (MD && !MD->isVirtual()) { 1907 // If we have a non-virtual method, check if if hides a virtual method. 1908 // (In that case, it's most likely the method has the wrong type.) 1909 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1910 FindHiddenVirtualMethods(MD, OverloadedMethods); 1911 1912 if (!OverloadedMethods.empty()) { 1913 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1914 Diag(OA->getLocation(), 1915 diag::override_keyword_hides_virtual_member_function) 1916 << "override" << (OverloadedMethods.size() > 1); 1917 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1918 Diag(FA->getLocation(), 1919 diag::override_keyword_hides_virtual_member_function) 1920 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1921 << (OverloadedMethods.size() > 1); 1922 } 1923 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1924 MD->setInvalidDecl(); 1925 return; 1926 } 1927 // Fall through into the general case diagnostic. 1928 // FIXME: We might want to attempt typo correction here. 1929 } 1930 1931 if (!MD || !MD->isVirtual()) { 1932 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1933 Diag(OA->getLocation(), 1934 diag::override_keyword_only_allowed_on_virtual_member_functions) 1935 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1936 D->dropAttr<OverrideAttr>(); 1937 } 1938 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1939 Diag(FA->getLocation(), 1940 diag::override_keyword_only_allowed_on_virtual_member_functions) 1941 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1942 << FixItHint::CreateRemoval(FA->getLocation()); 1943 D->dropAttr<FinalAttr>(); 1944 } 1945 return; 1946 } 1947 1948 // C++11 [class.virtual]p5: 1949 // If a function is marked with the virt-specifier override and 1950 // does not override a member function of a base class, the program is 1951 // ill-formed. 1952 bool HasOverriddenMethods = 1953 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1954 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1955 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1956 << MD->getDeclName(); 1957 } 1958 1959 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1960 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1961 return; 1962 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1963 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1964 isa<CXXDestructorDecl>(MD)) 1965 return; 1966 1967 SourceLocation Loc = MD->getLocation(); 1968 SourceLocation SpellingLoc = Loc; 1969 if (getSourceManager().isMacroArgExpansion(Loc)) 1970 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1971 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1972 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1973 return; 1974 1975 if (MD->size_overridden_methods() > 0) { 1976 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 1977 << MD->getDeclName(); 1978 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 1979 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 1980 } 1981 } 1982 1983 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1984 /// function overrides a virtual member function marked 'final', according to 1985 /// C++11 [class.virtual]p4. 1986 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1987 const CXXMethodDecl *Old) { 1988 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1989 if (!FA) 1990 return false; 1991 1992 Diag(New->getLocation(), diag::err_final_function_overridden) 1993 << New->getDeclName() 1994 << FA->isSpelledAsSealed(); 1995 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1996 return true; 1997 } 1998 1999 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2000 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2001 // FIXME: Destruction of ObjC lifetime types has side-effects. 2002 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2003 return !RD->isCompleteDefinition() || 2004 !RD->hasTrivialDefaultConstructor() || 2005 !RD->hasTrivialDestructor(); 2006 return false; 2007 } 2008 2009 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2010 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2011 if (it->isDeclspecPropertyAttribute()) 2012 return it; 2013 return nullptr; 2014 } 2015 2016 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2017 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2018 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2019 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2020 /// present (but parsing it has been deferred). 2021 NamedDecl * 2022 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2023 MultiTemplateParamsArg TemplateParameterLists, 2024 Expr *BW, const VirtSpecifiers &VS, 2025 InClassInitStyle InitStyle) { 2026 const DeclSpec &DS = D.getDeclSpec(); 2027 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2028 DeclarationName Name = NameInfo.getName(); 2029 SourceLocation Loc = NameInfo.getLoc(); 2030 2031 // For anonymous bitfields, the location should point to the type. 2032 if (Loc.isInvalid()) 2033 Loc = D.getLocStart(); 2034 2035 Expr *BitWidth = static_cast<Expr*>(BW); 2036 2037 assert(isa<CXXRecordDecl>(CurContext)); 2038 assert(!DS.isFriendSpecified()); 2039 2040 bool isFunc = D.isDeclarationOfFunction(); 2041 2042 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2043 // The Microsoft extension __interface only permits public member functions 2044 // and prohibits constructors, destructors, operators, non-public member 2045 // functions, static methods and data members. 2046 unsigned InvalidDecl; 2047 bool ShowDeclName = true; 2048 if (!isFunc) 2049 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2050 else if (AS != AS_public) 2051 InvalidDecl = 2; 2052 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2053 InvalidDecl = 3; 2054 else switch (Name.getNameKind()) { 2055 case DeclarationName::CXXConstructorName: 2056 InvalidDecl = 4; 2057 ShowDeclName = false; 2058 break; 2059 2060 case DeclarationName::CXXDestructorName: 2061 InvalidDecl = 5; 2062 ShowDeclName = false; 2063 break; 2064 2065 case DeclarationName::CXXOperatorName: 2066 case DeclarationName::CXXConversionFunctionName: 2067 InvalidDecl = 6; 2068 break; 2069 2070 default: 2071 InvalidDecl = 0; 2072 break; 2073 } 2074 2075 if (InvalidDecl) { 2076 if (ShowDeclName) 2077 Diag(Loc, diag::err_invalid_member_in_interface) 2078 << (InvalidDecl-1) << Name; 2079 else 2080 Diag(Loc, diag::err_invalid_member_in_interface) 2081 << (InvalidDecl-1) << ""; 2082 return nullptr; 2083 } 2084 } 2085 2086 // C++ 9.2p6: A member shall not be declared to have automatic storage 2087 // duration (auto, register) or with the extern storage-class-specifier. 2088 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2089 // data members and cannot be applied to names declared const or static, 2090 // and cannot be applied to reference members. 2091 switch (DS.getStorageClassSpec()) { 2092 case DeclSpec::SCS_unspecified: 2093 case DeclSpec::SCS_typedef: 2094 case DeclSpec::SCS_static: 2095 break; 2096 case DeclSpec::SCS_mutable: 2097 if (isFunc) { 2098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2099 2100 // FIXME: It would be nicer if the keyword was ignored only for this 2101 // declarator. Otherwise we could get follow-up errors. 2102 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2103 } 2104 break; 2105 default: 2106 Diag(DS.getStorageClassSpecLoc(), 2107 diag::err_storageclass_invalid_for_member); 2108 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2109 break; 2110 } 2111 2112 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2113 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2114 !isFunc); 2115 2116 if (DS.isConstexprSpecified() && isInstField) { 2117 SemaDiagnosticBuilder B = 2118 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2119 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2120 if (InitStyle == ICIS_NoInit) { 2121 B << 0 << 0; 2122 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2123 B << FixItHint::CreateRemoval(ConstexprLoc); 2124 else { 2125 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2126 D.getMutableDeclSpec().ClearConstexprSpec(); 2127 const char *PrevSpec; 2128 unsigned DiagID; 2129 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2130 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2131 (void)Failed; 2132 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2133 } 2134 } else { 2135 B << 1; 2136 const char *PrevSpec; 2137 unsigned DiagID; 2138 if (D.getMutableDeclSpec().SetStorageClassSpec( 2139 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2140 Context.getPrintingPolicy())) { 2141 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2142 "This is the only DeclSpec that should fail to be applied"); 2143 B << 1; 2144 } else { 2145 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2146 isInstField = false; 2147 } 2148 } 2149 } 2150 2151 NamedDecl *Member; 2152 if (isInstField) { 2153 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2154 2155 // Data members must have identifiers for names. 2156 if (!Name.isIdentifier()) { 2157 Diag(Loc, diag::err_bad_variable_name) 2158 << Name; 2159 return nullptr; 2160 } 2161 2162 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2163 2164 // Member field could not be with "template" keyword. 2165 // So TemplateParameterLists should be empty in this case. 2166 if (TemplateParameterLists.size()) { 2167 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2168 if (TemplateParams->size()) { 2169 // There is no such thing as a member field template. 2170 Diag(D.getIdentifierLoc(), diag::err_template_member) 2171 << II 2172 << SourceRange(TemplateParams->getTemplateLoc(), 2173 TemplateParams->getRAngleLoc()); 2174 } else { 2175 // There is an extraneous 'template<>' for this member. 2176 Diag(TemplateParams->getTemplateLoc(), 2177 diag::err_template_member_noparams) 2178 << II 2179 << SourceRange(TemplateParams->getTemplateLoc(), 2180 TemplateParams->getRAngleLoc()); 2181 } 2182 return nullptr; 2183 } 2184 2185 if (SS.isSet() && !SS.isInvalid()) { 2186 // The user provided a superfluous scope specifier inside a class 2187 // definition: 2188 // 2189 // class X { 2190 // int X::member; 2191 // }; 2192 if (DeclContext *DC = computeDeclContext(SS, false)) 2193 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2194 else 2195 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2196 << Name << SS.getRange(); 2197 2198 SS.clear(); 2199 } 2200 2201 AttributeList *MSPropertyAttr = 2202 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2203 if (MSPropertyAttr) { 2204 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2205 BitWidth, InitStyle, AS, MSPropertyAttr); 2206 if (!Member) 2207 return nullptr; 2208 isInstField = false; 2209 } else { 2210 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2211 BitWidth, InitStyle, AS); 2212 assert(Member && "HandleField never returns null"); 2213 } 2214 } else { 2215 assert(InitStyle == ICIS_NoInit || 2216 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2217 2218 Member = HandleDeclarator(S, D, TemplateParameterLists); 2219 if (!Member) 2220 return nullptr; 2221 2222 // Non-instance-fields can't have a bitfield. 2223 if (BitWidth) { 2224 if (Member->isInvalidDecl()) { 2225 // don't emit another diagnostic. 2226 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 2227 // C++ 9.6p3: A bit-field shall not be a static member. 2228 // "static member 'A' cannot be a bit-field" 2229 Diag(Loc, diag::err_static_not_bitfield) 2230 << Name << BitWidth->getSourceRange(); 2231 } else if (isa<TypedefDecl>(Member)) { 2232 // "typedef member 'x' cannot be a bit-field" 2233 Diag(Loc, diag::err_typedef_not_bitfield) 2234 << Name << BitWidth->getSourceRange(); 2235 } else { 2236 // A function typedef ("typedef int f(); f a;"). 2237 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2238 Diag(Loc, diag::err_not_integral_type_bitfield) 2239 << Name << cast<ValueDecl>(Member)->getType() 2240 << BitWidth->getSourceRange(); 2241 } 2242 2243 BitWidth = nullptr; 2244 Member->setInvalidDecl(); 2245 } 2246 2247 Member->setAccess(AS); 2248 2249 // If we have declared a member function template or static data member 2250 // template, set the access of the templated declaration as well. 2251 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2252 FunTmpl->getTemplatedDecl()->setAccess(AS); 2253 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2254 VarTmpl->getTemplatedDecl()->setAccess(AS); 2255 } 2256 2257 if (VS.isOverrideSpecified()) 2258 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2259 if (VS.isFinalSpecified()) 2260 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2261 VS.isFinalSpelledSealed())); 2262 2263 if (VS.getLastLocation().isValid()) { 2264 // Update the end location of a method that has a virt-specifiers. 2265 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2266 MD->setRangeEnd(VS.getLastLocation()); 2267 } 2268 2269 CheckOverrideControl(Member); 2270 2271 assert((Name || isInstField) && "No identifier for non-field ?"); 2272 2273 if (isInstField) { 2274 FieldDecl *FD = cast<FieldDecl>(Member); 2275 FieldCollector->Add(FD); 2276 2277 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2278 // Remember all explicit private FieldDecls that have a name, no side 2279 // effects and are not part of a dependent type declaration. 2280 if (!FD->isImplicit() && FD->getDeclName() && 2281 FD->getAccess() == AS_private && 2282 !FD->hasAttr<UnusedAttr>() && 2283 !FD->getParent()->isDependentContext() && 2284 !InitializationHasSideEffects(*FD)) 2285 UnusedPrivateFields.insert(FD); 2286 } 2287 } 2288 2289 return Member; 2290 } 2291 2292 namespace { 2293 class UninitializedFieldVisitor 2294 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2295 Sema &S; 2296 // List of Decls to generate a warning on. Also remove Decls that become 2297 // initialized. 2298 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2299 // List of base classes of the record. Classes are removed after their 2300 // initializers. 2301 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 2302 // Vector of decls to be removed from the Decl set prior to visiting the 2303 // nodes. These Decls may have been initialized in the prior initializer. 2304 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2305 // If non-null, add a note to the warning pointing back to the constructor. 2306 const CXXConstructorDecl *Constructor; 2307 // Variables to hold state when processing an initializer list. When 2308 // InitList is true, special case initialization of FieldDecls matching 2309 // InitListFieldDecl. 2310 bool InitList; 2311 FieldDecl *InitListFieldDecl; 2312 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2313 2314 public: 2315 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2316 UninitializedFieldVisitor(Sema &S, 2317 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 2318 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 2319 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 2320 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 2321 2322 // Returns true if the use of ME is not an uninitialized use. 2323 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2324 bool CheckReferenceOnly) { 2325 llvm::SmallVector<FieldDecl*, 4> Fields; 2326 bool ReferenceField = false; 2327 while (ME) { 2328 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2329 if (!FD) 2330 return false; 2331 Fields.push_back(FD); 2332 if (FD->getType()->isReferenceType()) 2333 ReferenceField = true; 2334 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2335 } 2336 2337 // Binding a reference to an unintialized field is not an 2338 // uninitialized use. 2339 if (CheckReferenceOnly && !ReferenceField) 2340 return true; 2341 2342 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2343 // Discard the first field since it is the field decl that is being 2344 // initialized. 2345 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2346 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2347 } 2348 2349 for (auto UsedIter = UsedFieldIndex.begin(), 2350 UsedEnd = UsedFieldIndex.end(), 2351 OrigIter = InitFieldIndex.begin(), 2352 OrigEnd = InitFieldIndex.end(); 2353 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2354 if (*UsedIter < *OrigIter) 2355 return true; 2356 if (*UsedIter > *OrigIter) 2357 break; 2358 } 2359 2360 return false; 2361 } 2362 2363 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2364 bool AddressOf) { 2365 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2366 return; 2367 2368 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2369 // or union. 2370 MemberExpr *FieldME = ME; 2371 2372 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2373 2374 Expr *Base = ME; 2375 while (MemberExpr *SubME = 2376 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 2377 2378 if (isa<VarDecl>(SubME->getMemberDecl())) 2379 return; 2380 2381 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2382 if (!FD->isAnonymousStructOrUnion()) 2383 FieldME = SubME; 2384 2385 if (!FieldME->getType().isPODType(S.Context)) 2386 AllPODFields = false; 2387 2388 Base = SubME->getBase(); 2389 } 2390 2391 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 2392 return; 2393 2394 if (AddressOf && AllPODFields) 2395 return; 2396 2397 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2398 2399 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 2400 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 2401 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 2402 } 2403 2404 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 2405 QualType T = BaseCast->getType(); 2406 if (T->isPointerType() && 2407 BaseClasses.count(T->getPointeeType())) { 2408 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 2409 << T->getPointeeType() << FoundVD; 2410 } 2411 } 2412 } 2413 2414 if (!Decls.count(FoundVD)) 2415 return; 2416 2417 const bool IsReference = FoundVD->getType()->isReferenceType(); 2418 2419 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2420 // Special checking for initializer lists. 2421 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2422 return; 2423 } 2424 } else { 2425 // Prevent double warnings on use of unbounded references. 2426 if (CheckReferenceOnly && !IsReference) 2427 return; 2428 } 2429 2430 unsigned diag = IsReference 2431 ? diag::warn_reference_field_is_uninit 2432 : diag::warn_field_is_uninit; 2433 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2434 if (Constructor) 2435 S.Diag(Constructor->getLocation(), 2436 diag::note_uninit_in_this_constructor) 2437 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2438 2439 } 2440 2441 void HandleValue(Expr *E, bool AddressOf) { 2442 E = E->IgnoreParens(); 2443 2444 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2445 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2446 AddressOf /*AddressOf*/); 2447 return; 2448 } 2449 2450 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2451 Visit(CO->getCond()); 2452 HandleValue(CO->getTrueExpr(), AddressOf); 2453 HandleValue(CO->getFalseExpr(), AddressOf); 2454 return; 2455 } 2456 2457 if (BinaryConditionalOperator *BCO = 2458 dyn_cast<BinaryConditionalOperator>(E)) { 2459 Visit(BCO->getCond()); 2460 HandleValue(BCO->getFalseExpr(), AddressOf); 2461 return; 2462 } 2463 2464 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2465 HandleValue(OVE->getSourceExpr(), AddressOf); 2466 return; 2467 } 2468 2469 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2470 switch (BO->getOpcode()) { 2471 default: 2472 break; 2473 case(BO_PtrMemD): 2474 case(BO_PtrMemI): 2475 HandleValue(BO->getLHS(), AddressOf); 2476 Visit(BO->getRHS()); 2477 return; 2478 case(BO_Comma): 2479 Visit(BO->getLHS()); 2480 HandleValue(BO->getRHS(), AddressOf); 2481 return; 2482 } 2483 } 2484 2485 Visit(E); 2486 } 2487 2488 void CheckInitListExpr(InitListExpr *ILE) { 2489 InitFieldIndex.push_back(0); 2490 for (auto Child : ILE->children()) { 2491 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2492 CheckInitListExpr(SubList); 2493 } else { 2494 Visit(Child); 2495 } 2496 ++InitFieldIndex.back(); 2497 } 2498 InitFieldIndex.pop_back(); 2499 } 2500 2501 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2502 FieldDecl *Field, const Type *BaseClass) { 2503 // Remove Decls that may have been initialized in the previous 2504 // initializer. 2505 for (ValueDecl* VD : DeclsToRemove) 2506 Decls.erase(VD); 2507 DeclsToRemove.clear(); 2508 2509 Constructor = FieldConstructor; 2510 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2511 2512 if (ILE && Field) { 2513 InitList = true; 2514 InitListFieldDecl = Field; 2515 InitFieldIndex.clear(); 2516 CheckInitListExpr(ILE); 2517 } else { 2518 InitList = false; 2519 Visit(E); 2520 } 2521 2522 if (Field) 2523 Decls.erase(Field); 2524 if (BaseClass) 2525 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 2526 } 2527 2528 void VisitMemberExpr(MemberExpr *ME) { 2529 // All uses of unbounded reference fields will warn. 2530 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2531 } 2532 2533 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2534 if (E->getCastKind() == CK_LValueToRValue) { 2535 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2536 return; 2537 } 2538 2539 Inherited::VisitImplicitCastExpr(E); 2540 } 2541 2542 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2543 if (E->getConstructor()->isCopyConstructor()) { 2544 Expr *ArgExpr = E->getArg(0); 2545 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2546 if (ILE->getNumInits() == 1) 2547 ArgExpr = ILE->getInit(0); 2548 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2549 if (ICE->getCastKind() == CK_NoOp) 2550 ArgExpr = ICE->getSubExpr(); 2551 HandleValue(ArgExpr, false /*AddressOf*/); 2552 return; 2553 } 2554 Inherited::VisitCXXConstructExpr(E); 2555 } 2556 2557 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2558 Expr *Callee = E->getCallee(); 2559 if (isa<MemberExpr>(Callee)) { 2560 HandleValue(Callee, false /*AddressOf*/); 2561 for (auto Arg : E->arguments()) 2562 Visit(Arg); 2563 return; 2564 } 2565 2566 Inherited::VisitCXXMemberCallExpr(E); 2567 } 2568 2569 void VisitCallExpr(CallExpr *E) { 2570 // Treat std::move as a use. 2571 if (E->getNumArgs() == 1) { 2572 if (FunctionDecl *FD = E->getDirectCallee()) { 2573 if (FD->isInStdNamespace() && FD->getIdentifier() && 2574 FD->getIdentifier()->isStr("move")) { 2575 HandleValue(E->getArg(0), false /*AddressOf*/); 2576 return; 2577 } 2578 } 2579 } 2580 2581 Inherited::VisitCallExpr(E); 2582 } 2583 2584 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2585 Expr *Callee = E->getCallee(); 2586 2587 if (isa<UnresolvedLookupExpr>(Callee)) 2588 return Inherited::VisitCXXOperatorCallExpr(E); 2589 2590 Visit(Callee); 2591 for (auto Arg : E->arguments()) 2592 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2593 } 2594 2595 void VisitBinaryOperator(BinaryOperator *E) { 2596 // If a field assignment is detected, remove the field from the 2597 // uninitiailized field set. 2598 if (E->getOpcode() == BO_Assign) 2599 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2600 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2601 if (!FD->getType()->isReferenceType()) 2602 DeclsToRemove.push_back(FD); 2603 2604 if (E->isCompoundAssignmentOp()) { 2605 HandleValue(E->getLHS(), false /*AddressOf*/); 2606 Visit(E->getRHS()); 2607 return; 2608 } 2609 2610 Inherited::VisitBinaryOperator(E); 2611 } 2612 2613 void VisitUnaryOperator(UnaryOperator *E) { 2614 if (E->isIncrementDecrementOp()) { 2615 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2616 return; 2617 } 2618 if (E->getOpcode() == UO_AddrOf) { 2619 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2620 HandleValue(ME->getBase(), true /*AddressOf*/); 2621 return; 2622 } 2623 } 2624 2625 Inherited::VisitUnaryOperator(E); 2626 } 2627 }; 2628 2629 // Diagnose value-uses of fields to initialize themselves, e.g. 2630 // foo(foo) 2631 // where foo is not also a parameter to the constructor. 2632 // Also diagnose across field uninitialized use such as 2633 // x(y), y(x) 2634 // TODO: implement -Wuninitialized and fold this into that framework. 2635 static void DiagnoseUninitializedFields( 2636 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2637 2638 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2639 Constructor->getLocation())) { 2640 return; 2641 } 2642 2643 if (Constructor->isInvalidDecl()) 2644 return; 2645 2646 const CXXRecordDecl *RD = Constructor->getParent(); 2647 2648 if (RD->getDescribedClassTemplate()) 2649 return; 2650 2651 // Holds fields that are uninitialized. 2652 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2653 2654 // At the beginning, all fields are uninitialized. 2655 for (auto *I : RD->decls()) { 2656 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2657 UninitializedFields.insert(FD); 2658 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2659 UninitializedFields.insert(IFD->getAnonField()); 2660 } 2661 } 2662 2663 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 2664 for (auto I : RD->bases()) 2665 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 2666 2667 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2668 return; 2669 2670 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2671 UninitializedFields, 2672 UninitializedBaseClasses); 2673 2674 for (const auto *FieldInit : Constructor->inits()) { 2675 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2676 break; 2677 2678 Expr *InitExpr = FieldInit->getInit(); 2679 if (!InitExpr) 2680 continue; 2681 2682 if (CXXDefaultInitExpr *Default = 2683 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2684 InitExpr = Default->getExpr(); 2685 if (!InitExpr) 2686 continue; 2687 // In class initializers will point to the constructor. 2688 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2689 FieldInit->getAnyMember(), 2690 FieldInit->getBaseClass()); 2691 } else { 2692 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2693 FieldInit->getAnyMember(), 2694 FieldInit->getBaseClass()); 2695 } 2696 } 2697 } 2698 } // namespace 2699 2700 /// \brief Enter a new C++ default initializer scope. After calling this, the 2701 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2702 /// parsing or instantiating the initializer failed. 2703 void Sema::ActOnStartCXXInClassMemberInitializer() { 2704 // Create a synthetic function scope to represent the call to the constructor 2705 // that notionally surrounds a use of this initializer. 2706 PushFunctionScope(); 2707 } 2708 2709 /// \brief This is invoked after parsing an in-class initializer for a 2710 /// non-static C++ class member, and after instantiating an in-class initializer 2711 /// in a class template. Such actions are deferred until the class is complete. 2712 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2713 SourceLocation InitLoc, 2714 Expr *InitExpr) { 2715 // Pop the notional constructor scope we created earlier. 2716 PopFunctionScopeInfo(nullptr, D); 2717 2718 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2719 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 2720 "must set init style when field is created"); 2721 2722 if (!InitExpr) { 2723 D->setInvalidDecl(); 2724 if (FD) 2725 FD->removeInClassInitializer(); 2726 return; 2727 } 2728 2729 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2730 FD->setInvalidDecl(); 2731 FD->removeInClassInitializer(); 2732 return; 2733 } 2734 2735 ExprResult Init = InitExpr; 2736 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2737 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2738 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2739 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2740 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2741 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2742 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2743 if (Init.isInvalid()) { 2744 FD->setInvalidDecl(); 2745 return; 2746 } 2747 } 2748 2749 // C++11 [class.base.init]p7: 2750 // The initialization of each base and member constitutes a 2751 // full-expression. 2752 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2753 if (Init.isInvalid()) { 2754 FD->setInvalidDecl(); 2755 return; 2756 } 2757 2758 InitExpr = Init.get(); 2759 2760 FD->setInClassInitializer(InitExpr); 2761 } 2762 2763 /// \brief Find the direct and/or virtual base specifiers that 2764 /// correspond to the given base type, for use in base initialization 2765 /// within a constructor. 2766 static bool FindBaseInitializer(Sema &SemaRef, 2767 CXXRecordDecl *ClassDecl, 2768 QualType BaseType, 2769 const CXXBaseSpecifier *&DirectBaseSpec, 2770 const CXXBaseSpecifier *&VirtualBaseSpec) { 2771 // First, check for a direct base class. 2772 DirectBaseSpec = nullptr; 2773 for (const auto &Base : ClassDecl->bases()) { 2774 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2775 // We found a direct base of this type. That's what we're 2776 // initializing. 2777 DirectBaseSpec = &Base; 2778 break; 2779 } 2780 } 2781 2782 // Check for a virtual base class. 2783 // FIXME: We might be able to short-circuit this if we know in advance that 2784 // there are no virtual bases. 2785 VirtualBaseSpec = nullptr; 2786 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2787 // We haven't found a base yet; search the class hierarchy for a 2788 // virtual base class. 2789 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2790 /*DetectVirtual=*/false); 2791 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2792 BaseType, Paths)) { 2793 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2794 Path != Paths.end(); ++Path) { 2795 if (Path->back().Base->isVirtual()) { 2796 VirtualBaseSpec = Path->back().Base; 2797 break; 2798 } 2799 } 2800 } 2801 } 2802 2803 return DirectBaseSpec || VirtualBaseSpec; 2804 } 2805 2806 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2807 MemInitResult 2808 Sema::ActOnMemInitializer(Decl *ConstructorD, 2809 Scope *S, 2810 CXXScopeSpec &SS, 2811 IdentifierInfo *MemberOrBase, 2812 ParsedType TemplateTypeTy, 2813 const DeclSpec &DS, 2814 SourceLocation IdLoc, 2815 Expr *InitList, 2816 SourceLocation EllipsisLoc) { 2817 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2818 DS, IdLoc, InitList, 2819 EllipsisLoc); 2820 } 2821 2822 /// \brief Handle a C++ member initializer using parentheses syntax. 2823 MemInitResult 2824 Sema::ActOnMemInitializer(Decl *ConstructorD, 2825 Scope *S, 2826 CXXScopeSpec &SS, 2827 IdentifierInfo *MemberOrBase, 2828 ParsedType TemplateTypeTy, 2829 const DeclSpec &DS, 2830 SourceLocation IdLoc, 2831 SourceLocation LParenLoc, 2832 ArrayRef<Expr *> Args, 2833 SourceLocation RParenLoc, 2834 SourceLocation EllipsisLoc) { 2835 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2836 Args, RParenLoc); 2837 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2838 DS, IdLoc, List, EllipsisLoc); 2839 } 2840 2841 namespace { 2842 2843 // Callback to only accept typo corrections that can be a valid C++ member 2844 // intializer: either a non-static field member or a base class. 2845 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2846 public: 2847 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2848 : ClassDecl(ClassDecl) {} 2849 2850 bool ValidateCandidate(const TypoCorrection &candidate) override { 2851 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2852 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2853 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2854 return isa<TypeDecl>(ND); 2855 } 2856 return false; 2857 } 2858 2859 private: 2860 CXXRecordDecl *ClassDecl; 2861 }; 2862 2863 } 2864 2865 /// \brief Handle a C++ member initializer. 2866 MemInitResult 2867 Sema::BuildMemInitializer(Decl *ConstructorD, 2868 Scope *S, 2869 CXXScopeSpec &SS, 2870 IdentifierInfo *MemberOrBase, 2871 ParsedType TemplateTypeTy, 2872 const DeclSpec &DS, 2873 SourceLocation IdLoc, 2874 Expr *Init, 2875 SourceLocation EllipsisLoc) { 2876 ExprResult Res = CorrectDelayedTyposInExpr(Init); 2877 if (!Res.isUsable()) 2878 return true; 2879 Init = Res.get(); 2880 2881 if (!ConstructorD) 2882 return true; 2883 2884 AdjustDeclIfTemplate(ConstructorD); 2885 2886 CXXConstructorDecl *Constructor 2887 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2888 if (!Constructor) { 2889 // The user wrote a constructor initializer on a function that is 2890 // not a C++ constructor. Ignore the error for now, because we may 2891 // have more member initializers coming; we'll diagnose it just 2892 // once in ActOnMemInitializers. 2893 return true; 2894 } 2895 2896 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2897 2898 // C++ [class.base.init]p2: 2899 // Names in a mem-initializer-id are looked up in the scope of the 2900 // constructor's class and, if not found in that scope, are looked 2901 // up in the scope containing the constructor's definition. 2902 // [Note: if the constructor's class contains a member with the 2903 // same name as a direct or virtual base class of the class, a 2904 // mem-initializer-id naming the member or base class and composed 2905 // of a single identifier refers to the class member. A 2906 // mem-initializer-id for the hidden base class may be specified 2907 // using a qualified name. ] 2908 if (!SS.getScopeRep() && !TemplateTypeTy) { 2909 // Look for a member, first. 2910 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2911 if (!Result.empty()) { 2912 ValueDecl *Member; 2913 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2914 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2915 if (EllipsisLoc.isValid()) 2916 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2917 << MemberOrBase 2918 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2919 2920 return BuildMemberInitializer(Member, Init, IdLoc); 2921 } 2922 } 2923 } 2924 // It didn't name a member, so see if it names a class. 2925 QualType BaseType; 2926 TypeSourceInfo *TInfo = nullptr; 2927 2928 if (TemplateTypeTy) { 2929 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2930 } else if (DS.getTypeSpecType() == TST_decltype) { 2931 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2932 } else { 2933 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2934 LookupParsedName(R, S, &SS); 2935 2936 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2937 if (!TyD) { 2938 if (R.isAmbiguous()) return true; 2939 2940 // We don't want access-control diagnostics here. 2941 R.suppressDiagnostics(); 2942 2943 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2944 bool NotUnknownSpecialization = false; 2945 DeclContext *DC = computeDeclContext(SS, false); 2946 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2947 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2948 2949 if (!NotUnknownSpecialization) { 2950 // When the scope specifier can refer to a member of an unknown 2951 // specialization, we take it as a type name. 2952 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2953 SS.getWithLocInContext(Context), 2954 *MemberOrBase, IdLoc); 2955 if (BaseType.isNull()) 2956 return true; 2957 2958 R.clear(); 2959 R.setLookupName(MemberOrBase); 2960 } 2961 } 2962 2963 // If no results were found, try to correct typos. 2964 TypoCorrection Corr; 2965 if (R.empty() && BaseType.isNull() && 2966 (Corr = CorrectTypo( 2967 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2968 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2969 CTK_ErrorRecovery, ClassDecl))) { 2970 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2971 // We have found a non-static data member with a similar 2972 // name to what was typed; complain and initialize that 2973 // member. 2974 diagnoseTypo(Corr, 2975 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2976 << MemberOrBase << true); 2977 return BuildMemberInitializer(Member, Init, IdLoc); 2978 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2979 const CXXBaseSpecifier *DirectBaseSpec; 2980 const CXXBaseSpecifier *VirtualBaseSpec; 2981 if (FindBaseInitializer(*this, ClassDecl, 2982 Context.getTypeDeclType(Type), 2983 DirectBaseSpec, VirtualBaseSpec)) { 2984 // We have found a direct or virtual base class with a 2985 // similar name to what was typed; complain and initialize 2986 // that base class. 2987 diagnoseTypo(Corr, 2988 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2989 << MemberOrBase << false, 2990 PDiag() /*Suppress note, we provide our own.*/); 2991 2992 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2993 : VirtualBaseSpec; 2994 Diag(BaseSpec->getLocStart(), 2995 diag::note_base_class_specified_here) 2996 << BaseSpec->getType() 2997 << BaseSpec->getSourceRange(); 2998 2999 TyD = Type; 3000 } 3001 } 3002 } 3003 3004 if (!TyD && BaseType.isNull()) { 3005 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3006 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3007 return true; 3008 } 3009 } 3010 3011 if (BaseType.isNull()) { 3012 BaseType = Context.getTypeDeclType(TyD); 3013 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3014 if (SS.isSet()) 3015 // FIXME: preserve source range information 3016 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3017 BaseType); 3018 } 3019 } 3020 3021 if (!TInfo) 3022 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3023 3024 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3025 } 3026 3027 /// Checks a member initializer expression for cases where reference (or 3028 /// pointer) members are bound to by-value parameters (or their addresses). 3029 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3030 Expr *Init, 3031 SourceLocation IdLoc) { 3032 QualType MemberTy = Member->getType(); 3033 3034 // We only handle pointers and references currently. 3035 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3036 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3037 return; 3038 3039 const bool IsPointer = MemberTy->isPointerType(); 3040 if (IsPointer) { 3041 if (const UnaryOperator *Op 3042 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3043 // The only case we're worried about with pointers requires taking the 3044 // address. 3045 if (Op->getOpcode() != UO_AddrOf) 3046 return; 3047 3048 Init = Op->getSubExpr(); 3049 } else { 3050 // We only handle address-of expression initializers for pointers. 3051 return; 3052 } 3053 } 3054 3055 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3056 // We only warn when referring to a non-reference parameter declaration. 3057 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3058 if (!Parameter || Parameter->getType()->isReferenceType()) 3059 return; 3060 3061 S.Diag(Init->getExprLoc(), 3062 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3063 : diag::warn_bind_ref_member_to_parameter) 3064 << Member << Parameter << Init->getSourceRange(); 3065 } else { 3066 // Other initializers are fine. 3067 return; 3068 } 3069 3070 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3071 << (unsigned)IsPointer; 3072 } 3073 3074 MemInitResult 3075 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3076 SourceLocation IdLoc) { 3077 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3078 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3079 assert((DirectMember || IndirectMember) && 3080 "Member must be a FieldDecl or IndirectFieldDecl"); 3081 3082 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3083 return true; 3084 3085 if (Member->isInvalidDecl()) 3086 return true; 3087 3088 MultiExprArg Args; 3089 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3090 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3091 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3092 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3093 } else { 3094 // Template instantiation doesn't reconstruct ParenListExprs for us. 3095 Args = Init; 3096 } 3097 3098 SourceRange InitRange = Init->getSourceRange(); 3099 3100 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3101 // Can't check initialization for a member of dependent type or when 3102 // any of the arguments are type-dependent expressions. 3103 DiscardCleanupsInEvaluationContext(); 3104 } else { 3105 bool InitList = false; 3106 if (isa<InitListExpr>(Init)) { 3107 InitList = true; 3108 Args = Init; 3109 } 3110 3111 // Initialize the member. 3112 InitializedEntity MemberEntity = 3113 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3114 : InitializedEntity::InitializeMember(IndirectMember, 3115 nullptr); 3116 InitializationKind Kind = 3117 InitList ? InitializationKind::CreateDirectList(IdLoc) 3118 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3119 InitRange.getEnd()); 3120 3121 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3122 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3123 nullptr); 3124 if (MemberInit.isInvalid()) 3125 return true; 3126 3127 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3128 3129 // C++11 [class.base.init]p7: 3130 // The initialization of each base and member constitutes a 3131 // full-expression. 3132 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3133 if (MemberInit.isInvalid()) 3134 return true; 3135 3136 Init = MemberInit.get(); 3137 } 3138 3139 if (DirectMember) { 3140 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3141 InitRange.getBegin(), Init, 3142 InitRange.getEnd()); 3143 } else { 3144 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3145 InitRange.getBegin(), Init, 3146 InitRange.getEnd()); 3147 } 3148 } 3149 3150 MemInitResult 3151 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3152 CXXRecordDecl *ClassDecl) { 3153 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3154 if (!LangOpts.CPlusPlus11) 3155 return Diag(NameLoc, diag::err_delegating_ctor) 3156 << TInfo->getTypeLoc().getLocalSourceRange(); 3157 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3158 3159 bool InitList = true; 3160 MultiExprArg Args = Init; 3161 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3162 InitList = false; 3163 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3164 } 3165 3166 SourceRange InitRange = Init->getSourceRange(); 3167 // Initialize the object. 3168 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3169 QualType(ClassDecl->getTypeForDecl(), 0)); 3170 InitializationKind Kind = 3171 InitList ? InitializationKind::CreateDirectList(NameLoc) 3172 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3173 InitRange.getEnd()); 3174 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3175 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3176 Args, nullptr); 3177 if (DelegationInit.isInvalid()) 3178 return true; 3179 3180 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3181 "Delegating constructor with no target?"); 3182 3183 // C++11 [class.base.init]p7: 3184 // The initialization of each base and member constitutes a 3185 // full-expression. 3186 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3187 InitRange.getBegin()); 3188 if (DelegationInit.isInvalid()) 3189 return true; 3190 3191 // If we are in a dependent context, template instantiation will 3192 // perform this type-checking again. Just save the arguments that we 3193 // received in a ParenListExpr. 3194 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3195 // of the information that we have about the base 3196 // initializer. However, deconstructing the ASTs is a dicey process, 3197 // and this approach is far more likely to get the corner cases right. 3198 if (CurContext->isDependentContext()) 3199 DelegationInit = Init; 3200 3201 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3202 DelegationInit.getAs<Expr>(), 3203 InitRange.getEnd()); 3204 } 3205 3206 MemInitResult 3207 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3208 Expr *Init, CXXRecordDecl *ClassDecl, 3209 SourceLocation EllipsisLoc) { 3210 SourceLocation BaseLoc 3211 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3212 3213 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3214 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3215 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3216 3217 // C++ [class.base.init]p2: 3218 // [...] Unless the mem-initializer-id names a nonstatic data 3219 // member of the constructor's class or a direct or virtual base 3220 // of that class, the mem-initializer is ill-formed. A 3221 // mem-initializer-list can initialize a base class using any 3222 // name that denotes that base class type. 3223 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3224 3225 SourceRange InitRange = Init->getSourceRange(); 3226 if (EllipsisLoc.isValid()) { 3227 // This is a pack expansion. 3228 if (!BaseType->containsUnexpandedParameterPack()) { 3229 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3230 << SourceRange(BaseLoc, InitRange.getEnd()); 3231 3232 EllipsisLoc = SourceLocation(); 3233 } 3234 } else { 3235 // Check for any unexpanded parameter packs. 3236 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3237 return true; 3238 3239 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3240 return true; 3241 } 3242 3243 // Check for direct and virtual base classes. 3244 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3245 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3246 if (!Dependent) { 3247 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3248 BaseType)) 3249 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3250 3251 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3252 VirtualBaseSpec); 3253 3254 // C++ [base.class.init]p2: 3255 // Unless the mem-initializer-id names a nonstatic data member of the 3256 // constructor's class or a direct or virtual base of that class, the 3257 // mem-initializer is ill-formed. 3258 if (!DirectBaseSpec && !VirtualBaseSpec) { 3259 // If the class has any dependent bases, then it's possible that 3260 // one of those types will resolve to the same type as 3261 // BaseType. Therefore, just treat this as a dependent base 3262 // class initialization. FIXME: Should we try to check the 3263 // initialization anyway? It seems odd. 3264 if (ClassDecl->hasAnyDependentBases()) 3265 Dependent = true; 3266 else 3267 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3268 << BaseType << Context.getTypeDeclType(ClassDecl) 3269 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3270 } 3271 } 3272 3273 if (Dependent) { 3274 DiscardCleanupsInEvaluationContext(); 3275 3276 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3277 /*IsVirtual=*/false, 3278 InitRange.getBegin(), Init, 3279 InitRange.getEnd(), EllipsisLoc); 3280 } 3281 3282 // C++ [base.class.init]p2: 3283 // If a mem-initializer-id is ambiguous because it designates both 3284 // a direct non-virtual base class and an inherited virtual base 3285 // class, the mem-initializer is ill-formed. 3286 if (DirectBaseSpec && VirtualBaseSpec) 3287 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3288 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3289 3290 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3291 if (!BaseSpec) 3292 BaseSpec = VirtualBaseSpec; 3293 3294 // Initialize the base. 3295 bool InitList = true; 3296 MultiExprArg Args = Init; 3297 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3298 InitList = false; 3299 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3300 } 3301 3302 InitializedEntity BaseEntity = 3303 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3304 InitializationKind Kind = 3305 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3306 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3307 InitRange.getEnd()); 3308 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3309 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3310 if (BaseInit.isInvalid()) 3311 return true; 3312 3313 // C++11 [class.base.init]p7: 3314 // The initialization of each base and member constitutes a 3315 // full-expression. 3316 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3317 if (BaseInit.isInvalid()) 3318 return true; 3319 3320 // If we are in a dependent context, template instantiation will 3321 // perform this type-checking again. Just save the arguments that we 3322 // received in a ParenListExpr. 3323 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3324 // of the information that we have about the base 3325 // initializer. However, deconstructing the ASTs is a dicey process, 3326 // and this approach is far more likely to get the corner cases right. 3327 if (CurContext->isDependentContext()) 3328 BaseInit = Init; 3329 3330 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3331 BaseSpec->isVirtual(), 3332 InitRange.getBegin(), 3333 BaseInit.getAs<Expr>(), 3334 InitRange.getEnd(), EllipsisLoc); 3335 } 3336 3337 // Create a static_cast\<T&&>(expr). 3338 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3339 if (T.isNull()) T = E->getType(); 3340 QualType TargetType = SemaRef.BuildReferenceType( 3341 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3342 SourceLocation ExprLoc = E->getLocStart(); 3343 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3344 TargetType, ExprLoc); 3345 3346 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3347 SourceRange(ExprLoc, ExprLoc), 3348 E->getSourceRange()).get(); 3349 } 3350 3351 /// ImplicitInitializerKind - How an implicit base or member initializer should 3352 /// initialize its base or member. 3353 enum ImplicitInitializerKind { 3354 IIK_Default, 3355 IIK_Copy, 3356 IIK_Move, 3357 IIK_Inherit 3358 }; 3359 3360 static bool 3361 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3362 ImplicitInitializerKind ImplicitInitKind, 3363 CXXBaseSpecifier *BaseSpec, 3364 bool IsInheritedVirtualBase, 3365 CXXCtorInitializer *&CXXBaseInit) { 3366 InitializedEntity InitEntity 3367 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3368 IsInheritedVirtualBase); 3369 3370 ExprResult BaseInit; 3371 3372 switch (ImplicitInitKind) { 3373 case IIK_Inherit: { 3374 const CXXRecordDecl *Inherited = 3375 Constructor->getInheritedConstructor()->getParent(); 3376 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3377 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3378 // C++11 [class.inhctor]p8: 3379 // Each expression in the expression-list is of the form 3380 // static_cast<T&&>(p), where p is the name of the corresponding 3381 // constructor parameter and T is the declared type of p. 3382 SmallVector<Expr*, 16> Args; 3383 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3384 ParmVarDecl *PD = Constructor->getParamDecl(I); 3385 ExprResult ArgExpr = 3386 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3387 VK_LValue, SourceLocation()); 3388 if (ArgExpr.isInvalid()) 3389 return true; 3390 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3391 } 3392 3393 InitializationKind InitKind = InitializationKind::CreateDirect( 3394 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3395 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3396 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3397 break; 3398 } 3399 } 3400 // Fall through. 3401 case IIK_Default: { 3402 InitializationKind InitKind 3403 = InitializationKind::CreateDefault(Constructor->getLocation()); 3404 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3405 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3406 break; 3407 } 3408 3409 case IIK_Move: 3410 case IIK_Copy: { 3411 bool Moving = ImplicitInitKind == IIK_Move; 3412 ParmVarDecl *Param = Constructor->getParamDecl(0); 3413 QualType ParamType = Param->getType().getNonReferenceType(); 3414 3415 Expr *CopyCtorArg = 3416 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3417 SourceLocation(), Param, false, 3418 Constructor->getLocation(), ParamType, 3419 VK_LValue, nullptr); 3420 3421 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3422 3423 // Cast to the base class to avoid ambiguities. 3424 QualType ArgTy = 3425 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3426 ParamType.getQualifiers()); 3427 3428 if (Moving) { 3429 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3430 } 3431 3432 CXXCastPath BasePath; 3433 BasePath.push_back(BaseSpec); 3434 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3435 CK_UncheckedDerivedToBase, 3436 Moving ? VK_XValue : VK_LValue, 3437 &BasePath).get(); 3438 3439 InitializationKind InitKind 3440 = InitializationKind::CreateDirect(Constructor->getLocation(), 3441 SourceLocation(), SourceLocation()); 3442 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3443 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3444 break; 3445 } 3446 } 3447 3448 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3449 if (BaseInit.isInvalid()) 3450 return true; 3451 3452 CXXBaseInit = 3453 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3454 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3455 SourceLocation()), 3456 BaseSpec->isVirtual(), 3457 SourceLocation(), 3458 BaseInit.getAs<Expr>(), 3459 SourceLocation(), 3460 SourceLocation()); 3461 3462 return false; 3463 } 3464 3465 static bool RefersToRValueRef(Expr *MemRef) { 3466 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3467 return Referenced->getType()->isRValueReferenceType(); 3468 } 3469 3470 static bool 3471 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3472 ImplicitInitializerKind ImplicitInitKind, 3473 FieldDecl *Field, IndirectFieldDecl *Indirect, 3474 CXXCtorInitializer *&CXXMemberInit) { 3475 if (Field->isInvalidDecl()) 3476 return true; 3477 3478 SourceLocation Loc = Constructor->getLocation(); 3479 3480 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3481 bool Moving = ImplicitInitKind == IIK_Move; 3482 ParmVarDecl *Param = Constructor->getParamDecl(0); 3483 QualType ParamType = Param->getType().getNonReferenceType(); 3484 3485 // Suppress copying zero-width bitfields. 3486 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3487 return false; 3488 3489 Expr *MemberExprBase = 3490 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3491 SourceLocation(), Param, false, 3492 Loc, ParamType, VK_LValue, nullptr); 3493 3494 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3495 3496 if (Moving) { 3497 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3498 } 3499 3500 // Build a reference to this field within the parameter. 3501 CXXScopeSpec SS; 3502 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3503 Sema::LookupMemberName); 3504 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3505 : cast<ValueDecl>(Field), AS_public); 3506 MemberLookup.resolveKind(); 3507 ExprResult CtorArg 3508 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3509 ParamType, Loc, 3510 /*IsArrow=*/false, 3511 SS, 3512 /*TemplateKWLoc=*/SourceLocation(), 3513 /*FirstQualifierInScope=*/nullptr, 3514 MemberLookup, 3515 /*TemplateArgs=*/nullptr); 3516 if (CtorArg.isInvalid()) 3517 return true; 3518 3519 // C++11 [class.copy]p15: 3520 // - if a member m has rvalue reference type T&&, it is direct-initialized 3521 // with static_cast<T&&>(x.m); 3522 if (RefersToRValueRef(CtorArg.get())) { 3523 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3524 } 3525 3526 // When the field we are copying is an array, create index variables for 3527 // each dimension of the array. We use these index variables to subscript 3528 // the source array, and other clients (e.g., CodeGen) will perform the 3529 // necessary iteration with these index variables. 3530 SmallVector<VarDecl *, 4> IndexVariables; 3531 QualType BaseType = Field->getType(); 3532 QualType SizeType = SemaRef.Context.getSizeType(); 3533 bool InitializingArray = false; 3534 while (const ConstantArrayType *Array 3535 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3536 InitializingArray = true; 3537 // Create the iteration variable for this array index. 3538 IdentifierInfo *IterationVarName = nullptr; 3539 { 3540 SmallString<8> Str; 3541 llvm::raw_svector_ostream OS(Str); 3542 OS << "__i" << IndexVariables.size(); 3543 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3544 } 3545 VarDecl *IterationVar 3546 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3547 IterationVarName, SizeType, 3548 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3549 SC_None); 3550 IndexVariables.push_back(IterationVar); 3551 3552 // Create a reference to the iteration variable. 3553 ExprResult IterationVarRef 3554 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3555 assert(!IterationVarRef.isInvalid() && 3556 "Reference to invented variable cannot fail!"); 3557 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3558 assert(!IterationVarRef.isInvalid() && 3559 "Conversion of invented variable cannot fail!"); 3560 3561 // Subscript the array with this iteration variable. 3562 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3563 IterationVarRef.get(), 3564 Loc); 3565 if (CtorArg.isInvalid()) 3566 return true; 3567 3568 BaseType = Array->getElementType(); 3569 } 3570 3571 // The array subscript expression is an lvalue, which is wrong for moving. 3572 if (Moving && InitializingArray) 3573 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3574 3575 // Construct the entity that we will be initializing. For an array, this 3576 // will be first element in the array, which may require several levels 3577 // of array-subscript entities. 3578 SmallVector<InitializedEntity, 4> Entities; 3579 Entities.reserve(1 + IndexVariables.size()); 3580 if (Indirect) 3581 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3582 else 3583 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3584 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3585 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3586 0, 3587 Entities.back())); 3588 3589 // Direct-initialize to use the copy constructor. 3590 InitializationKind InitKind = 3591 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3592 3593 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3594 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 3595 CtorArgE); 3596 3597 ExprResult MemberInit 3598 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3599 MultiExprArg(&CtorArgE, 1)); 3600 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3601 if (MemberInit.isInvalid()) 3602 return true; 3603 3604 if (Indirect) { 3605 assert(IndexVariables.size() == 0 && 3606 "Indirect field improperly initialized"); 3607 CXXMemberInit 3608 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3609 Loc, Loc, 3610 MemberInit.getAs<Expr>(), 3611 Loc); 3612 } else 3613 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3614 Loc, MemberInit.getAs<Expr>(), 3615 Loc, 3616 IndexVariables.data(), 3617 IndexVariables.size()); 3618 return false; 3619 } 3620 3621 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3622 "Unhandled implicit init kind!"); 3623 3624 QualType FieldBaseElementType = 3625 SemaRef.Context.getBaseElementType(Field->getType()); 3626 3627 if (FieldBaseElementType->isRecordType()) { 3628 InitializedEntity InitEntity 3629 = Indirect? InitializedEntity::InitializeMember(Indirect) 3630 : InitializedEntity::InitializeMember(Field); 3631 InitializationKind InitKind = 3632 InitializationKind::CreateDefault(Loc); 3633 3634 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3635 ExprResult MemberInit = 3636 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3637 3638 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3639 if (MemberInit.isInvalid()) 3640 return true; 3641 3642 if (Indirect) 3643 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3644 Indirect, Loc, 3645 Loc, 3646 MemberInit.get(), 3647 Loc); 3648 else 3649 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3650 Field, Loc, Loc, 3651 MemberInit.get(), 3652 Loc); 3653 return false; 3654 } 3655 3656 if (!Field->getParent()->isUnion()) { 3657 if (FieldBaseElementType->isReferenceType()) { 3658 SemaRef.Diag(Constructor->getLocation(), 3659 diag::err_uninitialized_member_in_ctor) 3660 << (int)Constructor->isImplicit() 3661 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3662 << 0 << Field->getDeclName(); 3663 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3664 return true; 3665 } 3666 3667 if (FieldBaseElementType.isConstQualified()) { 3668 SemaRef.Diag(Constructor->getLocation(), 3669 diag::err_uninitialized_member_in_ctor) 3670 << (int)Constructor->isImplicit() 3671 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3672 << 1 << Field->getDeclName(); 3673 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3674 return true; 3675 } 3676 } 3677 3678 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3679 FieldBaseElementType->isObjCRetainableType() && 3680 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3681 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3682 // ARC: 3683 // Default-initialize Objective-C pointers to NULL. 3684 CXXMemberInit 3685 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3686 Loc, Loc, 3687 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3688 Loc); 3689 return false; 3690 } 3691 3692 // Nothing to initialize. 3693 CXXMemberInit = nullptr; 3694 return false; 3695 } 3696 3697 namespace { 3698 struct BaseAndFieldInfo { 3699 Sema &S; 3700 CXXConstructorDecl *Ctor; 3701 bool AnyErrorsInInits; 3702 ImplicitInitializerKind IIK; 3703 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3704 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3705 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3706 3707 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3708 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3709 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3710 if (Generated && Ctor->isCopyConstructor()) 3711 IIK = IIK_Copy; 3712 else if (Generated && Ctor->isMoveConstructor()) 3713 IIK = IIK_Move; 3714 else if (Ctor->getInheritedConstructor()) 3715 IIK = IIK_Inherit; 3716 else 3717 IIK = IIK_Default; 3718 } 3719 3720 bool isImplicitCopyOrMove() const { 3721 switch (IIK) { 3722 case IIK_Copy: 3723 case IIK_Move: 3724 return true; 3725 3726 case IIK_Default: 3727 case IIK_Inherit: 3728 return false; 3729 } 3730 3731 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3732 } 3733 3734 bool addFieldInitializer(CXXCtorInitializer *Init) { 3735 AllToInit.push_back(Init); 3736 3737 // Check whether this initializer makes the field "used". 3738 if (Init->getInit()->HasSideEffects(S.Context)) 3739 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3740 3741 return false; 3742 } 3743 3744 bool isInactiveUnionMember(FieldDecl *Field) { 3745 RecordDecl *Record = Field->getParent(); 3746 if (!Record->isUnion()) 3747 return false; 3748 3749 if (FieldDecl *Active = 3750 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3751 return Active != Field->getCanonicalDecl(); 3752 3753 // In an implicit copy or move constructor, ignore any in-class initializer. 3754 if (isImplicitCopyOrMove()) 3755 return true; 3756 3757 // If there's no explicit initialization, the field is active only if it 3758 // has an in-class initializer... 3759 if (Field->hasInClassInitializer()) 3760 return false; 3761 // ... or it's an anonymous struct or union whose class has an in-class 3762 // initializer. 3763 if (!Field->isAnonymousStructOrUnion()) 3764 return true; 3765 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3766 return !FieldRD->hasInClassInitializer(); 3767 } 3768 3769 /// \brief Determine whether the given field is, or is within, a union member 3770 /// that is inactive (because there was an initializer given for a different 3771 /// member of the union, or because the union was not initialized at all). 3772 bool isWithinInactiveUnionMember(FieldDecl *Field, 3773 IndirectFieldDecl *Indirect) { 3774 if (!Indirect) 3775 return isInactiveUnionMember(Field); 3776 3777 for (auto *C : Indirect->chain()) { 3778 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3779 if (Field && isInactiveUnionMember(Field)) 3780 return true; 3781 } 3782 return false; 3783 } 3784 }; 3785 } 3786 3787 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3788 /// array type. 3789 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3790 if (T->isIncompleteArrayType()) 3791 return true; 3792 3793 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3794 if (!ArrayT->getSize()) 3795 return true; 3796 3797 T = ArrayT->getElementType(); 3798 } 3799 3800 return false; 3801 } 3802 3803 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3804 FieldDecl *Field, 3805 IndirectFieldDecl *Indirect = nullptr) { 3806 if (Field->isInvalidDecl()) 3807 return false; 3808 3809 // Overwhelmingly common case: we have a direct initializer for this field. 3810 if (CXXCtorInitializer *Init = 3811 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3812 return Info.addFieldInitializer(Init); 3813 3814 // C++11 [class.base.init]p8: 3815 // if the entity is a non-static data member that has a 3816 // brace-or-equal-initializer and either 3817 // -- the constructor's class is a union and no other variant member of that 3818 // union is designated by a mem-initializer-id or 3819 // -- the constructor's class is not a union, and, if the entity is a member 3820 // of an anonymous union, no other member of that union is designated by 3821 // a mem-initializer-id, 3822 // the entity is initialized as specified in [dcl.init]. 3823 // 3824 // We also apply the same rules to handle anonymous structs within anonymous 3825 // unions. 3826 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3827 return false; 3828 3829 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3830 ExprResult DIE = 3831 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3832 if (DIE.isInvalid()) 3833 return true; 3834 CXXCtorInitializer *Init; 3835 if (Indirect) 3836 Init = new (SemaRef.Context) 3837 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3838 SourceLocation(), DIE.get(), SourceLocation()); 3839 else 3840 Init = new (SemaRef.Context) 3841 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3842 SourceLocation(), DIE.get(), SourceLocation()); 3843 return Info.addFieldInitializer(Init); 3844 } 3845 3846 // Don't initialize incomplete or zero-length arrays. 3847 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3848 return false; 3849 3850 // Don't try to build an implicit initializer if there were semantic 3851 // errors in any of the initializers (and therefore we might be 3852 // missing some that the user actually wrote). 3853 if (Info.AnyErrorsInInits) 3854 return false; 3855 3856 CXXCtorInitializer *Init = nullptr; 3857 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3858 Indirect, Init)) 3859 return true; 3860 3861 if (!Init) 3862 return false; 3863 3864 return Info.addFieldInitializer(Init); 3865 } 3866 3867 bool 3868 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3869 CXXCtorInitializer *Initializer) { 3870 assert(Initializer->isDelegatingInitializer()); 3871 Constructor->setNumCtorInitializers(1); 3872 CXXCtorInitializer **initializer = 3873 new (Context) CXXCtorInitializer*[1]; 3874 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3875 Constructor->setCtorInitializers(initializer); 3876 3877 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3878 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3879 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3880 } 3881 3882 DelegatingCtorDecls.push_back(Constructor); 3883 3884 DiagnoseUninitializedFields(*this, Constructor); 3885 3886 return false; 3887 } 3888 3889 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3890 ArrayRef<CXXCtorInitializer *> Initializers) { 3891 if (Constructor->isDependentContext()) { 3892 // Just store the initializers as written, they will be checked during 3893 // instantiation. 3894 if (!Initializers.empty()) { 3895 Constructor->setNumCtorInitializers(Initializers.size()); 3896 CXXCtorInitializer **baseOrMemberInitializers = 3897 new (Context) CXXCtorInitializer*[Initializers.size()]; 3898 memcpy(baseOrMemberInitializers, Initializers.data(), 3899 Initializers.size() * sizeof(CXXCtorInitializer*)); 3900 Constructor->setCtorInitializers(baseOrMemberInitializers); 3901 } 3902 3903 // Let template instantiation know whether we had errors. 3904 if (AnyErrors) 3905 Constructor->setInvalidDecl(); 3906 3907 return false; 3908 } 3909 3910 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3911 3912 // We need to build the initializer AST according to order of construction 3913 // and not what user specified in the Initializers list. 3914 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3915 if (!ClassDecl) 3916 return true; 3917 3918 bool HadError = false; 3919 3920 for (unsigned i = 0; i < Initializers.size(); i++) { 3921 CXXCtorInitializer *Member = Initializers[i]; 3922 3923 if (Member->isBaseInitializer()) 3924 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3925 else { 3926 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3927 3928 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3929 for (auto *C : F->chain()) { 3930 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3931 if (FD && FD->getParent()->isUnion()) 3932 Info.ActiveUnionMember.insert(std::make_pair( 3933 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3934 } 3935 } else if (FieldDecl *FD = Member->getMember()) { 3936 if (FD->getParent()->isUnion()) 3937 Info.ActiveUnionMember.insert(std::make_pair( 3938 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3939 } 3940 } 3941 } 3942 3943 // Keep track of the direct virtual bases. 3944 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3945 for (auto &I : ClassDecl->bases()) { 3946 if (I.isVirtual()) 3947 DirectVBases.insert(&I); 3948 } 3949 3950 // Push virtual bases before others. 3951 for (auto &VBase : ClassDecl->vbases()) { 3952 if (CXXCtorInitializer *Value 3953 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3954 // [class.base.init]p7, per DR257: 3955 // A mem-initializer where the mem-initializer-id names a virtual base 3956 // class is ignored during execution of a constructor of any class that 3957 // is not the most derived class. 3958 if (ClassDecl->isAbstract()) { 3959 // FIXME: Provide a fixit to remove the base specifier. This requires 3960 // tracking the location of the associated comma for a base specifier. 3961 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3962 << VBase.getType() << ClassDecl; 3963 DiagnoseAbstractType(ClassDecl); 3964 } 3965 3966 Info.AllToInit.push_back(Value); 3967 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3968 // [class.base.init]p8, per DR257: 3969 // If a given [...] base class is not named by a mem-initializer-id 3970 // [...] and the entity is not a virtual base class of an abstract 3971 // class, then [...] the entity is default-initialized. 3972 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3973 CXXCtorInitializer *CXXBaseInit; 3974 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3975 &VBase, IsInheritedVirtualBase, 3976 CXXBaseInit)) { 3977 HadError = true; 3978 continue; 3979 } 3980 3981 Info.AllToInit.push_back(CXXBaseInit); 3982 } 3983 } 3984 3985 // Non-virtual bases. 3986 for (auto &Base : ClassDecl->bases()) { 3987 // Virtuals are in the virtual base list and already constructed. 3988 if (Base.isVirtual()) 3989 continue; 3990 3991 if (CXXCtorInitializer *Value 3992 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3993 Info.AllToInit.push_back(Value); 3994 } else if (!AnyErrors) { 3995 CXXCtorInitializer *CXXBaseInit; 3996 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3997 &Base, /*IsInheritedVirtualBase=*/false, 3998 CXXBaseInit)) { 3999 HadError = true; 4000 continue; 4001 } 4002 4003 Info.AllToInit.push_back(CXXBaseInit); 4004 } 4005 } 4006 4007 // Fields. 4008 for (auto *Mem : ClassDecl->decls()) { 4009 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4010 // C++ [class.bit]p2: 4011 // A declaration for a bit-field that omits the identifier declares an 4012 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4013 // initialized. 4014 if (F->isUnnamedBitfield()) 4015 continue; 4016 4017 // If we're not generating the implicit copy/move constructor, then we'll 4018 // handle anonymous struct/union fields based on their individual 4019 // indirect fields. 4020 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4021 continue; 4022 4023 if (CollectFieldInitializer(*this, Info, F)) 4024 HadError = true; 4025 continue; 4026 } 4027 4028 // Beyond this point, we only consider default initialization. 4029 if (Info.isImplicitCopyOrMove()) 4030 continue; 4031 4032 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4033 if (F->getType()->isIncompleteArrayType()) { 4034 assert(ClassDecl->hasFlexibleArrayMember() && 4035 "Incomplete array type is not valid"); 4036 continue; 4037 } 4038 4039 // Initialize each field of an anonymous struct individually. 4040 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4041 HadError = true; 4042 4043 continue; 4044 } 4045 } 4046 4047 unsigned NumInitializers = Info.AllToInit.size(); 4048 if (NumInitializers > 0) { 4049 Constructor->setNumCtorInitializers(NumInitializers); 4050 CXXCtorInitializer **baseOrMemberInitializers = 4051 new (Context) CXXCtorInitializer*[NumInitializers]; 4052 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4053 NumInitializers * sizeof(CXXCtorInitializer*)); 4054 Constructor->setCtorInitializers(baseOrMemberInitializers); 4055 4056 // Constructors implicitly reference the base and member 4057 // destructors. 4058 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4059 Constructor->getParent()); 4060 } 4061 4062 return HadError; 4063 } 4064 4065 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4066 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4067 const RecordDecl *RD = RT->getDecl(); 4068 if (RD->isAnonymousStructOrUnion()) { 4069 for (auto *Field : RD->fields()) 4070 PopulateKeysForFields(Field, IdealInits); 4071 return; 4072 } 4073 } 4074 IdealInits.push_back(Field->getCanonicalDecl()); 4075 } 4076 4077 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4078 return Context.getCanonicalType(BaseType).getTypePtr(); 4079 } 4080 4081 static const void *GetKeyForMember(ASTContext &Context, 4082 CXXCtorInitializer *Member) { 4083 if (!Member->isAnyMemberInitializer()) 4084 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4085 4086 return Member->getAnyMember()->getCanonicalDecl(); 4087 } 4088 4089 static void DiagnoseBaseOrMemInitializerOrder( 4090 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4091 ArrayRef<CXXCtorInitializer *> Inits) { 4092 if (Constructor->getDeclContext()->isDependentContext()) 4093 return; 4094 4095 // Don't check initializers order unless the warning is enabled at the 4096 // location of at least one initializer. 4097 bool ShouldCheckOrder = false; 4098 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4099 CXXCtorInitializer *Init = Inits[InitIndex]; 4100 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4101 Init->getSourceLocation())) { 4102 ShouldCheckOrder = true; 4103 break; 4104 } 4105 } 4106 if (!ShouldCheckOrder) 4107 return; 4108 4109 // Build the list of bases and members in the order that they'll 4110 // actually be initialized. The explicit initializers should be in 4111 // this same order but may be missing things. 4112 SmallVector<const void*, 32> IdealInitKeys; 4113 4114 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4115 4116 // 1. Virtual bases. 4117 for (const auto &VBase : ClassDecl->vbases()) 4118 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4119 4120 // 2. Non-virtual bases. 4121 for (const auto &Base : ClassDecl->bases()) { 4122 if (Base.isVirtual()) 4123 continue; 4124 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4125 } 4126 4127 // 3. Direct fields. 4128 for (auto *Field : ClassDecl->fields()) { 4129 if (Field->isUnnamedBitfield()) 4130 continue; 4131 4132 PopulateKeysForFields(Field, IdealInitKeys); 4133 } 4134 4135 unsigned NumIdealInits = IdealInitKeys.size(); 4136 unsigned IdealIndex = 0; 4137 4138 CXXCtorInitializer *PrevInit = nullptr; 4139 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4140 CXXCtorInitializer *Init = Inits[InitIndex]; 4141 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4142 4143 // Scan forward to try to find this initializer in the idealized 4144 // initializers list. 4145 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4146 if (InitKey == IdealInitKeys[IdealIndex]) 4147 break; 4148 4149 // If we didn't find this initializer, it must be because we 4150 // scanned past it on a previous iteration. That can only 4151 // happen if we're out of order; emit a warning. 4152 if (IdealIndex == NumIdealInits && PrevInit) { 4153 Sema::SemaDiagnosticBuilder D = 4154 SemaRef.Diag(PrevInit->getSourceLocation(), 4155 diag::warn_initializer_out_of_order); 4156 4157 if (PrevInit->isAnyMemberInitializer()) 4158 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4159 else 4160 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4161 4162 if (Init->isAnyMemberInitializer()) 4163 D << 0 << Init->getAnyMember()->getDeclName(); 4164 else 4165 D << 1 << Init->getTypeSourceInfo()->getType(); 4166 4167 // Move back to the initializer's location in the ideal list. 4168 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4169 if (InitKey == IdealInitKeys[IdealIndex]) 4170 break; 4171 4172 assert(IdealIndex != NumIdealInits && 4173 "initializer not found in initializer list"); 4174 } 4175 4176 PrevInit = Init; 4177 } 4178 } 4179 4180 namespace { 4181 bool CheckRedundantInit(Sema &S, 4182 CXXCtorInitializer *Init, 4183 CXXCtorInitializer *&PrevInit) { 4184 if (!PrevInit) { 4185 PrevInit = Init; 4186 return false; 4187 } 4188 4189 if (FieldDecl *Field = Init->getAnyMember()) 4190 S.Diag(Init->getSourceLocation(), 4191 diag::err_multiple_mem_initialization) 4192 << Field->getDeclName() 4193 << Init->getSourceRange(); 4194 else { 4195 const Type *BaseClass = Init->getBaseClass(); 4196 assert(BaseClass && "neither field nor base"); 4197 S.Diag(Init->getSourceLocation(), 4198 diag::err_multiple_base_initialization) 4199 << QualType(BaseClass, 0) 4200 << Init->getSourceRange(); 4201 } 4202 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4203 << 0 << PrevInit->getSourceRange(); 4204 4205 return true; 4206 } 4207 4208 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4209 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4210 4211 bool CheckRedundantUnionInit(Sema &S, 4212 CXXCtorInitializer *Init, 4213 RedundantUnionMap &Unions) { 4214 FieldDecl *Field = Init->getAnyMember(); 4215 RecordDecl *Parent = Field->getParent(); 4216 NamedDecl *Child = Field; 4217 4218 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4219 if (Parent->isUnion()) { 4220 UnionEntry &En = Unions[Parent]; 4221 if (En.first && En.first != Child) { 4222 S.Diag(Init->getSourceLocation(), 4223 diag::err_multiple_mem_union_initialization) 4224 << Field->getDeclName() 4225 << Init->getSourceRange(); 4226 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4227 << 0 << En.second->getSourceRange(); 4228 return true; 4229 } 4230 if (!En.first) { 4231 En.first = Child; 4232 En.second = Init; 4233 } 4234 if (!Parent->isAnonymousStructOrUnion()) 4235 return false; 4236 } 4237 4238 Child = Parent; 4239 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4240 } 4241 4242 return false; 4243 } 4244 } 4245 4246 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4247 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4248 SourceLocation ColonLoc, 4249 ArrayRef<CXXCtorInitializer*> MemInits, 4250 bool AnyErrors) { 4251 if (!ConstructorDecl) 4252 return; 4253 4254 AdjustDeclIfTemplate(ConstructorDecl); 4255 4256 CXXConstructorDecl *Constructor 4257 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4258 4259 if (!Constructor) { 4260 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4261 return; 4262 } 4263 4264 // Mapping for the duplicate initializers check. 4265 // For member initializers, this is keyed with a FieldDecl*. 4266 // For base initializers, this is keyed with a Type*. 4267 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4268 4269 // Mapping for the inconsistent anonymous-union initializers check. 4270 RedundantUnionMap MemberUnions; 4271 4272 bool HadError = false; 4273 for (unsigned i = 0; i < MemInits.size(); i++) { 4274 CXXCtorInitializer *Init = MemInits[i]; 4275 4276 // Set the source order index. 4277 Init->setSourceOrder(i); 4278 4279 if (Init->isAnyMemberInitializer()) { 4280 const void *Key = GetKeyForMember(Context, Init); 4281 if (CheckRedundantInit(*this, Init, Members[Key]) || 4282 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4283 HadError = true; 4284 } else if (Init->isBaseInitializer()) { 4285 const void *Key = GetKeyForMember(Context, Init); 4286 if (CheckRedundantInit(*this, Init, Members[Key])) 4287 HadError = true; 4288 } else { 4289 assert(Init->isDelegatingInitializer()); 4290 // This must be the only initializer 4291 if (MemInits.size() != 1) { 4292 Diag(Init->getSourceLocation(), 4293 diag::err_delegating_initializer_alone) 4294 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4295 // We will treat this as being the only initializer. 4296 } 4297 SetDelegatingInitializer(Constructor, MemInits[i]); 4298 // Return immediately as the initializer is set. 4299 return; 4300 } 4301 } 4302 4303 if (HadError) 4304 return; 4305 4306 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4307 4308 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4309 4310 DiagnoseUninitializedFields(*this, Constructor); 4311 } 4312 4313 void 4314 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4315 CXXRecordDecl *ClassDecl) { 4316 // Ignore dependent contexts. Also ignore unions, since their members never 4317 // have destructors implicitly called. 4318 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4319 return; 4320 4321 // FIXME: all the access-control diagnostics are positioned on the 4322 // field/base declaration. That's probably good; that said, the 4323 // user might reasonably want to know why the destructor is being 4324 // emitted, and we currently don't say. 4325 4326 // Non-static data members. 4327 for (auto *Field : ClassDecl->fields()) { 4328 if (Field->isInvalidDecl()) 4329 continue; 4330 4331 // Don't destroy incomplete or zero-length arrays. 4332 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4333 continue; 4334 4335 QualType FieldType = Context.getBaseElementType(Field->getType()); 4336 4337 const RecordType* RT = FieldType->getAs<RecordType>(); 4338 if (!RT) 4339 continue; 4340 4341 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4342 if (FieldClassDecl->isInvalidDecl()) 4343 continue; 4344 if (FieldClassDecl->hasIrrelevantDestructor()) 4345 continue; 4346 // The destructor for an implicit anonymous union member is never invoked. 4347 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4348 continue; 4349 4350 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4351 assert(Dtor && "No dtor found for FieldClassDecl!"); 4352 CheckDestructorAccess(Field->getLocation(), Dtor, 4353 PDiag(diag::err_access_dtor_field) 4354 << Field->getDeclName() 4355 << FieldType); 4356 4357 MarkFunctionReferenced(Location, Dtor); 4358 DiagnoseUseOfDecl(Dtor, Location); 4359 } 4360 4361 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4362 4363 // Bases. 4364 for (const auto &Base : ClassDecl->bases()) { 4365 // Bases are always records in a well-formed non-dependent class. 4366 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4367 4368 // Remember direct virtual bases. 4369 if (Base.isVirtual()) 4370 DirectVirtualBases.insert(RT); 4371 4372 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4373 // If our base class is invalid, we probably can't get its dtor anyway. 4374 if (BaseClassDecl->isInvalidDecl()) 4375 continue; 4376 if (BaseClassDecl->hasIrrelevantDestructor()) 4377 continue; 4378 4379 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4380 assert(Dtor && "No dtor found for BaseClassDecl!"); 4381 4382 // FIXME: caret should be on the start of the class name 4383 CheckDestructorAccess(Base.getLocStart(), Dtor, 4384 PDiag(diag::err_access_dtor_base) 4385 << Base.getType() 4386 << Base.getSourceRange(), 4387 Context.getTypeDeclType(ClassDecl)); 4388 4389 MarkFunctionReferenced(Location, Dtor); 4390 DiagnoseUseOfDecl(Dtor, Location); 4391 } 4392 4393 // Virtual bases. 4394 for (const auto &VBase : ClassDecl->vbases()) { 4395 // Bases are always records in a well-formed non-dependent class. 4396 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4397 4398 // Ignore direct virtual bases. 4399 if (DirectVirtualBases.count(RT)) 4400 continue; 4401 4402 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4403 // If our base class is invalid, we probably can't get its dtor anyway. 4404 if (BaseClassDecl->isInvalidDecl()) 4405 continue; 4406 if (BaseClassDecl->hasIrrelevantDestructor()) 4407 continue; 4408 4409 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4410 assert(Dtor && "No dtor found for BaseClassDecl!"); 4411 if (CheckDestructorAccess( 4412 ClassDecl->getLocation(), Dtor, 4413 PDiag(diag::err_access_dtor_vbase) 4414 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4415 Context.getTypeDeclType(ClassDecl)) == 4416 AR_accessible) { 4417 CheckDerivedToBaseConversion( 4418 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4419 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4420 SourceRange(), DeclarationName(), nullptr); 4421 } 4422 4423 MarkFunctionReferenced(Location, Dtor); 4424 DiagnoseUseOfDecl(Dtor, Location); 4425 } 4426 } 4427 4428 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4429 if (!CDtorDecl) 4430 return; 4431 4432 if (CXXConstructorDecl *Constructor 4433 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4434 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4435 DiagnoseUninitializedFields(*this, Constructor); 4436 } 4437 } 4438 4439 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4440 unsigned DiagID, AbstractDiagSelID SelID) { 4441 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4442 unsigned DiagID; 4443 AbstractDiagSelID SelID; 4444 4445 public: 4446 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4447 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4448 4449 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4450 if (Suppressed) return; 4451 if (SelID == -1) 4452 S.Diag(Loc, DiagID) << T; 4453 else 4454 S.Diag(Loc, DiagID) << SelID << T; 4455 } 4456 } Diagnoser(DiagID, SelID); 4457 4458 return RequireNonAbstractType(Loc, T, Diagnoser); 4459 } 4460 4461 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4462 TypeDiagnoser &Diagnoser) { 4463 if (!getLangOpts().CPlusPlus) 4464 return false; 4465 4466 if (const ArrayType *AT = Context.getAsArrayType(T)) 4467 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4468 4469 if (const PointerType *PT = T->getAs<PointerType>()) { 4470 // Find the innermost pointer type. 4471 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4472 PT = T; 4473 4474 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4475 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4476 } 4477 4478 const RecordType *RT = T->getAs<RecordType>(); 4479 if (!RT) 4480 return false; 4481 4482 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4483 4484 // We can't answer whether something is abstract until it has a 4485 // definition. If it's currently being defined, we'll walk back 4486 // over all the declarations when we have a full definition. 4487 const CXXRecordDecl *Def = RD->getDefinition(); 4488 if (!Def || Def->isBeingDefined()) 4489 return false; 4490 4491 if (!RD->isAbstract()) 4492 return false; 4493 4494 Diagnoser.diagnose(*this, Loc, T); 4495 DiagnoseAbstractType(RD); 4496 4497 return true; 4498 } 4499 4500 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4501 // Check if we've already emitted the list of pure virtual functions 4502 // for this class. 4503 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4504 return; 4505 4506 // If the diagnostic is suppressed, don't emit the notes. We're only 4507 // going to emit them once, so try to attach them to a diagnostic we're 4508 // actually going to show. 4509 if (Diags.isLastDiagnosticIgnored()) 4510 return; 4511 4512 CXXFinalOverriderMap FinalOverriders; 4513 RD->getFinalOverriders(FinalOverriders); 4514 4515 // Keep a set of seen pure methods so we won't diagnose the same method 4516 // more than once. 4517 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4518 4519 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4520 MEnd = FinalOverriders.end(); 4521 M != MEnd; 4522 ++M) { 4523 for (OverridingMethods::iterator SO = M->second.begin(), 4524 SOEnd = M->second.end(); 4525 SO != SOEnd; ++SO) { 4526 // C++ [class.abstract]p4: 4527 // A class is abstract if it contains or inherits at least one 4528 // pure virtual function for which the final overrider is pure 4529 // virtual. 4530 4531 // 4532 if (SO->second.size() != 1) 4533 continue; 4534 4535 if (!SO->second.front().Method->isPure()) 4536 continue; 4537 4538 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4539 continue; 4540 4541 Diag(SO->second.front().Method->getLocation(), 4542 diag::note_pure_virtual_function) 4543 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4544 } 4545 } 4546 4547 if (!PureVirtualClassDiagSet) 4548 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4549 PureVirtualClassDiagSet->insert(RD); 4550 } 4551 4552 namespace { 4553 struct AbstractUsageInfo { 4554 Sema &S; 4555 CXXRecordDecl *Record; 4556 CanQualType AbstractType; 4557 bool Invalid; 4558 4559 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4560 : S(S), Record(Record), 4561 AbstractType(S.Context.getCanonicalType( 4562 S.Context.getTypeDeclType(Record))), 4563 Invalid(false) {} 4564 4565 void DiagnoseAbstractType() { 4566 if (Invalid) return; 4567 S.DiagnoseAbstractType(Record); 4568 Invalid = true; 4569 } 4570 4571 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4572 }; 4573 4574 struct CheckAbstractUsage { 4575 AbstractUsageInfo &Info; 4576 const NamedDecl *Ctx; 4577 4578 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4579 : Info(Info), Ctx(Ctx) {} 4580 4581 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4582 switch (TL.getTypeLocClass()) { 4583 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4584 #define TYPELOC(CLASS, PARENT) \ 4585 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4586 #include "clang/AST/TypeLocNodes.def" 4587 } 4588 } 4589 4590 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4591 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4592 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4593 if (!TL.getParam(I)) 4594 continue; 4595 4596 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4597 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4598 } 4599 } 4600 4601 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4602 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4603 } 4604 4605 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4606 // Visit the type parameters from a permissive context. 4607 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4608 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4609 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4610 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4611 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4612 // TODO: other template argument types? 4613 } 4614 } 4615 4616 // Visit pointee types from a permissive context. 4617 #define CheckPolymorphic(Type) \ 4618 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4619 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4620 } 4621 CheckPolymorphic(PointerTypeLoc) 4622 CheckPolymorphic(ReferenceTypeLoc) 4623 CheckPolymorphic(MemberPointerTypeLoc) 4624 CheckPolymorphic(BlockPointerTypeLoc) 4625 CheckPolymorphic(AtomicTypeLoc) 4626 4627 /// Handle all the types we haven't given a more specific 4628 /// implementation for above. 4629 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4630 // Every other kind of type that we haven't called out already 4631 // that has an inner type is either (1) sugar or (2) contains that 4632 // inner type in some way as a subobject. 4633 if (TypeLoc Next = TL.getNextTypeLoc()) 4634 return Visit(Next, Sel); 4635 4636 // If there's no inner type and we're in a permissive context, 4637 // don't diagnose. 4638 if (Sel == Sema::AbstractNone) return; 4639 4640 // Check whether the type matches the abstract type. 4641 QualType T = TL.getType(); 4642 if (T->isArrayType()) { 4643 Sel = Sema::AbstractArrayType; 4644 T = Info.S.Context.getBaseElementType(T); 4645 } 4646 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4647 if (CT != Info.AbstractType) return; 4648 4649 // It matched; do some magic. 4650 if (Sel == Sema::AbstractArrayType) { 4651 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4652 << T << TL.getSourceRange(); 4653 } else { 4654 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4655 << Sel << T << TL.getSourceRange(); 4656 } 4657 Info.DiagnoseAbstractType(); 4658 } 4659 }; 4660 4661 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4662 Sema::AbstractDiagSelID Sel) { 4663 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4664 } 4665 4666 } 4667 4668 /// Check for invalid uses of an abstract type in a method declaration. 4669 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4670 CXXMethodDecl *MD) { 4671 // No need to do the check on definitions, which require that 4672 // the return/param types be complete. 4673 if (MD->doesThisDeclarationHaveABody()) 4674 return; 4675 4676 // For safety's sake, just ignore it if we don't have type source 4677 // information. This should never happen for non-implicit methods, 4678 // but... 4679 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4680 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4681 } 4682 4683 /// Check for invalid uses of an abstract type within a class definition. 4684 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4685 CXXRecordDecl *RD) { 4686 for (auto *D : RD->decls()) { 4687 if (D->isImplicit()) continue; 4688 4689 // Methods and method templates. 4690 if (isa<CXXMethodDecl>(D)) { 4691 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4692 } else if (isa<FunctionTemplateDecl>(D)) { 4693 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4694 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4695 4696 // Fields and static variables. 4697 } else if (isa<FieldDecl>(D)) { 4698 FieldDecl *FD = cast<FieldDecl>(D); 4699 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4700 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4701 } else if (isa<VarDecl>(D)) { 4702 VarDecl *VD = cast<VarDecl>(D); 4703 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4704 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4705 4706 // Nested classes and class templates. 4707 } else if (isa<CXXRecordDecl>(D)) { 4708 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4709 } else if (isa<ClassTemplateDecl>(D)) { 4710 CheckAbstractClassUsage(Info, 4711 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4712 } 4713 } 4714 } 4715 4716 /// \brief Check class-level dllimport/dllexport attribute. 4717 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4718 Attr *ClassAttr = getDLLAttr(Class); 4719 4720 // MSVC inherits DLL attributes to partial class template specializations. 4721 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4722 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4723 if (Attr *TemplateAttr = 4724 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4725 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext())); 4726 A->setInherited(true); 4727 ClassAttr = A; 4728 } 4729 } 4730 } 4731 4732 if (!ClassAttr) 4733 return; 4734 4735 if (!Class->isExternallyVisible()) { 4736 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4737 << Class << ClassAttr; 4738 return; 4739 } 4740 4741 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4742 !ClassAttr->isInherited()) { 4743 // Diagnose dll attributes on members of class with dll attribute. 4744 for (Decl *Member : Class->decls()) { 4745 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4746 continue; 4747 InheritableAttr *MemberAttr = getDLLAttr(Member); 4748 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4749 continue; 4750 4751 S.Diag(MemberAttr->getLocation(), 4752 diag::err_attribute_dll_member_of_dll_class) 4753 << MemberAttr << ClassAttr; 4754 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4755 Member->setInvalidDecl(); 4756 } 4757 } 4758 4759 if (Class->getDescribedClassTemplate()) 4760 // Don't inherit dll attribute until the template is instantiated. 4761 return; 4762 4763 // The class is either imported or exported. 4764 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4765 const bool ClassImported = !ClassExported; 4766 4767 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4768 4769 // Don't dllexport explicit class template instantiation declarations. 4770 if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) { 4771 Class->dropAttr<DLLExportAttr>(); 4772 return; 4773 } 4774 4775 // Force declaration of implicit members so they can inherit the attribute. 4776 S.ForceDeclarationOfImplicitMembers(Class); 4777 4778 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4779 // seem to be true in practice? 4780 4781 for (Decl *Member : Class->decls()) { 4782 VarDecl *VD = dyn_cast<VarDecl>(Member); 4783 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4784 4785 // Only methods and static fields inherit the attributes. 4786 if (!VD && !MD) 4787 continue; 4788 4789 if (MD) { 4790 // Don't process deleted methods. 4791 if (MD->isDeleted()) 4792 continue; 4793 4794 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) { 4795 // Current MSVC versions don't export the move assignment operators, so 4796 // don't attempt to import them if we have a definition. 4797 continue; 4798 } 4799 4800 if (MD->isInlined() && 4801 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4802 // MinGW does not import or export inline methods. 4803 continue; 4804 } 4805 } 4806 4807 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 4808 continue; 4809 4810 if (!getDLLAttr(Member)) { 4811 auto *NewAttr = 4812 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4813 NewAttr->setInherited(true); 4814 Member->addAttr(NewAttr); 4815 } 4816 4817 if (MD && ClassExported) { 4818 if (MD->isUserProvided()) { 4819 // Instantiate non-default class member functions ... 4820 4821 // .. except for certain kinds of template specializations. 4822 if (TSK == TSK_ExplicitInstantiationDeclaration) 4823 continue; 4824 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4825 continue; 4826 4827 S.MarkFunctionReferenced(Class->getLocation(), MD); 4828 4829 // The function will be passed to the consumer when its definition is 4830 // encountered. 4831 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4832 MD->isCopyAssignmentOperator() || 4833 MD->isMoveAssignmentOperator()) { 4834 // Synthesize and instantiate non-trivial implicit methods, explicitly 4835 // defaulted methods, and the copy and move assignment operators. The 4836 // latter are exported even if they are trivial, because the address of 4837 // an operator can be taken and should compare equal accross libraries. 4838 DiagnosticErrorTrap Trap(S.Diags); 4839 S.MarkFunctionReferenced(Class->getLocation(), MD); 4840 if (Trap.hasErrorOccurred()) { 4841 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 4842 << Class->getName() << !S.getLangOpts().CPlusPlus11; 4843 break; 4844 } 4845 4846 // There is no later point when we will see the definition of this 4847 // function, so pass it to the consumer now. 4848 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 4849 } 4850 } 4851 } 4852 } 4853 4854 /// \brief Perform semantic checks on a class definition that has been 4855 /// completing, introducing implicitly-declared members, checking for 4856 /// abstract types, etc. 4857 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4858 if (!Record) 4859 return; 4860 4861 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4862 AbstractUsageInfo Info(*this, Record); 4863 CheckAbstractClassUsage(Info, Record); 4864 } 4865 4866 // If this is not an aggregate type and has no user-declared constructor, 4867 // complain about any non-static data members of reference or const scalar 4868 // type, since they will never get initializers. 4869 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4870 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4871 !Record->isLambda()) { 4872 bool Complained = false; 4873 for (const auto *F : Record->fields()) { 4874 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4875 continue; 4876 4877 if (F->getType()->isReferenceType() || 4878 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4879 if (!Complained) { 4880 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4881 << Record->getTagKind() << Record; 4882 Complained = true; 4883 } 4884 4885 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4886 << F->getType()->isReferenceType() 4887 << F->getDeclName(); 4888 } 4889 } 4890 } 4891 4892 if (Record->getIdentifier()) { 4893 // C++ [class.mem]p13: 4894 // If T is the name of a class, then each of the following shall have a 4895 // name different from T: 4896 // - every member of every anonymous union that is a member of class T. 4897 // 4898 // C++ [class.mem]p14: 4899 // In addition, if class T has a user-declared constructor (12.1), every 4900 // non-static data member of class T shall have a name different from T. 4901 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4902 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4903 ++I) { 4904 NamedDecl *D = *I; 4905 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4906 isa<IndirectFieldDecl>(D)) { 4907 Diag(D->getLocation(), diag::err_member_name_of_class) 4908 << D->getDeclName(); 4909 break; 4910 } 4911 } 4912 } 4913 4914 // Warn if the class has virtual methods but non-virtual public destructor. 4915 if (Record->isPolymorphic() && !Record->isDependentType()) { 4916 CXXDestructorDecl *dtor = Record->getDestructor(); 4917 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4918 !Record->hasAttr<FinalAttr>()) 4919 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4920 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4921 } 4922 4923 if (Record->isAbstract()) { 4924 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4925 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4926 << FA->isSpelledAsSealed(); 4927 DiagnoseAbstractType(Record); 4928 } 4929 } 4930 4931 bool HasMethodWithOverrideControl = false, 4932 HasOverridingMethodWithoutOverrideControl = false; 4933 if (!Record->isDependentType()) { 4934 for (auto *M : Record->methods()) { 4935 // See if a method overloads virtual methods in a base 4936 // class without overriding any. 4937 if (!M->isStatic()) 4938 DiagnoseHiddenVirtualMethods(M); 4939 if (M->hasAttr<OverrideAttr>()) 4940 HasMethodWithOverrideControl = true; 4941 else if (M->size_overridden_methods() > 0) 4942 HasOverridingMethodWithoutOverrideControl = true; 4943 // Check whether the explicitly-defaulted special members are valid. 4944 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4945 CheckExplicitlyDefaultedSpecialMember(M); 4946 4947 // For an explicitly defaulted or deleted special member, we defer 4948 // determining triviality until the class is complete. That time is now! 4949 if (!M->isImplicit() && !M->isUserProvided()) { 4950 CXXSpecialMember CSM = getSpecialMember(M); 4951 if (CSM != CXXInvalid) { 4952 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4953 4954 // Inform the class that we've finished declaring this member. 4955 Record->finishedDefaultedOrDeletedMember(M); 4956 } 4957 } 4958 } 4959 } 4960 4961 if (HasMethodWithOverrideControl && 4962 HasOverridingMethodWithoutOverrideControl) { 4963 // At least one method has the 'override' control declared. 4964 // Diagnose all other overridden methods which do not have 'override' specified on them. 4965 for (auto *M : Record->methods()) 4966 DiagnoseAbsenceOfOverrideControl(M); 4967 } 4968 4969 // ms_struct is a request to use the same ABI rules as MSVC. Check 4970 // whether this class uses any C++ features that are implemented 4971 // completely differently in MSVC, and if so, emit a diagnostic. 4972 // That diagnostic defaults to an error, but we allow projects to 4973 // map it down to a warning (or ignore it). It's a fairly common 4974 // practice among users of the ms_struct pragma to mass-annotate 4975 // headers, sweeping up a bunch of types that the project doesn't 4976 // really rely on MSVC-compatible layout for. We must therefore 4977 // support "ms_struct except for C++ stuff" as a secondary ABI. 4978 if (Record->isMsStruct(Context) && 4979 (Record->isPolymorphic() || Record->getNumBases())) { 4980 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4981 } 4982 4983 // Declare inheriting constructors. We do this eagerly here because: 4984 // - The standard requires an eager diagnostic for conflicting inheriting 4985 // constructors from different classes. 4986 // - The lazy declaration of the other implicit constructors is so as to not 4987 // waste space and performance on classes that are not meant to be 4988 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4989 // have inheriting constructors. 4990 DeclareInheritingConstructors(Record); 4991 4992 checkDLLAttribute(*this, Record); 4993 } 4994 4995 /// Look up the special member function that would be called by a special 4996 /// member function for a subobject of class type. 4997 /// 4998 /// \param Class The class type of the subobject. 4999 /// \param CSM The kind of special member function. 5000 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5001 /// \param ConstRHS True if this is a copy operation with a const object 5002 /// on its RHS, that is, if the argument to the outer special member 5003 /// function is 'const' and this is not a field marked 'mutable'. 5004 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 5005 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5006 unsigned FieldQuals, bool ConstRHS) { 5007 unsigned LHSQuals = 0; 5008 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5009 LHSQuals = FieldQuals; 5010 5011 unsigned RHSQuals = FieldQuals; 5012 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5013 RHSQuals = 0; 5014 else if (ConstRHS) 5015 RHSQuals |= Qualifiers::Const; 5016 5017 return S.LookupSpecialMember(Class, CSM, 5018 RHSQuals & Qualifiers::Const, 5019 RHSQuals & Qualifiers::Volatile, 5020 false, 5021 LHSQuals & Qualifiers::Const, 5022 LHSQuals & Qualifiers::Volatile); 5023 } 5024 5025 /// Is the special member function which would be selected to perform the 5026 /// specified operation on the specified class type a constexpr constructor? 5027 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5028 Sema::CXXSpecialMember CSM, 5029 unsigned Quals, bool ConstRHS) { 5030 Sema::SpecialMemberOverloadResult *SMOR = 5031 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5032 if (!SMOR || !SMOR->getMethod()) 5033 // A constructor we wouldn't select can't be "involved in initializing" 5034 // anything. 5035 return true; 5036 return SMOR->getMethod()->isConstexpr(); 5037 } 5038 5039 /// Determine whether the specified special member function would be constexpr 5040 /// if it were implicitly defined. 5041 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5042 Sema::CXXSpecialMember CSM, 5043 bool ConstArg) { 5044 if (!S.getLangOpts().CPlusPlus11) 5045 return false; 5046 5047 // C++11 [dcl.constexpr]p4: 5048 // In the definition of a constexpr constructor [...] 5049 bool Ctor = true; 5050 switch (CSM) { 5051 case Sema::CXXDefaultConstructor: 5052 // Since default constructor lookup is essentially trivial (and cannot 5053 // involve, for instance, template instantiation), we compute whether a 5054 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5055 // 5056 // This is important for performance; we need to know whether the default 5057 // constructor is constexpr to determine whether the type is a literal type. 5058 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5059 5060 case Sema::CXXCopyConstructor: 5061 case Sema::CXXMoveConstructor: 5062 // For copy or move constructors, we need to perform overload resolution. 5063 break; 5064 5065 case Sema::CXXCopyAssignment: 5066 case Sema::CXXMoveAssignment: 5067 if (!S.getLangOpts().CPlusPlus14) 5068 return false; 5069 // In C++1y, we need to perform overload resolution. 5070 Ctor = false; 5071 break; 5072 5073 case Sema::CXXDestructor: 5074 case Sema::CXXInvalid: 5075 return false; 5076 } 5077 5078 // -- if the class is a non-empty union, or for each non-empty anonymous 5079 // union member of a non-union class, exactly one non-static data member 5080 // shall be initialized; [DR1359] 5081 // 5082 // If we squint, this is guaranteed, since exactly one non-static data member 5083 // will be initialized (if the constructor isn't deleted), we just don't know 5084 // which one. 5085 if (Ctor && ClassDecl->isUnion()) 5086 return true; 5087 5088 // -- the class shall not have any virtual base classes; 5089 if (Ctor && ClassDecl->getNumVBases()) 5090 return false; 5091 5092 // C++1y [class.copy]p26: 5093 // -- [the class] is a literal type, and 5094 if (!Ctor && !ClassDecl->isLiteral()) 5095 return false; 5096 5097 // -- every constructor involved in initializing [...] base class 5098 // sub-objects shall be a constexpr constructor; 5099 // -- the assignment operator selected to copy/move each direct base 5100 // class is a constexpr function, and 5101 for (const auto &B : ClassDecl->bases()) { 5102 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5103 if (!BaseType) continue; 5104 5105 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5106 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5107 return false; 5108 } 5109 5110 // -- every constructor involved in initializing non-static data members 5111 // [...] shall be a constexpr constructor; 5112 // -- every non-static data member and base class sub-object shall be 5113 // initialized 5114 // -- for each non-static data member of X that is of class type (or array 5115 // thereof), the assignment operator selected to copy/move that member is 5116 // a constexpr function 5117 for (const auto *F : ClassDecl->fields()) { 5118 if (F->isInvalidDecl()) 5119 continue; 5120 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5121 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5122 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5123 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5124 BaseType.getCVRQualifiers(), 5125 ConstArg && !F->isMutable())) 5126 return false; 5127 } 5128 } 5129 5130 // All OK, it's constexpr! 5131 return true; 5132 } 5133 5134 static Sema::ImplicitExceptionSpecification 5135 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5136 switch (S.getSpecialMember(MD)) { 5137 case Sema::CXXDefaultConstructor: 5138 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5139 case Sema::CXXCopyConstructor: 5140 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5141 case Sema::CXXCopyAssignment: 5142 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5143 case Sema::CXXMoveConstructor: 5144 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5145 case Sema::CXXMoveAssignment: 5146 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5147 case Sema::CXXDestructor: 5148 return S.ComputeDefaultedDtorExceptionSpec(MD); 5149 case Sema::CXXInvalid: 5150 break; 5151 } 5152 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5153 "only special members have implicit exception specs"); 5154 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5155 } 5156 5157 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5158 CXXMethodDecl *MD) { 5159 FunctionProtoType::ExtProtoInfo EPI; 5160 5161 // Build an exception specification pointing back at this member. 5162 EPI.ExceptionSpec.Type = EST_Unevaluated; 5163 EPI.ExceptionSpec.SourceDecl = MD; 5164 5165 // Set the calling convention to the default for C++ instance methods. 5166 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5167 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5168 /*IsCXXMethod=*/true)); 5169 return EPI; 5170 } 5171 5172 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5173 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5174 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5175 return; 5176 5177 // Evaluate the exception specification. 5178 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5179 5180 // Update the type of the special member to use it. 5181 UpdateExceptionSpec(MD, ESI); 5182 5183 // A user-provided destructor can be defined outside the class. When that 5184 // happens, be sure to update the exception specification on both 5185 // declarations. 5186 const FunctionProtoType *CanonicalFPT = 5187 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5188 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5189 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5190 } 5191 5192 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5193 CXXRecordDecl *RD = MD->getParent(); 5194 CXXSpecialMember CSM = getSpecialMember(MD); 5195 5196 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5197 "not an explicitly-defaulted special member"); 5198 5199 // Whether this was the first-declared instance of the constructor. 5200 // This affects whether we implicitly add an exception spec and constexpr. 5201 bool First = MD == MD->getCanonicalDecl(); 5202 5203 bool HadError = false; 5204 5205 // C++11 [dcl.fct.def.default]p1: 5206 // A function that is explicitly defaulted shall 5207 // -- be a special member function (checked elsewhere), 5208 // -- have the same type (except for ref-qualifiers, and except that a 5209 // copy operation can take a non-const reference) as an implicit 5210 // declaration, and 5211 // -- not have default arguments. 5212 unsigned ExpectedParams = 1; 5213 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5214 ExpectedParams = 0; 5215 if (MD->getNumParams() != ExpectedParams) { 5216 // This also checks for default arguments: a copy or move constructor with a 5217 // default argument is classified as a default constructor, and assignment 5218 // operations and destructors can't have default arguments. 5219 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5220 << CSM << MD->getSourceRange(); 5221 HadError = true; 5222 } else if (MD->isVariadic()) { 5223 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5224 << CSM << MD->getSourceRange(); 5225 HadError = true; 5226 } 5227 5228 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5229 5230 bool CanHaveConstParam = false; 5231 if (CSM == CXXCopyConstructor) 5232 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5233 else if (CSM == CXXCopyAssignment) 5234 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5235 5236 QualType ReturnType = Context.VoidTy; 5237 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5238 // Check for return type matching. 5239 ReturnType = Type->getReturnType(); 5240 QualType ExpectedReturnType = 5241 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5242 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5243 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5244 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5245 HadError = true; 5246 } 5247 5248 // A defaulted special member cannot have cv-qualifiers. 5249 if (Type->getTypeQuals()) { 5250 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5251 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5252 HadError = true; 5253 } 5254 } 5255 5256 // Check for parameter type matching. 5257 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5258 bool HasConstParam = false; 5259 if (ExpectedParams && ArgType->isReferenceType()) { 5260 // Argument must be reference to possibly-const T. 5261 QualType ReferentType = ArgType->getPointeeType(); 5262 HasConstParam = ReferentType.isConstQualified(); 5263 5264 if (ReferentType.isVolatileQualified()) { 5265 Diag(MD->getLocation(), 5266 diag::err_defaulted_special_member_volatile_param) << CSM; 5267 HadError = true; 5268 } 5269 5270 if (HasConstParam && !CanHaveConstParam) { 5271 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5272 Diag(MD->getLocation(), 5273 diag::err_defaulted_special_member_copy_const_param) 5274 << (CSM == CXXCopyAssignment); 5275 // FIXME: Explain why this special member can't be const. 5276 } else { 5277 Diag(MD->getLocation(), 5278 diag::err_defaulted_special_member_move_const_param) 5279 << (CSM == CXXMoveAssignment); 5280 } 5281 HadError = true; 5282 } 5283 } else if (ExpectedParams) { 5284 // A copy assignment operator can take its argument by value, but a 5285 // defaulted one cannot. 5286 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5287 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5288 HadError = true; 5289 } 5290 5291 // C++11 [dcl.fct.def.default]p2: 5292 // An explicitly-defaulted function may be declared constexpr only if it 5293 // would have been implicitly declared as constexpr, 5294 // Do not apply this rule to members of class templates, since core issue 1358 5295 // makes such functions always instantiate to constexpr functions. For 5296 // functions which cannot be constexpr (for non-constructors in C++11 and for 5297 // destructors in C++1y), this is checked elsewhere. 5298 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5299 HasConstParam); 5300 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5301 : isa<CXXConstructorDecl>(MD)) && 5302 MD->isConstexpr() && !Constexpr && 5303 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5304 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5305 // FIXME: Explain why the special member can't be constexpr. 5306 HadError = true; 5307 } 5308 5309 // and may have an explicit exception-specification only if it is compatible 5310 // with the exception-specification on the implicit declaration. 5311 if (Type->hasExceptionSpec()) { 5312 // Delay the check if this is the first declaration of the special member, 5313 // since we may not have parsed some necessary in-class initializers yet. 5314 if (First) { 5315 // If the exception specification needs to be instantiated, do so now, 5316 // before we clobber it with an EST_Unevaluated specification below. 5317 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5318 InstantiateExceptionSpec(MD->getLocStart(), MD); 5319 Type = MD->getType()->getAs<FunctionProtoType>(); 5320 } 5321 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5322 } else 5323 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5324 } 5325 5326 // If a function is explicitly defaulted on its first declaration, 5327 if (First) { 5328 // -- it is implicitly considered to be constexpr if the implicit 5329 // definition would be, 5330 MD->setConstexpr(Constexpr); 5331 5332 // -- it is implicitly considered to have the same exception-specification 5333 // as if it had been implicitly declared, 5334 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5335 EPI.ExceptionSpec.Type = EST_Unevaluated; 5336 EPI.ExceptionSpec.SourceDecl = MD; 5337 MD->setType(Context.getFunctionType(ReturnType, 5338 llvm::makeArrayRef(&ArgType, 5339 ExpectedParams), 5340 EPI)); 5341 } 5342 5343 if (ShouldDeleteSpecialMember(MD, CSM)) { 5344 if (First) { 5345 SetDeclDeleted(MD, MD->getLocation()); 5346 } else { 5347 // C++11 [dcl.fct.def.default]p4: 5348 // [For a] user-provided explicitly-defaulted function [...] if such a 5349 // function is implicitly defined as deleted, the program is ill-formed. 5350 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5351 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5352 HadError = true; 5353 } 5354 } 5355 5356 if (HadError) 5357 MD->setInvalidDecl(); 5358 } 5359 5360 /// Check whether the exception specification provided for an 5361 /// explicitly-defaulted special member matches the exception specification 5362 /// that would have been generated for an implicit special member, per 5363 /// C++11 [dcl.fct.def.default]p2. 5364 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5365 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5366 // If the exception specification was explicitly specified but hadn't been 5367 // parsed when the method was defaulted, grab it now. 5368 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5369 SpecifiedType = 5370 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5371 5372 // Compute the implicit exception specification. 5373 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5374 /*IsCXXMethod=*/true); 5375 FunctionProtoType::ExtProtoInfo EPI(CC); 5376 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5377 .getExceptionSpec(); 5378 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5379 Context.getFunctionType(Context.VoidTy, None, EPI)); 5380 5381 // Ensure that it matches. 5382 CheckEquivalentExceptionSpec( 5383 PDiag(diag::err_incorrect_defaulted_exception_spec) 5384 << getSpecialMember(MD), PDiag(), 5385 ImplicitType, SourceLocation(), 5386 SpecifiedType, MD->getLocation()); 5387 } 5388 5389 void Sema::CheckDelayedMemberExceptionSpecs() { 5390 decltype(DelayedExceptionSpecChecks) Checks; 5391 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 5392 5393 std::swap(Checks, DelayedExceptionSpecChecks); 5394 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5395 5396 // Perform any deferred checking of exception specifications for virtual 5397 // destructors. 5398 for (auto &Check : Checks) 5399 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 5400 5401 // Check that any explicitly-defaulted methods have exception specifications 5402 // compatible with their implicit exception specifications. 5403 for (auto &Spec : Specs) 5404 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 5405 } 5406 5407 namespace { 5408 struct SpecialMemberDeletionInfo { 5409 Sema &S; 5410 CXXMethodDecl *MD; 5411 Sema::CXXSpecialMember CSM; 5412 bool Diagnose; 5413 5414 // Properties of the special member, computed for convenience. 5415 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5416 SourceLocation Loc; 5417 5418 bool AllFieldsAreConst; 5419 5420 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5421 Sema::CXXSpecialMember CSM, bool Diagnose) 5422 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5423 IsConstructor(false), IsAssignment(false), IsMove(false), 5424 ConstArg(false), Loc(MD->getLocation()), 5425 AllFieldsAreConst(true) { 5426 switch (CSM) { 5427 case Sema::CXXDefaultConstructor: 5428 case Sema::CXXCopyConstructor: 5429 IsConstructor = true; 5430 break; 5431 case Sema::CXXMoveConstructor: 5432 IsConstructor = true; 5433 IsMove = true; 5434 break; 5435 case Sema::CXXCopyAssignment: 5436 IsAssignment = true; 5437 break; 5438 case Sema::CXXMoveAssignment: 5439 IsAssignment = true; 5440 IsMove = true; 5441 break; 5442 case Sema::CXXDestructor: 5443 break; 5444 case Sema::CXXInvalid: 5445 llvm_unreachable("invalid special member kind"); 5446 } 5447 5448 if (MD->getNumParams()) { 5449 if (const ReferenceType *RT = 5450 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5451 ConstArg = RT->getPointeeType().isConstQualified(); 5452 } 5453 } 5454 5455 bool inUnion() const { return MD->getParent()->isUnion(); } 5456 5457 /// Look up the corresponding special member in the given class. 5458 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5459 unsigned Quals, bool IsMutable) { 5460 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5461 ConstArg && !IsMutable); 5462 } 5463 5464 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5465 5466 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5467 bool shouldDeleteForField(FieldDecl *FD); 5468 bool shouldDeleteForAllConstMembers(); 5469 5470 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5471 unsigned Quals); 5472 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5473 Sema::SpecialMemberOverloadResult *SMOR, 5474 bool IsDtorCallInCtor); 5475 5476 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5477 }; 5478 } 5479 5480 /// Is the given special member inaccessible when used on the given 5481 /// sub-object. 5482 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5483 CXXMethodDecl *target) { 5484 /// If we're operating on a base class, the object type is the 5485 /// type of this special member. 5486 QualType objectTy; 5487 AccessSpecifier access = target->getAccess(); 5488 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5489 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5490 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5491 5492 // If we're operating on a field, the object type is the type of the field. 5493 } else { 5494 objectTy = S.Context.getTypeDeclType(target->getParent()); 5495 } 5496 5497 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5498 } 5499 5500 /// Check whether we should delete a special member due to the implicit 5501 /// definition containing a call to a special member of a subobject. 5502 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5503 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5504 bool IsDtorCallInCtor) { 5505 CXXMethodDecl *Decl = SMOR->getMethod(); 5506 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5507 5508 int DiagKind = -1; 5509 5510 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5511 DiagKind = !Decl ? 0 : 1; 5512 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5513 DiagKind = 2; 5514 else if (!isAccessible(Subobj, Decl)) 5515 DiagKind = 3; 5516 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5517 !Decl->isTrivial()) { 5518 // A member of a union must have a trivial corresponding special member. 5519 // As a weird special case, a destructor call from a union's constructor 5520 // must be accessible and non-deleted, but need not be trivial. Such a 5521 // destructor is never actually called, but is semantically checked as 5522 // if it were. 5523 DiagKind = 4; 5524 } 5525 5526 if (DiagKind == -1) 5527 return false; 5528 5529 if (Diagnose) { 5530 if (Field) { 5531 S.Diag(Field->getLocation(), 5532 diag::note_deleted_special_member_class_subobject) 5533 << CSM << MD->getParent() << /*IsField*/true 5534 << Field << DiagKind << IsDtorCallInCtor; 5535 } else { 5536 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5537 S.Diag(Base->getLocStart(), 5538 diag::note_deleted_special_member_class_subobject) 5539 << CSM << MD->getParent() << /*IsField*/false 5540 << Base->getType() << DiagKind << IsDtorCallInCtor; 5541 } 5542 5543 if (DiagKind == 1) 5544 S.NoteDeletedFunction(Decl); 5545 // FIXME: Explain inaccessibility if DiagKind == 3. 5546 } 5547 5548 return true; 5549 } 5550 5551 /// Check whether we should delete a special member function due to having a 5552 /// direct or virtual base class or non-static data member of class type M. 5553 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5554 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5555 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5556 bool IsMutable = Field && Field->isMutable(); 5557 5558 // C++11 [class.ctor]p5: 5559 // -- any direct or virtual base class, or non-static data member with no 5560 // brace-or-equal-initializer, has class type M (or array thereof) and 5561 // either M has no default constructor or overload resolution as applied 5562 // to M's default constructor results in an ambiguity or in a function 5563 // that is deleted or inaccessible 5564 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5565 // -- a direct or virtual base class B that cannot be copied/moved because 5566 // overload resolution, as applied to B's corresponding special member, 5567 // results in an ambiguity or a function that is deleted or inaccessible 5568 // from the defaulted special member 5569 // C++11 [class.dtor]p5: 5570 // -- any direct or virtual base class [...] has a type with a destructor 5571 // that is deleted or inaccessible 5572 if (!(CSM == Sema::CXXDefaultConstructor && 5573 Field && Field->hasInClassInitializer()) && 5574 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5575 false)) 5576 return true; 5577 5578 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5579 // -- any direct or virtual base class or non-static data member has a 5580 // type with a destructor that is deleted or inaccessible 5581 if (IsConstructor) { 5582 Sema::SpecialMemberOverloadResult *SMOR = 5583 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5584 false, false, false, false, false); 5585 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5586 return true; 5587 } 5588 5589 return false; 5590 } 5591 5592 /// Check whether we should delete a special member function due to the class 5593 /// having a particular direct or virtual base class. 5594 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5595 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5596 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5597 } 5598 5599 /// Check whether we should delete a special member function due to the class 5600 /// having a particular non-static data member. 5601 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5602 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5603 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5604 5605 if (CSM == Sema::CXXDefaultConstructor) { 5606 // For a default constructor, all references must be initialized in-class 5607 // and, if a union, it must have a non-const member. 5608 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5609 if (Diagnose) 5610 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5611 << MD->getParent() << FD << FieldType << /*Reference*/0; 5612 return true; 5613 } 5614 // C++11 [class.ctor]p5: any non-variant non-static data member of 5615 // const-qualified type (or array thereof) with no 5616 // brace-or-equal-initializer does not have a user-provided default 5617 // constructor. 5618 if (!inUnion() && FieldType.isConstQualified() && 5619 !FD->hasInClassInitializer() && 5620 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5621 if (Diagnose) 5622 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5623 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5624 return true; 5625 } 5626 5627 if (inUnion() && !FieldType.isConstQualified()) 5628 AllFieldsAreConst = false; 5629 } else if (CSM == Sema::CXXCopyConstructor) { 5630 // For a copy constructor, data members must not be of rvalue reference 5631 // type. 5632 if (FieldType->isRValueReferenceType()) { 5633 if (Diagnose) 5634 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5635 << MD->getParent() << FD << FieldType; 5636 return true; 5637 } 5638 } else if (IsAssignment) { 5639 // For an assignment operator, data members must not be of reference type. 5640 if (FieldType->isReferenceType()) { 5641 if (Diagnose) 5642 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5643 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5644 return true; 5645 } 5646 if (!FieldRecord && FieldType.isConstQualified()) { 5647 // C++11 [class.copy]p23: 5648 // -- a non-static data member of const non-class type (or array thereof) 5649 if (Diagnose) 5650 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5651 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5652 return true; 5653 } 5654 } 5655 5656 if (FieldRecord) { 5657 // Some additional restrictions exist on the variant members. 5658 if (!inUnion() && FieldRecord->isUnion() && 5659 FieldRecord->isAnonymousStructOrUnion()) { 5660 bool AllVariantFieldsAreConst = true; 5661 5662 // FIXME: Handle anonymous unions declared within anonymous unions. 5663 for (auto *UI : FieldRecord->fields()) { 5664 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5665 5666 if (!UnionFieldType.isConstQualified()) 5667 AllVariantFieldsAreConst = false; 5668 5669 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5670 if (UnionFieldRecord && 5671 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5672 UnionFieldType.getCVRQualifiers())) 5673 return true; 5674 } 5675 5676 // At least one member in each anonymous union must be non-const 5677 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5678 !FieldRecord->field_empty()) { 5679 if (Diagnose) 5680 S.Diag(FieldRecord->getLocation(), 5681 diag::note_deleted_default_ctor_all_const) 5682 << MD->getParent() << /*anonymous union*/1; 5683 return true; 5684 } 5685 5686 // Don't check the implicit member of the anonymous union type. 5687 // This is technically non-conformant, but sanity demands it. 5688 return false; 5689 } 5690 5691 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5692 FieldType.getCVRQualifiers())) 5693 return true; 5694 } 5695 5696 return false; 5697 } 5698 5699 /// C++11 [class.ctor] p5: 5700 /// A defaulted default constructor for a class X is defined as deleted if 5701 /// X is a union and all of its variant members are of const-qualified type. 5702 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5703 // This is a silly definition, because it gives an empty union a deleted 5704 // default constructor. Don't do that. 5705 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5706 !MD->getParent()->field_empty()) { 5707 if (Diagnose) 5708 S.Diag(MD->getParent()->getLocation(), 5709 diag::note_deleted_default_ctor_all_const) 5710 << MD->getParent() << /*not anonymous union*/0; 5711 return true; 5712 } 5713 return false; 5714 } 5715 5716 /// Determine whether a defaulted special member function should be defined as 5717 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5718 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5719 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5720 bool Diagnose) { 5721 if (MD->isInvalidDecl()) 5722 return false; 5723 CXXRecordDecl *RD = MD->getParent(); 5724 assert(!RD->isDependentType() && "do deletion after instantiation"); 5725 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5726 return false; 5727 5728 // C++11 [expr.lambda.prim]p19: 5729 // The closure type associated with a lambda-expression has a 5730 // deleted (8.4.3) default constructor and a deleted copy 5731 // assignment operator. 5732 if (RD->isLambda() && 5733 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5734 if (Diagnose) 5735 Diag(RD->getLocation(), diag::note_lambda_decl); 5736 return true; 5737 } 5738 5739 // For an anonymous struct or union, the copy and assignment special members 5740 // will never be used, so skip the check. For an anonymous union declared at 5741 // namespace scope, the constructor and destructor are used. 5742 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5743 RD->isAnonymousStructOrUnion()) 5744 return false; 5745 5746 // C++11 [class.copy]p7, p18: 5747 // If the class definition declares a move constructor or move assignment 5748 // operator, an implicitly declared copy constructor or copy assignment 5749 // operator is defined as deleted. 5750 if (MD->isImplicit() && 5751 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5752 CXXMethodDecl *UserDeclaredMove = nullptr; 5753 5754 // In Microsoft mode, a user-declared move only causes the deletion of the 5755 // corresponding copy operation, not both copy operations. 5756 if (RD->hasUserDeclaredMoveConstructor() && 5757 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5758 if (!Diagnose) return true; 5759 5760 // Find any user-declared move constructor. 5761 for (auto *I : RD->ctors()) { 5762 if (I->isMoveConstructor()) { 5763 UserDeclaredMove = I; 5764 break; 5765 } 5766 } 5767 assert(UserDeclaredMove); 5768 } else if (RD->hasUserDeclaredMoveAssignment() && 5769 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5770 if (!Diagnose) return true; 5771 5772 // Find any user-declared move assignment operator. 5773 for (auto *I : RD->methods()) { 5774 if (I->isMoveAssignmentOperator()) { 5775 UserDeclaredMove = I; 5776 break; 5777 } 5778 } 5779 assert(UserDeclaredMove); 5780 } 5781 5782 if (UserDeclaredMove) { 5783 Diag(UserDeclaredMove->getLocation(), 5784 diag::note_deleted_copy_user_declared_move) 5785 << (CSM == CXXCopyAssignment) << RD 5786 << UserDeclaredMove->isMoveAssignmentOperator(); 5787 return true; 5788 } 5789 } 5790 5791 // Do access control from the special member function 5792 ContextRAII MethodContext(*this, MD); 5793 5794 // C++11 [class.dtor]p5: 5795 // -- for a virtual destructor, lookup of the non-array deallocation function 5796 // results in an ambiguity or in a function that is deleted or inaccessible 5797 if (CSM == CXXDestructor && MD->isVirtual()) { 5798 FunctionDecl *OperatorDelete = nullptr; 5799 DeclarationName Name = 5800 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5801 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5802 OperatorDelete, false)) { 5803 if (Diagnose) 5804 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5805 return true; 5806 } 5807 } 5808 5809 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5810 5811 for (auto &BI : RD->bases()) 5812 if (!BI.isVirtual() && 5813 SMI.shouldDeleteForBase(&BI)) 5814 return true; 5815 5816 // Per DR1611, do not consider virtual bases of constructors of abstract 5817 // classes, since we are not going to construct them. 5818 if (!RD->isAbstract() || !SMI.IsConstructor) { 5819 for (auto &BI : RD->vbases()) 5820 if (SMI.shouldDeleteForBase(&BI)) 5821 return true; 5822 } 5823 5824 for (auto *FI : RD->fields()) 5825 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5826 SMI.shouldDeleteForField(FI)) 5827 return true; 5828 5829 if (SMI.shouldDeleteForAllConstMembers()) 5830 return true; 5831 5832 if (getLangOpts().CUDA) { 5833 // We should delete the special member in CUDA mode if target inference 5834 // failed. 5835 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5836 Diagnose); 5837 } 5838 5839 return false; 5840 } 5841 5842 /// Perform lookup for a special member of the specified kind, and determine 5843 /// whether it is trivial. If the triviality can be determined without the 5844 /// lookup, skip it. This is intended for use when determining whether a 5845 /// special member of a containing object is trivial, and thus does not ever 5846 /// perform overload resolution for default constructors. 5847 /// 5848 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5849 /// member that was most likely to be intended to be trivial, if any. 5850 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5851 Sema::CXXSpecialMember CSM, unsigned Quals, 5852 bool ConstRHS, CXXMethodDecl **Selected) { 5853 if (Selected) 5854 *Selected = nullptr; 5855 5856 switch (CSM) { 5857 case Sema::CXXInvalid: 5858 llvm_unreachable("not a special member"); 5859 5860 case Sema::CXXDefaultConstructor: 5861 // C++11 [class.ctor]p5: 5862 // A default constructor is trivial if: 5863 // - all the [direct subobjects] have trivial default constructors 5864 // 5865 // Note, no overload resolution is performed in this case. 5866 if (RD->hasTrivialDefaultConstructor()) 5867 return true; 5868 5869 if (Selected) { 5870 // If there's a default constructor which could have been trivial, dig it 5871 // out. Otherwise, if there's any user-provided default constructor, point 5872 // to that as an example of why there's not a trivial one. 5873 CXXConstructorDecl *DefCtor = nullptr; 5874 if (RD->needsImplicitDefaultConstructor()) 5875 S.DeclareImplicitDefaultConstructor(RD); 5876 for (auto *CI : RD->ctors()) { 5877 if (!CI->isDefaultConstructor()) 5878 continue; 5879 DefCtor = CI; 5880 if (!DefCtor->isUserProvided()) 5881 break; 5882 } 5883 5884 *Selected = DefCtor; 5885 } 5886 5887 return false; 5888 5889 case Sema::CXXDestructor: 5890 // C++11 [class.dtor]p5: 5891 // A destructor is trivial if: 5892 // - all the direct [subobjects] have trivial destructors 5893 if (RD->hasTrivialDestructor()) 5894 return true; 5895 5896 if (Selected) { 5897 if (RD->needsImplicitDestructor()) 5898 S.DeclareImplicitDestructor(RD); 5899 *Selected = RD->getDestructor(); 5900 } 5901 5902 return false; 5903 5904 case Sema::CXXCopyConstructor: 5905 // C++11 [class.copy]p12: 5906 // A copy constructor is trivial if: 5907 // - the constructor selected to copy each direct [subobject] is trivial 5908 if (RD->hasTrivialCopyConstructor()) { 5909 if (Quals == Qualifiers::Const) 5910 // We must either select the trivial copy constructor or reach an 5911 // ambiguity; no need to actually perform overload resolution. 5912 return true; 5913 } else if (!Selected) { 5914 return false; 5915 } 5916 // In C++98, we are not supposed to perform overload resolution here, but we 5917 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5918 // cases like B as having a non-trivial copy constructor: 5919 // struct A { template<typename T> A(T&); }; 5920 // struct B { mutable A a; }; 5921 goto NeedOverloadResolution; 5922 5923 case Sema::CXXCopyAssignment: 5924 // C++11 [class.copy]p25: 5925 // A copy assignment operator is trivial if: 5926 // - the assignment operator selected to copy each direct [subobject] is 5927 // trivial 5928 if (RD->hasTrivialCopyAssignment()) { 5929 if (Quals == Qualifiers::Const) 5930 return true; 5931 } else if (!Selected) { 5932 return false; 5933 } 5934 // In C++98, we are not supposed to perform overload resolution here, but we 5935 // treat that as a language defect. 5936 goto NeedOverloadResolution; 5937 5938 case Sema::CXXMoveConstructor: 5939 case Sema::CXXMoveAssignment: 5940 NeedOverloadResolution: 5941 Sema::SpecialMemberOverloadResult *SMOR = 5942 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5943 5944 // The standard doesn't describe how to behave if the lookup is ambiguous. 5945 // We treat it as not making the member non-trivial, just like the standard 5946 // mandates for the default constructor. This should rarely matter, because 5947 // the member will also be deleted. 5948 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5949 return true; 5950 5951 if (!SMOR->getMethod()) { 5952 assert(SMOR->getKind() == 5953 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5954 return false; 5955 } 5956 5957 // We deliberately don't check if we found a deleted special member. We're 5958 // not supposed to! 5959 if (Selected) 5960 *Selected = SMOR->getMethod(); 5961 return SMOR->getMethod()->isTrivial(); 5962 } 5963 5964 llvm_unreachable("unknown special method kind"); 5965 } 5966 5967 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5968 for (auto *CI : RD->ctors()) 5969 if (!CI->isImplicit()) 5970 return CI; 5971 5972 // Look for constructor templates. 5973 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5974 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5975 if (CXXConstructorDecl *CD = 5976 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5977 return CD; 5978 } 5979 5980 return nullptr; 5981 } 5982 5983 /// The kind of subobject we are checking for triviality. The values of this 5984 /// enumeration are used in diagnostics. 5985 enum TrivialSubobjectKind { 5986 /// The subobject is a base class. 5987 TSK_BaseClass, 5988 /// The subobject is a non-static data member. 5989 TSK_Field, 5990 /// The object is actually the complete object. 5991 TSK_CompleteObject 5992 }; 5993 5994 /// Check whether the special member selected for a given type would be trivial. 5995 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5996 QualType SubType, bool ConstRHS, 5997 Sema::CXXSpecialMember CSM, 5998 TrivialSubobjectKind Kind, 5999 bool Diagnose) { 6000 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 6001 if (!SubRD) 6002 return true; 6003 6004 CXXMethodDecl *Selected; 6005 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 6006 ConstRHS, Diagnose ? &Selected : nullptr)) 6007 return true; 6008 6009 if (Diagnose) { 6010 if (ConstRHS) 6011 SubType.addConst(); 6012 6013 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 6014 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 6015 << Kind << SubType.getUnqualifiedType(); 6016 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6017 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6018 } else if (!Selected) 6019 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6020 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6021 else if (Selected->isUserProvided()) { 6022 if (Kind == TSK_CompleteObject) 6023 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6024 << Kind << SubType.getUnqualifiedType() << CSM; 6025 else { 6026 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6027 << Kind << SubType.getUnqualifiedType() << CSM; 6028 S.Diag(Selected->getLocation(), diag::note_declared_at); 6029 } 6030 } else { 6031 if (Kind != TSK_CompleteObject) 6032 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6033 << Kind << SubType.getUnqualifiedType() << CSM; 6034 6035 // Explain why the defaulted or deleted special member isn't trivial. 6036 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6037 } 6038 } 6039 6040 return false; 6041 } 6042 6043 /// Check whether the members of a class type allow a special member to be 6044 /// trivial. 6045 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 6046 Sema::CXXSpecialMember CSM, 6047 bool ConstArg, bool Diagnose) { 6048 for (const auto *FI : RD->fields()) { 6049 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 6050 continue; 6051 6052 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 6053 6054 // Pretend anonymous struct or union members are members of this class. 6055 if (FI->isAnonymousStructOrUnion()) { 6056 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 6057 CSM, ConstArg, Diagnose)) 6058 return false; 6059 continue; 6060 } 6061 6062 // C++11 [class.ctor]p5: 6063 // A default constructor is trivial if [...] 6064 // -- no non-static data member of its class has a 6065 // brace-or-equal-initializer 6066 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 6067 if (Diagnose) 6068 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 6069 return false; 6070 } 6071 6072 // Objective C ARC 4.3.5: 6073 // [...] nontrivally ownership-qualified types are [...] not trivially 6074 // default constructible, copy constructible, move constructible, copy 6075 // assignable, move assignable, or destructible [...] 6076 if (S.getLangOpts().ObjCAutoRefCount && 6077 FieldType.hasNonTrivialObjCLifetime()) { 6078 if (Diagnose) 6079 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6080 << RD << FieldType.getObjCLifetime(); 6081 return false; 6082 } 6083 6084 bool ConstRHS = ConstArg && !FI->isMutable(); 6085 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6086 CSM, TSK_Field, Diagnose)) 6087 return false; 6088 } 6089 6090 return true; 6091 } 6092 6093 /// Diagnose why the specified class does not have a trivial special member of 6094 /// the given kind. 6095 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6096 QualType Ty = Context.getRecordType(RD); 6097 6098 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6099 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6100 TSK_CompleteObject, /*Diagnose*/true); 6101 } 6102 6103 /// Determine whether a defaulted or deleted special member function is trivial, 6104 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6105 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6106 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6107 bool Diagnose) { 6108 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6109 6110 CXXRecordDecl *RD = MD->getParent(); 6111 6112 bool ConstArg = false; 6113 6114 // C++11 [class.copy]p12, p25: [DR1593] 6115 // A [special member] is trivial if [...] its parameter-type-list is 6116 // equivalent to the parameter-type-list of an implicit declaration [...] 6117 switch (CSM) { 6118 case CXXDefaultConstructor: 6119 case CXXDestructor: 6120 // Trivial default constructors and destructors cannot have parameters. 6121 break; 6122 6123 case CXXCopyConstructor: 6124 case CXXCopyAssignment: { 6125 // Trivial copy operations always have const, non-volatile parameter types. 6126 ConstArg = true; 6127 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6128 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6129 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6130 if (Diagnose) 6131 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6132 << Param0->getSourceRange() << Param0->getType() 6133 << Context.getLValueReferenceType( 6134 Context.getRecordType(RD).withConst()); 6135 return false; 6136 } 6137 break; 6138 } 6139 6140 case CXXMoveConstructor: 6141 case CXXMoveAssignment: { 6142 // Trivial move operations always have non-cv-qualified parameters. 6143 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6144 const RValueReferenceType *RT = 6145 Param0->getType()->getAs<RValueReferenceType>(); 6146 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6147 if (Diagnose) 6148 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6149 << Param0->getSourceRange() << Param0->getType() 6150 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6151 return false; 6152 } 6153 break; 6154 } 6155 6156 case CXXInvalid: 6157 llvm_unreachable("not a special member"); 6158 } 6159 6160 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6161 if (Diagnose) 6162 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6163 diag::note_nontrivial_default_arg) 6164 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6165 return false; 6166 } 6167 if (MD->isVariadic()) { 6168 if (Diagnose) 6169 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6170 return false; 6171 } 6172 6173 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6174 // A copy/move [constructor or assignment operator] is trivial if 6175 // -- the [member] selected to copy/move each direct base class subobject 6176 // is trivial 6177 // 6178 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6179 // A [default constructor or destructor] is trivial if 6180 // -- all the direct base classes have trivial [default constructors or 6181 // destructors] 6182 for (const auto &BI : RD->bases()) 6183 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6184 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6185 return false; 6186 6187 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6188 // A copy/move [constructor or assignment operator] for a class X is 6189 // trivial if 6190 // -- for each non-static data member of X that is of class type (or array 6191 // thereof), the constructor selected to copy/move that member is 6192 // trivial 6193 // 6194 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6195 // A [default constructor or destructor] is trivial if 6196 // -- for all of the non-static data members of its class that are of class 6197 // type (or array thereof), each such class has a trivial [default 6198 // constructor or destructor] 6199 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6200 return false; 6201 6202 // C++11 [class.dtor]p5: 6203 // A destructor is trivial if [...] 6204 // -- the destructor is not virtual 6205 if (CSM == CXXDestructor && MD->isVirtual()) { 6206 if (Diagnose) 6207 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6208 return false; 6209 } 6210 6211 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6212 // A [special member] for class X is trivial if [...] 6213 // -- class X has no virtual functions and no virtual base classes 6214 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6215 if (!Diagnose) 6216 return false; 6217 6218 if (RD->getNumVBases()) { 6219 // Check for virtual bases. We already know that the corresponding 6220 // member in all bases is trivial, so vbases must all be direct. 6221 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6222 assert(BS.isVirtual()); 6223 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6224 return false; 6225 } 6226 6227 // Must have a virtual method. 6228 for (const auto *MI : RD->methods()) { 6229 if (MI->isVirtual()) { 6230 SourceLocation MLoc = MI->getLocStart(); 6231 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6232 return false; 6233 } 6234 } 6235 6236 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6237 } 6238 6239 // Looks like it's trivial! 6240 return true; 6241 } 6242 6243 /// \brief Data used with FindHiddenVirtualMethod 6244 namespace { 6245 struct FindHiddenVirtualMethodData { 6246 Sema *S; 6247 CXXMethodDecl *Method; 6248 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6249 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6250 }; 6251 } 6252 6253 /// \brief Check whether any most overriden method from MD in Methods 6254 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 6255 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6256 if (MD->size_overridden_methods() == 0) 6257 return Methods.count(MD->getCanonicalDecl()); 6258 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6259 E = MD->end_overridden_methods(); 6260 I != E; ++I) 6261 if (CheckMostOverridenMethods(*I, Methods)) 6262 return true; 6263 return false; 6264 } 6265 6266 /// \brief Member lookup function that determines whether a given C++ 6267 /// method overloads virtual methods in a base class without overriding any, 6268 /// to be used with CXXRecordDecl::lookupInBases(). 6269 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 6270 CXXBasePath &Path, 6271 void *UserData) { 6272 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6273 6274 FindHiddenVirtualMethodData &Data 6275 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 6276 6277 DeclarationName Name = Data.Method->getDeclName(); 6278 assert(Name.getNameKind() == DeclarationName::Identifier); 6279 6280 bool foundSameNameMethod = false; 6281 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6282 for (Path.Decls = BaseRecord->lookup(Name); 6283 !Path.Decls.empty(); 6284 Path.Decls = Path.Decls.slice(1)) { 6285 NamedDecl *D = Path.Decls.front(); 6286 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6287 MD = MD->getCanonicalDecl(); 6288 foundSameNameMethod = true; 6289 // Interested only in hidden virtual methods. 6290 if (!MD->isVirtual()) 6291 continue; 6292 // If the method we are checking overrides a method from its base 6293 // don't warn about the other overloaded methods. Clang deviates from GCC 6294 // by only diagnosing overloads of inherited virtual functions that do not 6295 // override any other virtual functions in the base. GCC's 6296 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6297 // function from a base class. These cases may be better served by a 6298 // warning (not specific to virtual functions) on call sites when the call 6299 // would select a different function from the base class, were it visible. 6300 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6301 if (!Data.S->IsOverload(Data.Method, MD, false)) 6302 return true; 6303 // Collect the overload only if its hidden. 6304 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 6305 overloadedMethods.push_back(MD); 6306 } 6307 } 6308 6309 if (foundSameNameMethod) 6310 Data.OverloadedMethods.append(overloadedMethods.begin(), 6311 overloadedMethods.end()); 6312 return foundSameNameMethod; 6313 } 6314 6315 /// \brief Add the most overriden methods from MD to Methods 6316 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6317 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6318 if (MD->size_overridden_methods() == 0) 6319 Methods.insert(MD->getCanonicalDecl()); 6320 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6321 E = MD->end_overridden_methods(); 6322 I != E; ++I) 6323 AddMostOverridenMethods(*I, Methods); 6324 } 6325 6326 /// \brief Check if a method overloads virtual methods in a base class without 6327 /// overriding any. 6328 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6329 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6330 if (!MD->getDeclName().isIdentifier()) 6331 return; 6332 6333 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6334 /*bool RecordPaths=*/false, 6335 /*bool DetectVirtual=*/false); 6336 FindHiddenVirtualMethodData Data; 6337 Data.Method = MD; 6338 Data.S = this; 6339 6340 // Keep the base methods that were overriden or introduced in the subclass 6341 // by 'using' in a set. A base method not in this set is hidden. 6342 CXXRecordDecl *DC = MD->getParent(); 6343 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6344 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6345 NamedDecl *ND = *I; 6346 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6347 ND = shad->getTargetDecl(); 6348 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6349 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6350 } 6351 6352 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6353 OverloadedMethods = Data.OverloadedMethods; 6354 } 6355 6356 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6357 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6358 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6359 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6360 PartialDiagnostic PD = PDiag( 6361 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6362 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6363 Diag(overloadedMD->getLocation(), PD); 6364 } 6365 } 6366 6367 /// \brief Diagnose methods which overload virtual methods in a base class 6368 /// without overriding any. 6369 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6370 if (MD->isInvalidDecl()) 6371 return; 6372 6373 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6374 return; 6375 6376 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6377 FindHiddenVirtualMethods(MD, OverloadedMethods); 6378 if (!OverloadedMethods.empty()) { 6379 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6380 << MD << (OverloadedMethods.size() > 1); 6381 6382 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6383 } 6384 } 6385 6386 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6387 Decl *TagDecl, 6388 SourceLocation LBrac, 6389 SourceLocation RBrac, 6390 AttributeList *AttrList) { 6391 if (!TagDecl) 6392 return; 6393 6394 AdjustDeclIfTemplate(TagDecl); 6395 6396 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6397 if (l->getKind() != AttributeList::AT_Visibility) 6398 continue; 6399 l->setInvalid(); 6400 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6401 l->getName(); 6402 } 6403 6404 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6405 // strict aliasing violation! 6406 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6407 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6408 6409 CheckCompletedCXXClass( 6410 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6411 } 6412 6413 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6414 /// special functions, such as the default constructor, copy 6415 /// constructor, or destructor, to the given C++ class (C++ 6416 /// [special]p1). This routine can only be executed just before the 6417 /// definition of the class is complete. 6418 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6419 if (!ClassDecl->hasUserDeclaredConstructor()) 6420 ++ASTContext::NumImplicitDefaultConstructors; 6421 6422 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6423 ++ASTContext::NumImplicitCopyConstructors; 6424 6425 // If the properties or semantics of the copy constructor couldn't be 6426 // determined while the class was being declared, force a declaration 6427 // of it now. 6428 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6429 DeclareImplicitCopyConstructor(ClassDecl); 6430 } 6431 6432 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6433 ++ASTContext::NumImplicitMoveConstructors; 6434 6435 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6436 DeclareImplicitMoveConstructor(ClassDecl); 6437 } 6438 6439 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6440 ++ASTContext::NumImplicitCopyAssignmentOperators; 6441 6442 // If we have a dynamic class, then the copy assignment operator may be 6443 // virtual, so we have to declare it immediately. This ensures that, e.g., 6444 // it shows up in the right place in the vtable and that we diagnose 6445 // problems with the implicit exception specification. 6446 if (ClassDecl->isDynamicClass() || 6447 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6448 DeclareImplicitCopyAssignment(ClassDecl); 6449 } 6450 6451 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6452 ++ASTContext::NumImplicitMoveAssignmentOperators; 6453 6454 // Likewise for the move assignment operator. 6455 if (ClassDecl->isDynamicClass() || 6456 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6457 DeclareImplicitMoveAssignment(ClassDecl); 6458 } 6459 6460 if (!ClassDecl->hasUserDeclaredDestructor()) { 6461 ++ASTContext::NumImplicitDestructors; 6462 6463 // If we have a dynamic class, then the destructor may be virtual, so we 6464 // have to declare the destructor immediately. This ensures that, e.g., it 6465 // shows up in the right place in the vtable and that we diagnose problems 6466 // with the implicit exception specification. 6467 if (ClassDecl->isDynamicClass() || 6468 ClassDecl->needsOverloadResolutionForDestructor()) 6469 DeclareImplicitDestructor(ClassDecl); 6470 } 6471 } 6472 6473 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6474 if (!D) 6475 return 0; 6476 6477 // The order of template parameters is not important here. All names 6478 // get added to the same scope. 6479 SmallVector<TemplateParameterList *, 4> ParameterLists; 6480 6481 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6482 D = TD->getTemplatedDecl(); 6483 6484 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6485 ParameterLists.push_back(PSD->getTemplateParameters()); 6486 6487 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6488 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6489 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6490 6491 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6492 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6493 ParameterLists.push_back(FTD->getTemplateParameters()); 6494 } 6495 } 6496 6497 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6498 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6499 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6500 6501 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6502 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6503 ParameterLists.push_back(CTD->getTemplateParameters()); 6504 } 6505 } 6506 6507 unsigned Count = 0; 6508 for (TemplateParameterList *Params : ParameterLists) { 6509 if (Params->size() > 0) 6510 // Ignore explicit specializations; they don't contribute to the template 6511 // depth. 6512 ++Count; 6513 for (NamedDecl *Param : *Params) { 6514 if (Param->getDeclName()) { 6515 S->AddDecl(Param); 6516 IdResolver.AddDecl(Param); 6517 } 6518 } 6519 } 6520 6521 return Count; 6522 } 6523 6524 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6525 if (!RecordD) return; 6526 AdjustDeclIfTemplate(RecordD); 6527 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6528 PushDeclContext(S, Record); 6529 } 6530 6531 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6532 if (!RecordD) return; 6533 PopDeclContext(); 6534 } 6535 6536 /// This is used to implement the constant expression evaluation part of the 6537 /// attribute enable_if extension. There is nothing in standard C++ which would 6538 /// require reentering parameters. 6539 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6540 if (!Param) 6541 return; 6542 6543 S->AddDecl(Param); 6544 if (Param->getDeclName()) 6545 IdResolver.AddDecl(Param); 6546 } 6547 6548 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6549 /// parsing a top-level (non-nested) C++ class, and we are now 6550 /// parsing those parts of the given Method declaration that could 6551 /// not be parsed earlier (C++ [class.mem]p2), such as default 6552 /// arguments. This action should enter the scope of the given 6553 /// Method declaration as if we had just parsed the qualified method 6554 /// name. However, it should not bring the parameters into scope; 6555 /// that will be performed by ActOnDelayedCXXMethodParameter. 6556 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6557 } 6558 6559 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6560 /// C++ method declaration. We're (re-)introducing the given 6561 /// function parameter into scope for use in parsing later parts of 6562 /// the method declaration. For example, we could see an 6563 /// ActOnParamDefaultArgument event for this parameter. 6564 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6565 if (!ParamD) 6566 return; 6567 6568 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6569 6570 // If this parameter has an unparsed default argument, clear it out 6571 // to make way for the parsed default argument. 6572 if (Param->hasUnparsedDefaultArg()) 6573 Param->setDefaultArg(nullptr); 6574 6575 S->AddDecl(Param); 6576 if (Param->getDeclName()) 6577 IdResolver.AddDecl(Param); 6578 } 6579 6580 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6581 /// processing the delayed method declaration for Method. The method 6582 /// declaration is now considered finished. There may be a separate 6583 /// ActOnStartOfFunctionDef action later (not necessarily 6584 /// immediately!) for this method, if it was also defined inside the 6585 /// class body. 6586 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6587 if (!MethodD) 6588 return; 6589 6590 AdjustDeclIfTemplate(MethodD); 6591 6592 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6593 6594 // Now that we have our default arguments, check the constructor 6595 // again. It could produce additional diagnostics or affect whether 6596 // the class has implicitly-declared destructors, among other 6597 // things. 6598 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6599 CheckConstructor(Constructor); 6600 6601 // Check the default arguments, which we may have added. 6602 if (!Method->isInvalidDecl()) 6603 CheckCXXDefaultArguments(Method); 6604 } 6605 6606 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6607 /// the well-formedness of the constructor declarator @p D with type @p 6608 /// R. If there are any errors in the declarator, this routine will 6609 /// emit diagnostics and set the invalid bit to true. In any case, the type 6610 /// will be updated to reflect a well-formed type for the constructor and 6611 /// returned. 6612 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6613 StorageClass &SC) { 6614 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6615 6616 // C++ [class.ctor]p3: 6617 // A constructor shall not be virtual (10.3) or static (9.4). A 6618 // constructor can be invoked for a const, volatile or const 6619 // volatile object. A constructor shall not be declared const, 6620 // volatile, or const volatile (9.3.2). 6621 if (isVirtual) { 6622 if (!D.isInvalidType()) 6623 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6624 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6625 << SourceRange(D.getIdentifierLoc()); 6626 D.setInvalidType(); 6627 } 6628 if (SC == SC_Static) { 6629 if (!D.isInvalidType()) 6630 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6631 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6632 << SourceRange(D.getIdentifierLoc()); 6633 D.setInvalidType(); 6634 SC = SC_None; 6635 } 6636 6637 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6638 diagnoseIgnoredQualifiers( 6639 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6640 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6641 D.getDeclSpec().getRestrictSpecLoc(), 6642 D.getDeclSpec().getAtomicSpecLoc()); 6643 D.setInvalidType(); 6644 } 6645 6646 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6647 if (FTI.TypeQuals != 0) { 6648 if (FTI.TypeQuals & Qualifiers::Const) 6649 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6650 << "const" << SourceRange(D.getIdentifierLoc()); 6651 if (FTI.TypeQuals & Qualifiers::Volatile) 6652 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6653 << "volatile" << SourceRange(D.getIdentifierLoc()); 6654 if (FTI.TypeQuals & Qualifiers::Restrict) 6655 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6656 << "restrict" << SourceRange(D.getIdentifierLoc()); 6657 D.setInvalidType(); 6658 } 6659 6660 // C++0x [class.ctor]p4: 6661 // A constructor shall not be declared with a ref-qualifier. 6662 if (FTI.hasRefQualifier()) { 6663 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6664 << FTI.RefQualifierIsLValueRef 6665 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6666 D.setInvalidType(); 6667 } 6668 6669 // Rebuild the function type "R" without any type qualifiers (in 6670 // case any of the errors above fired) and with "void" as the 6671 // return type, since constructors don't have return types. 6672 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6673 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6674 return R; 6675 6676 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6677 EPI.TypeQuals = 0; 6678 EPI.RefQualifier = RQ_None; 6679 6680 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6681 } 6682 6683 /// CheckConstructor - Checks a fully-formed constructor for 6684 /// well-formedness, issuing any diagnostics required. Returns true if 6685 /// the constructor declarator is invalid. 6686 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6687 CXXRecordDecl *ClassDecl 6688 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6689 if (!ClassDecl) 6690 return Constructor->setInvalidDecl(); 6691 6692 // C++ [class.copy]p3: 6693 // A declaration of a constructor for a class X is ill-formed if 6694 // its first parameter is of type (optionally cv-qualified) X and 6695 // either there are no other parameters or else all other 6696 // parameters have default arguments. 6697 if (!Constructor->isInvalidDecl() && 6698 ((Constructor->getNumParams() == 1) || 6699 (Constructor->getNumParams() > 1 && 6700 Constructor->getParamDecl(1)->hasDefaultArg())) && 6701 Constructor->getTemplateSpecializationKind() 6702 != TSK_ImplicitInstantiation) { 6703 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6704 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6705 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6706 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6707 const char *ConstRef 6708 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6709 : " const &"; 6710 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6711 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6712 6713 // FIXME: Rather that making the constructor invalid, we should endeavor 6714 // to fix the type. 6715 Constructor->setInvalidDecl(); 6716 } 6717 } 6718 } 6719 6720 /// CheckDestructor - Checks a fully-formed destructor definition for 6721 /// well-formedness, issuing any diagnostics required. Returns true 6722 /// on error. 6723 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6724 CXXRecordDecl *RD = Destructor->getParent(); 6725 6726 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6727 SourceLocation Loc; 6728 6729 if (!Destructor->isImplicit()) 6730 Loc = Destructor->getLocation(); 6731 else 6732 Loc = RD->getLocation(); 6733 6734 // If we have a virtual destructor, look up the deallocation function 6735 FunctionDecl *OperatorDelete = nullptr; 6736 DeclarationName Name = 6737 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6738 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6739 return true; 6740 // If there's no class-specific operator delete, look up the global 6741 // non-array delete. 6742 if (!OperatorDelete) 6743 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6744 6745 MarkFunctionReferenced(Loc, OperatorDelete); 6746 6747 Destructor->setOperatorDelete(OperatorDelete); 6748 } 6749 6750 return false; 6751 } 6752 6753 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6754 /// the well-formednes of the destructor declarator @p D with type @p 6755 /// R. If there are any errors in the declarator, this routine will 6756 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6757 /// will be updated to reflect a well-formed type for the destructor and 6758 /// returned. 6759 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6760 StorageClass& SC) { 6761 // C++ [class.dtor]p1: 6762 // [...] A typedef-name that names a class is a class-name 6763 // (7.1.3); however, a typedef-name that names a class shall not 6764 // be used as the identifier in the declarator for a destructor 6765 // declaration. 6766 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6767 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6768 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6769 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6770 else if (const TemplateSpecializationType *TST = 6771 DeclaratorType->getAs<TemplateSpecializationType>()) 6772 if (TST->isTypeAlias()) 6773 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6774 << DeclaratorType << 1; 6775 6776 // C++ [class.dtor]p2: 6777 // A destructor is used to destroy objects of its class type. A 6778 // destructor takes no parameters, and no return type can be 6779 // specified for it (not even void). The address of a destructor 6780 // shall not be taken. A destructor shall not be static. A 6781 // destructor can be invoked for a const, volatile or const 6782 // volatile object. A destructor shall not be declared const, 6783 // volatile or const volatile (9.3.2). 6784 if (SC == SC_Static) { 6785 if (!D.isInvalidType()) 6786 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6787 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6788 << SourceRange(D.getIdentifierLoc()) 6789 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6790 6791 SC = SC_None; 6792 } 6793 if (!D.isInvalidType()) { 6794 // Destructors don't have return types, but the parser will 6795 // happily parse something like: 6796 // 6797 // class X { 6798 // float ~X(); 6799 // }; 6800 // 6801 // The return type will be eliminated later. 6802 if (D.getDeclSpec().hasTypeSpecifier()) 6803 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6804 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6805 << SourceRange(D.getIdentifierLoc()); 6806 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6807 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6808 SourceLocation(), 6809 D.getDeclSpec().getConstSpecLoc(), 6810 D.getDeclSpec().getVolatileSpecLoc(), 6811 D.getDeclSpec().getRestrictSpecLoc(), 6812 D.getDeclSpec().getAtomicSpecLoc()); 6813 D.setInvalidType(); 6814 } 6815 } 6816 6817 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6818 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6819 if (FTI.TypeQuals & Qualifiers::Const) 6820 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6821 << "const" << SourceRange(D.getIdentifierLoc()); 6822 if (FTI.TypeQuals & Qualifiers::Volatile) 6823 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6824 << "volatile" << SourceRange(D.getIdentifierLoc()); 6825 if (FTI.TypeQuals & Qualifiers::Restrict) 6826 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6827 << "restrict" << SourceRange(D.getIdentifierLoc()); 6828 D.setInvalidType(); 6829 } 6830 6831 // C++0x [class.dtor]p2: 6832 // A destructor shall not be declared with a ref-qualifier. 6833 if (FTI.hasRefQualifier()) { 6834 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6835 << FTI.RefQualifierIsLValueRef 6836 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6837 D.setInvalidType(); 6838 } 6839 6840 // Make sure we don't have any parameters. 6841 if (FTIHasNonVoidParameters(FTI)) { 6842 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6843 6844 // Delete the parameters. 6845 FTI.freeParams(); 6846 D.setInvalidType(); 6847 } 6848 6849 // Make sure the destructor isn't variadic. 6850 if (FTI.isVariadic) { 6851 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6852 D.setInvalidType(); 6853 } 6854 6855 // Rebuild the function type "R" without any type qualifiers or 6856 // parameters (in case any of the errors above fired) and with 6857 // "void" as the return type, since destructors don't have return 6858 // types. 6859 if (!D.isInvalidType()) 6860 return R; 6861 6862 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6863 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6864 EPI.Variadic = false; 6865 EPI.TypeQuals = 0; 6866 EPI.RefQualifier = RQ_None; 6867 return Context.getFunctionType(Context.VoidTy, None, EPI); 6868 } 6869 6870 static void extendLeft(SourceRange &R, const SourceRange &Before) { 6871 if (Before.isInvalid()) 6872 return; 6873 R.setBegin(Before.getBegin()); 6874 if (R.getEnd().isInvalid()) 6875 R.setEnd(Before.getEnd()); 6876 } 6877 6878 static void extendRight(SourceRange &R, const SourceRange &After) { 6879 if (After.isInvalid()) 6880 return; 6881 if (R.getBegin().isInvalid()) 6882 R.setBegin(After.getBegin()); 6883 R.setEnd(After.getEnd()); 6884 } 6885 6886 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6887 /// well-formednes of the conversion function declarator @p D with 6888 /// type @p R. If there are any errors in the declarator, this routine 6889 /// will emit diagnostics and return true. Otherwise, it will return 6890 /// false. Either way, the type @p R will be updated to reflect a 6891 /// well-formed type for the conversion operator. 6892 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6893 StorageClass& SC) { 6894 // C++ [class.conv.fct]p1: 6895 // Neither parameter types nor return type can be specified. The 6896 // type of a conversion function (8.3.5) is "function taking no 6897 // parameter returning conversion-type-id." 6898 if (SC == SC_Static) { 6899 if (!D.isInvalidType()) 6900 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6901 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6902 << D.getName().getSourceRange(); 6903 D.setInvalidType(); 6904 SC = SC_None; 6905 } 6906 6907 TypeSourceInfo *ConvTSI = nullptr; 6908 QualType ConvType = 6909 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 6910 6911 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6912 // Conversion functions don't have return types, but the parser will 6913 // happily parse something like: 6914 // 6915 // class X { 6916 // float operator bool(); 6917 // }; 6918 // 6919 // The return type will be changed later anyway. 6920 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6921 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6922 << SourceRange(D.getIdentifierLoc()); 6923 D.setInvalidType(); 6924 } 6925 6926 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6927 6928 // Make sure we don't have any parameters. 6929 if (Proto->getNumParams() > 0) { 6930 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6931 6932 // Delete the parameters. 6933 D.getFunctionTypeInfo().freeParams(); 6934 D.setInvalidType(); 6935 } else if (Proto->isVariadic()) { 6936 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6937 D.setInvalidType(); 6938 } 6939 6940 // Diagnose "&operator bool()" and other such nonsense. This 6941 // is actually a gcc extension which we don't support. 6942 if (Proto->getReturnType() != ConvType) { 6943 bool NeedsTypedef = false; 6944 SourceRange Before, After; 6945 6946 // Walk the chunks and extract information on them for our diagnostic. 6947 bool PastFunctionChunk = false; 6948 for (auto &Chunk : D.type_objects()) { 6949 switch (Chunk.Kind) { 6950 case DeclaratorChunk::Function: 6951 if (!PastFunctionChunk) { 6952 if (Chunk.Fun.HasTrailingReturnType) { 6953 TypeSourceInfo *TRT = nullptr; 6954 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 6955 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 6956 } 6957 PastFunctionChunk = true; 6958 break; 6959 } 6960 // Fall through. 6961 case DeclaratorChunk::Array: 6962 NeedsTypedef = true; 6963 extendRight(After, Chunk.getSourceRange()); 6964 break; 6965 6966 case DeclaratorChunk::Pointer: 6967 case DeclaratorChunk::BlockPointer: 6968 case DeclaratorChunk::Reference: 6969 case DeclaratorChunk::MemberPointer: 6970 extendLeft(Before, Chunk.getSourceRange()); 6971 break; 6972 6973 case DeclaratorChunk::Paren: 6974 extendLeft(Before, Chunk.Loc); 6975 extendRight(After, Chunk.EndLoc); 6976 break; 6977 } 6978 } 6979 6980 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 6981 After.isValid() ? After.getBegin() : 6982 D.getIdentifierLoc(); 6983 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 6984 DB << Before << After; 6985 6986 if (!NeedsTypedef) { 6987 DB << /*don't need a typedef*/0; 6988 6989 // If we can provide a correct fix-it hint, do so. 6990 if (After.isInvalid() && ConvTSI) { 6991 SourceLocation InsertLoc = 6992 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 6993 DB << FixItHint::CreateInsertion(InsertLoc, " ") 6994 << FixItHint::CreateInsertionFromRange( 6995 InsertLoc, CharSourceRange::getTokenRange(Before)) 6996 << FixItHint::CreateRemoval(Before); 6997 } 6998 } else if (!Proto->getReturnType()->isDependentType()) { 6999 DB << /*typedef*/1 << Proto->getReturnType(); 7000 } else if (getLangOpts().CPlusPlus11) { 7001 DB << /*alias template*/2 << Proto->getReturnType(); 7002 } else { 7003 DB << /*might not be fixable*/3; 7004 } 7005 7006 // Recover by incorporating the other type chunks into the result type. 7007 // Note, this does *not* change the name of the function. This is compatible 7008 // with the GCC extension: 7009 // struct S { &operator int(); } s; 7010 // int &r = s.operator int(); // ok in GCC 7011 // S::operator int&() {} // error in GCC, function name is 'operator int'. 7012 ConvType = Proto->getReturnType(); 7013 } 7014 7015 // C++ [class.conv.fct]p4: 7016 // The conversion-type-id shall not represent a function type nor 7017 // an array type. 7018 if (ConvType->isArrayType()) { 7019 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7020 ConvType = Context.getPointerType(ConvType); 7021 D.setInvalidType(); 7022 } else if (ConvType->isFunctionType()) { 7023 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7024 ConvType = Context.getPointerType(ConvType); 7025 D.setInvalidType(); 7026 } 7027 7028 // Rebuild the function type "R" without any parameters (in case any 7029 // of the errors above fired) and with the conversion type as the 7030 // return type. 7031 if (D.isInvalidType()) 7032 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7033 7034 // C++0x explicit conversion operators. 7035 if (D.getDeclSpec().isExplicitSpecified()) 7036 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7037 getLangOpts().CPlusPlus11 ? 7038 diag::warn_cxx98_compat_explicit_conversion_functions : 7039 diag::ext_explicit_conversion_functions) 7040 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 7041 } 7042 7043 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 7044 /// the declaration of the given C++ conversion function. This routine 7045 /// is responsible for recording the conversion function in the C++ 7046 /// class, if possible. 7047 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 7048 assert(Conversion && "Expected to receive a conversion function declaration"); 7049 7050 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 7051 7052 // Make sure we aren't redeclaring the conversion function. 7053 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 7054 7055 // C++ [class.conv.fct]p1: 7056 // [...] A conversion function is never used to convert a 7057 // (possibly cv-qualified) object to the (possibly cv-qualified) 7058 // same object type (or a reference to it), to a (possibly 7059 // cv-qualified) base class of that type (or a reference to it), 7060 // or to (possibly cv-qualified) void. 7061 // FIXME: Suppress this warning if the conversion function ends up being a 7062 // virtual function that overrides a virtual function in a base class. 7063 QualType ClassType 7064 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7065 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 7066 ConvType = ConvTypeRef->getPointeeType(); 7067 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 7068 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 7069 /* Suppress diagnostics for instantiations. */; 7070 else if (ConvType->isRecordType()) { 7071 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 7072 if (ConvType == ClassType) 7073 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 7074 << ClassType; 7075 else if (IsDerivedFrom(ClassType, ConvType)) 7076 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 7077 << ClassType << ConvType; 7078 } else if (ConvType->isVoidType()) { 7079 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 7080 << ClassType << ConvType; 7081 } 7082 7083 if (FunctionTemplateDecl *ConversionTemplate 7084 = Conversion->getDescribedFunctionTemplate()) 7085 return ConversionTemplate; 7086 7087 return Conversion; 7088 } 7089 7090 //===----------------------------------------------------------------------===// 7091 // Namespace Handling 7092 //===----------------------------------------------------------------------===// 7093 7094 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 7095 /// reopened. 7096 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 7097 SourceLocation Loc, 7098 IdentifierInfo *II, bool *IsInline, 7099 NamespaceDecl *PrevNS) { 7100 assert(*IsInline != PrevNS->isInline()); 7101 7102 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 7103 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 7104 // inline namespaces, with the intention of bringing names into namespace std. 7105 // 7106 // We support this just well enough to get that case working; this is not 7107 // sufficient to support reopening namespaces as inline in general. 7108 if (*IsInline && II && II->getName().startswith("__atomic") && 7109 S.getSourceManager().isInSystemHeader(Loc)) { 7110 // Mark all prior declarations of the namespace as inline. 7111 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 7112 NS = NS->getPreviousDecl()) 7113 NS->setInline(*IsInline); 7114 // Patch up the lookup table for the containing namespace. This isn't really 7115 // correct, but it's good enough for this particular case. 7116 for (auto *I : PrevNS->decls()) 7117 if (auto *ND = dyn_cast<NamedDecl>(I)) 7118 PrevNS->getParent()->makeDeclVisibleInContext(ND); 7119 return; 7120 } 7121 7122 if (PrevNS->isInline()) 7123 // The user probably just forgot the 'inline', so suggest that it 7124 // be added back. 7125 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 7126 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 7127 else 7128 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 7129 7130 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 7131 *IsInline = PrevNS->isInline(); 7132 } 7133 7134 /// ActOnStartNamespaceDef - This is called at the start of a namespace 7135 /// definition. 7136 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 7137 SourceLocation InlineLoc, 7138 SourceLocation NamespaceLoc, 7139 SourceLocation IdentLoc, 7140 IdentifierInfo *II, 7141 SourceLocation LBrace, 7142 AttributeList *AttrList) { 7143 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 7144 // For anonymous namespace, take the location of the left brace. 7145 SourceLocation Loc = II ? IdentLoc : LBrace; 7146 bool IsInline = InlineLoc.isValid(); 7147 bool IsInvalid = false; 7148 bool IsStd = false; 7149 bool AddToKnown = false; 7150 Scope *DeclRegionScope = NamespcScope->getParent(); 7151 7152 NamespaceDecl *PrevNS = nullptr; 7153 if (II) { 7154 // C++ [namespace.def]p2: 7155 // The identifier in an original-namespace-definition shall not 7156 // have been previously defined in the declarative region in 7157 // which the original-namespace-definition appears. The 7158 // identifier in an original-namespace-definition is the name of 7159 // the namespace. Subsequently in that declarative region, it is 7160 // treated as an original-namespace-name. 7161 // 7162 // Since namespace names are unique in their scope, and we don't 7163 // look through using directives, just look for any ordinary names. 7164 7165 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 7166 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 7167 Decl::IDNS_Namespace; 7168 NamedDecl *PrevDecl = nullptr; 7169 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 7170 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 7171 ++I) { 7172 if ((*I)->getIdentifierNamespace() & IDNS) { 7173 PrevDecl = *I; 7174 break; 7175 } 7176 } 7177 7178 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7179 7180 if (PrevNS) { 7181 // This is an extended namespace definition. 7182 if (IsInline != PrevNS->isInline()) 7183 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7184 &IsInline, PrevNS); 7185 } else if (PrevDecl) { 7186 // This is an invalid name redefinition. 7187 Diag(Loc, diag::err_redefinition_different_kind) 7188 << II; 7189 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7190 IsInvalid = true; 7191 // Continue on to push Namespc as current DeclContext and return it. 7192 } else if (II->isStr("std") && 7193 CurContext->getRedeclContext()->isTranslationUnit()) { 7194 // This is the first "real" definition of the namespace "std", so update 7195 // our cache of the "std" namespace to point at this definition. 7196 PrevNS = getStdNamespace(); 7197 IsStd = true; 7198 AddToKnown = !IsInline; 7199 } else { 7200 // We've seen this namespace for the first time. 7201 AddToKnown = !IsInline; 7202 } 7203 } else { 7204 // Anonymous namespaces. 7205 7206 // Determine whether the parent already has an anonymous namespace. 7207 DeclContext *Parent = CurContext->getRedeclContext(); 7208 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7209 PrevNS = TU->getAnonymousNamespace(); 7210 } else { 7211 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7212 PrevNS = ND->getAnonymousNamespace(); 7213 } 7214 7215 if (PrevNS && IsInline != PrevNS->isInline()) 7216 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7217 &IsInline, PrevNS); 7218 } 7219 7220 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7221 StartLoc, Loc, II, PrevNS); 7222 if (IsInvalid) 7223 Namespc->setInvalidDecl(); 7224 7225 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7226 7227 // FIXME: Should we be merging attributes? 7228 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7229 PushNamespaceVisibilityAttr(Attr, Loc); 7230 7231 if (IsStd) 7232 StdNamespace = Namespc; 7233 if (AddToKnown) 7234 KnownNamespaces[Namespc] = false; 7235 7236 if (II) { 7237 PushOnScopeChains(Namespc, DeclRegionScope); 7238 } else { 7239 // Link the anonymous namespace into its parent. 7240 DeclContext *Parent = CurContext->getRedeclContext(); 7241 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7242 TU->setAnonymousNamespace(Namespc); 7243 } else { 7244 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7245 } 7246 7247 CurContext->addDecl(Namespc); 7248 7249 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7250 // behaves as if it were replaced by 7251 // namespace unique { /* empty body */ } 7252 // using namespace unique; 7253 // namespace unique { namespace-body } 7254 // where all occurrences of 'unique' in a translation unit are 7255 // replaced by the same identifier and this identifier differs 7256 // from all other identifiers in the entire program. 7257 7258 // We just create the namespace with an empty name and then add an 7259 // implicit using declaration, just like the standard suggests. 7260 // 7261 // CodeGen enforces the "universally unique" aspect by giving all 7262 // declarations semantically contained within an anonymous 7263 // namespace internal linkage. 7264 7265 if (!PrevNS) { 7266 UsingDirectiveDecl* UD 7267 = UsingDirectiveDecl::Create(Context, Parent, 7268 /* 'using' */ LBrace, 7269 /* 'namespace' */ SourceLocation(), 7270 /* qualifier */ NestedNameSpecifierLoc(), 7271 /* identifier */ SourceLocation(), 7272 Namespc, 7273 /* Ancestor */ Parent); 7274 UD->setImplicit(); 7275 Parent->addDecl(UD); 7276 } 7277 } 7278 7279 ActOnDocumentableDecl(Namespc); 7280 7281 // Although we could have an invalid decl (i.e. the namespace name is a 7282 // redefinition), push it as current DeclContext and try to continue parsing. 7283 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7284 // for the namespace has the declarations that showed up in that particular 7285 // namespace definition. 7286 PushDeclContext(NamespcScope, Namespc); 7287 return Namespc; 7288 } 7289 7290 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7291 /// is a namespace alias, returns the namespace it points to. 7292 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7293 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7294 return AD->getNamespace(); 7295 return dyn_cast_or_null<NamespaceDecl>(D); 7296 } 7297 7298 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7299 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7300 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7301 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7302 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7303 Namespc->setRBraceLoc(RBrace); 7304 PopDeclContext(); 7305 if (Namespc->hasAttr<VisibilityAttr>()) 7306 PopPragmaVisibility(true, RBrace); 7307 } 7308 7309 CXXRecordDecl *Sema::getStdBadAlloc() const { 7310 return cast_or_null<CXXRecordDecl>( 7311 StdBadAlloc.get(Context.getExternalSource())); 7312 } 7313 7314 NamespaceDecl *Sema::getStdNamespace() const { 7315 return cast_or_null<NamespaceDecl>( 7316 StdNamespace.get(Context.getExternalSource())); 7317 } 7318 7319 /// \brief Retrieve the special "std" namespace, which may require us to 7320 /// implicitly define the namespace. 7321 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7322 if (!StdNamespace) { 7323 // The "std" namespace has not yet been defined, so build one implicitly. 7324 StdNamespace = NamespaceDecl::Create(Context, 7325 Context.getTranslationUnitDecl(), 7326 /*Inline=*/false, 7327 SourceLocation(), SourceLocation(), 7328 &PP.getIdentifierTable().get("std"), 7329 /*PrevDecl=*/nullptr); 7330 getStdNamespace()->setImplicit(true); 7331 } 7332 7333 return getStdNamespace(); 7334 } 7335 7336 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7337 assert(getLangOpts().CPlusPlus && 7338 "Looking for std::initializer_list outside of C++."); 7339 7340 // We're looking for implicit instantiations of 7341 // template <typename E> class std::initializer_list. 7342 7343 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7344 return false; 7345 7346 ClassTemplateDecl *Template = nullptr; 7347 const TemplateArgument *Arguments = nullptr; 7348 7349 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7350 7351 ClassTemplateSpecializationDecl *Specialization = 7352 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7353 if (!Specialization) 7354 return false; 7355 7356 Template = Specialization->getSpecializedTemplate(); 7357 Arguments = Specialization->getTemplateArgs().data(); 7358 } else if (const TemplateSpecializationType *TST = 7359 Ty->getAs<TemplateSpecializationType>()) { 7360 Template = dyn_cast_or_null<ClassTemplateDecl>( 7361 TST->getTemplateName().getAsTemplateDecl()); 7362 Arguments = TST->getArgs(); 7363 } 7364 if (!Template) 7365 return false; 7366 7367 if (!StdInitializerList) { 7368 // Haven't recognized std::initializer_list yet, maybe this is it. 7369 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7370 if (TemplateClass->getIdentifier() != 7371 &PP.getIdentifierTable().get("initializer_list") || 7372 !getStdNamespace()->InEnclosingNamespaceSetOf( 7373 TemplateClass->getDeclContext())) 7374 return false; 7375 // This is a template called std::initializer_list, but is it the right 7376 // template? 7377 TemplateParameterList *Params = Template->getTemplateParameters(); 7378 if (Params->getMinRequiredArguments() != 1) 7379 return false; 7380 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7381 return false; 7382 7383 // It's the right template. 7384 StdInitializerList = Template; 7385 } 7386 7387 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 7388 return false; 7389 7390 // This is an instance of std::initializer_list. Find the argument type. 7391 if (Element) 7392 *Element = Arguments[0].getAsType(); 7393 return true; 7394 } 7395 7396 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7397 NamespaceDecl *Std = S.getStdNamespace(); 7398 if (!Std) { 7399 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7400 return nullptr; 7401 } 7402 7403 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7404 Loc, Sema::LookupOrdinaryName); 7405 if (!S.LookupQualifiedName(Result, Std)) { 7406 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7407 return nullptr; 7408 } 7409 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7410 if (!Template) { 7411 Result.suppressDiagnostics(); 7412 // We found something weird. Complain about the first thing we found. 7413 NamedDecl *Found = *Result.begin(); 7414 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7415 return nullptr; 7416 } 7417 7418 // We found some template called std::initializer_list. Now verify that it's 7419 // correct. 7420 TemplateParameterList *Params = Template->getTemplateParameters(); 7421 if (Params->getMinRequiredArguments() != 1 || 7422 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7423 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7424 return nullptr; 7425 } 7426 7427 return Template; 7428 } 7429 7430 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7431 if (!StdInitializerList) { 7432 StdInitializerList = LookupStdInitializerList(*this, Loc); 7433 if (!StdInitializerList) 7434 return QualType(); 7435 } 7436 7437 TemplateArgumentListInfo Args(Loc, Loc); 7438 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7439 Context.getTrivialTypeSourceInfo(Element, 7440 Loc))); 7441 return Context.getCanonicalType( 7442 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7443 } 7444 7445 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7446 // C++ [dcl.init.list]p2: 7447 // A constructor is an initializer-list constructor if its first parameter 7448 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7449 // std::initializer_list<E> for some type E, and either there are no other 7450 // parameters or else all other parameters have default arguments. 7451 if (Ctor->getNumParams() < 1 || 7452 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7453 return false; 7454 7455 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7456 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7457 ArgType = RT->getPointeeType().getUnqualifiedType(); 7458 7459 return isStdInitializerList(ArgType, nullptr); 7460 } 7461 7462 /// \brief Determine whether a using statement is in a context where it will be 7463 /// apply in all contexts. 7464 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7465 switch (CurContext->getDeclKind()) { 7466 case Decl::TranslationUnit: 7467 return true; 7468 case Decl::LinkageSpec: 7469 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7470 default: 7471 return false; 7472 } 7473 } 7474 7475 namespace { 7476 7477 // Callback to only accept typo corrections that are namespaces. 7478 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7479 public: 7480 bool ValidateCandidate(const TypoCorrection &candidate) override { 7481 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7482 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7483 return false; 7484 } 7485 }; 7486 7487 } 7488 7489 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7490 CXXScopeSpec &SS, 7491 SourceLocation IdentLoc, 7492 IdentifierInfo *Ident) { 7493 R.clear(); 7494 if (TypoCorrection Corrected = 7495 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7496 llvm::make_unique<NamespaceValidatorCCC>(), 7497 Sema::CTK_ErrorRecovery)) { 7498 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7499 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7500 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7501 Ident->getName().equals(CorrectedStr); 7502 S.diagnoseTypo(Corrected, 7503 S.PDiag(diag::err_using_directive_member_suggest) 7504 << Ident << DC << DroppedSpecifier << SS.getRange(), 7505 S.PDiag(diag::note_namespace_defined_here)); 7506 } else { 7507 S.diagnoseTypo(Corrected, 7508 S.PDiag(diag::err_using_directive_suggest) << Ident, 7509 S.PDiag(diag::note_namespace_defined_here)); 7510 } 7511 R.addDecl(Corrected.getCorrectionDecl()); 7512 return true; 7513 } 7514 return false; 7515 } 7516 7517 Decl *Sema::ActOnUsingDirective(Scope *S, 7518 SourceLocation UsingLoc, 7519 SourceLocation NamespcLoc, 7520 CXXScopeSpec &SS, 7521 SourceLocation IdentLoc, 7522 IdentifierInfo *NamespcName, 7523 AttributeList *AttrList) { 7524 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7525 assert(NamespcName && "Invalid NamespcName."); 7526 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7527 7528 // This can only happen along a recovery path. 7529 while (S->getFlags() & Scope::TemplateParamScope) 7530 S = S->getParent(); 7531 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7532 7533 UsingDirectiveDecl *UDir = nullptr; 7534 NestedNameSpecifier *Qualifier = nullptr; 7535 if (SS.isSet()) 7536 Qualifier = SS.getScopeRep(); 7537 7538 // Lookup namespace name. 7539 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7540 LookupParsedName(R, S, &SS); 7541 if (R.isAmbiguous()) 7542 return nullptr; 7543 7544 if (R.empty()) { 7545 R.clear(); 7546 // Allow "using namespace std;" or "using namespace ::std;" even if 7547 // "std" hasn't been defined yet, for GCC compatibility. 7548 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7549 NamespcName->isStr("std")) { 7550 Diag(IdentLoc, diag::ext_using_undefined_std); 7551 R.addDecl(getOrCreateStdNamespace()); 7552 R.resolveKind(); 7553 } 7554 // Otherwise, attempt typo correction. 7555 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7556 } 7557 7558 if (!R.empty()) { 7559 NamedDecl *Named = R.getFoundDecl(); 7560 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7561 && "expected namespace decl"); 7562 7563 // The use of a nested name specifier may trigger deprecation warnings. 7564 DiagnoseUseOfDecl(Named, IdentLoc); 7565 7566 // C++ [namespace.udir]p1: 7567 // A using-directive specifies that the names in the nominated 7568 // namespace can be used in the scope in which the 7569 // using-directive appears after the using-directive. During 7570 // unqualified name lookup (3.4.1), the names appear as if they 7571 // were declared in the nearest enclosing namespace which 7572 // contains both the using-directive and the nominated 7573 // namespace. [Note: in this context, "contains" means "contains 7574 // directly or indirectly". ] 7575 7576 // Find enclosing context containing both using-directive and 7577 // nominated namespace. 7578 NamespaceDecl *NS = getNamespaceDecl(Named); 7579 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7580 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7581 CommonAncestor = CommonAncestor->getParent(); 7582 7583 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7584 SS.getWithLocInContext(Context), 7585 IdentLoc, Named, CommonAncestor); 7586 7587 if (IsUsingDirectiveInToplevelContext(CurContext) && 7588 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7589 Diag(IdentLoc, diag::warn_using_directive_in_header); 7590 } 7591 7592 PushUsingDirective(S, UDir); 7593 } else { 7594 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7595 } 7596 7597 if (UDir) 7598 ProcessDeclAttributeList(S, UDir, AttrList); 7599 7600 return UDir; 7601 } 7602 7603 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7604 // If the scope has an associated entity and the using directive is at 7605 // namespace or translation unit scope, add the UsingDirectiveDecl into 7606 // its lookup structure so qualified name lookup can find it. 7607 DeclContext *Ctx = S->getEntity(); 7608 if (Ctx && !Ctx->isFunctionOrMethod()) 7609 Ctx->addDecl(UDir); 7610 else 7611 // Otherwise, it is at block scope. The using-directives will affect lookup 7612 // only to the end of the scope. 7613 S->PushUsingDirective(UDir); 7614 } 7615 7616 7617 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7618 AccessSpecifier AS, 7619 bool HasUsingKeyword, 7620 SourceLocation UsingLoc, 7621 CXXScopeSpec &SS, 7622 UnqualifiedId &Name, 7623 AttributeList *AttrList, 7624 bool HasTypenameKeyword, 7625 SourceLocation TypenameLoc) { 7626 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7627 7628 switch (Name.getKind()) { 7629 case UnqualifiedId::IK_ImplicitSelfParam: 7630 case UnqualifiedId::IK_Identifier: 7631 case UnqualifiedId::IK_OperatorFunctionId: 7632 case UnqualifiedId::IK_LiteralOperatorId: 7633 case UnqualifiedId::IK_ConversionFunctionId: 7634 break; 7635 7636 case UnqualifiedId::IK_ConstructorName: 7637 case UnqualifiedId::IK_ConstructorTemplateId: 7638 // C++11 inheriting constructors. 7639 Diag(Name.getLocStart(), 7640 getLangOpts().CPlusPlus11 ? 7641 diag::warn_cxx98_compat_using_decl_constructor : 7642 diag::err_using_decl_constructor) 7643 << SS.getRange(); 7644 7645 if (getLangOpts().CPlusPlus11) break; 7646 7647 return nullptr; 7648 7649 case UnqualifiedId::IK_DestructorName: 7650 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7651 << SS.getRange(); 7652 return nullptr; 7653 7654 case UnqualifiedId::IK_TemplateId: 7655 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7656 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7657 return nullptr; 7658 } 7659 7660 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7661 DeclarationName TargetName = TargetNameInfo.getName(); 7662 if (!TargetName) 7663 return nullptr; 7664 7665 // Warn about access declarations. 7666 if (!HasUsingKeyword) { 7667 Diag(Name.getLocStart(), 7668 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7669 : diag::warn_access_decl_deprecated) 7670 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7671 } 7672 7673 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7674 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7675 return nullptr; 7676 7677 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7678 TargetNameInfo, AttrList, 7679 /* IsInstantiation */ false, 7680 HasTypenameKeyword, TypenameLoc); 7681 if (UD) 7682 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7683 7684 return UD; 7685 } 7686 7687 /// \brief Determine whether a using declaration considers the given 7688 /// declarations as "equivalent", e.g., if they are redeclarations of 7689 /// the same entity or are both typedefs of the same type. 7690 static bool 7691 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7692 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7693 return true; 7694 7695 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7696 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7697 return Context.hasSameType(TD1->getUnderlyingType(), 7698 TD2->getUnderlyingType()); 7699 7700 return false; 7701 } 7702 7703 7704 /// Determines whether to create a using shadow decl for a particular 7705 /// decl, given the set of decls existing prior to this using lookup. 7706 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7707 const LookupResult &Previous, 7708 UsingShadowDecl *&PrevShadow) { 7709 // Diagnose finding a decl which is not from a base class of the 7710 // current class. We do this now because there are cases where this 7711 // function will silently decide not to build a shadow decl, which 7712 // will pre-empt further diagnostics. 7713 // 7714 // We don't need to do this in C++0x because we do the check once on 7715 // the qualifier. 7716 // 7717 // FIXME: diagnose the following if we care enough: 7718 // struct A { int foo; }; 7719 // struct B : A { using A::foo; }; 7720 // template <class T> struct C : A {}; 7721 // template <class T> struct D : C<T> { using B::foo; } // <--- 7722 // This is invalid (during instantiation) in C++03 because B::foo 7723 // resolves to the using decl in B, which is not a base class of D<T>. 7724 // We can't diagnose it immediately because C<T> is an unknown 7725 // specialization. The UsingShadowDecl in D<T> then points directly 7726 // to A::foo, which will look well-formed when we instantiate. 7727 // The right solution is to not collapse the shadow-decl chain. 7728 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7729 DeclContext *OrigDC = Orig->getDeclContext(); 7730 7731 // Handle enums and anonymous structs. 7732 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7733 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7734 while (OrigRec->isAnonymousStructOrUnion()) 7735 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7736 7737 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7738 if (OrigDC == CurContext) { 7739 Diag(Using->getLocation(), 7740 diag::err_using_decl_nested_name_specifier_is_current_class) 7741 << Using->getQualifierLoc().getSourceRange(); 7742 Diag(Orig->getLocation(), diag::note_using_decl_target); 7743 return true; 7744 } 7745 7746 Diag(Using->getQualifierLoc().getBeginLoc(), 7747 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7748 << Using->getQualifier() 7749 << cast<CXXRecordDecl>(CurContext) 7750 << Using->getQualifierLoc().getSourceRange(); 7751 Diag(Orig->getLocation(), diag::note_using_decl_target); 7752 return true; 7753 } 7754 } 7755 7756 if (Previous.empty()) return false; 7757 7758 NamedDecl *Target = Orig; 7759 if (isa<UsingShadowDecl>(Target)) 7760 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7761 7762 // If the target happens to be one of the previous declarations, we 7763 // don't have a conflict. 7764 // 7765 // FIXME: but we might be increasing its access, in which case we 7766 // should redeclare it. 7767 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7768 bool FoundEquivalentDecl = false; 7769 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7770 I != E; ++I) { 7771 NamedDecl *D = (*I)->getUnderlyingDecl(); 7772 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7773 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7774 PrevShadow = Shadow; 7775 FoundEquivalentDecl = true; 7776 } 7777 7778 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7779 } 7780 7781 if (FoundEquivalentDecl) 7782 return false; 7783 7784 if (FunctionDecl *FD = Target->getAsFunction()) { 7785 NamedDecl *OldDecl = nullptr; 7786 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7787 /*IsForUsingDecl*/ true)) { 7788 case Ovl_Overload: 7789 return false; 7790 7791 case Ovl_NonFunction: 7792 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7793 break; 7794 7795 // We found a decl with the exact signature. 7796 case Ovl_Match: 7797 // If we're in a record, we want to hide the target, so we 7798 // return true (without a diagnostic) to tell the caller not to 7799 // build a shadow decl. 7800 if (CurContext->isRecord()) 7801 return true; 7802 7803 // If we're not in a record, this is an error. 7804 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7805 break; 7806 } 7807 7808 Diag(Target->getLocation(), diag::note_using_decl_target); 7809 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7810 return true; 7811 } 7812 7813 // Target is not a function. 7814 7815 if (isa<TagDecl>(Target)) { 7816 // No conflict between a tag and a non-tag. 7817 if (!Tag) return false; 7818 7819 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7820 Diag(Target->getLocation(), diag::note_using_decl_target); 7821 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7822 return true; 7823 } 7824 7825 // No conflict between a tag and a non-tag. 7826 if (!NonTag) return false; 7827 7828 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7829 Diag(Target->getLocation(), diag::note_using_decl_target); 7830 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7831 return true; 7832 } 7833 7834 /// Builds a shadow declaration corresponding to a 'using' declaration. 7835 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7836 UsingDecl *UD, 7837 NamedDecl *Orig, 7838 UsingShadowDecl *PrevDecl) { 7839 7840 // If we resolved to another shadow declaration, just coalesce them. 7841 NamedDecl *Target = Orig; 7842 if (isa<UsingShadowDecl>(Target)) { 7843 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7844 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7845 } 7846 7847 UsingShadowDecl *Shadow 7848 = UsingShadowDecl::Create(Context, CurContext, 7849 UD->getLocation(), UD, Target); 7850 UD->addShadowDecl(Shadow); 7851 7852 Shadow->setAccess(UD->getAccess()); 7853 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7854 Shadow->setInvalidDecl(); 7855 7856 Shadow->setPreviousDecl(PrevDecl); 7857 7858 if (S) 7859 PushOnScopeChains(Shadow, S); 7860 else 7861 CurContext->addDecl(Shadow); 7862 7863 7864 return Shadow; 7865 } 7866 7867 /// Hides a using shadow declaration. This is required by the current 7868 /// using-decl implementation when a resolvable using declaration in a 7869 /// class is followed by a declaration which would hide or override 7870 /// one or more of the using decl's targets; for example: 7871 /// 7872 /// struct Base { void foo(int); }; 7873 /// struct Derived : Base { 7874 /// using Base::foo; 7875 /// void foo(int); 7876 /// }; 7877 /// 7878 /// The governing language is C++03 [namespace.udecl]p12: 7879 /// 7880 /// When a using-declaration brings names from a base class into a 7881 /// derived class scope, member functions in the derived class 7882 /// override and/or hide member functions with the same name and 7883 /// parameter types in a base class (rather than conflicting). 7884 /// 7885 /// There are two ways to implement this: 7886 /// (1) optimistically create shadow decls when they're not hidden 7887 /// by existing declarations, or 7888 /// (2) don't create any shadow decls (or at least don't make them 7889 /// visible) until we've fully parsed/instantiated the class. 7890 /// The problem with (1) is that we might have to retroactively remove 7891 /// a shadow decl, which requires several O(n) operations because the 7892 /// decl structures are (very reasonably) not designed for removal. 7893 /// (2) avoids this but is very fiddly and phase-dependent. 7894 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7895 if (Shadow->getDeclName().getNameKind() == 7896 DeclarationName::CXXConversionFunctionName) 7897 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7898 7899 // Remove it from the DeclContext... 7900 Shadow->getDeclContext()->removeDecl(Shadow); 7901 7902 // ...and the scope, if applicable... 7903 if (S) { 7904 S->RemoveDecl(Shadow); 7905 IdResolver.RemoveDecl(Shadow); 7906 } 7907 7908 // ...and the using decl. 7909 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7910 7911 // TODO: complain somehow if Shadow was used. It shouldn't 7912 // be possible for this to happen, because...? 7913 } 7914 7915 /// Find the base specifier for a base class with the given type. 7916 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7917 QualType DesiredBase, 7918 bool &AnyDependentBases) { 7919 // Check whether the named type is a direct base class. 7920 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7921 for (auto &Base : Derived->bases()) { 7922 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7923 if (CanonicalDesiredBase == BaseType) 7924 return &Base; 7925 if (BaseType->isDependentType()) 7926 AnyDependentBases = true; 7927 } 7928 return nullptr; 7929 } 7930 7931 namespace { 7932 class UsingValidatorCCC : public CorrectionCandidateCallback { 7933 public: 7934 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7935 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7936 : HasTypenameKeyword(HasTypenameKeyword), 7937 IsInstantiation(IsInstantiation), OldNNS(NNS), 7938 RequireMemberOf(RequireMemberOf) {} 7939 7940 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7941 NamedDecl *ND = Candidate.getCorrectionDecl(); 7942 7943 // Keywords are not valid here. 7944 if (!ND || isa<NamespaceDecl>(ND)) 7945 return false; 7946 7947 // Completely unqualified names are invalid for a 'using' declaration. 7948 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7949 return false; 7950 7951 if (RequireMemberOf) { 7952 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7953 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7954 // No-one ever wants a using-declaration to name an injected-class-name 7955 // of a base class, unless they're declaring an inheriting constructor. 7956 ASTContext &Ctx = ND->getASTContext(); 7957 if (!Ctx.getLangOpts().CPlusPlus11) 7958 return false; 7959 QualType FoundType = Ctx.getRecordType(FoundRecord); 7960 7961 // Check that the injected-class-name is named as a member of its own 7962 // type; we don't want to suggest 'using Derived::Base;', since that 7963 // means something else. 7964 NestedNameSpecifier *Specifier = 7965 Candidate.WillReplaceSpecifier() 7966 ? Candidate.getCorrectionSpecifier() 7967 : OldNNS; 7968 if (!Specifier->getAsType() || 7969 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7970 return false; 7971 7972 // Check that this inheriting constructor declaration actually names a 7973 // direct base class of the current class. 7974 bool AnyDependentBases = false; 7975 if (!findDirectBaseWithType(RequireMemberOf, 7976 Ctx.getRecordType(FoundRecord), 7977 AnyDependentBases) && 7978 !AnyDependentBases) 7979 return false; 7980 } else { 7981 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7982 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7983 return false; 7984 7985 // FIXME: Check that the base class member is accessible? 7986 } 7987 } 7988 7989 if (isa<TypeDecl>(ND)) 7990 return HasTypenameKeyword || !IsInstantiation; 7991 7992 return !HasTypenameKeyword; 7993 } 7994 7995 private: 7996 bool HasTypenameKeyword; 7997 bool IsInstantiation; 7998 NestedNameSpecifier *OldNNS; 7999 CXXRecordDecl *RequireMemberOf; 8000 }; 8001 } // end anonymous namespace 8002 8003 /// Builds a using declaration. 8004 /// 8005 /// \param IsInstantiation - Whether this call arises from an 8006 /// instantiation of an unresolved using declaration. We treat 8007 /// the lookup differently for these declarations. 8008 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 8009 SourceLocation UsingLoc, 8010 CXXScopeSpec &SS, 8011 DeclarationNameInfo NameInfo, 8012 AttributeList *AttrList, 8013 bool IsInstantiation, 8014 bool HasTypenameKeyword, 8015 SourceLocation TypenameLoc) { 8016 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8017 SourceLocation IdentLoc = NameInfo.getLoc(); 8018 assert(IdentLoc.isValid() && "Invalid TargetName location."); 8019 8020 // FIXME: We ignore attributes for now. 8021 8022 if (SS.isEmpty()) { 8023 Diag(IdentLoc, diag::err_using_requires_qualname); 8024 return nullptr; 8025 } 8026 8027 // Do the redeclaration lookup in the current scope. 8028 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 8029 ForRedeclaration); 8030 Previous.setHideTags(false); 8031 if (S) { 8032 LookupName(Previous, S); 8033 8034 // It is really dumb that we have to do this. 8035 LookupResult::Filter F = Previous.makeFilter(); 8036 while (F.hasNext()) { 8037 NamedDecl *D = F.next(); 8038 if (!isDeclInScope(D, CurContext, S)) 8039 F.erase(); 8040 // If we found a local extern declaration that's not ordinarily visible, 8041 // and this declaration is being added to a non-block scope, ignore it. 8042 // We're only checking for scope conflicts here, not also for violations 8043 // of the linkage rules. 8044 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 8045 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 8046 F.erase(); 8047 } 8048 F.done(); 8049 } else { 8050 assert(IsInstantiation && "no scope in non-instantiation"); 8051 assert(CurContext->isRecord() && "scope not record in instantiation"); 8052 LookupQualifiedName(Previous, CurContext); 8053 } 8054 8055 // Check for invalid redeclarations. 8056 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 8057 SS, IdentLoc, Previous)) 8058 return nullptr; 8059 8060 // Check for bad qualifiers. 8061 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 8062 return nullptr; 8063 8064 DeclContext *LookupContext = computeDeclContext(SS); 8065 NamedDecl *D; 8066 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 8067 if (!LookupContext) { 8068 if (HasTypenameKeyword) { 8069 // FIXME: not all declaration name kinds are legal here 8070 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 8071 UsingLoc, TypenameLoc, 8072 QualifierLoc, 8073 IdentLoc, NameInfo.getName()); 8074 } else { 8075 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 8076 QualifierLoc, NameInfo); 8077 } 8078 D->setAccess(AS); 8079 CurContext->addDecl(D); 8080 return D; 8081 } 8082 8083 auto Build = [&](bool Invalid) { 8084 UsingDecl *UD = 8085 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 8086 HasTypenameKeyword); 8087 UD->setAccess(AS); 8088 CurContext->addDecl(UD); 8089 UD->setInvalidDecl(Invalid); 8090 return UD; 8091 }; 8092 auto BuildInvalid = [&]{ return Build(true); }; 8093 auto BuildValid = [&]{ return Build(false); }; 8094 8095 if (RequireCompleteDeclContext(SS, LookupContext)) 8096 return BuildInvalid(); 8097 8098 // Look up the target name. 8099 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8100 8101 // Unlike most lookups, we don't always want to hide tag 8102 // declarations: tag names are visible through the using declaration 8103 // even if hidden by ordinary names, *except* in a dependent context 8104 // where it's important for the sanity of two-phase lookup. 8105 if (!IsInstantiation) 8106 R.setHideTags(false); 8107 8108 // For the purposes of this lookup, we have a base object type 8109 // equal to that of the current context. 8110 if (CurContext->isRecord()) { 8111 R.setBaseObjectType( 8112 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 8113 } 8114 8115 LookupQualifiedName(R, LookupContext); 8116 8117 // Try to correct typos if possible. If constructor name lookup finds no 8118 // results, that means the named class has no explicit constructors, and we 8119 // suppressed declaring implicit ones (probably because it's dependent or 8120 // invalid). 8121 if (R.empty() && 8122 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 8123 if (TypoCorrection Corrected = CorrectTypo( 8124 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 8125 llvm::make_unique<UsingValidatorCCC>( 8126 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8127 dyn_cast<CXXRecordDecl>(CurContext)), 8128 CTK_ErrorRecovery)) { 8129 // We reject any correction for which ND would be NULL. 8130 NamedDecl *ND = Corrected.getCorrectionDecl(); 8131 8132 // We reject candidates where DroppedSpecifier == true, hence the 8133 // literal '0' below. 8134 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8135 << NameInfo.getName() << LookupContext << 0 8136 << SS.getRange()); 8137 8138 // If we corrected to an inheriting constructor, handle it as one. 8139 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8140 if (RD && RD->isInjectedClassName()) { 8141 // Fix up the information we'll use to build the using declaration. 8142 if (Corrected.WillReplaceSpecifier()) { 8143 NestedNameSpecifierLocBuilder Builder; 8144 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8145 QualifierLoc.getSourceRange()); 8146 QualifierLoc = Builder.getWithLocInContext(Context); 8147 } 8148 8149 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8150 Context.getCanonicalType(Context.getRecordType(RD)))); 8151 NameInfo.setNamedTypeInfo(nullptr); 8152 for (auto *Ctor : LookupConstructors(RD)) 8153 R.addDecl(Ctor); 8154 } else { 8155 // FIXME: Pick up all the declarations if we found an overloaded function. 8156 R.addDecl(ND); 8157 } 8158 } else { 8159 Diag(IdentLoc, diag::err_no_member) 8160 << NameInfo.getName() << LookupContext << SS.getRange(); 8161 return BuildInvalid(); 8162 } 8163 } 8164 8165 if (R.isAmbiguous()) 8166 return BuildInvalid(); 8167 8168 if (HasTypenameKeyword) { 8169 // If we asked for a typename and got a non-type decl, error out. 8170 if (!R.getAsSingle<TypeDecl>()) { 8171 Diag(IdentLoc, diag::err_using_typename_non_type); 8172 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8173 Diag((*I)->getUnderlyingDecl()->getLocation(), 8174 diag::note_using_decl_target); 8175 return BuildInvalid(); 8176 } 8177 } else { 8178 // If we asked for a non-typename and we got a type, error out, 8179 // but only if this is an instantiation of an unresolved using 8180 // decl. Otherwise just silently find the type name. 8181 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8182 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8183 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8184 return BuildInvalid(); 8185 } 8186 } 8187 8188 // C++0x N2914 [namespace.udecl]p6: 8189 // A using-declaration shall not name a namespace. 8190 if (R.getAsSingle<NamespaceDecl>()) { 8191 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8192 << SS.getRange(); 8193 return BuildInvalid(); 8194 } 8195 8196 UsingDecl *UD = BuildValid(); 8197 8198 // The normal rules do not apply to inheriting constructor declarations. 8199 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 8200 // Suppress access diagnostics; the access check is instead performed at the 8201 // point of use for an inheriting constructor. 8202 R.suppressDiagnostics(); 8203 CheckInheritingConstructorUsingDecl(UD); 8204 return UD; 8205 } 8206 8207 // Otherwise, look up the target name. 8208 8209 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8210 UsingShadowDecl *PrevDecl = nullptr; 8211 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8212 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8213 } 8214 8215 return UD; 8216 } 8217 8218 /// Additional checks for a using declaration referring to a constructor name. 8219 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8220 assert(!UD->hasTypename() && "expecting a constructor name"); 8221 8222 const Type *SourceType = UD->getQualifier()->getAsType(); 8223 assert(SourceType && 8224 "Using decl naming constructor doesn't have type in scope spec."); 8225 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8226 8227 // Check whether the named type is a direct base class. 8228 bool AnyDependentBases = false; 8229 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8230 AnyDependentBases); 8231 if (!Base && !AnyDependentBases) { 8232 Diag(UD->getUsingLoc(), 8233 diag::err_using_decl_constructor_not_in_direct_base) 8234 << UD->getNameInfo().getSourceRange() 8235 << QualType(SourceType, 0) << TargetClass; 8236 UD->setInvalidDecl(); 8237 return true; 8238 } 8239 8240 if (Base) 8241 Base->setInheritConstructors(); 8242 8243 return false; 8244 } 8245 8246 /// Checks that the given using declaration is not an invalid 8247 /// redeclaration. Note that this is checking only for the using decl 8248 /// itself, not for any ill-formedness among the UsingShadowDecls. 8249 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8250 bool HasTypenameKeyword, 8251 const CXXScopeSpec &SS, 8252 SourceLocation NameLoc, 8253 const LookupResult &Prev) { 8254 // C++03 [namespace.udecl]p8: 8255 // C++0x [namespace.udecl]p10: 8256 // A using-declaration is a declaration and can therefore be used 8257 // repeatedly where (and only where) multiple declarations are 8258 // allowed. 8259 // 8260 // That's in non-member contexts. 8261 if (!CurContext->getRedeclContext()->isRecord()) 8262 return false; 8263 8264 NestedNameSpecifier *Qual = SS.getScopeRep(); 8265 8266 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8267 NamedDecl *D = *I; 8268 8269 bool DTypename; 8270 NestedNameSpecifier *DQual; 8271 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8272 DTypename = UD->hasTypename(); 8273 DQual = UD->getQualifier(); 8274 } else if (UnresolvedUsingValueDecl *UD 8275 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8276 DTypename = false; 8277 DQual = UD->getQualifier(); 8278 } else if (UnresolvedUsingTypenameDecl *UD 8279 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8280 DTypename = true; 8281 DQual = UD->getQualifier(); 8282 } else continue; 8283 8284 // using decls differ if one says 'typename' and the other doesn't. 8285 // FIXME: non-dependent using decls? 8286 if (HasTypenameKeyword != DTypename) continue; 8287 8288 // using decls differ if they name different scopes (but note that 8289 // template instantiation can cause this check to trigger when it 8290 // didn't before instantiation). 8291 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8292 Context.getCanonicalNestedNameSpecifier(DQual)) 8293 continue; 8294 8295 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8296 Diag(D->getLocation(), diag::note_using_decl) << 1; 8297 return true; 8298 } 8299 8300 return false; 8301 } 8302 8303 8304 /// Checks that the given nested-name qualifier used in a using decl 8305 /// in the current context is appropriately related to the current 8306 /// scope. If an error is found, diagnoses it and returns true. 8307 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8308 const CXXScopeSpec &SS, 8309 const DeclarationNameInfo &NameInfo, 8310 SourceLocation NameLoc) { 8311 DeclContext *NamedContext = computeDeclContext(SS); 8312 8313 if (!CurContext->isRecord()) { 8314 // C++03 [namespace.udecl]p3: 8315 // C++0x [namespace.udecl]p8: 8316 // A using-declaration for a class member shall be a member-declaration. 8317 8318 // If we weren't able to compute a valid scope, it must be a 8319 // dependent class scope. 8320 if (!NamedContext || NamedContext->isRecord()) { 8321 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext); 8322 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8323 RD = nullptr; 8324 8325 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8326 << SS.getRange(); 8327 8328 // If we have a complete, non-dependent source type, try to suggest a 8329 // way to get the same effect. 8330 if (!RD) 8331 return true; 8332 8333 // Find what this using-declaration was referring to. 8334 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8335 R.setHideTags(false); 8336 R.suppressDiagnostics(); 8337 LookupQualifiedName(R, RD); 8338 8339 if (R.getAsSingle<TypeDecl>()) { 8340 if (getLangOpts().CPlusPlus11) { 8341 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8342 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8343 << 0 // alias declaration 8344 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8345 NameInfo.getName().getAsString() + 8346 " = "); 8347 } else { 8348 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8349 SourceLocation InsertLoc = 8350 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8351 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8352 << 1 // typedef declaration 8353 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8354 << FixItHint::CreateInsertion( 8355 InsertLoc, " " + NameInfo.getName().getAsString()); 8356 } 8357 } else if (R.getAsSingle<VarDecl>()) { 8358 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8359 // repeating the type of the static data member here. 8360 FixItHint FixIt; 8361 if (getLangOpts().CPlusPlus11) { 8362 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8363 FixIt = FixItHint::CreateReplacement( 8364 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8365 } 8366 8367 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8368 << 2 // reference declaration 8369 << FixIt; 8370 } 8371 return true; 8372 } 8373 8374 // Otherwise, everything is known to be fine. 8375 return false; 8376 } 8377 8378 // The current scope is a record. 8379 8380 // If the named context is dependent, we can't decide much. 8381 if (!NamedContext) { 8382 // FIXME: in C++0x, we can diagnose if we can prove that the 8383 // nested-name-specifier does not refer to a base class, which is 8384 // still possible in some cases. 8385 8386 // Otherwise we have to conservatively report that things might be 8387 // okay. 8388 return false; 8389 } 8390 8391 if (!NamedContext->isRecord()) { 8392 // Ideally this would point at the last name in the specifier, 8393 // but we don't have that level of source info. 8394 Diag(SS.getRange().getBegin(), 8395 diag::err_using_decl_nested_name_specifier_is_not_class) 8396 << SS.getScopeRep() << SS.getRange(); 8397 return true; 8398 } 8399 8400 if (!NamedContext->isDependentContext() && 8401 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8402 return true; 8403 8404 if (getLangOpts().CPlusPlus11) { 8405 // C++0x [namespace.udecl]p3: 8406 // In a using-declaration used as a member-declaration, the 8407 // nested-name-specifier shall name a base class of the class 8408 // being defined. 8409 8410 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8411 cast<CXXRecordDecl>(NamedContext))) { 8412 if (CurContext == NamedContext) { 8413 Diag(NameLoc, 8414 diag::err_using_decl_nested_name_specifier_is_current_class) 8415 << SS.getRange(); 8416 return true; 8417 } 8418 8419 Diag(SS.getRange().getBegin(), 8420 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8421 << SS.getScopeRep() 8422 << cast<CXXRecordDecl>(CurContext) 8423 << SS.getRange(); 8424 return true; 8425 } 8426 8427 return false; 8428 } 8429 8430 // C++03 [namespace.udecl]p4: 8431 // A using-declaration used as a member-declaration shall refer 8432 // to a member of a base class of the class being defined [etc.]. 8433 8434 // Salient point: SS doesn't have to name a base class as long as 8435 // lookup only finds members from base classes. Therefore we can 8436 // diagnose here only if we can prove that that can't happen, 8437 // i.e. if the class hierarchies provably don't intersect. 8438 8439 // TODO: it would be nice if "definitely valid" results were cached 8440 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8441 // need to be repeated. 8442 8443 struct UserData { 8444 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8445 8446 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8447 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8448 Data->Bases.insert(Base); 8449 return true; 8450 } 8451 8452 bool hasDependentBases(const CXXRecordDecl *Class) { 8453 return !Class->forallBases(collect, this); 8454 } 8455 8456 /// Returns true if the base is dependent or is one of the 8457 /// accumulated base classes. 8458 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8459 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8460 return !Data->Bases.count(Base); 8461 } 8462 8463 bool mightShareBases(const CXXRecordDecl *Class) { 8464 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8465 } 8466 }; 8467 8468 UserData Data; 8469 8470 // Returns false if we find a dependent base. 8471 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8472 return false; 8473 8474 // Returns false if the class has a dependent base or if it or one 8475 // of its bases is present in the base set of the current context. 8476 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8477 return false; 8478 8479 Diag(SS.getRange().getBegin(), 8480 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8481 << SS.getScopeRep() 8482 << cast<CXXRecordDecl>(CurContext) 8483 << SS.getRange(); 8484 8485 return true; 8486 } 8487 8488 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8489 AccessSpecifier AS, 8490 MultiTemplateParamsArg TemplateParamLists, 8491 SourceLocation UsingLoc, 8492 UnqualifiedId &Name, 8493 AttributeList *AttrList, 8494 TypeResult Type, 8495 Decl *DeclFromDeclSpec) { 8496 // Skip up to the relevant declaration scope. 8497 while (S->getFlags() & Scope::TemplateParamScope) 8498 S = S->getParent(); 8499 assert((S->getFlags() & Scope::DeclScope) && 8500 "got alias-declaration outside of declaration scope"); 8501 8502 if (Type.isInvalid()) 8503 return nullptr; 8504 8505 bool Invalid = false; 8506 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8507 TypeSourceInfo *TInfo = nullptr; 8508 GetTypeFromParser(Type.get(), &TInfo); 8509 8510 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8511 return nullptr; 8512 8513 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8514 UPPC_DeclarationType)) { 8515 Invalid = true; 8516 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8517 TInfo->getTypeLoc().getBeginLoc()); 8518 } 8519 8520 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8521 LookupName(Previous, S); 8522 8523 // Warn about shadowing the name of a template parameter. 8524 if (Previous.isSingleResult() && 8525 Previous.getFoundDecl()->isTemplateParameter()) { 8526 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8527 Previous.clear(); 8528 } 8529 8530 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8531 "name in alias declaration must be an identifier"); 8532 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8533 Name.StartLocation, 8534 Name.Identifier, TInfo); 8535 8536 NewTD->setAccess(AS); 8537 8538 if (Invalid) 8539 NewTD->setInvalidDecl(); 8540 8541 ProcessDeclAttributeList(S, NewTD, AttrList); 8542 8543 CheckTypedefForVariablyModifiedType(S, NewTD); 8544 Invalid |= NewTD->isInvalidDecl(); 8545 8546 bool Redeclaration = false; 8547 8548 NamedDecl *NewND; 8549 if (TemplateParamLists.size()) { 8550 TypeAliasTemplateDecl *OldDecl = nullptr; 8551 TemplateParameterList *OldTemplateParams = nullptr; 8552 8553 if (TemplateParamLists.size() != 1) { 8554 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8555 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8556 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8557 } 8558 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8559 8560 // Only consider previous declarations in the same scope. 8561 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8562 /*ExplicitInstantiationOrSpecialization*/false); 8563 if (!Previous.empty()) { 8564 Redeclaration = true; 8565 8566 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8567 if (!OldDecl && !Invalid) { 8568 Diag(UsingLoc, diag::err_redefinition_different_kind) 8569 << Name.Identifier; 8570 8571 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8572 if (OldD->getLocation().isValid()) 8573 Diag(OldD->getLocation(), diag::note_previous_definition); 8574 8575 Invalid = true; 8576 } 8577 8578 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8579 if (TemplateParameterListsAreEqual(TemplateParams, 8580 OldDecl->getTemplateParameters(), 8581 /*Complain=*/true, 8582 TPL_TemplateMatch)) 8583 OldTemplateParams = OldDecl->getTemplateParameters(); 8584 else 8585 Invalid = true; 8586 8587 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8588 if (!Invalid && 8589 !Context.hasSameType(OldTD->getUnderlyingType(), 8590 NewTD->getUnderlyingType())) { 8591 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8592 // but we can't reasonably accept it. 8593 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8594 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8595 if (OldTD->getLocation().isValid()) 8596 Diag(OldTD->getLocation(), diag::note_previous_definition); 8597 Invalid = true; 8598 } 8599 } 8600 } 8601 8602 // Merge any previous default template arguments into our parameters, 8603 // and check the parameter list. 8604 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8605 TPC_TypeAliasTemplate)) 8606 return nullptr; 8607 8608 TypeAliasTemplateDecl *NewDecl = 8609 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8610 Name.Identifier, TemplateParams, 8611 NewTD); 8612 NewTD->setDescribedAliasTemplate(NewDecl); 8613 8614 NewDecl->setAccess(AS); 8615 8616 if (Invalid) 8617 NewDecl->setInvalidDecl(); 8618 else if (OldDecl) 8619 NewDecl->setPreviousDecl(OldDecl); 8620 8621 NewND = NewDecl; 8622 } else { 8623 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 8624 setTagNameForLinkagePurposes(TD, NewTD); 8625 handleTagNumbering(TD, S); 8626 } 8627 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8628 NewND = NewTD; 8629 } 8630 8631 if (!Redeclaration) 8632 PushOnScopeChains(NewND, S); 8633 8634 ActOnDocumentableDecl(NewND); 8635 return NewND; 8636 } 8637 8638 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8639 SourceLocation AliasLoc, 8640 IdentifierInfo *Alias, CXXScopeSpec &SS, 8641 SourceLocation IdentLoc, 8642 IdentifierInfo *Ident) { 8643 8644 // Lookup the namespace name. 8645 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8646 LookupParsedName(R, S, &SS); 8647 8648 if (R.isAmbiguous()) 8649 return nullptr; 8650 8651 if (R.empty()) { 8652 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8653 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8654 return nullptr; 8655 } 8656 } 8657 assert(!R.isAmbiguous() && !R.empty()); 8658 8659 // Check if we have a previous declaration with the same name. 8660 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8661 ForRedeclaration); 8662 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8663 PrevDecl = nullptr; 8664 8665 NamedDecl *ND = R.getFoundDecl(); 8666 8667 if (PrevDecl) { 8668 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8669 // We already have an alias with the same name that points to the same 8670 // namespace; check that it matches. 8671 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8672 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8673 << Alias; 8674 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8675 << AD->getNamespace(); 8676 return nullptr; 8677 } 8678 } else { 8679 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8680 ? diag::err_redefinition 8681 : diag::err_redefinition_different_kind; 8682 Diag(AliasLoc, DiagID) << Alias; 8683 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8684 return nullptr; 8685 } 8686 } 8687 8688 // The use of a nested name specifier may trigger deprecation warnings. 8689 DiagnoseUseOfDecl(ND, IdentLoc); 8690 8691 NamespaceAliasDecl *AliasDecl = 8692 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8693 Alias, SS.getWithLocInContext(Context), 8694 IdentLoc, ND); 8695 if (PrevDecl) 8696 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8697 8698 PushOnScopeChains(AliasDecl, S); 8699 return AliasDecl; 8700 } 8701 8702 Sema::ImplicitExceptionSpecification 8703 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8704 CXXMethodDecl *MD) { 8705 CXXRecordDecl *ClassDecl = MD->getParent(); 8706 8707 // C++ [except.spec]p14: 8708 // An implicitly declared special member function (Clause 12) shall have an 8709 // exception-specification. [...] 8710 ImplicitExceptionSpecification ExceptSpec(*this); 8711 if (ClassDecl->isInvalidDecl()) 8712 return ExceptSpec; 8713 8714 // Direct base-class constructors. 8715 for (const auto &B : ClassDecl->bases()) { 8716 if (B.isVirtual()) // Handled below. 8717 continue; 8718 8719 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8720 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8721 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8722 // If this is a deleted function, add it anyway. This might be conformant 8723 // with the standard. This might not. I'm not sure. It might not matter. 8724 if (Constructor) 8725 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8726 } 8727 } 8728 8729 // Virtual base-class constructors. 8730 for (const auto &B : ClassDecl->vbases()) { 8731 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8732 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8733 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8734 // If this is a deleted function, add it anyway. This might be conformant 8735 // with the standard. This might not. I'm not sure. It might not matter. 8736 if (Constructor) 8737 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8738 } 8739 } 8740 8741 // Field constructors. 8742 for (const auto *F : ClassDecl->fields()) { 8743 if (F->hasInClassInitializer()) { 8744 if (Expr *E = F->getInClassInitializer()) 8745 ExceptSpec.CalledExpr(E); 8746 } else if (const RecordType *RecordTy 8747 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8748 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8749 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8750 // If this is a deleted function, add it anyway. This might be conformant 8751 // with the standard. This might not. I'm not sure. It might not matter. 8752 // In particular, the problem is that this function never gets called. It 8753 // might just be ill-formed because this function attempts to refer to 8754 // a deleted function here. 8755 if (Constructor) 8756 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8757 } 8758 } 8759 8760 return ExceptSpec; 8761 } 8762 8763 Sema::ImplicitExceptionSpecification 8764 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8765 CXXRecordDecl *ClassDecl = CD->getParent(); 8766 8767 // C++ [except.spec]p14: 8768 // An inheriting constructor [...] shall have an exception-specification. [...] 8769 ImplicitExceptionSpecification ExceptSpec(*this); 8770 if (ClassDecl->isInvalidDecl()) 8771 return ExceptSpec; 8772 8773 // Inherited constructor. 8774 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8775 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8776 // FIXME: Copying or moving the parameters could add extra exceptions to the 8777 // set, as could the default arguments for the inherited constructor. This 8778 // will be addressed when we implement the resolution of core issue 1351. 8779 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8780 8781 // Direct base-class constructors. 8782 for (const auto &B : ClassDecl->bases()) { 8783 if (B.isVirtual()) // Handled below. 8784 continue; 8785 8786 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8787 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8788 if (BaseClassDecl == InheritedDecl) 8789 continue; 8790 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8791 if (Constructor) 8792 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8793 } 8794 } 8795 8796 // Virtual base-class constructors. 8797 for (const auto &B : ClassDecl->vbases()) { 8798 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8799 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8800 if (BaseClassDecl == InheritedDecl) 8801 continue; 8802 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8803 if (Constructor) 8804 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8805 } 8806 } 8807 8808 // Field constructors. 8809 for (const auto *F : ClassDecl->fields()) { 8810 if (F->hasInClassInitializer()) { 8811 if (Expr *E = F->getInClassInitializer()) 8812 ExceptSpec.CalledExpr(E); 8813 } else if (const RecordType *RecordTy 8814 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8815 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8816 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8817 if (Constructor) 8818 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8819 } 8820 } 8821 8822 return ExceptSpec; 8823 } 8824 8825 namespace { 8826 /// RAII object to register a special member as being currently declared. 8827 struct DeclaringSpecialMember { 8828 Sema &S; 8829 Sema::SpecialMemberDecl D; 8830 bool WasAlreadyBeingDeclared; 8831 8832 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8833 : S(S), D(RD, CSM) { 8834 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8835 if (WasAlreadyBeingDeclared) 8836 // This almost never happens, but if it does, ensure that our cache 8837 // doesn't contain a stale result. 8838 S.SpecialMemberCache.clear(); 8839 8840 // FIXME: Register a note to be produced if we encounter an error while 8841 // declaring the special member. 8842 } 8843 ~DeclaringSpecialMember() { 8844 if (!WasAlreadyBeingDeclared) 8845 S.SpecialMembersBeingDeclared.erase(D); 8846 } 8847 8848 /// \brief Are we already trying to declare this special member? 8849 bool isAlreadyBeingDeclared() const { 8850 return WasAlreadyBeingDeclared; 8851 } 8852 }; 8853 } 8854 8855 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8856 CXXRecordDecl *ClassDecl) { 8857 // C++ [class.ctor]p5: 8858 // A default constructor for a class X is a constructor of class X 8859 // that can be called without an argument. If there is no 8860 // user-declared constructor for class X, a default constructor is 8861 // implicitly declared. An implicitly-declared default constructor 8862 // is an inline public member of its class. 8863 assert(ClassDecl->needsImplicitDefaultConstructor() && 8864 "Should not build implicit default constructor!"); 8865 8866 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8867 if (DSM.isAlreadyBeingDeclared()) 8868 return nullptr; 8869 8870 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8871 CXXDefaultConstructor, 8872 false); 8873 8874 // Create the actual constructor declaration. 8875 CanQualType ClassType 8876 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8877 SourceLocation ClassLoc = ClassDecl->getLocation(); 8878 DeclarationName Name 8879 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8880 DeclarationNameInfo NameInfo(Name, ClassLoc); 8881 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8882 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8883 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8884 /*isImplicitlyDeclared=*/true, Constexpr); 8885 DefaultCon->setAccess(AS_public); 8886 DefaultCon->setDefaulted(); 8887 8888 if (getLangOpts().CUDA) { 8889 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8890 DefaultCon, 8891 /* ConstRHS */ false, 8892 /* Diagnose */ false); 8893 } 8894 8895 // Build an exception specification pointing back at this constructor. 8896 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8897 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8898 8899 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8900 // constructors is easy to compute. 8901 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8902 8903 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8904 SetDeclDeleted(DefaultCon, ClassLoc); 8905 8906 // Note that we have declared this constructor. 8907 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8908 8909 if (Scope *S = getScopeForContext(ClassDecl)) 8910 PushOnScopeChains(DefaultCon, S, false); 8911 ClassDecl->addDecl(DefaultCon); 8912 8913 return DefaultCon; 8914 } 8915 8916 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8917 CXXConstructorDecl *Constructor) { 8918 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8919 !Constructor->doesThisDeclarationHaveABody() && 8920 !Constructor->isDeleted()) && 8921 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8922 8923 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8924 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8925 8926 SynthesizedFunctionScope Scope(*this, Constructor); 8927 DiagnosticErrorTrap Trap(Diags); 8928 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8929 Trap.hasErrorOccurred()) { 8930 Diag(CurrentLocation, diag::note_member_synthesized_at) 8931 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8932 Constructor->setInvalidDecl(); 8933 return; 8934 } 8935 8936 // The exception specification is needed because we are defining the 8937 // function. 8938 ResolveExceptionSpec(CurrentLocation, 8939 Constructor->getType()->castAs<FunctionProtoType>()); 8940 8941 SourceLocation Loc = Constructor->getLocEnd().isValid() 8942 ? Constructor->getLocEnd() 8943 : Constructor->getLocation(); 8944 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8945 8946 Constructor->markUsed(Context); 8947 MarkVTableUsed(CurrentLocation, ClassDecl); 8948 8949 if (ASTMutationListener *L = getASTMutationListener()) { 8950 L->CompletedImplicitDefinition(Constructor); 8951 } 8952 8953 DiagnoseUninitializedFields(*this, Constructor); 8954 } 8955 8956 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8957 // Perform any delayed checks on exception specifications. 8958 CheckDelayedMemberExceptionSpecs(); 8959 } 8960 8961 namespace { 8962 /// Information on inheriting constructors to declare. 8963 class InheritingConstructorInfo { 8964 public: 8965 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8966 : SemaRef(SemaRef), Derived(Derived) { 8967 // Mark the constructors that we already have in the derived class. 8968 // 8969 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8970 // unless there is a user-declared constructor with the same signature in 8971 // the class where the using-declaration appears. 8972 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8973 } 8974 8975 void inheritAll(CXXRecordDecl *RD) { 8976 visitAll(RD, &InheritingConstructorInfo::inherit); 8977 } 8978 8979 private: 8980 /// Information about an inheriting constructor. 8981 struct InheritingConstructor { 8982 InheritingConstructor() 8983 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8984 8985 /// If \c true, a constructor with this signature is already declared 8986 /// in the derived class. 8987 bool DeclaredInDerived; 8988 8989 /// The constructor which is inherited. 8990 const CXXConstructorDecl *BaseCtor; 8991 8992 /// The derived constructor we declared. 8993 CXXConstructorDecl *DerivedCtor; 8994 }; 8995 8996 /// Inheriting constructors with a given canonical type. There can be at 8997 /// most one such non-template constructor, and any number of templated 8998 /// constructors. 8999 struct InheritingConstructorsForType { 9000 InheritingConstructor NonTemplate; 9001 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 9002 Templates; 9003 9004 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 9005 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 9006 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 9007 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 9008 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 9009 false, S.TPL_TemplateMatch)) 9010 return Templates[I].second; 9011 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 9012 return Templates.back().second; 9013 } 9014 9015 return NonTemplate; 9016 } 9017 }; 9018 9019 /// Get or create the inheriting constructor record for a constructor. 9020 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 9021 QualType CtorType) { 9022 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 9023 .getEntry(SemaRef, Ctor); 9024 } 9025 9026 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 9027 9028 /// Process all constructors for a class. 9029 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 9030 for (const auto *Ctor : RD->ctors()) 9031 (this->*Callback)(Ctor); 9032 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9033 I(RD->decls_begin()), E(RD->decls_end()); 9034 I != E; ++I) { 9035 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 9036 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 9037 (this->*Callback)(CD); 9038 } 9039 } 9040 9041 /// Note that a constructor (or constructor template) was declared in Derived. 9042 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 9043 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 9044 } 9045 9046 /// Inherit a single constructor. 9047 void inherit(const CXXConstructorDecl *Ctor) { 9048 const FunctionProtoType *CtorType = 9049 Ctor->getType()->castAs<FunctionProtoType>(); 9050 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 9051 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 9052 9053 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 9054 9055 // Core issue (no number yet): the ellipsis is always discarded. 9056 if (EPI.Variadic) { 9057 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 9058 SemaRef.Diag(Ctor->getLocation(), 9059 diag::note_using_decl_constructor_ellipsis); 9060 EPI.Variadic = false; 9061 } 9062 9063 // Declare a constructor for each number of parameters. 9064 // 9065 // C++11 [class.inhctor]p1: 9066 // The candidate set of inherited constructors from the class X named in 9067 // the using-declaration consists of [... modulo defects ...] for each 9068 // constructor or constructor template of X, the set of constructors or 9069 // constructor templates that results from omitting any ellipsis parameter 9070 // specification and successively omitting parameters with a default 9071 // argument from the end of the parameter-type-list 9072 unsigned MinParams = minParamsToInherit(Ctor); 9073 unsigned Params = Ctor->getNumParams(); 9074 if (Params >= MinParams) { 9075 do 9076 declareCtor(UsingLoc, Ctor, 9077 SemaRef.Context.getFunctionType( 9078 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 9079 while (Params > MinParams && 9080 Ctor->getParamDecl(--Params)->hasDefaultArg()); 9081 } 9082 } 9083 9084 /// Find the using-declaration which specified that we should inherit the 9085 /// constructors of \p Base. 9086 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 9087 // No fancy lookup required; just look for the base constructor name 9088 // directly within the derived class. 9089 ASTContext &Context = SemaRef.Context; 9090 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9091 Context.getCanonicalType(Context.getRecordType(Base))); 9092 DeclContext::lookup_result Decls = Derived->lookup(Name); 9093 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 9094 } 9095 9096 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 9097 // C++11 [class.inhctor]p3: 9098 // [F]or each constructor template in the candidate set of inherited 9099 // constructors, a constructor template is implicitly declared 9100 if (Ctor->getDescribedFunctionTemplate()) 9101 return 0; 9102 9103 // For each non-template constructor in the candidate set of inherited 9104 // constructors other than a constructor having no parameters or a 9105 // copy/move constructor having a single parameter, a constructor is 9106 // implicitly declared [...] 9107 if (Ctor->getNumParams() == 0) 9108 return 1; 9109 if (Ctor->isCopyOrMoveConstructor()) 9110 return 2; 9111 9112 // Per discussion on core reflector, never inherit a constructor which 9113 // would become a default, copy, or move constructor of Derived either. 9114 const ParmVarDecl *PD = Ctor->getParamDecl(0); 9115 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 9116 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 9117 } 9118 9119 /// Declare a single inheriting constructor, inheriting the specified 9120 /// constructor, with the given type. 9121 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 9122 QualType DerivedType) { 9123 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 9124 9125 // C++11 [class.inhctor]p3: 9126 // ... a constructor is implicitly declared with the same constructor 9127 // characteristics unless there is a user-declared constructor with 9128 // the same signature in the class where the using-declaration appears 9129 if (Entry.DeclaredInDerived) 9130 return; 9131 9132 // C++11 [class.inhctor]p7: 9133 // If two using-declarations declare inheriting constructors with the 9134 // same signature, the program is ill-formed 9135 if (Entry.DerivedCtor) { 9136 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 9137 // Only diagnose this once per constructor. 9138 if (Entry.DerivedCtor->isInvalidDecl()) 9139 return; 9140 Entry.DerivedCtor->setInvalidDecl(); 9141 9142 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9143 SemaRef.Diag(BaseCtor->getLocation(), 9144 diag::note_using_decl_constructor_conflict_current_ctor); 9145 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9146 diag::note_using_decl_constructor_conflict_previous_ctor); 9147 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9148 diag::note_using_decl_constructor_conflict_previous_using); 9149 } else { 9150 // Core issue (no number): if the same inheriting constructor is 9151 // produced by multiple base class constructors from the same base 9152 // class, the inheriting constructor is defined as deleted. 9153 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9154 } 9155 9156 return; 9157 } 9158 9159 ASTContext &Context = SemaRef.Context; 9160 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9161 Context.getCanonicalType(Context.getRecordType(Derived))); 9162 DeclarationNameInfo NameInfo(Name, UsingLoc); 9163 9164 TemplateParameterList *TemplateParams = nullptr; 9165 if (const FunctionTemplateDecl *FTD = 9166 BaseCtor->getDescribedFunctionTemplate()) { 9167 TemplateParams = FTD->getTemplateParameters(); 9168 // We're reusing template parameters from a different DeclContext. This 9169 // is questionable at best, but works out because the template depth in 9170 // both places is guaranteed to be 0. 9171 // FIXME: Rebuild the template parameters in the new context, and 9172 // transform the function type to refer to them. 9173 } 9174 9175 // Build type source info pointing at the using-declaration. This is 9176 // required by template instantiation. 9177 TypeSourceInfo *TInfo = 9178 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9179 FunctionProtoTypeLoc ProtoLoc = 9180 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9181 9182 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9183 Context, Derived, UsingLoc, NameInfo, DerivedType, 9184 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9185 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9186 9187 // Build an unevaluated exception specification for this constructor. 9188 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9189 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9190 EPI.ExceptionSpec.Type = EST_Unevaluated; 9191 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9192 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9193 FPT->getParamTypes(), EPI)); 9194 9195 // Build the parameter declarations. 9196 SmallVector<ParmVarDecl *, 16> ParamDecls; 9197 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9198 TypeSourceInfo *TInfo = 9199 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9200 ParmVarDecl *PD = ParmVarDecl::Create( 9201 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9202 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9203 PD->setScopeInfo(0, I); 9204 PD->setImplicit(); 9205 ParamDecls.push_back(PD); 9206 ProtoLoc.setParam(I, PD); 9207 } 9208 9209 // Set up the new constructor. 9210 DerivedCtor->setAccess(BaseCtor->getAccess()); 9211 DerivedCtor->setParams(ParamDecls); 9212 DerivedCtor->setInheritedConstructor(BaseCtor); 9213 if (BaseCtor->isDeleted()) 9214 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9215 9216 // If this is a constructor template, build the template declaration. 9217 if (TemplateParams) { 9218 FunctionTemplateDecl *DerivedTemplate = 9219 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9220 TemplateParams, DerivedCtor); 9221 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9222 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9223 Derived->addDecl(DerivedTemplate); 9224 } else { 9225 Derived->addDecl(DerivedCtor); 9226 } 9227 9228 Entry.BaseCtor = BaseCtor; 9229 Entry.DerivedCtor = DerivedCtor; 9230 } 9231 9232 Sema &SemaRef; 9233 CXXRecordDecl *Derived; 9234 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9235 MapType Map; 9236 }; 9237 } 9238 9239 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9240 // Defer declaring the inheriting constructors until the class is 9241 // instantiated. 9242 if (ClassDecl->isDependentContext()) 9243 return; 9244 9245 // Find base classes from which we might inherit constructors. 9246 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9247 for (const auto &BaseIt : ClassDecl->bases()) 9248 if (BaseIt.getInheritConstructors()) 9249 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9250 9251 // Go no further if we're not inheriting any constructors. 9252 if (InheritedBases.empty()) 9253 return; 9254 9255 // Declare the inherited constructors. 9256 InheritingConstructorInfo ICI(*this, ClassDecl); 9257 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9258 ICI.inheritAll(InheritedBases[I]); 9259 } 9260 9261 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9262 CXXConstructorDecl *Constructor) { 9263 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9264 assert(Constructor->getInheritedConstructor() && 9265 !Constructor->doesThisDeclarationHaveABody() && 9266 !Constructor->isDeleted()); 9267 9268 SynthesizedFunctionScope Scope(*this, Constructor); 9269 DiagnosticErrorTrap Trap(Diags); 9270 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9271 Trap.hasErrorOccurred()) { 9272 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9273 << Context.getTagDeclType(ClassDecl); 9274 Constructor->setInvalidDecl(); 9275 return; 9276 } 9277 9278 SourceLocation Loc = Constructor->getLocation(); 9279 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9280 9281 Constructor->markUsed(Context); 9282 MarkVTableUsed(CurrentLocation, ClassDecl); 9283 9284 if (ASTMutationListener *L = getASTMutationListener()) { 9285 L->CompletedImplicitDefinition(Constructor); 9286 } 9287 } 9288 9289 9290 Sema::ImplicitExceptionSpecification 9291 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9292 CXXRecordDecl *ClassDecl = MD->getParent(); 9293 9294 // C++ [except.spec]p14: 9295 // An implicitly declared special member function (Clause 12) shall have 9296 // an exception-specification. 9297 ImplicitExceptionSpecification ExceptSpec(*this); 9298 if (ClassDecl->isInvalidDecl()) 9299 return ExceptSpec; 9300 9301 // Direct base-class destructors. 9302 for (const auto &B : ClassDecl->bases()) { 9303 if (B.isVirtual()) // Handled below. 9304 continue; 9305 9306 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9307 ExceptSpec.CalledDecl(B.getLocStart(), 9308 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9309 } 9310 9311 // Virtual base-class destructors. 9312 for (const auto &B : ClassDecl->vbases()) { 9313 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9314 ExceptSpec.CalledDecl(B.getLocStart(), 9315 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9316 } 9317 9318 // Field destructors. 9319 for (const auto *F : ClassDecl->fields()) { 9320 if (const RecordType *RecordTy 9321 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9322 ExceptSpec.CalledDecl(F->getLocation(), 9323 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9324 } 9325 9326 return ExceptSpec; 9327 } 9328 9329 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9330 // C++ [class.dtor]p2: 9331 // If a class has no user-declared destructor, a destructor is 9332 // declared implicitly. An implicitly-declared destructor is an 9333 // inline public member of its class. 9334 assert(ClassDecl->needsImplicitDestructor()); 9335 9336 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9337 if (DSM.isAlreadyBeingDeclared()) 9338 return nullptr; 9339 9340 // Create the actual destructor declaration. 9341 CanQualType ClassType 9342 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9343 SourceLocation ClassLoc = ClassDecl->getLocation(); 9344 DeclarationName Name 9345 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9346 DeclarationNameInfo NameInfo(Name, ClassLoc); 9347 CXXDestructorDecl *Destructor 9348 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9349 QualType(), nullptr, /*isInline=*/true, 9350 /*isImplicitlyDeclared=*/true); 9351 Destructor->setAccess(AS_public); 9352 Destructor->setDefaulted(); 9353 9354 if (getLangOpts().CUDA) { 9355 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9356 Destructor, 9357 /* ConstRHS */ false, 9358 /* Diagnose */ false); 9359 } 9360 9361 // Build an exception specification pointing back at this destructor. 9362 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9363 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9364 9365 AddOverriddenMethods(ClassDecl, Destructor); 9366 9367 // We don't need to use SpecialMemberIsTrivial here; triviality for 9368 // destructors is easy to compute. 9369 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9370 9371 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9372 SetDeclDeleted(Destructor, ClassLoc); 9373 9374 // Note that we have declared this destructor. 9375 ++ASTContext::NumImplicitDestructorsDeclared; 9376 9377 // Introduce this destructor into its scope. 9378 if (Scope *S = getScopeForContext(ClassDecl)) 9379 PushOnScopeChains(Destructor, S, false); 9380 ClassDecl->addDecl(Destructor); 9381 9382 return Destructor; 9383 } 9384 9385 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9386 CXXDestructorDecl *Destructor) { 9387 assert((Destructor->isDefaulted() && 9388 !Destructor->doesThisDeclarationHaveABody() && 9389 !Destructor->isDeleted()) && 9390 "DefineImplicitDestructor - call it for implicit default dtor"); 9391 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9392 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9393 9394 if (Destructor->isInvalidDecl()) 9395 return; 9396 9397 SynthesizedFunctionScope Scope(*this, Destructor); 9398 9399 DiagnosticErrorTrap Trap(Diags); 9400 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9401 Destructor->getParent()); 9402 9403 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9404 Diag(CurrentLocation, diag::note_member_synthesized_at) 9405 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9406 9407 Destructor->setInvalidDecl(); 9408 return; 9409 } 9410 9411 // The exception specification is needed because we are defining the 9412 // function. 9413 ResolveExceptionSpec(CurrentLocation, 9414 Destructor->getType()->castAs<FunctionProtoType>()); 9415 9416 SourceLocation Loc = Destructor->getLocEnd().isValid() 9417 ? Destructor->getLocEnd() 9418 : Destructor->getLocation(); 9419 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9420 Destructor->markUsed(Context); 9421 MarkVTableUsed(CurrentLocation, ClassDecl); 9422 9423 if (ASTMutationListener *L = getASTMutationListener()) { 9424 L->CompletedImplicitDefinition(Destructor); 9425 } 9426 } 9427 9428 /// \brief Perform any semantic analysis which needs to be delayed until all 9429 /// pending class member declarations have been parsed. 9430 void Sema::ActOnFinishCXXMemberDecls() { 9431 // If the context is an invalid C++ class, just suppress these checks. 9432 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9433 if (Record->isInvalidDecl()) { 9434 DelayedDefaultedMemberExceptionSpecs.clear(); 9435 DelayedExceptionSpecChecks.clear(); 9436 return; 9437 } 9438 } 9439 } 9440 9441 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) { 9442 // Don't do anything for template patterns. 9443 if (Class->getDescribedClassTemplate()) 9444 return; 9445 9446 for (Decl *Member : Class->decls()) { 9447 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 9448 if (!CD) { 9449 // Recurse on nested classes. 9450 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member)) 9451 getDefaultArgExprsForConstructors(S, NestedRD); 9452 continue; 9453 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) { 9454 continue; 9455 } 9456 9457 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) { 9458 // Skip any default arguments that we've already instantiated. 9459 if (S.Context.getDefaultArgExprForConstructor(CD, I)) 9460 continue; 9461 9462 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD, 9463 CD->getParamDecl(I)).get(); 9464 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 9465 } 9466 } 9467 } 9468 9469 void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) { 9470 auto *RD = dyn_cast<CXXRecordDecl>(D); 9471 9472 // Default constructors that are annotated with __declspec(dllexport) which 9473 // have default arguments or don't use the standard calling convention are 9474 // wrapped with a thunk called the default constructor closure. 9475 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft()) 9476 getDefaultArgExprsForConstructors(*this, RD); 9477 } 9478 9479 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9480 CXXDestructorDecl *Destructor) { 9481 assert(getLangOpts().CPlusPlus11 && 9482 "adjusting dtor exception specs was introduced in c++11"); 9483 9484 // C++11 [class.dtor]p3: 9485 // A declaration of a destructor that does not have an exception- 9486 // specification is implicitly considered to have the same exception- 9487 // specification as an implicit declaration. 9488 const FunctionProtoType *DtorType = Destructor->getType()-> 9489 getAs<FunctionProtoType>(); 9490 if (DtorType->hasExceptionSpec()) 9491 return; 9492 9493 // Replace the destructor's type, building off the existing one. Fortunately, 9494 // the only thing of interest in the destructor type is its extended info. 9495 // The return and arguments are fixed. 9496 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9497 EPI.ExceptionSpec.Type = EST_Unevaluated; 9498 EPI.ExceptionSpec.SourceDecl = Destructor; 9499 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9500 9501 // FIXME: If the destructor has a body that could throw, and the newly created 9502 // spec doesn't allow exceptions, we should emit a warning, because this 9503 // change in behavior can break conforming C++03 programs at runtime. 9504 // However, we don't have a body or an exception specification yet, so it 9505 // needs to be done somewhere else. 9506 } 9507 9508 namespace { 9509 /// \brief An abstract base class for all helper classes used in building the 9510 // copy/move operators. These classes serve as factory functions and help us 9511 // avoid using the same Expr* in the AST twice. 9512 class ExprBuilder { 9513 ExprBuilder(const ExprBuilder&) = delete; 9514 ExprBuilder &operator=(const ExprBuilder&) = delete; 9515 9516 protected: 9517 static Expr *assertNotNull(Expr *E) { 9518 assert(E && "Expression construction must not fail."); 9519 return E; 9520 } 9521 9522 public: 9523 ExprBuilder() {} 9524 virtual ~ExprBuilder() {} 9525 9526 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9527 }; 9528 9529 class RefBuilder: public ExprBuilder { 9530 VarDecl *Var; 9531 QualType VarType; 9532 9533 public: 9534 Expr *build(Sema &S, SourceLocation Loc) const override { 9535 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9536 } 9537 9538 RefBuilder(VarDecl *Var, QualType VarType) 9539 : Var(Var), VarType(VarType) {} 9540 }; 9541 9542 class ThisBuilder: public ExprBuilder { 9543 public: 9544 Expr *build(Sema &S, SourceLocation Loc) const override { 9545 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9546 } 9547 }; 9548 9549 class CastBuilder: public ExprBuilder { 9550 const ExprBuilder &Builder; 9551 QualType Type; 9552 ExprValueKind Kind; 9553 const CXXCastPath &Path; 9554 9555 public: 9556 Expr *build(Sema &S, SourceLocation Loc) const override { 9557 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9558 CK_UncheckedDerivedToBase, Kind, 9559 &Path).get()); 9560 } 9561 9562 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9563 const CXXCastPath &Path) 9564 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9565 }; 9566 9567 class DerefBuilder: public ExprBuilder { 9568 const ExprBuilder &Builder; 9569 9570 public: 9571 Expr *build(Sema &S, SourceLocation Loc) const override { 9572 return assertNotNull( 9573 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9574 } 9575 9576 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9577 }; 9578 9579 class MemberBuilder: public ExprBuilder { 9580 const ExprBuilder &Builder; 9581 QualType Type; 9582 CXXScopeSpec SS; 9583 bool IsArrow; 9584 LookupResult &MemberLookup; 9585 9586 public: 9587 Expr *build(Sema &S, SourceLocation Loc) const override { 9588 return assertNotNull(S.BuildMemberReferenceExpr( 9589 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9590 nullptr, MemberLookup, nullptr).get()); 9591 } 9592 9593 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9594 LookupResult &MemberLookup) 9595 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9596 MemberLookup(MemberLookup) {} 9597 }; 9598 9599 class MoveCastBuilder: public ExprBuilder { 9600 const ExprBuilder &Builder; 9601 9602 public: 9603 Expr *build(Sema &S, SourceLocation Loc) const override { 9604 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9605 } 9606 9607 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9608 }; 9609 9610 class LvalueConvBuilder: public ExprBuilder { 9611 const ExprBuilder &Builder; 9612 9613 public: 9614 Expr *build(Sema &S, SourceLocation Loc) const override { 9615 return assertNotNull( 9616 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9617 } 9618 9619 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9620 }; 9621 9622 class SubscriptBuilder: public ExprBuilder { 9623 const ExprBuilder &Base; 9624 const ExprBuilder &Index; 9625 9626 public: 9627 Expr *build(Sema &S, SourceLocation Loc) const override { 9628 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9629 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9630 } 9631 9632 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9633 : Base(Base), Index(Index) {} 9634 }; 9635 9636 } // end anonymous namespace 9637 9638 /// When generating a defaulted copy or move assignment operator, if a field 9639 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9640 /// do so. This optimization only applies for arrays of scalars, and for arrays 9641 /// of class type where the selected copy/move-assignment operator is trivial. 9642 static StmtResult 9643 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9644 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9645 // Compute the size of the memory buffer to be copied. 9646 QualType SizeType = S.Context.getSizeType(); 9647 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9648 S.Context.getTypeSizeInChars(T).getQuantity()); 9649 9650 // Take the address of the field references for "from" and "to". We 9651 // directly construct UnaryOperators here because semantic analysis 9652 // does not permit us to take the address of an xvalue. 9653 Expr *From = FromB.build(S, Loc); 9654 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9655 S.Context.getPointerType(From->getType()), 9656 VK_RValue, OK_Ordinary, Loc); 9657 Expr *To = ToB.build(S, Loc); 9658 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9659 S.Context.getPointerType(To->getType()), 9660 VK_RValue, OK_Ordinary, Loc); 9661 9662 const Type *E = T->getBaseElementTypeUnsafe(); 9663 bool NeedsCollectableMemCpy = 9664 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9665 9666 // Create a reference to the __builtin_objc_memmove_collectable function 9667 StringRef MemCpyName = NeedsCollectableMemCpy ? 9668 "__builtin_objc_memmove_collectable" : 9669 "__builtin_memcpy"; 9670 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9671 Sema::LookupOrdinaryName); 9672 S.LookupName(R, S.TUScope, true); 9673 9674 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9675 if (!MemCpy) 9676 // Something went horribly wrong earlier, and we will have complained 9677 // about it. 9678 return StmtError(); 9679 9680 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9681 VK_RValue, Loc, nullptr); 9682 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9683 9684 Expr *CallArgs[] = { 9685 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9686 }; 9687 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9688 Loc, CallArgs, Loc); 9689 9690 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9691 return Call.getAs<Stmt>(); 9692 } 9693 9694 /// \brief Builds a statement that copies/moves the given entity from \p From to 9695 /// \c To. 9696 /// 9697 /// This routine is used to copy/move the members of a class with an 9698 /// implicitly-declared copy/move assignment operator. When the entities being 9699 /// copied are arrays, this routine builds for loops to copy them. 9700 /// 9701 /// \param S The Sema object used for type-checking. 9702 /// 9703 /// \param Loc The location where the implicit copy/move is being generated. 9704 /// 9705 /// \param T The type of the expressions being copied/moved. Both expressions 9706 /// must have this type. 9707 /// 9708 /// \param To The expression we are copying/moving to. 9709 /// 9710 /// \param From The expression we are copying/moving from. 9711 /// 9712 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9713 /// Otherwise, it's a non-static member subobject. 9714 /// 9715 /// \param Copying Whether we're copying or moving. 9716 /// 9717 /// \param Depth Internal parameter recording the depth of the recursion. 9718 /// 9719 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9720 /// if a memcpy should be used instead. 9721 static StmtResult 9722 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9723 const ExprBuilder &To, const ExprBuilder &From, 9724 bool CopyingBaseSubobject, bool Copying, 9725 unsigned Depth = 0) { 9726 // C++11 [class.copy]p28: 9727 // Each subobject is assigned in the manner appropriate to its type: 9728 // 9729 // - if the subobject is of class type, as if by a call to operator= with 9730 // the subobject as the object expression and the corresponding 9731 // subobject of x as a single function argument (as if by explicit 9732 // qualification; that is, ignoring any possible virtual overriding 9733 // functions in more derived classes); 9734 // 9735 // C++03 [class.copy]p13: 9736 // - if the subobject is of class type, the copy assignment operator for 9737 // the class is used (as if by explicit qualification; that is, 9738 // ignoring any possible virtual overriding functions in more derived 9739 // classes); 9740 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9741 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9742 9743 // Look for operator=. 9744 DeclarationName Name 9745 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9746 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9747 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9748 9749 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9750 // operator. 9751 if (!S.getLangOpts().CPlusPlus11) { 9752 LookupResult::Filter F = OpLookup.makeFilter(); 9753 while (F.hasNext()) { 9754 NamedDecl *D = F.next(); 9755 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9756 if (Method->isCopyAssignmentOperator() || 9757 (!Copying && Method->isMoveAssignmentOperator())) 9758 continue; 9759 9760 F.erase(); 9761 } 9762 F.done(); 9763 } 9764 9765 // Suppress the protected check (C++ [class.protected]) for each of the 9766 // assignment operators we found. This strange dance is required when 9767 // we're assigning via a base classes's copy-assignment operator. To 9768 // ensure that we're getting the right base class subobject (without 9769 // ambiguities), we need to cast "this" to that subobject type; to 9770 // ensure that we don't go through the virtual call mechanism, we need 9771 // to qualify the operator= name with the base class (see below). However, 9772 // this means that if the base class has a protected copy assignment 9773 // operator, the protected member access check will fail. So, we 9774 // rewrite "protected" access to "public" access in this case, since we 9775 // know by construction that we're calling from a derived class. 9776 if (CopyingBaseSubobject) { 9777 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9778 L != LEnd; ++L) { 9779 if (L.getAccess() == AS_protected) 9780 L.setAccess(AS_public); 9781 } 9782 } 9783 9784 // Create the nested-name-specifier that will be used to qualify the 9785 // reference to operator=; this is required to suppress the virtual 9786 // call mechanism. 9787 CXXScopeSpec SS; 9788 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9789 SS.MakeTrivial(S.Context, 9790 NestedNameSpecifier::Create(S.Context, nullptr, false, 9791 CanonicalT), 9792 Loc); 9793 9794 // Create the reference to operator=. 9795 ExprResult OpEqualRef 9796 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9797 SS, /*TemplateKWLoc=*/SourceLocation(), 9798 /*FirstQualifierInScope=*/nullptr, 9799 OpLookup, 9800 /*TemplateArgs=*/nullptr, 9801 /*SuppressQualifierCheck=*/true); 9802 if (OpEqualRef.isInvalid()) 9803 return StmtError(); 9804 9805 // Build the call to the assignment operator. 9806 9807 Expr *FromInst = From.build(S, Loc); 9808 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9809 OpEqualRef.getAs<Expr>(), 9810 Loc, FromInst, Loc); 9811 if (Call.isInvalid()) 9812 return StmtError(); 9813 9814 // If we built a call to a trivial 'operator=' while copying an array, 9815 // bail out. We'll replace the whole shebang with a memcpy. 9816 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9817 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9818 return StmtResult((Stmt*)nullptr); 9819 9820 // Convert to an expression-statement, and clean up any produced 9821 // temporaries. 9822 return S.ActOnExprStmt(Call); 9823 } 9824 9825 // - if the subobject is of scalar type, the built-in assignment 9826 // operator is used. 9827 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9828 if (!ArrayTy) { 9829 ExprResult Assignment = S.CreateBuiltinBinOp( 9830 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9831 if (Assignment.isInvalid()) 9832 return StmtError(); 9833 return S.ActOnExprStmt(Assignment); 9834 } 9835 9836 // - if the subobject is an array, each element is assigned, in the 9837 // manner appropriate to the element type; 9838 9839 // Construct a loop over the array bounds, e.g., 9840 // 9841 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9842 // 9843 // that will copy each of the array elements. 9844 QualType SizeType = S.Context.getSizeType(); 9845 9846 // Create the iteration variable. 9847 IdentifierInfo *IterationVarName = nullptr; 9848 { 9849 SmallString<8> Str; 9850 llvm::raw_svector_ostream OS(Str); 9851 OS << "__i" << Depth; 9852 IterationVarName = &S.Context.Idents.get(OS.str()); 9853 } 9854 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9855 IterationVarName, SizeType, 9856 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9857 SC_None); 9858 9859 // Initialize the iteration variable to zero. 9860 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9861 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9862 9863 // Creates a reference to the iteration variable. 9864 RefBuilder IterationVarRef(IterationVar, SizeType); 9865 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9866 9867 // Create the DeclStmt that holds the iteration variable. 9868 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9869 9870 // Subscript the "from" and "to" expressions with the iteration variable. 9871 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9872 MoveCastBuilder FromIndexMove(FromIndexCopy); 9873 const ExprBuilder *FromIndex; 9874 if (Copying) 9875 FromIndex = &FromIndexCopy; 9876 else 9877 FromIndex = &FromIndexMove; 9878 9879 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9880 9881 // Build the copy/move for an individual element of the array. 9882 StmtResult Copy = 9883 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9884 ToIndex, *FromIndex, CopyingBaseSubobject, 9885 Copying, Depth + 1); 9886 // Bail out if copying fails or if we determined that we should use memcpy. 9887 if (Copy.isInvalid() || !Copy.get()) 9888 return Copy; 9889 9890 // Create the comparison against the array bound. 9891 llvm::APInt Upper 9892 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9893 Expr *Comparison 9894 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9895 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9896 BO_NE, S.Context.BoolTy, 9897 VK_RValue, OK_Ordinary, Loc, false); 9898 9899 // Create the pre-increment of the iteration variable. 9900 Expr *Increment 9901 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9902 SizeType, VK_LValue, OK_Ordinary, Loc); 9903 9904 // Construct the loop that copies all elements of this array. 9905 return S.ActOnForStmt(Loc, Loc, InitStmt, 9906 S.MakeFullExpr(Comparison), 9907 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9908 Loc, Copy.get()); 9909 } 9910 9911 static StmtResult 9912 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9913 const ExprBuilder &To, const ExprBuilder &From, 9914 bool CopyingBaseSubobject, bool Copying) { 9915 // Maybe we should use a memcpy? 9916 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9917 T.isTriviallyCopyableType(S.Context)) 9918 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9919 9920 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9921 CopyingBaseSubobject, 9922 Copying, 0)); 9923 9924 // If we ended up picking a trivial assignment operator for an array of a 9925 // non-trivially-copyable class type, just emit a memcpy. 9926 if (!Result.isInvalid() && !Result.get()) 9927 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9928 9929 return Result; 9930 } 9931 9932 Sema::ImplicitExceptionSpecification 9933 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9934 CXXRecordDecl *ClassDecl = MD->getParent(); 9935 9936 ImplicitExceptionSpecification ExceptSpec(*this); 9937 if (ClassDecl->isInvalidDecl()) 9938 return ExceptSpec; 9939 9940 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9941 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9942 unsigned ArgQuals = 9943 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9944 9945 // C++ [except.spec]p14: 9946 // An implicitly declared special member function (Clause 12) shall have an 9947 // exception-specification. [...] 9948 9949 // It is unspecified whether or not an implicit copy assignment operator 9950 // attempts to deduplicate calls to assignment operators of virtual bases are 9951 // made. As such, this exception specification is effectively unspecified. 9952 // Based on a similar decision made for constness in C++0x, we're erring on 9953 // the side of assuming such calls to be made regardless of whether they 9954 // actually happen. 9955 for (const auto &Base : ClassDecl->bases()) { 9956 if (Base.isVirtual()) 9957 continue; 9958 9959 CXXRecordDecl *BaseClassDecl 9960 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9961 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9962 ArgQuals, false, 0)) 9963 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9964 } 9965 9966 for (const auto &Base : ClassDecl->vbases()) { 9967 CXXRecordDecl *BaseClassDecl 9968 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9969 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9970 ArgQuals, false, 0)) 9971 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9972 } 9973 9974 for (const auto *Field : ClassDecl->fields()) { 9975 QualType FieldType = Context.getBaseElementType(Field->getType()); 9976 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9977 if (CXXMethodDecl *CopyAssign = 9978 LookupCopyingAssignment(FieldClassDecl, 9979 ArgQuals | FieldType.getCVRQualifiers(), 9980 false, 0)) 9981 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9982 } 9983 } 9984 9985 return ExceptSpec; 9986 } 9987 9988 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9989 // Note: The following rules are largely analoguous to the copy 9990 // constructor rules. Note that virtual bases are not taken into account 9991 // for determining the argument type of the operator. Note also that 9992 // operators taking an object instead of a reference are allowed. 9993 assert(ClassDecl->needsImplicitCopyAssignment()); 9994 9995 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9996 if (DSM.isAlreadyBeingDeclared()) 9997 return nullptr; 9998 9999 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10000 QualType RetType = Context.getLValueReferenceType(ArgType); 10001 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 10002 if (Const) 10003 ArgType = ArgType.withConst(); 10004 ArgType = Context.getLValueReferenceType(ArgType); 10005 10006 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10007 CXXCopyAssignment, 10008 Const); 10009 10010 // An implicitly-declared copy assignment operator is an inline public 10011 // member of its class. 10012 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10013 SourceLocation ClassLoc = ClassDecl->getLocation(); 10014 DeclarationNameInfo NameInfo(Name, ClassLoc); 10015 CXXMethodDecl *CopyAssignment = 10016 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10017 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10018 /*isInline=*/true, Constexpr, SourceLocation()); 10019 CopyAssignment->setAccess(AS_public); 10020 CopyAssignment->setDefaulted(); 10021 CopyAssignment->setImplicit(); 10022 10023 if (getLangOpts().CUDA) { 10024 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 10025 CopyAssignment, 10026 /* ConstRHS */ Const, 10027 /* Diagnose */ false); 10028 } 10029 10030 // Build an exception specification pointing back at this member. 10031 FunctionProtoType::ExtProtoInfo EPI = 10032 getImplicitMethodEPI(*this, CopyAssignment); 10033 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10034 10035 // Add the parameter to the operator. 10036 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 10037 ClassLoc, ClassLoc, 10038 /*Id=*/nullptr, ArgType, 10039 /*TInfo=*/nullptr, SC_None, 10040 nullptr); 10041 CopyAssignment->setParams(FromParam); 10042 10043 AddOverriddenMethods(ClassDecl, CopyAssignment); 10044 10045 CopyAssignment->setTrivial( 10046 ClassDecl->needsOverloadResolutionForCopyAssignment() 10047 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 10048 : ClassDecl->hasTrivialCopyAssignment()); 10049 10050 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 10051 SetDeclDeleted(CopyAssignment, ClassLoc); 10052 10053 // Note that we have added this copy-assignment operator. 10054 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10055 10056 if (Scope *S = getScopeForContext(ClassDecl)) 10057 PushOnScopeChains(CopyAssignment, S, false); 10058 ClassDecl->addDecl(CopyAssignment); 10059 10060 return CopyAssignment; 10061 } 10062 10063 /// Diagnose an implicit copy operation for a class which is odr-used, but 10064 /// which is deprecated because the class has a user-declared copy constructor, 10065 /// copy assignment operator, or destructor. 10066 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 10067 SourceLocation UseLoc) { 10068 assert(CopyOp->isImplicit()); 10069 10070 CXXRecordDecl *RD = CopyOp->getParent(); 10071 CXXMethodDecl *UserDeclaredOperation = nullptr; 10072 10073 // In Microsoft mode, assignment operations don't affect constructors and 10074 // vice versa. 10075 if (RD->hasUserDeclaredDestructor()) { 10076 UserDeclaredOperation = RD->getDestructor(); 10077 } else if (!isa<CXXConstructorDecl>(CopyOp) && 10078 RD->hasUserDeclaredCopyConstructor() && 10079 !S.getLangOpts().MSVCCompat) { 10080 // Find any user-declared copy constructor. 10081 for (auto *I : RD->ctors()) { 10082 if (I->isCopyConstructor()) { 10083 UserDeclaredOperation = I; 10084 break; 10085 } 10086 } 10087 assert(UserDeclaredOperation); 10088 } else if (isa<CXXConstructorDecl>(CopyOp) && 10089 RD->hasUserDeclaredCopyAssignment() && 10090 !S.getLangOpts().MSVCCompat) { 10091 // Find any user-declared move assignment operator. 10092 for (auto *I : RD->methods()) { 10093 if (I->isCopyAssignmentOperator()) { 10094 UserDeclaredOperation = I; 10095 break; 10096 } 10097 } 10098 assert(UserDeclaredOperation); 10099 } 10100 10101 if (UserDeclaredOperation) { 10102 S.Diag(UserDeclaredOperation->getLocation(), 10103 diag::warn_deprecated_copy_operation) 10104 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 10105 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 10106 S.Diag(UseLoc, diag::note_member_synthesized_at) 10107 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 10108 : Sema::CXXCopyAssignment) 10109 << RD; 10110 } 10111 } 10112 10113 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 10114 CXXMethodDecl *CopyAssignOperator) { 10115 assert((CopyAssignOperator->isDefaulted() && 10116 CopyAssignOperator->isOverloadedOperator() && 10117 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 10118 !CopyAssignOperator->doesThisDeclarationHaveABody() && 10119 !CopyAssignOperator->isDeleted()) && 10120 "DefineImplicitCopyAssignment called for wrong function"); 10121 10122 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 10123 10124 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 10125 CopyAssignOperator->setInvalidDecl(); 10126 return; 10127 } 10128 10129 // C++11 [class.copy]p18: 10130 // The [definition of an implicitly declared copy assignment operator] is 10131 // deprecated if the class has a user-declared copy constructor or a 10132 // user-declared destructor. 10133 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 10134 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 10135 10136 CopyAssignOperator->markUsed(Context); 10137 10138 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 10139 DiagnosticErrorTrap Trap(Diags); 10140 10141 // C++0x [class.copy]p30: 10142 // The implicitly-defined or explicitly-defaulted copy assignment operator 10143 // for a non-union class X performs memberwise copy assignment of its 10144 // subobjects. The direct base classes of X are assigned first, in the 10145 // order of their declaration in the base-specifier-list, and then the 10146 // immediate non-static data members of X are assigned, in the order in 10147 // which they were declared in the class definition. 10148 10149 // The statements that form the synthesized function body. 10150 SmallVector<Stmt*, 8> Statements; 10151 10152 // The parameter for the "other" object, which we are copying from. 10153 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 10154 Qualifiers OtherQuals = Other->getType().getQualifiers(); 10155 QualType OtherRefType = Other->getType(); 10156 if (const LValueReferenceType *OtherRef 10157 = OtherRefType->getAs<LValueReferenceType>()) { 10158 OtherRefType = OtherRef->getPointeeType(); 10159 OtherQuals = OtherRefType.getQualifiers(); 10160 } 10161 10162 // Our location for everything implicitly-generated. 10163 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 10164 ? CopyAssignOperator->getLocEnd() 10165 : CopyAssignOperator->getLocation(); 10166 10167 // Builds a DeclRefExpr for the "other" object. 10168 RefBuilder OtherRef(Other, OtherRefType); 10169 10170 // Builds the "this" pointer. 10171 ThisBuilder This; 10172 10173 // Assign base classes. 10174 bool Invalid = false; 10175 for (auto &Base : ClassDecl->bases()) { 10176 // Form the assignment: 10177 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10178 QualType BaseType = Base.getType().getUnqualifiedType(); 10179 if (!BaseType->isRecordType()) { 10180 Invalid = true; 10181 continue; 10182 } 10183 10184 CXXCastPath BasePath; 10185 BasePath.push_back(&Base); 10186 10187 // Construct the "from" expression, which is an implicit cast to the 10188 // appropriately-qualified base type. 10189 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10190 VK_LValue, BasePath); 10191 10192 // Dereference "this". 10193 DerefBuilder DerefThis(This); 10194 CastBuilder To(DerefThis, 10195 Context.getCVRQualifiedType( 10196 BaseType, CopyAssignOperator->getTypeQualifiers()), 10197 VK_LValue, BasePath); 10198 10199 // Build the copy. 10200 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10201 To, From, 10202 /*CopyingBaseSubobject=*/true, 10203 /*Copying=*/true); 10204 if (Copy.isInvalid()) { 10205 Diag(CurrentLocation, diag::note_member_synthesized_at) 10206 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10207 CopyAssignOperator->setInvalidDecl(); 10208 return; 10209 } 10210 10211 // Success! Record the copy. 10212 Statements.push_back(Copy.getAs<Expr>()); 10213 } 10214 10215 // Assign non-static members. 10216 for (auto *Field : ClassDecl->fields()) { 10217 // FIXME: We should form some kind of AST representation for the implied 10218 // memcpy in a union copy operation. 10219 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10220 continue; 10221 10222 if (Field->isInvalidDecl()) { 10223 Invalid = true; 10224 continue; 10225 } 10226 10227 // Check for members of reference type; we can't copy those. 10228 if (Field->getType()->isReferenceType()) { 10229 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10230 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10231 Diag(Field->getLocation(), diag::note_declared_at); 10232 Diag(CurrentLocation, diag::note_member_synthesized_at) 10233 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10234 Invalid = true; 10235 continue; 10236 } 10237 10238 // Check for members of const-qualified, non-class type. 10239 QualType BaseType = Context.getBaseElementType(Field->getType()); 10240 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10241 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10242 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10243 Diag(Field->getLocation(), diag::note_declared_at); 10244 Diag(CurrentLocation, diag::note_member_synthesized_at) 10245 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10246 Invalid = true; 10247 continue; 10248 } 10249 10250 // Suppress assigning zero-width bitfields. 10251 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10252 continue; 10253 10254 QualType FieldType = Field->getType().getNonReferenceType(); 10255 if (FieldType->isIncompleteArrayType()) { 10256 assert(ClassDecl->hasFlexibleArrayMember() && 10257 "Incomplete array type is not valid"); 10258 continue; 10259 } 10260 10261 // Build references to the field in the object we're copying from and to. 10262 CXXScopeSpec SS; // Intentionally empty 10263 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10264 LookupMemberName); 10265 MemberLookup.addDecl(Field); 10266 MemberLookup.resolveKind(); 10267 10268 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10269 10270 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10271 10272 // Build the copy of this field. 10273 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10274 To, From, 10275 /*CopyingBaseSubobject=*/false, 10276 /*Copying=*/true); 10277 if (Copy.isInvalid()) { 10278 Diag(CurrentLocation, diag::note_member_synthesized_at) 10279 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10280 CopyAssignOperator->setInvalidDecl(); 10281 return; 10282 } 10283 10284 // Success! Record the copy. 10285 Statements.push_back(Copy.getAs<Stmt>()); 10286 } 10287 10288 if (!Invalid) { 10289 // Add a "return *this;" 10290 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10291 10292 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10293 if (Return.isInvalid()) 10294 Invalid = true; 10295 else { 10296 Statements.push_back(Return.getAs<Stmt>()); 10297 10298 if (Trap.hasErrorOccurred()) { 10299 Diag(CurrentLocation, diag::note_member_synthesized_at) 10300 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10301 Invalid = true; 10302 } 10303 } 10304 } 10305 10306 // The exception specification is needed because we are defining the 10307 // function. 10308 ResolveExceptionSpec(CurrentLocation, 10309 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10310 10311 if (Invalid) { 10312 CopyAssignOperator->setInvalidDecl(); 10313 return; 10314 } 10315 10316 StmtResult Body; 10317 { 10318 CompoundScopeRAII CompoundScope(*this); 10319 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10320 /*isStmtExpr=*/false); 10321 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10322 } 10323 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10324 10325 if (ASTMutationListener *L = getASTMutationListener()) { 10326 L->CompletedImplicitDefinition(CopyAssignOperator); 10327 } 10328 } 10329 10330 Sema::ImplicitExceptionSpecification 10331 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10332 CXXRecordDecl *ClassDecl = MD->getParent(); 10333 10334 ImplicitExceptionSpecification ExceptSpec(*this); 10335 if (ClassDecl->isInvalidDecl()) 10336 return ExceptSpec; 10337 10338 // C++0x [except.spec]p14: 10339 // An implicitly declared special member function (Clause 12) shall have an 10340 // exception-specification. [...] 10341 10342 // It is unspecified whether or not an implicit move assignment operator 10343 // attempts to deduplicate calls to assignment operators of virtual bases are 10344 // made. As such, this exception specification is effectively unspecified. 10345 // Based on a similar decision made for constness in C++0x, we're erring on 10346 // the side of assuming such calls to be made regardless of whether they 10347 // actually happen. 10348 // Note that a move constructor is not implicitly declared when there are 10349 // virtual bases, but it can still be user-declared and explicitly defaulted. 10350 for (const auto &Base : ClassDecl->bases()) { 10351 if (Base.isVirtual()) 10352 continue; 10353 10354 CXXRecordDecl *BaseClassDecl 10355 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10356 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10357 0, false, 0)) 10358 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10359 } 10360 10361 for (const auto &Base : ClassDecl->vbases()) { 10362 CXXRecordDecl *BaseClassDecl 10363 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10364 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10365 0, false, 0)) 10366 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10367 } 10368 10369 for (const auto *Field : ClassDecl->fields()) { 10370 QualType FieldType = Context.getBaseElementType(Field->getType()); 10371 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10372 if (CXXMethodDecl *MoveAssign = 10373 LookupMovingAssignment(FieldClassDecl, 10374 FieldType.getCVRQualifiers(), 10375 false, 0)) 10376 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10377 } 10378 } 10379 10380 return ExceptSpec; 10381 } 10382 10383 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10384 assert(ClassDecl->needsImplicitMoveAssignment()); 10385 10386 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10387 if (DSM.isAlreadyBeingDeclared()) 10388 return nullptr; 10389 10390 // Note: The following rules are largely analoguous to the move 10391 // constructor rules. 10392 10393 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10394 QualType RetType = Context.getLValueReferenceType(ArgType); 10395 ArgType = Context.getRValueReferenceType(ArgType); 10396 10397 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10398 CXXMoveAssignment, 10399 false); 10400 10401 // An implicitly-declared move assignment operator is an inline public 10402 // member of its class. 10403 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10404 SourceLocation ClassLoc = ClassDecl->getLocation(); 10405 DeclarationNameInfo NameInfo(Name, ClassLoc); 10406 CXXMethodDecl *MoveAssignment = 10407 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10408 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10409 /*isInline=*/true, Constexpr, SourceLocation()); 10410 MoveAssignment->setAccess(AS_public); 10411 MoveAssignment->setDefaulted(); 10412 MoveAssignment->setImplicit(); 10413 10414 if (getLangOpts().CUDA) { 10415 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10416 MoveAssignment, 10417 /* ConstRHS */ false, 10418 /* Diagnose */ false); 10419 } 10420 10421 // Build an exception specification pointing back at this member. 10422 FunctionProtoType::ExtProtoInfo EPI = 10423 getImplicitMethodEPI(*this, MoveAssignment); 10424 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10425 10426 // Add the parameter to the operator. 10427 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10428 ClassLoc, ClassLoc, 10429 /*Id=*/nullptr, ArgType, 10430 /*TInfo=*/nullptr, SC_None, 10431 nullptr); 10432 MoveAssignment->setParams(FromParam); 10433 10434 AddOverriddenMethods(ClassDecl, MoveAssignment); 10435 10436 MoveAssignment->setTrivial( 10437 ClassDecl->needsOverloadResolutionForMoveAssignment() 10438 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10439 : ClassDecl->hasTrivialMoveAssignment()); 10440 10441 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10442 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10443 SetDeclDeleted(MoveAssignment, ClassLoc); 10444 } 10445 10446 // Note that we have added this copy-assignment operator. 10447 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10448 10449 if (Scope *S = getScopeForContext(ClassDecl)) 10450 PushOnScopeChains(MoveAssignment, S, false); 10451 ClassDecl->addDecl(MoveAssignment); 10452 10453 return MoveAssignment; 10454 } 10455 10456 /// Check if we're implicitly defining a move assignment operator for a class 10457 /// with virtual bases. Such a move assignment might move-assign the virtual 10458 /// base multiple times. 10459 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10460 SourceLocation CurrentLocation) { 10461 assert(!Class->isDependentContext() && "should not define dependent move"); 10462 10463 // Only a virtual base could get implicitly move-assigned multiple times. 10464 // Only a non-trivial move assignment can observe this. We only want to 10465 // diagnose if we implicitly define an assignment operator that assigns 10466 // two base classes, both of which move-assign the same virtual base. 10467 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10468 Class->getNumBases() < 2) 10469 return; 10470 10471 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10472 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10473 VBaseMap VBases; 10474 10475 for (auto &BI : Class->bases()) { 10476 Worklist.push_back(&BI); 10477 while (!Worklist.empty()) { 10478 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10479 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10480 10481 // If the base has no non-trivial move assignment operators, 10482 // we don't care about moves from it. 10483 if (!Base->hasNonTrivialMoveAssignment()) 10484 continue; 10485 10486 // If there's nothing virtual here, skip it. 10487 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10488 continue; 10489 10490 // If we're not actually going to call a move assignment for this base, 10491 // or the selected move assignment is trivial, skip it. 10492 Sema::SpecialMemberOverloadResult *SMOR = 10493 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10494 /*ConstArg*/false, /*VolatileArg*/false, 10495 /*RValueThis*/true, /*ConstThis*/false, 10496 /*VolatileThis*/false); 10497 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10498 !SMOR->getMethod()->isMoveAssignmentOperator()) 10499 continue; 10500 10501 if (BaseSpec->isVirtual()) { 10502 // We're going to move-assign this virtual base, and its move 10503 // assignment operator is not trivial. If this can happen for 10504 // multiple distinct direct bases of Class, diagnose it. (If it 10505 // only happens in one base, we'll diagnose it when synthesizing 10506 // that base class's move assignment operator.) 10507 CXXBaseSpecifier *&Existing = 10508 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10509 .first->second; 10510 if (Existing && Existing != &BI) { 10511 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10512 << Class << Base; 10513 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10514 << (Base->getCanonicalDecl() == 10515 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10516 << Base << Existing->getType() << Existing->getSourceRange(); 10517 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10518 << (Base->getCanonicalDecl() == 10519 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10520 << Base << BI.getType() << BaseSpec->getSourceRange(); 10521 10522 // Only diagnose each vbase once. 10523 Existing = nullptr; 10524 } 10525 } else { 10526 // Only walk over bases that have defaulted move assignment operators. 10527 // We assume that any user-provided move assignment operator handles 10528 // the multiple-moves-of-vbase case itself somehow. 10529 if (!SMOR->getMethod()->isDefaulted()) 10530 continue; 10531 10532 // We're going to move the base classes of Base. Add them to the list. 10533 for (auto &BI : Base->bases()) 10534 Worklist.push_back(&BI); 10535 } 10536 } 10537 } 10538 } 10539 10540 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10541 CXXMethodDecl *MoveAssignOperator) { 10542 assert((MoveAssignOperator->isDefaulted() && 10543 MoveAssignOperator->isOverloadedOperator() && 10544 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10545 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10546 !MoveAssignOperator->isDeleted()) && 10547 "DefineImplicitMoveAssignment called for wrong function"); 10548 10549 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10550 10551 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10552 MoveAssignOperator->setInvalidDecl(); 10553 return; 10554 } 10555 10556 MoveAssignOperator->markUsed(Context); 10557 10558 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10559 DiagnosticErrorTrap Trap(Diags); 10560 10561 // C++0x [class.copy]p28: 10562 // The implicitly-defined or move assignment operator for a non-union class 10563 // X performs memberwise move assignment of its subobjects. The direct base 10564 // classes of X are assigned first, in the order of their declaration in the 10565 // base-specifier-list, and then the immediate non-static data members of X 10566 // are assigned, in the order in which they were declared in the class 10567 // definition. 10568 10569 // Issue a warning if our implicit move assignment operator will move 10570 // from a virtual base more than once. 10571 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10572 10573 // The statements that form the synthesized function body. 10574 SmallVector<Stmt*, 8> Statements; 10575 10576 // The parameter for the "other" object, which we are move from. 10577 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10578 QualType OtherRefType = Other->getType()-> 10579 getAs<RValueReferenceType>()->getPointeeType(); 10580 assert(!OtherRefType.getQualifiers() && 10581 "Bad argument type of defaulted move assignment"); 10582 10583 // Our location for everything implicitly-generated. 10584 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10585 ? MoveAssignOperator->getLocEnd() 10586 : MoveAssignOperator->getLocation(); 10587 10588 // Builds a reference to the "other" object. 10589 RefBuilder OtherRef(Other, OtherRefType); 10590 // Cast to rvalue. 10591 MoveCastBuilder MoveOther(OtherRef); 10592 10593 // Builds the "this" pointer. 10594 ThisBuilder This; 10595 10596 // Assign base classes. 10597 bool Invalid = false; 10598 for (auto &Base : ClassDecl->bases()) { 10599 // C++11 [class.copy]p28: 10600 // It is unspecified whether subobjects representing virtual base classes 10601 // are assigned more than once by the implicitly-defined copy assignment 10602 // operator. 10603 // FIXME: Do not assign to a vbase that will be assigned by some other base 10604 // class. For a move-assignment, this can result in the vbase being moved 10605 // multiple times. 10606 10607 // Form the assignment: 10608 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10609 QualType BaseType = Base.getType().getUnqualifiedType(); 10610 if (!BaseType->isRecordType()) { 10611 Invalid = true; 10612 continue; 10613 } 10614 10615 CXXCastPath BasePath; 10616 BasePath.push_back(&Base); 10617 10618 // Construct the "from" expression, which is an implicit cast to the 10619 // appropriately-qualified base type. 10620 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10621 10622 // Dereference "this". 10623 DerefBuilder DerefThis(This); 10624 10625 // Implicitly cast "this" to the appropriately-qualified base type. 10626 CastBuilder To(DerefThis, 10627 Context.getCVRQualifiedType( 10628 BaseType, MoveAssignOperator->getTypeQualifiers()), 10629 VK_LValue, BasePath); 10630 10631 // Build the move. 10632 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10633 To, From, 10634 /*CopyingBaseSubobject=*/true, 10635 /*Copying=*/false); 10636 if (Move.isInvalid()) { 10637 Diag(CurrentLocation, diag::note_member_synthesized_at) 10638 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10639 MoveAssignOperator->setInvalidDecl(); 10640 return; 10641 } 10642 10643 // Success! Record the move. 10644 Statements.push_back(Move.getAs<Expr>()); 10645 } 10646 10647 // Assign non-static members. 10648 for (auto *Field : ClassDecl->fields()) { 10649 // FIXME: We should form some kind of AST representation for the implied 10650 // memcpy in a union copy operation. 10651 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10652 continue; 10653 10654 if (Field->isInvalidDecl()) { 10655 Invalid = true; 10656 continue; 10657 } 10658 10659 // Check for members of reference type; we can't move those. 10660 if (Field->getType()->isReferenceType()) { 10661 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10662 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10663 Diag(Field->getLocation(), diag::note_declared_at); 10664 Diag(CurrentLocation, diag::note_member_synthesized_at) 10665 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10666 Invalid = true; 10667 continue; 10668 } 10669 10670 // Check for members of const-qualified, non-class type. 10671 QualType BaseType = Context.getBaseElementType(Field->getType()); 10672 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10673 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10674 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10675 Diag(Field->getLocation(), diag::note_declared_at); 10676 Diag(CurrentLocation, diag::note_member_synthesized_at) 10677 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10678 Invalid = true; 10679 continue; 10680 } 10681 10682 // Suppress assigning zero-width bitfields. 10683 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10684 continue; 10685 10686 QualType FieldType = Field->getType().getNonReferenceType(); 10687 if (FieldType->isIncompleteArrayType()) { 10688 assert(ClassDecl->hasFlexibleArrayMember() && 10689 "Incomplete array type is not valid"); 10690 continue; 10691 } 10692 10693 // Build references to the field in the object we're copying from and to. 10694 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10695 LookupMemberName); 10696 MemberLookup.addDecl(Field); 10697 MemberLookup.resolveKind(); 10698 MemberBuilder From(MoveOther, OtherRefType, 10699 /*IsArrow=*/false, MemberLookup); 10700 MemberBuilder To(This, getCurrentThisType(), 10701 /*IsArrow=*/true, MemberLookup); 10702 10703 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10704 "Member reference with rvalue base must be rvalue except for reference " 10705 "members, which aren't allowed for move assignment."); 10706 10707 // Build the move of this field. 10708 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10709 To, From, 10710 /*CopyingBaseSubobject=*/false, 10711 /*Copying=*/false); 10712 if (Move.isInvalid()) { 10713 Diag(CurrentLocation, diag::note_member_synthesized_at) 10714 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10715 MoveAssignOperator->setInvalidDecl(); 10716 return; 10717 } 10718 10719 // Success! Record the copy. 10720 Statements.push_back(Move.getAs<Stmt>()); 10721 } 10722 10723 if (!Invalid) { 10724 // Add a "return *this;" 10725 ExprResult ThisObj = 10726 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10727 10728 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10729 if (Return.isInvalid()) 10730 Invalid = true; 10731 else { 10732 Statements.push_back(Return.getAs<Stmt>()); 10733 10734 if (Trap.hasErrorOccurred()) { 10735 Diag(CurrentLocation, diag::note_member_synthesized_at) 10736 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10737 Invalid = true; 10738 } 10739 } 10740 } 10741 10742 // The exception specification is needed because we are defining the 10743 // function. 10744 ResolveExceptionSpec(CurrentLocation, 10745 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10746 10747 if (Invalid) { 10748 MoveAssignOperator->setInvalidDecl(); 10749 return; 10750 } 10751 10752 StmtResult Body; 10753 { 10754 CompoundScopeRAII CompoundScope(*this); 10755 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10756 /*isStmtExpr=*/false); 10757 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10758 } 10759 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10760 10761 if (ASTMutationListener *L = getASTMutationListener()) { 10762 L->CompletedImplicitDefinition(MoveAssignOperator); 10763 } 10764 } 10765 10766 Sema::ImplicitExceptionSpecification 10767 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10768 CXXRecordDecl *ClassDecl = MD->getParent(); 10769 10770 ImplicitExceptionSpecification ExceptSpec(*this); 10771 if (ClassDecl->isInvalidDecl()) 10772 return ExceptSpec; 10773 10774 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10775 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10776 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10777 10778 // C++ [except.spec]p14: 10779 // An implicitly declared special member function (Clause 12) shall have an 10780 // exception-specification. [...] 10781 for (const auto &Base : ClassDecl->bases()) { 10782 // Virtual bases are handled below. 10783 if (Base.isVirtual()) 10784 continue; 10785 10786 CXXRecordDecl *BaseClassDecl 10787 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10788 if (CXXConstructorDecl *CopyConstructor = 10789 LookupCopyingConstructor(BaseClassDecl, Quals)) 10790 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10791 } 10792 for (const auto &Base : ClassDecl->vbases()) { 10793 CXXRecordDecl *BaseClassDecl 10794 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10795 if (CXXConstructorDecl *CopyConstructor = 10796 LookupCopyingConstructor(BaseClassDecl, Quals)) 10797 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10798 } 10799 for (const auto *Field : ClassDecl->fields()) { 10800 QualType FieldType = Context.getBaseElementType(Field->getType()); 10801 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10802 if (CXXConstructorDecl *CopyConstructor = 10803 LookupCopyingConstructor(FieldClassDecl, 10804 Quals | FieldType.getCVRQualifiers())) 10805 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10806 } 10807 } 10808 10809 return ExceptSpec; 10810 } 10811 10812 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10813 CXXRecordDecl *ClassDecl) { 10814 // C++ [class.copy]p4: 10815 // If the class definition does not explicitly declare a copy 10816 // constructor, one is declared implicitly. 10817 assert(ClassDecl->needsImplicitCopyConstructor()); 10818 10819 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10820 if (DSM.isAlreadyBeingDeclared()) 10821 return nullptr; 10822 10823 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10824 QualType ArgType = ClassType; 10825 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10826 if (Const) 10827 ArgType = ArgType.withConst(); 10828 ArgType = Context.getLValueReferenceType(ArgType); 10829 10830 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10831 CXXCopyConstructor, 10832 Const); 10833 10834 DeclarationName Name 10835 = Context.DeclarationNames.getCXXConstructorName( 10836 Context.getCanonicalType(ClassType)); 10837 SourceLocation ClassLoc = ClassDecl->getLocation(); 10838 DeclarationNameInfo NameInfo(Name, ClassLoc); 10839 10840 // An implicitly-declared copy constructor is an inline public 10841 // member of its class. 10842 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10843 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10844 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10845 Constexpr); 10846 CopyConstructor->setAccess(AS_public); 10847 CopyConstructor->setDefaulted(); 10848 10849 if (getLangOpts().CUDA) { 10850 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10851 CopyConstructor, 10852 /* ConstRHS */ Const, 10853 /* Diagnose */ false); 10854 } 10855 10856 // Build an exception specification pointing back at this member. 10857 FunctionProtoType::ExtProtoInfo EPI = 10858 getImplicitMethodEPI(*this, CopyConstructor); 10859 CopyConstructor->setType( 10860 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10861 10862 // Add the parameter to the constructor. 10863 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10864 ClassLoc, ClassLoc, 10865 /*IdentifierInfo=*/nullptr, 10866 ArgType, /*TInfo=*/nullptr, 10867 SC_None, nullptr); 10868 CopyConstructor->setParams(FromParam); 10869 10870 CopyConstructor->setTrivial( 10871 ClassDecl->needsOverloadResolutionForCopyConstructor() 10872 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10873 : ClassDecl->hasTrivialCopyConstructor()); 10874 10875 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10876 SetDeclDeleted(CopyConstructor, ClassLoc); 10877 10878 // Note that we have declared this constructor. 10879 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10880 10881 if (Scope *S = getScopeForContext(ClassDecl)) 10882 PushOnScopeChains(CopyConstructor, S, false); 10883 ClassDecl->addDecl(CopyConstructor); 10884 10885 return CopyConstructor; 10886 } 10887 10888 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10889 CXXConstructorDecl *CopyConstructor) { 10890 assert((CopyConstructor->isDefaulted() && 10891 CopyConstructor->isCopyConstructor() && 10892 !CopyConstructor->doesThisDeclarationHaveABody() && 10893 !CopyConstructor->isDeleted()) && 10894 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10895 10896 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10897 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10898 10899 // C++11 [class.copy]p7: 10900 // The [definition of an implicitly declared copy constructor] is 10901 // deprecated if the class has a user-declared copy assignment operator 10902 // or a user-declared destructor. 10903 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10904 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10905 10906 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10907 DiagnosticErrorTrap Trap(Diags); 10908 10909 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10910 Trap.hasErrorOccurred()) { 10911 Diag(CurrentLocation, diag::note_member_synthesized_at) 10912 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10913 CopyConstructor->setInvalidDecl(); 10914 } else { 10915 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10916 ? CopyConstructor->getLocEnd() 10917 : CopyConstructor->getLocation(); 10918 Sema::CompoundScopeRAII CompoundScope(*this); 10919 CopyConstructor->setBody( 10920 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10921 } 10922 10923 // The exception specification is needed because we are defining the 10924 // function. 10925 ResolveExceptionSpec(CurrentLocation, 10926 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10927 10928 CopyConstructor->markUsed(Context); 10929 MarkVTableUsed(CurrentLocation, ClassDecl); 10930 10931 if (ASTMutationListener *L = getASTMutationListener()) { 10932 L->CompletedImplicitDefinition(CopyConstructor); 10933 } 10934 } 10935 10936 Sema::ImplicitExceptionSpecification 10937 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10938 CXXRecordDecl *ClassDecl = MD->getParent(); 10939 10940 // C++ [except.spec]p14: 10941 // An implicitly declared special member function (Clause 12) shall have an 10942 // exception-specification. [...] 10943 ImplicitExceptionSpecification ExceptSpec(*this); 10944 if (ClassDecl->isInvalidDecl()) 10945 return ExceptSpec; 10946 10947 // Direct base-class constructors. 10948 for (const auto &B : ClassDecl->bases()) { 10949 if (B.isVirtual()) // Handled below. 10950 continue; 10951 10952 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10953 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10954 CXXConstructorDecl *Constructor = 10955 LookupMovingConstructor(BaseClassDecl, 0); 10956 // If this is a deleted function, add it anyway. This might be conformant 10957 // with the standard. This might not. I'm not sure. It might not matter. 10958 if (Constructor) 10959 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10960 } 10961 } 10962 10963 // Virtual base-class constructors. 10964 for (const auto &B : ClassDecl->vbases()) { 10965 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10966 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10967 CXXConstructorDecl *Constructor = 10968 LookupMovingConstructor(BaseClassDecl, 0); 10969 // If this is a deleted function, add it anyway. This might be conformant 10970 // with the standard. This might not. I'm not sure. It might not matter. 10971 if (Constructor) 10972 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10973 } 10974 } 10975 10976 // Field constructors. 10977 for (const auto *F : ClassDecl->fields()) { 10978 QualType FieldType = Context.getBaseElementType(F->getType()); 10979 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10980 CXXConstructorDecl *Constructor = 10981 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10982 // If this is a deleted function, add it anyway. This might be conformant 10983 // with the standard. This might not. I'm not sure. It might not matter. 10984 // In particular, the problem is that this function never gets called. It 10985 // might just be ill-formed because this function attempts to refer to 10986 // a deleted function here. 10987 if (Constructor) 10988 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10989 } 10990 } 10991 10992 return ExceptSpec; 10993 } 10994 10995 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10996 CXXRecordDecl *ClassDecl) { 10997 assert(ClassDecl->needsImplicitMoveConstructor()); 10998 10999 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 11000 if (DSM.isAlreadyBeingDeclared()) 11001 return nullptr; 11002 11003 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11004 QualType ArgType = Context.getRValueReferenceType(ClassType); 11005 11006 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11007 CXXMoveConstructor, 11008 false); 11009 11010 DeclarationName Name 11011 = Context.DeclarationNames.getCXXConstructorName( 11012 Context.getCanonicalType(ClassType)); 11013 SourceLocation ClassLoc = ClassDecl->getLocation(); 11014 DeclarationNameInfo NameInfo(Name, ClassLoc); 11015 11016 // C++11 [class.copy]p11: 11017 // An implicitly-declared copy/move constructor is an inline public 11018 // member of its class. 11019 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 11020 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11021 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11022 Constexpr); 11023 MoveConstructor->setAccess(AS_public); 11024 MoveConstructor->setDefaulted(); 11025 11026 if (getLangOpts().CUDA) { 11027 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 11028 MoveConstructor, 11029 /* ConstRHS */ false, 11030 /* Diagnose */ false); 11031 } 11032 11033 // Build an exception specification pointing back at this member. 11034 FunctionProtoType::ExtProtoInfo EPI = 11035 getImplicitMethodEPI(*this, MoveConstructor); 11036 MoveConstructor->setType( 11037 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11038 11039 // Add the parameter to the constructor. 11040 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 11041 ClassLoc, ClassLoc, 11042 /*IdentifierInfo=*/nullptr, 11043 ArgType, /*TInfo=*/nullptr, 11044 SC_None, nullptr); 11045 MoveConstructor->setParams(FromParam); 11046 11047 MoveConstructor->setTrivial( 11048 ClassDecl->needsOverloadResolutionForMoveConstructor() 11049 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 11050 : ClassDecl->hasTrivialMoveConstructor()); 11051 11052 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 11053 ClassDecl->setImplicitMoveConstructorIsDeleted(); 11054 SetDeclDeleted(MoveConstructor, ClassLoc); 11055 } 11056 11057 // Note that we have declared this constructor. 11058 ++ASTContext::NumImplicitMoveConstructorsDeclared; 11059 11060 if (Scope *S = getScopeForContext(ClassDecl)) 11061 PushOnScopeChains(MoveConstructor, S, false); 11062 ClassDecl->addDecl(MoveConstructor); 11063 11064 return MoveConstructor; 11065 } 11066 11067 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 11068 CXXConstructorDecl *MoveConstructor) { 11069 assert((MoveConstructor->isDefaulted() && 11070 MoveConstructor->isMoveConstructor() && 11071 !MoveConstructor->doesThisDeclarationHaveABody() && 11072 !MoveConstructor->isDeleted()) && 11073 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 11074 11075 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 11076 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 11077 11078 SynthesizedFunctionScope Scope(*this, MoveConstructor); 11079 DiagnosticErrorTrap Trap(Diags); 11080 11081 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 11082 Trap.hasErrorOccurred()) { 11083 Diag(CurrentLocation, diag::note_member_synthesized_at) 11084 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 11085 MoveConstructor->setInvalidDecl(); 11086 } else { 11087 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 11088 ? MoveConstructor->getLocEnd() 11089 : MoveConstructor->getLocation(); 11090 Sema::CompoundScopeRAII CompoundScope(*this); 11091 MoveConstructor->setBody(ActOnCompoundStmt( 11092 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 11093 } 11094 11095 // The exception specification is needed because we are defining the 11096 // function. 11097 ResolveExceptionSpec(CurrentLocation, 11098 MoveConstructor->getType()->castAs<FunctionProtoType>()); 11099 11100 MoveConstructor->markUsed(Context); 11101 MarkVTableUsed(CurrentLocation, ClassDecl); 11102 11103 if (ASTMutationListener *L = getASTMutationListener()) { 11104 L->CompletedImplicitDefinition(MoveConstructor); 11105 } 11106 } 11107 11108 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 11109 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 11110 } 11111 11112 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 11113 SourceLocation CurrentLocation, 11114 CXXConversionDecl *Conv) { 11115 CXXRecordDecl *Lambda = Conv->getParent(); 11116 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 11117 // If we are defining a specialization of a conversion to function-ptr 11118 // cache the deduced template arguments for this specialization 11119 // so that we can use them to retrieve the corresponding call-operator 11120 // and static-invoker. 11121 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 11122 11123 // Retrieve the corresponding call-operator specialization. 11124 if (Lambda->isGenericLambda()) { 11125 assert(Conv->isFunctionTemplateSpecialization()); 11126 FunctionTemplateDecl *CallOpTemplate = 11127 CallOp->getDescribedFunctionTemplate(); 11128 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 11129 void *InsertPos = nullptr; 11130 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 11131 DeducedTemplateArgs->asArray(), 11132 InsertPos); 11133 assert(CallOpSpec && 11134 "Conversion operator must have a corresponding call operator"); 11135 CallOp = cast<CXXMethodDecl>(CallOpSpec); 11136 } 11137 // Mark the call operator referenced (and add to pending instantiations 11138 // if necessary). 11139 // For both the conversion and static-invoker template specializations 11140 // we construct their body's in this function, so no need to add them 11141 // to the PendingInstantiations. 11142 MarkFunctionReferenced(CurrentLocation, CallOp); 11143 11144 SynthesizedFunctionScope Scope(*this, Conv); 11145 DiagnosticErrorTrap Trap(Diags); 11146 11147 // Retrieve the static invoker... 11148 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 11149 // ... and get the corresponding specialization for a generic lambda. 11150 if (Lambda->isGenericLambda()) { 11151 assert(DeducedTemplateArgs && 11152 "Must have deduced template arguments from Conversion Operator"); 11153 FunctionTemplateDecl *InvokeTemplate = 11154 Invoker->getDescribedFunctionTemplate(); 11155 void *InsertPos = nullptr; 11156 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 11157 DeducedTemplateArgs->asArray(), 11158 InsertPos); 11159 assert(InvokeSpec && 11160 "Must have a corresponding static invoker specialization"); 11161 Invoker = cast<CXXMethodDecl>(InvokeSpec); 11162 } 11163 // Construct the body of the conversion function { return __invoke; }. 11164 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 11165 VK_LValue, Conv->getLocation()).get(); 11166 assert(FunctionRef && "Can't refer to __invoke function?"); 11167 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 11168 Conv->setBody(new (Context) CompoundStmt(Context, Return, 11169 Conv->getLocation(), 11170 Conv->getLocation())); 11171 11172 Conv->markUsed(Context); 11173 Conv->setReferenced(); 11174 11175 // Fill in the __invoke function with a dummy implementation. IR generation 11176 // will fill in the actual details. 11177 Invoker->markUsed(Context); 11178 Invoker->setReferenced(); 11179 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 11180 11181 if (ASTMutationListener *L = getASTMutationListener()) { 11182 L->CompletedImplicitDefinition(Conv); 11183 L->CompletedImplicitDefinition(Invoker); 11184 } 11185 } 11186 11187 11188 11189 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11190 SourceLocation CurrentLocation, 11191 CXXConversionDecl *Conv) 11192 { 11193 assert(!Conv->getParent()->isGenericLambda()); 11194 11195 Conv->markUsed(Context); 11196 11197 SynthesizedFunctionScope Scope(*this, Conv); 11198 DiagnosticErrorTrap Trap(Diags); 11199 11200 // Copy-initialize the lambda object as needed to capture it. 11201 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11202 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11203 11204 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11205 Conv->getLocation(), 11206 Conv, DerefThis); 11207 11208 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11209 // behavior. Note that only the general conversion function does this 11210 // (since it's unusable otherwise); in the case where we inline the 11211 // block literal, it has block literal lifetime semantics. 11212 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11213 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11214 CK_CopyAndAutoreleaseBlockObject, 11215 BuildBlock.get(), nullptr, VK_RValue); 11216 11217 if (BuildBlock.isInvalid()) { 11218 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11219 Conv->setInvalidDecl(); 11220 return; 11221 } 11222 11223 // Create the return statement that returns the block from the conversion 11224 // function. 11225 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11226 if (Return.isInvalid()) { 11227 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11228 Conv->setInvalidDecl(); 11229 return; 11230 } 11231 11232 // Set the body of the conversion function. 11233 Stmt *ReturnS = Return.get(); 11234 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11235 Conv->getLocation(), 11236 Conv->getLocation())); 11237 11238 // We're done; notify the mutation listener, if any. 11239 if (ASTMutationListener *L = getASTMutationListener()) { 11240 L->CompletedImplicitDefinition(Conv); 11241 } 11242 } 11243 11244 /// \brief Determine whether the given list arguments contains exactly one 11245 /// "real" (non-default) argument. 11246 static bool hasOneRealArgument(MultiExprArg Args) { 11247 switch (Args.size()) { 11248 case 0: 11249 return false; 11250 11251 default: 11252 if (!Args[1]->isDefaultArgument()) 11253 return false; 11254 11255 // fall through 11256 case 1: 11257 return !Args[0]->isDefaultArgument(); 11258 } 11259 11260 return false; 11261 } 11262 11263 ExprResult 11264 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11265 CXXConstructorDecl *Constructor, 11266 MultiExprArg ExprArgs, 11267 bool HadMultipleCandidates, 11268 bool IsListInitialization, 11269 bool IsStdInitListInitialization, 11270 bool RequiresZeroInit, 11271 unsigned ConstructKind, 11272 SourceRange ParenRange) { 11273 bool Elidable = false; 11274 11275 // C++0x [class.copy]p34: 11276 // When certain criteria are met, an implementation is allowed to 11277 // omit the copy/move construction of a class object, even if the 11278 // copy/move constructor and/or destructor for the object have 11279 // side effects. [...] 11280 // - when a temporary class object that has not been bound to a 11281 // reference (12.2) would be copied/moved to a class object 11282 // with the same cv-unqualified type, the copy/move operation 11283 // can be omitted by constructing the temporary object 11284 // directly into the target of the omitted copy/move 11285 if (ConstructKind == CXXConstructExpr::CK_Complete && 11286 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11287 Expr *SubExpr = ExprArgs[0]; 11288 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11289 } 11290 11291 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11292 Elidable, ExprArgs, HadMultipleCandidates, 11293 IsListInitialization, 11294 IsStdInitListInitialization, RequiresZeroInit, 11295 ConstructKind, ParenRange); 11296 } 11297 11298 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11299 /// including handling of its default argument expressions. 11300 ExprResult 11301 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11302 CXXConstructorDecl *Constructor, bool Elidable, 11303 MultiExprArg ExprArgs, 11304 bool HadMultipleCandidates, 11305 bool IsListInitialization, 11306 bool IsStdInitListInitialization, 11307 bool RequiresZeroInit, 11308 unsigned ConstructKind, 11309 SourceRange ParenRange) { 11310 MarkFunctionReferenced(ConstructLoc, Constructor); 11311 return CXXConstructExpr::Create( 11312 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11313 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11314 RequiresZeroInit, 11315 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11316 ParenRange); 11317 } 11318 11319 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11320 assert(Field->hasInClassInitializer()); 11321 11322 // If we already have the in-class initializer nothing needs to be done. 11323 if (Field->getInClassInitializer()) 11324 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11325 11326 // Maybe we haven't instantiated the in-class initializer. Go check the 11327 // pattern FieldDecl to see if it has one. 11328 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11329 11330 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11331 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11332 DeclContext::lookup_result Lookup = 11333 ClassPattern->lookup(Field->getDeclName()); 11334 assert(Lookup.size() == 1); 11335 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11336 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11337 getTemplateInstantiationArgs(Field))) 11338 return ExprError(); 11339 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11340 } 11341 11342 // DR1351: 11343 // If the brace-or-equal-initializer of a non-static data member 11344 // invokes a defaulted default constructor of its class or of an 11345 // enclosing class in a potentially evaluated subexpression, the 11346 // program is ill-formed. 11347 // 11348 // This resolution is unworkable: the exception specification of the 11349 // default constructor can be needed in an unevaluated context, in 11350 // particular, in the operand of a noexcept-expression, and we can be 11351 // unable to compute an exception specification for an enclosed class. 11352 // 11353 // Any attempt to resolve the exception specification of a defaulted default 11354 // constructor before the initializer is lexically complete will ultimately 11355 // come here at which point we can diagnose it. 11356 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11357 if (OutermostClass == ParentRD) { 11358 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11359 << ParentRD << Field; 11360 } else { 11361 Diag(Field->getLocEnd(), 11362 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11363 << ParentRD << OutermostClass << Field; 11364 } 11365 11366 return ExprError(); 11367 } 11368 11369 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11370 if (VD->isInvalidDecl()) return; 11371 11372 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11373 if (ClassDecl->isInvalidDecl()) return; 11374 if (ClassDecl->hasIrrelevantDestructor()) return; 11375 if (ClassDecl->isDependentContext()) return; 11376 11377 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11378 MarkFunctionReferenced(VD->getLocation(), Destructor); 11379 CheckDestructorAccess(VD->getLocation(), Destructor, 11380 PDiag(diag::err_access_dtor_var) 11381 << VD->getDeclName() 11382 << VD->getType()); 11383 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11384 11385 if (Destructor->isTrivial()) return; 11386 if (!VD->hasGlobalStorage()) return; 11387 11388 // Emit warning for non-trivial dtor in global scope (a real global, 11389 // class-static, function-static). 11390 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11391 11392 // TODO: this should be re-enabled for static locals by !CXAAtExit 11393 if (!VD->isStaticLocal()) 11394 Diag(VD->getLocation(), diag::warn_global_destructor); 11395 } 11396 11397 /// \brief Given a constructor and the set of arguments provided for the 11398 /// constructor, convert the arguments and add any required default arguments 11399 /// to form a proper call to this constructor. 11400 /// 11401 /// \returns true if an error occurred, false otherwise. 11402 bool 11403 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11404 MultiExprArg ArgsPtr, 11405 SourceLocation Loc, 11406 SmallVectorImpl<Expr*> &ConvertedArgs, 11407 bool AllowExplicit, 11408 bool IsListInitialization) { 11409 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11410 unsigned NumArgs = ArgsPtr.size(); 11411 Expr **Args = ArgsPtr.data(); 11412 11413 const FunctionProtoType *Proto 11414 = Constructor->getType()->getAs<FunctionProtoType>(); 11415 assert(Proto && "Constructor without a prototype?"); 11416 unsigned NumParams = Proto->getNumParams(); 11417 11418 // If too few arguments are available, we'll fill in the rest with defaults. 11419 if (NumArgs < NumParams) 11420 ConvertedArgs.reserve(NumParams); 11421 else 11422 ConvertedArgs.reserve(NumArgs); 11423 11424 VariadicCallType CallType = 11425 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11426 SmallVector<Expr *, 8> AllArgs; 11427 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11428 Proto, 0, 11429 llvm::makeArrayRef(Args, NumArgs), 11430 AllArgs, 11431 CallType, AllowExplicit, 11432 IsListInitialization); 11433 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11434 11435 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11436 11437 CheckConstructorCall(Constructor, 11438 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11439 Proto, Loc); 11440 11441 return Invalid; 11442 } 11443 11444 static inline bool 11445 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11446 const FunctionDecl *FnDecl) { 11447 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11448 if (isa<NamespaceDecl>(DC)) { 11449 return SemaRef.Diag(FnDecl->getLocation(), 11450 diag::err_operator_new_delete_declared_in_namespace) 11451 << FnDecl->getDeclName(); 11452 } 11453 11454 if (isa<TranslationUnitDecl>(DC) && 11455 FnDecl->getStorageClass() == SC_Static) { 11456 return SemaRef.Diag(FnDecl->getLocation(), 11457 diag::err_operator_new_delete_declared_static) 11458 << FnDecl->getDeclName(); 11459 } 11460 11461 return false; 11462 } 11463 11464 static inline bool 11465 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11466 CanQualType ExpectedResultType, 11467 CanQualType ExpectedFirstParamType, 11468 unsigned DependentParamTypeDiag, 11469 unsigned InvalidParamTypeDiag) { 11470 QualType ResultType = 11471 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11472 11473 // Check that the result type is not dependent. 11474 if (ResultType->isDependentType()) 11475 return SemaRef.Diag(FnDecl->getLocation(), 11476 diag::err_operator_new_delete_dependent_result_type) 11477 << FnDecl->getDeclName() << ExpectedResultType; 11478 11479 // Check that the result type is what we expect. 11480 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11481 return SemaRef.Diag(FnDecl->getLocation(), 11482 diag::err_operator_new_delete_invalid_result_type) 11483 << FnDecl->getDeclName() << ExpectedResultType; 11484 11485 // A function template must have at least 2 parameters. 11486 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11487 return SemaRef.Diag(FnDecl->getLocation(), 11488 diag::err_operator_new_delete_template_too_few_parameters) 11489 << FnDecl->getDeclName(); 11490 11491 // The function decl must have at least 1 parameter. 11492 if (FnDecl->getNumParams() == 0) 11493 return SemaRef.Diag(FnDecl->getLocation(), 11494 diag::err_operator_new_delete_too_few_parameters) 11495 << FnDecl->getDeclName(); 11496 11497 // Check the first parameter type is not dependent. 11498 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11499 if (FirstParamType->isDependentType()) 11500 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11501 << FnDecl->getDeclName() << ExpectedFirstParamType; 11502 11503 // Check that the first parameter type is what we expect. 11504 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11505 ExpectedFirstParamType) 11506 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11507 << FnDecl->getDeclName() << ExpectedFirstParamType; 11508 11509 return false; 11510 } 11511 11512 static bool 11513 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11514 // C++ [basic.stc.dynamic.allocation]p1: 11515 // A program is ill-formed if an allocation function is declared in a 11516 // namespace scope other than global scope or declared static in global 11517 // scope. 11518 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11519 return true; 11520 11521 CanQualType SizeTy = 11522 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11523 11524 // C++ [basic.stc.dynamic.allocation]p1: 11525 // The return type shall be void*. The first parameter shall have type 11526 // std::size_t. 11527 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11528 SizeTy, 11529 diag::err_operator_new_dependent_param_type, 11530 diag::err_operator_new_param_type)) 11531 return true; 11532 11533 // C++ [basic.stc.dynamic.allocation]p1: 11534 // The first parameter shall not have an associated default argument. 11535 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11536 return SemaRef.Diag(FnDecl->getLocation(), 11537 diag::err_operator_new_default_arg) 11538 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11539 11540 return false; 11541 } 11542 11543 static bool 11544 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11545 // C++ [basic.stc.dynamic.deallocation]p1: 11546 // A program is ill-formed if deallocation functions are declared in a 11547 // namespace scope other than global scope or declared static in global 11548 // scope. 11549 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11550 return true; 11551 11552 // C++ [basic.stc.dynamic.deallocation]p2: 11553 // Each deallocation function shall return void and its first parameter 11554 // shall be void*. 11555 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11556 SemaRef.Context.VoidPtrTy, 11557 diag::err_operator_delete_dependent_param_type, 11558 diag::err_operator_delete_param_type)) 11559 return true; 11560 11561 return false; 11562 } 11563 11564 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11565 /// of this overloaded operator is well-formed. If so, returns false; 11566 /// otherwise, emits appropriate diagnostics and returns true. 11567 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11568 assert(FnDecl && FnDecl->isOverloadedOperator() && 11569 "Expected an overloaded operator declaration"); 11570 11571 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11572 11573 // C++ [over.oper]p5: 11574 // The allocation and deallocation functions, operator new, 11575 // operator new[], operator delete and operator delete[], are 11576 // described completely in 3.7.3. The attributes and restrictions 11577 // found in the rest of this subclause do not apply to them unless 11578 // explicitly stated in 3.7.3. 11579 if (Op == OO_Delete || Op == OO_Array_Delete) 11580 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11581 11582 if (Op == OO_New || Op == OO_Array_New) 11583 return CheckOperatorNewDeclaration(*this, FnDecl); 11584 11585 // C++ [over.oper]p6: 11586 // An operator function shall either be a non-static member 11587 // function or be a non-member function and have at least one 11588 // parameter whose type is a class, a reference to a class, an 11589 // enumeration, or a reference to an enumeration. 11590 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11591 if (MethodDecl->isStatic()) 11592 return Diag(FnDecl->getLocation(), 11593 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11594 } else { 11595 bool ClassOrEnumParam = false; 11596 for (auto Param : FnDecl->params()) { 11597 QualType ParamType = Param->getType().getNonReferenceType(); 11598 if (ParamType->isDependentType() || ParamType->isRecordType() || 11599 ParamType->isEnumeralType()) { 11600 ClassOrEnumParam = true; 11601 break; 11602 } 11603 } 11604 11605 if (!ClassOrEnumParam) 11606 return Diag(FnDecl->getLocation(), 11607 diag::err_operator_overload_needs_class_or_enum) 11608 << FnDecl->getDeclName(); 11609 } 11610 11611 // C++ [over.oper]p8: 11612 // An operator function cannot have default arguments (8.3.6), 11613 // except where explicitly stated below. 11614 // 11615 // Only the function-call operator allows default arguments 11616 // (C++ [over.call]p1). 11617 if (Op != OO_Call) { 11618 for (auto Param : FnDecl->params()) { 11619 if (Param->hasDefaultArg()) 11620 return Diag(Param->getLocation(), 11621 diag::err_operator_overload_default_arg) 11622 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11623 } 11624 } 11625 11626 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11627 { false, false, false } 11628 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11629 , { Unary, Binary, MemberOnly } 11630 #include "clang/Basic/OperatorKinds.def" 11631 }; 11632 11633 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11634 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11635 bool MustBeMemberOperator = OperatorUses[Op][2]; 11636 11637 // C++ [over.oper]p8: 11638 // [...] Operator functions cannot have more or fewer parameters 11639 // than the number required for the corresponding operator, as 11640 // described in the rest of this subclause. 11641 unsigned NumParams = FnDecl->getNumParams() 11642 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11643 if (Op != OO_Call && 11644 ((NumParams == 1 && !CanBeUnaryOperator) || 11645 (NumParams == 2 && !CanBeBinaryOperator) || 11646 (NumParams < 1) || (NumParams > 2))) { 11647 // We have the wrong number of parameters. 11648 unsigned ErrorKind; 11649 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11650 ErrorKind = 2; // 2 -> unary or binary. 11651 } else if (CanBeUnaryOperator) { 11652 ErrorKind = 0; // 0 -> unary 11653 } else { 11654 assert(CanBeBinaryOperator && 11655 "All non-call overloaded operators are unary or binary!"); 11656 ErrorKind = 1; // 1 -> binary 11657 } 11658 11659 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11660 << FnDecl->getDeclName() << NumParams << ErrorKind; 11661 } 11662 11663 // Overloaded operators other than operator() cannot be variadic. 11664 if (Op != OO_Call && 11665 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11666 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11667 << FnDecl->getDeclName(); 11668 } 11669 11670 // Some operators must be non-static member functions. 11671 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11672 return Diag(FnDecl->getLocation(), 11673 diag::err_operator_overload_must_be_member) 11674 << FnDecl->getDeclName(); 11675 } 11676 11677 // C++ [over.inc]p1: 11678 // The user-defined function called operator++ implements the 11679 // prefix and postfix ++ operator. If this function is a member 11680 // function with no parameters, or a non-member function with one 11681 // parameter of class or enumeration type, it defines the prefix 11682 // increment operator ++ for objects of that type. If the function 11683 // is a member function with one parameter (which shall be of type 11684 // int) or a non-member function with two parameters (the second 11685 // of which shall be of type int), it defines the postfix 11686 // increment operator ++ for objects of that type. 11687 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11688 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11689 QualType ParamType = LastParam->getType(); 11690 11691 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11692 !ParamType->isDependentType()) 11693 return Diag(LastParam->getLocation(), 11694 diag::err_operator_overload_post_incdec_must_be_int) 11695 << LastParam->getType() << (Op == OO_MinusMinus); 11696 } 11697 11698 return false; 11699 } 11700 11701 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11702 /// of this literal operator function is well-formed. If so, returns 11703 /// false; otherwise, emits appropriate diagnostics and returns true. 11704 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11705 if (isa<CXXMethodDecl>(FnDecl)) { 11706 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11707 << FnDecl->getDeclName(); 11708 return true; 11709 } 11710 11711 if (FnDecl->isExternC()) { 11712 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11713 return true; 11714 } 11715 11716 bool Valid = false; 11717 11718 // This might be the definition of a literal operator template. 11719 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11720 // This might be a specialization of a literal operator template. 11721 if (!TpDecl) 11722 TpDecl = FnDecl->getPrimaryTemplate(); 11723 11724 // template <char...> type operator "" name() and 11725 // template <class T, T...> type operator "" name() are the only valid 11726 // template signatures, and the only valid signatures with no parameters. 11727 if (TpDecl) { 11728 if (FnDecl->param_size() == 0) { 11729 // Must have one or two template parameters 11730 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11731 if (Params->size() == 1) { 11732 NonTypeTemplateParmDecl *PmDecl = 11733 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11734 11735 // The template parameter must be a char parameter pack. 11736 if (PmDecl && PmDecl->isTemplateParameterPack() && 11737 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11738 Valid = true; 11739 } else if (Params->size() == 2) { 11740 TemplateTypeParmDecl *PmType = 11741 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11742 NonTypeTemplateParmDecl *PmArgs = 11743 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11744 11745 // The second template parameter must be a parameter pack with the 11746 // first template parameter as its type. 11747 if (PmType && PmArgs && 11748 !PmType->isTemplateParameterPack() && 11749 PmArgs->isTemplateParameterPack()) { 11750 const TemplateTypeParmType *TArgs = 11751 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11752 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11753 TArgs->getIndex() == PmType->getIndex()) { 11754 Valid = true; 11755 if (ActiveTemplateInstantiations.empty()) 11756 Diag(FnDecl->getLocation(), 11757 diag::ext_string_literal_operator_template); 11758 } 11759 } 11760 } 11761 } 11762 } else if (FnDecl->param_size()) { 11763 // Check the first parameter 11764 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11765 11766 QualType T = (*Param)->getType().getUnqualifiedType(); 11767 11768 // unsigned long long int, long double, and any character type are allowed 11769 // as the only parameters. 11770 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11771 Context.hasSameType(T, Context.LongDoubleTy) || 11772 Context.hasSameType(T, Context.CharTy) || 11773 Context.hasSameType(T, Context.WideCharTy) || 11774 Context.hasSameType(T, Context.Char16Ty) || 11775 Context.hasSameType(T, Context.Char32Ty)) { 11776 if (++Param == FnDecl->param_end()) 11777 Valid = true; 11778 goto FinishedParams; 11779 } 11780 11781 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11782 const PointerType *PT = T->getAs<PointerType>(); 11783 if (!PT) 11784 goto FinishedParams; 11785 T = PT->getPointeeType(); 11786 if (!T.isConstQualified() || T.isVolatileQualified()) 11787 goto FinishedParams; 11788 T = T.getUnqualifiedType(); 11789 11790 // Move on to the second parameter; 11791 ++Param; 11792 11793 // If there is no second parameter, the first must be a const char * 11794 if (Param == FnDecl->param_end()) { 11795 if (Context.hasSameType(T, Context.CharTy)) 11796 Valid = true; 11797 goto FinishedParams; 11798 } 11799 11800 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11801 // are allowed as the first parameter to a two-parameter function 11802 if (!(Context.hasSameType(T, Context.CharTy) || 11803 Context.hasSameType(T, Context.WideCharTy) || 11804 Context.hasSameType(T, Context.Char16Ty) || 11805 Context.hasSameType(T, Context.Char32Ty))) 11806 goto FinishedParams; 11807 11808 // The second and final parameter must be an std::size_t 11809 T = (*Param)->getType().getUnqualifiedType(); 11810 if (Context.hasSameType(T, Context.getSizeType()) && 11811 ++Param == FnDecl->param_end()) 11812 Valid = true; 11813 } 11814 11815 // FIXME: This diagnostic is absolutely terrible. 11816 FinishedParams: 11817 if (!Valid) { 11818 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11819 << FnDecl->getDeclName(); 11820 return true; 11821 } 11822 11823 // A parameter-declaration-clause containing a default argument is not 11824 // equivalent to any of the permitted forms. 11825 for (auto Param : FnDecl->params()) { 11826 if (Param->hasDefaultArg()) { 11827 Diag(Param->getDefaultArgRange().getBegin(), 11828 diag::err_literal_operator_default_argument) 11829 << Param->getDefaultArgRange(); 11830 break; 11831 } 11832 } 11833 11834 StringRef LiteralName 11835 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11836 if (LiteralName[0] != '_') { 11837 // C++11 [usrlit.suffix]p1: 11838 // Literal suffix identifiers that do not start with an underscore 11839 // are reserved for future standardization. 11840 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11841 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11842 } 11843 11844 return false; 11845 } 11846 11847 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11848 /// linkage specification, including the language and (if present) 11849 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11850 /// language string literal. LBraceLoc, if valid, provides the location of 11851 /// the '{' brace. Otherwise, this linkage specification does not 11852 /// have any braces. 11853 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11854 Expr *LangStr, 11855 SourceLocation LBraceLoc) { 11856 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11857 if (!Lit->isAscii()) { 11858 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11859 << LangStr->getSourceRange(); 11860 return nullptr; 11861 } 11862 11863 StringRef Lang = Lit->getString(); 11864 LinkageSpecDecl::LanguageIDs Language; 11865 if (Lang == "C") 11866 Language = LinkageSpecDecl::lang_c; 11867 else if (Lang == "C++") 11868 Language = LinkageSpecDecl::lang_cxx; 11869 else { 11870 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11871 << LangStr->getSourceRange(); 11872 return nullptr; 11873 } 11874 11875 // FIXME: Add all the various semantics of linkage specifications 11876 11877 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11878 LangStr->getExprLoc(), Language, 11879 LBraceLoc.isValid()); 11880 CurContext->addDecl(D); 11881 PushDeclContext(S, D); 11882 return D; 11883 } 11884 11885 /// ActOnFinishLinkageSpecification - Complete the definition of 11886 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11887 /// valid, it's the position of the closing '}' brace in a linkage 11888 /// specification that uses braces. 11889 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11890 Decl *LinkageSpec, 11891 SourceLocation RBraceLoc) { 11892 if (RBraceLoc.isValid()) { 11893 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11894 LSDecl->setRBraceLoc(RBraceLoc); 11895 } 11896 PopDeclContext(); 11897 return LinkageSpec; 11898 } 11899 11900 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11901 AttributeList *AttrList, 11902 SourceLocation SemiLoc) { 11903 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11904 // Attribute declarations appertain to empty declaration so we handle 11905 // them here. 11906 if (AttrList) 11907 ProcessDeclAttributeList(S, ED, AttrList); 11908 11909 CurContext->addDecl(ED); 11910 return ED; 11911 } 11912 11913 /// \brief Perform semantic analysis for the variable declaration that 11914 /// occurs within a C++ catch clause, returning the newly-created 11915 /// variable. 11916 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11917 TypeSourceInfo *TInfo, 11918 SourceLocation StartLoc, 11919 SourceLocation Loc, 11920 IdentifierInfo *Name) { 11921 bool Invalid = false; 11922 QualType ExDeclType = TInfo->getType(); 11923 11924 // Arrays and functions decay. 11925 if (ExDeclType->isArrayType()) 11926 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11927 else if (ExDeclType->isFunctionType()) 11928 ExDeclType = Context.getPointerType(ExDeclType); 11929 11930 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11931 // The exception-declaration shall not denote a pointer or reference to an 11932 // incomplete type, other than [cv] void*. 11933 // N2844 forbids rvalue references. 11934 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11935 Diag(Loc, diag::err_catch_rvalue_ref); 11936 Invalid = true; 11937 } 11938 11939 QualType BaseType = ExDeclType; 11940 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11941 unsigned DK = diag::err_catch_incomplete; 11942 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11943 BaseType = Ptr->getPointeeType(); 11944 Mode = 1; 11945 DK = diag::err_catch_incomplete_ptr; 11946 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11947 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11948 BaseType = Ref->getPointeeType(); 11949 Mode = 2; 11950 DK = diag::err_catch_incomplete_ref; 11951 } 11952 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11953 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11954 Invalid = true; 11955 11956 if (!Invalid && !ExDeclType->isDependentType() && 11957 RequireNonAbstractType(Loc, ExDeclType, 11958 diag::err_abstract_type_in_decl, 11959 AbstractVariableType)) 11960 Invalid = true; 11961 11962 // Only the non-fragile NeXT runtime currently supports C++ catches 11963 // of ObjC types, and no runtime supports catching ObjC types by value. 11964 if (!Invalid && getLangOpts().ObjC1) { 11965 QualType T = ExDeclType; 11966 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11967 T = RT->getPointeeType(); 11968 11969 if (T->isObjCObjectType()) { 11970 Diag(Loc, diag::err_objc_object_catch); 11971 Invalid = true; 11972 } else if (T->isObjCObjectPointerType()) { 11973 // FIXME: should this be a test for macosx-fragile specifically? 11974 if (getLangOpts().ObjCRuntime.isFragile()) 11975 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11976 } 11977 } 11978 11979 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11980 ExDeclType, TInfo, SC_None); 11981 ExDecl->setExceptionVariable(true); 11982 11983 // In ARC, infer 'retaining' for variables of retainable type. 11984 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11985 Invalid = true; 11986 11987 if (!Invalid && !ExDeclType->isDependentType()) { 11988 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11989 // Insulate this from anything else we might currently be parsing. 11990 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11991 11992 // C++ [except.handle]p16: 11993 // The object declared in an exception-declaration or, if the 11994 // exception-declaration does not specify a name, a temporary (12.2) is 11995 // copy-initialized (8.5) from the exception object. [...] 11996 // The object is destroyed when the handler exits, after the destruction 11997 // of any automatic objects initialized within the handler. 11998 // 11999 // We just pretend to initialize the object with itself, then make sure 12000 // it can be destroyed later. 12001 QualType initType = Context.getExceptionObjectType(ExDeclType); 12002 12003 InitializedEntity entity = 12004 InitializedEntity::InitializeVariable(ExDecl); 12005 InitializationKind initKind = 12006 InitializationKind::CreateCopy(Loc, SourceLocation()); 12007 12008 Expr *opaqueValue = 12009 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 12010 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 12011 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 12012 if (result.isInvalid()) 12013 Invalid = true; 12014 else { 12015 // If the constructor used was non-trivial, set this as the 12016 // "initializer". 12017 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 12018 if (!construct->getConstructor()->isTrivial()) { 12019 Expr *init = MaybeCreateExprWithCleanups(construct); 12020 ExDecl->setInit(init); 12021 } 12022 12023 // And make sure it's destructable. 12024 FinalizeVarWithDestructor(ExDecl, recordType); 12025 } 12026 } 12027 } 12028 12029 if (Invalid) 12030 ExDecl->setInvalidDecl(); 12031 12032 return ExDecl; 12033 } 12034 12035 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 12036 /// handler. 12037 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 12038 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12039 bool Invalid = D.isInvalidType(); 12040 12041 // Check for unexpanded parameter packs. 12042 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12043 UPPC_ExceptionType)) { 12044 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12045 D.getIdentifierLoc()); 12046 Invalid = true; 12047 } 12048 12049 IdentifierInfo *II = D.getIdentifier(); 12050 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 12051 LookupOrdinaryName, 12052 ForRedeclaration)) { 12053 // The scope should be freshly made just for us. There is just no way 12054 // it contains any previous declaration, except for function parameters in 12055 // a function-try-block's catch statement. 12056 assert(!S->isDeclScope(PrevDecl)); 12057 if (isDeclInScope(PrevDecl, CurContext, S)) { 12058 Diag(D.getIdentifierLoc(), diag::err_redefinition) 12059 << D.getIdentifier(); 12060 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12061 Invalid = true; 12062 } else if (PrevDecl->isTemplateParameter()) 12063 // Maybe we will complain about the shadowed template parameter. 12064 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12065 } 12066 12067 if (D.getCXXScopeSpec().isSet() && !Invalid) { 12068 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 12069 << D.getCXXScopeSpec().getRange(); 12070 Invalid = true; 12071 } 12072 12073 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 12074 D.getLocStart(), 12075 D.getIdentifierLoc(), 12076 D.getIdentifier()); 12077 if (Invalid) 12078 ExDecl->setInvalidDecl(); 12079 12080 // Add the exception declaration into this scope. 12081 if (II) 12082 PushOnScopeChains(ExDecl, S); 12083 else 12084 CurContext->addDecl(ExDecl); 12085 12086 ProcessDeclAttributes(S, ExDecl, D); 12087 return ExDecl; 12088 } 12089 12090 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12091 Expr *AssertExpr, 12092 Expr *AssertMessageExpr, 12093 SourceLocation RParenLoc) { 12094 StringLiteral *AssertMessage = 12095 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 12096 12097 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 12098 return nullptr; 12099 12100 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 12101 AssertMessage, RParenLoc, false); 12102 } 12103 12104 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12105 Expr *AssertExpr, 12106 StringLiteral *AssertMessage, 12107 SourceLocation RParenLoc, 12108 bool Failed) { 12109 assert(AssertExpr != nullptr && "Expected non-null condition"); 12110 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 12111 !Failed) { 12112 // In a static_assert-declaration, the constant-expression shall be a 12113 // constant expression that can be contextually converted to bool. 12114 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 12115 if (Converted.isInvalid()) 12116 Failed = true; 12117 12118 llvm::APSInt Cond; 12119 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 12120 diag::err_static_assert_expression_is_not_constant, 12121 /*AllowFold=*/false).isInvalid()) 12122 Failed = true; 12123 12124 if (!Failed && !Cond) { 12125 SmallString<256> MsgBuffer; 12126 llvm::raw_svector_ostream Msg(MsgBuffer); 12127 if (AssertMessage) 12128 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 12129 Diag(StaticAssertLoc, diag::err_static_assert_failed) 12130 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 12131 Failed = true; 12132 } 12133 } 12134 12135 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 12136 AssertExpr, AssertMessage, RParenLoc, 12137 Failed); 12138 12139 CurContext->addDecl(Decl); 12140 return Decl; 12141 } 12142 12143 /// \brief Perform semantic analysis of the given friend type declaration. 12144 /// 12145 /// \returns A friend declaration that. 12146 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 12147 SourceLocation FriendLoc, 12148 TypeSourceInfo *TSInfo) { 12149 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 12150 12151 QualType T = TSInfo->getType(); 12152 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 12153 12154 // C++03 [class.friend]p2: 12155 // An elaborated-type-specifier shall be used in a friend declaration 12156 // for a class.* 12157 // 12158 // * The class-key of the elaborated-type-specifier is required. 12159 if (!ActiveTemplateInstantiations.empty()) { 12160 // Do not complain about the form of friend template types during 12161 // template instantiation; we will already have complained when the 12162 // template was declared. 12163 } else { 12164 if (!T->isElaboratedTypeSpecifier()) { 12165 // If we evaluated the type to a record type, suggest putting 12166 // a tag in front. 12167 if (const RecordType *RT = T->getAs<RecordType>()) { 12168 RecordDecl *RD = RT->getDecl(); 12169 12170 SmallString<16> InsertionText(" "); 12171 InsertionText += RD->getKindName(); 12172 12173 Diag(TypeRange.getBegin(), 12174 getLangOpts().CPlusPlus11 ? 12175 diag::warn_cxx98_compat_unelaborated_friend_type : 12176 diag::ext_unelaborated_friend_type) 12177 << (unsigned) RD->getTagKind() 12178 << T 12179 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 12180 InsertionText); 12181 } else { 12182 Diag(FriendLoc, 12183 getLangOpts().CPlusPlus11 ? 12184 diag::warn_cxx98_compat_nonclass_type_friend : 12185 diag::ext_nonclass_type_friend) 12186 << T 12187 << TypeRange; 12188 } 12189 } else if (T->getAs<EnumType>()) { 12190 Diag(FriendLoc, 12191 getLangOpts().CPlusPlus11 ? 12192 diag::warn_cxx98_compat_enum_friend : 12193 diag::ext_enum_friend) 12194 << T 12195 << TypeRange; 12196 } 12197 12198 // C++11 [class.friend]p3: 12199 // A friend declaration that does not declare a function shall have one 12200 // of the following forms: 12201 // friend elaborated-type-specifier ; 12202 // friend simple-type-specifier ; 12203 // friend typename-specifier ; 12204 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12205 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12206 } 12207 12208 // If the type specifier in a friend declaration designates a (possibly 12209 // cv-qualified) class type, that class is declared as a friend; otherwise, 12210 // the friend declaration is ignored. 12211 return FriendDecl::Create(Context, CurContext, 12212 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12213 FriendLoc); 12214 } 12215 12216 /// Handle a friend tag declaration where the scope specifier was 12217 /// templated. 12218 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12219 unsigned TagSpec, SourceLocation TagLoc, 12220 CXXScopeSpec &SS, 12221 IdentifierInfo *Name, 12222 SourceLocation NameLoc, 12223 AttributeList *Attr, 12224 MultiTemplateParamsArg TempParamLists) { 12225 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12226 12227 bool isExplicitSpecialization = false; 12228 bool Invalid = false; 12229 12230 if (TemplateParameterList *TemplateParams = 12231 MatchTemplateParametersToScopeSpecifier( 12232 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12233 isExplicitSpecialization, Invalid)) { 12234 if (TemplateParams->size() > 0) { 12235 // This is a declaration of a class template. 12236 if (Invalid) 12237 return nullptr; 12238 12239 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12240 NameLoc, Attr, TemplateParams, AS_public, 12241 /*ModulePrivateLoc=*/SourceLocation(), 12242 FriendLoc, TempParamLists.size() - 1, 12243 TempParamLists.data()).get(); 12244 } else { 12245 // The "template<>" header is extraneous. 12246 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12247 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12248 isExplicitSpecialization = true; 12249 } 12250 } 12251 12252 if (Invalid) return nullptr; 12253 12254 bool isAllExplicitSpecializations = true; 12255 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12256 if (TempParamLists[I]->size()) { 12257 isAllExplicitSpecializations = false; 12258 break; 12259 } 12260 } 12261 12262 // FIXME: don't ignore attributes. 12263 12264 // If it's explicit specializations all the way down, just forget 12265 // about the template header and build an appropriate non-templated 12266 // friend. TODO: for source fidelity, remember the headers. 12267 if (isAllExplicitSpecializations) { 12268 if (SS.isEmpty()) { 12269 bool Owned = false; 12270 bool IsDependent = false; 12271 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12272 Attr, AS_public, 12273 /*ModulePrivateLoc=*/SourceLocation(), 12274 MultiTemplateParamsArg(), Owned, IsDependent, 12275 /*ScopedEnumKWLoc=*/SourceLocation(), 12276 /*ScopedEnumUsesClassTag=*/false, 12277 /*UnderlyingType=*/TypeResult(), 12278 /*IsTypeSpecifier=*/false); 12279 } 12280 12281 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12282 ElaboratedTypeKeyword Keyword 12283 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12284 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12285 *Name, NameLoc); 12286 if (T.isNull()) 12287 return nullptr; 12288 12289 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12290 if (isa<DependentNameType>(T)) { 12291 DependentNameTypeLoc TL = 12292 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12293 TL.setElaboratedKeywordLoc(TagLoc); 12294 TL.setQualifierLoc(QualifierLoc); 12295 TL.setNameLoc(NameLoc); 12296 } else { 12297 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12298 TL.setElaboratedKeywordLoc(TagLoc); 12299 TL.setQualifierLoc(QualifierLoc); 12300 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12301 } 12302 12303 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12304 TSI, FriendLoc, TempParamLists); 12305 Friend->setAccess(AS_public); 12306 CurContext->addDecl(Friend); 12307 return Friend; 12308 } 12309 12310 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12311 12312 12313 12314 // Handle the case of a templated-scope friend class. e.g. 12315 // template <class T> class A<T>::B; 12316 // FIXME: we don't support these right now. 12317 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12318 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12319 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12320 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12321 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12322 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12323 TL.setElaboratedKeywordLoc(TagLoc); 12324 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12325 TL.setNameLoc(NameLoc); 12326 12327 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12328 TSI, FriendLoc, TempParamLists); 12329 Friend->setAccess(AS_public); 12330 Friend->setUnsupportedFriend(true); 12331 CurContext->addDecl(Friend); 12332 return Friend; 12333 } 12334 12335 12336 /// Handle a friend type declaration. This works in tandem with 12337 /// ActOnTag. 12338 /// 12339 /// Notes on friend class templates: 12340 /// 12341 /// We generally treat friend class declarations as if they were 12342 /// declaring a class. So, for example, the elaborated type specifier 12343 /// in a friend declaration is required to obey the restrictions of a 12344 /// class-head (i.e. no typedefs in the scope chain), template 12345 /// parameters are required to match up with simple template-ids, &c. 12346 /// However, unlike when declaring a template specialization, it's 12347 /// okay to refer to a template specialization without an empty 12348 /// template parameter declaration, e.g. 12349 /// friend class A<T>::B<unsigned>; 12350 /// We permit this as a special case; if there are any template 12351 /// parameters present at all, require proper matching, i.e. 12352 /// template <> template \<class T> friend class A<int>::B; 12353 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12354 MultiTemplateParamsArg TempParams) { 12355 SourceLocation Loc = DS.getLocStart(); 12356 12357 assert(DS.isFriendSpecified()); 12358 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12359 12360 // Try to convert the decl specifier to a type. This works for 12361 // friend templates because ActOnTag never produces a ClassTemplateDecl 12362 // for a TUK_Friend. 12363 Declarator TheDeclarator(DS, Declarator::MemberContext); 12364 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12365 QualType T = TSI->getType(); 12366 if (TheDeclarator.isInvalidType()) 12367 return nullptr; 12368 12369 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12370 return nullptr; 12371 12372 // This is definitely an error in C++98. It's probably meant to 12373 // be forbidden in C++0x, too, but the specification is just 12374 // poorly written. 12375 // 12376 // The problem is with declarations like the following: 12377 // template <T> friend A<T>::foo; 12378 // where deciding whether a class C is a friend or not now hinges 12379 // on whether there exists an instantiation of A that causes 12380 // 'foo' to equal C. There are restrictions on class-heads 12381 // (which we declare (by fiat) elaborated friend declarations to 12382 // be) that makes this tractable. 12383 // 12384 // FIXME: handle "template <> friend class A<T>;", which 12385 // is possibly well-formed? Who even knows? 12386 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12387 Diag(Loc, diag::err_tagless_friend_type_template) 12388 << DS.getSourceRange(); 12389 return nullptr; 12390 } 12391 12392 // C++98 [class.friend]p1: A friend of a class is a function 12393 // or class that is not a member of the class . . . 12394 // This is fixed in DR77, which just barely didn't make the C++03 12395 // deadline. It's also a very silly restriction that seriously 12396 // affects inner classes and which nobody else seems to implement; 12397 // thus we never diagnose it, not even in -pedantic. 12398 // 12399 // But note that we could warn about it: it's always useless to 12400 // friend one of your own members (it's not, however, worthless to 12401 // friend a member of an arbitrary specialization of your template). 12402 12403 Decl *D; 12404 if (unsigned NumTempParamLists = TempParams.size()) 12405 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12406 NumTempParamLists, 12407 TempParams.data(), 12408 TSI, 12409 DS.getFriendSpecLoc()); 12410 else 12411 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12412 12413 if (!D) 12414 return nullptr; 12415 12416 D->setAccess(AS_public); 12417 CurContext->addDecl(D); 12418 12419 return D; 12420 } 12421 12422 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12423 MultiTemplateParamsArg TemplateParams) { 12424 const DeclSpec &DS = D.getDeclSpec(); 12425 12426 assert(DS.isFriendSpecified()); 12427 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12428 12429 SourceLocation Loc = D.getIdentifierLoc(); 12430 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12431 12432 // C++ [class.friend]p1 12433 // A friend of a class is a function or class.... 12434 // Note that this sees through typedefs, which is intended. 12435 // It *doesn't* see through dependent types, which is correct 12436 // according to [temp.arg.type]p3: 12437 // If a declaration acquires a function type through a 12438 // type dependent on a template-parameter and this causes 12439 // a declaration that does not use the syntactic form of a 12440 // function declarator to have a function type, the program 12441 // is ill-formed. 12442 if (!TInfo->getType()->isFunctionType()) { 12443 Diag(Loc, diag::err_unexpected_friend); 12444 12445 // It might be worthwhile to try to recover by creating an 12446 // appropriate declaration. 12447 return nullptr; 12448 } 12449 12450 // C++ [namespace.memdef]p3 12451 // - If a friend declaration in a non-local class first declares a 12452 // class or function, the friend class or function is a member 12453 // of the innermost enclosing namespace. 12454 // - The name of the friend is not found by simple name lookup 12455 // until a matching declaration is provided in that namespace 12456 // scope (either before or after the class declaration granting 12457 // friendship). 12458 // - If a friend function is called, its name may be found by the 12459 // name lookup that considers functions from namespaces and 12460 // classes associated with the types of the function arguments. 12461 // - When looking for a prior declaration of a class or a function 12462 // declared as a friend, scopes outside the innermost enclosing 12463 // namespace scope are not considered. 12464 12465 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12466 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12467 DeclarationName Name = NameInfo.getName(); 12468 assert(Name); 12469 12470 // Check for unexpanded parameter packs. 12471 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12472 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12473 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12474 return nullptr; 12475 12476 // The context we found the declaration in, or in which we should 12477 // create the declaration. 12478 DeclContext *DC; 12479 Scope *DCScope = S; 12480 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12481 ForRedeclaration); 12482 12483 // There are five cases here. 12484 // - There's no scope specifier and we're in a local class. Only look 12485 // for functions declared in the immediately-enclosing block scope. 12486 // We recover from invalid scope qualifiers as if they just weren't there. 12487 FunctionDecl *FunctionContainingLocalClass = nullptr; 12488 if ((SS.isInvalid() || !SS.isSet()) && 12489 (FunctionContainingLocalClass = 12490 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12491 // C++11 [class.friend]p11: 12492 // If a friend declaration appears in a local class and the name 12493 // specified is an unqualified name, a prior declaration is 12494 // looked up without considering scopes that are outside the 12495 // innermost enclosing non-class scope. For a friend function 12496 // declaration, if there is no prior declaration, the program is 12497 // ill-formed. 12498 12499 // Find the innermost enclosing non-class scope. This is the block 12500 // scope containing the local class definition (or for a nested class, 12501 // the outer local class). 12502 DCScope = S->getFnParent(); 12503 12504 // Look up the function name in the scope. 12505 Previous.clear(LookupLocalFriendName); 12506 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12507 12508 if (!Previous.empty()) { 12509 // All possible previous declarations must have the same context: 12510 // either they were declared at block scope or they are members of 12511 // one of the enclosing local classes. 12512 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12513 } else { 12514 // This is ill-formed, but provide the context that we would have 12515 // declared the function in, if we were permitted to, for error recovery. 12516 DC = FunctionContainingLocalClass; 12517 } 12518 adjustContextForLocalExternDecl(DC); 12519 12520 // C++ [class.friend]p6: 12521 // A function can be defined in a friend declaration of a class if and 12522 // only if the class is a non-local class (9.8), the function name is 12523 // unqualified, and the function has namespace scope. 12524 if (D.isFunctionDefinition()) { 12525 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12526 } 12527 12528 // - There's no scope specifier, in which case we just go to the 12529 // appropriate scope and look for a function or function template 12530 // there as appropriate. 12531 } else if (SS.isInvalid() || !SS.isSet()) { 12532 // C++11 [namespace.memdef]p3: 12533 // If the name in a friend declaration is neither qualified nor 12534 // a template-id and the declaration is a function or an 12535 // elaborated-type-specifier, the lookup to determine whether 12536 // the entity has been previously declared shall not consider 12537 // any scopes outside the innermost enclosing namespace. 12538 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12539 12540 // Find the appropriate context according to the above. 12541 DC = CurContext; 12542 12543 // Skip class contexts. If someone can cite chapter and verse 12544 // for this behavior, that would be nice --- it's what GCC and 12545 // EDG do, and it seems like a reasonable intent, but the spec 12546 // really only says that checks for unqualified existing 12547 // declarations should stop at the nearest enclosing namespace, 12548 // not that they should only consider the nearest enclosing 12549 // namespace. 12550 while (DC->isRecord()) 12551 DC = DC->getParent(); 12552 12553 DeclContext *LookupDC = DC; 12554 while (LookupDC->isTransparentContext()) 12555 LookupDC = LookupDC->getParent(); 12556 12557 while (true) { 12558 LookupQualifiedName(Previous, LookupDC); 12559 12560 if (!Previous.empty()) { 12561 DC = LookupDC; 12562 break; 12563 } 12564 12565 if (isTemplateId) { 12566 if (isa<TranslationUnitDecl>(LookupDC)) break; 12567 } else { 12568 if (LookupDC->isFileContext()) break; 12569 } 12570 LookupDC = LookupDC->getParent(); 12571 } 12572 12573 DCScope = getScopeForDeclContext(S, DC); 12574 12575 // - There's a non-dependent scope specifier, in which case we 12576 // compute it and do a previous lookup there for a function 12577 // or function template. 12578 } else if (!SS.getScopeRep()->isDependent()) { 12579 DC = computeDeclContext(SS); 12580 if (!DC) return nullptr; 12581 12582 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12583 12584 LookupQualifiedName(Previous, DC); 12585 12586 // Ignore things found implicitly in the wrong scope. 12587 // TODO: better diagnostics for this case. Suggesting the right 12588 // qualified scope would be nice... 12589 LookupResult::Filter F = Previous.makeFilter(); 12590 while (F.hasNext()) { 12591 NamedDecl *D = F.next(); 12592 if (!DC->InEnclosingNamespaceSetOf( 12593 D->getDeclContext()->getRedeclContext())) 12594 F.erase(); 12595 } 12596 F.done(); 12597 12598 if (Previous.empty()) { 12599 D.setInvalidType(); 12600 Diag(Loc, diag::err_qualified_friend_not_found) 12601 << Name << TInfo->getType(); 12602 return nullptr; 12603 } 12604 12605 // C++ [class.friend]p1: A friend of a class is a function or 12606 // class that is not a member of the class . . . 12607 if (DC->Equals(CurContext)) 12608 Diag(DS.getFriendSpecLoc(), 12609 getLangOpts().CPlusPlus11 ? 12610 diag::warn_cxx98_compat_friend_is_member : 12611 diag::err_friend_is_member); 12612 12613 if (D.isFunctionDefinition()) { 12614 // C++ [class.friend]p6: 12615 // A function can be defined in a friend declaration of a class if and 12616 // only if the class is a non-local class (9.8), the function name is 12617 // unqualified, and the function has namespace scope. 12618 SemaDiagnosticBuilder DB 12619 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12620 12621 DB << SS.getScopeRep(); 12622 if (DC->isFileContext()) 12623 DB << FixItHint::CreateRemoval(SS.getRange()); 12624 SS.clear(); 12625 } 12626 12627 // - There's a scope specifier that does not match any template 12628 // parameter lists, in which case we use some arbitrary context, 12629 // create a method or method template, and wait for instantiation. 12630 // - There's a scope specifier that does match some template 12631 // parameter lists, which we don't handle right now. 12632 } else { 12633 if (D.isFunctionDefinition()) { 12634 // C++ [class.friend]p6: 12635 // A function can be defined in a friend declaration of a class if and 12636 // only if the class is a non-local class (9.8), the function name is 12637 // unqualified, and the function has namespace scope. 12638 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12639 << SS.getScopeRep(); 12640 } 12641 12642 DC = CurContext; 12643 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12644 } 12645 12646 if (!DC->isRecord()) { 12647 // This implies that it has to be an operator or function. 12648 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12649 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12650 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12651 Diag(Loc, diag::err_introducing_special_friend) << 12652 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12653 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12654 return nullptr; 12655 } 12656 } 12657 12658 // FIXME: This is an egregious hack to cope with cases where the scope stack 12659 // does not contain the declaration context, i.e., in an out-of-line 12660 // definition of a class. 12661 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12662 if (!DCScope) { 12663 FakeDCScope.setEntity(DC); 12664 DCScope = &FakeDCScope; 12665 } 12666 12667 bool AddToScope = true; 12668 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12669 TemplateParams, AddToScope); 12670 if (!ND) return nullptr; 12671 12672 assert(ND->getLexicalDeclContext() == CurContext); 12673 12674 // If we performed typo correction, we might have added a scope specifier 12675 // and changed the decl context. 12676 DC = ND->getDeclContext(); 12677 12678 // Add the function declaration to the appropriate lookup tables, 12679 // adjusting the redeclarations list as necessary. We don't 12680 // want to do this yet if the friending class is dependent. 12681 // 12682 // Also update the scope-based lookup if the target context's 12683 // lookup context is in lexical scope. 12684 if (!CurContext->isDependentContext()) { 12685 DC = DC->getRedeclContext(); 12686 DC->makeDeclVisibleInContext(ND); 12687 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12688 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12689 } 12690 12691 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12692 D.getIdentifierLoc(), ND, 12693 DS.getFriendSpecLoc()); 12694 FrD->setAccess(AS_public); 12695 CurContext->addDecl(FrD); 12696 12697 if (ND->isInvalidDecl()) { 12698 FrD->setInvalidDecl(); 12699 } else { 12700 if (DC->isRecord()) CheckFriendAccess(ND); 12701 12702 FunctionDecl *FD; 12703 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12704 FD = FTD->getTemplatedDecl(); 12705 else 12706 FD = cast<FunctionDecl>(ND); 12707 12708 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12709 // default argument expression, that declaration shall be a definition 12710 // and shall be the only declaration of the function or function 12711 // template in the translation unit. 12712 if (functionDeclHasDefaultArgument(FD)) { 12713 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12714 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12715 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12716 } else if (!D.isFunctionDefinition()) 12717 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12718 } 12719 12720 // Mark templated-scope function declarations as unsupported. 12721 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12722 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12723 << SS.getScopeRep() << SS.getRange() 12724 << cast<CXXRecordDecl>(CurContext); 12725 FrD->setUnsupportedFriend(true); 12726 } 12727 } 12728 12729 return ND; 12730 } 12731 12732 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12733 AdjustDeclIfTemplate(Dcl); 12734 12735 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12736 if (!Fn) { 12737 Diag(DelLoc, diag::err_deleted_non_function); 12738 return; 12739 } 12740 12741 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12742 // Don't consider the implicit declaration we generate for explicit 12743 // specializations. FIXME: Do not generate these implicit declarations. 12744 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12745 Prev->getPreviousDecl()) && 12746 !Prev->isDefined()) { 12747 Diag(DelLoc, diag::err_deleted_decl_not_first); 12748 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12749 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12750 : diag::note_previous_declaration); 12751 } 12752 // If the declaration wasn't the first, we delete the function anyway for 12753 // recovery. 12754 Fn = Fn->getCanonicalDecl(); 12755 } 12756 12757 // dllimport/dllexport cannot be deleted. 12758 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12759 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12760 Fn->setInvalidDecl(); 12761 } 12762 12763 if (Fn->isDeleted()) 12764 return; 12765 12766 // See if we're deleting a function which is already known to override a 12767 // non-deleted virtual function. 12768 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12769 bool IssuedDiagnostic = false; 12770 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12771 E = MD->end_overridden_methods(); 12772 I != E; ++I) { 12773 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12774 if (!IssuedDiagnostic) { 12775 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12776 IssuedDiagnostic = true; 12777 } 12778 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12779 } 12780 } 12781 } 12782 12783 // C++11 [basic.start.main]p3: 12784 // A program that defines main as deleted [...] is ill-formed. 12785 if (Fn->isMain()) 12786 Diag(DelLoc, diag::err_deleted_main); 12787 12788 Fn->setDeletedAsWritten(); 12789 } 12790 12791 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12792 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12793 12794 if (MD) { 12795 if (MD->getParent()->isDependentType()) { 12796 MD->setDefaulted(); 12797 MD->setExplicitlyDefaulted(); 12798 return; 12799 } 12800 12801 CXXSpecialMember Member = getSpecialMember(MD); 12802 if (Member == CXXInvalid) { 12803 if (!MD->isInvalidDecl()) 12804 Diag(DefaultLoc, diag::err_default_special_members); 12805 return; 12806 } 12807 12808 MD->setDefaulted(); 12809 MD->setExplicitlyDefaulted(); 12810 12811 // If this definition appears within the record, do the checking when 12812 // the record is complete. 12813 const FunctionDecl *Primary = MD; 12814 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12815 // Find the uninstantiated declaration that actually had the '= default' 12816 // on it. 12817 Pattern->isDefined(Primary); 12818 12819 // If the method was defaulted on its first declaration, we will have 12820 // already performed the checking in CheckCompletedCXXClass. Such a 12821 // declaration doesn't trigger an implicit definition. 12822 if (Primary == Primary->getCanonicalDecl()) 12823 return; 12824 12825 CheckExplicitlyDefaultedSpecialMember(MD); 12826 12827 if (MD->isInvalidDecl()) 12828 return; 12829 12830 switch (Member) { 12831 case CXXDefaultConstructor: 12832 DefineImplicitDefaultConstructor(DefaultLoc, 12833 cast<CXXConstructorDecl>(MD)); 12834 break; 12835 case CXXCopyConstructor: 12836 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12837 break; 12838 case CXXCopyAssignment: 12839 DefineImplicitCopyAssignment(DefaultLoc, MD); 12840 break; 12841 case CXXDestructor: 12842 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12843 break; 12844 case CXXMoveConstructor: 12845 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12846 break; 12847 case CXXMoveAssignment: 12848 DefineImplicitMoveAssignment(DefaultLoc, MD); 12849 break; 12850 case CXXInvalid: 12851 llvm_unreachable("Invalid special member."); 12852 } 12853 } else { 12854 Diag(DefaultLoc, diag::err_default_special_members); 12855 } 12856 } 12857 12858 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12859 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12860 Stmt *SubStmt = *CI; 12861 if (!SubStmt) 12862 continue; 12863 if (isa<ReturnStmt>(SubStmt)) 12864 Self.Diag(SubStmt->getLocStart(), 12865 diag::err_return_in_constructor_handler); 12866 if (!isa<Expr>(SubStmt)) 12867 SearchForReturnInStmt(Self, SubStmt); 12868 } 12869 } 12870 12871 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12872 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12873 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12874 SearchForReturnInStmt(*this, Handler); 12875 } 12876 } 12877 12878 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12879 const CXXMethodDecl *Old) { 12880 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12881 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12882 12883 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12884 12885 // If the calling conventions match, everything is fine 12886 if (NewCC == OldCC) 12887 return false; 12888 12889 // If the calling conventions mismatch because the new function is static, 12890 // suppress the calling convention mismatch error; the error about static 12891 // function override (err_static_overrides_virtual from 12892 // Sema::CheckFunctionDeclaration) is more clear. 12893 if (New->getStorageClass() == SC_Static) 12894 return false; 12895 12896 Diag(New->getLocation(), 12897 diag::err_conflicting_overriding_cc_attributes) 12898 << New->getDeclName() << New->getType() << Old->getType(); 12899 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12900 return true; 12901 } 12902 12903 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12904 const CXXMethodDecl *Old) { 12905 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12906 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12907 12908 if (Context.hasSameType(NewTy, OldTy) || 12909 NewTy->isDependentType() || OldTy->isDependentType()) 12910 return false; 12911 12912 // Check if the return types are covariant 12913 QualType NewClassTy, OldClassTy; 12914 12915 /// Both types must be pointers or references to classes. 12916 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12917 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12918 NewClassTy = NewPT->getPointeeType(); 12919 OldClassTy = OldPT->getPointeeType(); 12920 } 12921 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12922 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12923 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12924 NewClassTy = NewRT->getPointeeType(); 12925 OldClassTy = OldRT->getPointeeType(); 12926 } 12927 } 12928 } 12929 12930 // The return types aren't either both pointers or references to a class type. 12931 if (NewClassTy.isNull()) { 12932 Diag(New->getLocation(), 12933 diag::err_different_return_type_for_overriding_virtual_function) 12934 << New->getDeclName() << NewTy << OldTy 12935 << New->getReturnTypeSourceRange(); 12936 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12937 << Old->getReturnTypeSourceRange(); 12938 12939 return true; 12940 } 12941 12942 // C++ [class.virtual]p6: 12943 // If the return type of D::f differs from the return type of B::f, the 12944 // class type in the return type of D::f shall be complete at the point of 12945 // declaration of D::f or shall be the class type D. 12946 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12947 if (!RT->isBeingDefined() && 12948 RequireCompleteType(New->getLocation(), NewClassTy, 12949 diag::err_covariant_return_incomplete, 12950 New->getDeclName())) 12951 return true; 12952 } 12953 12954 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12955 // Check if the new class derives from the old class. 12956 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12957 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12958 << New->getDeclName() << NewTy << OldTy 12959 << New->getReturnTypeSourceRange(); 12960 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12961 << Old->getReturnTypeSourceRange(); 12962 return true; 12963 } 12964 12965 // Check if we the conversion from derived to base is valid. 12966 if (CheckDerivedToBaseConversion( 12967 NewClassTy, OldClassTy, 12968 diag::err_covariant_return_inaccessible_base, 12969 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12970 New->getLocation(), New->getReturnTypeSourceRange(), 12971 New->getDeclName(), nullptr)) { 12972 // FIXME: this note won't trigger for delayed access control 12973 // diagnostics, and it's impossible to get an undelayed error 12974 // here from access control during the original parse because 12975 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12976 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12977 << Old->getReturnTypeSourceRange(); 12978 return true; 12979 } 12980 } 12981 12982 // The qualifiers of the return types must be the same. 12983 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12984 Diag(New->getLocation(), 12985 diag::err_covariant_return_type_different_qualifications) 12986 << New->getDeclName() << NewTy << OldTy 12987 << New->getReturnTypeSourceRange(); 12988 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12989 << Old->getReturnTypeSourceRange(); 12990 return true; 12991 }; 12992 12993 12994 // The new class type must have the same or less qualifiers as the old type. 12995 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12996 Diag(New->getLocation(), 12997 diag::err_covariant_return_type_class_type_more_qualified) 12998 << New->getDeclName() << NewTy << OldTy 12999 << New->getReturnTypeSourceRange(); 13000 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13001 << Old->getReturnTypeSourceRange(); 13002 return true; 13003 }; 13004 13005 return false; 13006 } 13007 13008 /// \brief Mark the given method pure. 13009 /// 13010 /// \param Method the method to be marked pure. 13011 /// 13012 /// \param InitRange the source range that covers the "0" initializer. 13013 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 13014 SourceLocation EndLoc = InitRange.getEnd(); 13015 if (EndLoc.isValid()) 13016 Method->setRangeEnd(EndLoc); 13017 13018 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 13019 Method->setPure(); 13020 return false; 13021 } 13022 13023 if (!Method->isInvalidDecl()) 13024 Diag(Method->getLocation(), diag::err_non_virtual_pure) 13025 << Method->getDeclName() << InitRange; 13026 return true; 13027 } 13028 13029 /// \brief Determine whether the given declaration is a static data member. 13030 static bool isStaticDataMember(const Decl *D) { 13031 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 13032 return Var->isStaticDataMember(); 13033 13034 return false; 13035 } 13036 13037 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 13038 /// an initializer for the out-of-line declaration 'Dcl'. The scope 13039 /// is a fresh scope pushed for just this purpose. 13040 /// 13041 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 13042 /// static data member of class X, names should be looked up in the scope of 13043 /// class X. 13044 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 13045 // If there is no declaration, there was an error parsing it. 13046 if (!D || D->isInvalidDecl()) 13047 return; 13048 13049 // We will always have a nested name specifier here, but this declaration 13050 // might not be out of line if the specifier names the current namespace: 13051 // extern int n; 13052 // int ::n = 0; 13053 if (D->isOutOfLine()) 13054 EnterDeclaratorContext(S, D->getDeclContext()); 13055 13056 // If we are parsing the initializer for a static data member, push a 13057 // new expression evaluation context that is associated with this static 13058 // data member. 13059 if (isStaticDataMember(D)) 13060 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 13061 } 13062 13063 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 13064 /// initializer for the out-of-line declaration 'D'. 13065 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 13066 // If there is no declaration, there was an error parsing it. 13067 if (!D || D->isInvalidDecl()) 13068 return; 13069 13070 if (isStaticDataMember(D)) 13071 PopExpressionEvaluationContext(); 13072 13073 if (D->isOutOfLine()) 13074 ExitDeclaratorContext(S); 13075 } 13076 13077 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 13078 /// C++ if/switch/while/for statement. 13079 /// e.g: "if (int x = f()) {...}" 13080 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 13081 // C++ 6.4p2: 13082 // The declarator shall not specify a function or an array. 13083 // The type-specifier-seq shall not contain typedef and shall not declare a 13084 // new class or enumeration. 13085 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 13086 "Parser allowed 'typedef' as storage class of condition decl."); 13087 13088 Decl *Dcl = ActOnDeclarator(S, D); 13089 if (!Dcl) 13090 return true; 13091 13092 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 13093 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 13094 << D.getSourceRange(); 13095 return true; 13096 } 13097 13098 return Dcl; 13099 } 13100 13101 void Sema::LoadExternalVTableUses() { 13102 if (!ExternalSource) 13103 return; 13104 13105 SmallVector<ExternalVTableUse, 4> VTables; 13106 ExternalSource->ReadUsedVTables(VTables); 13107 SmallVector<VTableUse, 4> NewUses; 13108 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 13109 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 13110 = VTablesUsed.find(VTables[I].Record); 13111 // Even if a definition wasn't required before, it may be required now. 13112 if (Pos != VTablesUsed.end()) { 13113 if (!Pos->second && VTables[I].DefinitionRequired) 13114 Pos->second = true; 13115 continue; 13116 } 13117 13118 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 13119 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 13120 } 13121 13122 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 13123 } 13124 13125 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 13126 bool DefinitionRequired) { 13127 // Ignore any vtable uses in unevaluated operands or for classes that do 13128 // not have a vtable. 13129 if (!Class->isDynamicClass() || Class->isDependentContext() || 13130 CurContext->isDependentContext() || isUnevaluatedContext()) 13131 return; 13132 13133 // Try to insert this class into the map. 13134 LoadExternalVTableUses(); 13135 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13136 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 13137 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 13138 if (!Pos.second) { 13139 // If we already had an entry, check to see if we are promoting this vtable 13140 // to require a definition. If so, we need to reappend to the VTableUses 13141 // list, since we may have already processed the first entry. 13142 if (DefinitionRequired && !Pos.first->second) { 13143 Pos.first->second = true; 13144 } else { 13145 // Otherwise, we can early exit. 13146 return; 13147 } 13148 } else { 13149 // The Microsoft ABI requires that we perform the destructor body 13150 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 13151 // the deleting destructor is emitted with the vtable, not with the 13152 // destructor definition as in the Itanium ABI. 13153 // If it has a definition, we do the check at that point instead. 13154 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13155 Class->hasUserDeclaredDestructor() && 13156 !Class->getDestructor()->isDefined() && 13157 !Class->getDestructor()->isDeleted()) { 13158 CXXDestructorDecl *DD = Class->getDestructor(); 13159 ContextRAII SavedContext(*this, DD); 13160 CheckDestructor(DD); 13161 } 13162 } 13163 13164 // Local classes need to have their virtual members marked 13165 // immediately. For all other classes, we mark their virtual members 13166 // at the end of the translation unit. 13167 if (Class->isLocalClass()) 13168 MarkVirtualMembersReferenced(Loc, Class); 13169 else 13170 VTableUses.push_back(std::make_pair(Class, Loc)); 13171 } 13172 13173 bool Sema::DefineUsedVTables() { 13174 LoadExternalVTableUses(); 13175 if (VTableUses.empty()) 13176 return false; 13177 13178 // Note: The VTableUses vector could grow as a result of marking 13179 // the members of a class as "used", so we check the size each 13180 // time through the loop and prefer indices (which are stable) to 13181 // iterators (which are not). 13182 bool DefinedAnything = false; 13183 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13184 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13185 if (!Class) 13186 continue; 13187 13188 SourceLocation Loc = VTableUses[I].second; 13189 13190 bool DefineVTable = true; 13191 13192 // If this class has a key function, but that key function is 13193 // defined in another translation unit, we don't need to emit the 13194 // vtable even though we're using it. 13195 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13196 if (KeyFunction && !KeyFunction->hasBody()) { 13197 // The key function is in another translation unit. 13198 DefineVTable = false; 13199 TemplateSpecializationKind TSK = 13200 KeyFunction->getTemplateSpecializationKind(); 13201 assert(TSK != TSK_ExplicitInstantiationDefinition && 13202 TSK != TSK_ImplicitInstantiation && 13203 "Instantiations don't have key functions"); 13204 (void)TSK; 13205 } else if (!KeyFunction) { 13206 // If we have a class with no key function that is the subject 13207 // of an explicit instantiation declaration, suppress the 13208 // vtable; it will live with the explicit instantiation 13209 // definition. 13210 bool IsExplicitInstantiationDeclaration 13211 = Class->getTemplateSpecializationKind() 13212 == TSK_ExplicitInstantiationDeclaration; 13213 for (auto R : Class->redecls()) { 13214 TemplateSpecializationKind TSK 13215 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13216 if (TSK == TSK_ExplicitInstantiationDeclaration) 13217 IsExplicitInstantiationDeclaration = true; 13218 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13219 IsExplicitInstantiationDeclaration = false; 13220 break; 13221 } 13222 } 13223 13224 if (IsExplicitInstantiationDeclaration) 13225 DefineVTable = false; 13226 } 13227 13228 // The exception specifications for all virtual members may be needed even 13229 // if we are not providing an authoritative form of the vtable in this TU. 13230 // We may choose to emit it available_externally anyway. 13231 if (!DefineVTable) { 13232 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13233 continue; 13234 } 13235 13236 // Mark all of the virtual members of this class as referenced, so 13237 // that we can build a vtable. Then, tell the AST consumer that a 13238 // vtable for this class is required. 13239 DefinedAnything = true; 13240 MarkVirtualMembersReferenced(Loc, Class); 13241 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13242 if (VTablesUsed[Canonical]) 13243 Consumer.HandleVTable(Class); 13244 13245 // Optionally warn if we're emitting a weak vtable. 13246 if (Class->isExternallyVisible() && 13247 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13248 const FunctionDecl *KeyFunctionDef = nullptr; 13249 if (!KeyFunction || 13250 (KeyFunction->hasBody(KeyFunctionDef) && 13251 KeyFunctionDef->isInlined())) 13252 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13253 TSK_ExplicitInstantiationDefinition 13254 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13255 << Class; 13256 } 13257 } 13258 VTableUses.clear(); 13259 13260 return DefinedAnything; 13261 } 13262 13263 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13264 const CXXRecordDecl *RD) { 13265 for (const auto *I : RD->methods()) 13266 if (I->isVirtual() && !I->isPure()) 13267 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13268 } 13269 13270 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13271 const CXXRecordDecl *RD) { 13272 // Mark all functions which will appear in RD's vtable as used. 13273 CXXFinalOverriderMap FinalOverriders; 13274 RD->getFinalOverriders(FinalOverriders); 13275 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13276 E = FinalOverriders.end(); 13277 I != E; ++I) { 13278 for (OverridingMethods::const_iterator OI = I->second.begin(), 13279 OE = I->second.end(); 13280 OI != OE; ++OI) { 13281 assert(OI->second.size() > 0 && "no final overrider"); 13282 CXXMethodDecl *Overrider = OI->second.front().Method; 13283 13284 // C++ [basic.def.odr]p2: 13285 // [...] A virtual member function is used if it is not pure. [...] 13286 if (!Overrider->isPure()) 13287 MarkFunctionReferenced(Loc, Overrider); 13288 } 13289 } 13290 13291 // Only classes that have virtual bases need a VTT. 13292 if (RD->getNumVBases() == 0) 13293 return; 13294 13295 for (const auto &I : RD->bases()) { 13296 const CXXRecordDecl *Base = 13297 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13298 if (Base->getNumVBases() == 0) 13299 continue; 13300 MarkVirtualMembersReferenced(Loc, Base); 13301 } 13302 } 13303 13304 /// SetIvarInitializers - This routine builds initialization ASTs for the 13305 /// Objective-C implementation whose ivars need be initialized. 13306 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13307 if (!getLangOpts().CPlusPlus) 13308 return; 13309 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13310 SmallVector<ObjCIvarDecl*, 8> ivars; 13311 CollectIvarsToConstructOrDestruct(OID, ivars); 13312 if (ivars.empty()) 13313 return; 13314 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13315 for (unsigned i = 0; i < ivars.size(); i++) { 13316 FieldDecl *Field = ivars[i]; 13317 if (Field->isInvalidDecl()) 13318 continue; 13319 13320 CXXCtorInitializer *Member; 13321 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13322 InitializationKind InitKind = 13323 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13324 13325 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13326 ExprResult MemberInit = 13327 InitSeq.Perform(*this, InitEntity, InitKind, None); 13328 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13329 // Note, MemberInit could actually come back empty if no initialization 13330 // is required (e.g., because it would call a trivial default constructor) 13331 if (!MemberInit.get() || MemberInit.isInvalid()) 13332 continue; 13333 13334 Member = 13335 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13336 SourceLocation(), 13337 MemberInit.getAs<Expr>(), 13338 SourceLocation()); 13339 AllToInit.push_back(Member); 13340 13341 // Be sure that the destructor is accessible and is marked as referenced. 13342 if (const RecordType *RecordTy = 13343 Context.getBaseElementType(Field->getType()) 13344 ->getAs<RecordType>()) { 13345 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13346 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13347 MarkFunctionReferenced(Field->getLocation(), Destructor); 13348 CheckDestructorAccess(Field->getLocation(), Destructor, 13349 PDiag(diag::err_access_dtor_ivar) 13350 << Context.getBaseElementType(Field->getType())); 13351 } 13352 } 13353 } 13354 ObjCImplementation->setIvarInitializers(Context, 13355 AllToInit.data(), AllToInit.size()); 13356 } 13357 } 13358 13359 static 13360 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13361 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13362 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13363 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13364 Sema &S) { 13365 if (Ctor->isInvalidDecl()) 13366 return; 13367 13368 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13369 13370 // Target may not be determinable yet, for instance if this is a dependent 13371 // call in an uninstantiated template. 13372 if (Target) { 13373 const FunctionDecl *FNTarget = nullptr; 13374 (void)Target->hasBody(FNTarget); 13375 Target = const_cast<CXXConstructorDecl*>( 13376 cast_or_null<CXXConstructorDecl>(FNTarget)); 13377 } 13378 13379 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13380 // Avoid dereferencing a null pointer here. 13381 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13382 13383 if (!Current.insert(Canonical).second) 13384 return; 13385 13386 // We know that beyond here, we aren't chaining into a cycle. 13387 if (!Target || !Target->isDelegatingConstructor() || 13388 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13389 Valid.insert(Current.begin(), Current.end()); 13390 Current.clear(); 13391 // We've hit a cycle. 13392 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13393 Current.count(TCanonical)) { 13394 // If we haven't diagnosed this cycle yet, do so now. 13395 if (!Invalid.count(TCanonical)) { 13396 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13397 diag::warn_delegating_ctor_cycle) 13398 << Ctor; 13399 13400 // Don't add a note for a function delegating directly to itself. 13401 if (TCanonical != Canonical) 13402 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13403 13404 CXXConstructorDecl *C = Target; 13405 while (C->getCanonicalDecl() != Canonical) { 13406 const FunctionDecl *FNTarget = nullptr; 13407 (void)C->getTargetConstructor()->hasBody(FNTarget); 13408 assert(FNTarget && "Ctor cycle through bodiless function"); 13409 13410 C = const_cast<CXXConstructorDecl*>( 13411 cast<CXXConstructorDecl>(FNTarget)); 13412 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13413 } 13414 } 13415 13416 Invalid.insert(Current.begin(), Current.end()); 13417 Current.clear(); 13418 } else { 13419 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13420 } 13421 } 13422 13423 13424 void Sema::CheckDelegatingCtorCycles() { 13425 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13426 13427 for (DelegatingCtorDeclsType::iterator 13428 I = DelegatingCtorDecls.begin(ExternalSource), 13429 E = DelegatingCtorDecls.end(); 13430 I != E; ++I) 13431 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13432 13433 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13434 CE = Invalid.end(); 13435 CI != CE; ++CI) 13436 (*CI)->setInvalidDecl(); 13437 } 13438 13439 namespace { 13440 /// \brief AST visitor that finds references to the 'this' expression. 13441 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13442 Sema &S; 13443 13444 public: 13445 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13446 13447 bool VisitCXXThisExpr(CXXThisExpr *E) { 13448 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13449 << E->isImplicit(); 13450 return false; 13451 } 13452 }; 13453 } 13454 13455 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13456 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13457 if (!TSInfo) 13458 return false; 13459 13460 TypeLoc TL = TSInfo->getTypeLoc(); 13461 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13462 if (!ProtoTL) 13463 return false; 13464 13465 // C++11 [expr.prim.general]p3: 13466 // [The expression this] shall not appear before the optional 13467 // cv-qualifier-seq and it shall not appear within the declaration of a 13468 // static member function (although its type and value category are defined 13469 // within a static member function as they are within a non-static member 13470 // function). [ Note: this is because declaration matching does not occur 13471 // until the complete declarator is known. - end note ] 13472 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13473 FindCXXThisExpr Finder(*this); 13474 13475 // If the return type came after the cv-qualifier-seq, check it now. 13476 if (Proto->hasTrailingReturn() && 13477 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13478 return true; 13479 13480 // Check the exception specification. 13481 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13482 return true; 13483 13484 return checkThisInStaticMemberFunctionAttributes(Method); 13485 } 13486 13487 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13488 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13489 if (!TSInfo) 13490 return false; 13491 13492 TypeLoc TL = TSInfo->getTypeLoc(); 13493 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13494 if (!ProtoTL) 13495 return false; 13496 13497 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13498 FindCXXThisExpr Finder(*this); 13499 13500 switch (Proto->getExceptionSpecType()) { 13501 case EST_Unparsed: 13502 case EST_Uninstantiated: 13503 case EST_Unevaluated: 13504 case EST_BasicNoexcept: 13505 case EST_DynamicNone: 13506 case EST_MSAny: 13507 case EST_None: 13508 break; 13509 13510 case EST_ComputedNoexcept: 13511 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13512 return true; 13513 13514 case EST_Dynamic: 13515 for (const auto &E : Proto->exceptions()) { 13516 if (!Finder.TraverseType(E)) 13517 return true; 13518 } 13519 break; 13520 } 13521 13522 return false; 13523 } 13524 13525 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13526 FindCXXThisExpr Finder(*this); 13527 13528 // Check attributes. 13529 for (const auto *A : Method->attrs()) { 13530 // FIXME: This should be emitted by tblgen. 13531 Expr *Arg = nullptr; 13532 ArrayRef<Expr *> Args; 13533 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13534 Arg = G->getArg(); 13535 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13536 Arg = G->getArg(); 13537 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13538 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13539 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13540 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13541 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13542 Arg = ETLF->getSuccessValue(); 13543 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13544 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13545 Arg = STLF->getSuccessValue(); 13546 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13547 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13548 Arg = LR->getArg(); 13549 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13550 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13551 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13552 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13553 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13554 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13555 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13556 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13557 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13558 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13559 13560 if (Arg && !Finder.TraverseStmt(Arg)) 13561 return true; 13562 13563 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13564 if (!Finder.TraverseStmt(Args[I])) 13565 return true; 13566 } 13567 } 13568 13569 return false; 13570 } 13571 13572 void Sema::checkExceptionSpecification( 13573 bool IsTopLevel, ExceptionSpecificationType EST, 13574 ArrayRef<ParsedType> DynamicExceptions, 13575 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13576 SmallVectorImpl<QualType> &Exceptions, 13577 FunctionProtoType::ExceptionSpecInfo &ESI) { 13578 Exceptions.clear(); 13579 ESI.Type = EST; 13580 if (EST == EST_Dynamic) { 13581 Exceptions.reserve(DynamicExceptions.size()); 13582 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13583 // FIXME: Preserve type source info. 13584 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13585 13586 if (IsTopLevel) { 13587 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13588 collectUnexpandedParameterPacks(ET, Unexpanded); 13589 if (!Unexpanded.empty()) { 13590 DiagnoseUnexpandedParameterPacks( 13591 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13592 Unexpanded); 13593 continue; 13594 } 13595 } 13596 13597 // Check that the type is valid for an exception spec, and 13598 // drop it if not. 13599 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13600 Exceptions.push_back(ET); 13601 } 13602 ESI.Exceptions = Exceptions; 13603 return; 13604 } 13605 13606 if (EST == EST_ComputedNoexcept) { 13607 // If an error occurred, there's no expression here. 13608 if (NoexceptExpr) { 13609 assert((NoexceptExpr->isTypeDependent() || 13610 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13611 Context.BoolTy) && 13612 "Parser should have made sure that the expression is boolean"); 13613 if (IsTopLevel && NoexceptExpr && 13614 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13615 ESI.Type = EST_BasicNoexcept; 13616 return; 13617 } 13618 13619 if (!NoexceptExpr->isValueDependent()) 13620 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13621 diag::err_noexcept_needs_constant_expression, 13622 /*AllowFold*/ false).get(); 13623 ESI.NoexceptExpr = NoexceptExpr; 13624 } 13625 return; 13626 } 13627 } 13628 13629 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13630 ExceptionSpecificationType EST, 13631 SourceRange SpecificationRange, 13632 ArrayRef<ParsedType> DynamicExceptions, 13633 ArrayRef<SourceRange> DynamicExceptionRanges, 13634 Expr *NoexceptExpr) { 13635 if (!MethodD) 13636 return; 13637 13638 // Dig out the method we're referring to. 13639 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13640 MethodD = FunTmpl->getTemplatedDecl(); 13641 13642 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13643 if (!Method) 13644 return; 13645 13646 // Check the exception specification. 13647 llvm::SmallVector<QualType, 4> Exceptions; 13648 FunctionProtoType::ExceptionSpecInfo ESI; 13649 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13650 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13651 ESI); 13652 13653 // Update the exception specification on the function type. 13654 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13655 13656 if (Method->isStatic()) 13657 checkThisInStaticMemberFunctionExceptionSpec(Method); 13658 13659 if (Method->isVirtual()) { 13660 // Check overrides, which we previously had to delay. 13661 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13662 OEnd = Method->end_overridden_methods(); 13663 O != OEnd; ++O) 13664 CheckOverridingFunctionExceptionSpec(Method, *O); 13665 } 13666 } 13667 13668 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13669 /// 13670 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13671 SourceLocation DeclStart, 13672 Declarator &D, Expr *BitWidth, 13673 InClassInitStyle InitStyle, 13674 AccessSpecifier AS, 13675 AttributeList *MSPropertyAttr) { 13676 IdentifierInfo *II = D.getIdentifier(); 13677 if (!II) { 13678 Diag(DeclStart, diag::err_anonymous_property); 13679 return nullptr; 13680 } 13681 SourceLocation Loc = D.getIdentifierLoc(); 13682 13683 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13684 QualType T = TInfo->getType(); 13685 if (getLangOpts().CPlusPlus) { 13686 CheckExtraCXXDefaultArguments(D); 13687 13688 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13689 UPPC_DataMemberType)) { 13690 D.setInvalidType(); 13691 T = Context.IntTy; 13692 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13693 } 13694 } 13695 13696 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13697 13698 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13699 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13700 diag::err_invalid_thread) 13701 << DeclSpec::getSpecifierName(TSCS); 13702 13703 // Check to see if this name was declared as a member previously 13704 NamedDecl *PrevDecl = nullptr; 13705 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13706 LookupName(Previous, S); 13707 switch (Previous.getResultKind()) { 13708 case LookupResult::Found: 13709 case LookupResult::FoundUnresolvedValue: 13710 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13711 break; 13712 13713 case LookupResult::FoundOverloaded: 13714 PrevDecl = Previous.getRepresentativeDecl(); 13715 break; 13716 13717 case LookupResult::NotFound: 13718 case LookupResult::NotFoundInCurrentInstantiation: 13719 case LookupResult::Ambiguous: 13720 break; 13721 } 13722 13723 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13724 // Maybe we will complain about the shadowed template parameter. 13725 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13726 // Just pretend that we didn't see the previous declaration. 13727 PrevDecl = nullptr; 13728 } 13729 13730 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13731 PrevDecl = nullptr; 13732 13733 SourceLocation TSSL = D.getLocStart(); 13734 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13735 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13736 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13737 ProcessDeclAttributes(TUScope, NewPD, D); 13738 NewPD->setAccess(AS); 13739 13740 if (NewPD->isInvalidDecl()) 13741 Record->setInvalidDecl(); 13742 13743 if (D.getDeclSpec().isModulePrivateSpecified()) 13744 NewPD->setModulePrivate(); 13745 13746 if (NewPD->isInvalidDecl() && PrevDecl) { 13747 // Don't introduce NewFD into scope; there's already something 13748 // with the same name in the same scope. 13749 } else if (II) { 13750 PushOnScopeChains(NewPD, S); 13751 } else 13752 Record->addDecl(NewPD); 13753 13754 return NewPD; 13755 } 13756