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 // The declaration context corresponding to the scope is the semantic 442 // parent, unless this is a local function declaration, in which case 443 // it is that surrounding function. 444 DeclContext *ScopeDC = New->isLocalExternDecl() 445 ? New->getLexicalDeclContext() 446 : New->getDeclContext(); 447 448 // Find the previous declaration for the purpose of default arguments. 449 FunctionDecl *PrevForDefaultArgs = Old; 450 for (/**/; PrevForDefaultArgs; 451 // Don't bother looking back past the latest decl if this is a local 452 // extern declaration; nothing else could work. 453 PrevForDefaultArgs = New->isLocalExternDecl() 454 ? nullptr 455 : PrevForDefaultArgs->getPreviousDecl()) { 456 // Ignore hidden declarations. 457 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 458 continue; 459 460 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 461 !New->isCXXClassMember()) { 462 // Ignore default arguments of old decl if they are not in 463 // the same scope and this is not an out-of-line definition of 464 // a member function. 465 continue; 466 } 467 468 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 469 // If only one of these is a local function declaration, then they are 470 // declared in different scopes, even though isDeclInScope may think 471 // they're in the same scope. (If both are local, the scope check is 472 // sufficent, and if neither is local, then they are in the same scope.) 473 continue; 474 } 475 476 // We found our guy. 477 break; 478 } 479 480 // C++ [dcl.fct.default]p4: 481 // For non-template functions, default arguments can be added in 482 // later declarations of a function in the same 483 // scope. Declarations in different scopes have completely 484 // distinct sets of default arguments. That is, declarations in 485 // inner scopes do not acquire default arguments from 486 // declarations in outer scopes, and vice versa. In a given 487 // function declaration, all parameters subsequent to a 488 // parameter with a default argument shall have default 489 // arguments supplied in this or previous declarations. A 490 // default argument shall not be redefined by a later 491 // declaration (not even to the same value). 492 // 493 // C++ [dcl.fct.default]p6: 494 // Except for member functions of class templates, the default arguments 495 // in a member function definition that appears outside of the class 496 // definition are added to the set of default arguments provided by the 497 // member function declaration in the class definition. 498 for (unsigned p = 0, NumParams = PrevForDefaultArgs 499 ? PrevForDefaultArgs->getNumParams() 500 : 0; 501 p < NumParams; ++p) { 502 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 503 ParmVarDecl *NewParam = New->getParamDecl(p); 504 505 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 506 bool NewParamHasDfl = NewParam->hasDefaultArg(); 507 508 if (OldParamHasDfl && NewParamHasDfl) { 509 unsigned DiagDefaultParamID = 510 diag::err_param_default_argument_redefinition; 511 512 // MSVC accepts that default parameters be redefined for member functions 513 // of template class. The new default parameter's value is ignored. 514 Invalid = true; 515 if (getLangOpts().MicrosoftExt) { 516 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 517 if (MD && MD->getParent()->getDescribedClassTemplate()) { 518 // Merge the old default argument into the new parameter. 519 NewParam->setHasInheritedDefaultArg(); 520 if (OldParam->hasUninstantiatedDefaultArg()) 521 NewParam->setUninstantiatedDefaultArg( 522 OldParam->getUninstantiatedDefaultArg()); 523 else 524 NewParam->setDefaultArg(OldParam->getInit()); 525 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 526 Invalid = false; 527 } 528 } 529 530 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 531 // hint here. Alternatively, we could walk the type-source information 532 // for NewParam to find the last source location in the type... but it 533 // isn't worth the effort right now. This is the kind of test case that 534 // is hard to get right: 535 // int f(int); 536 // void g(int (*fp)(int) = f); 537 // void g(int (*fp)(int) = &f); 538 Diag(NewParam->getLocation(), DiagDefaultParamID) 539 << NewParam->getDefaultArgRange(); 540 541 // Look for the function declaration where the default argument was 542 // actually written, which may be a declaration prior to Old. 543 for (auto Older = PrevForDefaultArgs; 544 OldParam->hasInheritedDefaultArg(); /**/) { 545 Older = Older->getPreviousDecl(); 546 OldParam = Older->getParamDecl(p); 547 } 548 549 Diag(OldParam->getLocation(), diag::note_previous_definition) 550 << OldParam->getDefaultArgRange(); 551 } else if (OldParamHasDfl) { 552 // Merge the old default argument into the new parameter. 553 // It's important to use getInit() here; getDefaultArg() 554 // strips off any top-level ExprWithCleanups. 555 NewParam->setHasInheritedDefaultArg(); 556 if (OldParam->hasUnparsedDefaultArg()) 557 NewParam->setUnparsedDefaultArg(); 558 else if (OldParam->hasUninstantiatedDefaultArg()) 559 NewParam->setUninstantiatedDefaultArg( 560 OldParam->getUninstantiatedDefaultArg()); 561 else 562 NewParam->setDefaultArg(OldParam->getInit()); 563 } else if (NewParamHasDfl) { 564 if (New->getDescribedFunctionTemplate()) { 565 // Paragraph 4, quoted above, only applies to non-template functions. 566 Diag(NewParam->getLocation(), 567 diag::err_param_default_argument_template_redecl) 568 << NewParam->getDefaultArgRange(); 569 Diag(PrevForDefaultArgs->getLocation(), 570 diag::note_template_prev_declaration) 571 << false; 572 } else if (New->getTemplateSpecializationKind() 573 != TSK_ImplicitInstantiation && 574 New->getTemplateSpecializationKind() != TSK_Undeclared) { 575 // C++ [temp.expr.spec]p21: 576 // Default function arguments shall not be specified in a declaration 577 // or a definition for one of the following explicit specializations: 578 // - the explicit specialization of a function template; 579 // - the explicit specialization of a member function template; 580 // - the explicit specialization of a member function of a class 581 // template where the class template specialization to which the 582 // member function specialization belongs is implicitly 583 // instantiated. 584 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 585 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 586 << New->getDeclName() 587 << NewParam->getDefaultArgRange(); 588 } else if (New->getDeclContext()->isDependentContext()) { 589 // C++ [dcl.fct.default]p6 (DR217): 590 // Default arguments for a member function of a class template shall 591 // be specified on the initial declaration of the member function 592 // within the class template. 593 // 594 // Reading the tea leaves a bit in DR217 and its reference to DR205 595 // leads me to the conclusion that one cannot add default function 596 // arguments for an out-of-line definition of a member function of a 597 // dependent type. 598 int WhichKind = 2; 599 if (CXXRecordDecl *Record 600 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 601 if (Record->getDescribedClassTemplate()) 602 WhichKind = 0; 603 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 604 WhichKind = 1; 605 else 606 WhichKind = 2; 607 } 608 609 Diag(NewParam->getLocation(), 610 diag::err_param_default_argument_member_template_redecl) 611 << WhichKind 612 << NewParam->getDefaultArgRange(); 613 } 614 } 615 } 616 617 // DR1344: If a default argument is added outside a class definition and that 618 // default argument makes the function a special member function, the program 619 // is ill-formed. This can only happen for constructors. 620 if (isa<CXXConstructorDecl>(New) && 621 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 622 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 623 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 624 if (NewSM != OldSM) { 625 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 626 assert(NewParam->hasDefaultArg()); 627 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 628 << NewParam->getDefaultArgRange() << NewSM; 629 Diag(Old->getLocation(), diag::note_previous_declaration); 630 } 631 } 632 633 const FunctionDecl *Def; 634 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 635 // template has a constexpr specifier then all its declarations shall 636 // contain the constexpr specifier. 637 if (New->isConstexpr() != Old->isConstexpr()) { 638 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 639 << New << New->isConstexpr(); 640 Diag(Old->getLocation(), diag::note_previous_declaration); 641 Invalid = true; 642 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 643 Old->isDefined(Def)) { 644 // C++11 [dcl.fcn.spec]p4: 645 // If the definition of a function appears in a translation unit before its 646 // first declaration as inline, the program is ill-formed. 647 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 648 Diag(Def->getLocation(), diag::note_previous_definition); 649 Invalid = true; 650 } 651 652 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 653 // argument expression, that declaration shall be a definition and shall be 654 // the only declaration of the function or function template in the 655 // translation unit. 656 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 657 functionDeclHasDefaultArgument(Old)) { 658 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 659 Diag(Old->getLocation(), diag::note_previous_declaration); 660 Invalid = true; 661 } 662 663 if (CheckEquivalentExceptionSpec(Old, New)) 664 Invalid = true; 665 666 return Invalid; 667 } 668 669 /// \brief Merge the exception specifications of two variable declarations. 670 /// 671 /// This is called when there's a redeclaration of a VarDecl. The function 672 /// checks if the redeclaration might have an exception specification and 673 /// validates compatibility and merges the specs if necessary. 674 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 675 // Shortcut if exceptions are disabled. 676 if (!getLangOpts().CXXExceptions) 677 return; 678 679 assert(Context.hasSameType(New->getType(), Old->getType()) && 680 "Should only be called if types are otherwise the same."); 681 682 QualType NewType = New->getType(); 683 QualType OldType = Old->getType(); 684 685 // We're only interested in pointers and references to functions, as well 686 // as pointers to member functions. 687 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 688 NewType = R->getPointeeType(); 689 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 690 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 691 NewType = P->getPointeeType(); 692 OldType = OldType->getAs<PointerType>()->getPointeeType(); 693 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 694 NewType = M->getPointeeType(); 695 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 696 } 697 698 if (!NewType->isFunctionProtoType()) 699 return; 700 701 // There's lots of special cases for functions. For function pointers, system 702 // libraries are hopefully not as broken so that we don't need these 703 // workarounds. 704 if (CheckEquivalentExceptionSpec( 705 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 706 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 707 New->setInvalidDecl(); 708 } 709 } 710 711 /// CheckCXXDefaultArguments - Verify that the default arguments for a 712 /// function declaration are well-formed according to C++ 713 /// [dcl.fct.default]. 714 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 715 unsigned NumParams = FD->getNumParams(); 716 unsigned p; 717 718 // Find first parameter with a default argument 719 for (p = 0; p < NumParams; ++p) { 720 ParmVarDecl *Param = FD->getParamDecl(p); 721 if (Param->hasDefaultArg()) 722 break; 723 } 724 725 // C++11 [dcl.fct.default]p4: 726 // In a given function declaration, each parameter subsequent to a parameter 727 // with a default argument shall have a default argument supplied in this or 728 // a previous declaration or shall be a function parameter pack. A default 729 // argument shall not be redefined by a later declaration (not even to the 730 // same value). 731 unsigned LastMissingDefaultArg = 0; 732 for (; p < NumParams; ++p) { 733 ParmVarDecl *Param = FD->getParamDecl(p); 734 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 735 if (Param->isInvalidDecl()) 736 /* We already complained about this parameter. */; 737 else if (Param->getIdentifier()) 738 Diag(Param->getLocation(), 739 diag::err_param_default_argument_missing_name) 740 << Param->getIdentifier(); 741 else 742 Diag(Param->getLocation(), 743 diag::err_param_default_argument_missing); 744 745 LastMissingDefaultArg = p; 746 } 747 } 748 749 if (LastMissingDefaultArg > 0) { 750 // Some default arguments were missing. Clear out all of the 751 // default arguments up to (and including) the last missing 752 // default argument, so that we leave the function parameters 753 // in a semantically valid state. 754 for (p = 0; p <= LastMissingDefaultArg; ++p) { 755 ParmVarDecl *Param = FD->getParamDecl(p); 756 if (Param->hasDefaultArg()) { 757 Param->setDefaultArg(nullptr); 758 } 759 } 760 } 761 } 762 763 // CheckConstexprParameterTypes - Check whether a function's parameter types 764 // are all literal types. If so, return true. If not, produce a suitable 765 // diagnostic and return false. 766 static bool CheckConstexprParameterTypes(Sema &SemaRef, 767 const FunctionDecl *FD) { 768 unsigned ArgIndex = 0; 769 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 770 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 771 e = FT->param_type_end(); 772 i != e; ++i, ++ArgIndex) { 773 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 774 SourceLocation ParamLoc = PD->getLocation(); 775 if (!(*i)->isDependentType() && 776 SemaRef.RequireLiteralType(ParamLoc, *i, 777 diag::err_constexpr_non_literal_param, 778 ArgIndex+1, PD->getSourceRange(), 779 isa<CXXConstructorDecl>(FD))) 780 return false; 781 } 782 return true; 783 } 784 785 /// \brief Get diagnostic %select index for tag kind for 786 /// record diagnostic message. 787 /// WARNING: Indexes apply to particular diagnostics only! 788 /// 789 /// \returns diagnostic %select index. 790 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 791 switch (Tag) { 792 case TTK_Struct: return 0; 793 case TTK_Interface: return 1; 794 case TTK_Class: return 2; 795 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 796 } 797 } 798 799 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 800 // the requirements of a constexpr function definition or a constexpr 801 // constructor definition. If so, return true. If not, produce appropriate 802 // diagnostics and return false. 803 // 804 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 805 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 806 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 807 if (MD && MD->isInstance()) { 808 // C++11 [dcl.constexpr]p4: 809 // The definition of a constexpr constructor shall satisfy the following 810 // constraints: 811 // - the class shall not have any virtual base classes; 812 const CXXRecordDecl *RD = MD->getParent(); 813 if (RD->getNumVBases()) { 814 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 815 << isa<CXXConstructorDecl>(NewFD) 816 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 817 for (const auto &I : RD->vbases()) 818 Diag(I.getLocStart(), 819 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 820 return false; 821 } 822 } 823 824 if (!isa<CXXConstructorDecl>(NewFD)) { 825 // C++11 [dcl.constexpr]p3: 826 // The definition of a constexpr function shall satisfy the following 827 // constraints: 828 // - it shall not be virtual; 829 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 830 if (Method && Method->isVirtual()) { 831 Method = Method->getCanonicalDecl(); 832 Diag(Method->getLocation(), diag::err_constexpr_virtual); 833 834 // If it's not obvious why this function is virtual, find an overridden 835 // function which uses the 'virtual' keyword. 836 const CXXMethodDecl *WrittenVirtual = Method; 837 while (!WrittenVirtual->isVirtualAsWritten()) 838 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 839 if (WrittenVirtual != Method) 840 Diag(WrittenVirtual->getLocation(), 841 diag::note_overridden_virtual_function); 842 return false; 843 } 844 845 // - its return type shall be a literal type; 846 QualType RT = NewFD->getReturnType(); 847 if (!RT->isDependentType() && 848 RequireLiteralType(NewFD->getLocation(), RT, 849 diag::err_constexpr_non_literal_return)) 850 return false; 851 } 852 853 // - each of its parameter types shall be a literal type; 854 if (!CheckConstexprParameterTypes(*this, NewFD)) 855 return false; 856 857 return true; 858 } 859 860 /// Check the given declaration statement is legal within a constexpr function 861 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 862 /// 863 /// \return true if the body is OK (maybe only as an extension), false if we 864 /// have diagnosed a problem. 865 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 866 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 867 // C++11 [dcl.constexpr]p3 and p4: 868 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 869 // contain only 870 for (const auto *DclIt : DS->decls()) { 871 switch (DclIt->getKind()) { 872 case Decl::StaticAssert: 873 case Decl::Using: 874 case Decl::UsingShadow: 875 case Decl::UsingDirective: 876 case Decl::UnresolvedUsingTypename: 877 case Decl::UnresolvedUsingValue: 878 // - static_assert-declarations 879 // - using-declarations, 880 // - using-directives, 881 continue; 882 883 case Decl::Typedef: 884 case Decl::TypeAlias: { 885 // - typedef declarations and alias-declarations that do not define 886 // classes or enumerations, 887 const auto *TN = cast<TypedefNameDecl>(DclIt); 888 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 889 // Don't allow variably-modified types in constexpr functions. 890 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 891 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 892 << TL.getSourceRange() << TL.getType() 893 << isa<CXXConstructorDecl>(Dcl); 894 return false; 895 } 896 continue; 897 } 898 899 case Decl::Enum: 900 case Decl::CXXRecord: 901 // C++1y allows types to be defined, not just declared. 902 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 903 SemaRef.Diag(DS->getLocStart(), 904 SemaRef.getLangOpts().CPlusPlus14 905 ? diag::warn_cxx11_compat_constexpr_type_definition 906 : diag::ext_constexpr_type_definition) 907 << isa<CXXConstructorDecl>(Dcl); 908 continue; 909 910 case Decl::EnumConstant: 911 case Decl::IndirectField: 912 case Decl::ParmVar: 913 // These can only appear with other declarations which are banned in 914 // C++11 and permitted in C++1y, so ignore them. 915 continue; 916 917 case Decl::Var: { 918 // C++1y [dcl.constexpr]p3 allows anything except: 919 // a definition of a variable of non-literal type or of static or 920 // thread storage duration or for which no initialization is performed. 921 const auto *VD = cast<VarDecl>(DclIt); 922 if (VD->isThisDeclarationADefinition()) { 923 if (VD->isStaticLocal()) { 924 SemaRef.Diag(VD->getLocation(), 925 diag::err_constexpr_local_var_static) 926 << isa<CXXConstructorDecl>(Dcl) 927 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 928 return false; 929 } 930 if (!VD->getType()->isDependentType() && 931 SemaRef.RequireLiteralType( 932 VD->getLocation(), VD->getType(), 933 diag::err_constexpr_local_var_non_literal_type, 934 isa<CXXConstructorDecl>(Dcl))) 935 return false; 936 if (!VD->getType()->isDependentType() && 937 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 938 SemaRef.Diag(VD->getLocation(), 939 diag::err_constexpr_local_var_no_init) 940 << isa<CXXConstructorDecl>(Dcl); 941 return false; 942 } 943 } 944 SemaRef.Diag(VD->getLocation(), 945 SemaRef.getLangOpts().CPlusPlus14 946 ? diag::warn_cxx11_compat_constexpr_local_var 947 : diag::ext_constexpr_local_var) 948 << isa<CXXConstructorDecl>(Dcl); 949 continue; 950 } 951 952 case Decl::NamespaceAlias: 953 case Decl::Function: 954 // These are disallowed in C++11 and permitted in C++1y. Allow them 955 // everywhere as an extension. 956 if (!Cxx1yLoc.isValid()) 957 Cxx1yLoc = DS->getLocStart(); 958 continue; 959 960 default: 961 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 962 << isa<CXXConstructorDecl>(Dcl); 963 return false; 964 } 965 } 966 967 return true; 968 } 969 970 /// Check that the given field is initialized within a constexpr constructor. 971 /// 972 /// \param Dcl The constexpr constructor being checked. 973 /// \param Field The field being checked. This may be a member of an anonymous 974 /// struct or union nested within the class being checked. 975 /// \param Inits All declarations, including anonymous struct/union members and 976 /// indirect members, for which any initialization was provided. 977 /// \param Diagnosed Set to true if an error is produced. 978 static void CheckConstexprCtorInitializer(Sema &SemaRef, 979 const FunctionDecl *Dcl, 980 FieldDecl *Field, 981 llvm::SmallSet<Decl*, 16> &Inits, 982 bool &Diagnosed) { 983 if (Field->isInvalidDecl()) 984 return; 985 986 if (Field->isUnnamedBitfield()) 987 return; 988 989 // Anonymous unions with no variant members and empty anonymous structs do not 990 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 991 // indirect fields don't need initializing. 992 if (Field->isAnonymousStructOrUnion() && 993 (Field->getType()->isUnionType() 994 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 995 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 996 return; 997 998 if (!Inits.count(Field)) { 999 if (!Diagnosed) { 1000 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1001 Diagnosed = true; 1002 } 1003 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1004 } else if (Field->isAnonymousStructOrUnion()) { 1005 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1006 for (auto *I : RD->fields()) 1007 // If an anonymous union contains an anonymous struct of which any member 1008 // is initialized, all members must be initialized. 1009 if (!RD->isUnion() || Inits.count(I)) 1010 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1011 } 1012 } 1013 1014 /// Check the provided statement is allowed in a constexpr function 1015 /// definition. 1016 static bool 1017 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1018 SmallVectorImpl<SourceLocation> &ReturnStmts, 1019 SourceLocation &Cxx1yLoc) { 1020 // - its function-body shall be [...] a compound-statement that contains only 1021 switch (S->getStmtClass()) { 1022 case Stmt::NullStmtClass: 1023 // - null statements, 1024 return true; 1025 1026 case Stmt::DeclStmtClass: 1027 // - static_assert-declarations 1028 // - using-declarations, 1029 // - using-directives, 1030 // - typedef declarations and alias-declarations that do not define 1031 // classes or enumerations, 1032 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1033 return false; 1034 return true; 1035 1036 case Stmt::ReturnStmtClass: 1037 // - and exactly one return statement; 1038 if (isa<CXXConstructorDecl>(Dcl)) { 1039 // C++1y allows return statements in constexpr constructors. 1040 if (!Cxx1yLoc.isValid()) 1041 Cxx1yLoc = S->getLocStart(); 1042 return true; 1043 } 1044 1045 ReturnStmts.push_back(S->getLocStart()); 1046 return true; 1047 1048 case Stmt::CompoundStmtClass: { 1049 // C++1y allows compound-statements. 1050 if (!Cxx1yLoc.isValid()) 1051 Cxx1yLoc = S->getLocStart(); 1052 1053 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1054 for (auto *BodyIt : CompStmt->body()) { 1055 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1056 Cxx1yLoc)) 1057 return false; 1058 } 1059 return true; 1060 } 1061 1062 case Stmt::AttributedStmtClass: 1063 if (!Cxx1yLoc.isValid()) 1064 Cxx1yLoc = S->getLocStart(); 1065 return true; 1066 1067 case Stmt::IfStmtClass: { 1068 // C++1y allows if-statements. 1069 if (!Cxx1yLoc.isValid()) 1070 Cxx1yLoc = S->getLocStart(); 1071 1072 IfStmt *If = cast<IfStmt>(S); 1073 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1074 Cxx1yLoc)) 1075 return false; 1076 if (If->getElse() && 1077 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1078 Cxx1yLoc)) 1079 return false; 1080 return true; 1081 } 1082 1083 case Stmt::WhileStmtClass: 1084 case Stmt::DoStmtClass: 1085 case Stmt::ForStmtClass: 1086 case Stmt::CXXForRangeStmtClass: 1087 case Stmt::ContinueStmtClass: 1088 // C++1y allows all of these. We don't allow them as extensions in C++11, 1089 // because they don't make sense without variable mutation. 1090 if (!SemaRef.getLangOpts().CPlusPlus14) 1091 break; 1092 if (!Cxx1yLoc.isValid()) 1093 Cxx1yLoc = S->getLocStart(); 1094 for (Stmt::child_range Children = S->children(); Children; ++Children) 1095 if (*Children && 1096 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1097 Cxx1yLoc)) 1098 return false; 1099 return true; 1100 1101 case Stmt::SwitchStmtClass: 1102 case Stmt::CaseStmtClass: 1103 case Stmt::DefaultStmtClass: 1104 case Stmt::BreakStmtClass: 1105 // C++1y allows switch-statements, and since they don't need variable 1106 // mutation, we can reasonably allow them in C++11 as an extension. 1107 if (!Cxx1yLoc.isValid()) 1108 Cxx1yLoc = S->getLocStart(); 1109 for (Stmt::child_range Children = S->children(); Children; ++Children) 1110 if (*Children && 1111 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1112 Cxx1yLoc)) 1113 return false; 1114 return true; 1115 1116 default: 1117 if (!isa<Expr>(S)) 1118 break; 1119 1120 // C++1y allows expression-statements. 1121 if (!Cxx1yLoc.isValid()) 1122 Cxx1yLoc = S->getLocStart(); 1123 return true; 1124 } 1125 1126 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1127 << isa<CXXConstructorDecl>(Dcl); 1128 return false; 1129 } 1130 1131 /// Check the body for the given constexpr function declaration only contains 1132 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1133 /// 1134 /// \return true if the body is OK, false if we have diagnosed a problem. 1135 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1136 if (isa<CXXTryStmt>(Body)) { 1137 // C++11 [dcl.constexpr]p3: 1138 // The definition of a constexpr function shall satisfy the following 1139 // constraints: [...] 1140 // - its function-body shall be = delete, = default, or a 1141 // compound-statement 1142 // 1143 // C++11 [dcl.constexpr]p4: 1144 // In the definition of a constexpr constructor, [...] 1145 // - its function-body shall not be a function-try-block; 1146 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1147 << isa<CXXConstructorDecl>(Dcl); 1148 return false; 1149 } 1150 1151 SmallVector<SourceLocation, 4> ReturnStmts; 1152 1153 // - its function-body shall be [...] a compound-statement that contains only 1154 // [... list of cases ...] 1155 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1156 SourceLocation Cxx1yLoc; 1157 for (auto *BodyIt : CompBody->body()) { 1158 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1159 return false; 1160 } 1161 1162 if (Cxx1yLoc.isValid()) 1163 Diag(Cxx1yLoc, 1164 getLangOpts().CPlusPlus14 1165 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1166 : diag::ext_constexpr_body_invalid_stmt) 1167 << isa<CXXConstructorDecl>(Dcl); 1168 1169 if (const CXXConstructorDecl *Constructor 1170 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1171 const CXXRecordDecl *RD = Constructor->getParent(); 1172 // DR1359: 1173 // - every non-variant non-static data member and base class sub-object 1174 // shall be initialized; 1175 // DR1460: 1176 // - if the class is a union having variant members, exactly one of them 1177 // shall be initialized; 1178 if (RD->isUnion()) { 1179 if (Constructor->getNumCtorInitializers() == 0 && 1180 RD->hasVariantMembers()) { 1181 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1182 return false; 1183 } 1184 } else if (!Constructor->isDependentContext() && 1185 !Constructor->isDelegatingConstructor()) { 1186 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1187 1188 // Skip detailed checking if we have enough initializers, and we would 1189 // allow at most one initializer per member. 1190 bool AnyAnonStructUnionMembers = false; 1191 unsigned Fields = 0; 1192 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1193 E = RD->field_end(); I != E; ++I, ++Fields) { 1194 if (I->isAnonymousStructOrUnion()) { 1195 AnyAnonStructUnionMembers = true; 1196 break; 1197 } 1198 } 1199 // DR1460: 1200 // - if the class is a union-like class, but is not a union, for each of 1201 // its anonymous union members having variant members, exactly one of 1202 // them shall be initialized; 1203 if (AnyAnonStructUnionMembers || 1204 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1205 // Check initialization of non-static data members. Base classes are 1206 // always initialized so do not need to be checked. Dependent bases 1207 // might not have initializers in the member initializer list. 1208 llvm::SmallSet<Decl*, 16> Inits; 1209 for (const auto *I: Constructor->inits()) { 1210 if (FieldDecl *FD = I->getMember()) 1211 Inits.insert(FD); 1212 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1213 Inits.insert(ID->chain_begin(), ID->chain_end()); 1214 } 1215 1216 bool Diagnosed = false; 1217 for (auto *I : RD->fields()) 1218 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1219 if (Diagnosed) 1220 return false; 1221 } 1222 } 1223 } else { 1224 if (ReturnStmts.empty()) { 1225 // C++1y doesn't require constexpr functions to contain a 'return' 1226 // statement. We still do, unless the return type might be void, because 1227 // otherwise if there's no return statement, the function cannot 1228 // be used in a core constant expression. 1229 bool OK = getLangOpts().CPlusPlus14 && 1230 (Dcl->getReturnType()->isVoidType() || 1231 Dcl->getReturnType()->isDependentType()); 1232 Diag(Dcl->getLocation(), 1233 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1234 : diag::err_constexpr_body_no_return); 1235 return OK; 1236 } 1237 if (ReturnStmts.size() > 1) { 1238 Diag(ReturnStmts.back(), 1239 getLangOpts().CPlusPlus14 1240 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1241 : diag::ext_constexpr_body_multiple_return); 1242 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1243 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1244 } 1245 } 1246 1247 // C++11 [dcl.constexpr]p5: 1248 // if no function argument values exist such that the function invocation 1249 // substitution would produce a constant expression, the program is 1250 // ill-formed; no diagnostic required. 1251 // C++11 [dcl.constexpr]p3: 1252 // - every constructor call and implicit conversion used in initializing the 1253 // return value shall be one of those allowed in a constant expression. 1254 // C++11 [dcl.constexpr]p4: 1255 // - every constructor involved in initializing non-static data members and 1256 // base class sub-objects shall be a constexpr constructor. 1257 SmallVector<PartialDiagnosticAt, 8> Diags; 1258 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1259 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1260 << isa<CXXConstructorDecl>(Dcl); 1261 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1262 Diag(Diags[I].first, Diags[I].second); 1263 // Don't return false here: we allow this for compatibility in 1264 // system headers. 1265 } 1266 1267 return true; 1268 } 1269 1270 /// isCurrentClassName - Determine whether the identifier II is the 1271 /// name of the class type currently being defined. In the case of 1272 /// nested classes, this will only return true if II is the name of 1273 /// the innermost class. 1274 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1275 const CXXScopeSpec *SS) { 1276 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1277 1278 CXXRecordDecl *CurDecl; 1279 if (SS && SS->isSet() && !SS->isInvalid()) { 1280 DeclContext *DC = computeDeclContext(*SS, true); 1281 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1282 } else 1283 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1284 1285 if (CurDecl && CurDecl->getIdentifier()) 1286 return &II == CurDecl->getIdentifier(); 1287 return false; 1288 } 1289 1290 /// \brief Determine whether the identifier II is a typo for the name of 1291 /// the class type currently being defined. If so, update it to the identifier 1292 /// that should have been used. 1293 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1294 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1295 1296 if (!getLangOpts().SpellChecking) 1297 return false; 1298 1299 CXXRecordDecl *CurDecl; 1300 if (SS && SS->isSet() && !SS->isInvalid()) { 1301 DeclContext *DC = computeDeclContext(*SS, true); 1302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1303 } else 1304 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1305 1306 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1307 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1308 < II->getLength()) { 1309 II = CurDecl->getIdentifier(); 1310 return true; 1311 } 1312 1313 return false; 1314 } 1315 1316 /// \brief Determine whether the given class is a base class of the given 1317 /// class, including looking at dependent bases. 1318 static bool findCircularInheritance(const CXXRecordDecl *Class, 1319 const CXXRecordDecl *Current) { 1320 SmallVector<const CXXRecordDecl*, 8> Queue; 1321 1322 Class = Class->getCanonicalDecl(); 1323 while (true) { 1324 for (const auto &I : Current->bases()) { 1325 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1326 if (!Base) 1327 continue; 1328 1329 Base = Base->getDefinition(); 1330 if (!Base) 1331 continue; 1332 1333 if (Base->getCanonicalDecl() == Class) 1334 return true; 1335 1336 Queue.push_back(Base); 1337 } 1338 1339 if (Queue.empty()) 1340 return false; 1341 1342 Current = Queue.pop_back_val(); 1343 } 1344 1345 return false; 1346 } 1347 1348 /// \brief Perform propagation of DLL attributes from a derived class to a 1349 /// templated base class for MS compatibility. 1350 static void propagateDLLAttrToBaseClassTemplate( 1351 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1352 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1353 if (getDLLAttr( 1354 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1355 // If the base class template has a DLL attribute, don't try to change it. 1356 return; 1357 } 1358 1359 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1360 // If the base class is not already specialized, we can do the propagation. 1361 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1362 NewAttr->setInherited(true); 1363 BaseTemplateSpec->addAttr(NewAttr); 1364 return; 1365 } 1366 1367 bool DifferentAttribute = false; 1368 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1369 if (!SpecializationAttr->isInherited()) { 1370 // The template has previously been specialized or instantiated with an 1371 // explicit attribute. We should not try to change it. 1372 return; 1373 } 1374 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1375 // The specialization already has the right attribute. 1376 return; 1377 } 1378 DifferentAttribute = true; 1379 } 1380 1381 // The template was previously instantiated or explicitly specialized without 1382 // a dll attribute, or the template was previously instantiated with a 1383 // different inherited attribute. It's too late for us to change the 1384 // attribute, so warn that this is unsupported. 1385 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1386 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1387 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1388 if (BaseTemplateSpec->isExplicitSpecialization()) { 1389 S.Diag(BaseTemplateSpec->getLocation(), 1390 diag::note_template_class_explicit_specialization_was_here) 1391 << BaseTemplateSpec; 1392 } else { 1393 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1394 diag::note_template_class_instantiation_was_here) 1395 << BaseTemplateSpec; 1396 } 1397 } 1398 1399 /// \brief Check the validity of a C++ base class specifier. 1400 /// 1401 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1402 /// and returns NULL otherwise. 1403 CXXBaseSpecifier * 1404 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1405 SourceRange SpecifierRange, 1406 bool Virtual, AccessSpecifier Access, 1407 TypeSourceInfo *TInfo, 1408 SourceLocation EllipsisLoc) { 1409 QualType BaseType = TInfo->getType(); 1410 1411 // C++ [class.union]p1: 1412 // A union shall not have base classes. 1413 if (Class->isUnion()) { 1414 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1415 << SpecifierRange; 1416 return nullptr; 1417 } 1418 1419 if (EllipsisLoc.isValid() && 1420 !TInfo->getType()->containsUnexpandedParameterPack()) { 1421 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1422 << TInfo->getTypeLoc().getSourceRange(); 1423 EllipsisLoc = SourceLocation(); 1424 } 1425 1426 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1427 1428 if (BaseType->isDependentType()) { 1429 // Make sure that we don't have circular inheritance among our dependent 1430 // bases. For non-dependent bases, the check for completeness below handles 1431 // this. 1432 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1433 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1434 ((BaseDecl = BaseDecl->getDefinition()) && 1435 findCircularInheritance(Class, BaseDecl))) { 1436 Diag(BaseLoc, diag::err_circular_inheritance) 1437 << BaseType << Context.getTypeDeclType(Class); 1438 1439 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1440 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1441 << BaseType; 1442 1443 return nullptr; 1444 } 1445 } 1446 1447 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1448 Class->getTagKind() == TTK_Class, 1449 Access, TInfo, EllipsisLoc); 1450 } 1451 1452 // Base specifiers must be record types. 1453 if (!BaseType->isRecordType()) { 1454 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1455 return nullptr; 1456 } 1457 1458 // C++ [class.union]p1: 1459 // A union shall not be used as a base class. 1460 if (BaseType->isUnionType()) { 1461 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1462 return nullptr; 1463 } 1464 1465 // For the MS ABI, propagate DLL attributes to base class templates. 1466 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1467 if (Attr *ClassAttr = getDLLAttr(Class)) { 1468 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1469 BaseType->getAsCXXRecordDecl())) { 1470 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1471 BaseTemplate, BaseLoc); 1472 } 1473 } 1474 } 1475 1476 // C++ [class.derived]p2: 1477 // The class-name in a base-specifier shall not be an incompletely 1478 // defined class. 1479 if (RequireCompleteType(BaseLoc, BaseType, 1480 diag::err_incomplete_base_class, SpecifierRange)) { 1481 Class->setInvalidDecl(); 1482 return nullptr; 1483 } 1484 1485 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1486 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1487 assert(BaseDecl && "Record type has no declaration"); 1488 BaseDecl = BaseDecl->getDefinition(); 1489 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1490 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1491 assert(CXXBaseDecl && "Base type is not a C++ type"); 1492 1493 // A class which contains a flexible array member is not suitable for use as a 1494 // base class: 1495 // - If the layout determines that a base comes before another base, 1496 // the flexible array member would index into the subsequent base. 1497 // - If the layout determines that base comes before the derived class, 1498 // the flexible array member would index into the derived class. 1499 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1500 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1501 << CXXBaseDecl->getDeclName(); 1502 return nullptr; 1503 } 1504 1505 // C++ [class]p3: 1506 // If a class is marked final and it appears as a base-type-specifier in 1507 // base-clause, the program is ill-formed. 1508 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1509 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1510 << CXXBaseDecl->getDeclName() 1511 << FA->isSpelledAsSealed(); 1512 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1513 << CXXBaseDecl->getDeclName() << FA->getRange(); 1514 return nullptr; 1515 } 1516 1517 if (BaseDecl->isInvalidDecl()) 1518 Class->setInvalidDecl(); 1519 1520 // Create the base specifier. 1521 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1522 Class->getTagKind() == TTK_Class, 1523 Access, TInfo, EllipsisLoc); 1524 } 1525 1526 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1527 /// one entry in the base class list of a class specifier, for 1528 /// example: 1529 /// class foo : public bar, virtual private baz { 1530 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1531 BaseResult 1532 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1533 ParsedAttributes &Attributes, 1534 bool Virtual, AccessSpecifier Access, 1535 ParsedType basetype, SourceLocation BaseLoc, 1536 SourceLocation EllipsisLoc) { 1537 if (!classdecl) 1538 return true; 1539 1540 AdjustDeclIfTemplate(classdecl); 1541 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1542 if (!Class) 1543 return true; 1544 1545 // We haven't yet attached the base specifiers. 1546 Class->setIsParsingBaseSpecifiers(); 1547 1548 // We do not support any C++11 attributes on base-specifiers yet. 1549 // Diagnose any attributes we see. 1550 if (!Attributes.empty()) { 1551 for (AttributeList *Attr = Attributes.getList(); Attr; 1552 Attr = Attr->getNext()) { 1553 if (Attr->isInvalid() || 1554 Attr->getKind() == AttributeList::IgnoredAttribute) 1555 continue; 1556 Diag(Attr->getLoc(), 1557 Attr->getKind() == AttributeList::UnknownAttribute 1558 ? diag::warn_unknown_attribute_ignored 1559 : diag::err_base_specifier_attribute) 1560 << Attr->getName(); 1561 } 1562 } 1563 1564 TypeSourceInfo *TInfo = nullptr; 1565 GetTypeFromParser(basetype, &TInfo); 1566 1567 if (EllipsisLoc.isInvalid() && 1568 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1569 UPPC_BaseType)) 1570 return true; 1571 1572 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1573 Virtual, Access, TInfo, 1574 EllipsisLoc)) 1575 return BaseSpec; 1576 else 1577 Class->setInvalidDecl(); 1578 1579 return true; 1580 } 1581 1582 /// Use small set to collect indirect bases. As this is only used 1583 /// locally, there's no need to abstract the small size parameter. 1584 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 1585 1586 /// \brief Recursively add the bases of Type. Don't add Type itself. 1587 static void 1588 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 1589 const QualType &Type) 1590 { 1591 // Even though the incoming type is a base, it might not be 1592 // a class -- it could be a template parm, for instance. 1593 if (auto Rec = Type->getAs<RecordType>()) { 1594 auto Decl = Rec->getAsCXXRecordDecl(); 1595 1596 // Iterate over its bases. 1597 for (const auto &BaseSpec : Decl->bases()) { 1598 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 1599 .getUnqualifiedType(); 1600 if (Set.insert(Base).second) 1601 // If we've not already seen it, recurse. 1602 NoteIndirectBases(Context, Set, Base); 1603 } 1604 } 1605 } 1606 1607 /// \brief Performs the actual work of attaching the given base class 1608 /// specifiers to a C++ class. 1609 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1610 unsigned NumBases) { 1611 if (NumBases == 0) 1612 return false; 1613 1614 // Used to keep track of which base types we have already seen, so 1615 // that we can properly diagnose redundant direct base types. Note 1616 // that the key is always the unqualified canonical type of the base 1617 // class. 1618 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1619 1620 // Used to track indirect bases so we can see if a direct base is 1621 // ambiguous. 1622 IndirectBaseSet IndirectBaseTypes; 1623 1624 // Copy non-redundant base specifiers into permanent storage. 1625 unsigned NumGoodBases = 0; 1626 bool Invalid = false; 1627 for (unsigned idx = 0; idx < NumBases; ++idx) { 1628 QualType NewBaseType 1629 = Context.getCanonicalType(Bases[idx]->getType()); 1630 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1631 1632 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1633 if (KnownBase) { 1634 // C++ [class.mi]p3: 1635 // A class shall not be specified as a direct base class of a 1636 // derived class more than once. 1637 Diag(Bases[idx]->getLocStart(), 1638 diag::err_duplicate_base_class) 1639 << KnownBase->getType() 1640 << Bases[idx]->getSourceRange(); 1641 1642 // Delete the duplicate base class specifier; we're going to 1643 // overwrite its pointer later. 1644 Context.Deallocate(Bases[idx]); 1645 1646 Invalid = true; 1647 } else { 1648 // Okay, add this new base class. 1649 KnownBase = Bases[idx]; 1650 Bases[NumGoodBases++] = Bases[idx]; 1651 1652 // Note this base's direct & indirect bases, if there could be ambiguity. 1653 if (NumBases > 1) 1654 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 1655 1656 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1657 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1658 if (Class->isInterface() && 1659 (!RD->isInterface() || 1660 KnownBase->getAccessSpecifier() != AS_public)) { 1661 // The Microsoft extension __interface does not permit bases that 1662 // are not themselves public interfaces. 1663 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1664 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1665 << RD->getSourceRange(); 1666 Invalid = true; 1667 } 1668 if (RD->hasAttr<WeakAttr>()) 1669 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1670 } 1671 } 1672 } 1673 1674 // Attach the remaining base class specifiers to the derived class. 1675 Class->setBases(Bases, NumGoodBases); 1676 1677 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 1678 // Check whether this direct base is inaccessible due to ambiguity. 1679 QualType BaseType = Bases[idx]->getType(); 1680 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 1681 .getUnqualifiedType(); 1682 1683 if (IndirectBaseTypes.count(CanonicalBase)) { 1684 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1685 /*DetectVirtual=*/true); 1686 bool found 1687 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 1688 assert(found); 1689 (void)found; 1690 1691 if (Paths.isAmbiguous(CanonicalBase)) 1692 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 1693 << BaseType << getAmbiguousPathsDisplayString(Paths) 1694 << Bases[idx]->getSourceRange(); 1695 else 1696 assert(Bases[idx]->isVirtual()); 1697 } 1698 1699 // Delete the base class specifier, since its data has been copied 1700 // into the CXXRecordDecl. 1701 Context.Deallocate(Bases[idx]); 1702 } 1703 1704 return Invalid; 1705 } 1706 1707 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1708 /// class, after checking whether there are any duplicate base 1709 /// classes. 1710 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1711 unsigned NumBases) { 1712 if (!ClassDecl || !Bases || !NumBases) 1713 return; 1714 1715 AdjustDeclIfTemplate(ClassDecl); 1716 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1717 } 1718 1719 /// \brief Determine whether the type \p Derived is a C++ class that is 1720 /// derived from the type \p Base. 1721 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1722 if (!getLangOpts().CPlusPlus) 1723 return false; 1724 1725 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1726 if (!DerivedRD) 1727 return false; 1728 1729 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1730 if (!BaseRD) 1731 return false; 1732 1733 // If either the base or the derived type is invalid, don't try to 1734 // check whether one is derived from the other. 1735 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1736 return false; 1737 1738 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1739 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1740 } 1741 1742 /// \brief Determine whether the type \p Derived is a C++ class that is 1743 /// derived from the type \p Base. 1744 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1745 if (!getLangOpts().CPlusPlus) 1746 return false; 1747 1748 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1749 if (!DerivedRD) 1750 return false; 1751 1752 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1753 if (!BaseRD) 1754 return false; 1755 1756 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1757 } 1758 1759 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1760 CXXCastPath &BasePathArray) { 1761 assert(BasePathArray.empty() && "Base path array must be empty!"); 1762 assert(Paths.isRecordingPaths() && "Must record paths!"); 1763 1764 const CXXBasePath &Path = Paths.front(); 1765 1766 // We first go backward and check if we have a virtual base. 1767 // FIXME: It would be better if CXXBasePath had the base specifier for 1768 // the nearest virtual base. 1769 unsigned Start = 0; 1770 for (unsigned I = Path.size(); I != 0; --I) { 1771 if (Path[I - 1].Base->isVirtual()) { 1772 Start = I - 1; 1773 break; 1774 } 1775 } 1776 1777 // Now add all bases. 1778 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1779 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1780 } 1781 1782 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1783 /// conversion (where Derived and Base are class types) is 1784 /// well-formed, meaning that the conversion is unambiguous (and 1785 /// that all of the base classes are accessible). Returns true 1786 /// and emits a diagnostic if the code is ill-formed, returns false 1787 /// otherwise. Loc is the location where this routine should point to 1788 /// if there is an error, and Range is the source range to highlight 1789 /// if there is an error. 1790 bool 1791 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1792 unsigned InaccessibleBaseID, 1793 unsigned AmbigiousBaseConvID, 1794 SourceLocation Loc, SourceRange Range, 1795 DeclarationName Name, 1796 CXXCastPath *BasePath) { 1797 // First, determine whether the path from Derived to Base is 1798 // ambiguous. This is slightly more expensive than checking whether 1799 // the Derived to Base conversion exists, because here we need to 1800 // explore multiple paths to determine if there is an ambiguity. 1801 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1802 /*DetectVirtual=*/false); 1803 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1804 assert(DerivationOkay && 1805 "Can only be used with a derived-to-base conversion"); 1806 (void)DerivationOkay; 1807 1808 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1809 if (InaccessibleBaseID) { 1810 // Check that the base class can be accessed. 1811 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1812 InaccessibleBaseID)) { 1813 case AR_inaccessible: 1814 return true; 1815 case AR_accessible: 1816 case AR_dependent: 1817 case AR_delayed: 1818 break; 1819 } 1820 } 1821 1822 // Build a base path if necessary. 1823 if (BasePath) 1824 BuildBasePathArray(Paths, *BasePath); 1825 return false; 1826 } 1827 1828 if (AmbigiousBaseConvID) { 1829 // We know that the derived-to-base conversion is ambiguous, and 1830 // we're going to produce a diagnostic. Perform the derived-to-base 1831 // search just one more time to compute all of the possible paths so 1832 // that we can print them out. This is more expensive than any of 1833 // the previous derived-to-base checks we've done, but at this point 1834 // performance isn't as much of an issue. 1835 Paths.clear(); 1836 Paths.setRecordingPaths(true); 1837 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1838 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1839 (void)StillOkay; 1840 1841 // Build up a textual representation of the ambiguous paths, e.g., 1842 // D -> B -> A, that will be used to illustrate the ambiguous 1843 // conversions in the diagnostic. We only print one of the paths 1844 // to each base class subobject. 1845 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1846 1847 Diag(Loc, AmbigiousBaseConvID) 1848 << Derived << Base << PathDisplayStr << Range << Name; 1849 } 1850 return true; 1851 } 1852 1853 bool 1854 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1855 SourceLocation Loc, SourceRange Range, 1856 CXXCastPath *BasePath, 1857 bool IgnoreAccess) { 1858 return CheckDerivedToBaseConversion(Derived, Base, 1859 IgnoreAccess ? 0 1860 : diag::err_upcast_to_inaccessible_base, 1861 diag::err_ambiguous_derived_to_base_conv, 1862 Loc, Range, DeclarationName(), 1863 BasePath); 1864 } 1865 1866 1867 /// @brief Builds a string representing ambiguous paths from a 1868 /// specific derived class to different subobjects of the same base 1869 /// class. 1870 /// 1871 /// This function builds a string that can be used in error messages 1872 /// to show the different paths that one can take through the 1873 /// inheritance hierarchy to go from the derived class to different 1874 /// subobjects of a base class. The result looks something like this: 1875 /// @code 1876 /// struct D -> struct B -> struct A 1877 /// struct D -> struct C -> struct A 1878 /// @endcode 1879 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1880 std::string PathDisplayStr; 1881 std::set<unsigned> DisplayedPaths; 1882 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1883 Path != Paths.end(); ++Path) { 1884 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1885 // We haven't displayed a path to this particular base 1886 // class subobject yet. 1887 PathDisplayStr += "\n "; 1888 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1889 for (CXXBasePath::const_iterator Element = Path->begin(); 1890 Element != Path->end(); ++Element) 1891 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1892 } 1893 } 1894 1895 return PathDisplayStr; 1896 } 1897 1898 //===----------------------------------------------------------------------===// 1899 // C++ class member Handling 1900 //===----------------------------------------------------------------------===// 1901 1902 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1903 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1904 SourceLocation ASLoc, 1905 SourceLocation ColonLoc, 1906 AttributeList *Attrs) { 1907 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1908 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1909 ASLoc, ColonLoc); 1910 CurContext->addHiddenDecl(ASDecl); 1911 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1912 } 1913 1914 /// CheckOverrideControl - Check C++11 override control semantics. 1915 void Sema::CheckOverrideControl(NamedDecl *D) { 1916 if (D->isInvalidDecl()) 1917 return; 1918 1919 // We only care about "override" and "final" declarations. 1920 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1921 return; 1922 1923 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1924 1925 // We can't check dependent instance methods. 1926 if (MD && MD->isInstance() && 1927 (MD->getParent()->hasAnyDependentBases() || 1928 MD->getType()->isDependentType())) 1929 return; 1930 1931 if (MD && !MD->isVirtual()) { 1932 // If we have a non-virtual method, check if if hides a virtual method. 1933 // (In that case, it's most likely the method has the wrong type.) 1934 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1935 FindHiddenVirtualMethods(MD, OverloadedMethods); 1936 1937 if (!OverloadedMethods.empty()) { 1938 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1939 Diag(OA->getLocation(), 1940 diag::override_keyword_hides_virtual_member_function) 1941 << "override" << (OverloadedMethods.size() > 1); 1942 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1943 Diag(FA->getLocation(), 1944 diag::override_keyword_hides_virtual_member_function) 1945 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1946 << (OverloadedMethods.size() > 1); 1947 } 1948 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1949 MD->setInvalidDecl(); 1950 return; 1951 } 1952 // Fall through into the general case diagnostic. 1953 // FIXME: We might want to attempt typo correction here. 1954 } 1955 1956 if (!MD || !MD->isVirtual()) { 1957 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1958 Diag(OA->getLocation(), 1959 diag::override_keyword_only_allowed_on_virtual_member_functions) 1960 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1961 D->dropAttr<OverrideAttr>(); 1962 } 1963 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1964 Diag(FA->getLocation(), 1965 diag::override_keyword_only_allowed_on_virtual_member_functions) 1966 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1967 << FixItHint::CreateRemoval(FA->getLocation()); 1968 D->dropAttr<FinalAttr>(); 1969 } 1970 return; 1971 } 1972 1973 // C++11 [class.virtual]p5: 1974 // If a function is marked with the virt-specifier override and 1975 // does not override a member function of a base class, the program is 1976 // ill-formed. 1977 bool HasOverriddenMethods = 1978 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1979 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1980 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1981 << MD->getDeclName(); 1982 } 1983 1984 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1985 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1986 return; 1987 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1988 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1989 isa<CXXDestructorDecl>(MD)) 1990 return; 1991 1992 SourceLocation Loc = MD->getLocation(); 1993 SourceLocation SpellingLoc = Loc; 1994 if (getSourceManager().isMacroArgExpansion(Loc)) 1995 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1996 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1997 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1998 return; 1999 2000 if (MD->size_overridden_methods() > 0) { 2001 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 2002 << MD->getDeclName(); 2003 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2004 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2005 } 2006 } 2007 2008 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2009 /// function overrides a virtual member function marked 'final', according to 2010 /// C++11 [class.virtual]p4. 2011 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2012 const CXXMethodDecl *Old) { 2013 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2014 if (!FA) 2015 return false; 2016 2017 Diag(New->getLocation(), diag::err_final_function_overridden) 2018 << New->getDeclName() 2019 << FA->isSpelledAsSealed(); 2020 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2021 return true; 2022 } 2023 2024 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2025 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2026 // FIXME: Destruction of ObjC lifetime types has side-effects. 2027 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2028 return !RD->isCompleteDefinition() || 2029 !RD->hasTrivialDefaultConstructor() || 2030 !RD->hasTrivialDestructor(); 2031 return false; 2032 } 2033 2034 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2035 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2036 if (it->isDeclspecPropertyAttribute()) 2037 return it; 2038 return nullptr; 2039 } 2040 2041 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2042 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2043 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2044 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2045 /// present (but parsing it has been deferred). 2046 NamedDecl * 2047 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2048 MultiTemplateParamsArg TemplateParameterLists, 2049 Expr *BW, const VirtSpecifiers &VS, 2050 InClassInitStyle InitStyle) { 2051 const DeclSpec &DS = D.getDeclSpec(); 2052 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2053 DeclarationName Name = NameInfo.getName(); 2054 SourceLocation Loc = NameInfo.getLoc(); 2055 2056 // For anonymous bitfields, the location should point to the type. 2057 if (Loc.isInvalid()) 2058 Loc = D.getLocStart(); 2059 2060 Expr *BitWidth = static_cast<Expr*>(BW); 2061 2062 assert(isa<CXXRecordDecl>(CurContext)); 2063 assert(!DS.isFriendSpecified()); 2064 2065 bool isFunc = D.isDeclarationOfFunction(); 2066 2067 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2068 // The Microsoft extension __interface only permits public member functions 2069 // and prohibits constructors, destructors, operators, non-public member 2070 // functions, static methods and data members. 2071 unsigned InvalidDecl; 2072 bool ShowDeclName = true; 2073 if (!isFunc) 2074 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2075 else if (AS != AS_public) 2076 InvalidDecl = 2; 2077 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2078 InvalidDecl = 3; 2079 else switch (Name.getNameKind()) { 2080 case DeclarationName::CXXConstructorName: 2081 InvalidDecl = 4; 2082 ShowDeclName = false; 2083 break; 2084 2085 case DeclarationName::CXXDestructorName: 2086 InvalidDecl = 5; 2087 ShowDeclName = false; 2088 break; 2089 2090 case DeclarationName::CXXOperatorName: 2091 case DeclarationName::CXXConversionFunctionName: 2092 InvalidDecl = 6; 2093 break; 2094 2095 default: 2096 InvalidDecl = 0; 2097 break; 2098 } 2099 2100 if (InvalidDecl) { 2101 if (ShowDeclName) 2102 Diag(Loc, diag::err_invalid_member_in_interface) 2103 << (InvalidDecl-1) << Name; 2104 else 2105 Diag(Loc, diag::err_invalid_member_in_interface) 2106 << (InvalidDecl-1) << ""; 2107 return nullptr; 2108 } 2109 } 2110 2111 // C++ 9.2p6: A member shall not be declared to have automatic storage 2112 // duration (auto, register) or with the extern storage-class-specifier. 2113 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2114 // data members and cannot be applied to names declared const or static, 2115 // and cannot be applied to reference members. 2116 switch (DS.getStorageClassSpec()) { 2117 case DeclSpec::SCS_unspecified: 2118 case DeclSpec::SCS_typedef: 2119 case DeclSpec::SCS_static: 2120 break; 2121 case DeclSpec::SCS_mutable: 2122 if (isFunc) { 2123 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2124 2125 // FIXME: It would be nicer if the keyword was ignored only for this 2126 // declarator. Otherwise we could get follow-up errors. 2127 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2128 } 2129 break; 2130 default: 2131 Diag(DS.getStorageClassSpecLoc(), 2132 diag::err_storageclass_invalid_for_member); 2133 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2134 break; 2135 } 2136 2137 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2138 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2139 !isFunc); 2140 2141 if (DS.isConstexprSpecified() && isInstField) { 2142 SemaDiagnosticBuilder B = 2143 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2144 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2145 if (InitStyle == ICIS_NoInit) { 2146 B << 0 << 0; 2147 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2148 B << FixItHint::CreateRemoval(ConstexprLoc); 2149 else { 2150 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2151 D.getMutableDeclSpec().ClearConstexprSpec(); 2152 const char *PrevSpec; 2153 unsigned DiagID; 2154 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2155 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2156 (void)Failed; 2157 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2158 } 2159 } else { 2160 B << 1; 2161 const char *PrevSpec; 2162 unsigned DiagID; 2163 if (D.getMutableDeclSpec().SetStorageClassSpec( 2164 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2165 Context.getPrintingPolicy())) { 2166 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2167 "This is the only DeclSpec that should fail to be applied"); 2168 B << 1; 2169 } else { 2170 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2171 isInstField = false; 2172 } 2173 } 2174 } 2175 2176 NamedDecl *Member; 2177 if (isInstField) { 2178 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2179 2180 // Data members must have identifiers for names. 2181 if (!Name.isIdentifier()) { 2182 Diag(Loc, diag::err_bad_variable_name) 2183 << Name; 2184 return nullptr; 2185 } 2186 2187 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2188 2189 // Member field could not be with "template" keyword. 2190 // So TemplateParameterLists should be empty in this case. 2191 if (TemplateParameterLists.size()) { 2192 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2193 if (TemplateParams->size()) { 2194 // There is no such thing as a member field template. 2195 Diag(D.getIdentifierLoc(), diag::err_template_member) 2196 << II 2197 << SourceRange(TemplateParams->getTemplateLoc(), 2198 TemplateParams->getRAngleLoc()); 2199 } else { 2200 // There is an extraneous 'template<>' for this member. 2201 Diag(TemplateParams->getTemplateLoc(), 2202 diag::err_template_member_noparams) 2203 << II 2204 << SourceRange(TemplateParams->getTemplateLoc(), 2205 TemplateParams->getRAngleLoc()); 2206 } 2207 return nullptr; 2208 } 2209 2210 if (SS.isSet() && !SS.isInvalid()) { 2211 // The user provided a superfluous scope specifier inside a class 2212 // definition: 2213 // 2214 // class X { 2215 // int X::member; 2216 // }; 2217 if (DeclContext *DC = computeDeclContext(SS, false)) 2218 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2219 else 2220 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2221 << Name << SS.getRange(); 2222 2223 SS.clear(); 2224 } 2225 2226 AttributeList *MSPropertyAttr = 2227 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2228 if (MSPropertyAttr) { 2229 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2230 BitWidth, InitStyle, AS, MSPropertyAttr); 2231 if (!Member) 2232 return nullptr; 2233 isInstField = false; 2234 } else { 2235 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2236 BitWidth, InitStyle, AS); 2237 assert(Member && "HandleField never returns null"); 2238 } 2239 } else { 2240 assert(InitStyle == ICIS_NoInit || 2241 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2242 2243 Member = HandleDeclarator(S, D, TemplateParameterLists); 2244 if (!Member) 2245 return nullptr; 2246 2247 // Non-instance-fields can't have a bitfield. 2248 if (BitWidth) { 2249 if (Member->isInvalidDecl()) { 2250 // don't emit another diagnostic. 2251 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 2252 // C++ 9.6p3: A bit-field shall not be a static member. 2253 // "static member 'A' cannot be a bit-field" 2254 Diag(Loc, diag::err_static_not_bitfield) 2255 << Name << BitWidth->getSourceRange(); 2256 } else if (isa<TypedefDecl>(Member)) { 2257 // "typedef member 'x' cannot be a bit-field" 2258 Diag(Loc, diag::err_typedef_not_bitfield) 2259 << Name << BitWidth->getSourceRange(); 2260 } else { 2261 // A function typedef ("typedef int f(); f a;"). 2262 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2263 Diag(Loc, diag::err_not_integral_type_bitfield) 2264 << Name << cast<ValueDecl>(Member)->getType() 2265 << BitWidth->getSourceRange(); 2266 } 2267 2268 BitWidth = nullptr; 2269 Member->setInvalidDecl(); 2270 } 2271 2272 Member->setAccess(AS); 2273 2274 // If we have declared a member function template or static data member 2275 // template, set the access of the templated declaration as well. 2276 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2277 FunTmpl->getTemplatedDecl()->setAccess(AS); 2278 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2279 VarTmpl->getTemplatedDecl()->setAccess(AS); 2280 } 2281 2282 if (VS.isOverrideSpecified()) 2283 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2284 if (VS.isFinalSpecified()) 2285 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2286 VS.isFinalSpelledSealed())); 2287 2288 if (VS.getLastLocation().isValid()) { 2289 // Update the end location of a method that has a virt-specifiers. 2290 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2291 MD->setRangeEnd(VS.getLastLocation()); 2292 } 2293 2294 CheckOverrideControl(Member); 2295 2296 assert((Name || isInstField) && "No identifier for non-field ?"); 2297 2298 if (isInstField) { 2299 FieldDecl *FD = cast<FieldDecl>(Member); 2300 FieldCollector->Add(FD); 2301 2302 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2303 // Remember all explicit private FieldDecls that have a name, no side 2304 // effects and are not part of a dependent type declaration. 2305 if (!FD->isImplicit() && FD->getDeclName() && 2306 FD->getAccess() == AS_private && 2307 !FD->hasAttr<UnusedAttr>() && 2308 !FD->getParent()->isDependentContext() && 2309 !InitializationHasSideEffects(*FD)) 2310 UnusedPrivateFields.insert(FD); 2311 } 2312 } 2313 2314 return Member; 2315 } 2316 2317 namespace { 2318 class UninitializedFieldVisitor 2319 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2320 Sema &S; 2321 // List of Decls to generate a warning on. Also remove Decls that become 2322 // initialized. 2323 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2324 // List of base classes of the record. Classes are removed after their 2325 // initializers. 2326 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 2327 // Vector of decls to be removed from the Decl set prior to visiting the 2328 // nodes. These Decls may have been initialized in the prior initializer. 2329 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2330 // If non-null, add a note to the warning pointing back to the constructor. 2331 const CXXConstructorDecl *Constructor; 2332 // Variables to hold state when processing an initializer list. When 2333 // InitList is true, special case initialization of FieldDecls matching 2334 // InitListFieldDecl. 2335 bool InitList; 2336 FieldDecl *InitListFieldDecl; 2337 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2338 2339 public: 2340 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2341 UninitializedFieldVisitor(Sema &S, 2342 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 2343 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 2344 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 2345 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 2346 2347 // Returns true if the use of ME is not an uninitialized use. 2348 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2349 bool CheckReferenceOnly) { 2350 llvm::SmallVector<FieldDecl*, 4> Fields; 2351 bool ReferenceField = false; 2352 while (ME) { 2353 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2354 if (!FD) 2355 return false; 2356 Fields.push_back(FD); 2357 if (FD->getType()->isReferenceType()) 2358 ReferenceField = true; 2359 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2360 } 2361 2362 // Binding a reference to an unintialized field is not an 2363 // uninitialized use. 2364 if (CheckReferenceOnly && !ReferenceField) 2365 return true; 2366 2367 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2368 // Discard the first field since it is the field decl that is being 2369 // initialized. 2370 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2371 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2372 } 2373 2374 for (auto UsedIter = UsedFieldIndex.begin(), 2375 UsedEnd = UsedFieldIndex.end(), 2376 OrigIter = InitFieldIndex.begin(), 2377 OrigEnd = InitFieldIndex.end(); 2378 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2379 if (*UsedIter < *OrigIter) 2380 return true; 2381 if (*UsedIter > *OrigIter) 2382 break; 2383 } 2384 2385 return false; 2386 } 2387 2388 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2389 bool AddressOf) { 2390 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2391 return; 2392 2393 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2394 // or union. 2395 MemberExpr *FieldME = ME; 2396 2397 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2398 2399 Expr *Base = ME; 2400 while (MemberExpr *SubME = 2401 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 2402 2403 if (isa<VarDecl>(SubME->getMemberDecl())) 2404 return; 2405 2406 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2407 if (!FD->isAnonymousStructOrUnion()) 2408 FieldME = SubME; 2409 2410 if (!FieldME->getType().isPODType(S.Context)) 2411 AllPODFields = false; 2412 2413 Base = SubME->getBase(); 2414 } 2415 2416 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 2417 return; 2418 2419 if (AddressOf && AllPODFields) 2420 return; 2421 2422 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2423 2424 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 2425 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 2426 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 2427 } 2428 2429 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 2430 QualType T = BaseCast->getType(); 2431 if (T->isPointerType() && 2432 BaseClasses.count(T->getPointeeType())) { 2433 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 2434 << T->getPointeeType() << FoundVD; 2435 } 2436 } 2437 } 2438 2439 if (!Decls.count(FoundVD)) 2440 return; 2441 2442 const bool IsReference = FoundVD->getType()->isReferenceType(); 2443 2444 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2445 // Special checking for initializer lists. 2446 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2447 return; 2448 } 2449 } else { 2450 // Prevent double warnings on use of unbounded references. 2451 if (CheckReferenceOnly && !IsReference) 2452 return; 2453 } 2454 2455 unsigned diag = IsReference 2456 ? diag::warn_reference_field_is_uninit 2457 : diag::warn_field_is_uninit; 2458 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2459 if (Constructor) 2460 S.Diag(Constructor->getLocation(), 2461 diag::note_uninit_in_this_constructor) 2462 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2463 2464 } 2465 2466 void HandleValue(Expr *E, bool AddressOf) { 2467 E = E->IgnoreParens(); 2468 2469 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2470 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2471 AddressOf /*AddressOf*/); 2472 return; 2473 } 2474 2475 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2476 Visit(CO->getCond()); 2477 HandleValue(CO->getTrueExpr(), AddressOf); 2478 HandleValue(CO->getFalseExpr(), AddressOf); 2479 return; 2480 } 2481 2482 if (BinaryConditionalOperator *BCO = 2483 dyn_cast<BinaryConditionalOperator>(E)) { 2484 Visit(BCO->getCond()); 2485 HandleValue(BCO->getFalseExpr(), AddressOf); 2486 return; 2487 } 2488 2489 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2490 HandleValue(OVE->getSourceExpr(), AddressOf); 2491 return; 2492 } 2493 2494 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2495 switch (BO->getOpcode()) { 2496 default: 2497 break; 2498 case(BO_PtrMemD): 2499 case(BO_PtrMemI): 2500 HandleValue(BO->getLHS(), AddressOf); 2501 Visit(BO->getRHS()); 2502 return; 2503 case(BO_Comma): 2504 Visit(BO->getLHS()); 2505 HandleValue(BO->getRHS(), AddressOf); 2506 return; 2507 } 2508 } 2509 2510 Visit(E); 2511 } 2512 2513 void CheckInitListExpr(InitListExpr *ILE) { 2514 InitFieldIndex.push_back(0); 2515 for (auto Child : ILE->children()) { 2516 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2517 CheckInitListExpr(SubList); 2518 } else { 2519 Visit(Child); 2520 } 2521 ++InitFieldIndex.back(); 2522 } 2523 InitFieldIndex.pop_back(); 2524 } 2525 2526 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2527 FieldDecl *Field, const Type *BaseClass) { 2528 // Remove Decls that may have been initialized in the previous 2529 // initializer. 2530 for (ValueDecl* VD : DeclsToRemove) 2531 Decls.erase(VD); 2532 DeclsToRemove.clear(); 2533 2534 Constructor = FieldConstructor; 2535 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2536 2537 if (ILE && Field) { 2538 InitList = true; 2539 InitListFieldDecl = Field; 2540 InitFieldIndex.clear(); 2541 CheckInitListExpr(ILE); 2542 } else { 2543 InitList = false; 2544 Visit(E); 2545 } 2546 2547 if (Field) 2548 Decls.erase(Field); 2549 if (BaseClass) 2550 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 2551 } 2552 2553 void VisitMemberExpr(MemberExpr *ME) { 2554 // All uses of unbounded reference fields will warn. 2555 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2556 } 2557 2558 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2559 if (E->getCastKind() == CK_LValueToRValue) { 2560 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2561 return; 2562 } 2563 2564 Inherited::VisitImplicitCastExpr(E); 2565 } 2566 2567 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2568 if (E->getConstructor()->isCopyConstructor()) { 2569 Expr *ArgExpr = E->getArg(0); 2570 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2571 if (ILE->getNumInits() == 1) 2572 ArgExpr = ILE->getInit(0); 2573 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2574 if (ICE->getCastKind() == CK_NoOp) 2575 ArgExpr = ICE->getSubExpr(); 2576 HandleValue(ArgExpr, false /*AddressOf*/); 2577 return; 2578 } 2579 Inherited::VisitCXXConstructExpr(E); 2580 } 2581 2582 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2583 Expr *Callee = E->getCallee(); 2584 if (isa<MemberExpr>(Callee)) { 2585 HandleValue(Callee, false /*AddressOf*/); 2586 for (auto Arg : E->arguments()) 2587 Visit(Arg); 2588 return; 2589 } 2590 2591 Inherited::VisitCXXMemberCallExpr(E); 2592 } 2593 2594 void VisitCallExpr(CallExpr *E) { 2595 // Treat std::move as a use. 2596 if (E->getNumArgs() == 1) { 2597 if (FunctionDecl *FD = E->getDirectCallee()) { 2598 if (FD->isInStdNamespace() && FD->getIdentifier() && 2599 FD->getIdentifier()->isStr("move")) { 2600 HandleValue(E->getArg(0), false /*AddressOf*/); 2601 return; 2602 } 2603 } 2604 } 2605 2606 Inherited::VisitCallExpr(E); 2607 } 2608 2609 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2610 Expr *Callee = E->getCallee(); 2611 2612 if (isa<UnresolvedLookupExpr>(Callee)) 2613 return Inherited::VisitCXXOperatorCallExpr(E); 2614 2615 Visit(Callee); 2616 for (auto Arg : E->arguments()) 2617 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2618 } 2619 2620 void VisitBinaryOperator(BinaryOperator *E) { 2621 // If a field assignment is detected, remove the field from the 2622 // uninitiailized field set. 2623 if (E->getOpcode() == BO_Assign) 2624 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2625 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2626 if (!FD->getType()->isReferenceType()) 2627 DeclsToRemove.push_back(FD); 2628 2629 if (E->isCompoundAssignmentOp()) { 2630 HandleValue(E->getLHS(), false /*AddressOf*/); 2631 Visit(E->getRHS()); 2632 return; 2633 } 2634 2635 Inherited::VisitBinaryOperator(E); 2636 } 2637 2638 void VisitUnaryOperator(UnaryOperator *E) { 2639 if (E->isIncrementDecrementOp()) { 2640 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2641 return; 2642 } 2643 if (E->getOpcode() == UO_AddrOf) { 2644 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2645 HandleValue(ME->getBase(), true /*AddressOf*/); 2646 return; 2647 } 2648 } 2649 2650 Inherited::VisitUnaryOperator(E); 2651 } 2652 }; 2653 2654 // Diagnose value-uses of fields to initialize themselves, e.g. 2655 // foo(foo) 2656 // where foo is not also a parameter to the constructor. 2657 // Also diagnose across field uninitialized use such as 2658 // x(y), y(x) 2659 // TODO: implement -Wuninitialized and fold this into that framework. 2660 static void DiagnoseUninitializedFields( 2661 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2662 2663 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2664 Constructor->getLocation())) { 2665 return; 2666 } 2667 2668 if (Constructor->isInvalidDecl()) 2669 return; 2670 2671 const CXXRecordDecl *RD = Constructor->getParent(); 2672 2673 if (RD->getDescribedClassTemplate()) 2674 return; 2675 2676 // Holds fields that are uninitialized. 2677 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2678 2679 // At the beginning, all fields are uninitialized. 2680 for (auto *I : RD->decls()) { 2681 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2682 UninitializedFields.insert(FD); 2683 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2684 UninitializedFields.insert(IFD->getAnonField()); 2685 } 2686 } 2687 2688 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 2689 for (auto I : RD->bases()) 2690 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 2691 2692 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2693 return; 2694 2695 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2696 UninitializedFields, 2697 UninitializedBaseClasses); 2698 2699 for (const auto *FieldInit : Constructor->inits()) { 2700 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2701 break; 2702 2703 Expr *InitExpr = FieldInit->getInit(); 2704 if (!InitExpr) 2705 continue; 2706 2707 if (CXXDefaultInitExpr *Default = 2708 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2709 InitExpr = Default->getExpr(); 2710 if (!InitExpr) 2711 continue; 2712 // In class initializers will point to the constructor. 2713 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2714 FieldInit->getAnyMember(), 2715 FieldInit->getBaseClass()); 2716 } else { 2717 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2718 FieldInit->getAnyMember(), 2719 FieldInit->getBaseClass()); 2720 } 2721 } 2722 } 2723 } // namespace 2724 2725 /// \brief Enter a new C++ default initializer scope. After calling this, the 2726 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2727 /// parsing or instantiating the initializer failed. 2728 void Sema::ActOnStartCXXInClassMemberInitializer() { 2729 // Create a synthetic function scope to represent the call to the constructor 2730 // that notionally surrounds a use of this initializer. 2731 PushFunctionScope(); 2732 } 2733 2734 /// \brief This is invoked after parsing an in-class initializer for a 2735 /// non-static C++ class member, and after instantiating an in-class initializer 2736 /// in a class template. Such actions are deferred until the class is complete. 2737 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2738 SourceLocation InitLoc, 2739 Expr *InitExpr) { 2740 // Pop the notional constructor scope we created earlier. 2741 PopFunctionScopeInfo(nullptr, D); 2742 2743 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2744 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 2745 "must set init style when field is created"); 2746 2747 if (!InitExpr) { 2748 D->setInvalidDecl(); 2749 if (FD) 2750 FD->removeInClassInitializer(); 2751 return; 2752 } 2753 2754 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2755 FD->setInvalidDecl(); 2756 FD->removeInClassInitializer(); 2757 return; 2758 } 2759 2760 ExprResult Init = InitExpr; 2761 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2762 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2763 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2764 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2765 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2766 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2767 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2768 if (Init.isInvalid()) { 2769 FD->setInvalidDecl(); 2770 return; 2771 } 2772 } 2773 2774 // C++11 [class.base.init]p7: 2775 // The initialization of each base and member constitutes a 2776 // full-expression. 2777 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2778 if (Init.isInvalid()) { 2779 FD->setInvalidDecl(); 2780 return; 2781 } 2782 2783 InitExpr = Init.get(); 2784 2785 FD->setInClassInitializer(InitExpr); 2786 } 2787 2788 /// \brief Find the direct and/or virtual base specifiers that 2789 /// correspond to the given base type, for use in base initialization 2790 /// within a constructor. 2791 static bool FindBaseInitializer(Sema &SemaRef, 2792 CXXRecordDecl *ClassDecl, 2793 QualType BaseType, 2794 const CXXBaseSpecifier *&DirectBaseSpec, 2795 const CXXBaseSpecifier *&VirtualBaseSpec) { 2796 // First, check for a direct base class. 2797 DirectBaseSpec = nullptr; 2798 for (const auto &Base : ClassDecl->bases()) { 2799 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2800 // We found a direct base of this type. That's what we're 2801 // initializing. 2802 DirectBaseSpec = &Base; 2803 break; 2804 } 2805 } 2806 2807 // Check for a virtual base class. 2808 // FIXME: We might be able to short-circuit this if we know in advance that 2809 // there are no virtual bases. 2810 VirtualBaseSpec = nullptr; 2811 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2812 // We haven't found a base yet; search the class hierarchy for a 2813 // virtual base class. 2814 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2815 /*DetectVirtual=*/false); 2816 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2817 BaseType, Paths)) { 2818 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2819 Path != Paths.end(); ++Path) { 2820 if (Path->back().Base->isVirtual()) { 2821 VirtualBaseSpec = Path->back().Base; 2822 break; 2823 } 2824 } 2825 } 2826 } 2827 2828 return DirectBaseSpec || VirtualBaseSpec; 2829 } 2830 2831 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2832 MemInitResult 2833 Sema::ActOnMemInitializer(Decl *ConstructorD, 2834 Scope *S, 2835 CXXScopeSpec &SS, 2836 IdentifierInfo *MemberOrBase, 2837 ParsedType TemplateTypeTy, 2838 const DeclSpec &DS, 2839 SourceLocation IdLoc, 2840 Expr *InitList, 2841 SourceLocation EllipsisLoc) { 2842 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2843 DS, IdLoc, InitList, 2844 EllipsisLoc); 2845 } 2846 2847 /// \brief Handle a C++ member initializer using parentheses syntax. 2848 MemInitResult 2849 Sema::ActOnMemInitializer(Decl *ConstructorD, 2850 Scope *S, 2851 CXXScopeSpec &SS, 2852 IdentifierInfo *MemberOrBase, 2853 ParsedType TemplateTypeTy, 2854 const DeclSpec &DS, 2855 SourceLocation IdLoc, 2856 SourceLocation LParenLoc, 2857 ArrayRef<Expr *> Args, 2858 SourceLocation RParenLoc, 2859 SourceLocation EllipsisLoc) { 2860 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2861 Args, RParenLoc); 2862 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2863 DS, IdLoc, List, EllipsisLoc); 2864 } 2865 2866 namespace { 2867 2868 // Callback to only accept typo corrections that can be a valid C++ member 2869 // intializer: either a non-static field member or a base class. 2870 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2871 public: 2872 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2873 : ClassDecl(ClassDecl) {} 2874 2875 bool ValidateCandidate(const TypoCorrection &candidate) override { 2876 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2877 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2878 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2879 return isa<TypeDecl>(ND); 2880 } 2881 return false; 2882 } 2883 2884 private: 2885 CXXRecordDecl *ClassDecl; 2886 }; 2887 2888 } 2889 2890 /// \brief Handle a C++ member initializer. 2891 MemInitResult 2892 Sema::BuildMemInitializer(Decl *ConstructorD, 2893 Scope *S, 2894 CXXScopeSpec &SS, 2895 IdentifierInfo *MemberOrBase, 2896 ParsedType TemplateTypeTy, 2897 const DeclSpec &DS, 2898 SourceLocation IdLoc, 2899 Expr *Init, 2900 SourceLocation EllipsisLoc) { 2901 ExprResult Res = CorrectDelayedTyposInExpr(Init); 2902 if (!Res.isUsable()) 2903 return true; 2904 Init = Res.get(); 2905 2906 if (!ConstructorD) 2907 return true; 2908 2909 AdjustDeclIfTemplate(ConstructorD); 2910 2911 CXXConstructorDecl *Constructor 2912 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2913 if (!Constructor) { 2914 // The user wrote a constructor initializer on a function that is 2915 // not a C++ constructor. Ignore the error for now, because we may 2916 // have more member initializers coming; we'll diagnose it just 2917 // once in ActOnMemInitializers. 2918 return true; 2919 } 2920 2921 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2922 2923 // C++ [class.base.init]p2: 2924 // Names in a mem-initializer-id are looked up in the scope of the 2925 // constructor's class and, if not found in that scope, are looked 2926 // up in the scope containing the constructor's definition. 2927 // [Note: if the constructor's class contains a member with the 2928 // same name as a direct or virtual base class of the class, a 2929 // mem-initializer-id naming the member or base class and composed 2930 // of a single identifier refers to the class member. A 2931 // mem-initializer-id for the hidden base class may be specified 2932 // using a qualified name. ] 2933 if (!SS.getScopeRep() && !TemplateTypeTy) { 2934 // Look for a member, first. 2935 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2936 if (!Result.empty()) { 2937 ValueDecl *Member; 2938 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2939 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2940 if (EllipsisLoc.isValid()) 2941 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2942 << MemberOrBase 2943 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2944 2945 return BuildMemberInitializer(Member, Init, IdLoc); 2946 } 2947 } 2948 } 2949 // It didn't name a member, so see if it names a class. 2950 QualType BaseType; 2951 TypeSourceInfo *TInfo = nullptr; 2952 2953 if (TemplateTypeTy) { 2954 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2955 } else if (DS.getTypeSpecType() == TST_decltype) { 2956 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2957 } else { 2958 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2959 LookupParsedName(R, S, &SS); 2960 2961 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2962 if (!TyD) { 2963 if (R.isAmbiguous()) return true; 2964 2965 // We don't want access-control diagnostics here. 2966 R.suppressDiagnostics(); 2967 2968 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2969 bool NotUnknownSpecialization = false; 2970 DeclContext *DC = computeDeclContext(SS, false); 2971 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2972 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2973 2974 if (!NotUnknownSpecialization) { 2975 // When the scope specifier can refer to a member of an unknown 2976 // specialization, we take it as a type name. 2977 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2978 SS.getWithLocInContext(Context), 2979 *MemberOrBase, IdLoc); 2980 if (BaseType.isNull()) 2981 return true; 2982 2983 R.clear(); 2984 R.setLookupName(MemberOrBase); 2985 } 2986 } 2987 2988 // If no results were found, try to correct typos. 2989 TypoCorrection Corr; 2990 if (R.empty() && BaseType.isNull() && 2991 (Corr = CorrectTypo( 2992 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2993 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2994 CTK_ErrorRecovery, ClassDecl))) { 2995 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2996 // We have found a non-static data member with a similar 2997 // name to what was typed; complain and initialize that 2998 // member. 2999 diagnoseTypo(Corr, 3000 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3001 << MemberOrBase << true); 3002 return BuildMemberInitializer(Member, Init, IdLoc); 3003 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3004 const CXXBaseSpecifier *DirectBaseSpec; 3005 const CXXBaseSpecifier *VirtualBaseSpec; 3006 if (FindBaseInitializer(*this, ClassDecl, 3007 Context.getTypeDeclType(Type), 3008 DirectBaseSpec, VirtualBaseSpec)) { 3009 // We have found a direct or virtual base class with a 3010 // similar name to what was typed; complain and initialize 3011 // that base class. 3012 diagnoseTypo(Corr, 3013 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3014 << MemberOrBase << false, 3015 PDiag() /*Suppress note, we provide our own.*/); 3016 3017 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3018 : VirtualBaseSpec; 3019 Diag(BaseSpec->getLocStart(), 3020 diag::note_base_class_specified_here) 3021 << BaseSpec->getType() 3022 << BaseSpec->getSourceRange(); 3023 3024 TyD = Type; 3025 } 3026 } 3027 } 3028 3029 if (!TyD && BaseType.isNull()) { 3030 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3031 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3032 return true; 3033 } 3034 } 3035 3036 if (BaseType.isNull()) { 3037 BaseType = Context.getTypeDeclType(TyD); 3038 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3039 if (SS.isSet()) 3040 // FIXME: preserve source range information 3041 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3042 BaseType); 3043 } 3044 } 3045 3046 if (!TInfo) 3047 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3048 3049 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3050 } 3051 3052 /// Checks a member initializer expression for cases where reference (or 3053 /// pointer) members are bound to by-value parameters (or their addresses). 3054 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3055 Expr *Init, 3056 SourceLocation IdLoc) { 3057 QualType MemberTy = Member->getType(); 3058 3059 // We only handle pointers and references currently. 3060 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3061 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3062 return; 3063 3064 const bool IsPointer = MemberTy->isPointerType(); 3065 if (IsPointer) { 3066 if (const UnaryOperator *Op 3067 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3068 // The only case we're worried about with pointers requires taking the 3069 // address. 3070 if (Op->getOpcode() != UO_AddrOf) 3071 return; 3072 3073 Init = Op->getSubExpr(); 3074 } else { 3075 // We only handle address-of expression initializers for pointers. 3076 return; 3077 } 3078 } 3079 3080 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3081 // We only warn when referring to a non-reference parameter declaration. 3082 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3083 if (!Parameter || Parameter->getType()->isReferenceType()) 3084 return; 3085 3086 S.Diag(Init->getExprLoc(), 3087 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3088 : diag::warn_bind_ref_member_to_parameter) 3089 << Member << Parameter << Init->getSourceRange(); 3090 } else { 3091 // Other initializers are fine. 3092 return; 3093 } 3094 3095 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3096 << (unsigned)IsPointer; 3097 } 3098 3099 MemInitResult 3100 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3101 SourceLocation IdLoc) { 3102 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3103 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3104 assert((DirectMember || IndirectMember) && 3105 "Member must be a FieldDecl or IndirectFieldDecl"); 3106 3107 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3108 return true; 3109 3110 if (Member->isInvalidDecl()) 3111 return true; 3112 3113 MultiExprArg Args; 3114 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3115 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3116 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3117 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3118 } else { 3119 // Template instantiation doesn't reconstruct ParenListExprs for us. 3120 Args = Init; 3121 } 3122 3123 SourceRange InitRange = Init->getSourceRange(); 3124 3125 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3126 // Can't check initialization for a member of dependent type or when 3127 // any of the arguments are type-dependent expressions. 3128 DiscardCleanupsInEvaluationContext(); 3129 } else { 3130 bool InitList = false; 3131 if (isa<InitListExpr>(Init)) { 3132 InitList = true; 3133 Args = Init; 3134 } 3135 3136 // Initialize the member. 3137 InitializedEntity MemberEntity = 3138 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3139 : InitializedEntity::InitializeMember(IndirectMember, 3140 nullptr); 3141 InitializationKind Kind = 3142 InitList ? InitializationKind::CreateDirectList(IdLoc) 3143 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3144 InitRange.getEnd()); 3145 3146 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3147 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3148 nullptr); 3149 if (MemberInit.isInvalid()) 3150 return true; 3151 3152 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3153 3154 // C++11 [class.base.init]p7: 3155 // The initialization of each base and member constitutes a 3156 // full-expression. 3157 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3158 if (MemberInit.isInvalid()) 3159 return true; 3160 3161 Init = MemberInit.get(); 3162 } 3163 3164 if (DirectMember) { 3165 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3166 InitRange.getBegin(), Init, 3167 InitRange.getEnd()); 3168 } else { 3169 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3170 InitRange.getBegin(), Init, 3171 InitRange.getEnd()); 3172 } 3173 } 3174 3175 MemInitResult 3176 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3177 CXXRecordDecl *ClassDecl) { 3178 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3179 if (!LangOpts.CPlusPlus11) 3180 return Diag(NameLoc, diag::err_delegating_ctor) 3181 << TInfo->getTypeLoc().getLocalSourceRange(); 3182 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3183 3184 bool InitList = true; 3185 MultiExprArg Args = Init; 3186 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3187 InitList = false; 3188 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3189 } 3190 3191 SourceRange InitRange = Init->getSourceRange(); 3192 // Initialize the object. 3193 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3194 QualType(ClassDecl->getTypeForDecl(), 0)); 3195 InitializationKind Kind = 3196 InitList ? InitializationKind::CreateDirectList(NameLoc) 3197 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3198 InitRange.getEnd()); 3199 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3200 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3201 Args, nullptr); 3202 if (DelegationInit.isInvalid()) 3203 return true; 3204 3205 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3206 "Delegating constructor with no target?"); 3207 3208 // C++11 [class.base.init]p7: 3209 // The initialization of each base and member constitutes a 3210 // full-expression. 3211 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3212 InitRange.getBegin()); 3213 if (DelegationInit.isInvalid()) 3214 return true; 3215 3216 // If we are in a dependent context, template instantiation will 3217 // perform this type-checking again. Just save the arguments that we 3218 // received in a ParenListExpr. 3219 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3220 // of the information that we have about the base 3221 // initializer. However, deconstructing the ASTs is a dicey process, 3222 // and this approach is far more likely to get the corner cases right. 3223 if (CurContext->isDependentContext()) 3224 DelegationInit = Init; 3225 3226 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3227 DelegationInit.getAs<Expr>(), 3228 InitRange.getEnd()); 3229 } 3230 3231 MemInitResult 3232 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3233 Expr *Init, CXXRecordDecl *ClassDecl, 3234 SourceLocation EllipsisLoc) { 3235 SourceLocation BaseLoc 3236 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3237 3238 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3239 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3240 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3241 3242 // C++ [class.base.init]p2: 3243 // [...] Unless the mem-initializer-id names a nonstatic data 3244 // member of the constructor's class or a direct or virtual base 3245 // of that class, the mem-initializer is ill-formed. A 3246 // mem-initializer-list can initialize a base class using any 3247 // name that denotes that base class type. 3248 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3249 3250 SourceRange InitRange = Init->getSourceRange(); 3251 if (EllipsisLoc.isValid()) { 3252 // This is a pack expansion. 3253 if (!BaseType->containsUnexpandedParameterPack()) { 3254 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3255 << SourceRange(BaseLoc, InitRange.getEnd()); 3256 3257 EllipsisLoc = SourceLocation(); 3258 } 3259 } else { 3260 // Check for any unexpanded parameter packs. 3261 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3262 return true; 3263 3264 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3265 return true; 3266 } 3267 3268 // Check for direct and virtual base classes. 3269 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3270 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3271 if (!Dependent) { 3272 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3273 BaseType)) 3274 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3275 3276 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3277 VirtualBaseSpec); 3278 3279 // C++ [base.class.init]p2: 3280 // Unless the mem-initializer-id names a nonstatic data member of the 3281 // constructor's class or a direct or virtual base of that class, the 3282 // mem-initializer is ill-formed. 3283 if (!DirectBaseSpec && !VirtualBaseSpec) { 3284 // If the class has any dependent bases, then it's possible that 3285 // one of those types will resolve to the same type as 3286 // BaseType. Therefore, just treat this as a dependent base 3287 // class initialization. FIXME: Should we try to check the 3288 // initialization anyway? It seems odd. 3289 if (ClassDecl->hasAnyDependentBases()) 3290 Dependent = true; 3291 else 3292 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3293 << BaseType << Context.getTypeDeclType(ClassDecl) 3294 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3295 } 3296 } 3297 3298 if (Dependent) { 3299 DiscardCleanupsInEvaluationContext(); 3300 3301 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3302 /*IsVirtual=*/false, 3303 InitRange.getBegin(), Init, 3304 InitRange.getEnd(), EllipsisLoc); 3305 } 3306 3307 // C++ [base.class.init]p2: 3308 // If a mem-initializer-id is ambiguous because it designates both 3309 // a direct non-virtual base class and an inherited virtual base 3310 // class, the mem-initializer is ill-formed. 3311 if (DirectBaseSpec && VirtualBaseSpec) 3312 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3313 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3314 3315 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3316 if (!BaseSpec) 3317 BaseSpec = VirtualBaseSpec; 3318 3319 // Initialize the base. 3320 bool InitList = true; 3321 MultiExprArg Args = Init; 3322 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3323 InitList = false; 3324 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3325 } 3326 3327 InitializedEntity BaseEntity = 3328 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3329 InitializationKind Kind = 3330 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3331 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3332 InitRange.getEnd()); 3333 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3334 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3335 if (BaseInit.isInvalid()) 3336 return true; 3337 3338 // C++11 [class.base.init]p7: 3339 // The initialization of each base and member constitutes a 3340 // full-expression. 3341 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3342 if (BaseInit.isInvalid()) 3343 return true; 3344 3345 // If we are in a dependent context, template instantiation will 3346 // perform this type-checking again. Just save the arguments that we 3347 // received in a ParenListExpr. 3348 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3349 // of the information that we have about the base 3350 // initializer. However, deconstructing the ASTs is a dicey process, 3351 // and this approach is far more likely to get the corner cases right. 3352 if (CurContext->isDependentContext()) 3353 BaseInit = Init; 3354 3355 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3356 BaseSpec->isVirtual(), 3357 InitRange.getBegin(), 3358 BaseInit.getAs<Expr>(), 3359 InitRange.getEnd(), EllipsisLoc); 3360 } 3361 3362 // Create a static_cast\<T&&>(expr). 3363 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3364 if (T.isNull()) T = E->getType(); 3365 QualType TargetType = SemaRef.BuildReferenceType( 3366 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3367 SourceLocation ExprLoc = E->getLocStart(); 3368 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3369 TargetType, ExprLoc); 3370 3371 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3372 SourceRange(ExprLoc, ExprLoc), 3373 E->getSourceRange()).get(); 3374 } 3375 3376 /// ImplicitInitializerKind - How an implicit base or member initializer should 3377 /// initialize its base or member. 3378 enum ImplicitInitializerKind { 3379 IIK_Default, 3380 IIK_Copy, 3381 IIK_Move, 3382 IIK_Inherit 3383 }; 3384 3385 static bool 3386 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3387 ImplicitInitializerKind ImplicitInitKind, 3388 CXXBaseSpecifier *BaseSpec, 3389 bool IsInheritedVirtualBase, 3390 CXXCtorInitializer *&CXXBaseInit) { 3391 InitializedEntity InitEntity 3392 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3393 IsInheritedVirtualBase); 3394 3395 ExprResult BaseInit; 3396 3397 switch (ImplicitInitKind) { 3398 case IIK_Inherit: { 3399 const CXXRecordDecl *Inherited = 3400 Constructor->getInheritedConstructor()->getParent(); 3401 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3402 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3403 // C++11 [class.inhctor]p8: 3404 // Each expression in the expression-list is of the form 3405 // static_cast<T&&>(p), where p is the name of the corresponding 3406 // constructor parameter and T is the declared type of p. 3407 SmallVector<Expr*, 16> Args; 3408 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3409 ParmVarDecl *PD = Constructor->getParamDecl(I); 3410 ExprResult ArgExpr = 3411 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3412 VK_LValue, SourceLocation()); 3413 if (ArgExpr.isInvalid()) 3414 return true; 3415 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3416 } 3417 3418 InitializationKind InitKind = InitializationKind::CreateDirect( 3419 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3420 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3421 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3422 break; 3423 } 3424 } 3425 // Fall through. 3426 case IIK_Default: { 3427 InitializationKind InitKind 3428 = InitializationKind::CreateDefault(Constructor->getLocation()); 3429 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3430 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3431 break; 3432 } 3433 3434 case IIK_Move: 3435 case IIK_Copy: { 3436 bool Moving = ImplicitInitKind == IIK_Move; 3437 ParmVarDecl *Param = Constructor->getParamDecl(0); 3438 QualType ParamType = Param->getType().getNonReferenceType(); 3439 3440 Expr *CopyCtorArg = 3441 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3442 SourceLocation(), Param, false, 3443 Constructor->getLocation(), ParamType, 3444 VK_LValue, nullptr); 3445 3446 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3447 3448 // Cast to the base class to avoid ambiguities. 3449 QualType ArgTy = 3450 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3451 ParamType.getQualifiers()); 3452 3453 if (Moving) { 3454 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3455 } 3456 3457 CXXCastPath BasePath; 3458 BasePath.push_back(BaseSpec); 3459 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3460 CK_UncheckedDerivedToBase, 3461 Moving ? VK_XValue : VK_LValue, 3462 &BasePath).get(); 3463 3464 InitializationKind InitKind 3465 = InitializationKind::CreateDirect(Constructor->getLocation(), 3466 SourceLocation(), SourceLocation()); 3467 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3468 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3469 break; 3470 } 3471 } 3472 3473 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3474 if (BaseInit.isInvalid()) 3475 return true; 3476 3477 CXXBaseInit = 3478 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3479 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3480 SourceLocation()), 3481 BaseSpec->isVirtual(), 3482 SourceLocation(), 3483 BaseInit.getAs<Expr>(), 3484 SourceLocation(), 3485 SourceLocation()); 3486 3487 return false; 3488 } 3489 3490 static bool RefersToRValueRef(Expr *MemRef) { 3491 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3492 return Referenced->getType()->isRValueReferenceType(); 3493 } 3494 3495 static bool 3496 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3497 ImplicitInitializerKind ImplicitInitKind, 3498 FieldDecl *Field, IndirectFieldDecl *Indirect, 3499 CXXCtorInitializer *&CXXMemberInit) { 3500 if (Field->isInvalidDecl()) 3501 return true; 3502 3503 SourceLocation Loc = Constructor->getLocation(); 3504 3505 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3506 bool Moving = ImplicitInitKind == IIK_Move; 3507 ParmVarDecl *Param = Constructor->getParamDecl(0); 3508 QualType ParamType = Param->getType().getNonReferenceType(); 3509 3510 // Suppress copying zero-width bitfields. 3511 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3512 return false; 3513 3514 Expr *MemberExprBase = 3515 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3516 SourceLocation(), Param, false, 3517 Loc, ParamType, VK_LValue, nullptr); 3518 3519 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3520 3521 if (Moving) { 3522 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3523 } 3524 3525 // Build a reference to this field within the parameter. 3526 CXXScopeSpec SS; 3527 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3528 Sema::LookupMemberName); 3529 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3530 : cast<ValueDecl>(Field), AS_public); 3531 MemberLookup.resolveKind(); 3532 ExprResult CtorArg 3533 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3534 ParamType, Loc, 3535 /*IsArrow=*/false, 3536 SS, 3537 /*TemplateKWLoc=*/SourceLocation(), 3538 /*FirstQualifierInScope=*/nullptr, 3539 MemberLookup, 3540 /*TemplateArgs=*/nullptr); 3541 if (CtorArg.isInvalid()) 3542 return true; 3543 3544 // C++11 [class.copy]p15: 3545 // - if a member m has rvalue reference type T&&, it is direct-initialized 3546 // with static_cast<T&&>(x.m); 3547 if (RefersToRValueRef(CtorArg.get())) { 3548 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3549 } 3550 3551 // When the field we are copying is an array, create index variables for 3552 // each dimension of the array. We use these index variables to subscript 3553 // the source array, and other clients (e.g., CodeGen) will perform the 3554 // necessary iteration with these index variables. 3555 SmallVector<VarDecl *, 4> IndexVariables; 3556 QualType BaseType = Field->getType(); 3557 QualType SizeType = SemaRef.Context.getSizeType(); 3558 bool InitializingArray = false; 3559 while (const ConstantArrayType *Array 3560 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3561 InitializingArray = true; 3562 // Create the iteration variable for this array index. 3563 IdentifierInfo *IterationVarName = nullptr; 3564 { 3565 SmallString<8> Str; 3566 llvm::raw_svector_ostream OS(Str); 3567 OS << "__i" << IndexVariables.size(); 3568 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3569 } 3570 VarDecl *IterationVar 3571 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3572 IterationVarName, SizeType, 3573 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3574 SC_None); 3575 IndexVariables.push_back(IterationVar); 3576 3577 // Create a reference to the iteration variable. 3578 ExprResult IterationVarRef 3579 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3580 assert(!IterationVarRef.isInvalid() && 3581 "Reference to invented variable cannot fail!"); 3582 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3583 assert(!IterationVarRef.isInvalid() && 3584 "Conversion of invented variable cannot fail!"); 3585 3586 // Subscript the array with this iteration variable. 3587 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3588 IterationVarRef.get(), 3589 Loc); 3590 if (CtorArg.isInvalid()) 3591 return true; 3592 3593 BaseType = Array->getElementType(); 3594 } 3595 3596 // The array subscript expression is an lvalue, which is wrong for moving. 3597 if (Moving && InitializingArray) 3598 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3599 3600 // Construct the entity that we will be initializing. For an array, this 3601 // will be first element in the array, which may require several levels 3602 // of array-subscript entities. 3603 SmallVector<InitializedEntity, 4> Entities; 3604 Entities.reserve(1 + IndexVariables.size()); 3605 if (Indirect) 3606 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3607 else 3608 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3609 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3610 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3611 0, 3612 Entities.back())); 3613 3614 // Direct-initialize to use the copy constructor. 3615 InitializationKind InitKind = 3616 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3617 3618 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3619 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 3620 CtorArgE); 3621 3622 ExprResult MemberInit 3623 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3624 MultiExprArg(&CtorArgE, 1)); 3625 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3626 if (MemberInit.isInvalid()) 3627 return true; 3628 3629 if (Indirect) { 3630 assert(IndexVariables.size() == 0 && 3631 "Indirect field improperly initialized"); 3632 CXXMemberInit 3633 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3634 Loc, Loc, 3635 MemberInit.getAs<Expr>(), 3636 Loc); 3637 } else 3638 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3639 Loc, MemberInit.getAs<Expr>(), 3640 Loc, 3641 IndexVariables.data(), 3642 IndexVariables.size()); 3643 return false; 3644 } 3645 3646 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3647 "Unhandled implicit init kind!"); 3648 3649 QualType FieldBaseElementType = 3650 SemaRef.Context.getBaseElementType(Field->getType()); 3651 3652 if (FieldBaseElementType->isRecordType()) { 3653 InitializedEntity InitEntity 3654 = Indirect? InitializedEntity::InitializeMember(Indirect) 3655 : InitializedEntity::InitializeMember(Field); 3656 InitializationKind InitKind = 3657 InitializationKind::CreateDefault(Loc); 3658 3659 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3660 ExprResult MemberInit = 3661 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3662 3663 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3664 if (MemberInit.isInvalid()) 3665 return true; 3666 3667 if (Indirect) 3668 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3669 Indirect, Loc, 3670 Loc, 3671 MemberInit.get(), 3672 Loc); 3673 else 3674 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3675 Field, Loc, Loc, 3676 MemberInit.get(), 3677 Loc); 3678 return false; 3679 } 3680 3681 if (!Field->getParent()->isUnion()) { 3682 if (FieldBaseElementType->isReferenceType()) { 3683 SemaRef.Diag(Constructor->getLocation(), 3684 diag::err_uninitialized_member_in_ctor) 3685 << (int)Constructor->isImplicit() 3686 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3687 << 0 << Field->getDeclName(); 3688 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3689 return true; 3690 } 3691 3692 if (FieldBaseElementType.isConstQualified()) { 3693 SemaRef.Diag(Constructor->getLocation(), 3694 diag::err_uninitialized_member_in_ctor) 3695 << (int)Constructor->isImplicit() 3696 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3697 << 1 << Field->getDeclName(); 3698 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3699 return true; 3700 } 3701 } 3702 3703 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3704 FieldBaseElementType->isObjCRetainableType() && 3705 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3706 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3707 // ARC: 3708 // Default-initialize Objective-C pointers to NULL. 3709 CXXMemberInit 3710 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3711 Loc, Loc, 3712 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3713 Loc); 3714 return false; 3715 } 3716 3717 // Nothing to initialize. 3718 CXXMemberInit = nullptr; 3719 return false; 3720 } 3721 3722 namespace { 3723 struct BaseAndFieldInfo { 3724 Sema &S; 3725 CXXConstructorDecl *Ctor; 3726 bool AnyErrorsInInits; 3727 ImplicitInitializerKind IIK; 3728 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3729 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3730 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3731 3732 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3733 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3734 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3735 if (Generated && Ctor->isCopyConstructor()) 3736 IIK = IIK_Copy; 3737 else if (Generated && Ctor->isMoveConstructor()) 3738 IIK = IIK_Move; 3739 else if (Ctor->getInheritedConstructor()) 3740 IIK = IIK_Inherit; 3741 else 3742 IIK = IIK_Default; 3743 } 3744 3745 bool isImplicitCopyOrMove() const { 3746 switch (IIK) { 3747 case IIK_Copy: 3748 case IIK_Move: 3749 return true; 3750 3751 case IIK_Default: 3752 case IIK_Inherit: 3753 return false; 3754 } 3755 3756 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3757 } 3758 3759 bool addFieldInitializer(CXXCtorInitializer *Init) { 3760 AllToInit.push_back(Init); 3761 3762 // Check whether this initializer makes the field "used". 3763 if (Init->getInit()->HasSideEffects(S.Context)) 3764 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3765 3766 return false; 3767 } 3768 3769 bool isInactiveUnionMember(FieldDecl *Field) { 3770 RecordDecl *Record = Field->getParent(); 3771 if (!Record->isUnion()) 3772 return false; 3773 3774 if (FieldDecl *Active = 3775 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3776 return Active != Field->getCanonicalDecl(); 3777 3778 // In an implicit copy or move constructor, ignore any in-class initializer. 3779 if (isImplicitCopyOrMove()) 3780 return true; 3781 3782 // If there's no explicit initialization, the field is active only if it 3783 // has an in-class initializer... 3784 if (Field->hasInClassInitializer()) 3785 return false; 3786 // ... or it's an anonymous struct or union whose class has an in-class 3787 // initializer. 3788 if (!Field->isAnonymousStructOrUnion()) 3789 return true; 3790 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3791 return !FieldRD->hasInClassInitializer(); 3792 } 3793 3794 /// \brief Determine whether the given field is, or is within, a union member 3795 /// that is inactive (because there was an initializer given for a different 3796 /// member of the union, or because the union was not initialized at all). 3797 bool isWithinInactiveUnionMember(FieldDecl *Field, 3798 IndirectFieldDecl *Indirect) { 3799 if (!Indirect) 3800 return isInactiveUnionMember(Field); 3801 3802 for (auto *C : Indirect->chain()) { 3803 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3804 if (Field && isInactiveUnionMember(Field)) 3805 return true; 3806 } 3807 return false; 3808 } 3809 }; 3810 } 3811 3812 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3813 /// array type. 3814 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3815 if (T->isIncompleteArrayType()) 3816 return true; 3817 3818 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3819 if (!ArrayT->getSize()) 3820 return true; 3821 3822 T = ArrayT->getElementType(); 3823 } 3824 3825 return false; 3826 } 3827 3828 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3829 FieldDecl *Field, 3830 IndirectFieldDecl *Indirect = nullptr) { 3831 if (Field->isInvalidDecl()) 3832 return false; 3833 3834 // Overwhelmingly common case: we have a direct initializer for this field. 3835 if (CXXCtorInitializer *Init = 3836 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3837 return Info.addFieldInitializer(Init); 3838 3839 // C++11 [class.base.init]p8: 3840 // if the entity is a non-static data member that has a 3841 // brace-or-equal-initializer and either 3842 // -- the constructor's class is a union and no other variant member of that 3843 // union is designated by a mem-initializer-id or 3844 // -- the constructor's class is not a union, and, if the entity is a member 3845 // of an anonymous union, no other member of that union is designated by 3846 // a mem-initializer-id, 3847 // the entity is initialized as specified in [dcl.init]. 3848 // 3849 // We also apply the same rules to handle anonymous structs within anonymous 3850 // unions. 3851 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3852 return false; 3853 3854 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3855 ExprResult DIE = 3856 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3857 if (DIE.isInvalid()) 3858 return true; 3859 CXXCtorInitializer *Init; 3860 if (Indirect) 3861 Init = new (SemaRef.Context) 3862 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3863 SourceLocation(), DIE.get(), SourceLocation()); 3864 else 3865 Init = new (SemaRef.Context) 3866 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3867 SourceLocation(), DIE.get(), SourceLocation()); 3868 return Info.addFieldInitializer(Init); 3869 } 3870 3871 // Don't initialize incomplete or zero-length arrays. 3872 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3873 return false; 3874 3875 // Don't try to build an implicit initializer if there were semantic 3876 // errors in any of the initializers (and therefore we might be 3877 // missing some that the user actually wrote). 3878 if (Info.AnyErrorsInInits) 3879 return false; 3880 3881 CXXCtorInitializer *Init = nullptr; 3882 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3883 Indirect, Init)) 3884 return true; 3885 3886 if (!Init) 3887 return false; 3888 3889 return Info.addFieldInitializer(Init); 3890 } 3891 3892 bool 3893 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3894 CXXCtorInitializer *Initializer) { 3895 assert(Initializer->isDelegatingInitializer()); 3896 Constructor->setNumCtorInitializers(1); 3897 CXXCtorInitializer **initializer = 3898 new (Context) CXXCtorInitializer*[1]; 3899 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3900 Constructor->setCtorInitializers(initializer); 3901 3902 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3903 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3904 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3905 } 3906 3907 DelegatingCtorDecls.push_back(Constructor); 3908 3909 DiagnoseUninitializedFields(*this, Constructor); 3910 3911 return false; 3912 } 3913 3914 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3915 ArrayRef<CXXCtorInitializer *> Initializers) { 3916 if (Constructor->isDependentContext()) { 3917 // Just store the initializers as written, they will be checked during 3918 // instantiation. 3919 if (!Initializers.empty()) { 3920 Constructor->setNumCtorInitializers(Initializers.size()); 3921 CXXCtorInitializer **baseOrMemberInitializers = 3922 new (Context) CXXCtorInitializer*[Initializers.size()]; 3923 memcpy(baseOrMemberInitializers, Initializers.data(), 3924 Initializers.size() * sizeof(CXXCtorInitializer*)); 3925 Constructor->setCtorInitializers(baseOrMemberInitializers); 3926 } 3927 3928 // Let template instantiation know whether we had errors. 3929 if (AnyErrors) 3930 Constructor->setInvalidDecl(); 3931 3932 return false; 3933 } 3934 3935 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3936 3937 // We need to build the initializer AST according to order of construction 3938 // and not what user specified in the Initializers list. 3939 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3940 if (!ClassDecl) 3941 return true; 3942 3943 bool HadError = false; 3944 3945 for (unsigned i = 0; i < Initializers.size(); i++) { 3946 CXXCtorInitializer *Member = Initializers[i]; 3947 3948 if (Member->isBaseInitializer()) 3949 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3950 else { 3951 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3952 3953 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3954 for (auto *C : F->chain()) { 3955 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3956 if (FD && FD->getParent()->isUnion()) 3957 Info.ActiveUnionMember.insert(std::make_pair( 3958 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3959 } 3960 } else if (FieldDecl *FD = Member->getMember()) { 3961 if (FD->getParent()->isUnion()) 3962 Info.ActiveUnionMember.insert(std::make_pair( 3963 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3964 } 3965 } 3966 } 3967 3968 // Keep track of the direct virtual bases. 3969 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3970 for (auto &I : ClassDecl->bases()) { 3971 if (I.isVirtual()) 3972 DirectVBases.insert(&I); 3973 } 3974 3975 // Push virtual bases before others. 3976 for (auto &VBase : ClassDecl->vbases()) { 3977 if (CXXCtorInitializer *Value 3978 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3979 // [class.base.init]p7, per DR257: 3980 // A mem-initializer where the mem-initializer-id names a virtual base 3981 // class is ignored during execution of a constructor of any class that 3982 // is not the most derived class. 3983 if (ClassDecl->isAbstract()) { 3984 // FIXME: Provide a fixit to remove the base specifier. This requires 3985 // tracking the location of the associated comma for a base specifier. 3986 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3987 << VBase.getType() << ClassDecl; 3988 DiagnoseAbstractType(ClassDecl); 3989 } 3990 3991 Info.AllToInit.push_back(Value); 3992 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3993 // [class.base.init]p8, per DR257: 3994 // If a given [...] base class is not named by a mem-initializer-id 3995 // [...] and the entity is not a virtual base class of an abstract 3996 // class, then [...] the entity is default-initialized. 3997 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3998 CXXCtorInitializer *CXXBaseInit; 3999 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4000 &VBase, IsInheritedVirtualBase, 4001 CXXBaseInit)) { 4002 HadError = true; 4003 continue; 4004 } 4005 4006 Info.AllToInit.push_back(CXXBaseInit); 4007 } 4008 } 4009 4010 // Non-virtual bases. 4011 for (auto &Base : ClassDecl->bases()) { 4012 // Virtuals are in the virtual base list and already constructed. 4013 if (Base.isVirtual()) 4014 continue; 4015 4016 if (CXXCtorInitializer *Value 4017 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4018 Info.AllToInit.push_back(Value); 4019 } else if (!AnyErrors) { 4020 CXXCtorInitializer *CXXBaseInit; 4021 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4022 &Base, /*IsInheritedVirtualBase=*/false, 4023 CXXBaseInit)) { 4024 HadError = true; 4025 continue; 4026 } 4027 4028 Info.AllToInit.push_back(CXXBaseInit); 4029 } 4030 } 4031 4032 // Fields. 4033 for (auto *Mem : ClassDecl->decls()) { 4034 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4035 // C++ [class.bit]p2: 4036 // A declaration for a bit-field that omits the identifier declares an 4037 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4038 // initialized. 4039 if (F->isUnnamedBitfield()) 4040 continue; 4041 4042 // If we're not generating the implicit copy/move constructor, then we'll 4043 // handle anonymous struct/union fields based on their individual 4044 // indirect fields. 4045 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4046 continue; 4047 4048 if (CollectFieldInitializer(*this, Info, F)) 4049 HadError = true; 4050 continue; 4051 } 4052 4053 // Beyond this point, we only consider default initialization. 4054 if (Info.isImplicitCopyOrMove()) 4055 continue; 4056 4057 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4058 if (F->getType()->isIncompleteArrayType()) { 4059 assert(ClassDecl->hasFlexibleArrayMember() && 4060 "Incomplete array type is not valid"); 4061 continue; 4062 } 4063 4064 // Initialize each field of an anonymous struct individually. 4065 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4066 HadError = true; 4067 4068 continue; 4069 } 4070 } 4071 4072 unsigned NumInitializers = Info.AllToInit.size(); 4073 if (NumInitializers > 0) { 4074 Constructor->setNumCtorInitializers(NumInitializers); 4075 CXXCtorInitializer **baseOrMemberInitializers = 4076 new (Context) CXXCtorInitializer*[NumInitializers]; 4077 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4078 NumInitializers * sizeof(CXXCtorInitializer*)); 4079 Constructor->setCtorInitializers(baseOrMemberInitializers); 4080 4081 // Constructors implicitly reference the base and member 4082 // destructors. 4083 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4084 Constructor->getParent()); 4085 } 4086 4087 return HadError; 4088 } 4089 4090 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4091 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4092 const RecordDecl *RD = RT->getDecl(); 4093 if (RD->isAnonymousStructOrUnion()) { 4094 for (auto *Field : RD->fields()) 4095 PopulateKeysForFields(Field, IdealInits); 4096 return; 4097 } 4098 } 4099 IdealInits.push_back(Field->getCanonicalDecl()); 4100 } 4101 4102 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4103 return Context.getCanonicalType(BaseType).getTypePtr(); 4104 } 4105 4106 static const void *GetKeyForMember(ASTContext &Context, 4107 CXXCtorInitializer *Member) { 4108 if (!Member->isAnyMemberInitializer()) 4109 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4110 4111 return Member->getAnyMember()->getCanonicalDecl(); 4112 } 4113 4114 static void DiagnoseBaseOrMemInitializerOrder( 4115 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4116 ArrayRef<CXXCtorInitializer *> Inits) { 4117 if (Constructor->getDeclContext()->isDependentContext()) 4118 return; 4119 4120 // Don't check initializers order unless the warning is enabled at the 4121 // location of at least one initializer. 4122 bool ShouldCheckOrder = false; 4123 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4124 CXXCtorInitializer *Init = Inits[InitIndex]; 4125 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4126 Init->getSourceLocation())) { 4127 ShouldCheckOrder = true; 4128 break; 4129 } 4130 } 4131 if (!ShouldCheckOrder) 4132 return; 4133 4134 // Build the list of bases and members in the order that they'll 4135 // actually be initialized. The explicit initializers should be in 4136 // this same order but may be missing things. 4137 SmallVector<const void*, 32> IdealInitKeys; 4138 4139 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4140 4141 // 1. Virtual bases. 4142 for (const auto &VBase : ClassDecl->vbases()) 4143 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4144 4145 // 2. Non-virtual bases. 4146 for (const auto &Base : ClassDecl->bases()) { 4147 if (Base.isVirtual()) 4148 continue; 4149 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4150 } 4151 4152 // 3. Direct fields. 4153 for (auto *Field : ClassDecl->fields()) { 4154 if (Field->isUnnamedBitfield()) 4155 continue; 4156 4157 PopulateKeysForFields(Field, IdealInitKeys); 4158 } 4159 4160 unsigned NumIdealInits = IdealInitKeys.size(); 4161 unsigned IdealIndex = 0; 4162 4163 CXXCtorInitializer *PrevInit = nullptr; 4164 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4165 CXXCtorInitializer *Init = Inits[InitIndex]; 4166 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4167 4168 // Scan forward to try to find this initializer in the idealized 4169 // initializers list. 4170 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4171 if (InitKey == IdealInitKeys[IdealIndex]) 4172 break; 4173 4174 // If we didn't find this initializer, it must be because we 4175 // scanned past it on a previous iteration. That can only 4176 // happen if we're out of order; emit a warning. 4177 if (IdealIndex == NumIdealInits && PrevInit) { 4178 Sema::SemaDiagnosticBuilder D = 4179 SemaRef.Diag(PrevInit->getSourceLocation(), 4180 diag::warn_initializer_out_of_order); 4181 4182 if (PrevInit->isAnyMemberInitializer()) 4183 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4184 else 4185 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4186 4187 if (Init->isAnyMemberInitializer()) 4188 D << 0 << Init->getAnyMember()->getDeclName(); 4189 else 4190 D << 1 << Init->getTypeSourceInfo()->getType(); 4191 4192 // Move back to the initializer's location in the ideal list. 4193 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4194 if (InitKey == IdealInitKeys[IdealIndex]) 4195 break; 4196 4197 assert(IdealIndex != NumIdealInits && 4198 "initializer not found in initializer list"); 4199 } 4200 4201 PrevInit = Init; 4202 } 4203 } 4204 4205 namespace { 4206 bool CheckRedundantInit(Sema &S, 4207 CXXCtorInitializer *Init, 4208 CXXCtorInitializer *&PrevInit) { 4209 if (!PrevInit) { 4210 PrevInit = Init; 4211 return false; 4212 } 4213 4214 if (FieldDecl *Field = Init->getAnyMember()) 4215 S.Diag(Init->getSourceLocation(), 4216 diag::err_multiple_mem_initialization) 4217 << Field->getDeclName() 4218 << Init->getSourceRange(); 4219 else { 4220 const Type *BaseClass = Init->getBaseClass(); 4221 assert(BaseClass && "neither field nor base"); 4222 S.Diag(Init->getSourceLocation(), 4223 diag::err_multiple_base_initialization) 4224 << QualType(BaseClass, 0) 4225 << Init->getSourceRange(); 4226 } 4227 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4228 << 0 << PrevInit->getSourceRange(); 4229 4230 return true; 4231 } 4232 4233 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4234 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4235 4236 bool CheckRedundantUnionInit(Sema &S, 4237 CXXCtorInitializer *Init, 4238 RedundantUnionMap &Unions) { 4239 FieldDecl *Field = Init->getAnyMember(); 4240 RecordDecl *Parent = Field->getParent(); 4241 NamedDecl *Child = Field; 4242 4243 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4244 if (Parent->isUnion()) { 4245 UnionEntry &En = Unions[Parent]; 4246 if (En.first && En.first != Child) { 4247 S.Diag(Init->getSourceLocation(), 4248 diag::err_multiple_mem_union_initialization) 4249 << Field->getDeclName() 4250 << Init->getSourceRange(); 4251 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4252 << 0 << En.second->getSourceRange(); 4253 return true; 4254 } 4255 if (!En.first) { 4256 En.first = Child; 4257 En.second = Init; 4258 } 4259 if (!Parent->isAnonymousStructOrUnion()) 4260 return false; 4261 } 4262 4263 Child = Parent; 4264 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4265 } 4266 4267 return false; 4268 } 4269 } 4270 4271 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4272 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4273 SourceLocation ColonLoc, 4274 ArrayRef<CXXCtorInitializer*> MemInits, 4275 bool AnyErrors) { 4276 if (!ConstructorDecl) 4277 return; 4278 4279 AdjustDeclIfTemplate(ConstructorDecl); 4280 4281 CXXConstructorDecl *Constructor 4282 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4283 4284 if (!Constructor) { 4285 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4286 return; 4287 } 4288 4289 // Mapping for the duplicate initializers check. 4290 // For member initializers, this is keyed with a FieldDecl*. 4291 // For base initializers, this is keyed with a Type*. 4292 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4293 4294 // Mapping for the inconsistent anonymous-union initializers check. 4295 RedundantUnionMap MemberUnions; 4296 4297 bool HadError = false; 4298 for (unsigned i = 0; i < MemInits.size(); i++) { 4299 CXXCtorInitializer *Init = MemInits[i]; 4300 4301 // Set the source order index. 4302 Init->setSourceOrder(i); 4303 4304 if (Init->isAnyMemberInitializer()) { 4305 const void *Key = GetKeyForMember(Context, Init); 4306 if (CheckRedundantInit(*this, Init, Members[Key]) || 4307 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4308 HadError = true; 4309 } else if (Init->isBaseInitializer()) { 4310 const void *Key = GetKeyForMember(Context, Init); 4311 if (CheckRedundantInit(*this, Init, Members[Key])) 4312 HadError = true; 4313 } else { 4314 assert(Init->isDelegatingInitializer()); 4315 // This must be the only initializer 4316 if (MemInits.size() != 1) { 4317 Diag(Init->getSourceLocation(), 4318 diag::err_delegating_initializer_alone) 4319 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4320 // We will treat this as being the only initializer. 4321 } 4322 SetDelegatingInitializer(Constructor, MemInits[i]); 4323 // Return immediately as the initializer is set. 4324 return; 4325 } 4326 } 4327 4328 if (HadError) 4329 return; 4330 4331 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4332 4333 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4334 4335 DiagnoseUninitializedFields(*this, Constructor); 4336 } 4337 4338 void 4339 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4340 CXXRecordDecl *ClassDecl) { 4341 // Ignore dependent contexts. Also ignore unions, since their members never 4342 // have destructors implicitly called. 4343 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4344 return; 4345 4346 // FIXME: all the access-control diagnostics are positioned on the 4347 // field/base declaration. That's probably good; that said, the 4348 // user might reasonably want to know why the destructor is being 4349 // emitted, and we currently don't say. 4350 4351 // Non-static data members. 4352 for (auto *Field : ClassDecl->fields()) { 4353 if (Field->isInvalidDecl()) 4354 continue; 4355 4356 // Don't destroy incomplete or zero-length arrays. 4357 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4358 continue; 4359 4360 QualType FieldType = Context.getBaseElementType(Field->getType()); 4361 4362 const RecordType* RT = FieldType->getAs<RecordType>(); 4363 if (!RT) 4364 continue; 4365 4366 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4367 if (FieldClassDecl->isInvalidDecl()) 4368 continue; 4369 if (FieldClassDecl->hasIrrelevantDestructor()) 4370 continue; 4371 // The destructor for an implicit anonymous union member is never invoked. 4372 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4373 continue; 4374 4375 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4376 assert(Dtor && "No dtor found for FieldClassDecl!"); 4377 CheckDestructorAccess(Field->getLocation(), Dtor, 4378 PDiag(diag::err_access_dtor_field) 4379 << Field->getDeclName() 4380 << FieldType); 4381 4382 MarkFunctionReferenced(Location, Dtor); 4383 DiagnoseUseOfDecl(Dtor, Location); 4384 } 4385 4386 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4387 4388 // Bases. 4389 for (const auto &Base : ClassDecl->bases()) { 4390 // Bases are always records in a well-formed non-dependent class. 4391 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4392 4393 // Remember direct virtual bases. 4394 if (Base.isVirtual()) 4395 DirectVirtualBases.insert(RT); 4396 4397 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4398 // If our base class is invalid, we probably can't get its dtor anyway. 4399 if (BaseClassDecl->isInvalidDecl()) 4400 continue; 4401 if (BaseClassDecl->hasIrrelevantDestructor()) 4402 continue; 4403 4404 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4405 assert(Dtor && "No dtor found for BaseClassDecl!"); 4406 4407 // FIXME: caret should be on the start of the class name 4408 CheckDestructorAccess(Base.getLocStart(), Dtor, 4409 PDiag(diag::err_access_dtor_base) 4410 << Base.getType() 4411 << Base.getSourceRange(), 4412 Context.getTypeDeclType(ClassDecl)); 4413 4414 MarkFunctionReferenced(Location, Dtor); 4415 DiagnoseUseOfDecl(Dtor, Location); 4416 } 4417 4418 // Virtual bases. 4419 for (const auto &VBase : ClassDecl->vbases()) { 4420 // Bases are always records in a well-formed non-dependent class. 4421 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4422 4423 // Ignore direct virtual bases. 4424 if (DirectVirtualBases.count(RT)) 4425 continue; 4426 4427 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4428 // If our base class is invalid, we probably can't get its dtor anyway. 4429 if (BaseClassDecl->isInvalidDecl()) 4430 continue; 4431 if (BaseClassDecl->hasIrrelevantDestructor()) 4432 continue; 4433 4434 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4435 assert(Dtor && "No dtor found for BaseClassDecl!"); 4436 if (CheckDestructorAccess( 4437 ClassDecl->getLocation(), Dtor, 4438 PDiag(diag::err_access_dtor_vbase) 4439 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4440 Context.getTypeDeclType(ClassDecl)) == 4441 AR_accessible) { 4442 CheckDerivedToBaseConversion( 4443 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4444 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4445 SourceRange(), DeclarationName(), nullptr); 4446 } 4447 4448 MarkFunctionReferenced(Location, Dtor); 4449 DiagnoseUseOfDecl(Dtor, Location); 4450 } 4451 } 4452 4453 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4454 if (!CDtorDecl) 4455 return; 4456 4457 if (CXXConstructorDecl *Constructor 4458 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4459 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4460 DiagnoseUninitializedFields(*this, Constructor); 4461 } 4462 } 4463 4464 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4465 unsigned DiagID, AbstractDiagSelID SelID) { 4466 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4467 unsigned DiagID; 4468 AbstractDiagSelID SelID; 4469 4470 public: 4471 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4472 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4473 4474 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4475 if (Suppressed) return; 4476 if (SelID == -1) 4477 S.Diag(Loc, DiagID) << T; 4478 else 4479 S.Diag(Loc, DiagID) << SelID << T; 4480 } 4481 } Diagnoser(DiagID, SelID); 4482 4483 return RequireNonAbstractType(Loc, T, Diagnoser); 4484 } 4485 4486 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4487 TypeDiagnoser &Diagnoser) { 4488 if (!getLangOpts().CPlusPlus) 4489 return false; 4490 4491 if (const ArrayType *AT = Context.getAsArrayType(T)) 4492 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4493 4494 if (const PointerType *PT = T->getAs<PointerType>()) { 4495 // Find the innermost pointer type. 4496 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4497 PT = T; 4498 4499 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4500 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4501 } 4502 4503 const RecordType *RT = T->getAs<RecordType>(); 4504 if (!RT) 4505 return false; 4506 4507 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4508 4509 // We can't answer whether something is abstract until it has a 4510 // definition. If it's currently being defined, we'll walk back 4511 // over all the declarations when we have a full definition. 4512 const CXXRecordDecl *Def = RD->getDefinition(); 4513 if (!Def || Def->isBeingDefined()) 4514 return false; 4515 4516 if (!RD->isAbstract()) 4517 return false; 4518 4519 Diagnoser.diagnose(*this, Loc, T); 4520 DiagnoseAbstractType(RD); 4521 4522 return true; 4523 } 4524 4525 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4526 // Check if we've already emitted the list of pure virtual functions 4527 // for this class. 4528 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4529 return; 4530 4531 // If the diagnostic is suppressed, don't emit the notes. We're only 4532 // going to emit them once, so try to attach them to a diagnostic we're 4533 // actually going to show. 4534 if (Diags.isLastDiagnosticIgnored()) 4535 return; 4536 4537 CXXFinalOverriderMap FinalOverriders; 4538 RD->getFinalOverriders(FinalOverriders); 4539 4540 // Keep a set of seen pure methods so we won't diagnose the same method 4541 // more than once. 4542 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4543 4544 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4545 MEnd = FinalOverriders.end(); 4546 M != MEnd; 4547 ++M) { 4548 for (OverridingMethods::iterator SO = M->second.begin(), 4549 SOEnd = M->second.end(); 4550 SO != SOEnd; ++SO) { 4551 // C++ [class.abstract]p4: 4552 // A class is abstract if it contains or inherits at least one 4553 // pure virtual function for which the final overrider is pure 4554 // virtual. 4555 4556 // 4557 if (SO->second.size() != 1) 4558 continue; 4559 4560 if (!SO->second.front().Method->isPure()) 4561 continue; 4562 4563 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4564 continue; 4565 4566 Diag(SO->second.front().Method->getLocation(), 4567 diag::note_pure_virtual_function) 4568 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4569 } 4570 } 4571 4572 if (!PureVirtualClassDiagSet) 4573 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4574 PureVirtualClassDiagSet->insert(RD); 4575 } 4576 4577 namespace { 4578 struct AbstractUsageInfo { 4579 Sema &S; 4580 CXXRecordDecl *Record; 4581 CanQualType AbstractType; 4582 bool Invalid; 4583 4584 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4585 : S(S), Record(Record), 4586 AbstractType(S.Context.getCanonicalType( 4587 S.Context.getTypeDeclType(Record))), 4588 Invalid(false) {} 4589 4590 void DiagnoseAbstractType() { 4591 if (Invalid) return; 4592 S.DiagnoseAbstractType(Record); 4593 Invalid = true; 4594 } 4595 4596 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4597 }; 4598 4599 struct CheckAbstractUsage { 4600 AbstractUsageInfo &Info; 4601 const NamedDecl *Ctx; 4602 4603 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4604 : Info(Info), Ctx(Ctx) {} 4605 4606 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4607 switch (TL.getTypeLocClass()) { 4608 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4609 #define TYPELOC(CLASS, PARENT) \ 4610 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4611 #include "clang/AST/TypeLocNodes.def" 4612 } 4613 } 4614 4615 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4616 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4617 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4618 if (!TL.getParam(I)) 4619 continue; 4620 4621 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4622 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4623 } 4624 } 4625 4626 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4627 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4628 } 4629 4630 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4631 // Visit the type parameters from a permissive context. 4632 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4633 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4634 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4635 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4636 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4637 // TODO: other template argument types? 4638 } 4639 } 4640 4641 // Visit pointee types from a permissive context. 4642 #define CheckPolymorphic(Type) \ 4643 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4644 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4645 } 4646 CheckPolymorphic(PointerTypeLoc) 4647 CheckPolymorphic(ReferenceTypeLoc) 4648 CheckPolymorphic(MemberPointerTypeLoc) 4649 CheckPolymorphic(BlockPointerTypeLoc) 4650 CheckPolymorphic(AtomicTypeLoc) 4651 4652 /// Handle all the types we haven't given a more specific 4653 /// implementation for above. 4654 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4655 // Every other kind of type that we haven't called out already 4656 // that has an inner type is either (1) sugar or (2) contains that 4657 // inner type in some way as a subobject. 4658 if (TypeLoc Next = TL.getNextTypeLoc()) 4659 return Visit(Next, Sel); 4660 4661 // If there's no inner type and we're in a permissive context, 4662 // don't diagnose. 4663 if (Sel == Sema::AbstractNone) return; 4664 4665 // Check whether the type matches the abstract type. 4666 QualType T = TL.getType(); 4667 if (T->isArrayType()) { 4668 Sel = Sema::AbstractArrayType; 4669 T = Info.S.Context.getBaseElementType(T); 4670 } 4671 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4672 if (CT != Info.AbstractType) return; 4673 4674 // It matched; do some magic. 4675 if (Sel == Sema::AbstractArrayType) { 4676 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4677 << T << TL.getSourceRange(); 4678 } else { 4679 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4680 << Sel << T << TL.getSourceRange(); 4681 } 4682 Info.DiagnoseAbstractType(); 4683 } 4684 }; 4685 4686 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4687 Sema::AbstractDiagSelID Sel) { 4688 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4689 } 4690 4691 } 4692 4693 /// Check for invalid uses of an abstract type in a method declaration. 4694 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4695 CXXMethodDecl *MD) { 4696 // No need to do the check on definitions, which require that 4697 // the return/param types be complete. 4698 if (MD->doesThisDeclarationHaveABody()) 4699 return; 4700 4701 // For safety's sake, just ignore it if we don't have type source 4702 // information. This should never happen for non-implicit methods, 4703 // but... 4704 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4705 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4706 } 4707 4708 /// Check for invalid uses of an abstract type within a class definition. 4709 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4710 CXXRecordDecl *RD) { 4711 for (auto *D : RD->decls()) { 4712 if (D->isImplicit()) continue; 4713 4714 // Methods and method templates. 4715 if (isa<CXXMethodDecl>(D)) { 4716 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4717 } else if (isa<FunctionTemplateDecl>(D)) { 4718 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4719 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4720 4721 // Fields and static variables. 4722 } else if (isa<FieldDecl>(D)) { 4723 FieldDecl *FD = cast<FieldDecl>(D); 4724 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4725 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4726 } else if (isa<VarDecl>(D)) { 4727 VarDecl *VD = cast<VarDecl>(D); 4728 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4729 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4730 4731 // Nested classes and class templates. 4732 } else if (isa<CXXRecordDecl>(D)) { 4733 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4734 } else if (isa<ClassTemplateDecl>(D)) { 4735 CheckAbstractClassUsage(Info, 4736 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4737 } 4738 } 4739 } 4740 4741 /// \brief Check class-level dllimport/dllexport attribute. 4742 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 4743 Attr *ClassAttr = getDLLAttr(Class); 4744 4745 // MSVC inherits DLL attributes to partial class template specializations. 4746 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4747 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4748 if (Attr *TemplateAttr = 4749 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4750 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 4751 A->setInherited(true); 4752 ClassAttr = A; 4753 } 4754 } 4755 } 4756 4757 if (!ClassAttr) 4758 return; 4759 4760 if (!Class->isExternallyVisible()) { 4761 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4762 << Class << ClassAttr; 4763 return; 4764 } 4765 4766 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 4767 !ClassAttr->isInherited()) { 4768 // Diagnose dll attributes on members of class with dll attribute. 4769 for (Decl *Member : Class->decls()) { 4770 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4771 continue; 4772 InheritableAttr *MemberAttr = getDLLAttr(Member); 4773 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4774 continue; 4775 4776 Diag(MemberAttr->getLocation(), 4777 diag::err_attribute_dll_member_of_dll_class) 4778 << MemberAttr << ClassAttr; 4779 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4780 Member->setInvalidDecl(); 4781 } 4782 } 4783 4784 if (Class->getDescribedClassTemplate()) 4785 // Don't inherit dll attribute until the template is instantiated. 4786 return; 4787 4788 // The class is either imported or exported. 4789 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4790 const bool ClassImported = !ClassExported; 4791 4792 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4793 4794 // Don't dllexport explicit class template instantiation declarations. 4795 if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) { 4796 Class->dropAttr<DLLExportAttr>(); 4797 return; 4798 } 4799 4800 // Force declaration of implicit members so they can inherit the attribute. 4801 ForceDeclarationOfImplicitMembers(Class); 4802 4803 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4804 // seem to be true in practice? 4805 4806 for (Decl *Member : Class->decls()) { 4807 VarDecl *VD = dyn_cast<VarDecl>(Member); 4808 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4809 4810 // Only methods and static fields inherit the attributes. 4811 if (!VD && !MD) 4812 continue; 4813 4814 if (MD) { 4815 // Don't process deleted methods. 4816 if (MD->isDeleted()) 4817 continue; 4818 4819 if (MD->isInlined()) { 4820 // MinGW does not import or export inline methods. 4821 if (!Context.getTargetInfo().getCXXABI().isMicrosoft()) 4822 continue; 4823 4824 // MSVC versions before 2015 don't export the move assignment operators, 4825 // so don't attempt to import them if we have a definition. 4826 if (ClassImported && MD->isMoveAssignmentOperator() && 4827 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 4828 continue; 4829 } 4830 } 4831 4832 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 4833 continue; 4834 4835 if (!getDLLAttr(Member)) { 4836 auto *NewAttr = 4837 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 4838 NewAttr->setInherited(true); 4839 Member->addAttr(NewAttr); 4840 } 4841 4842 if (MD && ClassExported) { 4843 if (MD->isUserProvided()) { 4844 // Instantiate non-default class member functions ... 4845 4846 // .. except for certain kinds of template specializations. 4847 if (TSK == TSK_ExplicitInstantiationDeclaration) 4848 continue; 4849 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4850 continue; 4851 4852 MarkFunctionReferenced(Class->getLocation(), MD); 4853 4854 // The function will be passed to the consumer when its definition is 4855 // encountered. 4856 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4857 MD->isCopyAssignmentOperator() || 4858 MD->isMoveAssignmentOperator()) { 4859 // Synthesize and instantiate non-trivial implicit methods, explicitly 4860 // defaulted methods, and the copy and move assignment operators. The 4861 // latter are exported even if they are trivial, because the address of 4862 // an operator can be taken and should compare equal accross libraries. 4863 DiagnosticErrorTrap Trap(Diags); 4864 MarkFunctionReferenced(Class->getLocation(), MD); 4865 if (Trap.hasErrorOccurred()) { 4866 Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 4867 << Class->getName() << !getLangOpts().CPlusPlus11; 4868 break; 4869 } 4870 4871 // There is no later point when we will see the definition of this 4872 // function, so pass it to the consumer now. 4873 Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 4874 } 4875 } 4876 } 4877 } 4878 4879 /// \brief Perform semantic checks on a class definition that has been 4880 /// completing, introducing implicitly-declared members, checking for 4881 /// abstract types, etc. 4882 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4883 if (!Record) 4884 return; 4885 4886 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4887 AbstractUsageInfo Info(*this, Record); 4888 CheckAbstractClassUsage(Info, Record); 4889 } 4890 4891 // If this is not an aggregate type and has no user-declared constructor, 4892 // complain about any non-static data members of reference or const scalar 4893 // type, since they will never get initializers. 4894 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4895 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4896 !Record->isLambda()) { 4897 bool Complained = false; 4898 for (const auto *F : Record->fields()) { 4899 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4900 continue; 4901 4902 if (F->getType()->isReferenceType() || 4903 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4904 if (!Complained) { 4905 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4906 << Record->getTagKind() << Record; 4907 Complained = true; 4908 } 4909 4910 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4911 << F->getType()->isReferenceType() 4912 << F->getDeclName(); 4913 } 4914 } 4915 } 4916 4917 if (Record->getIdentifier()) { 4918 // C++ [class.mem]p13: 4919 // If T is the name of a class, then each of the following shall have a 4920 // name different from T: 4921 // - every member of every anonymous union that is a member of class T. 4922 // 4923 // C++ [class.mem]p14: 4924 // In addition, if class T has a user-declared constructor (12.1), every 4925 // non-static data member of class T shall have a name different from T. 4926 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4927 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4928 ++I) { 4929 NamedDecl *D = *I; 4930 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4931 isa<IndirectFieldDecl>(D)) { 4932 Diag(D->getLocation(), diag::err_member_name_of_class) 4933 << D->getDeclName(); 4934 break; 4935 } 4936 } 4937 } 4938 4939 // Warn if the class has virtual methods but non-virtual public destructor. 4940 if (Record->isPolymorphic() && !Record->isDependentType()) { 4941 CXXDestructorDecl *dtor = Record->getDestructor(); 4942 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4943 !Record->hasAttr<FinalAttr>()) 4944 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4945 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4946 } 4947 4948 if (Record->isAbstract()) { 4949 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4950 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4951 << FA->isSpelledAsSealed(); 4952 DiagnoseAbstractType(Record); 4953 } 4954 } 4955 4956 bool HasMethodWithOverrideControl = false, 4957 HasOverridingMethodWithoutOverrideControl = false; 4958 if (!Record->isDependentType()) { 4959 for (auto *M : Record->methods()) { 4960 // See if a method overloads virtual methods in a base 4961 // class without overriding any. 4962 if (!M->isStatic()) 4963 DiagnoseHiddenVirtualMethods(M); 4964 if (M->hasAttr<OverrideAttr>()) 4965 HasMethodWithOverrideControl = true; 4966 else if (M->size_overridden_methods() > 0) 4967 HasOverridingMethodWithoutOverrideControl = true; 4968 // Check whether the explicitly-defaulted special members are valid. 4969 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4970 CheckExplicitlyDefaultedSpecialMember(M); 4971 4972 // For an explicitly defaulted or deleted special member, we defer 4973 // determining triviality until the class is complete. That time is now! 4974 if (!M->isImplicit() && !M->isUserProvided()) { 4975 CXXSpecialMember CSM = getSpecialMember(M); 4976 if (CSM != CXXInvalid) { 4977 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4978 4979 // Inform the class that we've finished declaring this member. 4980 Record->finishedDefaultedOrDeletedMember(M); 4981 } 4982 } 4983 } 4984 } 4985 4986 if (HasMethodWithOverrideControl && 4987 HasOverridingMethodWithoutOverrideControl) { 4988 // At least one method has the 'override' control declared. 4989 // Diagnose all other overridden methods which do not have 'override' specified on them. 4990 for (auto *M : Record->methods()) 4991 DiagnoseAbsenceOfOverrideControl(M); 4992 } 4993 4994 // ms_struct is a request to use the same ABI rules as MSVC. Check 4995 // whether this class uses any C++ features that are implemented 4996 // completely differently in MSVC, and if so, emit a diagnostic. 4997 // That diagnostic defaults to an error, but we allow projects to 4998 // map it down to a warning (or ignore it). It's a fairly common 4999 // practice among users of the ms_struct pragma to mass-annotate 5000 // headers, sweeping up a bunch of types that the project doesn't 5001 // really rely on MSVC-compatible layout for. We must therefore 5002 // support "ms_struct except for C++ stuff" as a secondary ABI. 5003 if (Record->isMsStruct(Context) && 5004 (Record->isPolymorphic() || Record->getNumBases())) { 5005 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5006 } 5007 5008 // Declare inheriting constructors. We do this eagerly here because: 5009 // - The standard requires an eager diagnostic for conflicting inheriting 5010 // constructors from different classes. 5011 // - The lazy declaration of the other implicit constructors is so as to not 5012 // waste space and performance on classes that are not meant to be 5013 // instantiated (e.g. meta-functions). This doesn't apply to classes that 5014 // have inheriting constructors. 5015 DeclareInheritingConstructors(Record); 5016 5017 checkClassLevelDLLAttribute(Record); 5018 } 5019 5020 /// Look up the special member function that would be called by a special 5021 /// member function for a subobject of class type. 5022 /// 5023 /// \param Class The class type of the subobject. 5024 /// \param CSM The kind of special member function. 5025 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5026 /// \param ConstRHS True if this is a copy operation with a const object 5027 /// on its RHS, that is, if the argument to the outer special member 5028 /// function is 'const' and this is not a field marked 'mutable'. 5029 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 5030 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5031 unsigned FieldQuals, bool ConstRHS) { 5032 unsigned LHSQuals = 0; 5033 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5034 LHSQuals = FieldQuals; 5035 5036 unsigned RHSQuals = FieldQuals; 5037 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5038 RHSQuals = 0; 5039 else if (ConstRHS) 5040 RHSQuals |= Qualifiers::Const; 5041 5042 return S.LookupSpecialMember(Class, CSM, 5043 RHSQuals & Qualifiers::Const, 5044 RHSQuals & Qualifiers::Volatile, 5045 false, 5046 LHSQuals & Qualifiers::Const, 5047 LHSQuals & Qualifiers::Volatile); 5048 } 5049 5050 /// Is the special member function which would be selected to perform the 5051 /// specified operation on the specified class type a constexpr constructor? 5052 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5053 Sema::CXXSpecialMember CSM, 5054 unsigned Quals, bool ConstRHS) { 5055 Sema::SpecialMemberOverloadResult *SMOR = 5056 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5057 if (!SMOR || !SMOR->getMethod()) 5058 // A constructor we wouldn't select can't be "involved in initializing" 5059 // anything. 5060 return true; 5061 return SMOR->getMethod()->isConstexpr(); 5062 } 5063 5064 /// Determine whether the specified special member function would be constexpr 5065 /// if it were implicitly defined. 5066 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5067 Sema::CXXSpecialMember CSM, 5068 bool ConstArg) { 5069 if (!S.getLangOpts().CPlusPlus11) 5070 return false; 5071 5072 // C++11 [dcl.constexpr]p4: 5073 // In the definition of a constexpr constructor [...] 5074 bool Ctor = true; 5075 switch (CSM) { 5076 case Sema::CXXDefaultConstructor: 5077 // Since default constructor lookup is essentially trivial (and cannot 5078 // involve, for instance, template instantiation), we compute whether a 5079 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5080 // 5081 // This is important for performance; we need to know whether the default 5082 // constructor is constexpr to determine whether the type is a literal type. 5083 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5084 5085 case Sema::CXXCopyConstructor: 5086 case Sema::CXXMoveConstructor: 5087 // For copy or move constructors, we need to perform overload resolution. 5088 break; 5089 5090 case Sema::CXXCopyAssignment: 5091 case Sema::CXXMoveAssignment: 5092 if (!S.getLangOpts().CPlusPlus14) 5093 return false; 5094 // In C++1y, we need to perform overload resolution. 5095 Ctor = false; 5096 break; 5097 5098 case Sema::CXXDestructor: 5099 case Sema::CXXInvalid: 5100 return false; 5101 } 5102 5103 // -- if the class is a non-empty union, or for each non-empty anonymous 5104 // union member of a non-union class, exactly one non-static data member 5105 // shall be initialized; [DR1359] 5106 // 5107 // If we squint, this is guaranteed, since exactly one non-static data member 5108 // will be initialized (if the constructor isn't deleted), we just don't know 5109 // which one. 5110 if (Ctor && ClassDecl->isUnion()) 5111 return true; 5112 5113 // -- the class shall not have any virtual base classes; 5114 if (Ctor && ClassDecl->getNumVBases()) 5115 return false; 5116 5117 // C++1y [class.copy]p26: 5118 // -- [the class] is a literal type, and 5119 if (!Ctor && !ClassDecl->isLiteral()) 5120 return false; 5121 5122 // -- every constructor involved in initializing [...] base class 5123 // sub-objects shall be a constexpr constructor; 5124 // -- the assignment operator selected to copy/move each direct base 5125 // class is a constexpr function, and 5126 for (const auto &B : ClassDecl->bases()) { 5127 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5128 if (!BaseType) continue; 5129 5130 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5131 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5132 return false; 5133 } 5134 5135 // -- every constructor involved in initializing non-static data members 5136 // [...] shall be a constexpr constructor; 5137 // -- every non-static data member and base class sub-object shall be 5138 // initialized 5139 // -- for each non-static data member of X that is of class type (or array 5140 // thereof), the assignment operator selected to copy/move that member is 5141 // a constexpr function 5142 for (const auto *F : ClassDecl->fields()) { 5143 if (F->isInvalidDecl()) 5144 continue; 5145 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5146 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5147 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5148 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5149 BaseType.getCVRQualifiers(), 5150 ConstArg && !F->isMutable())) 5151 return false; 5152 } 5153 } 5154 5155 // All OK, it's constexpr! 5156 return true; 5157 } 5158 5159 static Sema::ImplicitExceptionSpecification 5160 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5161 switch (S.getSpecialMember(MD)) { 5162 case Sema::CXXDefaultConstructor: 5163 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5164 case Sema::CXXCopyConstructor: 5165 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5166 case Sema::CXXCopyAssignment: 5167 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5168 case Sema::CXXMoveConstructor: 5169 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5170 case Sema::CXXMoveAssignment: 5171 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5172 case Sema::CXXDestructor: 5173 return S.ComputeDefaultedDtorExceptionSpec(MD); 5174 case Sema::CXXInvalid: 5175 break; 5176 } 5177 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5178 "only special members have implicit exception specs"); 5179 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5180 } 5181 5182 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5183 CXXMethodDecl *MD) { 5184 FunctionProtoType::ExtProtoInfo EPI; 5185 5186 // Build an exception specification pointing back at this member. 5187 EPI.ExceptionSpec.Type = EST_Unevaluated; 5188 EPI.ExceptionSpec.SourceDecl = MD; 5189 5190 // Set the calling convention to the default for C++ instance methods. 5191 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5192 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5193 /*IsCXXMethod=*/true)); 5194 return EPI; 5195 } 5196 5197 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5198 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5199 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5200 return; 5201 5202 // Evaluate the exception specification. 5203 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5204 5205 // Update the type of the special member to use it. 5206 UpdateExceptionSpec(MD, ESI); 5207 5208 // A user-provided destructor can be defined outside the class. When that 5209 // happens, be sure to update the exception specification on both 5210 // declarations. 5211 const FunctionProtoType *CanonicalFPT = 5212 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5213 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5214 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5215 } 5216 5217 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5218 CXXRecordDecl *RD = MD->getParent(); 5219 CXXSpecialMember CSM = getSpecialMember(MD); 5220 5221 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5222 "not an explicitly-defaulted special member"); 5223 5224 // Whether this was the first-declared instance of the constructor. 5225 // This affects whether we implicitly add an exception spec and constexpr. 5226 bool First = MD == MD->getCanonicalDecl(); 5227 5228 bool HadError = false; 5229 5230 // C++11 [dcl.fct.def.default]p1: 5231 // A function that is explicitly defaulted shall 5232 // -- be a special member function (checked elsewhere), 5233 // -- have the same type (except for ref-qualifiers, and except that a 5234 // copy operation can take a non-const reference) as an implicit 5235 // declaration, and 5236 // -- not have default arguments. 5237 unsigned ExpectedParams = 1; 5238 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5239 ExpectedParams = 0; 5240 if (MD->getNumParams() != ExpectedParams) { 5241 // This also checks for default arguments: a copy or move constructor with a 5242 // default argument is classified as a default constructor, and assignment 5243 // operations and destructors can't have default arguments. 5244 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5245 << CSM << MD->getSourceRange(); 5246 HadError = true; 5247 } else if (MD->isVariadic()) { 5248 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5249 << CSM << MD->getSourceRange(); 5250 HadError = true; 5251 } 5252 5253 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5254 5255 bool CanHaveConstParam = false; 5256 if (CSM == CXXCopyConstructor) 5257 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5258 else if (CSM == CXXCopyAssignment) 5259 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5260 5261 QualType ReturnType = Context.VoidTy; 5262 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5263 // Check for return type matching. 5264 ReturnType = Type->getReturnType(); 5265 QualType ExpectedReturnType = 5266 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5267 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5268 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5269 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5270 HadError = true; 5271 } 5272 5273 // A defaulted special member cannot have cv-qualifiers. 5274 if (Type->getTypeQuals()) { 5275 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5276 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5277 HadError = true; 5278 } 5279 } 5280 5281 // Check for parameter type matching. 5282 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5283 bool HasConstParam = false; 5284 if (ExpectedParams && ArgType->isReferenceType()) { 5285 // Argument must be reference to possibly-const T. 5286 QualType ReferentType = ArgType->getPointeeType(); 5287 HasConstParam = ReferentType.isConstQualified(); 5288 5289 if (ReferentType.isVolatileQualified()) { 5290 Diag(MD->getLocation(), 5291 diag::err_defaulted_special_member_volatile_param) << CSM; 5292 HadError = true; 5293 } 5294 5295 if (HasConstParam && !CanHaveConstParam) { 5296 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5297 Diag(MD->getLocation(), 5298 diag::err_defaulted_special_member_copy_const_param) 5299 << (CSM == CXXCopyAssignment); 5300 // FIXME: Explain why this special member can't be const. 5301 } else { 5302 Diag(MD->getLocation(), 5303 diag::err_defaulted_special_member_move_const_param) 5304 << (CSM == CXXMoveAssignment); 5305 } 5306 HadError = true; 5307 } 5308 } else if (ExpectedParams) { 5309 // A copy assignment operator can take its argument by value, but a 5310 // defaulted one cannot. 5311 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5312 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5313 HadError = true; 5314 } 5315 5316 // C++11 [dcl.fct.def.default]p2: 5317 // An explicitly-defaulted function may be declared constexpr only if it 5318 // would have been implicitly declared as constexpr, 5319 // Do not apply this rule to members of class templates, since core issue 1358 5320 // makes such functions always instantiate to constexpr functions. For 5321 // functions which cannot be constexpr (for non-constructors in C++11 and for 5322 // destructors in C++1y), this is checked elsewhere. 5323 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5324 HasConstParam); 5325 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5326 : isa<CXXConstructorDecl>(MD)) && 5327 MD->isConstexpr() && !Constexpr && 5328 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5329 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5330 // FIXME: Explain why the special member can't be constexpr. 5331 HadError = true; 5332 } 5333 5334 // and may have an explicit exception-specification only if it is compatible 5335 // with the exception-specification on the implicit declaration. 5336 if (Type->hasExceptionSpec()) { 5337 // Delay the check if this is the first declaration of the special member, 5338 // since we may not have parsed some necessary in-class initializers yet. 5339 if (First) { 5340 // If the exception specification needs to be instantiated, do so now, 5341 // before we clobber it with an EST_Unevaluated specification below. 5342 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5343 InstantiateExceptionSpec(MD->getLocStart(), MD); 5344 Type = MD->getType()->getAs<FunctionProtoType>(); 5345 } 5346 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5347 } else 5348 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5349 } 5350 5351 // If a function is explicitly defaulted on its first declaration, 5352 if (First) { 5353 // -- it is implicitly considered to be constexpr if the implicit 5354 // definition would be, 5355 MD->setConstexpr(Constexpr); 5356 5357 // -- it is implicitly considered to have the same exception-specification 5358 // as if it had been implicitly declared, 5359 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5360 EPI.ExceptionSpec.Type = EST_Unevaluated; 5361 EPI.ExceptionSpec.SourceDecl = MD; 5362 MD->setType(Context.getFunctionType(ReturnType, 5363 llvm::makeArrayRef(&ArgType, 5364 ExpectedParams), 5365 EPI)); 5366 } 5367 5368 if (ShouldDeleteSpecialMember(MD, CSM)) { 5369 if (First) { 5370 SetDeclDeleted(MD, MD->getLocation()); 5371 } else { 5372 // C++11 [dcl.fct.def.default]p4: 5373 // [For a] user-provided explicitly-defaulted function [...] if such a 5374 // function is implicitly defined as deleted, the program is ill-formed. 5375 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5376 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5377 HadError = true; 5378 } 5379 } 5380 5381 if (HadError) 5382 MD->setInvalidDecl(); 5383 } 5384 5385 /// Check whether the exception specification provided for an 5386 /// explicitly-defaulted special member matches the exception specification 5387 /// that would have been generated for an implicit special member, per 5388 /// C++11 [dcl.fct.def.default]p2. 5389 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5390 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5391 // If the exception specification was explicitly specified but hadn't been 5392 // parsed when the method was defaulted, grab it now. 5393 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5394 SpecifiedType = 5395 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5396 5397 // Compute the implicit exception specification. 5398 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5399 /*IsCXXMethod=*/true); 5400 FunctionProtoType::ExtProtoInfo EPI(CC); 5401 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5402 .getExceptionSpec(); 5403 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5404 Context.getFunctionType(Context.VoidTy, None, EPI)); 5405 5406 // Ensure that it matches. 5407 CheckEquivalentExceptionSpec( 5408 PDiag(diag::err_incorrect_defaulted_exception_spec) 5409 << getSpecialMember(MD), PDiag(), 5410 ImplicitType, SourceLocation(), 5411 SpecifiedType, MD->getLocation()); 5412 } 5413 5414 void Sema::CheckDelayedMemberExceptionSpecs() { 5415 decltype(DelayedExceptionSpecChecks) Checks; 5416 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 5417 5418 std::swap(Checks, DelayedExceptionSpecChecks); 5419 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5420 5421 // Perform any deferred checking of exception specifications for virtual 5422 // destructors. 5423 for (auto &Check : Checks) 5424 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 5425 5426 // Check that any explicitly-defaulted methods have exception specifications 5427 // compatible with their implicit exception specifications. 5428 for (auto &Spec : Specs) 5429 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 5430 } 5431 5432 namespace { 5433 struct SpecialMemberDeletionInfo { 5434 Sema &S; 5435 CXXMethodDecl *MD; 5436 Sema::CXXSpecialMember CSM; 5437 bool Diagnose; 5438 5439 // Properties of the special member, computed for convenience. 5440 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5441 SourceLocation Loc; 5442 5443 bool AllFieldsAreConst; 5444 5445 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5446 Sema::CXXSpecialMember CSM, bool Diagnose) 5447 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5448 IsConstructor(false), IsAssignment(false), IsMove(false), 5449 ConstArg(false), Loc(MD->getLocation()), 5450 AllFieldsAreConst(true) { 5451 switch (CSM) { 5452 case Sema::CXXDefaultConstructor: 5453 case Sema::CXXCopyConstructor: 5454 IsConstructor = true; 5455 break; 5456 case Sema::CXXMoveConstructor: 5457 IsConstructor = true; 5458 IsMove = true; 5459 break; 5460 case Sema::CXXCopyAssignment: 5461 IsAssignment = true; 5462 break; 5463 case Sema::CXXMoveAssignment: 5464 IsAssignment = true; 5465 IsMove = true; 5466 break; 5467 case Sema::CXXDestructor: 5468 break; 5469 case Sema::CXXInvalid: 5470 llvm_unreachable("invalid special member kind"); 5471 } 5472 5473 if (MD->getNumParams()) { 5474 if (const ReferenceType *RT = 5475 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5476 ConstArg = RT->getPointeeType().isConstQualified(); 5477 } 5478 } 5479 5480 bool inUnion() const { return MD->getParent()->isUnion(); } 5481 5482 /// Look up the corresponding special member in the given class. 5483 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5484 unsigned Quals, bool IsMutable) { 5485 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5486 ConstArg && !IsMutable); 5487 } 5488 5489 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5490 5491 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5492 bool shouldDeleteForField(FieldDecl *FD); 5493 bool shouldDeleteForAllConstMembers(); 5494 5495 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5496 unsigned Quals); 5497 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5498 Sema::SpecialMemberOverloadResult *SMOR, 5499 bool IsDtorCallInCtor); 5500 5501 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5502 }; 5503 } 5504 5505 /// Is the given special member inaccessible when used on the given 5506 /// sub-object. 5507 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5508 CXXMethodDecl *target) { 5509 /// If we're operating on a base class, the object type is the 5510 /// type of this special member. 5511 QualType objectTy; 5512 AccessSpecifier access = target->getAccess(); 5513 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5514 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5515 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5516 5517 // If we're operating on a field, the object type is the type of the field. 5518 } else { 5519 objectTy = S.Context.getTypeDeclType(target->getParent()); 5520 } 5521 5522 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5523 } 5524 5525 /// Check whether we should delete a special member due to the implicit 5526 /// definition containing a call to a special member of a subobject. 5527 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5528 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5529 bool IsDtorCallInCtor) { 5530 CXXMethodDecl *Decl = SMOR->getMethod(); 5531 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5532 5533 int DiagKind = -1; 5534 5535 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5536 DiagKind = !Decl ? 0 : 1; 5537 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5538 DiagKind = 2; 5539 else if (!isAccessible(Subobj, Decl)) 5540 DiagKind = 3; 5541 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5542 !Decl->isTrivial()) { 5543 // A member of a union must have a trivial corresponding special member. 5544 // As a weird special case, a destructor call from a union's constructor 5545 // must be accessible and non-deleted, but need not be trivial. Such a 5546 // destructor is never actually called, but is semantically checked as 5547 // if it were. 5548 DiagKind = 4; 5549 } 5550 5551 if (DiagKind == -1) 5552 return false; 5553 5554 if (Diagnose) { 5555 if (Field) { 5556 S.Diag(Field->getLocation(), 5557 diag::note_deleted_special_member_class_subobject) 5558 << CSM << MD->getParent() << /*IsField*/true 5559 << Field << DiagKind << IsDtorCallInCtor; 5560 } else { 5561 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5562 S.Diag(Base->getLocStart(), 5563 diag::note_deleted_special_member_class_subobject) 5564 << CSM << MD->getParent() << /*IsField*/false 5565 << Base->getType() << DiagKind << IsDtorCallInCtor; 5566 } 5567 5568 if (DiagKind == 1) 5569 S.NoteDeletedFunction(Decl); 5570 // FIXME: Explain inaccessibility if DiagKind == 3. 5571 } 5572 5573 return true; 5574 } 5575 5576 /// Check whether we should delete a special member function due to having a 5577 /// direct or virtual base class or non-static data member of class type M. 5578 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5579 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5580 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5581 bool IsMutable = Field && Field->isMutable(); 5582 5583 // C++11 [class.ctor]p5: 5584 // -- any direct or virtual base class, or non-static data member with no 5585 // brace-or-equal-initializer, has class type M (or array thereof) and 5586 // either M has no default constructor or overload resolution as applied 5587 // to M's default constructor results in an ambiguity or in a function 5588 // that is deleted or inaccessible 5589 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5590 // -- a direct or virtual base class B that cannot be copied/moved because 5591 // overload resolution, as applied to B's corresponding special member, 5592 // results in an ambiguity or a function that is deleted or inaccessible 5593 // from the defaulted special member 5594 // C++11 [class.dtor]p5: 5595 // -- any direct or virtual base class [...] has a type with a destructor 5596 // that is deleted or inaccessible 5597 if (!(CSM == Sema::CXXDefaultConstructor && 5598 Field && Field->hasInClassInitializer()) && 5599 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5600 false)) 5601 return true; 5602 5603 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5604 // -- any direct or virtual base class or non-static data member has a 5605 // type with a destructor that is deleted or inaccessible 5606 if (IsConstructor) { 5607 Sema::SpecialMemberOverloadResult *SMOR = 5608 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5609 false, false, false, false, false); 5610 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5611 return true; 5612 } 5613 5614 return false; 5615 } 5616 5617 /// Check whether we should delete a special member function due to the class 5618 /// having a particular direct or virtual base class. 5619 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5620 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5621 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5622 } 5623 5624 /// Check whether we should delete a special member function due to the class 5625 /// having a particular non-static data member. 5626 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5627 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5628 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5629 5630 if (CSM == Sema::CXXDefaultConstructor) { 5631 // For a default constructor, all references must be initialized in-class 5632 // and, if a union, it must have a non-const member. 5633 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5634 if (Diagnose) 5635 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5636 << MD->getParent() << FD << FieldType << /*Reference*/0; 5637 return true; 5638 } 5639 // C++11 [class.ctor]p5: any non-variant non-static data member of 5640 // const-qualified type (or array thereof) with no 5641 // brace-or-equal-initializer does not have a user-provided default 5642 // constructor. 5643 if (!inUnion() && FieldType.isConstQualified() && 5644 !FD->hasInClassInitializer() && 5645 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5646 if (Diagnose) 5647 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5648 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5649 return true; 5650 } 5651 5652 if (inUnion() && !FieldType.isConstQualified()) 5653 AllFieldsAreConst = false; 5654 } else if (CSM == Sema::CXXCopyConstructor) { 5655 // For a copy constructor, data members must not be of rvalue reference 5656 // type. 5657 if (FieldType->isRValueReferenceType()) { 5658 if (Diagnose) 5659 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5660 << MD->getParent() << FD << FieldType; 5661 return true; 5662 } 5663 } else if (IsAssignment) { 5664 // For an assignment operator, data members must not be of reference type. 5665 if (FieldType->isReferenceType()) { 5666 if (Diagnose) 5667 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5668 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5669 return true; 5670 } 5671 if (!FieldRecord && FieldType.isConstQualified()) { 5672 // C++11 [class.copy]p23: 5673 // -- a non-static data member of const non-class type (or array thereof) 5674 if (Diagnose) 5675 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5676 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5677 return true; 5678 } 5679 } 5680 5681 if (FieldRecord) { 5682 // Some additional restrictions exist on the variant members. 5683 if (!inUnion() && FieldRecord->isUnion() && 5684 FieldRecord->isAnonymousStructOrUnion()) { 5685 bool AllVariantFieldsAreConst = true; 5686 5687 // FIXME: Handle anonymous unions declared within anonymous unions. 5688 for (auto *UI : FieldRecord->fields()) { 5689 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5690 5691 if (!UnionFieldType.isConstQualified()) 5692 AllVariantFieldsAreConst = false; 5693 5694 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5695 if (UnionFieldRecord && 5696 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5697 UnionFieldType.getCVRQualifiers())) 5698 return true; 5699 } 5700 5701 // At least one member in each anonymous union must be non-const 5702 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5703 !FieldRecord->field_empty()) { 5704 if (Diagnose) 5705 S.Diag(FieldRecord->getLocation(), 5706 diag::note_deleted_default_ctor_all_const) 5707 << MD->getParent() << /*anonymous union*/1; 5708 return true; 5709 } 5710 5711 // Don't check the implicit member of the anonymous union type. 5712 // This is technically non-conformant, but sanity demands it. 5713 return false; 5714 } 5715 5716 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5717 FieldType.getCVRQualifiers())) 5718 return true; 5719 } 5720 5721 return false; 5722 } 5723 5724 /// C++11 [class.ctor] p5: 5725 /// A defaulted default constructor for a class X is defined as deleted if 5726 /// X is a union and all of its variant members are of const-qualified type. 5727 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5728 // This is a silly definition, because it gives an empty union a deleted 5729 // default constructor. Don't do that. 5730 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5731 !MD->getParent()->field_empty()) { 5732 if (Diagnose) 5733 S.Diag(MD->getParent()->getLocation(), 5734 diag::note_deleted_default_ctor_all_const) 5735 << MD->getParent() << /*not anonymous union*/0; 5736 return true; 5737 } 5738 return false; 5739 } 5740 5741 /// Determine whether a defaulted special member function should be defined as 5742 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5743 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5744 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5745 bool Diagnose) { 5746 if (MD->isInvalidDecl()) 5747 return false; 5748 CXXRecordDecl *RD = MD->getParent(); 5749 assert(!RD->isDependentType() && "do deletion after instantiation"); 5750 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5751 return false; 5752 5753 // C++11 [expr.lambda.prim]p19: 5754 // The closure type associated with a lambda-expression has a 5755 // deleted (8.4.3) default constructor and a deleted copy 5756 // assignment operator. 5757 if (RD->isLambda() && 5758 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5759 if (Diagnose) 5760 Diag(RD->getLocation(), diag::note_lambda_decl); 5761 return true; 5762 } 5763 5764 // For an anonymous struct or union, the copy and assignment special members 5765 // will never be used, so skip the check. For an anonymous union declared at 5766 // namespace scope, the constructor and destructor are used. 5767 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5768 RD->isAnonymousStructOrUnion()) 5769 return false; 5770 5771 // C++11 [class.copy]p7, p18: 5772 // If the class definition declares a move constructor or move assignment 5773 // operator, an implicitly declared copy constructor or copy assignment 5774 // operator is defined as deleted. 5775 if (MD->isImplicit() && 5776 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5777 CXXMethodDecl *UserDeclaredMove = nullptr; 5778 5779 // In Microsoft mode, a user-declared move only causes the deletion of the 5780 // corresponding copy operation, not both copy operations. 5781 if (RD->hasUserDeclaredMoveConstructor() && 5782 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5783 if (!Diagnose) return true; 5784 5785 // Find any user-declared move constructor. 5786 for (auto *I : RD->ctors()) { 5787 if (I->isMoveConstructor()) { 5788 UserDeclaredMove = I; 5789 break; 5790 } 5791 } 5792 assert(UserDeclaredMove); 5793 } else if (RD->hasUserDeclaredMoveAssignment() && 5794 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5795 if (!Diagnose) return true; 5796 5797 // Find any user-declared move assignment operator. 5798 for (auto *I : RD->methods()) { 5799 if (I->isMoveAssignmentOperator()) { 5800 UserDeclaredMove = I; 5801 break; 5802 } 5803 } 5804 assert(UserDeclaredMove); 5805 } 5806 5807 if (UserDeclaredMove) { 5808 Diag(UserDeclaredMove->getLocation(), 5809 diag::note_deleted_copy_user_declared_move) 5810 << (CSM == CXXCopyAssignment) << RD 5811 << UserDeclaredMove->isMoveAssignmentOperator(); 5812 return true; 5813 } 5814 } 5815 5816 // Do access control from the special member function 5817 ContextRAII MethodContext(*this, MD); 5818 5819 // C++11 [class.dtor]p5: 5820 // -- for a virtual destructor, lookup of the non-array deallocation function 5821 // results in an ambiguity or in a function that is deleted or inaccessible 5822 if (CSM == CXXDestructor && MD->isVirtual()) { 5823 FunctionDecl *OperatorDelete = nullptr; 5824 DeclarationName Name = 5825 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5826 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5827 OperatorDelete, false)) { 5828 if (Diagnose) 5829 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5830 return true; 5831 } 5832 } 5833 5834 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5835 5836 for (auto &BI : RD->bases()) 5837 if (!BI.isVirtual() && 5838 SMI.shouldDeleteForBase(&BI)) 5839 return true; 5840 5841 // Per DR1611, do not consider virtual bases of constructors of abstract 5842 // classes, since we are not going to construct them. 5843 if (!RD->isAbstract() || !SMI.IsConstructor) { 5844 for (auto &BI : RD->vbases()) 5845 if (SMI.shouldDeleteForBase(&BI)) 5846 return true; 5847 } 5848 5849 for (auto *FI : RD->fields()) 5850 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5851 SMI.shouldDeleteForField(FI)) 5852 return true; 5853 5854 if (SMI.shouldDeleteForAllConstMembers()) 5855 return true; 5856 5857 if (getLangOpts().CUDA) { 5858 // We should delete the special member in CUDA mode if target inference 5859 // failed. 5860 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5861 Diagnose); 5862 } 5863 5864 return false; 5865 } 5866 5867 /// Perform lookup for a special member of the specified kind, and determine 5868 /// whether it is trivial. If the triviality can be determined without the 5869 /// lookup, skip it. This is intended for use when determining whether a 5870 /// special member of a containing object is trivial, and thus does not ever 5871 /// perform overload resolution for default constructors. 5872 /// 5873 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5874 /// member that was most likely to be intended to be trivial, if any. 5875 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5876 Sema::CXXSpecialMember CSM, unsigned Quals, 5877 bool ConstRHS, CXXMethodDecl **Selected) { 5878 if (Selected) 5879 *Selected = nullptr; 5880 5881 switch (CSM) { 5882 case Sema::CXXInvalid: 5883 llvm_unreachable("not a special member"); 5884 5885 case Sema::CXXDefaultConstructor: 5886 // C++11 [class.ctor]p5: 5887 // A default constructor is trivial if: 5888 // - all the [direct subobjects] have trivial default constructors 5889 // 5890 // Note, no overload resolution is performed in this case. 5891 if (RD->hasTrivialDefaultConstructor()) 5892 return true; 5893 5894 if (Selected) { 5895 // If there's a default constructor which could have been trivial, dig it 5896 // out. Otherwise, if there's any user-provided default constructor, point 5897 // to that as an example of why there's not a trivial one. 5898 CXXConstructorDecl *DefCtor = nullptr; 5899 if (RD->needsImplicitDefaultConstructor()) 5900 S.DeclareImplicitDefaultConstructor(RD); 5901 for (auto *CI : RD->ctors()) { 5902 if (!CI->isDefaultConstructor()) 5903 continue; 5904 DefCtor = CI; 5905 if (!DefCtor->isUserProvided()) 5906 break; 5907 } 5908 5909 *Selected = DefCtor; 5910 } 5911 5912 return false; 5913 5914 case Sema::CXXDestructor: 5915 // C++11 [class.dtor]p5: 5916 // A destructor is trivial if: 5917 // - all the direct [subobjects] have trivial destructors 5918 if (RD->hasTrivialDestructor()) 5919 return true; 5920 5921 if (Selected) { 5922 if (RD->needsImplicitDestructor()) 5923 S.DeclareImplicitDestructor(RD); 5924 *Selected = RD->getDestructor(); 5925 } 5926 5927 return false; 5928 5929 case Sema::CXXCopyConstructor: 5930 // C++11 [class.copy]p12: 5931 // A copy constructor is trivial if: 5932 // - the constructor selected to copy each direct [subobject] is trivial 5933 if (RD->hasTrivialCopyConstructor()) { 5934 if (Quals == Qualifiers::Const) 5935 // We must either select the trivial copy constructor or reach an 5936 // ambiguity; no need to actually perform overload resolution. 5937 return true; 5938 } else if (!Selected) { 5939 return false; 5940 } 5941 // In C++98, we are not supposed to perform overload resolution here, but we 5942 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5943 // cases like B as having a non-trivial copy constructor: 5944 // struct A { template<typename T> A(T&); }; 5945 // struct B { mutable A a; }; 5946 goto NeedOverloadResolution; 5947 5948 case Sema::CXXCopyAssignment: 5949 // C++11 [class.copy]p25: 5950 // A copy assignment operator is trivial if: 5951 // - the assignment operator selected to copy each direct [subobject] is 5952 // trivial 5953 if (RD->hasTrivialCopyAssignment()) { 5954 if (Quals == Qualifiers::Const) 5955 return true; 5956 } else if (!Selected) { 5957 return false; 5958 } 5959 // In C++98, we are not supposed to perform overload resolution here, but we 5960 // treat that as a language defect. 5961 goto NeedOverloadResolution; 5962 5963 case Sema::CXXMoveConstructor: 5964 case Sema::CXXMoveAssignment: 5965 NeedOverloadResolution: 5966 Sema::SpecialMemberOverloadResult *SMOR = 5967 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5968 5969 // The standard doesn't describe how to behave if the lookup is ambiguous. 5970 // We treat it as not making the member non-trivial, just like the standard 5971 // mandates for the default constructor. This should rarely matter, because 5972 // the member will also be deleted. 5973 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5974 return true; 5975 5976 if (!SMOR->getMethod()) { 5977 assert(SMOR->getKind() == 5978 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5979 return false; 5980 } 5981 5982 // We deliberately don't check if we found a deleted special member. We're 5983 // not supposed to! 5984 if (Selected) 5985 *Selected = SMOR->getMethod(); 5986 return SMOR->getMethod()->isTrivial(); 5987 } 5988 5989 llvm_unreachable("unknown special method kind"); 5990 } 5991 5992 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5993 for (auto *CI : RD->ctors()) 5994 if (!CI->isImplicit()) 5995 return CI; 5996 5997 // Look for constructor templates. 5998 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5999 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 6000 if (CXXConstructorDecl *CD = 6001 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 6002 return CD; 6003 } 6004 6005 return nullptr; 6006 } 6007 6008 /// The kind of subobject we are checking for triviality. The values of this 6009 /// enumeration are used in diagnostics. 6010 enum TrivialSubobjectKind { 6011 /// The subobject is a base class. 6012 TSK_BaseClass, 6013 /// The subobject is a non-static data member. 6014 TSK_Field, 6015 /// The object is actually the complete object. 6016 TSK_CompleteObject 6017 }; 6018 6019 /// Check whether the special member selected for a given type would be trivial. 6020 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 6021 QualType SubType, bool ConstRHS, 6022 Sema::CXXSpecialMember CSM, 6023 TrivialSubobjectKind Kind, 6024 bool Diagnose) { 6025 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 6026 if (!SubRD) 6027 return true; 6028 6029 CXXMethodDecl *Selected; 6030 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 6031 ConstRHS, Diagnose ? &Selected : nullptr)) 6032 return true; 6033 6034 if (Diagnose) { 6035 if (ConstRHS) 6036 SubType.addConst(); 6037 6038 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 6039 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 6040 << Kind << SubType.getUnqualifiedType(); 6041 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6042 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6043 } else if (!Selected) 6044 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6045 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6046 else if (Selected->isUserProvided()) { 6047 if (Kind == TSK_CompleteObject) 6048 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6049 << Kind << SubType.getUnqualifiedType() << CSM; 6050 else { 6051 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6052 << Kind << SubType.getUnqualifiedType() << CSM; 6053 S.Diag(Selected->getLocation(), diag::note_declared_at); 6054 } 6055 } else { 6056 if (Kind != TSK_CompleteObject) 6057 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6058 << Kind << SubType.getUnqualifiedType() << CSM; 6059 6060 // Explain why the defaulted or deleted special member isn't trivial. 6061 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6062 } 6063 } 6064 6065 return false; 6066 } 6067 6068 /// Check whether the members of a class type allow a special member to be 6069 /// trivial. 6070 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 6071 Sema::CXXSpecialMember CSM, 6072 bool ConstArg, bool Diagnose) { 6073 for (const auto *FI : RD->fields()) { 6074 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 6075 continue; 6076 6077 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 6078 6079 // Pretend anonymous struct or union members are members of this class. 6080 if (FI->isAnonymousStructOrUnion()) { 6081 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 6082 CSM, ConstArg, Diagnose)) 6083 return false; 6084 continue; 6085 } 6086 6087 // C++11 [class.ctor]p5: 6088 // A default constructor is trivial if [...] 6089 // -- no non-static data member of its class has a 6090 // brace-or-equal-initializer 6091 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 6092 if (Diagnose) 6093 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 6094 return false; 6095 } 6096 6097 // Objective C ARC 4.3.5: 6098 // [...] nontrivally ownership-qualified types are [...] not trivially 6099 // default constructible, copy constructible, move constructible, copy 6100 // assignable, move assignable, or destructible [...] 6101 if (S.getLangOpts().ObjCAutoRefCount && 6102 FieldType.hasNonTrivialObjCLifetime()) { 6103 if (Diagnose) 6104 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6105 << RD << FieldType.getObjCLifetime(); 6106 return false; 6107 } 6108 6109 bool ConstRHS = ConstArg && !FI->isMutable(); 6110 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6111 CSM, TSK_Field, Diagnose)) 6112 return false; 6113 } 6114 6115 return true; 6116 } 6117 6118 /// Diagnose why the specified class does not have a trivial special member of 6119 /// the given kind. 6120 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6121 QualType Ty = Context.getRecordType(RD); 6122 6123 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6124 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6125 TSK_CompleteObject, /*Diagnose*/true); 6126 } 6127 6128 /// Determine whether a defaulted or deleted special member function is trivial, 6129 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6130 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6131 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6132 bool Diagnose) { 6133 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6134 6135 CXXRecordDecl *RD = MD->getParent(); 6136 6137 bool ConstArg = false; 6138 6139 // C++11 [class.copy]p12, p25: [DR1593] 6140 // A [special member] is trivial if [...] its parameter-type-list is 6141 // equivalent to the parameter-type-list of an implicit declaration [...] 6142 switch (CSM) { 6143 case CXXDefaultConstructor: 6144 case CXXDestructor: 6145 // Trivial default constructors and destructors cannot have parameters. 6146 break; 6147 6148 case CXXCopyConstructor: 6149 case CXXCopyAssignment: { 6150 // Trivial copy operations always have const, non-volatile parameter types. 6151 ConstArg = true; 6152 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6153 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6154 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6155 if (Diagnose) 6156 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6157 << Param0->getSourceRange() << Param0->getType() 6158 << Context.getLValueReferenceType( 6159 Context.getRecordType(RD).withConst()); 6160 return false; 6161 } 6162 break; 6163 } 6164 6165 case CXXMoveConstructor: 6166 case CXXMoveAssignment: { 6167 // Trivial move operations always have non-cv-qualified parameters. 6168 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6169 const RValueReferenceType *RT = 6170 Param0->getType()->getAs<RValueReferenceType>(); 6171 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6172 if (Diagnose) 6173 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6174 << Param0->getSourceRange() << Param0->getType() 6175 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6176 return false; 6177 } 6178 break; 6179 } 6180 6181 case CXXInvalid: 6182 llvm_unreachable("not a special member"); 6183 } 6184 6185 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6186 if (Diagnose) 6187 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6188 diag::note_nontrivial_default_arg) 6189 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6190 return false; 6191 } 6192 if (MD->isVariadic()) { 6193 if (Diagnose) 6194 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6195 return false; 6196 } 6197 6198 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6199 // A copy/move [constructor or assignment operator] is trivial if 6200 // -- the [member] selected to copy/move each direct base class subobject 6201 // is trivial 6202 // 6203 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6204 // A [default constructor or destructor] is trivial if 6205 // -- all the direct base classes have trivial [default constructors or 6206 // destructors] 6207 for (const auto &BI : RD->bases()) 6208 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6209 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6210 return false; 6211 6212 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6213 // A copy/move [constructor or assignment operator] for a class X is 6214 // trivial if 6215 // -- for each non-static data member of X that is of class type (or array 6216 // thereof), the constructor selected to copy/move that member is 6217 // trivial 6218 // 6219 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6220 // A [default constructor or destructor] is trivial if 6221 // -- for all of the non-static data members of its class that are of class 6222 // type (or array thereof), each such class has a trivial [default 6223 // constructor or destructor] 6224 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6225 return false; 6226 6227 // C++11 [class.dtor]p5: 6228 // A destructor is trivial if [...] 6229 // -- the destructor is not virtual 6230 if (CSM == CXXDestructor && MD->isVirtual()) { 6231 if (Diagnose) 6232 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6233 return false; 6234 } 6235 6236 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6237 // A [special member] for class X is trivial if [...] 6238 // -- class X has no virtual functions and no virtual base classes 6239 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6240 if (!Diagnose) 6241 return false; 6242 6243 if (RD->getNumVBases()) { 6244 // Check for virtual bases. We already know that the corresponding 6245 // member in all bases is trivial, so vbases must all be direct. 6246 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6247 assert(BS.isVirtual()); 6248 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6249 return false; 6250 } 6251 6252 // Must have a virtual method. 6253 for (const auto *MI : RD->methods()) { 6254 if (MI->isVirtual()) { 6255 SourceLocation MLoc = MI->getLocStart(); 6256 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6257 return false; 6258 } 6259 } 6260 6261 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6262 } 6263 6264 // Looks like it's trivial! 6265 return true; 6266 } 6267 6268 /// \brief Data used with FindHiddenVirtualMethod 6269 namespace { 6270 struct FindHiddenVirtualMethodData { 6271 Sema *S; 6272 CXXMethodDecl *Method; 6273 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6274 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6275 }; 6276 } 6277 6278 /// \brief Check whether any most overriden method from MD in Methods 6279 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 6280 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6281 if (MD->size_overridden_methods() == 0) 6282 return Methods.count(MD->getCanonicalDecl()); 6283 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6284 E = MD->end_overridden_methods(); 6285 I != E; ++I) 6286 if (CheckMostOverridenMethods(*I, Methods)) 6287 return true; 6288 return false; 6289 } 6290 6291 /// \brief Member lookup function that determines whether a given C++ 6292 /// method overloads virtual methods in a base class without overriding any, 6293 /// to be used with CXXRecordDecl::lookupInBases(). 6294 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 6295 CXXBasePath &Path, 6296 void *UserData) { 6297 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6298 6299 FindHiddenVirtualMethodData &Data 6300 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 6301 6302 DeclarationName Name = Data.Method->getDeclName(); 6303 assert(Name.getNameKind() == DeclarationName::Identifier); 6304 6305 bool foundSameNameMethod = false; 6306 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6307 for (Path.Decls = BaseRecord->lookup(Name); 6308 !Path.Decls.empty(); 6309 Path.Decls = Path.Decls.slice(1)) { 6310 NamedDecl *D = Path.Decls.front(); 6311 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6312 MD = MD->getCanonicalDecl(); 6313 foundSameNameMethod = true; 6314 // Interested only in hidden virtual methods. 6315 if (!MD->isVirtual()) 6316 continue; 6317 // If the method we are checking overrides a method from its base 6318 // don't warn about the other overloaded methods. Clang deviates from GCC 6319 // by only diagnosing overloads of inherited virtual functions that do not 6320 // override any other virtual functions in the base. GCC's 6321 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6322 // function from a base class. These cases may be better served by a 6323 // warning (not specific to virtual functions) on call sites when the call 6324 // would select a different function from the base class, were it visible. 6325 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6326 if (!Data.S->IsOverload(Data.Method, MD, false)) 6327 return true; 6328 // Collect the overload only if its hidden. 6329 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 6330 overloadedMethods.push_back(MD); 6331 } 6332 } 6333 6334 if (foundSameNameMethod) 6335 Data.OverloadedMethods.append(overloadedMethods.begin(), 6336 overloadedMethods.end()); 6337 return foundSameNameMethod; 6338 } 6339 6340 /// \brief Add the most overriden methods from MD to Methods 6341 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6342 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6343 if (MD->size_overridden_methods() == 0) 6344 Methods.insert(MD->getCanonicalDecl()); 6345 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6346 E = MD->end_overridden_methods(); 6347 I != E; ++I) 6348 AddMostOverridenMethods(*I, Methods); 6349 } 6350 6351 /// \brief Check if a method overloads virtual methods in a base class without 6352 /// overriding any. 6353 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6354 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6355 if (!MD->getDeclName().isIdentifier()) 6356 return; 6357 6358 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6359 /*bool RecordPaths=*/false, 6360 /*bool DetectVirtual=*/false); 6361 FindHiddenVirtualMethodData Data; 6362 Data.Method = MD; 6363 Data.S = this; 6364 6365 // Keep the base methods that were overriden or introduced in the subclass 6366 // by 'using' in a set. A base method not in this set is hidden. 6367 CXXRecordDecl *DC = MD->getParent(); 6368 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6369 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6370 NamedDecl *ND = *I; 6371 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6372 ND = shad->getTargetDecl(); 6373 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6374 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6375 } 6376 6377 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6378 OverloadedMethods = Data.OverloadedMethods; 6379 } 6380 6381 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6382 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6383 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6384 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6385 PartialDiagnostic PD = PDiag( 6386 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6387 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6388 Diag(overloadedMD->getLocation(), PD); 6389 } 6390 } 6391 6392 /// \brief Diagnose methods which overload virtual methods in a base class 6393 /// without overriding any. 6394 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6395 if (MD->isInvalidDecl()) 6396 return; 6397 6398 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6399 return; 6400 6401 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6402 FindHiddenVirtualMethods(MD, OverloadedMethods); 6403 if (!OverloadedMethods.empty()) { 6404 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6405 << MD << (OverloadedMethods.size() > 1); 6406 6407 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6408 } 6409 } 6410 6411 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6412 Decl *TagDecl, 6413 SourceLocation LBrac, 6414 SourceLocation RBrac, 6415 AttributeList *AttrList) { 6416 if (!TagDecl) 6417 return; 6418 6419 AdjustDeclIfTemplate(TagDecl); 6420 6421 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6422 if (l->getKind() != AttributeList::AT_Visibility) 6423 continue; 6424 l->setInvalid(); 6425 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6426 l->getName(); 6427 } 6428 6429 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6430 // strict aliasing violation! 6431 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6432 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6433 6434 CheckCompletedCXXClass( 6435 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6436 } 6437 6438 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6439 /// special functions, such as the default constructor, copy 6440 /// constructor, or destructor, to the given C++ class (C++ 6441 /// [special]p1). This routine can only be executed just before the 6442 /// definition of the class is complete. 6443 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6444 if (!ClassDecl->hasUserDeclaredConstructor()) 6445 ++ASTContext::NumImplicitDefaultConstructors; 6446 6447 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6448 ++ASTContext::NumImplicitCopyConstructors; 6449 6450 // If the properties or semantics of the copy constructor couldn't be 6451 // determined while the class was being declared, force a declaration 6452 // of it now. 6453 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6454 DeclareImplicitCopyConstructor(ClassDecl); 6455 } 6456 6457 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6458 ++ASTContext::NumImplicitMoveConstructors; 6459 6460 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6461 DeclareImplicitMoveConstructor(ClassDecl); 6462 } 6463 6464 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6465 ++ASTContext::NumImplicitCopyAssignmentOperators; 6466 6467 // If we have a dynamic class, then the copy assignment operator may be 6468 // virtual, so we have to declare it immediately. This ensures that, e.g., 6469 // it shows up in the right place in the vtable and that we diagnose 6470 // problems with the implicit exception specification. 6471 if (ClassDecl->isDynamicClass() || 6472 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6473 DeclareImplicitCopyAssignment(ClassDecl); 6474 } 6475 6476 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6477 ++ASTContext::NumImplicitMoveAssignmentOperators; 6478 6479 // Likewise for the move assignment operator. 6480 if (ClassDecl->isDynamicClass() || 6481 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6482 DeclareImplicitMoveAssignment(ClassDecl); 6483 } 6484 6485 if (!ClassDecl->hasUserDeclaredDestructor()) { 6486 ++ASTContext::NumImplicitDestructors; 6487 6488 // If we have a dynamic class, then the destructor may be virtual, so we 6489 // have to declare the destructor immediately. This ensures that, e.g., it 6490 // shows up in the right place in the vtable and that we diagnose problems 6491 // with the implicit exception specification. 6492 if (ClassDecl->isDynamicClass() || 6493 ClassDecl->needsOverloadResolutionForDestructor()) 6494 DeclareImplicitDestructor(ClassDecl); 6495 } 6496 } 6497 6498 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6499 if (!D) 6500 return 0; 6501 6502 // The order of template parameters is not important here. All names 6503 // get added to the same scope. 6504 SmallVector<TemplateParameterList *, 4> ParameterLists; 6505 6506 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6507 D = TD->getTemplatedDecl(); 6508 6509 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6510 ParameterLists.push_back(PSD->getTemplateParameters()); 6511 6512 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6513 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6514 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6515 6516 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6517 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6518 ParameterLists.push_back(FTD->getTemplateParameters()); 6519 } 6520 } 6521 6522 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6523 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6524 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6525 6526 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6527 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6528 ParameterLists.push_back(CTD->getTemplateParameters()); 6529 } 6530 } 6531 6532 unsigned Count = 0; 6533 for (TemplateParameterList *Params : ParameterLists) { 6534 if (Params->size() > 0) 6535 // Ignore explicit specializations; they don't contribute to the template 6536 // depth. 6537 ++Count; 6538 for (NamedDecl *Param : *Params) { 6539 if (Param->getDeclName()) { 6540 S->AddDecl(Param); 6541 IdResolver.AddDecl(Param); 6542 } 6543 } 6544 } 6545 6546 return Count; 6547 } 6548 6549 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6550 if (!RecordD) return; 6551 AdjustDeclIfTemplate(RecordD); 6552 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6553 PushDeclContext(S, Record); 6554 } 6555 6556 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6557 if (!RecordD) return; 6558 PopDeclContext(); 6559 } 6560 6561 /// This is used to implement the constant expression evaluation part of the 6562 /// attribute enable_if extension. There is nothing in standard C++ which would 6563 /// require reentering parameters. 6564 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6565 if (!Param) 6566 return; 6567 6568 S->AddDecl(Param); 6569 if (Param->getDeclName()) 6570 IdResolver.AddDecl(Param); 6571 } 6572 6573 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6574 /// parsing a top-level (non-nested) C++ class, and we are now 6575 /// parsing those parts of the given Method declaration that could 6576 /// not be parsed earlier (C++ [class.mem]p2), such as default 6577 /// arguments. This action should enter the scope of the given 6578 /// Method declaration as if we had just parsed the qualified method 6579 /// name. However, it should not bring the parameters into scope; 6580 /// that will be performed by ActOnDelayedCXXMethodParameter. 6581 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6582 } 6583 6584 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6585 /// C++ method declaration. We're (re-)introducing the given 6586 /// function parameter into scope for use in parsing later parts of 6587 /// the method declaration. For example, we could see an 6588 /// ActOnParamDefaultArgument event for this parameter. 6589 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6590 if (!ParamD) 6591 return; 6592 6593 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6594 6595 // If this parameter has an unparsed default argument, clear it out 6596 // to make way for the parsed default argument. 6597 if (Param->hasUnparsedDefaultArg()) 6598 Param->setDefaultArg(nullptr); 6599 6600 S->AddDecl(Param); 6601 if (Param->getDeclName()) 6602 IdResolver.AddDecl(Param); 6603 } 6604 6605 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6606 /// processing the delayed method declaration for Method. The method 6607 /// declaration is now considered finished. There may be a separate 6608 /// ActOnStartOfFunctionDef action later (not necessarily 6609 /// immediately!) for this method, if it was also defined inside the 6610 /// class body. 6611 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6612 if (!MethodD) 6613 return; 6614 6615 AdjustDeclIfTemplate(MethodD); 6616 6617 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6618 6619 // Now that we have our default arguments, check the constructor 6620 // again. It could produce additional diagnostics or affect whether 6621 // the class has implicitly-declared destructors, among other 6622 // things. 6623 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6624 CheckConstructor(Constructor); 6625 6626 // Check the default arguments, which we may have added. 6627 if (!Method->isInvalidDecl()) 6628 CheckCXXDefaultArguments(Method); 6629 } 6630 6631 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6632 /// the well-formedness of the constructor declarator @p D with type @p 6633 /// R. If there are any errors in the declarator, this routine will 6634 /// emit diagnostics and set the invalid bit to true. In any case, the type 6635 /// will be updated to reflect a well-formed type for the constructor and 6636 /// returned. 6637 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6638 StorageClass &SC) { 6639 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6640 6641 // C++ [class.ctor]p3: 6642 // A constructor shall not be virtual (10.3) or static (9.4). A 6643 // constructor can be invoked for a const, volatile or const 6644 // volatile object. A constructor shall not be declared const, 6645 // volatile, or const volatile (9.3.2). 6646 if (isVirtual) { 6647 if (!D.isInvalidType()) 6648 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6649 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6650 << SourceRange(D.getIdentifierLoc()); 6651 D.setInvalidType(); 6652 } 6653 if (SC == SC_Static) { 6654 if (!D.isInvalidType()) 6655 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6656 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6657 << SourceRange(D.getIdentifierLoc()); 6658 D.setInvalidType(); 6659 SC = SC_None; 6660 } 6661 6662 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6663 diagnoseIgnoredQualifiers( 6664 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6665 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6666 D.getDeclSpec().getRestrictSpecLoc(), 6667 D.getDeclSpec().getAtomicSpecLoc()); 6668 D.setInvalidType(); 6669 } 6670 6671 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6672 if (FTI.TypeQuals != 0) { 6673 if (FTI.TypeQuals & Qualifiers::Const) 6674 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6675 << "const" << SourceRange(D.getIdentifierLoc()); 6676 if (FTI.TypeQuals & Qualifiers::Volatile) 6677 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6678 << "volatile" << SourceRange(D.getIdentifierLoc()); 6679 if (FTI.TypeQuals & Qualifiers::Restrict) 6680 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6681 << "restrict" << SourceRange(D.getIdentifierLoc()); 6682 D.setInvalidType(); 6683 } 6684 6685 // C++0x [class.ctor]p4: 6686 // A constructor shall not be declared with a ref-qualifier. 6687 if (FTI.hasRefQualifier()) { 6688 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6689 << FTI.RefQualifierIsLValueRef 6690 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6691 D.setInvalidType(); 6692 } 6693 6694 // Rebuild the function type "R" without any type qualifiers (in 6695 // case any of the errors above fired) and with "void" as the 6696 // return type, since constructors don't have return types. 6697 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6698 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6699 return R; 6700 6701 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6702 EPI.TypeQuals = 0; 6703 EPI.RefQualifier = RQ_None; 6704 6705 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6706 } 6707 6708 /// CheckConstructor - Checks a fully-formed constructor for 6709 /// well-formedness, issuing any diagnostics required. Returns true if 6710 /// the constructor declarator is invalid. 6711 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6712 CXXRecordDecl *ClassDecl 6713 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6714 if (!ClassDecl) 6715 return Constructor->setInvalidDecl(); 6716 6717 // C++ [class.copy]p3: 6718 // A declaration of a constructor for a class X is ill-formed if 6719 // its first parameter is of type (optionally cv-qualified) X and 6720 // either there are no other parameters or else all other 6721 // parameters have default arguments. 6722 if (!Constructor->isInvalidDecl() && 6723 ((Constructor->getNumParams() == 1) || 6724 (Constructor->getNumParams() > 1 && 6725 Constructor->getParamDecl(1)->hasDefaultArg())) && 6726 Constructor->getTemplateSpecializationKind() 6727 != TSK_ImplicitInstantiation) { 6728 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6729 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6730 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6731 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6732 const char *ConstRef 6733 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6734 : " const &"; 6735 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6736 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6737 6738 // FIXME: Rather that making the constructor invalid, we should endeavor 6739 // to fix the type. 6740 Constructor->setInvalidDecl(); 6741 } 6742 } 6743 } 6744 6745 /// CheckDestructor - Checks a fully-formed destructor definition for 6746 /// well-formedness, issuing any diagnostics required. Returns true 6747 /// on error. 6748 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6749 CXXRecordDecl *RD = Destructor->getParent(); 6750 6751 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6752 SourceLocation Loc; 6753 6754 if (!Destructor->isImplicit()) 6755 Loc = Destructor->getLocation(); 6756 else 6757 Loc = RD->getLocation(); 6758 6759 // If we have a virtual destructor, look up the deallocation function 6760 FunctionDecl *OperatorDelete = nullptr; 6761 DeclarationName Name = 6762 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6763 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6764 return true; 6765 // If there's no class-specific operator delete, look up the global 6766 // non-array delete. 6767 if (!OperatorDelete) 6768 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6769 6770 MarkFunctionReferenced(Loc, OperatorDelete); 6771 6772 Destructor->setOperatorDelete(OperatorDelete); 6773 } 6774 6775 return false; 6776 } 6777 6778 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6779 /// the well-formednes of the destructor declarator @p D with type @p 6780 /// R. If there are any errors in the declarator, this routine will 6781 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6782 /// will be updated to reflect a well-formed type for the destructor and 6783 /// returned. 6784 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6785 StorageClass& SC) { 6786 // C++ [class.dtor]p1: 6787 // [...] A typedef-name that names a class is a class-name 6788 // (7.1.3); however, a typedef-name that names a class shall not 6789 // be used as the identifier in the declarator for a destructor 6790 // declaration. 6791 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6792 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6793 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6794 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6795 else if (const TemplateSpecializationType *TST = 6796 DeclaratorType->getAs<TemplateSpecializationType>()) 6797 if (TST->isTypeAlias()) 6798 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6799 << DeclaratorType << 1; 6800 6801 // C++ [class.dtor]p2: 6802 // A destructor is used to destroy objects of its class type. A 6803 // destructor takes no parameters, and no return type can be 6804 // specified for it (not even void). The address of a destructor 6805 // shall not be taken. A destructor shall not be static. A 6806 // destructor can be invoked for a const, volatile or const 6807 // volatile object. A destructor shall not be declared const, 6808 // volatile or const volatile (9.3.2). 6809 if (SC == SC_Static) { 6810 if (!D.isInvalidType()) 6811 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6812 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6813 << SourceRange(D.getIdentifierLoc()) 6814 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6815 6816 SC = SC_None; 6817 } 6818 if (!D.isInvalidType()) { 6819 // Destructors don't have return types, but the parser will 6820 // happily parse something like: 6821 // 6822 // class X { 6823 // float ~X(); 6824 // }; 6825 // 6826 // The return type will be eliminated later. 6827 if (D.getDeclSpec().hasTypeSpecifier()) 6828 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6829 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6830 << SourceRange(D.getIdentifierLoc()); 6831 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6832 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6833 SourceLocation(), 6834 D.getDeclSpec().getConstSpecLoc(), 6835 D.getDeclSpec().getVolatileSpecLoc(), 6836 D.getDeclSpec().getRestrictSpecLoc(), 6837 D.getDeclSpec().getAtomicSpecLoc()); 6838 D.setInvalidType(); 6839 } 6840 } 6841 6842 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6843 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6844 if (FTI.TypeQuals & Qualifiers::Const) 6845 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6846 << "const" << SourceRange(D.getIdentifierLoc()); 6847 if (FTI.TypeQuals & Qualifiers::Volatile) 6848 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6849 << "volatile" << SourceRange(D.getIdentifierLoc()); 6850 if (FTI.TypeQuals & Qualifiers::Restrict) 6851 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6852 << "restrict" << SourceRange(D.getIdentifierLoc()); 6853 D.setInvalidType(); 6854 } 6855 6856 // C++0x [class.dtor]p2: 6857 // A destructor shall not be declared with a ref-qualifier. 6858 if (FTI.hasRefQualifier()) { 6859 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6860 << FTI.RefQualifierIsLValueRef 6861 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6862 D.setInvalidType(); 6863 } 6864 6865 // Make sure we don't have any parameters. 6866 if (FTIHasNonVoidParameters(FTI)) { 6867 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6868 6869 // Delete the parameters. 6870 FTI.freeParams(); 6871 D.setInvalidType(); 6872 } 6873 6874 // Make sure the destructor isn't variadic. 6875 if (FTI.isVariadic) { 6876 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6877 D.setInvalidType(); 6878 } 6879 6880 // Rebuild the function type "R" without any type qualifiers or 6881 // parameters (in case any of the errors above fired) and with 6882 // "void" as the return type, since destructors don't have return 6883 // types. 6884 if (!D.isInvalidType()) 6885 return R; 6886 6887 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6888 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6889 EPI.Variadic = false; 6890 EPI.TypeQuals = 0; 6891 EPI.RefQualifier = RQ_None; 6892 return Context.getFunctionType(Context.VoidTy, None, EPI); 6893 } 6894 6895 static void extendLeft(SourceRange &R, const SourceRange &Before) { 6896 if (Before.isInvalid()) 6897 return; 6898 R.setBegin(Before.getBegin()); 6899 if (R.getEnd().isInvalid()) 6900 R.setEnd(Before.getEnd()); 6901 } 6902 6903 static void extendRight(SourceRange &R, const SourceRange &After) { 6904 if (After.isInvalid()) 6905 return; 6906 if (R.getBegin().isInvalid()) 6907 R.setBegin(After.getBegin()); 6908 R.setEnd(After.getEnd()); 6909 } 6910 6911 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6912 /// well-formednes of the conversion function declarator @p D with 6913 /// type @p R. If there are any errors in the declarator, this routine 6914 /// will emit diagnostics and return true. Otherwise, it will return 6915 /// false. Either way, the type @p R will be updated to reflect a 6916 /// well-formed type for the conversion operator. 6917 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6918 StorageClass& SC) { 6919 // C++ [class.conv.fct]p1: 6920 // Neither parameter types nor return type can be specified. The 6921 // type of a conversion function (8.3.5) is "function taking no 6922 // parameter returning conversion-type-id." 6923 if (SC == SC_Static) { 6924 if (!D.isInvalidType()) 6925 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6926 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6927 << D.getName().getSourceRange(); 6928 D.setInvalidType(); 6929 SC = SC_None; 6930 } 6931 6932 TypeSourceInfo *ConvTSI = nullptr; 6933 QualType ConvType = 6934 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 6935 6936 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6937 // Conversion functions don't have return types, but the parser will 6938 // happily parse something like: 6939 // 6940 // class X { 6941 // float operator bool(); 6942 // }; 6943 // 6944 // The return type will be changed later anyway. 6945 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6946 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6947 << SourceRange(D.getIdentifierLoc()); 6948 D.setInvalidType(); 6949 } 6950 6951 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6952 6953 // Make sure we don't have any parameters. 6954 if (Proto->getNumParams() > 0) { 6955 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6956 6957 // Delete the parameters. 6958 D.getFunctionTypeInfo().freeParams(); 6959 D.setInvalidType(); 6960 } else if (Proto->isVariadic()) { 6961 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6962 D.setInvalidType(); 6963 } 6964 6965 // Diagnose "&operator bool()" and other such nonsense. This 6966 // is actually a gcc extension which we don't support. 6967 if (Proto->getReturnType() != ConvType) { 6968 bool NeedsTypedef = false; 6969 SourceRange Before, After; 6970 6971 // Walk the chunks and extract information on them for our diagnostic. 6972 bool PastFunctionChunk = false; 6973 for (auto &Chunk : D.type_objects()) { 6974 switch (Chunk.Kind) { 6975 case DeclaratorChunk::Function: 6976 if (!PastFunctionChunk) { 6977 if (Chunk.Fun.HasTrailingReturnType) { 6978 TypeSourceInfo *TRT = nullptr; 6979 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 6980 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 6981 } 6982 PastFunctionChunk = true; 6983 break; 6984 } 6985 // Fall through. 6986 case DeclaratorChunk::Array: 6987 NeedsTypedef = true; 6988 extendRight(After, Chunk.getSourceRange()); 6989 break; 6990 6991 case DeclaratorChunk::Pointer: 6992 case DeclaratorChunk::BlockPointer: 6993 case DeclaratorChunk::Reference: 6994 case DeclaratorChunk::MemberPointer: 6995 extendLeft(Before, Chunk.getSourceRange()); 6996 break; 6997 6998 case DeclaratorChunk::Paren: 6999 extendLeft(Before, Chunk.Loc); 7000 extendRight(After, Chunk.EndLoc); 7001 break; 7002 } 7003 } 7004 7005 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 7006 After.isValid() ? After.getBegin() : 7007 D.getIdentifierLoc(); 7008 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 7009 DB << Before << After; 7010 7011 if (!NeedsTypedef) { 7012 DB << /*don't need a typedef*/0; 7013 7014 // If we can provide a correct fix-it hint, do so. 7015 if (After.isInvalid() && ConvTSI) { 7016 SourceLocation InsertLoc = 7017 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 7018 DB << FixItHint::CreateInsertion(InsertLoc, " ") 7019 << FixItHint::CreateInsertionFromRange( 7020 InsertLoc, CharSourceRange::getTokenRange(Before)) 7021 << FixItHint::CreateRemoval(Before); 7022 } 7023 } else if (!Proto->getReturnType()->isDependentType()) { 7024 DB << /*typedef*/1 << Proto->getReturnType(); 7025 } else if (getLangOpts().CPlusPlus11) { 7026 DB << /*alias template*/2 << Proto->getReturnType(); 7027 } else { 7028 DB << /*might not be fixable*/3; 7029 } 7030 7031 // Recover by incorporating the other type chunks into the result type. 7032 // Note, this does *not* change the name of the function. This is compatible 7033 // with the GCC extension: 7034 // struct S { &operator int(); } s; 7035 // int &r = s.operator int(); // ok in GCC 7036 // S::operator int&() {} // error in GCC, function name is 'operator int'. 7037 ConvType = Proto->getReturnType(); 7038 } 7039 7040 // C++ [class.conv.fct]p4: 7041 // The conversion-type-id shall not represent a function type nor 7042 // an array type. 7043 if (ConvType->isArrayType()) { 7044 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7045 ConvType = Context.getPointerType(ConvType); 7046 D.setInvalidType(); 7047 } else if (ConvType->isFunctionType()) { 7048 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7049 ConvType = Context.getPointerType(ConvType); 7050 D.setInvalidType(); 7051 } 7052 7053 // Rebuild the function type "R" without any parameters (in case any 7054 // of the errors above fired) and with the conversion type as the 7055 // return type. 7056 if (D.isInvalidType()) 7057 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7058 7059 // C++0x explicit conversion operators. 7060 if (D.getDeclSpec().isExplicitSpecified()) 7061 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7062 getLangOpts().CPlusPlus11 ? 7063 diag::warn_cxx98_compat_explicit_conversion_functions : 7064 diag::ext_explicit_conversion_functions) 7065 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 7066 } 7067 7068 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 7069 /// the declaration of the given C++ conversion function. This routine 7070 /// is responsible for recording the conversion function in the C++ 7071 /// class, if possible. 7072 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 7073 assert(Conversion && "Expected to receive a conversion function declaration"); 7074 7075 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 7076 7077 // Make sure we aren't redeclaring the conversion function. 7078 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 7079 7080 // C++ [class.conv.fct]p1: 7081 // [...] A conversion function is never used to convert a 7082 // (possibly cv-qualified) object to the (possibly cv-qualified) 7083 // same object type (or a reference to it), to a (possibly 7084 // cv-qualified) base class of that type (or a reference to it), 7085 // or to (possibly cv-qualified) void. 7086 // FIXME: Suppress this warning if the conversion function ends up being a 7087 // virtual function that overrides a virtual function in a base class. 7088 QualType ClassType 7089 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7090 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 7091 ConvType = ConvTypeRef->getPointeeType(); 7092 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 7093 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 7094 /* Suppress diagnostics for instantiations. */; 7095 else if (ConvType->isRecordType()) { 7096 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 7097 if (ConvType == ClassType) 7098 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 7099 << ClassType; 7100 else if (IsDerivedFrom(ClassType, ConvType)) 7101 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 7102 << ClassType << ConvType; 7103 } else if (ConvType->isVoidType()) { 7104 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 7105 << ClassType << ConvType; 7106 } 7107 7108 if (FunctionTemplateDecl *ConversionTemplate 7109 = Conversion->getDescribedFunctionTemplate()) 7110 return ConversionTemplate; 7111 7112 return Conversion; 7113 } 7114 7115 //===----------------------------------------------------------------------===// 7116 // Namespace Handling 7117 //===----------------------------------------------------------------------===// 7118 7119 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 7120 /// reopened. 7121 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 7122 SourceLocation Loc, 7123 IdentifierInfo *II, bool *IsInline, 7124 NamespaceDecl *PrevNS) { 7125 assert(*IsInline != PrevNS->isInline()); 7126 7127 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 7128 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 7129 // inline namespaces, with the intention of bringing names into namespace std. 7130 // 7131 // We support this just well enough to get that case working; this is not 7132 // sufficient to support reopening namespaces as inline in general. 7133 if (*IsInline && II && II->getName().startswith("__atomic") && 7134 S.getSourceManager().isInSystemHeader(Loc)) { 7135 // Mark all prior declarations of the namespace as inline. 7136 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 7137 NS = NS->getPreviousDecl()) 7138 NS->setInline(*IsInline); 7139 // Patch up the lookup table for the containing namespace. This isn't really 7140 // correct, but it's good enough for this particular case. 7141 for (auto *I : PrevNS->decls()) 7142 if (auto *ND = dyn_cast<NamedDecl>(I)) 7143 PrevNS->getParent()->makeDeclVisibleInContext(ND); 7144 return; 7145 } 7146 7147 if (PrevNS->isInline()) 7148 // The user probably just forgot the 'inline', so suggest that it 7149 // be added back. 7150 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 7151 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 7152 else 7153 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 7154 7155 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 7156 *IsInline = PrevNS->isInline(); 7157 } 7158 7159 /// ActOnStartNamespaceDef - This is called at the start of a namespace 7160 /// definition. 7161 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 7162 SourceLocation InlineLoc, 7163 SourceLocation NamespaceLoc, 7164 SourceLocation IdentLoc, 7165 IdentifierInfo *II, 7166 SourceLocation LBrace, 7167 AttributeList *AttrList) { 7168 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 7169 // For anonymous namespace, take the location of the left brace. 7170 SourceLocation Loc = II ? IdentLoc : LBrace; 7171 bool IsInline = InlineLoc.isValid(); 7172 bool IsInvalid = false; 7173 bool IsStd = false; 7174 bool AddToKnown = false; 7175 Scope *DeclRegionScope = NamespcScope->getParent(); 7176 7177 NamespaceDecl *PrevNS = nullptr; 7178 if (II) { 7179 // C++ [namespace.def]p2: 7180 // The identifier in an original-namespace-definition shall not 7181 // have been previously defined in the declarative region in 7182 // which the original-namespace-definition appears. The 7183 // identifier in an original-namespace-definition is the name of 7184 // the namespace. Subsequently in that declarative region, it is 7185 // treated as an original-namespace-name. 7186 // 7187 // Since namespace names are unique in their scope, and we don't 7188 // look through using directives, just look for any ordinary names. 7189 7190 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 7191 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 7192 Decl::IDNS_Namespace; 7193 NamedDecl *PrevDecl = nullptr; 7194 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 7195 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 7196 ++I) { 7197 if ((*I)->getIdentifierNamespace() & IDNS) { 7198 PrevDecl = *I; 7199 break; 7200 } 7201 } 7202 7203 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7204 7205 if (PrevNS) { 7206 // This is an extended namespace definition. 7207 if (IsInline != PrevNS->isInline()) 7208 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7209 &IsInline, PrevNS); 7210 } else if (PrevDecl) { 7211 // This is an invalid name redefinition. 7212 Diag(Loc, diag::err_redefinition_different_kind) 7213 << II; 7214 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7215 IsInvalid = true; 7216 // Continue on to push Namespc as current DeclContext and return it. 7217 } else if (II->isStr("std") && 7218 CurContext->getRedeclContext()->isTranslationUnit()) { 7219 // This is the first "real" definition of the namespace "std", so update 7220 // our cache of the "std" namespace to point at this definition. 7221 PrevNS = getStdNamespace(); 7222 IsStd = true; 7223 AddToKnown = !IsInline; 7224 } else { 7225 // We've seen this namespace for the first time. 7226 AddToKnown = !IsInline; 7227 } 7228 } else { 7229 // Anonymous namespaces. 7230 7231 // Determine whether the parent already has an anonymous namespace. 7232 DeclContext *Parent = CurContext->getRedeclContext(); 7233 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7234 PrevNS = TU->getAnonymousNamespace(); 7235 } else { 7236 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7237 PrevNS = ND->getAnonymousNamespace(); 7238 } 7239 7240 if (PrevNS && IsInline != PrevNS->isInline()) 7241 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7242 &IsInline, PrevNS); 7243 } 7244 7245 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7246 StartLoc, Loc, II, PrevNS); 7247 if (IsInvalid) 7248 Namespc->setInvalidDecl(); 7249 7250 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7251 7252 // FIXME: Should we be merging attributes? 7253 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7254 PushNamespaceVisibilityAttr(Attr, Loc); 7255 7256 if (IsStd) 7257 StdNamespace = Namespc; 7258 if (AddToKnown) 7259 KnownNamespaces[Namespc] = false; 7260 7261 if (II) { 7262 PushOnScopeChains(Namespc, DeclRegionScope); 7263 } else { 7264 // Link the anonymous namespace into its parent. 7265 DeclContext *Parent = CurContext->getRedeclContext(); 7266 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7267 TU->setAnonymousNamespace(Namespc); 7268 } else { 7269 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7270 } 7271 7272 CurContext->addDecl(Namespc); 7273 7274 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7275 // behaves as if it were replaced by 7276 // namespace unique { /* empty body */ } 7277 // using namespace unique; 7278 // namespace unique { namespace-body } 7279 // where all occurrences of 'unique' in a translation unit are 7280 // replaced by the same identifier and this identifier differs 7281 // from all other identifiers in the entire program. 7282 7283 // We just create the namespace with an empty name and then add an 7284 // implicit using declaration, just like the standard suggests. 7285 // 7286 // CodeGen enforces the "universally unique" aspect by giving all 7287 // declarations semantically contained within an anonymous 7288 // namespace internal linkage. 7289 7290 if (!PrevNS) { 7291 UsingDirectiveDecl* UD 7292 = UsingDirectiveDecl::Create(Context, Parent, 7293 /* 'using' */ LBrace, 7294 /* 'namespace' */ SourceLocation(), 7295 /* qualifier */ NestedNameSpecifierLoc(), 7296 /* identifier */ SourceLocation(), 7297 Namespc, 7298 /* Ancestor */ Parent); 7299 UD->setImplicit(); 7300 Parent->addDecl(UD); 7301 } 7302 } 7303 7304 ActOnDocumentableDecl(Namespc); 7305 7306 // Although we could have an invalid decl (i.e. the namespace name is a 7307 // redefinition), push it as current DeclContext and try to continue parsing. 7308 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7309 // for the namespace has the declarations that showed up in that particular 7310 // namespace definition. 7311 PushDeclContext(NamespcScope, Namespc); 7312 return Namespc; 7313 } 7314 7315 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7316 /// is a namespace alias, returns the namespace it points to. 7317 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7318 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7319 return AD->getNamespace(); 7320 return dyn_cast_or_null<NamespaceDecl>(D); 7321 } 7322 7323 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7324 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7325 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7326 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7327 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7328 Namespc->setRBraceLoc(RBrace); 7329 PopDeclContext(); 7330 if (Namespc->hasAttr<VisibilityAttr>()) 7331 PopPragmaVisibility(true, RBrace); 7332 } 7333 7334 CXXRecordDecl *Sema::getStdBadAlloc() const { 7335 return cast_or_null<CXXRecordDecl>( 7336 StdBadAlloc.get(Context.getExternalSource())); 7337 } 7338 7339 NamespaceDecl *Sema::getStdNamespace() const { 7340 return cast_or_null<NamespaceDecl>( 7341 StdNamespace.get(Context.getExternalSource())); 7342 } 7343 7344 /// \brief Retrieve the special "std" namespace, which may require us to 7345 /// implicitly define the namespace. 7346 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7347 if (!StdNamespace) { 7348 // The "std" namespace has not yet been defined, so build one implicitly. 7349 StdNamespace = NamespaceDecl::Create(Context, 7350 Context.getTranslationUnitDecl(), 7351 /*Inline=*/false, 7352 SourceLocation(), SourceLocation(), 7353 &PP.getIdentifierTable().get("std"), 7354 /*PrevDecl=*/nullptr); 7355 getStdNamespace()->setImplicit(true); 7356 } 7357 7358 return getStdNamespace(); 7359 } 7360 7361 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7362 assert(getLangOpts().CPlusPlus && 7363 "Looking for std::initializer_list outside of C++."); 7364 7365 // We're looking for implicit instantiations of 7366 // template <typename E> class std::initializer_list. 7367 7368 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7369 return false; 7370 7371 ClassTemplateDecl *Template = nullptr; 7372 const TemplateArgument *Arguments = nullptr; 7373 7374 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7375 7376 ClassTemplateSpecializationDecl *Specialization = 7377 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7378 if (!Specialization) 7379 return false; 7380 7381 Template = Specialization->getSpecializedTemplate(); 7382 Arguments = Specialization->getTemplateArgs().data(); 7383 } else if (const TemplateSpecializationType *TST = 7384 Ty->getAs<TemplateSpecializationType>()) { 7385 Template = dyn_cast_or_null<ClassTemplateDecl>( 7386 TST->getTemplateName().getAsTemplateDecl()); 7387 Arguments = TST->getArgs(); 7388 } 7389 if (!Template) 7390 return false; 7391 7392 if (!StdInitializerList) { 7393 // Haven't recognized std::initializer_list yet, maybe this is it. 7394 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7395 if (TemplateClass->getIdentifier() != 7396 &PP.getIdentifierTable().get("initializer_list") || 7397 !getStdNamespace()->InEnclosingNamespaceSetOf( 7398 TemplateClass->getDeclContext())) 7399 return false; 7400 // This is a template called std::initializer_list, but is it the right 7401 // template? 7402 TemplateParameterList *Params = Template->getTemplateParameters(); 7403 if (Params->getMinRequiredArguments() != 1) 7404 return false; 7405 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7406 return false; 7407 7408 // It's the right template. 7409 StdInitializerList = Template; 7410 } 7411 7412 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 7413 return false; 7414 7415 // This is an instance of std::initializer_list. Find the argument type. 7416 if (Element) 7417 *Element = Arguments[0].getAsType(); 7418 return true; 7419 } 7420 7421 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7422 NamespaceDecl *Std = S.getStdNamespace(); 7423 if (!Std) { 7424 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7425 return nullptr; 7426 } 7427 7428 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7429 Loc, Sema::LookupOrdinaryName); 7430 if (!S.LookupQualifiedName(Result, Std)) { 7431 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7432 return nullptr; 7433 } 7434 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7435 if (!Template) { 7436 Result.suppressDiagnostics(); 7437 // We found something weird. Complain about the first thing we found. 7438 NamedDecl *Found = *Result.begin(); 7439 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7440 return nullptr; 7441 } 7442 7443 // We found some template called std::initializer_list. Now verify that it's 7444 // correct. 7445 TemplateParameterList *Params = Template->getTemplateParameters(); 7446 if (Params->getMinRequiredArguments() != 1 || 7447 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7448 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7449 return nullptr; 7450 } 7451 7452 return Template; 7453 } 7454 7455 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7456 if (!StdInitializerList) { 7457 StdInitializerList = LookupStdInitializerList(*this, Loc); 7458 if (!StdInitializerList) 7459 return QualType(); 7460 } 7461 7462 TemplateArgumentListInfo Args(Loc, Loc); 7463 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7464 Context.getTrivialTypeSourceInfo(Element, 7465 Loc))); 7466 return Context.getCanonicalType( 7467 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7468 } 7469 7470 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7471 // C++ [dcl.init.list]p2: 7472 // A constructor is an initializer-list constructor if its first parameter 7473 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7474 // std::initializer_list<E> for some type E, and either there are no other 7475 // parameters or else all other parameters have default arguments. 7476 if (Ctor->getNumParams() < 1 || 7477 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7478 return false; 7479 7480 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7481 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7482 ArgType = RT->getPointeeType().getUnqualifiedType(); 7483 7484 return isStdInitializerList(ArgType, nullptr); 7485 } 7486 7487 /// \brief Determine whether a using statement is in a context where it will be 7488 /// apply in all contexts. 7489 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7490 switch (CurContext->getDeclKind()) { 7491 case Decl::TranslationUnit: 7492 return true; 7493 case Decl::LinkageSpec: 7494 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7495 default: 7496 return false; 7497 } 7498 } 7499 7500 namespace { 7501 7502 // Callback to only accept typo corrections that are namespaces. 7503 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7504 public: 7505 bool ValidateCandidate(const TypoCorrection &candidate) override { 7506 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7507 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7508 return false; 7509 } 7510 }; 7511 7512 } 7513 7514 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7515 CXXScopeSpec &SS, 7516 SourceLocation IdentLoc, 7517 IdentifierInfo *Ident) { 7518 R.clear(); 7519 if (TypoCorrection Corrected = 7520 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7521 llvm::make_unique<NamespaceValidatorCCC>(), 7522 Sema::CTK_ErrorRecovery)) { 7523 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7524 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7525 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7526 Ident->getName().equals(CorrectedStr); 7527 S.diagnoseTypo(Corrected, 7528 S.PDiag(diag::err_using_directive_member_suggest) 7529 << Ident << DC << DroppedSpecifier << SS.getRange(), 7530 S.PDiag(diag::note_namespace_defined_here)); 7531 } else { 7532 S.diagnoseTypo(Corrected, 7533 S.PDiag(diag::err_using_directive_suggest) << Ident, 7534 S.PDiag(diag::note_namespace_defined_here)); 7535 } 7536 R.addDecl(Corrected.getCorrectionDecl()); 7537 return true; 7538 } 7539 return false; 7540 } 7541 7542 Decl *Sema::ActOnUsingDirective(Scope *S, 7543 SourceLocation UsingLoc, 7544 SourceLocation NamespcLoc, 7545 CXXScopeSpec &SS, 7546 SourceLocation IdentLoc, 7547 IdentifierInfo *NamespcName, 7548 AttributeList *AttrList) { 7549 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7550 assert(NamespcName && "Invalid NamespcName."); 7551 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7552 7553 // This can only happen along a recovery path. 7554 while (S->getFlags() & Scope::TemplateParamScope) 7555 S = S->getParent(); 7556 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7557 7558 UsingDirectiveDecl *UDir = nullptr; 7559 NestedNameSpecifier *Qualifier = nullptr; 7560 if (SS.isSet()) 7561 Qualifier = SS.getScopeRep(); 7562 7563 // Lookup namespace name. 7564 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7565 LookupParsedName(R, S, &SS); 7566 if (R.isAmbiguous()) 7567 return nullptr; 7568 7569 if (R.empty()) { 7570 R.clear(); 7571 // Allow "using namespace std;" or "using namespace ::std;" even if 7572 // "std" hasn't been defined yet, for GCC compatibility. 7573 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7574 NamespcName->isStr("std")) { 7575 Diag(IdentLoc, diag::ext_using_undefined_std); 7576 R.addDecl(getOrCreateStdNamespace()); 7577 R.resolveKind(); 7578 } 7579 // Otherwise, attempt typo correction. 7580 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7581 } 7582 7583 if (!R.empty()) { 7584 NamedDecl *Named = R.getFoundDecl(); 7585 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7586 && "expected namespace decl"); 7587 7588 // The use of a nested name specifier may trigger deprecation warnings. 7589 DiagnoseUseOfDecl(Named, IdentLoc); 7590 7591 // C++ [namespace.udir]p1: 7592 // A using-directive specifies that the names in the nominated 7593 // namespace can be used in the scope in which the 7594 // using-directive appears after the using-directive. During 7595 // unqualified name lookup (3.4.1), the names appear as if they 7596 // were declared in the nearest enclosing namespace which 7597 // contains both the using-directive and the nominated 7598 // namespace. [Note: in this context, "contains" means "contains 7599 // directly or indirectly". ] 7600 7601 // Find enclosing context containing both using-directive and 7602 // nominated namespace. 7603 NamespaceDecl *NS = getNamespaceDecl(Named); 7604 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7605 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7606 CommonAncestor = CommonAncestor->getParent(); 7607 7608 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7609 SS.getWithLocInContext(Context), 7610 IdentLoc, Named, CommonAncestor); 7611 7612 if (IsUsingDirectiveInToplevelContext(CurContext) && 7613 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7614 Diag(IdentLoc, diag::warn_using_directive_in_header); 7615 } 7616 7617 PushUsingDirective(S, UDir); 7618 } else { 7619 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7620 } 7621 7622 if (UDir) 7623 ProcessDeclAttributeList(S, UDir, AttrList); 7624 7625 return UDir; 7626 } 7627 7628 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7629 // If the scope has an associated entity and the using directive is at 7630 // namespace or translation unit scope, add the UsingDirectiveDecl into 7631 // its lookup structure so qualified name lookup can find it. 7632 DeclContext *Ctx = S->getEntity(); 7633 if (Ctx && !Ctx->isFunctionOrMethod()) 7634 Ctx->addDecl(UDir); 7635 else 7636 // Otherwise, it is at block scope. The using-directives will affect lookup 7637 // only to the end of the scope. 7638 S->PushUsingDirective(UDir); 7639 } 7640 7641 7642 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7643 AccessSpecifier AS, 7644 bool HasUsingKeyword, 7645 SourceLocation UsingLoc, 7646 CXXScopeSpec &SS, 7647 UnqualifiedId &Name, 7648 AttributeList *AttrList, 7649 bool HasTypenameKeyword, 7650 SourceLocation TypenameLoc) { 7651 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7652 7653 switch (Name.getKind()) { 7654 case UnqualifiedId::IK_ImplicitSelfParam: 7655 case UnqualifiedId::IK_Identifier: 7656 case UnqualifiedId::IK_OperatorFunctionId: 7657 case UnqualifiedId::IK_LiteralOperatorId: 7658 case UnqualifiedId::IK_ConversionFunctionId: 7659 break; 7660 7661 case UnqualifiedId::IK_ConstructorName: 7662 case UnqualifiedId::IK_ConstructorTemplateId: 7663 // C++11 inheriting constructors. 7664 Diag(Name.getLocStart(), 7665 getLangOpts().CPlusPlus11 ? 7666 diag::warn_cxx98_compat_using_decl_constructor : 7667 diag::err_using_decl_constructor) 7668 << SS.getRange(); 7669 7670 if (getLangOpts().CPlusPlus11) break; 7671 7672 return nullptr; 7673 7674 case UnqualifiedId::IK_DestructorName: 7675 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7676 << SS.getRange(); 7677 return nullptr; 7678 7679 case UnqualifiedId::IK_TemplateId: 7680 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7681 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7682 return nullptr; 7683 } 7684 7685 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7686 DeclarationName TargetName = TargetNameInfo.getName(); 7687 if (!TargetName) 7688 return nullptr; 7689 7690 // Warn about access declarations. 7691 if (!HasUsingKeyword) { 7692 Diag(Name.getLocStart(), 7693 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7694 : diag::warn_access_decl_deprecated) 7695 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7696 } 7697 7698 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7699 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7700 return nullptr; 7701 7702 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7703 TargetNameInfo, AttrList, 7704 /* IsInstantiation */ false, 7705 HasTypenameKeyword, TypenameLoc); 7706 if (UD) 7707 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7708 7709 return UD; 7710 } 7711 7712 /// \brief Determine whether a using declaration considers the given 7713 /// declarations as "equivalent", e.g., if they are redeclarations of 7714 /// the same entity or are both typedefs of the same type. 7715 static bool 7716 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7717 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7718 return true; 7719 7720 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7721 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7722 return Context.hasSameType(TD1->getUnderlyingType(), 7723 TD2->getUnderlyingType()); 7724 7725 return false; 7726 } 7727 7728 7729 /// Determines whether to create a using shadow decl for a particular 7730 /// decl, given the set of decls existing prior to this using lookup. 7731 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7732 const LookupResult &Previous, 7733 UsingShadowDecl *&PrevShadow) { 7734 // Diagnose finding a decl which is not from a base class of the 7735 // current class. We do this now because there are cases where this 7736 // function will silently decide not to build a shadow decl, which 7737 // will pre-empt further diagnostics. 7738 // 7739 // We don't need to do this in C++0x because we do the check once on 7740 // the qualifier. 7741 // 7742 // FIXME: diagnose the following if we care enough: 7743 // struct A { int foo; }; 7744 // struct B : A { using A::foo; }; 7745 // template <class T> struct C : A {}; 7746 // template <class T> struct D : C<T> { using B::foo; } // <--- 7747 // This is invalid (during instantiation) in C++03 because B::foo 7748 // resolves to the using decl in B, which is not a base class of D<T>. 7749 // We can't diagnose it immediately because C<T> is an unknown 7750 // specialization. The UsingShadowDecl in D<T> then points directly 7751 // to A::foo, which will look well-formed when we instantiate. 7752 // The right solution is to not collapse the shadow-decl chain. 7753 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7754 DeclContext *OrigDC = Orig->getDeclContext(); 7755 7756 // Handle enums and anonymous structs. 7757 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7758 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7759 while (OrigRec->isAnonymousStructOrUnion()) 7760 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7761 7762 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7763 if (OrigDC == CurContext) { 7764 Diag(Using->getLocation(), 7765 diag::err_using_decl_nested_name_specifier_is_current_class) 7766 << Using->getQualifierLoc().getSourceRange(); 7767 Diag(Orig->getLocation(), diag::note_using_decl_target); 7768 return true; 7769 } 7770 7771 Diag(Using->getQualifierLoc().getBeginLoc(), 7772 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7773 << Using->getQualifier() 7774 << cast<CXXRecordDecl>(CurContext) 7775 << Using->getQualifierLoc().getSourceRange(); 7776 Diag(Orig->getLocation(), diag::note_using_decl_target); 7777 return true; 7778 } 7779 } 7780 7781 if (Previous.empty()) return false; 7782 7783 NamedDecl *Target = Orig; 7784 if (isa<UsingShadowDecl>(Target)) 7785 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7786 7787 // If the target happens to be one of the previous declarations, we 7788 // don't have a conflict. 7789 // 7790 // FIXME: but we might be increasing its access, in which case we 7791 // should redeclare it. 7792 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7793 bool FoundEquivalentDecl = false; 7794 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7795 I != E; ++I) { 7796 NamedDecl *D = (*I)->getUnderlyingDecl(); 7797 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7798 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7799 PrevShadow = Shadow; 7800 FoundEquivalentDecl = true; 7801 } 7802 7803 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7804 } 7805 7806 if (FoundEquivalentDecl) 7807 return false; 7808 7809 if (FunctionDecl *FD = Target->getAsFunction()) { 7810 NamedDecl *OldDecl = nullptr; 7811 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7812 /*IsForUsingDecl*/ true)) { 7813 case Ovl_Overload: 7814 return false; 7815 7816 case Ovl_NonFunction: 7817 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7818 break; 7819 7820 // We found a decl with the exact signature. 7821 case Ovl_Match: 7822 // If we're in a record, we want to hide the target, so we 7823 // return true (without a diagnostic) to tell the caller not to 7824 // build a shadow decl. 7825 if (CurContext->isRecord()) 7826 return true; 7827 7828 // If we're not in a record, this is an error. 7829 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7830 break; 7831 } 7832 7833 Diag(Target->getLocation(), diag::note_using_decl_target); 7834 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7835 return true; 7836 } 7837 7838 // Target is not a function. 7839 7840 if (isa<TagDecl>(Target)) { 7841 // No conflict between a tag and a non-tag. 7842 if (!Tag) return false; 7843 7844 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7845 Diag(Target->getLocation(), diag::note_using_decl_target); 7846 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7847 return true; 7848 } 7849 7850 // No conflict between a tag and a non-tag. 7851 if (!NonTag) return false; 7852 7853 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7854 Diag(Target->getLocation(), diag::note_using_decl_target); 7855 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7856 return true; 7857 } 7858 7859 /// Builds a shadow declaration corresponding to a 'using' declaration. 7860 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7861 UsingDecl *UD, 7862 NamedDecl *Orig, 7863 UsingShadowDecl *PrevDecl) { 7864 7865 // If we resolved to another shadow declaration, just coalesce them. 7866 NamedDecl *Target = Orig; 7867 if (isa<UsingShadowDecl>(Target)) { 7868 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7869 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7870 } 7871 7872 UsingShadowDecl *Shadow 7873 = UsingShadowDecl::Create(Context, CurContext, 7874 UD->getLocation(), UD, Target); 7875 UD->addShadowDecl(Shadow); 7876 7877 Shadow->setAccess(UD->getAccess()); 7878 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7879 Shadow->setInvalidDecl(); 7880 7881 Shadow->setPreviousDecl(PrevDecl); 7882 7883 if (S) 7884 PushOnScopeChains(Shadow, S); 7885 else 7886 CurContext->addDecl(Shadow); 7887 7888 7889 return Shadow; 7890 } 7891 7892 /// Hides a using shadow declaration. This is required by the current 7893 /// using-decl implementation when a resolvable using declaration in a 7894 /// class is followed by a declaration which would hide or override 7895 /// one or more of the using decl's targets; for example: 7896 /// 7897 /// struct Base { void foo(int); }; 7898 /// struct Derived : Base { 7899 /// using Base::foo; 7900 /// void foo(int); 7901 /// }; 7902 /// 7903 /// The governing language is C++03 [namespace.udecl]p12: 7904 /// 7905 /// When a using-declaration brings names from a base class into a 7906 /// derived class scope, member functions in the derived class 7907 /// override and/or hide member functions with the same name and 7908 /// parameter types in a base class (rather than conflicting). 7909 /// 7910 /// There are two ways to implement this: 7911 /// (1) optimistically create shadow decls when they're not hidden 7912 /// by existing declarations, or 7913 /// (2) don't create any shadow decls (or at least don't make them 7914 /// visible) until we've fully parsed/instantiated the class. 7915 /// The problem with (1) is that we might have to retroactively remove 7916 /// a shadow decl, which requires several O(n) operations because the 7917 /// decl structures are (very reasonably) not designed for removal. 7918 /// (2) avoids this but is very fiddly and phase-dependent. 7919 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7920 if (Shadow->getDeclName().getNameKind() == 7921 DeclarationName::CXXConversionFunctionName) 7922 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7923 7924 // Remove it from the DeclContext... 7925 Shadow->getDeclContext()->removeDecl(Shadow); 7926 7927 // ...and the scope, if applicable... 7928 if (S) { 7929 S->RemoveDecl(Shadow); 7930 IdResolver.RemoveDecl(Shadow); 7931 } 7932 7933 // ...and the using decl. 7934 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7935 7936 // TODO: complain somehow if Shadow was used. It shouldn't 7937 // be possible for this to happen, because...? 7938 } 7939 7940 /// Find the base specifier for a base class with the given type. 7941 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7942 QualType DesiredBase, 7943 bool &AnyDependentBases) { 7944 // Check whether the named type is a direct base class. 7945 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7946 for (auto &Base : Derived->bases()) { 7947 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7948 if (CanonicalDesiredBase == BaseType) 7949 return &Base; 7950 if (BaseType->isDependentType()) 7951 AnyDependentBases = true; 7952 } 7953 return nullptr; 7954 } 7955 7956 namespace { 7957 class UsingValidatorCCC : public CorrectionCandidateCallback { 7958 public: 7959 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7960 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7961 : HasTypenameKeyword(HasTypenameKeyword), 7962 IsInstantiation(IsInstantiation), OldNNS(NNS), 7963 RequireMemberOf(RequireMemberOf) {} 7964 7965 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7966 NamedDecl *ND = Candidate.getCorrectionDecl(); 7967 7968 // Keywords are not valid here. 7969 if (!ND || isa<NamespaceDecl>(ND)) 7970 return false; 7971 7972 // Completely unqualified names are invalid for a 'using' declaration. 7973 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7974 return false; 7975 7976 if (RequireMemberOf) { 7977 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7978 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7979 // No-one ever wants a using-declaration to name an injected-class-name 7980 // of a base class, unless they're declaring an inheriting constructor. 7981 ASTContext &Ctx = ND->getASTContext(); 7982 if (!Ctx.getLangOpts().CPlusPlus11) 7983 return false; 7984 QualType FoundType = Ctx.getRecordType(FoundRecord); 7985 7986 // Check that the injected-class-name is named as a member of its own 7987 // type; we don't want to suggest 'using Derived::Base;', since that 7988 // means something else. 7989 NestedNameSpecifier *Specifier = 7990 Candidate.WillReplaceSpecifier() 7991 ? Candidate.getCorrectionSpecifier() 7992 : OldNNS; 7993 if (!Specifier->getAsType() || 7994 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7995 return false; 7996 7997 // Check that this inheriting constructor declaration actually names a 7998 // direct base class of the current class. 7999 bool AnyDependentBases = false; 8000 if (!findDirectBaseWithType(RequireMemberOf, 8001 Ctx.getRecordType(FoundRecord), 8002 AnyDependentBases) && 8003 !AnyDependentBases) 8004 return false; 8005 } else { 8006 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 8007 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 8008 return false; 8009 8010 // FIXME: Check that the base class member is accessible? 8011 } 8012 } 8013 8014 if (isa<TypeDecl>(ND)) 8015 return HasTypenameKeyword || !IsInstantiation; 8016 8017 return !HasTypenameKeyword; 8018 } 8019 8020 private: 8021 bool HasTypenameKeyword; 8022 bool IsInstantiation; 8023 NestedNameSpecifier *OldNNS; 8024 CXXRecordDecl *RequireMemberOf; 8025 }; 8026 } // end anonymous namespace 8027 8028 /// Builds a using declaration. 8029 /// 8030 /// \param IsInstantiation - Whether this call arises from an 8031 /// instantiation of an unresolved using declaration. We treat 8032 /// the lookup differently for these declarations. 8033 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 8034 SourceLocation UsingLoc, 8035 CXXScopeSpec &SS, 8036 DeclarationNameInfo NameInfo, 8037 AttributeList *AttrList, 8038 bool IsInstantiation, 8039 bool HasTypenameKeyword, 8040 SourceLocation TypenameLoc) { 8041 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8042 SourceLocation IdentLoc = NameInfo.getLoc(); 8043 assert(IdentLoc.isValid() && "Invalid TargetName location."); 8044 8045 // FIXME: We ignore attributes for now. 8046 8047 if (SS.isEmpty()) { 8048 Diag(IdentLoc, diag::err_using_requires_qualname); 8049 return nullptr; 8050 } 8051 8052 // Do the redeclaration lookup in the current scope. 8053 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 8054 ForRedeclaration); 8055 Previous.setHideTags(false); 8056 if (S) { 8057 LookupName(Previous, S); 8058 8059 // It is really dumb that we have to do this. 8060 LookupResult::Filter F = Previous.makeFilter(); 8061 while (F.hasNext()) { 8062 NamedDecl *D = F.next(); 8063 if (!isDeclInScope(D, CurContext, S)) 8064 F.erase(); 8065 // If we found a local extern declaration that's not ordinarily visible, 8066 // and this declaration is being added to a non-block scope, ignore it. 8067 // We're only checking for scope conflicts here, not also for violations 8068 // of the linkage rules. 8069 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 8070 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 8071 F.erase(); 8072 } 8073 F.done(); 8074 } else { 8075 assert(IsInstantiation && "no scope in non-instantiation"); 8076 assert(CurContext->isRecord() && "scope not record in instantiation"); 8077 LookupQualifiedName(Previous, CurContext); 8078 } 8079 8080 // Check for invalid redeclarations. 8081 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 8082 SS, IdentLoc, Previous)) 8083 return nullptr; 8084 8085 // Check for bad qualifiers. 8086 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 8087 return nullptr; 8088 8089 DeclContext *LookupContext = computeDeclContext(SS); 8090 NamedDecl *D; 8091 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 8092 if (!LookupContext) { 8093 if (HasTypenameKeyword) { 8094 // FIXME: not all declaration name kinds are legal here 8095 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 8096 UsingLoc, TypenameLoc, 8097 QualifierLoc, 8098 IdentLoc, NameInfo.getName()); 8099 } else { 8100 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 8101 QualifierLoc, NameInfo); 8102 } 8103 D->setAccess(AS); 8104 CurContext->addDecl(D); 8105 return D; 8106 } 8107 8108 auto Build = [&](bool Invalid) { 8109 UsingDecl *UD = 8110 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 8111 HasTypenameKeyword); 8112 UD->setAccess(AS); 8113 CurContext->addDecl(UD); 8114 UD->setInvalidDecl(Invalid); 8115 return UD; 8116 }; 8117 auto BuildInvalid = [&]{ return Build(true); }; 8118 auto BuildValid = [&]{ return Build(false); }; 8119 8120 if (RequireCompleteDeclContext(SS, LookupContext)) 8121 return BuildInvalid(); 8122 8123 // Look up the target name. 8124 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8125 8126 // Unlike most lookups, we don't always want to hide tag 8127 // declarations: tag names are visible through the using declaration 8128 // even if hidden by ordinary names, *except* in a dependent context 8129 // where it's important for the sanity of two-phase lookup. 8130 if (!IsInstantiation) 8131 R.setHideTags(false); 8132 8133 // For the purposes of this lookup, we have a base object type 8134 // equal to that of the current context. 8135 if (CurContext->isRecord()) { 8136 R.setBaseObjectType( 8137 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 8138 } 8139 8140 LookupQualifiedName(R, LookupContext); 8141 8142 // Try to correct typos if possible. If constructor name lookup finds no 8143 // results, that means the named class has no explicit constructors, and we 8144 // suppressed declaring implicit ones (probably because it's dependent or 8145 // invalid). 8146 if (R.empty() && 8147 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 8148 if (TypoCorrection Corrected = CorrectTypo( 8149 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 8150 llvm::make_unique<UsingValidatorCCC>( 8151 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8152 dyn_cast<CXXRecordDecl>(CurContext)), 8153 CTK_ErrorRecovery)) { 8154 // We reject any correction for which ND would be NULL. 8155 NamedDecl *ND = Corrected.getCorrectionDecl(); 8156 8157 // We reject candidates where DroppedSpecifier == true, hence the 8158 // literal '0' below. 8159 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8160 << NameInfo.getName() << LookupContext << 0 8161 << SS.getRange()); 8162 8163 // If we corrected to an inheriting constructor, handle it as one. 8164 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8165 if (RD && RD->isInjectedClassName()) { 8166 // Fix up the information we'll use to build the using declaration. 8167 if (Corrected.WillReplaceSpecifier()) { 8168 NestedNameSpecifierLocBuilder Builder; 8169 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8170 QualifierLoc.getSourceRange()); 8171 QualifierLoc = Builder.getWithLocInContext(Context); 8172 } 8173 8174 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8175 Context.getCanonicalType(Context.getRecordType(RD)))); 8176 NameInfo.setNamedTypeInfo(nullptr); 8177 for (auto *Ctor : LookupConstructors(RD)) 8178 R.addDecl(Ctor); 8179 } else { 8180 // FIXME: Pick up all the declarations if we found an overloaded function. 8181 R.addDecl(ND); 8182 } 8183 } else { 8184 Diag(IdentLoc, diag::err_no_member) 8185 << NameInfo.getName() << LookupContext << SS.getRange(); 8186 return BuildInvalid(); 8187 } 8188 } 8189 8190 if (R.isAmbiguous()) 8191 return BuildInvalid(); 8192 8193 if (HasTypenameKeyword) { 8194 // If we asked for a typename and got a non-type decl, error out. 8195 if (!R.getAsSingle<TypeDecl>()) { 8196 Diag(IdentLoc, diag::err_using_typename_non_type); 8197 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8198 Diag((*I)->getUnderlyingDecl()->getLocation(), 8199 diag::note_using_decl_target); 8200 return BuildInvalid(); 8201 } 8202 } else { 8203 // If we asked for a non-typename and we got a type, error out, 8204 // but only if this is an instantiation of an unresolved using 8205 // decl. Otherwise just silently find the type name. 8206 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8207 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8208 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8209 return BuildInvalid(); 8210 } 8211 } 8212 8213 // C++0x N2914 [namespace.udecl]p6: 8214 // A using-declaration shall not name a namespace. 8215 if (R.getAsSingle<NamespaceDecl>()) { 8216 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8217 << SS.getRange(); 8218 return BuildInvalid(); 8219 } 8220 8221 UsingDecl *UD = BuildValid(); 8222 8223 // The normal rules do not apply to inheriting constructor declarations. 8224 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 8225 // Suppress access diagnostics; the access check is instead performed at the 8226 // point of use for an inheriting constructor. 8227 R.suppressDiagnostics(); 8228 CheckInheritingConstructorUsingDecl(UD); 8229 return UD; 8230 } 8231 8232 // Otherwise, look up the target name. 8233 8234 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8235 UsingShadowDecl *PrevDecl = nullptr; 8236 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8237 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8238 } 8239 8240 return UD; 8241 } 8242 8243 /// Additional checks for a using declaration referring to a constructor name. 8244 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8245 assert(!UD->hasTypename() && "expecting a constructor name"); 8246 8247 const Type *SourceType = UD->getQualifier()->getAsType(); 8248 assert(SourceType && 8249 "Using decl naming constructor doesn't have type in scope spec."); 8250 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8251 8252 // Check whether the named type is a direct base class. 8253 bool AnyDependentBases = false; 8254 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8255 AnyDependentBases); 8256 if (!Base && !AnyDependentBases) { 8257 Diag(UD->getUsingLoc(), 8258 diag::err_using_decl_constructor_not_in_direct_base) 8259 << UD->getNameInfo().getSourceRange() 8260 << QualType(SourceType, 0) << TargetClass; 8261 UD->setInvalidDecl(); 8262 return true; 8263 } 8264 8265 if (Base) 8266 Base->setInheritConstructors(); 8267 8268 return false; 8269 } 8270 8271 /// Checks that the given using declaration is not an invalid 8272 /// redeclaration. Note that this is checking only for the using decl 8273 /// itself, not for any ill-formedness among the UsingShadowDecls. 8274 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8275 bool HasTypenameKeyword, 8276 const CXXScopeSpec &SS, 8277 SourceLocation NameLoc, 8278 const LookupResult &Prev) { 8279 // C++03 [namespace.udecl]p8: 8280 // C++0x [namespace.udecl]p10: 8281 // A using-declaration is a declaration and can therefore be used 8282 // repeatedly where (and only where) multiple declarations are 8283 // allowed. 8284 // 8285 // That's in non-member contexts. 8286 if (!CurContext->getRedeclContext()->isRecord()) 8287 return false; 8288 8289 NestedNameSpecifier *Qual = SS.getScopeRep(); 8290 8291 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8292 NamedDecl *D = *I; 8293 8294 bool DTypename; 8295 NestedNameSpecifier *DQual; 8296 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8297 DTypename = UD->hasTypename(); 8298 DQual = UD->getQualifier(); 8299 } else if (UnresolvedUsingValueDecl *UD 8300 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8301 DTypename = false; 8302 DQual = UD->getQualifier(); 8303 } else if (UnresolvedUsingTypenameDecl *UD 8304 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8305 DTypename = true; 8306 DQual = UD->getQualifier(); 8307 } else continue; 8308 8309 // using decls differ if one says 'typename' and the other doesn't. 8310 // FIXME: non-dependent using decls? 8311 if (HasTypenameKeyword != DTypename) continue; 8312 8313 // using decls differ if they name different scopes (but note that 8314 // template instantiation can cause this check to trigger when it 8315 // didn't before instantiation). 8316 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8317 Context.getCanonicalNestedNameSpecifier(DQual)) 8318 continue; 8319 8320 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8321 Diag(D->getLocation(), diag::note_using_decl) << 1; 8322 return true; 8323 } 8324 8325 return false; 8326 } 8327 8328 8329 /// Checks that the given nested-name qualifier used in a using decl 8330 /// in the current context is appropriately related to the current 8331 /// scope. If an error is found, diagnoses it and returns true. 8332 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8333 const CXXScopeSpec &SS, 8334 const DeclarationNameInfo &NameInfo, 8335 SourceLocation NameLoc) { 8336 DeclContext *NamedContext = computeDeclContext(SS); 8337 8338 if (!CurContext->isRecord()) { 8339 // C++03 [namespace.udecl]p3: 8340 // C++0x [namespace.udecl]p8: 8341 // A using-declaration for a class member shall be a member-declaration. 8342 8343 // If we weren't able to compute a valid scope, it must be a 8344 // dependent class scope. 8345 if (!NamedContext || NamedContext->isRecord()) { 8346 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext); 8347 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8348 RD = nullptr; 8349 8350 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8351 << SS.getRange(); 8352 8353 // If we have a complete, non-dependent source type, try to suggest a 8354 // way to get the same effect. 8355 if (!RD) 8356 return true; 8357 8358 // Find what this using-declaration was referring to. 8359 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8360 R.setHideTags(false); 8361 R.suppressDiagnostics(); 8362 LookupQualifiedName(R, RD); 8363 8364 if (R.getAsSingle<TypeDecl>()) { 8365 if (getLangOpts().CPlusPlus11) { 8366 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8367 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8368 << 0 // alias declaration 8369 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8370 NameInfo.getName().getAsString() + 8371 " = "); 8372 } else { 8373 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8374 SourceLocation InsertLoc = 8375 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8376 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8377 << 1 // typedef declaration 8378 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8379 << FixItHint::CreateInsertion( 8380 InsertLoc, " " + NameInfo.getName().getAsString()); 8381 } 8382 } else if (R.getAsSingle<VarDecl>()) { 8383 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8384 // repeating the type of the static data member here. 8385 FixItHint FixIt; 8386 if (getLangOpts().CPlusPlus11) { 8387 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8388 FixIt = FixItHint::CreateReplacement( 8389 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8390 } 8391 8392 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8393 << 2 // reference declaration 8394 << FixIt; 8395 } 8396 return true; 8397 } 8398 8399 // Otherwise, everything is known to be fine. 8400 return false; 8401 } 8402 8403 // The current scope is a record. 8404 8405 // If the named context is dependent, we can't decide much. 8406 if (!NamedContext) { 8407 // FIXME: in C++0x, we can diagnose if we can prove that the 8408 // nested-name-specifier does not refer to a base class, which is 8409 // still possible in some cases. 8410 8411 // Otherwise we have to conservatively report that things might be 8412 // okay. 8413 return false; 8414 } 8415 8416 if (!NamedContext->isRecord()) { 8417 // Ideally this would point at the last name in the specifier, 8418 // but we don't have that level of source info. 8419 Diag(SS.getRange().getBegin(), 8420 diag::err_using_decl_nested_name_specifier_is_not_class) 8421 << SS.getScopeRep() << SS.getRange(); 8422 return true; 8423 } 8424 8425 if (!NamedContext->isDependentContext() && 8426 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8427 return true; 8428 8429 if (getLangOpts().CPlusPlus11) { 8430 // C++0x [namespace.udecl]p3: 8431 // In a using-declaration used as a member-declaration, the 8432 // nested-name-specifier shall name a base class of the class 8433 // being defined. 8434 8435 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8436 cast<CXXRecordDecl>(NamedContext))) { 8437 if (CurContext == NamedContext) { 8438 Diag(NameLoc, 8439 diag::err_using_decl_nested_name_specifier_is_current_class) 8440 << SS.getRange(); 8441 return true; 8442 } 8443 8444 Diag(SS.getRange().getBegin(), 8445 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8446 << SS.getScopeRep() 8447 << cast<CXXRecordDecl>(CurContext) 8448 << SS.getRange(); 8449 return true; 8450 } 8451 8452 return false; 8453 } 8454 8455 // C++03 [namespace.udecl]p4: 8456 // A using-declaration used as a member-declaration shall refer 8457 // to a member of a base class of the class being defined [etc.]. 8458 8459 // Salient point: SS doesn't have to name a base class as long as 8460 // lookup only finds members from base classes. Therefore we can 8461 // diagnose here only if we can prove that that can't happen, 8462 // i.e. if the class hierarchies provably don't intersect. 8463 8464 // TODO: it would be nice if "definitely valid" results were cached 8465 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8466 // need to be repeated. 8467 8468 struct UserData { 8469 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8470 8471 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8472 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8473 Data->Bases.insert(Base); 8474 return true; 8475 } 8476 8477 bool hasDependentBases(const CXXRecordDecl *Class) { 8478 return !Class->forallBases(collect, this); 8479 } 8480 8481 /// Returns true if the base is dependent or is one of the 8482 /// accumulated base classes. 8483 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8484 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8485 return !Data->Bases.count(Base); 8486 } 8487 8488 bool mightShareBases(const CXXRecordDecl *Class) { 8489 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8490 } 8491 }; 8492 8493 UserData Data; 8494 8495 // Returns false if we find a dependent base. 8496 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8497 return false; 8498 8499 // Returns false if the class has a dependent base or if it or one 8500 // of its bases is present in the base set of the current context. 8501 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8502 return false; 8503 8504 Diag(SS.getRange().getBegin(), 8505 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8506 << SS.getScopeRep() 8507 << cast<CXXRecordDecl>(CurContext) 8508 << SS.getRange(); 8509 8510 return true; 8511 } 8512 8513 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8514 AccessSpecifier AS, 8515 MultiTemplateParamsArg TemplateParamLists, 8516 SourceLocation UsingLoc, 8517 UnqualifiedId &Name, 8518 AttributeList *AttrList, 8519 TypeResult Type, 8520 Decl *DeclFromDeclSpec) { 8521 // Skip up to the relevant declaration scope. 8522 while (S->getFlags() & Scope::TemplateParamScope) 8523 S = S->getParent(); 8524 assert((S->getFlags() & Scope::DeclScope) && 8525 "got alias-declaration outside of declaration scope"); 8526 8527 if (Type.isInvalid()) 8528 return nullptr; 8529 8530 bool Invalid = false; 8531 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8532 TypeSourceInfo *TInfo = nullptr; 8533 GetTypeFromParser(Type.get(), &TInfo); 8534 8535 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8536 return nullptr; 8537 8538 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8539 UPPC_DeclarationType)) { 8540 Invalid = true; 8541 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8542 TInfo->getTypeLoc().getBeginLoc()); 8543 } 8544 8545 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8546 LookupName(Previous, S); 8547 8548 // Warn about shadowing the name of a template parameter. 8549 if (Previous.isSingleResult() && 8550 Previous.getFoundDecl()->isTemplateParameter()) { 8551 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8552 Previous.clear(); 8553 } 8554 8555 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8556 "name in alias declaration must be an identifier"); 8557 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8558 Name.StartLocation, 8559 Name.Identifier, TInfo); 8560 8561 NewTD->setAccess(AS); 8562 8563 if (Invalid) 8564 NewTD->setInvalidDecl(); 8565 8566 ProcessDeclAttributeList(S, NewTD, AttrList); 8567 8568 CheckTypedefForVariablyModifiedType(S, NewTD); 8569 Invalid |= NewTD->isInvalidDecl(); 8570 8571 bool Redeclaration = false; 8572 8573 NamedDecl *NewND; 8574 if (TemplateParamLists.size()) { 8575 TypeAliasTemplateDecl *OldDecl = nullptr; 8576 TemplateParameterList *OldTemplateParams = nullptr; 8577 8578 if (TemplateParamLists.size() != 1) { 8579 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8580 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8581 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8582 } 8583 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8584 8585 // Only consider previous declarations in the same scope. 8586 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8587 /*ExplicitInstantiationOrSpecialization*/false); 8588 if (!Previous.empty()) { 8589 Redeclaration = true; 8590 8591 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8592 if (!OldDecl && !Invalid) { 8593 Diag(UsingLoc, diag::err_redefinition_different_kind) 8594 << Name.Identifier; 8595 8596 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8597 if (OldD->getLocation().isValid()) 8598 Diag(OldD->getLocation(), diag::note_previous_definition); 8599 8600 Invalid = true; 8601 } 8602 8603 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8604 if (TemplateParameterListsAreEqual(TemplateParams, 8605 OldDecl->getTemplateParameters(), 8606 /*Complain=*/true, 8607 TPL_TemplateMatch)) 8608 OldTemplateParams = OldDecl->getTemplateParameters(); 8609 else 8610 Invalid = true; 8611 8612 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8613 if (!Invalid && 8614 !Context.hasSameType(OldTD->getUnderlyingType(), 8615 NewTD->getUnderlyingType())) { 8616 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8617 // but we can't reasonably accept it. 8618 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8619 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8620 if (OldTD->getLocation().isValid()) 8621 Diag(OldTD->getLocation(), diag::note_previous_definition); 8622 Invalid = true; 8623 } 8624 } 8625 } 8626 8627 // Merge any previous default template arguments into our parameters, 8628 // and check the parameter list. 8629 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8630 TPC_TypeAliasTemplate)) 8631 return nullptr; 8632 8633 TypeAliasTemplateDecl *NewDecl = 8634 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8635 Name.Identifier, TemplateParams, 8636 NewTD); 8637 NewTD->setDescribedAliasTemplate(NewDecl); 8638 8639 NewDecl->setAccess(AS); 8640 8641 if (Invalid) 8642 NewDecl->setInvalidDecl(); 8643 else if (OldDecl) 8644 NewDecl->setPreviousDecl(OldDecl); 8645 8646 NewND = NewDecl; 8647 } else { 8648 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 8649 setTagNameForLinkagePurposes(TD, NewTD); 8650 handleTagNumbering(TD, S); 8651 } 8652 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8653 NewND = NewTD; 8654 } 8655 8656 if (!Redeclaration) 8657 PushOnScopeChains(NewND, S); 8658 8659 ActOnDocumentableDecl(NewND); 8660 return NewND; 8661 } 8662 8663 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8664 SourceLocation AliasLoc, 8665 IdentifierInfo *Alias, CXXScopeSpec &SS, 8666 SourceLocation IdentLoc, 8667 IdentifierInfo *Ident) { 8668 8669 // Lookup the namespace name. 8670 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8671 LookupParsedName(R, S, &SS); 8672 8673 if (R.isAmbiguous()) 8674 return nullptr; 8675 8676 if (R.empty()) { 8677 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8678 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8679 return nullptr; 8680 } 8681 } 8682 assert(!R.isAmbiguous() && !R.empty()); 8683 8684 // Check if we have a previous declaration with the same name. 8685 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8686 ForRedeclaration); 8687 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8688 PrevDecl = nullptr; 8689 8690 NamedDecl *ND = R.getFoundDecl(); 8691 8692 if (PrevDecl) { 8693 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8694 // We already have an alias with the same name that points to the same 8695 // namespace; check that it matches. 8696 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8697 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8698 << Alias; 8699 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8700 << AD->getNamespace(); 8701 return nullptr; 8702 } 8703 } else { 8704 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8705 ? diag::err_redefinition 8706 : diag::err_redefinition_different_kind; 8707 Diag(AliasLoc, DiagID) << Alias; 8708 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8709 return nullptr; 8710 } 8711 } 8712 8713 // The use of a nested name specifier may trigger deprecation warnings. 8714 DiagnoseUseOfDecl(ND, IdentLoc); 8715 8716 NamespaceAliasDecl *AliasDecl = 8717 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8718 Alias, SS.getWithLocInContext(Context), 8719 IdentLoc, ND); 8720 if (PrevDecl) 8721 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8722 8723 PushOnScopeChains(AliasDecl, S); 8724 return AliasDecl; 8725 } 8726 8727 Sema::ImplicitExceptionSpecification 8728 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8729 CXXMethodDecl *MD) { 8730 CXXRecordDecl *ClassDecl = MD->getParent(); 8731 8732 // C++ [except.spec]p14: 8733 // An implicitly declared special member function (Clause 12) shall have an 8734 // exception-specification. [...] 8735 ImplicitExceptionSpecification ExceptSpec(*this); 8736 if (ClassDecl->isInvalidDecl()) 8737 return ExceptSpec; 8738 8739 // Direct base-class constructors. 8740 for (const auto &B : ClassDecl->bases()) { 8741 if (B.isVirtual()) // Handled below. 8742 continue; 8743 8744 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8745 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8746 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8747 // If this is a deleted function, add it anyway. This might be conformant 8748 // with the standard. This might not. I'm not sure. It might not matter. 8749 if (Constructor) 8750 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8751 } 8752 } 8753 8754 // Virtual base-class constructors. 8755 for (const auto &B : ClassDecl->vbases()) { 8756 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8757 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8758 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8759 // If this is a deleted function, add it anyway. This might be conformant 8760 // with the standard. This might not. I'm not sure. It might not matter. 8761 if (Constructor) 8762 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8763 } 8764 } 8765 8766 // Field constructors. 8767 for (const auto *F : ClassDecl->fields()) { 8768 if (F->hasInClassInitializer()) { 8769 if (Expr *E = F->getInClassInitializer()) 8770 ExceptSpec.CalledExpr(E); 8771 } else if (const RecordType *RecordTy 8772 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8773 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8774 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8775 // If this is a deleted function, add it anyway. This might be conformant 8776 // with the standard. This might not. I'm not sure. It might not matter. 8777 // In particular, the problem is that this function never gets called. It 8778 // might just be ill-formed because this function attempts to refer to 8779 // a deleted function here. 8780 if (Constructor) 8781 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8782 } 8783 } 8784 8785 return ExceptSpec; 8786 } 8787 8788 Sema::ImplicitExceptionSpecification 8789 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8790 CXXRecordDecl *ClassDecl = CD->getParent(); 8791 8792 // C++ [except.spec]p14: 8793 // An inheriting constructor [...] shall have an exception-specification. [...] 8794 ImplicitExceptionSpecification ExceptSpec(*this); 8795 if (ClassDecl->isInvalidDecl()) 8796 return ExceptSpec; 8797 8798 // Inherited constructor. 8799 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8800 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8801 // FIXME: Copying or moving the parameters could add extra exceptions to the 8802 // set, as could the default arguments for the inherited constructor. This 8803 // will be addressed when we implement the resolution of core issue 1351. 8804 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8805 8806 // Direct base-class constructors. 8807 for (const auto &B : ClassDecl->bases()) { 8808 if (B.isVirtual()) // Handled below. 8809 continue; 8810 8811 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8812 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8813 if (BaseClassDecl == InheritedDecl) 8814 continue; 8815 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8816 if (Constructor) 8817 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8818 } 8819 } 8820 8821 // Virtual base-class constructors. 8822 for (const auto &B : ClassDecl->vbases()) { 8823 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8824 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8825 if (BaseClassDecl == InheritedDecl) 8826 continue; 8827 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8828 if (Constructor) 8829 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8830 } 8831 } 8832 8833 // Field constructors. 8834 for (const auto *F : ClassDecl->fields()) { 8835 if (F->hasInClassInitializer()) { 8836 if (Expr *E = F->getInClassInitializer()) 8837 ExceptSpec.CalledExpr(E); 8838 } else if (const RecordType *RecordTy 8839 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8840 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8841 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8842 if (Constructor) 8843 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8844 } 8845 } 8846 8847 return ExceptSpec; 8848 } 8849 8850 namespace { 8851 /// RAII object to register a special member as being currently declared. 8852 struct DeclaringSpecialMember { 8853 Sema &S; 8854 Sema::SpecialMemberDecl D; 8855 bool WasAlreadyBeingDeclared; 8856 8857 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8858 : S(S), D(RD, CSM) { 8859 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8860 if (WasAlreadyBeingDeclared) 8861 // This almost never happens, but if it does, ensure that our cache 8862 // doesn't contain a stale result. 8863 S.SpecialMemberCache.clear(); 8864 8865 // FIXME: Register a note to be produced if we encounter an error while 8866 // declaring the special member. 8867 } 8868 ~DeclaringSpecialMember() { 8869 if (!WasAlreadyBeingDeclared) 8870 S.SpecialMembersBeingDeclared.erase(D); 8871 } 8872 8873 /// \brief Are we already trying to declare this special member? 8874 bool isAlreadyBeingDeclared() const { 8875 return WasAlreadyBeingDeclared; 8876 } 8877 }; 8878 } 8879 8880 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8881 CXXRecordDecl *ClassDecl) { 8882 // C++ [class.ctor]p5: 8883 // A default constructor for a class X is a constructor of class X 8884 // that can be called without an argument. If there is no 8885 // user-declared constructor for class X, a default constructor is 8886 // implicitly declared. An implicitly-declared default constructor 8887 // is an inline public member of its class. 8888 assert(ClassDecl->needsImplicitDefaultConstructor() && 8889 "Should not build implicit default constructor!"); 8890 8891 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8892 if (DSM.isAlreadyBeingDeclared()) 8893 return nullptr; 8894 8895 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8896 CXXDefaultConstructor, 8897 false); 8898 8899 // Create the actual constructor declaration. 8900 CanQualType ClassType 8901 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8902 SourceLocation ClassLoc = ClassDecl->getLocation(); 8903 DeclarationName Name 8904 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8905 DeclarationNameInfo NameInfo(Name, ClassLoc); 8906 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8907 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8908 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8909 /*isImplicitlyDeclared=*/true, Constexpr); 8910 DefaultCon->setAccess(AS_public); 8911 DefaultCon->setDefaulted(); 8912 8913 if (getLangOpts().CUDA) { 8914 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8915 DefaultCon, 8916 /* ConstRHS */ false, 8917 /* Diagnose */ false); 8918 } 8919 8920 // Build an exception specification pointing back at this constructor. 8921 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8922 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8923 8924 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8925 // constructors is easy to compute. 8926 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8927 8928 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8929 SetDeclDeleted(DefaultCon, ClassLoc); 8930 8931 // Note that we have declared this constructor. 8932 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8933 8934 if (Scope *S = getScopeForContext(ClassDecl)) 8935 PushOnScopeChains(DefaultCon, S, false); 8936 ClassDecl->addDecl(DefaultCon); 8937 8938 return DefaultCon; 8939 } 8940 8941 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8942 CXXConstructorDecl *Constructor) { 8943 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8944 !Constructor->doesThisDeclarationHaveABody() && 8945 !Constructor->isDeleted()) && 8946 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8947 8948 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8949 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8950 8951 SynthesizedFunctionScope Scope(*this, Constructor); 8952 DiagnosticErrorTrap Trap(Diags); 8953 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8954 Trap.hasErrorOccurred()) { 8955 Diag(CurrentLocation, diag::note_member_synthesized_at) 8956 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8957 Constructor->setInvalidDecl(); 8958 return; 8959 } 8960 8961 // The exception specification is needed because we are defining the 8962 // function. 8963 ResolveExceptionSpec(CurrentLocation, 8964 Constructor->getType()->castAs<FunctionProtoType>()); 8965 8966 SourceLocation Loc = Constructor->getLocEnd().isValid() 8967 ? Constructor->getLocEnd() 8968 : Constructor->getLocation(); 8969 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8970 8971 Constructor->markUsed(Context); 8972 MarkVTableUsed(CurrentLocation, ClassDecl); 8973 8974 if (ASTMutationListener *L = getASTMutationListener()) { 8975 L->CompletedImplicitDefinition(Constructor); 8976 } 8977 8978 DiagnoseUninitializedFields(*this, Constructor); 8979 } 8980 8981 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8982 // Perform any delayed checks on exception specifications. 8983 CheckDelayedMemberExceptionSpecs(); 8984 } 8985 8986 namespace { 8987 /// Information on inheriting constructors to declare. 8988 class InheritingConstructorInfo { 8989 public: 8990 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8991 : SemaRef(SemaRef), Derived(Derived) { 8992 // Mark the constructors that we already have in the derived class. 8993 // 8994 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8995 // unless there is a user-declared constructor with the same signature in 8996 // the class where the using-declaration appears. 8997 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8998 } 8999 9000 void inheritAll(CXXRecordDecl *RD) { 9001 visitAll(RD, &InheritingConstructorInfo::inherit); 9002 } 9003 9004 private: 9005 /// Information about an inheriting constructor. 9006 struct InheritingConstructor { 9007 InheritingConstructor() 9008 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 9009 9010 /// If \c true, a constructor with this signature is already declared 9011 /// in the derived class. 9012 bool DeclaredInDerived; 9013 9014 /// The constructor which is inherited. 9015 const CXXConstructorDecl *BaseCtor; 9016 9017 /// The derived constructor we declared. 9018 CXXConstructorDecl *DerivedCtor; 9019 }; 9020 9021 /// Inheriting constructors with a given canonical type. There can be at 9022 /// most one such non-template constructor, and any number of templated 9023 /// constructors. 9024 struct InheritingConstructorsForType { 9025 InheritingConstructor NonTemplate; 9026 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 9027 Templates; 9028 9029 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 9030 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 9031 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 9032 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 9033 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 9034 false, S.TPL_TemplateMatch)) 9035 return Templates[I].second; 9036 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 9037 return Templates.back().second; 9038 } 9039 9040 return NonTemplate; 9041 } 9042 }; 9043 9044 /// Get or create the inheriting constructor record for a constructor. 9045 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 9046 QualType CtorType) { 9047 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 9048 .getEntry(SemaRef, Ctor); 9049 } 9050 9051 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 9052 9053 /// Process all constructors for a class. 9054 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 9055 for (const auto *Ctor : RD->ctors()) 9056 (this->*Callback)(Ctor); 9057 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9058 I(RD->decls_begin()), E(RD->decls_end()); 9059 I != E; ++I) { 9060 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 9061 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 9062 (this->*Callback)(CD); 9063 } 9064 } 9065 9066 /// Note that a constructor (or constructor template) was declared in Derived. 9067 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 9068 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 9069 } 9070 9071 /// Inherit a single constructor. 9072 void inherit(const CXXConstructorDecl *Ctor) { 9073 const FunctionProtoType *CtorType = 9074 Ctor->getType()->castAs<FunctionProtoType>(); 9075 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 9076 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 9077 9078 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 9079 9080 // Core issue (no number yet): the ellipsis is always discarded. 9081 if (EPI.Variadic) { 9082 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 9083 SemaRef.Diag(Ctor->getLocation(), 9084 diag::note_using_decl_constructor_ellipsis); 9085 EPI.Variadic = false; 9086 } 9087 9088 // Declare a constructor for each number of parameters. 9089 // 9090 // C++11 [class.inhctor]p1: 9091 // The candidate set of inherited constructors from the class X named in 9092 // the using-declaration consists of [... modulo defects ...] for each 9093 // constructor or constructor template of X, the set of constructors or 9094 // constructor templates that results from omitting any ellipsis parameter 9095 // specification and successively omitting parameters with a default 9096 // argument from the end of the parameter-type-list 9097 unsigned MinParams = minParamsToInherit(Ctor); 9098 unsigned Params = Ctor->getNumParams(); 9099 if (Params >= MinParams) { 9100 do 9101 declareCtor(UsingLoc, Ctor, 9102 SemaRef.Context.getFunctionType( 9103 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 9104 while (Params > MinParams && 9105 Ctor->getParamDecl(--Params)->hasDefaultArg()); 9106 } 9107 } 9108 9109 /// Find the using-declaration which specified that we should inherit the 9110 /// constructors of \p Base. 9111 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 9112 // No fancy lookup required; just look for the base constructor name 9113 // directly within the derived class. 9114 ASTContext &Context = SemaRef.Context; 9115 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9116 Context.getCanonicalType(Context.getRecordType(Base))); 9117 DeclContext::lookup_result Decls = Derived->lookup(Name); 9118 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 9119 } 9120 9121 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 9122 // C++11 [class.inhctor]p3: 9123 // [F]or each constructor template in the candidate set of inherited 9124 // constructors, a constructor template is implicitly declared 9125 if (Ctor->getDescribedFunctionTemplate()) 9126 return 0; 9127 9128 // For each non-template constructor in the candidate set of inherited 9129 // constructors other than a constructor having no parameters or a 9130 // copy/move constructor having a single parameter, a constructor is 9131 // implicitly declared [...] 9132 if (Ctor->getNumParams() == 0) 9133 return 1; 9134 if (Ctor->isCopyOrMoveConstructor()) 9135 return 2; 9136 9137 // Per discussion on core reflector, never inherit a constructor which 9138 // would become a default, copy, or move constructor of Derived either. 9139 const ParmVarDecl *PD = Ctor->getParamDecl(0); 9140 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 9141 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 9142 } 9143 9144 /// Declare a single inheriting constructor, inheriting the specified 9145 /// constructor, with the given type. 9146 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 9147 QualType DerivedType) { 9148 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 9149 9150 // C++11 [class.inhctor]p3: 9151 // ... a constructor is implicitly declared with the same constructor 9152 // characteristics unless there is a user-declared constructor with 9153 // the same signature in the class where the using-declaration appears 9154 if (Entry.DeclaredInDerived) 9155 return; 9156 9157 // C++11 [class.inhctor]p7: 9158 // If two using-declarations declare inheriting constructors with the 9159 // same signature, the program is ill-formed 9160 if (Entry.DerivedCtor) { 9161 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 9162 // Only diagnose this once per constructor. 9163 if (Entry.DerivedCtor->isInvalidDecl()) 9164 return; 9165 Entry.DerivedCtor->setInvalidDecl(); 9166 9167 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9168 SemaRef.Diag(BaseCtor->getLocation(), 9169 diag::note_using_decl_constructor_conflict_current_ctor); 9170 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9171 diag::note_using_decl_constructor_conflict_previous_ctor); 9172 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9173 diag::note_using_decl_constructor_conflict_previous_using); 9174 } else { 9175 // Core issue (no number): if the same inheriting constructor is 9176 // produced by multiple base class constructors from the same base 9177 // class, the inheriting constructor is defined as deleted. 9178 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9179 } 9180 9181 return; 9182 } 9183 9184 ASTContext &Context = SemaRef.Context; 9185 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9186 Context.getCanonicalType(Context.getRecordType(Derived))); 9187 DeclarationNameInfo NameInfo(Name, UsingLoc); 9188 9189 TemplateParameterList *TemplateParams = nullptr; 9190 if (const FunctionTemplateDecl *FTD = 9191 BaseCtor->getDescribedFunctionTemplate()) { 9192 TemplateParams = FTD->getTemplateParameters(); 9193 // We're reusing template parameters from a different DeclContext. This 9194 // is questionable at best, but works out because the template depth in 9195 // both places is guaranteed to be 0. 9196 // FIXME: Rebuild the template parameters in the new context, and 9197 // transform the function type to refer to them. 9198 } 9199 9200 // Build type source info pointing at the using-declaration. This is 9201 // required by template instantiation. 9202 TypeSourceInfo *TInfo = 9203 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9204 FunctionProtoTypeLoc ProtoLoc = 9205 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9206 9207 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9208 Context, Derived, UsingLoc, NameInfo, DerivedType, 9209 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9210 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9211 9212 // Build an unevaluated exception specification for this constructor. 9213 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9214 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9215 EPI.ExceptionSpec.Type = EST_Unevaluated; 9216 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9217 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9218 FPT->getParamTypes(), EPI)); 9219 9220 // Build the parameter declarations. 9221 SmallVector<ParmVarDecl *, 16> ParamDecls; 9222 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9223 TypeSourceInfo *TInfo = 9224 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9225 ParmVarDecl *PD = ParmVarDecl::Create( 9226 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9227 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9228 PD->setScopeInfo(0, I); 9229 PD->setImplicit(); 9230 ParamDecls.push_back(PD); 9231 ProtoLoc.setParam(I, PD); 9232 } 9233 9234 // Set up the new constructor. 9235 DerivedCtor->setAccess(BaseCtor->getAccess()); 9236 DerivedCtor->setParams(ParamDecls); 9237 DerivedCtor->setInheritedConstructor(BaseCtor); 9238 if (BaseCtor->isDeleted()) 9239 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9240 9241 // If this is a constructor template, build the template declaration. 9242 if (TemplateParams) { 9243 FunctionTemplateDecl *DerivedTemplate = 9244 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9245 TemplateParams, DerivedCtor); 9246 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9247 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9248 Derived->addDecl(DerivedTemplate); 9249 } else { 9250 Derived->addDecl(DerivedCtor); 9251 } 9252 9253 Entry.BaseCtor = BaseCtor; 9254 Entry.DerivedCtor = DerivedCtor; 9255 } 9256 9257 Sema &SemaRef; 9258 CXXRecordDecl *Derived; 9259 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9260 MapType Map; 9261 }; 9262 } 9263 9264 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9265 // Defer declaring the inheriting constructors until the class is 9266 // instantiated. 9267 if (ClassDecl->isDependentContext()) 9268 return; 9269 9270 // Find base classes from which we might inherit constructors. 9271 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9272 for (const auto &BaseIt : ClassDecl->bases()) 9273 if (BaseIt.getInheritConstructors()) 9274 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9275 9276 // Go no further if we're not inheriting any constructors. 9277 if (InheritedBases.empty()) 9278 return; 9279 9280 // Declare the inherited constructors. 9281 InheritingConstructorInfo ICI(*this, ClassDecl); 9282 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9283 ICI.inheritAll(InheritedBases[I]); 9284 } 9285 9286 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9287 CXXConstructorDecl *Constructor) { 9288 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9289 assert(Constructor->getInheritedConstructor() && 9290 !Constructor->doesThisDeclarationHaveABody() && 9291 !Constructor->isDeleted()); 9292 9293 SynthesizedFunctionScope Scope(*this, Constructor); 9294 DiagnosticErrorTrap Trap(Diags); 9295 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9296 Trap.hasErrorOccurred()) { 9297 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9298 << Context.getTagDeclType(ClassDecl); 9299 Constructor->setInvalidDecl(); 9300 return; 9301 } 9302 9303 SourceLocation Loc = Constructor->getLocation(); 9304 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9305 9306 Constructor->markUsed(Context); 9307 MarkVTableUsed(CurrentLocation, ClassDecl); 9308 9309 if (ASTMutationListener *L = getASTMutationListener()) { 9310 L->CompletedImplicitDefinition(Constructor); 9311 } 9312 } 9313 9314 9315 Sema::ImplicitExceptionSpecification 9316 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9317 CXXRecordDecl *ClassDecl = MD->getParent(); 9318 9319 // C++ [except.spec]p14: 9320 // An implicitly declared special member function (Clause 12) shall have 9321 // an exception-specification. 9322 ImplicitExceptionSpecification ExceptSpec(*this); 9323 if (ClassDecl->isInvalidDecl()) 9324 return ExceptSpec; 9325 9326 // Direct base-class destructors. 9327 for (const auto &B : ClassDecl->bases()) { 9328 if (B.isVirtual()) // Handled below. 9329 continue; 9330 9331 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9332 ExceptSpec.CalledDecl(B.getLocStart(), 9333 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9334 } 9335 9336 // Virtual base-class destructors. 9337 for (const auto &B : ClassDecl->vbases()) { 9338 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9339 ExceptSpec.CalledDecl(B.getLocStart(), 9340 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9341 } 9342 9343 // Field destructors. 9344 for (const auto *F : ClassDecl->fields()) { 9345 if (const RecordType *RecordTy 9346 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9347 ExceptSpec.CalledDecl(F->getLocation(), 9348 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9349 } 9350 9351 return ExceptSpec; 9352 } 9353 9354 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9355 // C++ [class.dtor]p2: 9356 // If a class has no user-declared destructor, a destructor is 9357 // declared implicitly. An implicitly-declared destructor is an 9358 // inline public member of its class. 9359 assert(ClassDecl->needsImplicitDestructor()); 9360 9361 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9362 if (DSM.isAlreadyBeingDeclared()) 9363 return nullptr; 9364 9365 // Create the actual destructor declaration. 9366 CanQualType ClassType 9367 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9368 SourceLocation ClassLoc = ClassDecl->getLocation(); 9369 DeclarationName Name 9370 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9371 DeclarationNameInfo NameInfo(Name, ClassLoc); 9372 CXXDestructorDecl *Destructor 9373 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9374 QualType(), nullptr, /*isInline=*/true, 9375 /*isImplicitlyDeclared=*/true); 9376 Destructor->setAccess(AS_public); 9377 Destructor->setDefaulted(); 9378 9379 if (getLangOpts().CUDA) { 9380 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9381 Destructor, 9382 /* ConstRHS */ false, 9383 /* Diagnose */ false); 9384 } 9385 9386 // Build an exception specification pointing back at this destructor. 9387 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9388 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9389 9390 AddOverriddenMethods(ClassDecl, Destructor); 9391 9392 // We don't need to use SpecialMemberIsTrivial here; triviality for 9393 // destructors is easy to compute. 9394 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9395 9396 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9397 SetDeclDeleted(Destructor, ClassLoc); 9398 9399 // Note that we have declared this destructor. 9400 ++ASTContext::NumImplicitDestructorsDeclared; 9401 9402 // Introduce this destructor into its scope. 9403 if (Scope *S = getScopeForContext(ClassDecl)) 9404 PushOnScopeChains(Destructor, S, false); 9405 ClassDecl->addDecl(Destructor); 9406 9407 return Destructor; 9408 } 9409 9410 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9411 CXXDestructorDecl *Destructor) { 9412 assert((Destructor->isDefaulted() && 9413 !Destructor->doesThisDeclarationHaveABody() && 9414 !Destructor->isDeleted()) && 9415 "DefineImplicitDestructor - call it for implicit default dtor"); 9416 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9417 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9418 9419 if (Destructor->isInvalidDecl()) 9420 return; 9421 9422 SynthesizedFunctionScope Scope(*this, Destructor); 9423 9424 DiagnosticErrorTrap Trap(Diags); 9425 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9426 Destructor->getParent()); 9427 9428 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9429 Diag(CurrentLocation, diag::note_member_synthesized_at) 9430 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9431 9432 Destructor->setInvalidDecl(); 9433 return; 9434 } 9435 9436 // The exception specification is needed because we are defining the 9437 // function. 9438 ResolveExceptionSpec(CurrentLocation, 9439 Destructor->getType()->castAs<FunctionProtoType>()); 9440 9441 SourceLocation Loc = Destructor->getLocEnd().isValid() 9442 ? Destructor->getLocEnd() 9443 : Destructor->getLocation(); 9444 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9445 Destructor->markUsed(Context); 9446 MarkVTableUsed(CurrentLocation, ClassDecl); 9447 9448 if (ASTMutationListener *L = getASTMutationListener()) { 9449 L->CompletedImplicitDefinition(Destructor); 9450 } 9451 } 9452 9453 /// \brief Perform any semantic analysis which needs to be delayed until all 9454 /// pending class member declarations have been parsed. 9455 void Sema::ActOnFinishCXXMemberDecls() { 9456 // If the context is an invalid C++ class, just suppress these checks. 9457 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9458 if (Record->isInvalidDecl()) { 9459 DelayedDefaultedMemberExceptionSpecs.clear(); 9460 DelayedExceptionSpecChecks.clear(); 9461 return; 9462 } 9463 } 9464 } 9465 9466 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) { 9467 // Don't do anything for template patterns. 9468 if (Class->getDescribedClassTemplate()) 9469 return; 9470 9471 for (Decl *Member : Class->decls()) { 9472 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 9473 if (!CD) { 9474 // Recurse on nested classes. 9475 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member)) 9476 getDefaultArgExprsForConstructors(S, NestedRD); 9477 continue; 9478 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) { 9479 continue; 9480 } 9481 9482 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) { 9483 // Skip any default arguments that we've already instantiated. 9484 if (S.Context.getDefaultArgExprForConstructor(CD, I)) 9485 continue; 9486 9487 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD, 9488 CD->getParamDecl(I)).get(); 9489 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 9490 } 9491 } 9492 } 9493 9494 void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) { 9495 auto *RD = dyn_cast<CXXRecordDecl>(D); 9496 9497 // Default constructors that are annotated with __declspec(dllexport) which 9498 // have default arguments or don't use the standard calling convention are 9499 // wrapped with a thunk called the default constructor closure. 9500 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft()) 9501 getDefaultArgExprsForConstructors(*this, RD); 9502 } 9503 9504 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9505 CXXDestructorDecl *Destructor) { 9506 assert(getLangOpts().CPlusPlus11 && 9507 "adjusting dtor exception specs was introduced in c++11"); 9508 9509 // C++11 [class.dtor]p3: 9510 // A declaration of a destructor that does not have an exception- 9511 // specification is implicitly considered to have the same exception- 9512 // specification as an implicit declaration. 9513 const FunctionProtoType *DtorType = Destructor->getType()-> 9514 getAs<FunctionProtoType>(); 9515 if (DtorType->hasExceptionSpec()) 9516 return; 9517 9518 // Replace the destructor's type, building off the existing one. Fortunately, 9519 // the only thing of interest in the destructor type is its extended info. 9520 // The return and arguments are fixed. 9521 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9522 EPI.ExceptionSpec.Type = EST_Unevaluated; 9523 EPI.ExceptionSpec.SourceDecl = Destructor; 9524 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9525 9526 // FIXME: If the destructor has a body that could throw, and the newly created 9527 // spec doesn't allow exceptions, we should emit a warning, because this 9528 // change in behavior can break conforming C++03 programs at runtime. 9529 // However, we don't have a body or an exception specification yet, so it 9530 // needs to be done somewhere else. 9531 } 9532 9533 namespace { 9534 /// \brief An abstract base class for all helper classes used in building the 9535 // copy/move operators. These classes serve as factory functions and help us 9536 // avoid using the same Expr* in the AST twice. 9537 class ExprBuilder { 9538 ExprBuilder(const ExprBuilder&) = delete; 9539 ExprBuilder &operator=(const ExprBuilder&) = delete; 9540 9541 protected: 9542 static Expr *assertNotNull(Expr *E) { 9543 assert(E && "Expression construction must not fail."); 9544 return E; 9545 } 9546 9547 public: 9548 ExprBuilder() {} 9549 virtual ~ExprBuilder() {} 9550 9551 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9552 }; 9553 9554 class RefBuilder: public ExprBuilder { 9555 VarDecl *Var; 9556 QualType VarType; 9557 9558 public: 9559 Expr *build(Sema &S, SourceLocation Loc) const override { 9560 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9561 } 9562 9563 RefBuilder(VarDecl *Var, QualType VarType) 9564 : Var(Var), VarType(VarType) {} 9565 }; 9566 9567 class ThisBuilder: public ExprBuilder { 9568 public: 9569 Expr *build(Sema &S, SourceLocation Loc) const override { 9570 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9571 } 9572 }; 9573 9574 class CastBuilder: public ExprBuilder { 9575 const ExprBuilder &Builder; 9576 QualType Type; 9577 ExprValueKind Kind; 9578 const CXXCastPath &Path; 9579 9580 public: 9581 Expr *build(Sema &S, SourceLocation Loc) const override { 9582 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9583 CK_UncheckedDerivedToBase, Kind, 9584 &Path).get()); 9585 } 9586 9587 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9588 const CXXCastPath &Path) 9589 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9590 }; 9591 9592 class DerefBuilder: public ExprBuilder { 9593 const ExprBuilder &Builder; 9594 9595 public: 9596 Expr *build(Sema &S, SourceLocation Loc) const override { 9597 return assertNotNull( 9598 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9599 } 9600 9601 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9602 }; 9603 9604 class MemberBuilder: public ExprBuilder { 9605 const ExprBuilder &Builder; 9606 QualType Type; 9607 CXXScopeSpec SS; 9608 bool IsArrow; 9609 LookupResult &MemberLookup; 9610 9611 public: 9612 Expr *build(Sema &S, SourceLocation Loc) const override { 9613 return assertNotNull(S.BuildMemberReferenceExpr( 9614 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9615 nullptr, MemberLookup, nullptr).get()); 9616 } 9617 9618 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9619 LookupResult &MemberLookup) 9620 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9621 MemberLookup(MemberLookup) {} 9622 }; 9623 9624 class MoveCastBuilder: public ExprBuilder { 9625 const ExprBuilder &Builder; 9626 9627 public: 9628 Expr *build(Sema &S, SourceLocation Loc) const override { 9629 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9630 } 9631 9632 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9633 }; 9634 9635 class LvalueConvBuilder: public ExprBuilder { 9636 const ExprBuilder &Builder; 9637 9638 public: 9639 Expr *build(Sema &S, SourceLocation Loc) const override { 9640 return assertNotNull( 9641 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9642 } 9643 9644 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9645 }; 9646 9647 class SubscriptBuilder: public ExprBuilder { 9648 const ExprBuilder &Base; 9649 const ExprBuilder &Index; 9650 9651 public: 9652 Expr *build(Sema &S, SourceLocation Loc) const override { 9653 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9654 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9655 } 9656 9657 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9658 : Base(Base), Index(Index) {} 9659 }; 9660 9661 } // end anonymous namespace 9662 9663 /// When generating a defaulted copy or move assignment operator, if a field 9664 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9665 /// do so. This optimization only applies for arrays of scalars, and for arrays 9666 /// of class type where the selected copy/move-assignment operator is trivial. 9667 static StmtResult 9668 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9669 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9670 // Compute the size of the memory buffer to be copied. 9671 QualType SizeType = S.Context.getSizeType(); 9672 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9673 S.Context.getTypeSizeInChars(T).getQuantity()); 9674 9675 // Take the address of the field references for "from" and "to". We 9676 // directly construct UnaryOperators here because semantic analysis 9677 // does not permit us to take the address of an xvalue. 9678 Expr *From = FromB.build(S, Loc); 9679 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9680 S.Context.getPointerType(From->getType()), 9681 VK_RValue, OK_Ordinary, Loc); 9682 Expr *To = ToB.build(S, Loc); 9683 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9684 S.Context.getPointerType(To->getType()), 9685 VK_RValue, OK_Ordinary, Loc); 9686 9687 const Type *E = T->getBaseElementTypeUnsafe(); 9688 bool NeedsCollectableMemCpy = 9689 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9690 9691 // Create a reference to the __builtin_objc_memmove_collectable function 9692 StringRef MemCpyName = NeedsCollectableMemCpy ? 9693 "__builtin_objc_memmove_collectable" : 9694 "__builtin_memcpy"; 9695 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9696 Sema::LookupOrdinaryName); 9697 S.LookupName(R, S.TUScope, true); 9698 9699 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9700 if (!MemCpy) 9701 // Something went horribly wrong earlier, and we will have complained 9702 // about it. 9703 return StmtError(); 9704 9705 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9706 VK_RValue, Loc, nullptr); 9707 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9708 9709 Expr *CallArgs[] = { 9710 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9711 }; 9712 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9713 Loc, CallArgs, Loc); 9714 9715 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9716 return Call.getAs<Stmt>(); 9717 } 9718 9719 /// \brief Builds a statement that copies/moves the given entity from \p From to 9720 /// \c To. 9721 /// 9722 /// This routine is used to copy/move the members of a class with an 9723 /// implicitly-declared copy/move assignment operator. When the entities being 9724 /// copied are arrays, this routine builds for loops to copy them. 9725 /// 9726 /// \param S The Sema object used for type-checking. 9727 /// 9728 /// \param Loc The location where the implicit copy/move is being generated. 9729 /// 9730 /// \param T The type of the expressions being copied/moved. Both expressions 9731 /// must have this type. 9732 /// 9733 /// \param To The expression we are copying/moving to. 9734 /// 9735 /// \param From The expression we are copying/moving from. 9736 /// 9737 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9738 /// Otherwise, it's a non-static member subobject. 9739 /// 9740 /// \param Copying Whether we're copying or moving. 9741 /// 9742 /// \param Depth Internal parameter recording the depth of the recursion. 9743 /// 9744 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9745 /// if a memcpy should be used instead. 9746 static StmtResult 9747 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9748 const ExprBuilder &To, const ExprBuilder &From, 9749 bool CopyingBaseSubobject, bool Copying, 9750 unsigned Depth = 0) { 9751 // C++11 [class.copy]p28: 9752 // Each subobject is assigned in the manner appropriate to its type: 9753 // 9754 // - if the subobject is of class type, as if by a call to operator= with 9755 // the subobject as the object expression and the corresponding 9756 // subobject of x as a single function argument (as if by explicit 9757 // qualification; that is, ignoring any possible virtual overriding 9758 // functions in more derived classes); 9759 // 9760 // C++03 [class.copy]p13: 9761 // - if the subobject is of class type, the copy assignment operator for 9762 // the class is used (as if by explicit qualification; that is, 9763 // ignoring any possible virtual overriding functions in more derived 9764 // classes); 9765 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9766 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9767 9768 // Look for operator=. 9769 DeclarationName Name 9770 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9771 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9772 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9773 9774 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9775 // operator. 9776 if (!S.getLangOpts().CPlusPlus11) { 9777 LookupResult::Filter F = OpLookup.makeFilter(); 9778 while (F.hasNext()) { 9779 NamedDecl *D = F.next(); 9780 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9781 if (Method->isCopyAssignmentOperator() || 9782 (!Copying && Method->isMoveAssignmentOperator())) 9783 continue; 9784 9785 F.erase(); 9786 } 9787 F.done(); 9788 } 9789 9790 // Suppress the protected check (C++ [class.protected]) for each of the 9791 // assignment operators we found. This strange dance is required when 9792 // we're assigning via a base classes's copy-assignment operator. To 9793 // ensure that we're getting the right base class subobject (without 9794 // ambiguities), we need to cast "this" to that subobject type; to 9795 // ensure that we don't go through the virtual call mechanism, we need 9796 // to qualify the operator= name with the base class (see below). However, 9797 // this means that if the base class has a protected copy assignment 9798 // operator, the protected member access check will fail. So, we 9799 // rewrite "protected" access to "public" access in this case, since we 9800 // know by construction that we're calling from a derived class. 9801 if (CopyingBaseSubobject) { 9802 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9803 L != LEnd; ++L) { 9804 if (L.getAccess() == AS_protected) 9805 L.setAccess(AS_public); 9806 } 9807 } 9808 9809 // Create the nested-name-specifier that will be used to qualify the 9810 // reference to operator=; this is required to suppress the virtual 9811 // call mechanism. 9812 CXXScopeSpec SS; 9813 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9814 SS.MakeTrivial(S.Context, 9815 NestedNameSpecifier::Create(S.Context, nullptr, false, 9816 CanonicalT), 9817 Loc); 9818 9819 // Create the reference to operator=. 9820 ExprResult OpEqualRef 9821 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9822 SS, /*TemplateKWLoc=*/SourceLocation(), 9823 /*FirstQualifierInScope=*/nullptr, 9824 OpLookup, 9825 /*TemplateArgs=*/nullptr, 9826 /*SuppressQualifierCheck=*/true); 9827 if (OpEqualRef.isInvalid()) 9828 return StmtError(); 9829 9830 // Build the call to the assignment operator. 9831 9832 Expr *FromInst = From.build(S, Loc); 9833 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9834 OpEqualRef.getAs<Expr>(), 9835 Loc, FromInst, Loc); 9836 if (Call.isInvalid()) 9837 return StmtError(); 9838 9839 // If we built a call to a trivial 'operator=' while copying an array, 9840 // bail out. We'll replace the whole shebang with a memcpy. 9841 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9842 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9843 return StmtResult((Stmt*)nullptr); 9844 9845 // Convert to an expression-statement, and clean up any produced 9846 // temporaries. 9847 return S.ActOnExprStmt(Call); 9848 } 9849 9850 // - if the subobject is of scalar type, the built-in assignment 9851 // operator is used. 9852 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9853 if (!ArrayTy) { 9854 ExprResult Assignment = S.CreateBuiltinBinOp( 9855 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9856 if (Assignment.isInvalid()) 9857 return StmtError(); 9858 return S.ActOnExprStmt(Assignment); 9859 } 9860 9861 // - if the subobject is an array, each element is assigned, in the 9862 // manner appropriate to the element type; 9863 9864 // Construct a loop over the array bounds, e.g., 9865 // 9866 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9867 // 9868 // that will copy each of the array elements. 9869 QualType SizeType = S.Context.getSizeType(); 9870 9871 // Create the iteration variable. 9872 IdentifierInfo *IterationVarName = nullptr; 9873 { 9874 SmallString<8> Str; 9875 llvm::raw_svector_ostream OS(Str); 9876 OS << "__i" << Depth; 9877 IterationVarName = &S.Context.Idents.get(OS.str()); 9878 } 9879 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9880 IterationVarName, SizeType, 9881 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9882 SC_None); 9883 9884 // Initialize the iteration variable to zero. 9885 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9886 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9887 9888 // Creates a reference to the iteration variable. 9889 RefBuilder IterationVarRef(IterationVar, SizeType); 9890 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9891 9892 // Create the DeclStmt that holds the iteration variable. 9893 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9894 9895 // Subscript the "from" and "to" expressions with the iteration variable. 9896 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9897 MoveCastBuilder FromIndexMove(FromIndexCopy); 9898 const ExprBuilder *FromIndex; 9899 if (Copying) 9900 FromIndex = &FromIndexCopy; 9901 else 9902 FromIndex = &FromIndexMove; 9903 9904 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9905 9906 // Build the copy/move for an individual element of the array. 9907 StmtResult Copy = 9908 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9909 ToIndex, *FromIndex, CopyingBaseSubobject, 9910 Copying, Depth + 1); 9911 // Bail out if copying fails or if we determined that we should use memcpy. 9912 if (Copy.isInvalid() || !Copy.get()) 9913 return Copy; 9914 9915 // Create the comparison against the array bound. 9916 llvm::APInt Upper 9917 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9918 Expr *Comparison 9919 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9920 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9921 BO_NE, S.Context.BoolTy, 9922 VK_RValue, OK_Ordinary, Loc, false); 9923 9924 // Create the pre-increment of the iteration variable. 9925 Expr *Increment 9926 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9927 SizeType, VK_LValue, OK_Ordinary, Loc); 9928 9929 // Construct the loop that copies all elements of this array. 9930 return S.ActOnForStmt(Loc, Loc, InitStmt, 9931 S.MakeFullExpr(Comparison), 9932 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9933 Loc, Copy.get()); 9934 } 9935 9936 static StmtResult 9937 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9938 const ExprBuilder &To, const ExprBuilder &From, 9939 bool CopyingBaseSubobject, bool Copying) { 9940 // Maybe we should use a memcpy? 9941 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9942 T.isTriviallyCopyableType(S.Context)) 9943 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9944 9945 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9946 CopyingBaseSubobject, 9947 Copying, 0)); 9948 9949 // If we ended up picking a trivial assignment operator for an array of a 9950 // non-trivially-copyable class type, just emit a memcpy. 9951 if (!Result.isInvalid() && !Result.get()) 9952 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9953 9954 return Result; 9955 } 9956 9957 Sema::ImplicitExceptionSpecification 9958 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9959 CXXRecordDecl *ClassDecl = MD->getParent(); 9960 9961 ImplicitExceptionSpecification ExceptSpec(*this); 9962 if (ClassDecl->isInvalidDecl()) 9963 return ExceptSpec; 9964 9965 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9966 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9967 unsigned ArgQuals = 9968 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9969 9970 // C++ [except.spec]p14: 9971 // An implicitly declared special member function (Clause 12) shall have an 9972 // exception-specification. [...] 9973 9974 // It is unspecified whether or not an implicit copy assignment operator 9975 // attempts to deduplicate calls to assignment operators of virtual bases are 9976 // made. As such, this exception specification is effectively unspecified. 9977 // Based on a similar decision made for constness in C++0x, we're erring on 9978 // the side of assuming such calls to be made regardless of whether they 9979 // actually happen. 9980 for (const auto &Base : ClassDecl->bases()) { 9981 if (Base.isVirtual()) 9982 continue; 9983 9984 CXXRecordDecl *BaseClassDecl 9985 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9986 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9987 ArgQuals, false, 0)) 9988 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9989 } 9990 9991 for (const auto &Base : ClassDecl->vbases()) { 9992 CXXRecordDecl *BaseClassDecl 9993 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9994 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9995 ArgQuals, false, 0)) 9996 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9997 } 9998 9999 for (const auto *Field : ClassDecl->fields()) { 10000 QualType FieldType = Context.getBaseElementType(Field->getType()); 10001 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10002 if (CXXMethodDecl *CopyAssign = 10003 LookupCopyingAssignment(FieldClassDecl, 10004 ArgQuals | FieldType.getCVRQualifiers(), 10005 false, 0)) 10006 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 10007 } 10008 } 10009 10010 return ExceptSpec; 10011 } 10012 10013 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 10014 // Note: The following rules are largely analoguous to the copy 10015 // constructor rules. Note that virtual bases are not taken into account 10016 // for determining the argument type of the operator. Note also that 10017 // operators taking an object instead of a reference are allowed. 10018 assert(ClassDecl->needsImplicitCopyAssignment()); 10019 10020 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 10021 if (DSM.isAlreadyBeingDeclared()) 10022 return nullptr; 10023 10024 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10025 QualType RetType = Context.getLValueReferenceType(ArgType); 10026 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 10027 if (Const) 10028 ArgType = ArgType.withConst(); 10029 ArgType = Context.getLValueReferenceType(ArgType); 10030 10031 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10032 CXXCopyAssignment, 10033 Const); 10034 10035 // An implicitly-declared copy assignment operator is an inline public 10036 // member of its class. 10037 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10038 SourceLocation ClassLoc = ClassDecl->getLocation(); 10039 DeclarationNameInfo NameInfo(Name, ClassLoc); 10040 CXXMethodDecl *CopyAssignment = 10041 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10042 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10043 /*isInline=*/true, Constexpr, SourceLocation()); 10044 CopyAssignment->setAccess(AS_public); 10045 CopyAssignment->setDefaulted(); 10046 CopyAssignment->setImplicit(); 10047 10048 if (getLangOpts().CUDA) { 10049 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 10050 CopyAssignment, 10051 /* ConstRHS */ Const, 10052 /* Diagnose */ false); 10053 } 10054 10055 // Build an exception specification pointing back at this member. 10056 FunctionProtoType::ExtProtoInfo EPI = 10057 getImplicitMethodEPI(*this, CopyAssignment); 10058 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10059 10060 // Add the parameter to the operator. 10061 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 10062 ClassLoc, ClassLoc, 10063 /*Id=*/nullptr, ArgType, 10064 /*TInfo=*/nullptr, SC_None, 10065 nullptr); 10066 CopyAssignment->setParams(FromParam); 10067 10068 AddOverriddenMethods(ClassDecl, CopyAssignment); 10069 10070 CopyAssignment->setTrivial( 10071 ClassDecl->needsOverloadResolutionForCopyAssignment() 10072 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 10073 : ClassDecl->hasTrivialCopyAssignment()); 10074 10075 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 10076 SetDeclDeleted(CopyAssignment, ClassLoc); 10077 10078 // Note that we have added this copy-assignment operator. 10079 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10080 10081 if (Scope *S = getScopeForContext(ClassDecl)) 10082 PushOnScopeChains(CopyAssignment, S, false); 10083 ClassDecl->addDecl(CopyAssignment); 10084 10085 return CopyAssignment; 10086 } 10087 10088 /// Diagnose an implicit copy operation for a class which is odr-used, but 10089 /// which is deprecated because the class has a user-declared copy constructor, 10090 /// copy assignment operator, or destructor. 10091 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 10092 SourceLocation UseLoc) { 10093 assert(CopyOp->isImplicit()); 10094 10095 CXXRecordDecl *RD = CopyOp->getParent(); 10096 CXXMethodDecl *UserDeclaredOperation = nullptr; 10097 10098 // In Microsoft mode, assignment operations don't affect constructors and 10099 // vice versa. 10100 if (RD->hasUserDeclaredDestructor()) { 10101 UserDeclaredOperation = RD->getDestructor(); 10102 } else if (!isa<CXXConstructorDecl>(CopyOp) && 10103 RD->hasUserDeclaredCopyConstructor() && 10104 !S.getLangOpts().MSVCCompat) { 10105 // Find any user-declared copy constructor. 10106 for (auto *I : RD->ctors()) { 10107 if (I->isCopyConstructor()) { 10108 UserDeclaredOperation = I; 10109 break; 10110 } 10111 } 10112 assert(UserDeclaredOperation); 10113 } else if (isa<CXXConstructorDecl>(CopyOp) && 10114 RD->hasUserDeclaredCopyAssignment() && 10115 !S.getLangOpts().MSVCCompat) { 10116 // Find any user-declared move assignment operator. 10117 for (auto *I : RD->methods()) { 10118 if (I->isCopyAssignmentOperator()) { 10119 UserDeclaredOperation = I; 10120 break; 10121 } 10122 } 10123 assert(UserDeclaredOperation); 10124 } 10125 10126 if (UserDeclaredOperation) { 10127 S.Diag(UserDeclaredOperation->getLocation(), 10128 diag::warn_deprecated_copy_operation) 10129 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 10130 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 10131 S.Diag(UseLoc, diag::note_member_synthesized_at) 10132 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 10133 : Sema::CXXCopyAssignment) 10134 << RD; 10135 } 10136 } 10137 10138 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 10139 CXXMethodDecl *CopyAssignOperator) { 10140 assert((CopyAssignOperator->isDefaulted() && 10141 CopyAssignOperator->isOverloadedOperator() && 10142 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 10143 !CopyAssignOperator->doesThisDeclarationHaveABody() && 10144 !CopyAssignOperator->isDeleted()) && 10145 "DefineImplicitCopyAssignment called for wrong function"); 10146 10147 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 10148 10149 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 10150 CopyAssignOperator->setInvalidDecl(); 10151 return; 10152 } 10153 10154 // C++11 [class.copy]p18: 10155 // The [definition of an implicitly declared copy assignment operator] is 10156 // deprecated if the class has a user-declared copy constructor or a 10157 // user-declared destructor. 10158 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 10159 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 10160 10161 CopyAssignOperator->markUsed(Context); 10162 10163 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 10164 DiagnosticErrorTrap Trap(Diags); 10165 10166 // C++0x [class.copy]p30: 10167 // The implicitly-defined or explicitly-defaulted copy assignment operator 10168 // for a non-union class X performs memberwise copy assignment of its 10169 // subobjects. The direct base classes of X are assigned first, in the 10170 // order of their declaration in the base-specifier-list, and then the 10171 // immediate non-static data members of X are assigned, in the order in 10172 // which they were declared in the class definition. 10173 10174 // The statements that form the synthesized function body. 10175 SmallVector<Stmt*, 8> Statements; 10176 10177 // The parameter for the "other" object, which we are copying from. 10178 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 10179 Qualifiers OtherQuals = Other->getType().getQualifiers(); 10180 QualType OtherRefType = Other->getType(); 10181 if (const LValueReferenceType *OtherRef 10182 = OtherRefType->getAs<LValueReferenceType>()) { 10183 OtherRefType = OtherRef->getPointeeType(); 10184 OtherQuals = OtherRefType.getQualifiers(); 10185 } 10186 10187 // Our location for everything implicitly-generated. 10188 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 10189 ? CopyAssignOperator->getLocEnd() 10190 : CopyAssignOperator->getLocation(); 10191 10192 // Builds a DeclRefExpr for the "other" object. 10193 RefBuilder OtherRef(Other, OtherRefType); 10194 10195 // Builds the "this" pointer. 10196 ThisBuilder This; 10197 10198 // Assign base classes. 10199 bool Invalid = false; 10200 for (auto &Base : ClassDecl->bases()) { 10201 // Form the assignment: 10202 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10203 QualType BaseType = Base.getType().getUnqualifiedType(); 10204 if (!BaseType->isRecordType()) { 10205 Invalid = true; 10206 continue; 10207 } 10208 10209 CXXCastPath BasePath; 10210 BasePath.push_back(&Base); 10211 10212 // Construct the "from" expression, which is an implicit cast to the 10213 // appropriately-qualified base type. 10214 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10215 VK_LValue, BasePath); 10216 10217 // Dereference "this". 10218 DerefBuilder DerefThis(This); 10219 CastBuilder To(DerefThis, 10220 Context.getCVRQualifiedType( 10221 BaseType, CopyAssignOperator->getTypeQualifiers()), 10222 VK_LValue, BasePath); 10223 10224 // Build the copy. 10225 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10226 To, From, 10227 /*CopyingBaseSubobject=*/true, 10228 /*Copying=*/true); 10229 if (Copy.isInvalid()) { 10230 Diag(CurrentLocation, diag::note_member_synthesized_at) 10231 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10232 CopyAssignOperator->setInvalidDecl(); 10233 return; 10234 } 10235 10236 // Success! Record the copy. 10237 Statements.push_back(Copy.getAs<Expr>()); 10238 } 10239 10240 // Assign non-static members. 10241 for (auto *Field : ClassDecl->fields()) { 10242 // FIXME: We should form some kind of AST representation for the implied 10243 // memcpy in a union copy operation. 10244 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10245 continue; 10246 10247 if (Field->isInvalidDecl()) { 10248 Invalid = true; 10249 continue; 10250 } 10251 10252 // Check for members of reference type; we can't copy those. 10253 if (Field->getType()->isReferenceType()) { 10254 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10255 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10256 Diag(Field->getLocation(), diag::note_declared_at); 10257 Diag(CurrentLocation, diag::note_member_synthesized_at) 10258 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10259 Invalid = true; 10260 continue; 10261 } 10262 10263 // Check for members of const-qualified, non-class type. 10264 QualType BaseType = Context.getBaseElementType(Field->getType()); 10265 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10266 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10267 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10268 Diag(Field->getLocation(), diag::note_declared_at); 10269 Diag(CurrentLocation, diag::note_member_synthesized_at) 10270 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10271 Invalid = true; 10272 continue; 10273 } 10274 10275 // Suppress assigning zero-width bitfields. 10276 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10277 continue; 10278 10279 QualType FieldType = Field->getType().getNonReferenceType(); 10280 if (FieldType->isIncompleteArrayType()) { 10281 assert(ClassDecl->hasFlexibleArrayMember() && 10282 "Incomplete array type is not valid"); 10283 continue; 10284 } 10285 10286 // Build references to the field in the object we're copying from and to. 10287 CXXScopeSpec SS; // Intentionally empty 10288 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10289 LookupMemberName); 10290 MemberLookup.addDecl(Field); 10291 MemberLookup.resolveKind(); 10292 10293 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10294 10295 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10296 10297 // Build the copy of this field. 10298 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10299 To, From, 10300 /*CopyingBaseSubobject=*/false, 10301 /*Copying=*/true); 10302 if (Copy.isInvalid()) { 10303 Diag(CurrentLocation, diag::note_member_synthesized_at) 10304 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10305 CopyAssignOperator->setInvalidDecl(); 10306 return; 10307 } 10308 10309 // Success! Record the copy. 10310 Statements.push_back(Copy.getAs<Stmt>()); 10311 } 10312 10313 if (!Invalid) { 10314 // Add a "return *this;" 10315 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10316 10317 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10318 if (Return.isInvalid()) 10319 Invalid = true; 10320 else { 10321 Statements.push_back(Return.getAs<Stmt>()); 10322 10323 if (Trap.hasErrorOccurred()) { 10324 Diag(CurrentLocation, diag::note_member_synthesized_at) 10325 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10326 Invalid = true; 10327 } 10328 } 10329 } 10330 10331 // The exception specification is needed because we are defining the 10332 // function. 10333 ResolveExceptionSpec(CurrentLocation, 10334 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10335 10336 if (Invalid) { 10337 CopyAssignOperator->setInvalidDecl(); 10338 return; 10339 } 10340 10341 StmtResult Body; 10342 { 10343 CompoundScopeRAII CompoundScope(*this); 10344 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10345 /*isStmtExpr=*/false); 10346 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10347 } 10348 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10349 10350 if (ASTMutationListener *L = getASTMutationListener()) { 10351 L->CompletedImplicitDefinition(CopyAssignOperator); 10352 } 10353 } 10354 10355 Sema::ImplicitExceptionSpecification 10356 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10357 CXXRecordDecl *ClassDecl = MD->getParent(); 10358 10359 ImplicitExceptionSpecification ExceptSpec(*this); 10360 if (ClassDecl->isInvalidDecl()) 10361 return ExceptSpec; 10362 10363 // C++0x [except.spec]p14: 10364 // An implicitly declared special member function (Clause 12) shall have an 10365 // exception-specification. [...] 10366 10367 // It is unspecified whether or not an implicit move assignment operator 10368 // attempts to deduplicate calls to assignment operators of virtual bases are 10369 // made. As such, this exception specification is effectively unspecified. 10370 // Based on a similar decision made for constness in C++0x, we're erring on 10371 // the side of assuming such calls to be made regardless of whether they 10372 // actually happen. 10373 // Note that a move constructor is not implicitly declared when there are 10374 // virtual bases, but it can still be user-declared and explicitly defaulted. 10375 for (const auto &Base : ClassDecl->bases()) { 10376 if (Base.isVirtual()) 10377 continue; 10378 10379 CXXRecordDecl *BaseClassDecl 10380 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10381 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10382 0, false, 0)) 10383 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10384 } 10385 10386 for (const auto &Base : ClassDecl->vbases()) { 10387 CXXRecordDecl *BaseClassDecl 10388 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10389 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10390 0, false, 0)) 10391 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10392 } 10393 10394 for (const auto *Field : ClassDecl->fields()) { 10395 QualType FieldType = Context.getBaseElementType(Field->getType()); 10396 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10397 if (CXXMethodDecl *MoveAssign = 10398 LookupMovingAssignment(FieldClassDecl, 10399 FieldType.getCVRQualifiers(), 10400 false, 0)) 10401 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10402 } 10403 } 10404 10405 return ExceptSpec; 10406 } 10407 10408 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10409 assert(ClassDecl->needsImplicitMoveAssignment()); 10410 10411 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10412 if (DSM.isAlreadyBeingDeclared()) 10413 return nullptr; 10414 10415 // Note: The following rules are largely analoguous to the move 10416 // constructor rules. 10417 10418 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10419 QualType RetType = Context.getLValueReferenceType(ArgType); 10420 ArgType = Context.getRValueReferenceType(ArgType); 10421 10422 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10423 CXXMoveAssignment, 10424 false); 10425 10426 // An implicitly-declared move assignment operator is an inline public 10427 // member of its class. 10428 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10429 SourceLocation ClassLoc = ClassDecl->getLocation(); 10430 DeclarationNameInfo NameInfo(Name, ClassLoc); 10431 CXXMethodDecl *MoveAssignment = 10432 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10433 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10434 /*isInline=*/true, Constexpr, SourceLocation()); 10435 MoveAssignment->setAccess(AS_public); 10436 MoveAssignment->setDefaulted(); 10437 MoveAssignment->setImplicit(); 10438 10439 if (getLangOpts().CUDA) { 10440 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10441 MoveAssignment, 10442 /* ConstRHS */ false, 10443 /* Diagnose */ false); 10444 } 10445 10446 // Build an exception specification pointing back at this member. 10447 FunctionProtoType::ExtProtoInfo EPI = 10448 getImplicitMethodEPI(*this, MoveAssignment); 10449 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10450 10451 // Add the parameter to the operator. 10452 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10453 ClassLoc, ClassLoc, 10454 /*Id=*/nullptr, ArgType, 10455 /*TInfo=*/nullptr, SC_None, 10456 nullptr); 10457 MoveAssignment->setParams(FromParam); 10458 10459 AddOverriddenMethods(ClassDecl, MoveAssignment); 10460 10461 MoveAssignment->setTrivial( 10462 ClassDecl->needsOverloadResolutionForMoveAssignment() 10463 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10464 : ClassDecl->hasTrivialMoveAssignment()); 10465 10466 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10467 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10468 SetDeclDeleted(MoveAssignment, ClassLoc); 10469 } 10470 10471 // Note that we have added this copy-assignment operator. 10472 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10473 10474 if (Scope *S = getScopeForContext(ClassDecl)) 10475 PushOnScopeChains(MoveAssignment, S, false); 10476 ClassDecl->addDecl(MoveAssignment); 10477 10478 return MoveAssignment; 10479 } 10480 10481 /// Check if we're implicitly defining a move assignment operator for a class 10482 /// with virtual bases. Such a move assignment might move-assign the virtual 10483 /// base multiple times. 10484 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10485 SourceLocation CurrentLocation) { 10486 assert(!Class->isDependentContext() && "should not define dependent move"); 10487 10488 // Only a virtual base could get implicitly move-assigned multiple times. 10489 // Only a non-trivial move assignment can observe this. We only want to 10490 // diagnose if we implicitly define an assignment operator that assigns 10491 // two base classes, both of which move-assign the same virtual base. 10492 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10493 Class->getNumBases() < 2) 10494 return; 10495 10496 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10497 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10498 VBaseMap VBases; 10499 10500 for (auto &BI : Class->bases()) { 10501 Worklist.push_back(&BI); 10502 while (!Worklist.empty()) { 10503 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10504 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10505 10506 // If the base has no non-trivial move assignment operators, 10507 // we don't care about moves from it. 10508 if (!Base->hasNonTrivialMoveAssignment()) 10509 continue; 10510 10511 // If there's nothing virtual here, skip it. 10512 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10513 continue; 10514 10515 // If we're not actually going to call a move assignment for this base, 10516 // or the selected move assignment is trivial, skip it. 10517 Sema::SpecialMemberOverloadResult *SMOR = 10518 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10519 /*ConstArg*/false, /*VolatileArg*/false, 10520 /*RValueThis*/true, /*ConstThis*/false, 10521 /*VolatileThis*/false); 10522 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10523 !SMOR->getMethod()->isMoveAssignmentOperator()) 10524 continue; 10525 10526 if (BaseSpec->isVirtual()) { 10527 // We're going to move-assign this virtual base, and its move 10528 // assignment operator is not trivial. If this can happen for 10529 // multiple distinct direct bases of Class, diagnose it. (If it 10530 // only happens in one base, we'll diagnose it when synthesizing 10531 // that base class's move assignment operator.) 10532 CXXBaseSpecifier *&Existing = 10533 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10534 .first->second; 10535 if (Existing && Existing != &BI) { 10536 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10537 << Class << Base; 10538 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10539 << (Base->getCanonicalDecl() == 10540 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10541 << Base << Existing->getType() << Existing->getSourceRange(); 10542 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10543 << (Base->getCanonicalDecl() == 10544 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10545 << Base << BI.getType() << BaseSpec->getSourceRange(); 10546 10547 // Only diagnose each vbase once. 10548 Existing = nullptr; 10549 } 10550 } else { 10551 // Only walk over bases that have defaulted move assignment operators. 10552 // We assume that any user-provided move assignment operator handles 10553 // the multiple-moves-of-vbase case itself somehow. 10554 if (!SMOR->getMethod()->isDefaulted()) 10555 continue; 10556 10557 // We're going to move the base classes of Base. Add them to the list. 10558 for (auto &BI : Base->bases()) 10559 Worklist.push_back(&BI); 10560 } 10561 } 10562 } 10563 } 10564 10565 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10566 CXXMethodDecl *MoveAssignOperator) { 10567 assert((MoveAssignOperator->isDefaulted() && 10568 MoveAssignOperator->isOverloadedOperator() && 10569 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10570 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10571 !MoveAssignOperator->isDeleted()) && 10572 "DefineImplicitMoveAssignment called for wrong function"); 10573 10574 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10575 10576 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10577 MoveAssignOperator->setInvalidDecl(); 10578 return; 10579 } 10580 10581 MoveAssignOperator->markUsed(Context); 10582 10583 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10584 DiagnosticErrorTrap Trap(Diags); 10585 10586 // C++0x [class.copy]p28: 10587 // The implicitly-defined or move assignment operator for a non-union class 10588 // X performs memberwise move assignment of its subobjects. The direct base 10589 // classes of X are assigned first, in the order of their declaration in the 10590 // base-specifier-list, and then the immediate non-static data members of X 10591 // are assigned, in the order in which they were declared in the class 10592 // definition. 10593 10594 // Issue a warning if our implicit move assignment operator will move 10595 // from a virtual base more than once. 10596 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10597 10598 // The statements that form the synthesized function body. 10599 SmallVector<Stmt*, 8> Statements; 10600 10601 // The parameter for the "other" object, which we are move from. 10602 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10603 QualType OtherRefType = Other->getType()-> 10604 getAs<RValueReferenceType>()->getPointeeType(); 10605 assert(!OtherRefType.getQualifiers() && 10606 "Bad argument type of defaulted move assignment"); 10607 10608 // Our location for everything implicitly-generated. 10609 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10610 ? MoveAssignOperator->getLocEnd() 10611 : MoveAssignOperator->getLocation(); 10612 10613 // Builds a reference to the "other" object. 10614 RefBuilder OtherRef(Other, OtherRefType); 10615 // Cast to rvalue. 10616 MoveCastBuilder MoveOther(OtherRef); 10617 10618 // Builds the "this" pointer. 10619 ThisBuilder This; 10620 10621 // Assign base classes. 10622 bool Invalid = false; 10623 for (auto &Base : ClassDecl->bases()) { 10624 // C++11 [class.copy]p28: 10625 // It is unspecified whether subobjects representing virtual base classes 10626 // are assigned more than once by the implicitly-defined copy assignment 10627 // operator. 10628 // FIXME: Do not assign to a vbase that will be assigned by some other base 10629 // class. For a move-assignment, this can result in the vbase being moved 10630 // multiple times. 10631 10632 // Form the assignment: 10633 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10634 QualType BaseType = Base.getType().getUnqualifiedType(); 10635 if (!BaseType->isRecordType()) { 10636 Invalid = true; 10637 continue; 10638 } 10639 10640 CXXCastPath BasePath; 10641 BasePath.push_back(&Base); 10642 10643 // Construct the "from" expression, which is an implicit cast to the 10644 // appropriately-qualified base type. 10645 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10646 10647 // Dereference "this". 10648 DerefBuilder DerefThis(This); 10649 10650 // Implicitly cast "this" to the appropriately-qualified base type. 10651 CastBuilder To(DerefThis, 10652 Context.getCVRQualifiedType( 10653 BaseType, MoveAssignOperator->getTypeQualifiers()), 10654 VK_LValue, BasePath); 10655 10656 // Build the move. 10657 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10658 To, From, 10659 /*CopyingBaseSubobject=*/true, 10660 /*Copying=*/false); 10661 if (Move.isInvalid()) { 10662 Diag(CurrentLocation, diag::note_member_synthesized_at) 10663 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10664 MoveAssignOperator->setInvalidDecl(); 10665 return; 10666 } 10667 10668 // Success! Record the move. 10669 Statements.push_back(Move.getAs<Expr>()); 10670 } 10671 10672 // Assign non-static members. 10673 for (auto *Field : ClassDecl->fields()) { 10674 // FIXME: We should form some kind of AST representation for the implied 10675 // memcpy in a union copy operation. 10676 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10677 continue; 10678 10679 if (Field->isInvalidDecl()) { 10680 Invalid = true; 10681 continue; 10682 } 10683 10684 // Check for members of reference type; we can't move those. 10685 if (Field->getType()->isReferenceType()) { 10686 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10687 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10688 Diag(Field->getLocation(), diag::note_declared_at); 10689 Diag(CurrentLocation, diag::note_member_synthesized_at) 10690 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10691 Invalid = true; 10692 continue; 10693 } 10694 10695 // Check for members of const-qualified, non-class type. 10696 QualType BaseType = Context.getBaseElementType(Field->getType()); 10697 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10698 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10699 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10700 Diag(Field->getLocation(), diag::note_declared_at); 10701 Diag(CurrentLocation, diag::note_member_synthesized_at) 10702 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10703 Invalid = true; 10704 continue; 10705 } 10706 10707 // Suppress assigning zero-width bitfields. 10708 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10709 continue; 10710 10711 QualType FieldType = Field->getType().getNonReferenceType(); 10712 if (FieldType->isIncompleteArrayType()) { 10713 assert(ClassDecl->hasFlexibleArrayMember() && 10714 "Incomplete array type is not valid"); 10715 continue; 10716 } 10717 10718 // Build references to the field in the object we're copying from and to. 10719 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10720 LookupMemberName); 10721 MemberLookup.addDecl(Field); 10722 MemberLookup.resolveKind(); 10723 MemberBuilder From(MoveOther, OtherRefType, 10724 /*IsArrow=*/false, MemberLookup); 10725 MemberBuilder To(This, getCurrentThisType(), 10726 /*IsArrow=*/true, MemberLookup); 10727 10728 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10729 "Member reference with rvalue base must be rvalue except for reference " 10730 "members, which aren't allowed for move assignment."); 10731 10732 // Build the move of this field. 10733 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10734 To, From, 10735 /*CopyingBaseSubobject=*/false, 10736 /*Copying=*/false); 10737 if (Move.isInvalid()) { 10738 Diag(CurrentLocation, diag::note_member_synthesized_at) 10739 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10740 MoveAssignOperator->setInvalidDecl(); 10741 return; 10742 } 10743 10744 // Success! Record the copy. 10745 Statements.push_back(Move.getAs<Stmt>()); 10746 } 10747 10748 if (!Invalid) { 10749 // Add a "return *this;" 10750 ExprResult ThisObj = 10751 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10752 10753 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10754 if (Return.isInvalid()) 10755 Invalid = true; 10756 else { 10757 Statements.push_back(Return.getAs<Stmt>()); 10758 10759 if (Trap.hasErrorOccurred()) { 10760 Diag(CurrentLocation, diag::note_member_synthesized_at) 10761 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10762 Invalid = true; 10763 } 10764 } 10765 } 10766 10767 // The exception specification is needed because we are defining the 10768 // function. 10769 ResolveExceptionSpec(CurrentLocation, 10770 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10771 10772 if (Invalid) { 10773 MoveAssignOperator->setInvalidDecl(); 10774 return; 10775 } 10776 10777 StmtResult Body; 10778 { 10779 CompoundScopeRAII CompoundScope(*this); 10780 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10781 /*isStmtExpr=*/false); 10782 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10783 } 10784 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10785 10786 if (ASTMutationListener *L = getASTMutationListener()) { 10787 L->CompletedImplicitDefinition(MoveAssignOperator); 10788 } 10789 } 10790 10791 Sema::ImplicitExceptionSpecification 10792 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10793 CXXRecordDecl *ClassDecl = MD->getParent(); 10794 10795 ImplicitExceptionSpecification ExceptSpec(*this); 10796 if (ClassDecl->isInvalidDecl()) 10797 return ExceptSpec; 10798 10799 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10800 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10801 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10802 10803 // C++ [except.spec]p14: 10804 // An implicitly declared special member function (Clause 12) shall have an 10805 // exception-specification. [...] 10806 for (const auto &Base : ClassDecl->bases()) { 10807 // Virtual bases are handled below. 10808 if (Base.isVirtual()) 10809 continue; 10810 10811 CXXRecordDecl *BaseClassDecl 10812 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10813 if (CXXConstructorDecl *CopyConstructor = 10814 LookupCopyingConstructor(BaseClassDecl, Quals)) 10815 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10816 } 10817 for (const auto &Base : ClassDecl->vbases()) { 10818 CXXRecordDecl *BaseClassDecl 10819 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10820 if (CXXConstructorDecl *CopyConstructor = 10821 LookupCopyingConstructor(BaseClassDecl, Quals)) 10822 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10823 } 10824 for (const auto *Field : ClassDecl->fields()) { 10825 QualType FieldType = Context.getBaseElementType(Field->getType()); 10826 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10827 if (CXXConstructorDecl *CopyConstructor = 10828 LookupCopyingConstructor(FieldClassDecl, 10829 Quals | FieldType.getCVRQualifiers())) 10830 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10831 } 10832 } 10833 10834 return ExceptSpec; 10835 } 10836 10837 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10838 CXXRecordDecl *ClassDecl) { 10839 // C++ [class.copy]p4: 10840 // If the class definition does not explicitly declare a copy 10841 // constructor, one is declared implicitly. 10842 assert(ClassDecl->needsImplicitCopyConstructor()); 10843 10844 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10845 if (DSM.isAlreadyBeingDeclared()) 10846 return nullptr; 10847 10848 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10849 QualType ArgType = ClassType; 10850 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10851 if (Const) 10852 ArgType = ArgType.withConst(); 10853 ArgType = Context.getLValueReferenceType(ArgType); 10854 10855 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10856 CXXCopyConstructor, 10857 Const); 10858 10859 DeclarationName Name 10860 = Context.DeclarationNames.getCXXConstructorName( 10861 Context.getCanonicalType(ClassType)); 10862 SourceLocation ClassLoc = ClassDecl->getLocation(); 10863 DeclarationNameInfo NameInfo(Name, ClassLoc); 10864 10865 // An implicitly-declared copy constructor is an inline public 10866 // member of its class. 10867 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10868 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10869 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10870 Constexpr); 10871 CopyConstructor->setAccess(AS_public); 10872 CopyConstructor->setDefaulted(); 10873 10874 if (getLangOpts().CUDA) { 10875 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10876 CopyConstructor, 10877 /* ConstRHS */ Const, 10878 /* Diagnose */ false); 10879 } 10880 10881 // Build an exception specification pointing back at this member. 10882 FunctionProtoType::ExtProtoInfo EPI = 10883 getImplicitMethodEPI(*this, CopyConstructor); 10884 CopyConstructor->setType( 10885 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10886 10887 // Add the parameter to the constructor. 10888 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10889 ClassLoc, ClassLoc, 10890 /*IdentifierInfo=*/nullptr, 10891 ArgType, /*TInfo=*/nullptr, 10892 SC_None, nullptr); 10893 CopyConstructor->setParams(FromParam); 10894 10895 CopyConstructor->setTrivial( 10896 ClassDecl->needsOverloadResolutionForCopyConstructor() 10897 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10898 : ClassDecl->hasTrivialCopyConstructor()); 10899 10900 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10901 SetDeclDeleted(CopyConstructor, ClassLoc); 10902 10903 // Note that we have declared this constructor. 10904 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10905 10906 if (Scope *S = getScopeForContext(ClassDecl)) 10907 PushOnScopeChains(CopyConstructor, S, false); 10908 ClassDecl->addDecl(CopyConstructor); 10909 10910 return CopyConstructor; 10911 } 10912 10913 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10914 CXXConstructorDecl *CopyConstructor) { 10915 assert((CopyConstructor->isDefaulted() && 10916 CopyConstructor->isCopyConstructor() && 10917 !CopyConstructor->doesThisDeclarationHaveABody() && 10918 !CopyConstructor->isDeleted()) && 10919 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10920 10921 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10922 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10923 10924 // C++11 [class.copy]p7: 10925 // The [definition of an implicitly declared copy constructor] is 10926 // deprecated if the class has a user-declared copy assignment operator 10927 // or a user-declared destructor. 10928 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10929 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10930 10931 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10932 DiagnosticErrorTrap Trap(Diags); 10933 10934 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10935 Trap.hasErrorOccurred()) { 10936 Diag(CurrentLocation, diag::note_member_synthesized_at) 10937 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10938 CopyConstructor->setInvalidDecl(); 10939 } else { 10940 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10941 ? CopyConstructor->getLocEnd() 10942 : CopyConstructor->getLocation(); 10943 Sema::CompoundScopeRAII CompoundScope(*this); 10944 CopyConstructor->setBody( 10945 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10946 } 10947 10948 // The exception specification is needed because we are defining the 10949 // function. 10950 ResolveExceptionSpec(CurrentLocation, 10951 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10952 10953 CopyConstructor->markUsed(Context); 10954 MarkVTableUsed(CurrentLocation, ClassDecl); 10955 10956 if (ASTMutationListener *L = getASTMutationListener()) { 10957 L->CompletedImplicitDefinition(CopyConstructor); 10958 } 10959 } 10960 10961 Sema::ImplicitExceptionSpecification 10962 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10963 CXXRecordDecl *ClassDecl = MD->getParent(); 10964 10965 // C++ [except.spec]p14: 10966 // An implicitly declared special member function (Clause 12) shall have an 10967 // exception-specification. [...] 10968 ImplicitExceptionSpecification ExceptSpec(*this); 10969 if (ClassDecl->isInvalidDecl()) 10970 return ExceptSpec; 10971 10972 // Direct base-class constructors. 10973 for (const auto &B : ClassDecl->bases()) { 10974 if (B.isVirtual()) // Handled below. 10975 continue; 10976 10977 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10978 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10979 CXXConstructorDecl *Constructor = 10980 LookupMovingConstructor(BaseClassDecl, 0); 10981 // If this is a deleted function, add it anyway. This might be conformant 10982 // with the standard. This might not. I'm not sure. It might not matter. 10983 if (Constructor) 10984 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10985 } 10986 } 10987 10988 // Virtual base-class constructors. 10989 for (const auto &B : ClassDecl->vbases()) { 10990 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10991 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10992 CXXConstructorDecl *Constructor = 10993 LookupMovingConstructor(BaseClassDecl, 0); 10994 // If this is a deleted function, add it anyway. This might be conformant 10995 // with the standard. This might not. I'm not sure. It might not matter. 10996 if (Constructor) 10997 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10998 } 10999 } 11000 11001 // Field constructors. 11002 for (const auto *F : ClassDecl->fields()) { 11003 QualType FieldType = Context.getBaseElementType(F->getType()); 11004 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 11005 CXXConstructorDecl *Constructor = 11006 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 11007 // If this is a deleted function, add it anyway. This might be conformant 11008 // with the standard. This might not. I'm not sure. It might not matter. 11009 // In particular, the problem is that this function never gets called. It 11010 // might just be ill-formed because this function attempts to refer to 11011 // a deleted function here. 11012 if (Constructor) 11013 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 11014 } 11015 } 11016 11017 return ExceptSpec; 11018 } 11019 11020 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 11021 CXXRecordDecl *ClassDecl) { 11022 assert(ClassDecl->needsImplicitMoveConstructor()); 11023 11024 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 11025 if (DSM.isAlreadyBeingDeclared()) 11026 return nullptr; 11027 11028 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11029 QualType ArgType = Context.getRValueReferenceType(ClassType); 11030 11031 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11032 CXXMoveConstructor, 11033 false); 11034 11035 DeclarationName Name 11036 = Context.DeclarationNames.getCXXConstructorName( 11037 Context.getCanonicalType(ClassType)); 11038 SourceLocation ClassLoc = ClassDecl->getLocation(); 11039 DeclarationNameInfo NameInfo(Name, ClassLoc); 11040 11041 // C++11 [class.copy]p11: 11042 // An implicitly-declared copy/move constructor is an inline public 11043 // member of its class. 11044 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 11045 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11046 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11047 Constexpr); 11048 MoveConstructor->setAccess(AS_public); 11049 MoveConstructor->setDefaulted(); 11050 11051 if (getLangOpts().CUDA) { 11052 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 11053 MoveConstructor, 11054 /* ConstRHS */ false, 11055 /* Diagnose */ false); 11056 } 11057 11058 // Build an exception specification pointing back at this member. 11059 FunctionProtoType::ExtProtoInfo EPI = 11060 getImplicitMethodEPI(*this, MoveConstructor); 11061 MoveConstructor->setType( 11062 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11063 11064 // Add the parameter to the constructor. 11065 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 11066 ClassLoc, ClassLoc, 11067 /*IdentifierInfo=*/nullptr, 11068 ArgType, /*TInfo=*/nullptr, 11069 SC_None, nullptr); 11070 MoveConstructor->setParams(FromParam); 11071 11072 MoveConstructor->setTrivial( 11073 ClassDecl->needsOverloadResolutionForMoveConstructor() 11074 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 11075 : ClassDecl->hasTrivialMoveConstructor()); 11076 11077 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 11078 ClassDecl->setImplicitMoveConstructorIsDeleted(); 11079 SetDeclDeleted(MoveConstructor, ClassLoc); 11080 } 11081 11082 // Note that we have declared this constructor. 11083 ++ASTContext::NumImplicitMoveConstructorsDeclared; 11084 11085 if (Scope *S = getScopeForContext(ClassDecl)) 11086 PushOnScopeChains(MoveConstructor, S, false); 11087 ClassDecl->addDecl(MoveConstructor); 11088 11089 return MoveConstructor; 11090 } 11091 11092 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 11093 CXXConstructorDecl *MoveConstructor) { 11094 assert((MoveConstructor->isDefaulted() && 11095 MoveConstructor->isMoveConstructor() && 11096 !MoveConstructor->doesThisDeclarationHaveABody() && 11097 !MoveConstructor->isDeleted()) && 11098 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 11099 11100 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 11101 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 11102 11103 SynthesizedFunctionScope Scope(*this, MoveConstructor); 11104 DiagnosticErrorTrap Trap(Diags); 11105 11106 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 11107 Trap.hasErrorOccurred()) { 11108 Diag(CurrentLocation, diag::note_member_synthesized_at) 11109 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 11110 MoveConstructor->setInvalidDecl(); 11111 } else { 11112 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 11113 ? MoveConstructor->getLocEnd() 11114 : MoveConstructor->getLocation(); 11115 Sema::CompoundScopeRAII CompoundScope(*this); 11116 MoveConstructor->setBody(ActOnCompoundStmt( 11117 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 11118 } 11119 11120 // The exception specification is needed because we are defining the 11121 // function. 11122 ResolveExceptionSpec(CurrentLocation, 11123 MoveConstructor->getType()->castAs<FunctionProtoType>()); 11124 11125 MoveConstructor->markUsed(Context); 11126 MarkVTableUsed(CurrentLocation, ClassDecl); 11127 11128 if (ASTMutationListener *L = getASTMutationListener()) { 11129 L->CompletedImplicitDefinition(MoveConstructor); 11130 } 11131 } 11132 11133 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 11134 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 11135 } 11136 11137 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 11138 SourceLocation CurrentLocation, 11139 CXXConversionDecl *Conv) { 11140 CXXRecordDecl *Lambda = Conv->getParent(); 11141 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 11142 // If we are defining a specialization of a conversion to function-ptr 11143 // cache the deduced template arguments for this specialization 11144 // so that we can use them to retrieve the corresponding call-operator 11145 // and static-invoker. 11146 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 11147 11148 // Retrieve the corresponding call-operator specialization. 11149 if (Lambda->isGenericLambda()) { 11150 assert(Conv->isFunctionTemplateSpecialization()); 11151 FunctionTemplateDecl *CallOpTemplate = 11152 CallOp->getDescribedFunctionTemplate(); 11153 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 11154 void *InsertPos = nullptr; 11155 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 11156 DeducedTemplateArgs->asArray(), 11157 InsertPos); 11158 assert(CallOpSpec && 11159 "Conversion operator must have a corresponding call operator"); 11160 CallOp = cast<CXXMethodDecl>(CallOpSpec); 11161 } 11162 // Mark the call operator referenced (and add to pending instantiations 11163 // if necessary). 11164 // For both the conversion and static-invoker template specializations 11165 // we construct their body's in this function, so no need to add them 11166 // to the PendingInstantiations. 11167 MarkFunctionReferenced(CurrentLocation, CallOp); 11168 11169 SynthesizedFunctionScope Scope(*this, Conv); 11170 DiagnosticErrorTrap Trap(Diags); 11171 11172 // Retrieve the static invoker... 11173 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 11174 // ... and get the corresponding specialization for a generic lambda. 11175 if (Lambda->isGenericLambda()) { 11176 assert(DeducedTemplateArgs && 11177 "Must have deduced template arguments from Conversion Operator"); 11178 FunctionTemplateDecl *InvokeTemplate = 11179 Invoker->getDescribedFunctionTemplate(); 11180 void *InsertPos = nullptr; 11181 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 11182 DeducedTemplateArgs->asArray(), 11183 InsertPos); 11184 assert(InvokeSpec && 11185 "Must have a corresponding static invoker specialization"); 11186 Invoker = cast<CXXMethodDecl>(InvokeSpec); 11187 } 11188 // Construct the body of the conversion function { return __invoke; }. 11189 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 11190 VK_LValue, Conv->getLocation()).get(); 11191 assert(FunctionRef && "Can't refer to __invoke function?"); 11192 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 11193 Conv->setBody(new (Context) CompoundStmt(Context, Return, 11194 Conv->getLocation(), 11195 Conv->getLocation())); 11196 11197 Conv->markUsed(Context); 11198 Conv->setReferenced(); 11199 11200 // Fill in the __invoke function with a dummy implementation. IR generation 11201 // will fill in the actual details. 11202 Invoker->markUsed(Context); 11203 Invoker->setReferenced(); 11204 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 11205 11206 if (ASTMutationListener *L = getASTMutationListener()) { 11207 L->CompletedImplicitDefinition(Conv); 11208 L->CompletedImplicitDefinition(Invoker); 11209 } 11210 } 11211 11212 11213 11214 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11215 SourceLocation CurrentLocation, 11216 CXXConversionDecl *Conv) 11217 { 11218 assert(!Conv->getParent()->isGenericLambda()); 11219 11220 Conv->markUsed(Context); 11221 11222 SynthesizedFunctionScope Scope(*this, Conv); 11223 DiagnosticErrorTrap Trap(Diags); 11224 11225 // Copy-initialize the lambda object as needed to capture it. 11226 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11227 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11228 11229 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11230 Conv->getLocation(), 11231 Conv, DerefThis); 11232 11233 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11234 // behavior. Note that only the general conversion function does this 11235 // (since it's unusable otherwise); in the case where we inline the 11236 // block literal, it has block literal lifetime semantics. 11237 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11238 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11239 CK_CopyAndAutoreleaseBlockObject, 11240 BuildBlock.get(), nullptr, VK_RValue); 11241 11242 if (BuildBlock.isInvalid()) { 11243 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11244 Conv->setInvalidDecl(); 11245 return; 11246 } 11247 11248 // Create the return statement that returns the block from the conversion 11249 // function. 11250 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11251 if (Return.isInvalid()) { 11252 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11253 Conv->setInvalidDecl(); 11254 return; 11255 } 11256 11257 // Set the body of the conversion function. 11258 Stmt *ReturnS = Return.get(); 11259 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11260 Conv->getLocation(), 11261 Conv->getLocation())); 11262 11263 // We're done; notify the mutation listener, if any. 11264 if (ASTMutationListener *L = getASTMutationListener()) { 11265 L->CompletedImplicitDefinition(Conv); 11266 } 11267 } 11268 11269 /// \brief Determine whether the given list arguments contains exactly one 11270 /// "real" (non-default) argument. 11271 static bool hasOneRealArgument(MultiExprArg Args) { 11272 switch (Args.size()) { 11273 case 0: 11274 return false; 11275 11276 default: 11277 if (!Args[1]->isDefaultArgument()) 11278 return false; 11279 11280 // fall through 11281 case 1: 11282 return !Args[0]->isDefaultArgument(); 11283 } 11284 11285 return false; 11286 } 11287 11288 ExprResult 11289 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11290 CXXConstructorDecl *Constructor, 11291 MultiExprArg ExprArgs, 11292 bool HadMultipleCandidates, 11293 bool IsListInitialization, 11294 bool IsStdInitListInitialization, 11295 bool RequiresZeroInit, 11296 unsigned ConstructKind, 11297 SourceRange ParenRange) { 11298 bool Elidable = false; 11299 11300 // C++0x [class.copy]p34: 11301 // When certain criteria are met, an implementation is allowed to 11302 // omit the copy/move construction of a class object, even if the 11303 // copy/move constructor and/or destructor for the object have 11304 // side effects. [...] 11305 // - when a temporary class object that has not been bound to a 11306 // reference (12.2) would be copied/moved to a class object 11307 // with the same cv-unqualified type, the copy/move operation 11308 // can be omitted by constructing the temporary object 11309 // directly into the target of the omitted copy/move 11310 if (ConstructKind == CXXConstructExpr::CK_Complete && 11311 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11312 Expr *SubExpr = ExprArgs[0]; 11313 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11314 } 11315 11316 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11317 Elidable, ExprArgs, HadMultipleCandidates, 11318 IsListInitialization, 11319 IsStdInitListInitialization, RequiresZeroInit, 11320 ConstructKind, ParenRange); 11321 } 11322 11323 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11324 /// including handling of its default argument expressions. 11325 ExprResult 11326 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11327 CXXConstructorDecl *Constructor, bool Elidable, 11328 MultiExprArg ExprArgs, 11329 bool HadMultipleCandidates, 11330 bool IsListInitialization, 11331 bool IsStdInitListInitialization, 11332 bool RequiresZeroInit, 11333 unsigned ConstructKind, 11334 SourceRange ParenRange) { 11335 MarkFunctionReferenced(ConstructLoc, Constructor); 11336 return CXXConstructExpr::Create( 11337 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11338 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11339 RequiresZeroInit, 11340 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11341 ParenRange); 11342 } 11343 11344 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11345 assert(Field->hasInClassInitializer()); 11346 11347 // If we already have the in-class initializer nothing needs to be done. 11348 if (Field->getInClassInitializer()) 11349 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11350 11351 // Maybe we haven't instantiated the in-class initializer. Go check the 11352 // pattern FieldDecl to see if it has one. 11353 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11354 11355 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11356 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11357 DeclContext::lookup_result Lookup = 11358 ClassPattern->lookup(Field->getDeclName()); 11359 assert(Lookup.size() == 1); 11360 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11361 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11362 getTemplateInstantiationArgs(Field))) 11363 return ExprError(); 11364 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11365 } 11366 11367 // DR1351: 11368 // If the brace-or-equal-initializer of a non-static data member 11369 // invokes a defaulted default constructor of its class or of an 11370 // enclosing class in a potentially evaluated subexpression, the 11371 // program is ill-formed. 11372 // 11373 // This resolution is unworkable: the exception specification of the 11374 // default constructor can be needed in an unevaluated context, in 11375 // particular, in the operand of a noexcept-expression, and we can be 11376 // unable to compute an exception specification for an enclosed class. 11377 // 11378 // Any attempt to resolve the exception specification of a defaulted default 11379 // constructor before the initializer is lexically complete will ultimately 11380 // come here at which point we can diagnose it. 11381 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11382 if (OutermostClass == ParentRD) { 11383 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11384 << ParentRD << Field; 11385 } else { 11386 Diag(Field->getLocEnd(), 11387 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11388 << ParentRD << OutermostClass << Field; 11389 } 11390 11391 return ExprError(); 11392 } 11393 11394 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11395 if (VD->isInvalidDecl()) return; 11396 11397 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11398 if (ClassDecl->isInvalidDecl()) return; 11399 if (ClassDecl->hasIrrelevantDestructor()) return; 11400 if (ClassDecl->isDependentContext()) return; 11401 11402 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11403 MarkFunctionReferenced(VD->getLocation(), Destructor); 11404 CheckDestructorAccess(VD->getLocation(), Destructor, 11405 PDiag(diag::err_access_dtor_var) 11406 << VD->getDeclName() 11407 << VD->getType()); 11408 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11409 11410 if (Destructor->isTrivial()) return; 11411 if (!VD->hasGlobalStorage()) return; 11412 11413 // Emit warning for non-trivial dtor in global scope (a real global, 11414 // class-static, function-static). 11415 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11416 11417 // TODO: this should be re-enabled for static locals by !CXAAtExit 11418 if (!VD->isStaticLocal()) 11419 Diag(VD->getLocation(), diag::warn_global_destructor); 11420 } 11421 11422 /// \brief Given a constructor and the set of arguments provided for the 11423 /// constructor, convert the arguments and add any required default arguments 11424 /// to form a proper call to this constructor. 11425 /// 11426 /// \returns true if an error occurred, false otherwise. 11427 bool 11428 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11429 MultiExprArg ArgsPtr, 11430 SourceLocation Loc, 11431 SmallVectorImpl<Expr*> &ConvertedArgs, 11432 bool AllowExplicit, 11433 bool IsListInitialization) { 11434 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11435 unsigned NumArgs = ArgsPtr.size(); 11436 Expr **Args = ArgsPtr.data(); 11437 11438 const FunctionProtoType *Proto 11439 = Constructor->getType()->getAs<FunctionProtoType>(); 11440 assert(Proto && "Constructor without a prototype?"); 11441 unsigned NumParams = Proto->getNumParams(); 11442 11443 // If too few arguments are available, we'll fill in the rest with defaults. 11444 if (NumArgs < NumParams) 11445 ConvertedArgs.reserve(NumParams); 11446 else 11447 ConvertedArgs.reserve(NumArgs); 11448 11449 VariadicCallType CallType = 11450 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11451 SmallVector<Expr *, 8> AllArgs; 11452 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11453 Proto, 0, 11454 llvm::makeArrayRef(Args, NumArgs), 11455 AllArgs, 11456 CallType, AllowExplicit, 11457 IsListInitialization); 11458 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11459 11460 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11461 11462 CheckConstructorCall(Constructor, 11463 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11464 Proto, Loc); 11465 11466 return Invalid; 11467 } 11468 11469 static inline bool 11470 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11471 const FunctionDecl *FnDecl) { 11472 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11473 if (isa<NamespaceDecl>(DC)) { 11474 return SemaRef.Diag(FnDecl->getLocation(), 11475 diag::err_operator_new_delete_declared_in_namespace) 11476 << FnDecl->getDeclName(); 11477 } 11478 11479 if (isa<TranslationUnitDecl>(DC) && 11480 FnDecl->getStorageClass() == SC_Static) { 11481 return SemaRef.Diag(FnDecl->getLocation(), 11482 diag::err_operator_new_delete_declared_static) 11483 << FnDecl->getDeclName(); 11484 } 11485 11486 return false; 11487 } 11488 11489 static inline bool 11490 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11491 CanQualType ExpectedResultType, 11492 CanQualType ExpectedFirstParamType, 11493 unsigned DependentParamTypeDiag, 11494 unsigned InvalidParamTypeDiag) { 11495 QualType ResultType = 11496 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11497 11498 // Check that the result type is not dependent. 11499 if (ResultType->isDependentType()) 11500 return SemaRef.Diag(FnDecl->getLocation(), 11501 diag::err_operator_new_delete_dependent_result_type) 11502 << FnDecl->getDeclName() << ExpectedResultType; 11503 11504 // Check that the result type is what we expect. 11505 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11506 return SemaRef.Diag(FnDecl->getLocation(), 11507 diag::err_operator_new_delete_invalid_result_type) 11508 << FnDecl->getDeclName() << ExpectedResultType; 11509 11510 // A function template must have at least 2 parameters. 11511 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11512 return SemaRef.Diag(FnDecl->getLocation(), 11513 diag::err_operator_new_delete_template_too_few_parameters) 11514 << FnDecl->getDeclName(); 11515 11516 // The function decl must have at least 1 parameter. 11517 if (FnDecl->getNumParams() == 0) 11518 return SemaRef.Diag(FnDecl->getLocation(), 11519 diag::err_operator_new_delete_too_few_parameters) 11520 << FnDecl->getDeclName(); 11521 11522 // Check the first parameter type is not dependent. 11523 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11524 if (FirstParamType->isDependentType()) 11525 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11526 << FnDecl->getDeclName() << ExpectedFirstParamType; 11527 11528 // Check that the first parameter type is what we expect. 11529 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11530 ExpectedFirstParamType) 11531 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11532 << FnDecl->getDeclName() << ExpectedFirstParamType; 11533 11534 return false; 11535 } 11536 11537 static bool 11538 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11539 // C++ [basic.stc.dynamic.allocation]p1: 11540 // A program is ill-formed if an allocation function is declared in a 11541 // namespace scope other than global scope or declared static in global 11542 // scope. 11543 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11544 return true; 11545 11546 CanQualType SizeTy = 11547 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11548 11549 // C++ [basic.stc.dynamic.allocation]p1: 11550 // The return type shall be void*. The first parameter shall have type 11551 // std::size_t. 11552 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11553 SizeTy, 11554 diag::err_operator_new_dependent_param_type, 11555 diag::err_operator_new_param_type)) 11556 return true; 11557 11558 // C++ [basic.stc.dynamic.allocation]p1: 11559 // The first parameter shall not have an associated default argument. 11560 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11561 return SemaRef.Diag(FnDecl->getLocation(), 11562 diag::err_operator_new_default_arg) 11563 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11564 11565 return false; 11566 } 11567 11568 static bool 11569 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11570 // C++ [basic.stc.dynamic.deallocation]p1: 11571 // A program is ill-formed if deallocation functions are declared in a 11572 // namespace scope other than global scope or declared static in global 11573 // scope. 11574 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11575 return true; 11576 11577 // C++ [basic.stc.dynamic.deallocation]p2: 11578 // Each deallocation function shall return void and its first parameter 11579 // shall be void*. 11580 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11581 SemaRef.Context.VoidPtrTy, 11582 diag::err_operator_delete_dependent_param_type, 11583 diag::err_operator_delete_param_type)) 11584 return true; 11585 11586 return false; 11587 } 11588 11589 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11590 /// of this overloaded operator is well-formed. If so, returns false; 11591 /// otherwise, emits appropriate diagnostics and returns true. 11592 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11593 assert(FnDecl && FnDecl->isOverloadedOperator() && 11594 "Expected an overloaded operator declaration"); 11595 11596 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11597 11598 // C++ [over.oper]p5: 11599 // The allocation and deallocation functions, operator new, 11600 // operator new[], operator delete and operator delete[], are 11601 // described completely in 3.7.3. The attributes and restrictions 11602 // found in the rest of this subclause do not apply to them unless 11603 // explicitly stated in 3.7.3. 11604 if (Op == OO_Delete || Op == OO_Array_Delete) 11605 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11606 11607 if (Op == OO_New || Op == OO_Array_New) 11608 return CheckOperatorNewDeclaration(*this, FnDecl); 11609 11610 // C++ [over.oper]p6: 11611 // An operator function shall either be a non-static member 11612 // function or be a non-member function and have at least one 11613 // parameter whose type is a class, a reference to a class, an 11614 // enumeration, or a reference to an enumeration. 11615 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11616 if (MethodDecl->isStatic()) 11617 return Diag(FnDecl->getLocation(), 11618 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11619 } else { 11620 bool ClassOrEnumParam = false; 11621 for (auto Param : FnDecl->params()) { 11622 QualType ParamType = Param->getType().getNonReferenceType(); 11623 if (ParamType->isDependentType() || ParamType->isRecordType() || 11624 ParamType->isEnumeralType()) { 11625 ClassOrEnumParam = true; 11626 break; 11627 } 11628 } 11629 11630 if (!ClassOrEnumParam) 11631 return Diag(FnDecl->getLocation(), 11632 diag::err_operator_overload_needs_class_or_enum) 11633 << FnDecl->getDeclName(); 11634 } 11635 11636 // C++ [over.oper]p8: 11637 // An operator function cannot have default arguments (8.3.6), 11638 // except where explicitly stated below. 11639 // 11640 // Only the function-call operator allows default arguments 11641 // (C++ [over.call]p1). 11642 if (Op != OO_Call) { 11643 for (auto Param : FnDecl->params()) { 11644 if (Param->hasDefaultArg()) 11645 return Diag(Param->getLocation(), 11646 diag::err_operator_overload_default_arg) 11647 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11648 } 11649 } 11650 11651 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11652 { false, false, false } 11653 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11654 , { Unary, Binary, MemberOnly } 11655 #include "clang/Basic/OperatorKinds.def" 11656 }; 11657 11658 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11659 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11660 bool MustBeMemberOperator = OperatorUses[Op][2]; 11661 11662 // C++ [over.oper]p8: 11663 // [...] Operator functions cannot have more or fewer parameters 11664 // than the number required for the corresponding operator, as 11665 // described in the rest of this subclause. 11666 unsigned NumParams = FnDecl->getNumParams() 11667 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11668 if (Op != OO_Call && 11669 ((NumParams == 1 && !CanBeUnaryOperator) || 11670 (NumParams == 2 && !CanBeBinaryOperator) || 11671 (NumParams < 1) || (NumParams > 2))) { 11672 // We have the wrong number of parameters. 11673 unsigned ErrorKind; 11674 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11675 ErrorKind = 2; // 2 -> unary or binary. 11676 } else if (CanBeUnaryOperator) { 11677 ErrorKind = 0; // 0 -> unary 11678 } else { 11679 assert(CanBeBinaryOperator && 11680 "All non-call overloaded operators are unary or binary!"); 11681 ErrorKind = 1; // 1 -> binary 11682 } 11683 11684 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11685 << FnDecl->getDeclName() << NumParams << ErrorKind; 11686 } 11687 11688 // Overloaded operators other than operator() cannot be variadic. 11689 if (Op != OO_Call && 11690 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11691 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11692 << FnDecl->getDeclName(); 11693 } 11694 11695 // Some operators must be non-static member functions. 11696 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11697 return Diag(FnDecl->getLocation(), 11698 diag::err_operator_overload_must_be_member) 11699 << FnDecl->getDeclName(); 11700 } 11701 11702 // C++ [over.inc]p1: 11703 // The user-defined function called operator++ implements the 11704 // prefix and postfix ++ operator. If this function is a member 11705 // function with no parameters, or a non-member function with one 11706 // parameter of class or enumeration type, it defines the prefix 11707 // increment operator ++ for objects of that type. If the function 11708 // is a member function with one parameter (which shall be of type 11709 // int) or a non-member function with two parameters (the second 11710 // of which shall be of type int), it defines the postfix 11711 // increment operator ++ for objects of that type. 11712 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11713 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11714 QualType ParamType = LastParam->getType(); 11715 11716 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11717 !ParamType->isDependentType()) 11718 return Diag(LastParam->getLocation(), 11719 diag::err_operator_overload_post_incdec_must_be_int) 11720 << LastParam->getType() << (Op == OO_MinusMinus); 11721 } 11722 11723 return false; 11724 } 11725 11726 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11727 /// of this literal operator function is well-formed. If so, returns 11728 /// false; otherwise, emits appropriate diagnostics and returns true. 11729 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11730 if (isa<CXXMethodDecl>(FnDecl)) { 11731 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11732 << FnDecl->getDeclName(); 11733 return true; 11734 } 11735 11736 if (FnDecl->isExternC()) { 11737 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11738 return true; 11739 } 11740 11741 bool Valid = false; 11742 11743 // This might be the definition of a literal operator template. 11744 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11745 // This might be a specialization of a literal operator template. 11746 if (!TpDecl) 11747 TpDecl = FnDecl->getPrimaryTemplate(); 11748 11749 // template <char...> type operator "" name() and 11750 // template <class T, T...> type operator "" name() are the only valid 11751 // template signatures, and the only valid signatures with no parameters. 11752 if (TpDecl) { 11753 if (FnDecl->param_size() == 0) { 11754 // Must have one or two template parameters 11755 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11756 if (Params->size() == 1) { 11757 NonTypeTemplateParmDecl *PmDecl = 11758 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11759 11760 // The template parameter must be a char parameter pack. 11761 if (PmDecl && PmDecl->isTemplateParameterPack() && 11762 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11763 Valid = true; 11764 } else if (Params->size() == 2) { 11765 TemplateTypeParmDecl *PmType = 11766 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11767 NonTypeTemplateParmDecl *PmArgs = 11768 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11769 11770 // The second template parameter must be a parameter pack with the 11771 // first template parameter as its type. 11772 if (PmType && PmArgs && 11773 !PmType->isTemplateParameterPack() && 11774 PmArgs->isTemplateParameterPack()) { 11775 const TemplateTypeParmType *TArgs = 11776 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11777 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11778 TArgs->getIndex() == PmType->getIndex()) { 11779 Valid = true; 11780 if (ActiveTemplateInstantiations.empty()) 11781 Diag(FnDecl->getLocation(), 11782 diag::ext_string_literal_operator_template); 11783 } 11784 } 11785 } 11786 } 11787 } else if (FnDecl->param_size()) { 11788 // Check the first parameter 11789 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11790 11791 QualType T = (*Param)->getType().getUnqualifiedType(); 11792 11793 // unsigned long long int, long double, and any character type are allowed 11794 // as the only parameters. 11795 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11796 Context.hasSameType(T, Context.LongDoubleTy) || 11797 Context.hasSameType(T, Context.CharTy) || 11798 Context.hasSameType(T, Context.WideCharTy) || 11799 Context.hasSameType(T, Context.Char16Ty) || 11800 Context.hasSameType(T, Context.Char32Ty)) { 11801 if (++Param == FnDecl->param_end()) 11802 Valid = true; 11803 goto FinishedParams; 11804 } 11805 11806 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11807 const PointerType *PT = T->getAs<PointerType>(); 11808 if (!PT) 11809 goto FinishedParams; 11810 T = PT->getPointeeType(); 11811 if (!T.isConstQualified() || T.isVolatileQualified()) 11812 goto FinishedParams; 11813 T = T.getUnqualifiedType(); 11814 11815 // Move on to the second parameter; 11816 ++Param; 11817 11818 // If there is no second parameter, the first must be a const char * 11819 if (Param == FnDecl->param_end()) { 11820 if (Context.hasSameType(T, Context.CharTy)) 11821 Valid = true; 11822 goto FinishedParams; 11823 } 11824 11825 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11826 // are allowed as the first parameter to a two-parameter function 11827 if (!(Context.hasSameType(T, Context.CharTy) || 11828 Context.hasSameType(T, Context.WideCharTy) || 11829 Context.hasSameType(T, Context.Char16Ty) || 11830 Context.hasSameType(T, Context.Char32Ty))) 11831 goto FinishedParams; 11832 11833 // The second and final parameter must be an std::size_t 11834 T = (*Param)->getType().getUnqualifiedType(); 11835 if (Context.hasSameType(T, Context.getSizeType()) && 11836 ++Param == FnDecl->param_end()) 11837 Valid = true; 11838 } 11839 11840 // FIXME: This diagnostic is absolutely terrible. 11841 FinishedParams: 11842 if (!Valid) { 11843 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11844 << FnDecl->getDeclName(); 11845 return true; 11846 } 11847 11848 // A parameter-declaration-clause containing a default argument is not 11849 // equivalent to any of the permitted forms. 11850 for (auto Param : FnDecl->params()) { 11851 if (Param->hasDefaultArg()) { 11852 Diag(Param->getDefaultArgRange().getBegin(), 11853 diag::err_literal_operator_default_argument) 11854 << Param->getDefaultArgRange(); 11855 break; 11856 } 11857 } 11858 11859 StringRef LiteralName 11860 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11861 if (LiteralName[0] != '_') { 11862 // C++11 [usrlit.suffix]p1: 11863 // Literal suffix identifiers that do not start with an underscore 11864 // are reserved for future standardization. 11865 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11866 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11867 } 11868 11869 return false; 11870 } 11871 11872 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11873 /// linkage specification, including the language and (if present) 11874 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11875 /// language string literal. LBraceLoc, if valid, provides the location of 11876 /// the '{' brace. Otherwise, this linkage specification does not 11877 /// have any braces. 11878 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11879 Expr *LangStr, 11880 SourceLocation LBraceLoc) { 11881 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11882 if (!Lit->isAscii()) { 11883 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11884 << LangStr->getSourceRange(); 11885 return nullptr; 11886 } 11887 11888 StringRef Lang = Lit->getString(); 11889 LinkageSpecDecl::LanguageIDs Language; 11890 if (Lang == "C") 11891 Language = LinkageSpecDecl::lang_c; 11892 else if (Lang == "C++") 11893 Language = LinkageSpecDecl::lang_cxx; 11894 else { 11895 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11896 << LangStr->getSourceRange(); 11897 return nullptr; 11898 } 11899 11900 // FIXME: Add all the various semantics of linkage specifications 11901 11902 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11903 LangStr->getExprLoc(), Language, 11904 LBraceLoc.isValid()); 11905 CurContext->addDecl(D); 11906 PushDeclContext(S, D); 11907 return D; 11908 } 11909 11910 /// ActOnFinishLinkageSpecification - Complete the definition of 11911 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11912 /// valid, it's the position of the closing '}' brace in a linkage 11913 /// specification that uses braces. 11914 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11915 Decl *LinkageSpec, 11916 SourceLocation RBraceLoc) { 11917 if (RBraceLoc.isValid()) { 11918 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11919 LSDecl->setRBraceLoc(RBraceLoc); 11920 } 11921 PopDeclContext(); 11922 return LinkageSpec; 11923 } 11924 11925 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11926 AttributeList *AttrList, 11927 SourceLocation SemiLoc) { 11928 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11929 // Attribute declarations appertain to empty declaration so we handle 11930 // them here. 11931 if (AttrList) 11932 ProcessDeclAttributeList(S, ED, AttrList); 11933 11934 CurContext->addDecl(ED); 11935 return ED; 11936 } 11937 11938 /// \brief Perform semantic analysis for the variable declaration that 11939 /// occurs within a C++ catch clause, returning the newly-created 11940 /// variable. 11941 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11942 TypeSourceInfo *TInfo, 11943 SourceLocation StartLoc, 11944 SourceLocation Loc, 11945 IdentifierInfo *Name) { 11946 bool Invalid = false; 11947 QualType ExDeclType = TInfo->getType(); 11948 11949 // Arrays and functions decay. 11950 if (ExDeclType->isArrayType()) 11951 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11952 else if (ExDeclType->isFunctionType()) 11953 ExDeclType = Context.getPointerType(ExDeclType); 11954 11955 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11956 // The exception-declaration shall not denote a pointer or reference to an 11957 // incomplete type, other than [cv] void*. 11958 // N2844 forbids rvalue references. 11959 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11960 Diag(Loc, diag::err_catch_rvalue_ref); 11961 Invalid = true; 11962 } 11963 11964 QualType BaseType = ExDeclType; 11965 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11966 unsigned DK = diag::err_catch_incomplete; 11967 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11968 BaseType = Ptr->getPointeeType(); 11969 Mode = 1; 11970 DK = diag::err_catch_incomplete_ptr; 11971 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11972 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11973 BaseType = Ref->getPointeeType(); 11974 Mode = 2; 11975 DK = diag::err_catch_incomplete_ref; 11976 } 11977 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11978 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11979 Invalid = true; 11980 11981 if (!Invalid && !ExDeclType->isDependentType() && 11982 RequireNonAbstractType(Loc, ExDeclType, 11983 diag::err_abstract_type_in_decl, 11984 AbstractVariableType)) 11985 Invalid = true; 11986 11987 // Only the non-fragile NeXT runtime currently supports C++ catches 11988 // of ObjC types, and no runtime supports catching ObjC types by value. 11989 if (!Invalid && getLangOpts().ObjC1) { 11990 QualType T = ExDeclType; 11991 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11992 T = RT->getPointeeType(); 11993 11994 if (T->isObjCObjectType()) { 11995 Diag(Loc, diag::err_objc_object_catch); 11996 Invalid = true; 11997 } else if (T->isObjCObjectPointerType()) { 11998 // FIXME: should this be a test for macosx-fragile specifically? 11999 if (getLangOpts().ObjCRuntime.isFragile()) 12000 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 12001 } 12002 } 12003 12004 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 12005 ExDeclType, TInfo, SC_None); 12006 ExDecl->setExceptionVariable(true); 12007 12008 // In ARC, infer 'retaining' for variables of retainable type. 12009 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 12010 Invalid = true; 12011 12012 if (!Invalid && !ExDeclType->isDependentType()) { 12013 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 12014 // Insulate this from anything else we might currently be parsing. 12015 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 12016 12017 // C++ [except.handle]p16: 12018 // The object declared in an exception-declaration or, if the 12019 // exception-declaration does not specify a name, a temporary (12.2) is 12020 // copy-initialized (8.5) from the exception object. [...] 12021 // The object is destroyed when the handler exits, after the destruction 12022 // of any automatic objects initialized within the handler. 12023 // 12024 // We just pretend to initialize the object with itself, then make sure 12025 // it can be destroyed later. 12026 QualType initType = Context.getExceptionObjectType(ExDeclType); 12027 12028 InitializedEntity entity = 12029 InitializedEntity::InitializeVariable(ExDecl); 12030 InitializationKind initKind = 12031 InitializationKind::CreateCopy(Loc, SourceLocation()); 12032 12033 Expr *opaqueValue = 12034 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 12035 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 12036 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 12037 if (result.isInvalid()) 12038 Invalid = true; 12039 else { 12040 // If the constructor used was non-trivial, set this as the 12041 // "initializer". 12042 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 12043 if (!construct->getConstructor()->isTrivial()) { 12044 Expr *init = MaybeCreateExprWithCleanups(construct); 12045 ExDecl->setInit(init); 12046 } 12047 12048 // And make sure it's destructable. 12049 FinalizeVarWithDestructor(ExDecl, recordType); 12050 } 12051 } 12052 } 12053 12054 if (Invalid) 12055 ExDecl->setInvalidDecl(); 12056 12057 return ExDecl; 12058 } 12059 12060 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 12061 /// handler. 12062 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 12063 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12064 bool Invalid = D.isInvalidType(); 12065 12066 // Check for unexpanded parameter packs. 12067 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12068 UPPC_ExceptionType)) { 12069 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12070 D.getIdentifierLoc()); 12071 Invalid = true; 12072 } 12073 12074 IdentifierInfo *II = D.getIdentifier(); 12075 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 12076 LookupOrdinaryName, 12077 ForRedeclaration)) { 12078 // The scope should be freshly made just for us. There is just no way 12079 // it contains any previous declaration, except for function parameters in 12080 // a function-try-block's catch statement. 12081 assert(!S->isDeclScope(PrevDecl)); 12082 if (isDeclInScope(PrevDecl, CurContext, S)) { 12083 Diag(D.getIdentifierLoc(), diag::err_redefinition) 12084 << D.getIdentifier(); 12085 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12086 Invalid = true; 12087 } else if (PrevDecl->isTemplateParameter()) 12088 // Maybe we will complain about the shadowed template parameter. 12089 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12090 } 12091 12092 if (D.getCXXScopeSpec().isSet() && !Invalid) { 12093 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 12094 << D.getCXXScopeSpec().getRange(); 12095 Invalid = true; 12096 } 12097 12098 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 12099 D.getLocStart(), 12100 D.getIdentifierLoc(), 12101 D.getIdentifier()); 12102 if (Invalid) 12103 ExDecl->setInvalidDecl(); 12104 12105 // Add the exception declaration into this scope. 12106 if (II) 12107 PushOnScopeChains(ExDecl, S); 12108 else 12109 CurContext->addDecl(ExDecl); 12110 12111 ProcessDeclAttributes(S, ExDecl, D); 12112 return ExDecl; 12113 } 12114 12115 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12116 Expr *AssertExpr, 12117 Expr *AssertMessageExpr, 12118 SourceLocation RParenLoc) { 12119 StringLiteral *AssertMessage = 12120 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 12121 12122 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 12123 return nullptr; 12124 12125 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 12126 AssertMessage, RParenLoc, false); 12127 } 12128 12129 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12130 Expr *AssertExpr, 12131 StringLiteral *AssertMessage, 12132 SourceLocation RParenLoc, 12133 bool Failed) { 12134 assert(AssertExpr != nullptr && "Expected non-null condition"); 12135 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 12136 !Failed) { 12137 // In a static_assert-declaration, the constant-expression shall be a 12138 // constant expression that can be contextually converted to bool. 12139 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 12140 if (Converted.isInvalid()) 12141 Failed = true; 12142 12143 llvm::APSInt Cond; 12144 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 12145 diag::err_static_assert_expression_is_not_constant, 12146 /*AllowFold=*/false).isInvalid()) 12147 Failed = true; 12148 12149 if (!Failed && !Cond) { 12150 SmallString<256> MsgBuffer; 12151 llvm::raw_svector_ostream Msg(MsgBuffer); 12152 if (AssertMessage) 12153 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 12154 Diag(StaticAssertLoc, diag::err_static_assert_failed) 12155 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 12156 Failed = true; 12157 } 12158 } 12159 12160 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 12161 AssertExpr, AssertMessage, RParenLoc, 12162 Failed); 12163 12164 CurContext->addDecl(Decl); 12165 return Decl; 12166 } 12167 12168 /// \brief Perform semantic analysis of the given friend type declaration. 12169 /// 12170 /// \returns A friend declaration that. 12171 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 12172 SourceLocation FriendLoc, 12173 TypeSourceInfo *TSInfo) { 12174 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 12175 12176 QualType T = TSInfo->getType(); 12177 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 12178 12179 // C++03 [class.friend]p2: 12180 // An elaborated-type-specifier shall be used in a friend declaration 12181 // for a class.* 12182 // 12183 // * The class-key of the elaborated-type-specifier is required. 12184 if (!ActiveTemplateInstantiations.empty()) { 12185 // Do not complain about the form of friend template types during 12186 // template instantiation; we will already have complained when the 12187 // template was declared. 12188 } else { 12189 if (!T->isElaboratedTypeSpecifier()) { 12190 // If we evaluated the type to a record type, suggest putting 12191 // a tag in front. 12192 if (const RecordType *RT = T->getAs<RecordType>()) { 12193 RecordDecl *RD = RT->getDecl(); 12194 12195 SmallString<16> InsertionText(" "); 12196 InsertionText += RD->getKindName(); 12197 12198 Diag(TypeRange.getBegin(), 12199 getLangOpts().CPlusPlus11 ? 12200 diag::warn_cxx98_compat_unelaborated_friend_type : 12201 diag::ext_unelaborated_friend_type) 12202 << (unsigned) RD->getTagKind() 12203 << T 12204 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 12205 InsertionText); 12206 } else { 12207 Diag(FriendLoc, 12208 getLangOpts().CPlusPlus11 ? 12209 diag::warn_cxx98_compat_nonclass_type_friend : 12210 diag::ext_nonclass_type_friend) 12211 << T 12212 << TypeRange; 12213 } 12214 } else if (T->getAs<EnumType>()) { 12215 Diag(FriendLoc, 12216 getLangOpts().CPlusPlus11 ? 12217 diag::warn_cxx98_compat_enum_friend : 12218 diag::ext_enum_friend) 12219 << T 12220 << TypeRange; 12221 } 12222 12223 // C++11 [class.friend]p3: 12224 // A friend declaration that does not declare a function shall have one 12225 // of the following forms: 12226 // friend elaborated-type-specifier ; 12227 // friend simple-type-specifier ; 12228 // friend typename-specifier ; 12229 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12230 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12231 } 12232 12233 // If the type specifier in a friend declaration designates a (possibly 12234 // cv-qualified) class type, that class is declared as a friend; otherwise, 12235 // the friend declaration is ignored. 12236 return FriendDecl::Create(Context, CurContext, 12237 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12238 FriendLoc); 12239 } 12240 12241 /// Handle a friend tag declaration where the scope specifier was 12242 /// templated. 12243 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12244 unsigned TagSpec, SourceLocation TagLoc, 12245 CXXScopeSpec &SS, 12246 IdentifierInfo *Name, 12247 SourceLocation NameLoc, 12248 AttributeList *Attr, 12249 MultiTemplateParamsArg TempParamLists) { 12250 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12251 12252 bool isExplicitSpecialization = false; 12253 bool Invalid = false; 12254 12255 if (TemplateParameterList *TemplateParams = 12256 MatchTemplateParametersToScopeSpecifier( 12257 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12258 isExplicitSpecialization, Invalid)) { 12259 if (TemplateParams->size() > 0) { 12260 // This is a declaration of a class template. 12261 if (Invalid) 12262 return nullptr; 12263 12264 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12265 NameLoc, Attr, TemplateParams, AS_public, 12266 /*ModulePrivateLoc=*/SourceLocation(), 12267 FriendLoc, TempParamLists.size() - 1, 12268 TempParamLists.data()).get(); 12269 } else { 12270 // The "template<>" header is extraneous. 12271 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12272 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12273 isExplicitSpecialization = true; 12274 } 12275 } 12276 12277 if (Invalid) return nullptr; 12278 12279 bool isAllExplicitSpecializations = true; 12280 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12281 if (TempParamLists[I]->size()) { 12282 isAllExplicitSpecializations = false; 12283 break; 12284 } 12285 } 12286 12287 // FIXME: don't ignore attributes. 12288 12289 // If it's explicit specializations all the way down, just forget 12290 // about the template header and build an appropriate non-templated 12291 // friend. TODO: for source fidelity, remember the headers. 12292 if (isAllExplicitSpecializations) { 12293 if (SS.isEmpty()) { 12294 bool Owned = false; 12295 bool IsDependent = false; 12296 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12297 Attr, AS_public, 12298 /*ModulePrivateLoc=*/SourceLocation(), 12299 MultiTemplateParamsArg(), Owned, IsDependent, 12300 /*ScopedEnumKWLoc=*/SourceLocation(), 12301 /*ScopedEnumUsesClassTag=*/false, 12302 /*UnderlyingType=*/TypeResult(), 12303 /*IsTypeSpecifier=*/false); 12304 } 12305 12306 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12307 ElaboratedTypeKeyword Keyword 12308 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12309 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12310 *Name, NameLoc); 12311 if (T.isNull()) 12312 return nullptr; 12313 12314 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12315 if (isa<DependentNameType>(T)) { 12316 DependentNameTypeLoc TL = 12317 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12318 TL.setElaboratedKeywordLoc(TagLoc); 12319 TL.setQualifierLoc(QualifierLoc); 12320 TL.setNameLoc(NameLoc); 12321 } else { 12322 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12323 TL.setElaboratedKeywordLoc(TagLoc); 12324 TL.setQualifierLoc(QualifierLoc); 12325 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12326 } 12327 12328 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12329 TSI, FriendLoc, TempParamLists); 12330 Friend->setAccess(AS_public); 12331 CurContext->addDecl(Friend); 12332 return Friend; 12333 } 12334 12335 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12336 12337 12338 12339 // Handle the case of a templated-scope friend class. e.g. 12340 // template <class T> class A<T>::B; 12341 // FIXME: we don't support these right now. 12342 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12343 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12344 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12345 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12346 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12347 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12348 TL.setElaboratedKeywordLoc(TagLoc); 12349 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12350 TL.setNameLoc(NameLoc); 12351 12352 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12353 TSI, FriendLoc, TempParamLists); 12354 Friend->setAccess(AS_public); 12355 Friend->setUnsupportedFriend(true); 12356 CurContext->addDecl(Friend); 12357 return Friend; 12358 } 12359 12360 12361 /// Handle a friend type declaration. This works in tandem with 12362 /// ActOnTag. 12363 /// 12364 /// Notes on friend class templates: 12365 /// 12366 /// We generally treat friend class declarations as if they were 12367 /// declaring a class. So, for example, the elaborated type specifier 12368 /// in a friend declaration is required to obey the restrictions of a 12369 /// class-head (i.e. no typedefs in the scope chain), template 12370 /// parameters are required to match up with simple template-ids, &c. 12371 /// However, unlike when declaring a template specialization, it's 12372 /// okay to refer to a template specialization without an empty 12373 /// template parameter declaration, e.g. 12374 /// friend class A<T>::B<unsigned>; 12375 /// We permit this as a special case; if there are any template 12376 /// parameters present at all, require proper matching, i.e. 12377 /// template <> template \<class T> friend class A<int>::B; 12378 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12379 MultiTemplateParamsArg TempParams) { 12380 SourceLocation Loc = DS.getLocStart(); 12381 12382 assert(DS.isFriendSpecified()); 12383 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12384 12385 // Try to convert the decl specifier to a type. This works for 12386 // friend templates because ActOnTag never produces a ClassTemplateDecl 12387 // for a TUK_Friend. 12388 Declarator TheDeclarator(DS, Declarator::MemberContext); 12389 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12390 QualType T = TSI->getType(); 12391 if (TheDeclarator.isInvalidType()) 12392 return nullptr; 12393 12394 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12395 return nullptr; 12396 12397 // This is definitely an error in C++98. It's probably meant to 12398 // be forbidden in C++0x, too, but the specification is just 12399 // poorly written. 12400 // 12401 // The problem is with declarations like the following: 12402 // template <T> friend A<T>::foo; 12403 // where deciding whether a class C is a friend or not now hinges 12404 // on whether there exists an instantiation of A that causes 12405 // 'foo' to equal C. There are restrictions on class-heads 12406 // (which we declare (by fiat) elaborated friend declarations to 12407 // be) that makes this tractable. 12408 // 12409 // FIXME: handle "template <> friend class A<T>;", which 12410 // is possibly well-formed? Who even knows? 12411 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12412 Diag(Loc, diag::err_tagless_friend_type_template) 12413 << DS.getSourceRange(); 12414 return nullptr; 12415 } 12416 12417 // C++98 [class.friend]p1: A friend of a class is a function 12418 // or class that is not a member of the class . . . 12419 // This is fixed in DR77, which just barely didn't make the C++03 12420 // deadline. It's also a very silly restriction that seriously 12421 // affects inner classes and which nobody else seems to implement; 12422 // thus we never diagnose it, not even in -pedantic. 12423 // 12424 // But note that we could warn about it: it's always useless to 12425 // friend one of your own members (it's not, however, worthless to 12426 // friend a member of an arbitrary specialization of your template). 12427 12428 Decl *D; 12429 if (unsigned NumTempParamLists = TempParams.size()) 12430 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12431 NumTempParamLists, 12432 TempParams.data(), 12433 TSI, 12434 DS.getFriendSpecLoc()); 12435 else 12436 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12437 12438 if (!D) 12439 return nullptr; 12440 12441 D->setAccess(AS_public); 12442 CurContext->addDecl(D); 12443 12444 return D; 12445 } 12446 12447 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12448 MultiTemplateParamsArg TemplateParams) { 12449 const DeclSpec &DS = D.getDeclSpec(); 12450 12451 assert(DS.isFriendSpecified()); 12452 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12453 12454 SourceLocation Loc = D.getIdentifierLoc(); 12455 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12456 12457 // C++ [class.friend]p1 12458 // A friend of a class is a function or class.... 12459 // Note that this sees through typedefs, which is intended. 12460 // It *doesn't* see through dependent types, which is correct 12461 // according to [temp.arg.type]p3: 12462 // If a declaration acquires a function type through a 12463 // type dependent on a template-parameter and this causes 12464 // a declaration that does not use the syntactic form of a 12465 // function declarator to have a function type, the program 12466 // is ill-formed. 12467 if (!TInfo->getType()->isFunctionType()) { 12468 Diag(Loc, diag::err_unexpected_friend); 12469 12470 // It might be worthwhile to try to recover by creating an 12471 // appropriate declaration. 12472 return nullptr; 12473 } 12474 12475 // C++ [namespace.memdef]p3 12476 // - If a friend declaration in a non-local class first declares a 12477 // class or function, the friend class or function is a member 12478 // of the innermost enclosing namespace. 12479 // - The name of the friend is not found by simple name lookup 12480 // until a matching declaration is provided in that namespace 12481 // scope (either before or after the class declaration granting 12482 // friendship). 12483 // - If a friend function is called, its name may be found by the 12484 // name lookup that considers functions from namespaces and 12485 // classes associated with the types of the function arguments. 12486 // - When looking for a prior declaration of a class or a function 12487 // declared as a friend, scopes outside the innermost enclosing 12488 // namespace scope are not considered. 12489 12490 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12491 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12492 DeclarationName Name = NameInfo.getName(); 12493 assert(Name); 12494 12495 // Check for unexpanded parameter packs. 12496 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12497 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12498 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12499 return nullptr; 12500 12501 // The context we found the declaration in, or in which we should 12502 // create the declaration. 12503 DeclContext *DC; 12504 Scope *DCScope = S; 12505 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12506 ForRedeclaration); 12507 12508 // There are five cases here. 12509 // - There's no scope specifier and we're in a local class. Only look 12510 // for functions declared in the immediately-enclosing block scope. 12511 // We recover from invalid scope qualifiers as if they just weren't there. 12512 FunctionDecl *FunctionContainingLocalClass = nullptr; 12513 if ((SS.isInvalid() || !SS.isSet()) && 12514 (FunctionContainingLocalClass = 12515 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12516 // C++11 [class.friend]p11: 12517 // If a friend declaration appears in a local class and the name 12518 // specified is an unqualified name, a prior declaration is 12519 // looked up without considering scopes that are outside the 12520 // innermost enclosing non-class scope. For a friend function 12521 // declaration, if there is no prior declaration, the program is 12522 // ill-formed. 12523 12524 // Find the innermost enclosing non-class scope. This is the block 12525 // scope containing the local class definition (or for a nested class, 12526 // the outer local class). 12527 DCScope = S->getFnParent(); 12528 12529 // Look up the function name in the scope. 12530 Previous.clear(LookupLocalFriendName); 12531 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12532 12533 if (!Previous.empty()) { 12534 // All possible previous declarations must have the same context: 12535 // either they were declared at block scope or they are members of 12536 // one of the enclosing local classes. 12537 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12538 } else { 12539 // This is ill-formed, but provide the context that we would have 12540 // declared the function in, if we were permitted to, for error recovery. 12541 DC = FunctionContainingLocalClass; 12542 } 12543 adjustContextForLocalExternDecl(DC); 12544 12545 // C++ [class.friend]p6: 12546 // A function can be defined in a friend declaration of a class if and 12547 // only if the class is a non-local class (9.8), the function name is 12548 // unqualified, and the function has namespace scope. 12549 if (D.isFunctionDefinition()) { 12550 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12551 } 12552 12553 // - There's no scope specifier, in which case we just go to the 12554 // appropriate scope and look for a function or function template 12555 // there as appropriate. 12556 } else if (SS.isInvalid() || !SS.isSet()) { 12557 // C++11 [namespace.memdef]p3: 12558 // If the name in a friend declaration is neither qualified nor 12559 // a template-id and the declaration is a function or an 12560 // elaborated-type-specifier, the lookup to determine whether 12561 // the entity has been previously declared shall not consider 12562 // any scopes outside the innermost enclosing namespace. 12563 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12564 12565 // Find the appropriate context according to the above. 12566 DC = CurContext; 12567 12568 // Skip class contexts. If someone can cite chapter and verse 12569 // for this behavior, that would be nice --- it's what GCC and 12570 // EDG do, and it seems like a reasonable intent, but the spec 12571 // really only says that checks for unqualified existing 12572 // declarations should stop at the nearest enclosing namespace, 12573 // not that they should only consider the nearest enclosing 12574 // namespace. 12575 while (DC->isRecord()) 12576 DC = DC->getParent(); 12577 12578 DeclContext *LookupDC = DC; 12579 while (LookupDC->isTransparentContext()) 12580 LookupDC = LookupDC->getParent(); 12581 12582 while (true) { 12583 LookupQualifiedName(Previous, LookupDC); 12584 12585 if (!Previous.empty()) { 12586 DC = LookupDC; 12587 break; 12588 } 12589 12590 if (isTemplateId) { 12591 if (isa<TranslationUnitDecl>(LookupDC)) break; 12592 } else { 12593 if (LookupDC->isFileContext()) break; 12594 } 12595 LookupDC = LookupDC->getParent(); 12596 } 12597 12598 DCScope = getScopeForDeclContext(S, DC); 12599 12600 // - There's a non-dependent scope specifier, in which case we 12601 // compute it and do a previous lookup there for a function 12602 // or function template. 12603 } else if (!SS.getScopeRep()->isDependent()) { 12604 DC = computeDeclContext(SS); 12605 if (!DC) return nullptr; 12606 12607 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12608 12609 LookupQualifiedName(Previous, DC); 12610 12611 // Ignore things found implicitly in the wrong scope. 12612 // TODO: better diagnostics for this case. Suggesting the right 12613 // qualified scope would be nice... 12614 LookupResult::Filter F = Previous.makeFilter(); 12615 while (F.hasNext()) { 12616 NamedDecl *D = F.next(); 12617 if (!DC->InEnclosingNamespaceSetOf( 12618 D->getDeclContext()->getRedeclContext())) 12619 F.erase(); 12620 } 12621 F.done(); 12622 12623 if (Previous.empty()) { 12624 D.setInvalidType(); 12625 Diag(Loc, diag::err_qualified_friend_not_found) 12626 << Name << TInfo->getType(); 12627 return nullptr; 12628 } 12629 12630 // C++ [class.friend]p1: A friend of a class is a function or 12631 // class that is not a member of the class . . . 12632 if (DC->Equals(CurContext)) 12633 Diag(DS.getFriendSpecLoc(), 12634 getLangOpts().CPlusPlus11 ? 12635 diag::warn_cxx98_compat_friend_is_member : 12636 diag::err_friend_is_member); 12637 12638 if (D.isFunctionDefinition()) { 12639 // C++ [class.friend]p6: 12640 // A function can be defined in a friend declaration of a class if and 12641 // only if the class is a non-local class (9.8), the function name is 12642 // unqualified, and the function has namespace scope. 12643 SemaDiagnosticBuilder DB 12644 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12645 12646 DB << SS.getScopeRep(); 12647 if (DC->isFileContext()) 12648 DB << FixItHint::CreateRemoval(SS.getRange()); 12649 SS.clear(); 12650 } 12651 12652 // - There's a scope specifier that does not match any template 12653 // parameter lists, in which case we use some arbitrary context, 12654 // create a method or method template, and wait for instantiation. 12655 // - There's a scope specifier that does match some template 12656 // parameter lists, which we don't handle right now. 12657 } else { 12658 if (D.isFunctionDefinition()) { 12659 // C++ [class.friend]p6: 12660 // A function can be defined in a friend declaration of a class if and 12661 // only if the class is a non-local class (9.8), the function name is 12662 // unqualified, and the function has namespace scope. 12663 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12664 << SS.getScopeRep(); 12665 } 12666 12667 DC = CurContext; 12668 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12669 } 12670 12671 if (!DC->isRecord()) { 12672 // This implies that it has to be an operator or function. 12673 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12674 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12675 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12676 Diag(Loc, diag::err_introducing_special_friend) << 12677 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12678 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12679 return nullptr; 12680 } 12681 } 12682 12683 // FIXME: This is an egregious hack to cope with cases where the scope stack 12684 // does not contain the declaration context, i.e., in an out-of-line 12685 // definition of a class. 12686 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12687 if (!DCScope) { 12688 FakeDCScope.setEntity(DC); 12689 DCScope = &FakeDCScope; 12690 } 12691 12692 bool AddToScope = true; 12693 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12694 TemplateParams, AddToScope); 12695 if (!ND) return nullptr; 12696 12697 assert(ND->getLexicalDeclContext() == CurContext); 12698 12699 // If we performed typo correction, we might have added a scope specifier 12700 // and changed the decl context. 12701 DC = ND->getDeclContext(); 12702 12703 // Add the function declaration to the appropriate lookup tables, 12704 // adjusting the redeclarations list as necessary. We don't 12705 // want to do this yet if the friending class is dependent. 12706 // 12707 // Also update the scope-based lookup if the target context's 12708 // lookup context is in lexical scope. 12709 if (!CurContext->isDependentContext()) { 12710 DC = DC->getRedeclContext(); 12711 DC->makeDeclVisibleInContext(ND); 12712 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12713 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12714 } 12715 12716 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12717 D.getIdentifierLoc(), ND, 12718 DS.getFriendSpecLoc()); 12719 FrD->setAccess(AS_public); 12720 CurContext->addDecl(FrD); 12721 12722 if (ND->isInvalidDecl()) { 12723 FrD->setInvalidDecl(); 12724 } else { 12725 if (DC->isRecord()) CheckFriendAccess(ND); 12726 12727 FunctionDecl *FD; 12728 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12729 FD = FTD->getTemplatedDecl(); 12730 else 12731 FD = cast<FunctionDecl>(ND); 12732 12733 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12734 // default argument expression, that declaration shall be a definition 12735 // and shall be the only declaration of the function or function 12736 // template in the translation unit. 12737 if (functionDeclHasDefaultArgument(FD)) { 12738 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12739 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12740 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12741 } else if (!D.isFunctionDefinition()) 12742 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12743 } 12744 12745 // Mark templated-scope function declarations as unsupported. 12746 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12747 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12748 << SS.getScopeRep() << SS.getRange() 12749 << cast<CXXRecordDecl>(CurContext); 12750 FrD->setUnsupportedFriend(true); 12751 } 12752 } 12753 12754 return ND; 12755 } 12756 12757 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12758 AdjustDeclIfTemplate(Dcl); 12759 12760 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12761 if (!Fn) { 12762 Diag(DelLoc, diag::err_deleted_non_function); 12763 return; 12764 } 12765 12766 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12767 // Don't consider the implicit declaration we generate for explicit 12768 // specializations. FIXME: Do not generate these implicit declarations. 12769 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12770 Prev->getPreviousDecl()) && 12771 !Prev->isDefined()) { 12772 Diag(DelLoc, diag::err_deleted_decl_not_first); 12773 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12774 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12775 : diag::note_previous_declaration); 12776 } 12777 // If the declaration wasn't the first, we delete the function anyway for 12778 // recovery. 12779 Fn = Fn->getCanonicalDecl(); 12780 } 12781 12782 // dllimport/dllexport cannot be deleted. 12783 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12784 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12785 Fn->setInvalidDecl(); 12786 } 12787 12788 if (Fn->isDeleted()) 12789 return; 12790 12791 // See if we're deleting a function which is already known to override a 12792 // non-deleted virtual function. 12793 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12794 bool IssuedDiagnostic = false; 12795 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12796 E = MD->end_overridden_methods(); 12797 I != E; ++I) { 12798 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12799 if (!IssuedDiagnostic) { 12800 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12801 IssuedDiagnostic = true; 12802 } 12803 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12804 } 12805 } 12806 } 12807 12808 // C++11 [basic.start.main]p3: 12809 // A program that defines main as deleted [...] is ill-formed. 12810 if (Fn->isMain()) 12811 Diag(DelLoc, diag::err_deleted_main); 12812 12813 Fn->setDeletedAsWritten(); 12814 } 12815 12816 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12817 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12818 12819 if (MD) { 12820 if (MD->getParent()->isDependentType()) { 12821 MD->setDefaulted(); 12822 MD->setExplicitlyDefaulted(); 12823 return; 12824 } 12825 12826 CXXSpecialMember Member = getSpecialMember(MD); 12827 if (Member == CXXInvalid) { 12828 if (!MD->isInvalidDecl()) 12829 Diag(DefaultLoc, diag::err_default_special_members); 12830 return; 12831 } 12832 12833 MD->setDefaulted(); 12834 MD->setExplicitlyDefaulted(); 12835 12836 // If this definition appears within the record, do the checking when 12837 // the record is complete. 12838 const FunctionDecl *Primary = MD; 12839 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12840 // Find the uninstantiated declaration that actually had the '= default' 12841 // on it. 12842 Pattern->isDefined(Primary); 12843 12844 // If the method was defaulted on its first declaration, we will have 12845 // already performed the checking in CheckCompletedCXXClass. Such a 12846 // declaration doesn't trigger an implicit definition. 12847 if (Primary == Primary->getCanonicalDecl()) 12848 return; 12849 12850 CheckExplicitlyDefaultedSpecialMember(MD); 12851 12852 if (MD->isInvalidDecl()) 12853 return; 12854 12855 switch (Member) { 12856 case CXXDefaultConstructor: 12857 DefineImplicitDefaultConstructor(DefaultLoc, 12858 cast<CXXConstructorDecl>(MD)); 12859 break; 12860 case CXXCopyConstructor: 12861 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12862 break; 12863 case CXXCopyAssignment: 12864 DefineImplicitCopyAssignment(DefaultLoc, MD); 12865 break; 12866 case CXXDestructor: 12867 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12868 break; 12869 case CXXMoveConstructor: 12870 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12871 break; 12872 case CXXMoveAssignment: 12873 DefineImplicitMoveAssignment(DefaultLoc, MD); 12874 break; 12875 case CXXInvalid: 12876 llvm_unreachable("Invalid special member."); 12877 } 12878 } else { 12879 Diag(DefaultLoc, diag::err_default_special_members); 12880 } 12881 } 12882 12883 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12884 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12885 Stmt *SubStmt = *CI; 12886 if (!SubStmt) 12887 continue; 12888 if (isa<ReturnStmt>(SubStmt)) 12889 Self.Diag(SubStmt->getLocStart(), 12890 diag::err_return_in_constructor_handler); 12891 if (!isa<Expr>(SubStmt)) 12892 SearchForReturnInStmt(Self, SubStmt); 12893 } 12894 } 12895 12896 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12897 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12898 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12899 SearchForReturnInStmt(*this, Handler); 12900 } 12901 } 12902 12903 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12904 const CXXMethodDecl *Old) { 12905 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12906 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12907 12908 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12909 12910 // If the calling conventions match, everything is fine 12911 if (NewCC == OldCC) 12912 return false; 12913 12914 // If the calling conventions mismatch because the new function is static, 12915 // suppress the calling convention mismatch error; the error about static 12916 // function override (err_static_overrides_virtual from 12917 // Sema::CheckFunctionDeclaration) is more clear. 12918 if (New->getStorageClass() == SC_Static) 12919 return false; 12920 12921 Diag(New->getLocation(), 12922 diag::err_conflicting_overriding_cc_attributes) 12923 << New->getDeclName() << New->getType() << Old->getType(); 12924 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12925 return true; 12926 } 12927 12928 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12929 const CXXMethodDecl *Old) { 12930 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12931 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12932 12933 if (Context.hasSameType(NewTy, OldTy) || 12934 NewTy->isDependentType() || OldTy->isDependentType()) 12935 return false; 12936 12937 // Check if the return types are covariant 12938 QualType NewClassTy, OldClassTy; 12939 12940 /// Both types must be pointers or references to classes. 12941 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12942 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12943 NewClassTy = NewPT->getPointeeType(); 12944 OldClassTy = OldPT->getPointeeType(); 12945 } 12946 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12947 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12948 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12949 NewClassTy = NewRT->getPointeeType(); 12950 OldClassTy = OldRT->getPointeeType(); 12951 } 12952 } 12953 } 12954 12955 // The return types aren't either both pointers or references to a class type. 12956 if (NewClassTy.isNull()) { 12957 Diag(New->getLocation(), 12958 diag::err_different_return_type_for_overriding_virtual_function) 12959 << New->getDeclName() << NewTy << OldTy 12960 << New->getReturnTypeSourceRange(); 12961 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12962 << Old->getReturnTypeSourceRange(); 12963 12964 return true; 12965 } 12966 12967 // C++ [class.virtual]p6: 12968 // If the return type of D::f differs from the return type of B::f, the 12969 // class type in the return type of D::f shall be complete at the point of 12970 // declaration of D::f or shall be the class type D. 12971 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12972 if (!RT->isBeingDefined() && 12973 RequireCompleteType(New->getLocation(), NewClassTy, 12974 diag::err_covariant_return_incomplete, 12975 New->getDeclName())) 12976 return true; 12977 } 12978 12979 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12980 // Check if the new class derives from the old class. 12981 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12982 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12983 << New->getDeclName() << NewTy << OldTy 12984 << New->getReturnTypeSourceRange(); 12985 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12986 << Old->getReturnTypeSourceRange(); 12987 return true; 12988 } 12989 12990 // Check if we the conversion from derived to base is valid. 12991 if (CheckDerivedToBaseConversion( 12992 NewClassTy, OldClassTy, 12993 diag::err_covariant_return_inaccessible_base, 12994 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12995 New->getLocation(), New->getReturnTypeSourceRange(), 12996 New->getDeclName(), nullptr)) { 12997 // FIXME: this note won't trigger for delayed access control 12998 // diagnostics, and it's impossible to get an undelayed error 12999 // here from access control during the original parse because 13000 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 13001 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13002 << Old->getReturnTypeSourceRange(); 13003 return true; 13004 } 13005 } 13006 13007 // The qualifiers of the return types must be the same. 13008 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 13009 Diag(New->getLocation(), 13010 diag::err_covariant_return_type_different_qualifications) 13011 << New->getDeclName() << NewTy << OldTy 13012 << New->getReturnTypeSourceRange(); 13013 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13014 << Old->getReturnTypeSourceRange(); 13015 return true; 13016 }; 13017 13018 13019 // The new class type must have the same or less qualifiers as the old type. 13020 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 13021 Diag(New->getLocation(), 13022 diag::err_covariant_return_type_class_type_more_qualified) 13023 << New->getDeclName() << NewTy << OldTy 13024 << New->getReturnTypeSourceRange(); 13025 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13026 << Old->getReturnTypeSourceRange(); 13027 return true; 13028 }; 13029 13030 return false; 13031 } 13032 13033 /// \brief Mark the given method pure. 13034 /// 13035 /// \param Method the method to be marked pure. 13036 /// 13037 /// \param InitRange the source range that covers the "0" initializer. 13038 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 13039 SourceLocation EndLoc = InitRange.getEnd(); 13040 if (EndLoc.isValid()) 13041 Method->setRangeEnd(EndLoc); 13042 13043 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 13044 Method->setPure(); 13045 return false; 13046 } 13047 13048 if (!Method->isInvalidDecl()) 13049 Diag(Method->getLocation(), diag::err_non_virtual_pure) 13050 << Method->getDeclName() << InitRange; 13051 return true; 13052 } 13053 13054 /// \brief Determine whether the given declaration is a static data member. 13055 static bool isStaticDataMember(const Decl *D) { 13056 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 13057 return Var->isStaticDataMember(); 13058 13059 return false; 13060 } 13061 13062 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 13063 /// an initializer for the out-of-line declaration 'Dcl'. The scope 13064 /// is a fresh scope pushed for just this purpose. 13065 /// 13066 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 13067 /// static data member of class X, names should be looked up in the scope of 13068 /// class X. 13069 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 13070 // If there is no declaration, there was an error parsing it. 13071 if (!D || D->isInvalidDecl()) 13072 return; 13073 13074 // We will always have a nested name specifier here, but this declaration 13075 // might not be out of line if the specifier names the current namespace: 13076 // extern int n; 13077 // int ::n = 0; 13078 if (D->isOutOfLine()) 13079 EnterDeclaratorContext(S, D->getDeclContext()); 13080 13081 // If we are parsing the initializer for a static data member, push a 13082 // new expression evaluation context that is associated with this static 13083 // data member. 13084 if (isStaticDataMember(D)) 13085 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 13086 } 13087 13088 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 13089 /// initializer for the out-of-line declaration 'D'. 13090 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 13091 // If there is no declaration, there was an error parsing it. 13092 if (!D || D->isInvalidDecl()) 13093 return; 13094 13095 if (isStaticDataMember(D)) 13096 PopExpressionEvaluationContext(); 13097 13098 if (D->isOutOfLine()) 13099 ExitDeclaratorContext(S); 13100 } 13101 13102 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 13103 /// C++ if/switch/while/for statement. 13104 /// e.g: "if (int x = f()) {...}" 13105 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 13106 // C++ 6.4p2: 13107 // The declarator shall not specify a function or an array. 13108 // The type-specifier-seq shall not contain typedef and shall not declare a 13109 // new class or enumeration. 13110 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 13111 "Parser allowed 'typedef' as storage class of condition decl."); 13112 13113 Decl *Dcl = ActOnDeclarator(S, D); 13114 if (!Dcl) 13115 return true; 13116 13117 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 13118 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 13119 << D.getSourceRange(); 13120 return true; 13121 } 13122 13123 return Dcl; 13124 } 13125 13126 void Sema::LoadExternalVTableUses() { 13127 if (!ExternalSource) 13128 return; 13129 13130 SmallVector<ExternalVTableUse, 4> VTables; 13131 ExternalSource->ReadUsedVTables(VTables); 13132 SmallVector<VTableUse, 4> NewUses; 13133 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 13134 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 13135 = VTablesUsed.find(VTables[I].Record); 13136 // Even if a definition wasn't required before, it may be required now. 13137 if (Pos != VTablesUsed.end()) { 13138 if (!Pos->second && VTables[I].DefinitionRequired) 13139 Pos->second = true; 13140 continue; 13141 } 13142 13143 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 13144 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 13145 } 13146 13147 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 13148 } 13149 13150 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 13151 bool DefinitionRequired) { 13152 // Ignore any vtable uses in unevaluated operands or for classes that do 13153 // not have a vtable. 13154 if (!Class->isDynamicClass() || Class->isDependentContext() || 13155 CurContext->isDependentContext() || isUnevaluatedContext()) 13156 return; 13157 13158 // Try to insert this class into the map. 13159 LoadExternalVTableUses(); 13160 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13161 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 13162 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 13163 if (!Pos.second) { 13164 // If we already had an entry, check to see if we are promoting this vtable 13165 // to require a definition. If so, we need to reappend to the VTableUses 13166 // list, since we may have already processed the first entry. 13167 if (DefinitionRequired && !Pos.first->second) { 13168 Pos.first->second = true; 13169 } else { 13170 // Otherwise, we can early exit. 13171 return; 13172 } 13173 } else { 13174 // The Microsoft ABI requires that we perform the destructor body 13175 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 13176 // the deleting destructor is emitted with the vtable, not with the 13177 // destructor definition as in the Itanium ABI. 13178 // If it has a definition, we do the check at that point instead. 13179 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13180 Class->hasUserDeclaredDestructor() && 13181 !Class->getDestructor()->isDefined() && 13182 !Class->getDestructor()->isDeleted()) { 13183 CXXDestructorDecl *DD = Class->getDestructor(); 13184 ContextRAII SavedContext(*this, DD); 13185 CheckDestructor(DD); 13186 } 13187 } 13188 13189 // Local classes need to have their virtual members marked 13190 // immediately. For all other classes, we mark their virtual members 13191 // at the end of the translation unit. 13192 if (Class->isLocalClass()) 13193 MarkVirtualMembersReferenced(Loc, Class); 13194 else 13195 VTableUses.push_back(std::make_pair(Class, Loc)); 13196 } 13197 13198 bool Sema::DefineUsedVTables() { 13199 LoadExternalVTableUses(); 13200 if (VTableUses.empty()) 13201 return false; 13202 13203 // Note: The VTableUses vector could grow as a result of marking 13204 // the members of a class as "used", so we check the size each 13205 // time through the loop and prefer indices (which are stable) to 13206 // iterators (which are not). 13207 bool DefinedAnything = false; 13208 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13209 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13210 if (!Class) 13211 continue; 13212 13213 SourceLocation Loc = VTableUses[I].second; 13214 13215 bool DefineVTable = true; 13216 13217 // If this class has a key function, but that key function is 13218 // defined in another translation unit, we don't need to emit the 13219 // vtable even though we're using it. 13220 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13221 if (KeyFunction && !KeyFunction->hasBody()) { 13222 // The key function is in another translation unit. 13223 DefineVTable = false; 13224 TemplateSpecializationKind TSK = 13225 KeyFunction->getTemplateSpecializationKind(); 13226 assert(TSK != TSK_ExplicitInstantiationDefinition && 13227 TSK != TSK_ImplicitInstantiation && 13228 "Instantiations don't have key functions"); 13229 (void)TSK; 13230 } else if (!KeyFunction) { 13231 // If we have a class with no key function that is the subject 13232 // of an explicit instantiation declaration, suppress the 13233 // vtable; it will live with the explicit instantiation 13234 // definition. 13235 bool IsExplicitInstantiationDeclaration 13236 = Class->getTemplateSpecializationKind() 13237 == TSK_ExplicitInstantiationDeclaration; 13238 for (auto R : Class->redecls()) { 13239 TemplateSpecializationKind TSK 13240 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13241 if (TSK == TSK_ExplicitInstantiationDeclaration) 13242 IsExplicitInstantiationDeclaration = true; 13243 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13244 IsExplicitInstantiationDeclaration = false; 13245 break; 13246 } 13247 } 13248 13249 if (IsExplicitInstantiationDeclaration) 13250 DefineVTable = false; 13251 } 13252 13253 // The exception specifications for all virtual members may be needed even 13254 // if we are not providing an authoritative form of the vtable in this TU. 13255 // We may choose to emit it available_externally anyway. 13256 if (!DefineVTable) { 13257 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13258 continue; 13259 } 13260 13261 // Mark all of the virtual members of this class as referenced, so 13262 // that we can build a vtable. Then, tell the AST consumer that a 13263 // vtable for this class is required. 13264 DefinedAnything = true; 13265 MarkVirtualMembersReferenced(Loc, Class); 13266 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13267 if (VTablesUsed[Canonical]) 13268 Consumer.HandleVTable(Class); 13269 13270 // Optionally warn if we're emitting a weak vtable. 13271 if (Class->isExternallyVisible() && 13272 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13273 const FunctionDecl *KeyFunctionDef = nullptr; 13274 if (!KeyFunction || 13275 (KeyFunction->hasBody(KeyFunctionDef) && 13276 KeyFunctionDef->isInlined())) 13277 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13278 TSK_ExplicitInstantiationDefinition 13279 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13280 << Class; 13281 } 13282 } 13283 VTableUses.clear(); 13284 13285 return DefinedAnything; 13286 } 13287 13288 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13289 const CXXRecordDecl *RD) { 13290 for (const auto *I : RD->methods()) 13291 if (I->isVirtual() && !I->isPure()) 13292 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13293 } 13294 13295 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13296 const CXXRecordDecl *RD) { 13297 // Mark all functions which will appear in RD's vtable as used. 13298 CXXFinalOverriderMap FinalOverriders; 13299 RD->getFinalOverriders(FinalOverriders); 13300 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13301 E = FinalOverriders.end(); 13302 I != E; ++I) { 13303 for (OverridingMethods::const_iterator OI = I->second.begin(), 13304 OE = I->second.end(); 13305 OI != OE; ++OI) { 13306 assert(OI->second.size() > 0 && "no final overrider"); 13307 CXXMethodDecl *Overrider = OI->second.front().Method; 13308 13309 // C++ [basic.def.odr]p2: 13310 // [...] A virtual member function is used if it is not pure. [...] 13311 if (!Overrider->isPure()) 13312 MarkFunctionReferenced(Loc, Overrider); 13313 } 13314 } 13315 13316 // Only classes that have virtual bases need a VTT. 13317 if (RD->getNumVBases() == 0) 13318 return; 13319 13320 for (const auto &I : RD->bases()) { 13321 const CXXRecordDecl *Base = 13322 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13323 if (Base->getNumVBases() == 0) 13324 continue; 13325 MarkVirtualMembersReferenced(Loc, Base); 13326 } 13327 } 13328 13329 /// SetIvarInitializers - This routine builds initialization ASTs for the 13330 /// Objective-C implementation whose ivars need be initialized. 13331 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13332 if (!getLangOpts().CPlusPlus) 13333 return; 13334 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13335 SmallVector<ObjCIvarDecl*, 8> ivars; 13336 CollectIvarsToConstructOrDestruct(OID, ivars); 13337 if (ivars.empty()) 13338 return; 13339 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13340 for (unsigned i = 0; i < ivars.size(); i++) { 13341 FieldDecl *Field = ivars[i]; 13342 if (Field->isInvalidDecl()) 13343 continue; 13344 13345 CXXCtorInitializer *Member; 13346 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13347 InitializationKind InitKind = 13348 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13349 13350 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13351 ExprResult MemberInit = 13352 InitSeq.Perform(*this, InitEntity, InitKind, None); 13353 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13354 // Note, MemberInit could actually come back empty if no initialization 13355 // is required (e.g., because it would call a trivial default constructor) 13356 if (!MemberInit.get() || MemberInit.isInvalid()) 13357 continue; 13358 13359 Member = 13360 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13361 SourceLocation(), 13362 MemberInit.getAs<Expr>(), 13363 SourceLocation()); 13364 AllToInit.push_back(Member); 13365 13366 // Be sure that the destructor is accessible and is marked as referenced. 13367 if (const RecordType *RecordTy = 13368 Context.getBaseElementType(Field->getType()) 13369 ->getAs<RecordType>()) { 13370 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13371 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13372 MarkFunctionReferenced(Field->getLocation(), Destructor); 13373 CheckDestructorAccess(Field->getLocation(), Destructor, 13374 PDiag(diag::err_access_dtor_ivar) 13375 << Context.getBaseElementType(Field->getType())); 13376 } 13377 } 13378 } 13379 ObjCImplementation->setIvarInitializers(Context, 13380 AllToInit.data(), AllToInit.size()); 13381 } 13382 } 13383 13384 static 13385 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13386 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13387 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13388 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13389 Sema &S) { 13390 if (Ctor->isInvalidDecl()) 13391 return; 13392 13393 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13394 13395 // Target may not be determinable yet, for instance if this is a dependent 13396 // call in an uninstantiated template. 13397 if (Target) { 13398 const FunctionDecl *FNTarget = nullptr; 13399 (void)Target->hasBody(FNTarget); 13400 Target = const_cast<CXXConstructorDecl*>( 13401 cast_or_null<CXXConstructorDecl>(FNTarget)); 13402 } 13403 13404 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13405 // Avoid dereferencing a null pointer here. 13406 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13407 13408 if (!Current.insert(Canonical).second) 13409 return; 13410 13411 // We know that beyond here, we aren't chaining into a cycle. 13412 if (!Target || !Target->isDelegatingConstructor() || 13413 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13414 Valid.insert(Current.begin(), Current.end()); 13415 Current.clear(); 13416 // We've hit a cycle. 13417 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13418 Current.count(TCanonical)) { 13419 // If we haven't diagnosed this cycle yet, do so now. 13420 if (!Invalid.count(TCanonical)) { 13421 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13422 diag::warn_delegating_ctor_cycle) 13423 << Ctor; 13424 13425 // Don't add a note for a function delegating directly to itself. 13426 if (TCanonical != Canonical) 13427 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13428 13429 CXXConstructorDecl *C = Target; 13430 while (C->getCanonicalDecl() != Canonical) { 13431 const FunctionDecl *FNTarget = nullptr; 13432 (void)C->getTargetConstructor()->hasBody(FNTarget); 13433 assert(FNTarget && "Ctor cycle through bodiless function"); 13434 13435 C = const_cast<CXXConstructorDecl*>( 13436 cast<CXXConstructorDecl>(FNTarget)); 13437 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13438 } 13439 } 13440 13441 Invalid.insert(Current.begin(), Current.end()); 13442 Current.clear(); 13443 } else { 13444 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13445 } 13446 } 13447 13448 13449 void Sema::CheckDelegatingCtorCycles() { 13450 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13451 13452 for (DelegatingCtorDeclsType::iterator 13453 I = DelegatingCtorDecls.begin(ExternalSource), 13454 E = DelegatingCtorDecls.end(); 13455 I != E; ++I) 13456 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13457 13458 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13459 CE = Invalid.end(); 13460 CI != CE; ++CI) 13461 (*CI)->setInvalidDecl(); 13462 } 13463 13464 namespace { 13465 /// \brief AST visitor that finds references to the 'this' expression. 13466 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13467 Sema &S; 13468 13469 public: 13470 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13471 13472 bool VisitCXXThisExpr(CXXThisExpr *E) { 13473 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13474 << E->isImplicit(); 13475 return false; 13476 } 13477 }; 13478 } 13479 13480 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13481 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13482 if (!TSInfo) 13483 return false; 13484 13485 TypeLoc TL = TSInfo->getTypeLoc(); 13486 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13487 if (!ProtoTL) 13488 return false; 13489 13490 // C++11 [expr.prim.general]p3: 13491 // [The expression this] shall not appear before the optional 13492 // cv-qualifier-seq and it shall not appear within the declaration of a 13493 // static member function (although its type and value category are defined 13494 // within a static member function as they are within a non-static member 13495 // function). [ Note: this is because declaration matching does not occur 13496 // until the complete declarator is known. - end note ] 13497 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13498 FindCXXThisExpr Finder(*this); 13499 13500 // If the return type came after the cv-qualifier-seq, check it now. 13501 if (Proto->hasTrailingReturn() && 13502 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13503 return true; 13504 13505 // Check the exception specification. 13506 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13507 return true; 13508 13509 return checkThisInStaticMemberFunctionAttributes(Method); 13510 } 13511 13512 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13513 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13514 if (!TSInfo) 13515 return false; 13516 13517 TypeLoc TL = TSInfo->getTypeLoc(); 13518 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13519 if (!ProtoTL) 13520 return false; 13521 13522 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13523 FindCXXThisExpr Finder(*this); 13524 13525 switch (Proto->getExceptionSpecType()) { 13526 case EST_Unparsed: 13527 case EST_Uninstantiated: 13528 case EST_Unevaluated: 13529 case EST_BasicNoexcept: 13530 case EST_DynamicNone: 13531 case EST_MSAny: 13532 case EST_None: 13533 break; 13534 13535 case EST_ComputedNoexcept: 13536 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13537 return true; 13538 13539 case EST_Dynamic: 13540 for (const auto &E : Proto->exceptions()) { 13541 if (!Finder.TraverseType(E)) 13542 return true; 13543 } 13544 break; 13545 } 13546 13547 return false; 13548 } 13549 13550 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13551 FindCXXThisExpr Finder(*this); 13552 13553 // Check attributes. 13554 for (const auto *A : Method->attrs()) { 13555 // FIXME: This should be emitted by tblgen. 13556 Expr *Arg = nullptr; 13557 ArrayRef<Expr *> Args; 13558 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13559 Arg = G->getArg(); 13560 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13561 Arg = G->getArg(); 13562 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13563 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13564 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13565 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13566 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13567 Arg = ETLF->getSuccessValue(); 13568 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13569 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13570 Arg = STLF->getSuccessValue(); 13571 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13572 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13573 Arg = LR->getArg(); 13574 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13575 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13576 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13577 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13578 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13579 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13580 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13581 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13582 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13583 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13584 13585 if (Arg && !Finder.TraverseStmt(Arg)) 13586 return true; 13587 13588 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13589 if (!Finder.TraverseStmt(Args[I])) 13590 return true; 13591 } 13592 } 13593 13594 return false; 13595 } 13596 13597 void Sema::checkExceptionSpecification( 13598 bool IsTopLevel, ExceptionSpecificationType EST, 13599 ArrayRef<ParsedType> DynamicExceptions, 13600 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13601 SmallVectorImpl<QualType> &Exceptions, 13602 FunctionProtoType::ExceptionSpecInfo &ESI) { 13603 Exceptions.clear(); 13604 ESI.Type = EST; 13605 if (EST == EST_Dynamic) { 13606 Exceptions.reserve(DynamicExceptions.size()); 13607 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13608 // FIXME: Preserve type source info. 13609 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13610 13611 if (IsTopLevel) { 13612 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13613 collectUnexpandedParameterPacks(ET, Unexpanded); 13614 if (!Unexpanded.empty()) { 13615 DiagnoseUnexpandedParameterPacks( 13616 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13617 Unexpanded); 13618 continue; 13619 } 13620 } 13621 13622 // Check that the type is valid for an exception spec, and 13623 // drop it if not. 13624 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13625 Exceptions.push_back(ET); 13626 } 13627 ESI.Exceptions = Exceptions; 13628 return; 13629 } 13630 13631 if (EST == EST_ComputedNoexcept) { 13632 // If an error occurred, there's no expression here. 13633 if (NoexceptExpr) { 13634 assert((NoexceptExpr->isTypeDependent() || 13635 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13636 Context.BoolTy) && 13637 "Parser should have made sure that the expression is boolean"); 13638 if (IsTopLevel && NoexceptExpr && 13639 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13640 ESI.Type = EST_BasicNoexcept; 13641 return; 13642 } 13643 13644 if (!NoexceptExpr->isValueDependent()) 13645 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13646 diag::err_noexcept_needs_constant_expression, 13647 /*AllowFold*/ false).get(); 13648 ESI.NoexceptExpr = NoexceptExpr; 13649 } 13650 return; 13651 } 13652 } 13653 13654 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13655 ExceptionSpecificationType EST, 13656 SourceRange SpecificationRange, 13657 ArrayRef<ParsedType> DynamicExceptions, 13658 ArrayRef<SourceRange> DynamicExceptionRanges, 13659 Expr *NoexceptExpr) { 13660 if (!MethodD) 13661 return; 13662 13663 // Dig out the method we're referring to. 13664 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13665 MethodD = FunTmpl->getTemplatedDecl(); 13666 13667 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13668 if (!Method) 13669 return; 13670 13671 // Check the exception specification. 13672 llvm::SmallVector<QualType, 4> Exceptions; 13673 FunctionProtoType::ExceptionSpecInfo ESI; 13674 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13675 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13676 ESI); 13677 13678 // Update the exception specification on the function type. 13679 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13680 13681 if (Method->isStatic()) 13682 checkThisInStaticMemberFunctionExceptionSpec(Method); 13683 13684 if (Method->isVirtual()) { 13685 // Check overrides, which we previously had to delay. 13686 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13687 OEnd = Method->end_overridden_methods(); 13688 O != OEnd; ++O) 13689 CheckOverridingFunctionExceptionSpec(Method, *O); 13690 } 13691 } 13692 13693 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13694 /// 13695 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13696 SourceLocation DeclStart, 13697 Declarator &D, Expr *BitWidth, 13698 InClassInitStyle InitStyle, 13699 AccessSpecifier AS, 13700 AttributeList *MSPropertyAttr) { 13701 IdentifierInfo *II = D.getIdentifier(); 13702 if (!II) { 13703 Diag(DeclStart, diag::err_anonymous_property); 13704 return nullptr; 13705 } 13706 SourceLocation Loc = D.getIdentifierLoc(); 13707 13708 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13709 QualType T = TInfo->getType(); 13710 if (getLangOpts().CPlusPlus) { 13711 CheckExtraCXXDefaultArguments(D); 13712 13713 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13714 UPPC_DataMemberType)) { 13715 D.setInvalidType(); 13716 T = Context.IntTy; 13717 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13718 } 13719 } 13720 13721 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13722 13723 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13724 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13725 diag::err_invalid_thread) 13726 << DeclSpec::getSpecifierName(TSCS); 13727 13728 // Check to see if this name was declared as a member previously 13729 NamedDecl *PrevDecl = nullptr; 13730 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13731 LookupName(Previous, S); 13732 switch (Previous.getResultKind()) { 13733 case LookupResult::Found: 13734 case LookupResult::FoundUnresolvedValue: 13735 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13736 break; 13737 13738 case LookupResult::FoundOverloaded: 13739 PrevDecl = Previous.getRepresentativeDecl(); 13740 break; 13741 13742 case LookupResult::NotFound: 13743 case LookupResult::NotFoundInCurrentInstantiation: 13744 case LookupResult::Ambiguous: 13745 break; 13746 } 13747 13748 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13749 // Maybe we will complain about the shadowed template parameter. 13750 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13751 // Just pretend that we didn't see the previous declaration. 13752 PrevDecl = nullptr; 13753 } 13754 13755 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13756 PrevDecl = nullptr; 13757 13758 SourceLocation TSSL = D.getLocStart(); 13759 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13760 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13761 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13762 ProcessDeclAttributes(TUScope, NewPD, D); 13763 NewPD->setAccess(AS); 13764 13765 if (NewPD->isInvalidDecl()) 13766 Record->setInvalidDecl(); 13767 13768 if (D.getDeclSpec().isModulePrivateSpecified()) 13769 NewPD->setModulePrivate(); 13770 13771 if (NewPD->isInvalidDecl() && PrevDecl) { 13772 // Don't introduce NewFD into scope; there's already something 13773 // with the same name in the same scope. 13774 } else if (II) { 13775 PushOnScopeChains(NewPD, S); 13776 } else 13777 Record->addDecl(NewPD); 13778 13779 return NewPD; 13780 } 13781