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 *SubStmt : Node->children()) 77 IsInvalid |= Visit(SubStmt); 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 we have a throw-all spec at this point, ignore the function. 166 if (ComputedEST == EST_None) 167 return; 168 169 switch(EST) { 170 // If this function can throw any exceptions, make a note of that. 171 case EST_MSAny: 172 case EST_None: 173 ClearExceptions(); 174 ComputedEST = EST; 175 return; 176 // FIXME: If the call to this decl is using any of its default arguments, we 177 // need to search them for potentially-throwing calls. 178 // If this function has a basic noexcept, it doesn't affect the outcome. 179 case EST_BasicNoexcept: 180 return; 181 // If we're still at noexcept(true) and there's a nothrow() callee, 182 // change to that specification. 183 case EST_DynamicNone: 184 if (ComputedEST == EST_BasicNoexcept) 185 ComputedEST = EST_DynamicNone; 186 return; 187 // Check out noexcept specs. 188 case EST_ComputedNoexcept: 189 { 190 FunctionProtoType::NoexceptResult NR = 191 Proto->getNoexceptSpec(Self->Context); 192 assert(NR != FunctionProtoType::NR_NoNoexcept && 193 "Must have noexcept result for EST_ComputedNoexcept."); 194 assert(NR != FunctionProtoType::NR_Dependent && 195 "Should not generate implicit declarations for dependent cases, " 196 "and don't know how to handle them anyway."); 197 // noexcept(false) -> no spec on the new function 198 if (NR == FunctionProtoType::NR_Throw) { 199 ClearExceptions(); 200 ComputedEST = EST_None; 201 } 202 // noexcept(true) won't change anything either. 203 return; 204 } 205 default: 206 break; 207 } 208 assert(EST == EST_Dynamic && "EST case not considered earlier."); 209 assert(ComputedEST != EST_None && 210 "Shouldn't collect exceptions when throw-all is guaranteed."); 211 ComputedEST = EST_Dynamic; 212 // Record the exceptions in this function's exception specification. 213 for (const auto &E : Proto->exceptions()) 214 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 215 Exceptions.push_back(E); 216 } 217 218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 219 if (!E || ComputedEST == EST_MSAny) 220 return; 221 222 // FIXME: 223 // 224 // C++0x [except.spec]p14: 225 // [An] implicit exception-specification specifies the type-id T if and 226 // only if T is allowed by the exception-specification of a function directly 227 // invoked by f's implicit definition; f shall allow all exceptions if any 228 // function it directly invokes allows all exceptions, and f shall allow no 229 // exceptions if every function it directly invokes allows no exceptions. 230 // 231 // Note in particular that if an implicit exception-specification is generated 232 // for a function containing a throw-expression, that specification can still 233 // be noexcept(true). 234 // 235 // Note also that 'directly invoked' is not defined in the standard, and there 236 // is no indication that we should only consider potentially-evaluated calls. 237 // 238 // Ultimately we should implement the intent of the standard: the exception 239 // specification should be the set of exceptions which can be thrown by the 240 // implicit definition. For now, we assume that any non-nothrow expression can 241 // throw any exception. 242 243 if (Self->canThrow(E)) 244 ComputedEST = EST_None; 245 } 246 247 bool 248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 249 SourceLocation EqualLoc) { 250 if (RequireCompleteType(Param->getLocation(), Param->getType(), 251 diag::err_typecheck_decl_incomplete_type)) { 252 Param->setInvalidDecl(); 253 return true; 254 } 255 256 // C++ [dcl.fct.default]p5 257 // A default argument expression is implicitly converted (clause 258 // 4) to the parameter type. The default argument expression has 259 // the same semantic constraints as the initializer expression in 260 // a declaration of a variable of the parameter type, using the 261 // copy-initialization semantics (8.5). 262 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 263 Param); 264 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 265 EqualLoc); 266 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 268 if (Result.isInvalid()) 269 return true; 270 Arg = Result.getAs<Expr>(); 271 272 CheckCompletedExpr(Arg, EqualLoc); 273 Arg = MaybeCreateExprWithCleanups(Arg); 274 275 // Okay: add the default argument to the parameter 276 Param->setDefaultArg(Arg); 277 278 // We have already instantiated this parameter; provide each of the 279 // instantiations with the uninstantiated default argument. 280 UnparsedDefaultArgInstantiationsMap::iterator InstPos 281 = UnparsedDefaultArgInstantiations.find(Param); 282 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 283 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 284 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 285 286 // We're done tracking this parameter's instantiations. 287 UnparsedDefaultArgInstantiations.erase(InstPos); 288 } 289 290 return false; 291 } 292 293 /// ActOnParamDefaultArgument - Check whether the default argument 294 /// provided for a function parameter is well-formed. If so, attach it 295 /// to the parameter declaration. 296 void 297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 298 Expr *DefaultArg) { 299 if (!param || !DefaultArg) 300 return; 301 302 ParmVarDecl *Param = cast<ParmVarDecl>(param); 303 UnparsedDefaultArgLocs.erase(Param); 304 305 // Default arguments are only permitted in C++ 306 if (!getLangOpts().CPlusPlus) { 307 Diag(EqualLoc, diag::err_param_default_argument) 308 << DefaultArg->getSourceRange(); 309 Param->setInvalidDecl(); 310 return; 311 } 312 313 // Check for unexpanded parameter packs. 314 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 315 Param->setInvalidDecl(); 316 return; 317 } 318 319 // C++11 [dcl.fct.default]p3 320 // A default argument expression [...] shall not be specified for a 321 // parameter pack. 322 if (Param->isParameterPack()) { 323 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 324 << DefaultArg->getSourceRange(); 325 return; 326 } 327 328 // Check that the default argument is well-formed 329 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 330 if (DefaultArgChecker.Visit(DefaultArg)) { 331 Param->setInvalidDecl(); 332 return; 333 } 334 335 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 336 } 337 338 /// ActOnParamUnparsedDefaultArgument - We've seen a default 339 /// argument for a function parameter, but we can't parse it yet 340 /// because we're inside a class definition. Note that this default 341 /// argument will be parsed later. 342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 343 SourceLocation EqualLoc, 344 SourceLocation ArgLoc) { 345 if (!param) 346 return; 347 348 ParmVarDecl *Param = cast<ParmVarDecl>(param); 349 Param->setUnparsedDefaultArg(); 350 UnparsedDefaultArgLocs[Param] = ArgLoc; 351 } 352 353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 354 /// the default argument for the parameter param failed. 355 void Sema::ActOnParamDefaultArgumentError(Decl *param, 356 SourceLocation EqualLoc) { 357 if (!param) 358 return; 359 360 ParmVarDecl *Param = cast<ParmVarDecl>(param); 361 Param->setInvalidDecl(); 362 UnparsedDefaultArgLocs.erase(Param); 363 Param->setDefaultArg(new(Context) 364 OpaqueValueExpr(EqualLoc, 365 Param->getType().getNonReferenceType(), 366 VK_RValue)); 367 } 368 369 /// CheckExtraCXXDefaultArguments - Check for any extra default 370 /// arguments in the declarator, which is not a function declaration 371 /// or definition and therefore is not permitted to have default 372 /// arguments. This routine should be invoked for every declarator 373 /// that is not a function declaration or definition. 374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 375 // C++ [dcl.fct.default]p3 376 // A default argument expression shall be specified only in the 377 // parameter-declaration-clause of a function declaration or in a 378 // template-parameter (14.1). It shall not be specified for a 379 // parameter pack. If it is specified in a 380 // parameter-declaration-clause, it shall not occur within a 381 // declarator or abstract-declarator of a parameter-declaration. 382 bool MightBeFunction = D.isFunctionDeclarationContext(); 383 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 384 DeclaratorChunk &chunk = D.getTypeObject(i); 385 if (chunk.Kind == DeclaratorChunk::Function) { 386 if (MightBeFunction) { 387 // This is a function declaration. It can have default arguments, but 388 // keep looking in case its return type is a function type with default 389 // arguments. 390 MightBeFunction = false; 391 continue; 392 } 393 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 394 ++argIdx) { 395 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 396 if (Param->hasUnparsedDefaultArg()) { 397 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 398 SourceRange SR; 399 if (Toks->size() > 1) 400 SR = SourceRange((*Toks)[1].getLocation(), 401 Toks->back().getLocation()); 402 else 403 SR = UnparsedDefaultArgLocs[Param]; 404 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 405 << SR; 406 delete Toks; 407 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 408 } else if (Param->getDefaultArg()) { 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << Param->getDefaultArg()->getSourceRange(); 411 Param->setDefaultArg(nullptr); 412 } 413 } 414 } else if (chunk.Kind != DeclaratorChunk::Paren) { 415 MightBeFunction = false; 416 } 417 } 418 } 419 420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 423 if (!PVD->hasDefaultArg()) 424 return false; 425 if (!PVD->hasInheritedDefaultArg()) 426 return true; 427 } 428 return false; 429 } 430 431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 432 /// function, once we already know that they have the same 433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 434 /// error, false otherwise. 435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 436 Scope *S) { 437 bool Invalid = false; 438 439 // The declaration context corresponding to the scope is the semantic 440 // parent, unless this is a local function declaration, in which case 441 // it is that surrounding function. 442 DeclContext *ScopeDC = New->isLocalExternDecl() 443 ? New->getLexicalDeclContext() 444 : New->getDeclContext(); 445 446 // Find the previous declaration for the purpose of default arguments. 447 FunctionDecl *PrevForDefaultArgs = Old; 448 for (/**/; PrevForDefaultArgs; 449 // Don't bother looking back past the latest decl if this is a local 450 // extern declaration; nothing else could work. 451 PrevForDefaultArgs = New->isLocalExternDecl() 452 ? nullptr 453 : PrevForDefaultArgs->getPreviousDecl()) { 454 // Ignore hidden declarations. 455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 456 continue; 457 458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 459 !New->isCXXClassMember()) { 460 // Ignore default arguments of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 continue; 464 } 465 466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 467 // If only one of these is a local function declaration, then they are 468 // declared in different scopes, even though isDeclInScope may think 469 // they're in the same scope. (If both are local, the scope check is 470 // sufficent, and if neither is local, then they are in the same scope.) 471 continue; 472 } 473 474 // We found our guy. 475 break; 476 } 477 478 // C++ [dcl.fct.default]p4: 479 // For non-template functions, default arguments can be added in 480 // later declarations of a function in the same 481 // scope. Declarations in different scopes have completely 482 // distinct sets of default arguments. That is, declarations in 483 // inner scopes do not acquire default arguments from 484 // declarations in outer scopes, and vice versa. In a given 485 // function declaration, all parameters subsequent to a 486 // parameter with a default argument shall have default 487 // arguments supplied in this or previous declarations. A 488 // default argument shall not be redefined by a later 489 // declaration (not even to the same value). 490 // 491 // C++ [dcl.fct.default]p6: 492 // Except for member functions of class templates, the default arguments 493 // in a member function definition that appears outside of the class 494 // definition are added to the set of default arguments provided by the 495 // member function declaration in the class definition. 496 for (unsigned p = 0, NumParams = PrevForDefaultArgs 497 ? PrevForDefaultArgs->getNumParams() 498 : 0; 499 p < NumParams; ++p) { 500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 501 ParmVarDecl *NewParam = New->getParamDecl(p); 502 503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 504 bool NewParamHasDfl = NewParam->hasDefaultArg(); 505 506 if (OldParamHasDfl && NewParamHasDfl) { 507 unsigned DiagDefaultParamID = 508 diag::err_param_default_argument_redefinition; 509 510 // MSVC accepts that default parameters be redefined for member functions 511 // of template class. The new default parameter's value is ignored. 512 Invalid = true; 513 if (getLangOpts().MicrosoftExt) { 514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 515 if (MD && MD->getParent()->getDescribedClassTemplate()) { 516 // Merge the old default argument into the new parameter. 517 NewParam->setHasInheritedDefaultArg(); 518 if (OldParam->hasUninstantiatedDefaultArg()) 519 NewParam->setUninstantiatedDefaultArg( 520 OldParam->getUninstantiatedDefaultArg()); 521 else 522 NewParam->setDefaultArg(OldParam->getInit()); 523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 524 Invalid = false; 525 } 526 } 527 528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 529 // hint here. Alternatively, we could walk the type-source information 530 // for NewParam to find the last source location in the type... but it 531 // isn't worth the effort right now. This is the kind of test case that 532 // is hard to get right: 533 // int f(int); 534 // void g(int (*fp)(int) = f); 535 // void g(int (*fp)(int) = &f); 536 Diag(NewParam->getLocation(), DiagDefaultParamID) 537 << NewParam->getDefaultArgRange(); 538 539 // Look for the function declaration where the default argument was 540 // actually written, which may be a declaration prior to Old. 541 for (auto Older = PrevForDefaultArgs; 542 OldParam->hasInheritedDefaultArg(); /**/) { 543 Older = Older->getPreviousDecl(); 544 OldParam = Older->getParamDecl(p); 545 } 546 547 Diag(OldParam->getLocation(), diag::note_previous_definition) 548 << OldParam->getDefaultArgRange(); 549 } else if (OldParamHasDfl) { 550 // Merge the old default argument into the new parameter. 551 // It's important to use getInit() here; getDefaultArg() 552 // strips off any top-level ExprWithCleanups. 553 NewParam->setHasInheritedDefaultArg(); 554 if (OldParam->hasUnparsedDefaultArg()) 555 NewParam->setUnparsedDefaultArg(); 556 else if (OldParam->hasUninstantiatedDefaultArg()) 557 NewParam->setUninstantiatedDefaultArg( 558 OldParam->getUninstantiatedDefaultArg()); 559 else 560 NewParam->setDefaultArg(OldParam->getInit()); 561 } else if (NewParamHasDfl) { 562 if (New->getDescribedFunctionTemplate()) { 563 // Paragraph 4, quoted above, only applies to non-template functions. 564 Diag(NewParam->getLocation(), 565 diag::err_param_default_argument_template_redecl) 566 << NewParam->getDefaultArgRange(); 567 Diag(PrevForDefaultArgs->getLocation(), 568 diag::note_template_prev_declaration) 569 << false; 570 } else if (New->getTemplateSpecializationKind() 571 != TSK_ImplicitInstantiation && 572 New->getTemplateSpecializationKind() != TSK_Undeclared) { 573 // C++ [temp.expr.spec]p21: 574 // Default function arguments shall not be specified in a declaration 575 // or a definition for one of the following explicit specializations: 576 // - the explicit specialization of a function template; 577 // - the explicit specialization of a member function template; 578 // - the explicit specialization of a member function of a class 579 // template where the class template specialization to which the 580 // member function specialization belongs is implicitly 581 // instantiated. 582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 584 << New->getDeclName() 585 << NewParam->getDefaultArgRange(); 586 } else if (New->getDeclContext()->isDependentContext()) { 587 // C++ [dcl.fct.default]p6 (DR217): 588 // Default arguments for a member function of a class template shall 589 // be specified on the initial declaration of the member function 590 // within the class template. 591 // 592 // Reading the tea leaves a bit in DR217 and its reference to DR205 593 // leads me to the conclusion that one cannot add default function 594 // arguments for an out-of-line definition of a member function of a 595 // dependent type. 596 int WhichKind = 2; 597 if (CXXRecordDecl *Record 598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 599 if (Record->getDescribedClassTemplate()) 600 WhichKind = 0; 601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 602 WhichKind = 1; 603 else 604 WhichKind = 2; 605 } 606 607 Diag(NewParam->getLocation(), 608 diag::err_param_default_argument_member_template_redecl) 609 << WhichKind 610 << NewParam->getDefaultArgRange(); 611 } 612 } 613 } 614 615 // DR1344: If a default argument is added outside a class definition and that 616 // default argument makes the function a special member function, the program 617 // is ill-formed. This can only happen for constructors. 618 if (isa<CXXConstructorDecl>(New) && 619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 622 if (NewSM != OldSM) { 623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 624 assert(NewParam->hasDefaultArg()); 625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 626 << NewParam->getDefaultArgRange() << NewSM; 627 Diag(Old->getLocation(), diag::note_previous_declaration); 628 } 629 } 630 631 const FunctionDecl *Def; 632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 633 // template has a constexpr specifier then all its declarations shall 634 // contain the constexpr specifier. 635 if (New->isConstexpr() != Old->isConstexpr()) { 636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 637 << New << New->isConstexpr(); 638 Diag(Old->getLocation(), diag::note_previous_declaration); 639 Invalid = true; 640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 641 Old->isDefined(Def)) { 642 // C++11 [dcl.fcn.spec]p4: 643 // If the definition of a function appears in a translation unit before its 644 // first declaration as inline, the program is ill-formed. 645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 646 Diag(Def->getLocation(), diag::note_previous_definition); 647 Invalid = true; 648 } 649 650 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 651 // argument expression, that declaration shall be a definition and shall be 652 // the only declaration of the function or function template in the 653 // translation unit. 654 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 655 functionDeclHasDefaultArgument(Old)) { 656 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 657 Diag(Old->getLocation(), diag::note_previous_declaration); 658 Invalid = true; 659 } 660 661 if (CheckEquivalentExceptionSpec(Old, New)) 662 Invalid = true; 663 664 return Invalid; 665 } 666 667 /// \brief Merge the exception specifications of two variable declarations. 668 /// 669 /// This is called when there's a redeclaration of a VarDecl. The function 670 /// checks if the redeclaration might have an exception specification and 671 /// validates compatibility and merges the specs if necessary. 672 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 673 // Shortcut if exceptions are disabled. 674 if (!getLangOpts().CXXExceptions) 675 return; 676 677 assert(Context.hasSameType(New->getType(), Old->getType()) && 678 "Should only be called if types are otherwise the same."); 679 680 QualType NewType = New->getType(); 681 QualType OldType = Old->getType(); 682 683 // We're only interested in pointers and references to functions, as well 684 // as pointers to member functions. 685 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 686 NewType = R->getPointeeType(); 687 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 688 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 689 NewType = P->getPointeeType(); 690 OldType = OldType->getAs<PointerType>()->getPointeeType(); 691 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 692 NewType = M->getPointeeType(); 693 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 694 } 695 696 if (!NewType->isFunctionProtoType()) 697 return; 698 699 // There's lots of special cases for functions. For function pointers, system 700 // libraries are hopefully not as broken so that we don't need these 701 // workarounds. 702 if (CheckEquivalentExceptionSpec( 703 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 704 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 705 New->setInvalidDecl(); 706 } 707 } 708 709 /// CheckCXXDefaultArguments - Verify that the default arguments for a 710 /// function declaration are well-formed according to C++ 711 /// [dcl.fct.default]. 712 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 713 unsigned NumParams = FD->getNumParams(); 714 unsigned p; 715 716 // Find first parameter with a default argument 717 for (p = 0; p < NumParams; ++p) { 718 ParmVarDecl *Param = FD->getParamDecl(p); 719 if (Param->hasDefaultArg()) 720 break; 721 } 722 723 // C++11 [dcl.fct.default]p4: 724 // In a given function declaration, each parameter subsequent to a parameter 725 // with a default argument shall have a default argument supplied in this or 726 // a previous declaration or shall be a function parameter pack. A default 727 // argument shall not be redefined by a later declaration (not even to the 728 // same value). 729 unsigned LastMissingDefaultArg = 0; 730 for (; p < NumParams; ++p) { 731 ParmVarDecl *Param = FD->getParamDecl(p); 732 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 733 if (Param->isInvalidDecl()) 734 /* We already complained about this parameter. */; 735 else if (Param->getIdentifier()) 736 Diag(Param->getLocation(), 737 diag::err_param_default_argument_missing_name) 738 << Param->getIdentifier(); 739 else 740 Diag(Param->getLocation(), 741 diag::err_param_default_argument_missing); 742 743 LastMissingDefaultArg = p; 744 } 745 } 746 747 if (LastMissingDefaultArg > 0) { 748 // Some default arguments were missing. Clear out all of the 749 // default arguments up to (and including) the last missing 750 // default argument, so that we leave the function parameters 751 // in a semantically valid state. 752 for (p = 0; p <= LastMissingDefaultArg; ++p) { 753 ParmVarDecl *Param = FD->getParamDecl(p); 754 if (Param->hasDefaultArg()) { 755 Param->setDefaultArg(nullptr); 756 } 757 } 758 } 759 } 760 761 // CheckConstexprParameterTypes - Check whether a function's parameter types 762 // are all literal types. If so, return true. If not, produce a suitable 763 // diagnostic and return false. 764 static bool CheckConstexprParameterTypes(Sema &SemaRef, 765 const FunctionDecl *FD) { 766 unsigned ArgIndex = 0; 767 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 768 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 769 e = FT->param_type_end(); 770 i != e; ++i, ++ArgIndex) { 771 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 772 SourceLocation ParamLoc = PD->getLocation(); 773 if (!(*i)->isDependentType() && 774 SemaRef.RequireLiteralType(ParamLoc, *i, 775 diag::err_constexpr_non_literal_param, 776 ArgIndex+1, PD->getSourceRange(), 777 isa<CXXConstructorDecl>(FD))) 778 return false; 779 } 780 return true; 781 } 782 783 /// \brief Get diagnostic %select index for tag kind for 784 /// record diagnostic message. 785 /// WARNING: Indexes apply to particular diagnostics only! 786 /// 787 /// \returns diagnostic %select index. 788 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 789 switch (Tag) { 790 case TTK_Struct: return 0; 791 case TTK_Interface: return 1; 792 case TTK_Class: return 2; 793 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 794 } 795 } 796 797 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 798 // the requirements of a constexpr function definition or a constexpr 799 // constructor definition. If so, return true. If not, produce appropriate 800 // diagnostics and return false. 801 // 802 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 803 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 804 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 805 if (MD && MD->isInstance()) { 806 // C++11 [dcl.constexpr]p4: 807 // The definition of a constexpr constructor shall satisfy the following 808 // constraints: 809 // - the class shall not have any virtual base classes; 810 const CXXRecordDecl *RD = MD->getParent(); 811 if (RD->getNumVBases()) { 812 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 813 << isa<CXXConstructorDecl>(NewFD) 814 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 815 for (const auto &I : RD->vbases()) 816 Diag(I.getLocStart(), 817 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 818 return false; 819 } 820 } 821 822 if (!isa<CXXConstructorDecl>(NewFD)) { 823 // C++11 [dcl.constexpr]p3: 824 // The definition of a constexpr function shall satisfy the following 825 // constraints: 826 // - it shall not be virtual; 827 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 828 if (Method && Method->isVirtual()) { 829 Method = Method->getCanonicalDecl(); 830 Diag(Method->getLocation(), diag::err_constexpr_virtual); 831 832 // If it's not obvious why this function is virtual, find an overridden 833 // function which uses the 'virtual' keyword. 834 const CXXMethodDecl *WrittenVirtual = Method; 835 while (!WrittenVirtual->isVirtualAsWritten()) 836 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 837 if (WrittenVirtual != Method) 838 Diag(WrittenVirtual->getLocation(), 839 diag::note_overridden_virtual_function); 840 return false; 841 } 842 843 // - its return type shall be a literal type; 844 QualType RT = NewFD->getReturnType(); 845 if (!RT->isDependentType() && 846 RequireLiteralType(NewFD->getLocation(), RT, 847 diag::err_constexpr_non_literal_return)) 848 return false; 849 } 850 851 // - each of its parameter types shall be a literal type; 852 if (!CheckConstexprParameterTypes(*this, NewFD)) 853 return false; 854 855 return true; 856 } 857 858 /// Check the given declaration statement is legal within a constexpr function 859 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 860 /// 861 /// \return true if the body is OK (maybe only as an extension), false if we 862 /// have diagnosed a problem. 863 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 864 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 865 // C++11 [dcl.constexpr]p3 and p4: 866 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 867 // contain only 868 for (const auto *DclIt : DS->decls()) { 869 switch (DclIt->getKind()) { 870 case Decl::StaticAssert: 871 case Decl::Using: 872 case Decl::UsingShadow: 873 case Decl::UsingDirective: 874 case Decl::UnresolvedUsingTypename: 875 case Decl::UnresolvedUsingValue: 876 // - static_assert-declarations 877 // - using-declarations, 878 // - using-directives, 879 continue; 880 881 case Decl::Typedef: 882 case Decl::TypeAlias: { 883 // - typedef declarations and alias-declarations that do not define 884 // classes or enumerations, 885 const auto *TN = cast<TypedefNameDecl>(DclIt); 886 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 887 // Don't allow variably-modified types in constexpr functions. 888 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 889 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 890 << TL.getSourceRange() << TL.getType() 891 << isa<CXXConstructorDecl>(Dcl); 892 return false; 893 } 894 continue; 895 } 896 897 case Decl::Enum: 898 case Decl::CXXRecord: 899 // C++1y allows types to be defined, not just declared. 900 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 901 SemaRef.Diag(DS->getLocStart(), 902 SemaRef.getLangOpts().CPlusPlus14 903 ? diag::warn_cxx11_compat_constexpr_type_definition 904 : diag::ext_constexpr_type_definition) 905 << isa<CXXConstructorDecl>(Dcl); 906 continue; 907 908 case Decl::EnumConstant: 909 case Decl::IndirectField: 910 case Decl::ParmVar: 911 // These can only appear with other declarations which are banned in 912 // C++11 and permitted in C++1y, so ignore them. 913 continue; 914 915 case Decl::Var: { 916 // C++1y [dcl.constexpr]p3 allows anything except: 917 // a definition of a variable of non-literal type or of static or 918 // thread storage duration or for which no initialization is performed. 919 const auto *VD = cast<VarDecl>(DclIt); 920 if (VD->isThisDeclarationADefinition()) { 921 if (VD->isStaticLocal()) { 922 SemaRef.Diag(VD->getLocation(), 923 diag::err_constexpr_local_var_static) 924 << isa<CXXConstructorDecl>(Dcl) 925 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 926 return false; 927 } 928 if (!VD->getType()->isDependentType() && 929 SemaRef.RequireLiteralType( 930 VD->getLocation(), VD->getType(), 931 diag::err_constexpr_local_var_non_literal_type, 932 isa<CXXConstructorDecl>(Dcl))) 933 return false; 934 if (!VD->getType()->isDependentType() && 935 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 936 SemaRef.Diag(VD->getLocation(), 937 diag::err_constexpr_local_var_no_init) 938 << isa<CXXConstructorDecl>(Dcl); 939 return false; 940 } 941 } 942 SemaRef.Diag(VD->getLocation(), 943 SemaRef.getLangOpts().CPlusPlus14 944 ? diag::warn_cxx11_compat_constexpr_local_var 945 : diag::ext_constexpr_local_var) 946 << isa<CXXConstructorDecl>(Dcl); 947 continue; 948 } 949 950 case Decl::NamespaceAlias: 951 case Decl::Function: 952 // These are disallowed in C++11 and permitted in C++1y. Allow them 953 // everywhere as an extension. 954 if (!Cxx1yLoc.isValid()) 955 Cxx1yLoc = DS->getLocStart(); 956 continue; 957 958 default: 959 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 960 << isa<CXXConstructorDecl>(Dcl); 961 return false; 962 } 963 } 964 965 return true; 966 } 967 968 /// Check that the given field is initialized within a constexpr constructor. 969 /// 970 /// \param Dcl The constexpr constructor being checked. 971 /// \param Field The field being checked. This may be a member of an anonymous 972 /// struct or union nested within the class being checked. 973 /// \param Inits All declarations, including anonymous struct/union members and 974 /// indirect members, for which any initialization was provided. 975 /// \param Diagnosed Set to true if an error is produced. 976 static void CheckConstexprCtorInitializer(Sema &SemaRef, 977 const FunctionDecl *Dcl, 978 FieldDecl *Field, 979 llvm::SmallSet<Decl*, 16> &Inits, 980 bool &Diagnosed) { 981 if (Field->isInvalidDecl()) 982 return; 983 984 if (Field->isUnnamedBitfield()) 985 return; 986 987 // Anonymous unions with no variant members and empty anonymous structs do not 988 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 989 // indirect fields don't need initializing. 990 if (Field->isAnonymousStructOrUnion() && 991 (Field->getType()->isUnionType() 992 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 993 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 994 return; 995 996 if (!Inits.count(Field)) { 997 if (!Diagnosed) { 998 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 999 Diagnosed = true; 1000 } 1001 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1002 } else if (Field->isAnonymousStructOrUnion()) { 1003 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1004 for (auto *I : RD->fields()) 1005 // If an anonymous union contains an anonymous struct of which any member 1006 // is initialized, all members must be initialized. 1007 if (!RD->isUnion() || Inits.count(I)) 1008 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1009 } 1010 } 1011 1012 /// Check the provided statement is allowed in a constexpr function 1013 /// definition. 1014 static bool 1015 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1016 SmallVectorImpl<SourceLocation> &ReturnStmts, 1017 SourceLocation &Cxx1yLoc) { 1018 // - its function-body shall be [...] a compound-statement that contains only 1019 switch (S->getStmtClass()) { 1020 case Stmt::NullStmtClass: 1021 // - null statements, 1022 return true; 1023 1024 case Stmt::DeclStmtClass: 1025 // - static_assert-declarations 1026 // - using-declarations, 1027 // - using-directives, 1028 // - typedef declarations and alias-declarations that do not define 1029 // classes or enumerations, 1030 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1031 return false; 1032 return true; 1033 1034 case Stmt::ReturnStmtClass: 1035 // - and exactly one return statement; 1036 if (isa<CXXConstructorDecl>(Dcl)) { 1037 // C++1y allows return statements in constexpr constructors. 1038 if (!Cxx1yLoc.isValid()) 1039 Cxx1yLoc = S->getLocStart(); 1040 return true; 1041 } 1042 1043 ReturnStmts.push_back(S->getLocStart()); 1044 return true; 1045 1046 case Stmt::CompoundStmtClass: { 1047 // C++1y allows compound-statements. 1048 if (!Cxx1yLoc.isValid()) 1049 Cxx1yLoc = S->getLocStart(); 1050 1051 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1052 for (auto *BodyIt : CompStmt->body()) { 1053 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1054 Cxx1yLoc)) 1055 return false; 1056 } 1057 return true; 1058 } 1059 1060 case Stmt::AttributedStmtClass: 1061 if (!Cxx1yLoc.isValid()) 1062 Cxx1yLoc = S->getLocStart(); 1063 return true; 1064 1065 case Stmt::IfStmtClass: { 1066 // C++1y allows if-statements. 1067 if (!Cxx1yLoc.isValid()) 1068 Cxx1yLoc = S->getLocStart(); 1069 1070 IfStmt *If = cast<IfStmt>(S); 1071 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1072 Cxx1yLoc)) 1073 return false; 1074 if (If->getElse() && 1075 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1076 Cxx1yLoc)) 1077 return false; 1078 return true; 1079 } 1080 1081 case Stmt::WhileStmtClass: 1082 case Stmt::DoStmtClass: 1083 case Stmt::ForStmtClass: 1084 case Stmt::CXXForRangeStmtClass: 1085 case Stmt::ContinueStmtClass: 1086 // C++1y allows all of these. We don't allow them as extensions in C++11, 1087 // because they don't make sense without variable mutation. 1088 if (!SemaRef.getLangOpts().CPlusPlus14) 1089 break; 1090 if (!Cxx1yLoc.isValid()) 1091 Cxx1yLoc = S->getLocStart(); 1092 for (Stmt *SubStmt : S->children()) 1093 if (SubStmt && 1094 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1095 Cxx1yLoc)) 1096 return false; 1097 return true; 1098 1099 case Stmt::SwitchStmtClass: 1100 case Stmt::CaseStmtClass: 1101 case Stmt::DefaultStmtClass: 1102 case Stmt::BreakStmtClass: 1103 // C++1y allows switch-statements, and since they don't need variable 1104 // mutation, we can reasonably allow them in C++11 as an extension. 1105 if (!Cxx1yLoc.isValid()) 1106 Cxx1yLoc = S->getLocStart(); 1107 for (Stmt *SubStmt : S->children()) 1108 if (SubStmt && 1109 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1110 Cxx1yLoc)) 1111 return false; 1112 return true; 1113 1114 default: 1115 if (!isa<Expr>(S)) 1116 break; 1117 1118 // C++1y allows expression-statements. 1119 if (!Cxx1yLoc.isValid()) 1120 Cxx1yLoc = S->getLocStart(); 1121 return true; 1122 } 1123 1124 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1125 << isa<CXXConstructorDecl>(Dcl); 1126 return false; 1127 } 1128 1129 /// Check the body for the given constexpr function declaration only contains 1130 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1131 /// 1132 /// \return true if the body is OK, false if we have diagnosed a problem. 1133 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1134 if (isa<CXXTryStmt>(Body)) { 1135 // C++11 [dcl.constexpr]p3: 1136 // The definition of a constexpr function shall satisfy the following 1137 // constraints: [...] 1138 // - its function-body shall be = delete, = default, or a 1139 // compound-statement 1140 // 1141 // C++11 [dcl.constexpr]p4: 1142 // In the definition of a constexpr constructor, [...] 1143 // - its function-body shall not be a function-try-block; 1144 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1145 << isa<CXXConstructorDecl>(Dcl); 1146 return false; 1147 } 1148 1149 SmallVector<SourceLocation, 4> ReturnStmts; 1150 1151 // - its function-body shall be [...] a compound-statement that contains only 1152 // [... list of cases ...] 1153 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1154 SourceLocation Cxx1yLoc; 1155 for (auto *BodyIt : CompBody->body()) { 1156 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1157 return false; 1158 } 1159 1160 if (Cxx1yLoc.isValid()) 1161 Diag(Cxx1yLoc, 1162 getLangOpts().CPlusPlus14 1163 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1164 : diag::ext_constexpr_body_invalid_stmt) 1165 << isa<CXXConstructorDecl>(Dcl); 1166 1167 if (const CXXConstructorDecl *Constructor 1168 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1169 const CXXRecordDecl *RD = Constructor->getParent(); 1170 // DR1359: 1171 // - every non-variant non-static data member and base class sub-object 1172 // shall be initialized; 1173 // DR1460: 1174 // - if the class is a union having variant members, exactly one of them 1175 // shall be initialized; 1176 if (RD->isUnion()) { 1177 if (Constructor->getNumCtorInitializers() == 0 && 1178 RD->hasVariantMembers()) { 1179 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1180 return false; 1181 } 1182 } else if (!Constructor->isDependentContext() && 1183 !Constructor->isDelegatingConstructor()) { 1184 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1185 1186 // Skip detailed checking if we have enough initializers, and we would 1187 // allow at most one initializer per member. 1188 bool AnyAnonStructUnionMembers = false; 1189 unsigned Fields = 0; 1190 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1191 E = RD->field_end(); I != E; ++I, ++Fields) { 1192 if (I->isAnonymousStructOrUnion()) { 1193 AnyAnonStructUnionMembers = true; 1194 break; 1195 } 1196 } 1197 // DR1460: 1198 // - if the class is a union-like class, but is not a union, for each of 1199 // its anonymous union members having variant members, exactly one of 1200 // them shall be initialized; 1201 if (AnyAnonStructUnionMembers || 1202 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1203 // Check initialization of non-static data members. Base classes are 1204 // always initialized so do not need to be checked. Dependent bases 1205 // might not have initializers in the member initializer list. 1206 llvm::SmallSet<Decl*, 16> Inits; 1207 for (const auto *I: Constructor->inits()) { 1208 if (FieldDecl *FD = I->getMember()) 1209 Inits.insert(FD); 1210 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1211 Inits.insert(ID->chain_begin(), ID->chain_end()); 1212 } 1213 1214 bool Diagnosed = false; 1215 for (auto *I : RD->fields()) 1216 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1217 if (Diagnosed) 1218 return false; 1219 } 1220 } 1221 } else { 1222 if (ReturnStmts.empty()) { 1223 // C++1y doesn't require constexpr functions to contain a 'return' 1224 // statement. We still do, unless the return type might be void, because 1225 // otherwise if there's no return statement, the function cannot 1226 // be used in a core constant expression. 1227 bool OK = getLangOpts().CPlusPlus14 && 1228 (Dcl->getReturnType()->isVoidType() || 1229 Dcl->getReturnType()->isDependentType()); 1230 Diag(Dcl->getLocation(), 1231 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1232 : diag::err_constexpr_body_no_return); 1233 if (!OK) 1234 return false; 1235 } else if (ReturnStmts.size() > 1) { 1236 Diag(ReturnStmts.back(), 1237 getLangOpts().CPlusPlus14 1238 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1239 : diag::ext_constexpr_body_multiple_return); 1240 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1241 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1242 } 1243 } 1244 1245 // C++11 [dcl.constexpr]p5: 1246 // if no function argument values exist such that the function invocation 1247 // substitution would produce a constant expression, the program is 1248 // ill-formed; no diagnostic required. 1249 // C++11 [dcl.constexpr]p3: 1250 // - every constructor call and implicit conversion used in initializing the 1251 // return value shall be one of those allowed in a constant expression. 1252 // C++11 [dcl.constexpr]p4: 1253 // - every constructor involved in initializing non-static data members and 1254 // base class sub-objects shall be a constexpr constructor. 1255 SmallVector<PartialDiagnosticAt, 8> Diags; 1256 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1257 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1258 << isa<CXXConstructorDecl>(Dcl); 1259 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1260 Diag(Diags[I].first, Diags[I].second); 1261 // Don't return false here: we allow this for compatibility in 1262 // system headers. 1263 } 1264 1265 return true; 1266 } 1267 1268 /// isCurrentClassName - Determine whether the identifier II is the 1269 /// name of the class type currently being defined. In the case of 1270 /// nested classes, this will only return true if II is the name of 1271 /// the innermost class. 1272 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1273 const CXXScopeSpec *SS) { 1274 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1275 1276 CXXRecordDecl *CurDecl; 1277 if (SS && SS->isSet() && !SS->isInvalid()) { 1278 DeclContext *DC = computeDeclContext(*SS, true); 1279 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1280 } else 1281 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1282 1283 if (CurDecl && CurDecl->getIdentifier()) 1284 return &II == CurDecl->getIdentifier(); 1285 return false; 1286 } 1287 1288 /// \brief Determine whether the identifier II is a typo for the name of 1289 /// the class type currently being defined. If so, update it to the identifier 1290 /// that should have been used. 1291 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1292 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1293 1294 if (!getLangOpts().SpellChecking) 1295 return false; 1296 1297 CXXRecordDecl *CurDecl; 1298 if (SS && SS->isSet() && !SS->isInvalid()) { 1299 DeclContext *DC = computeDeclContext(*SS, true); 1300 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1301 } else 1302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1303 1304 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1305 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1306 < II->getLength()) { 1307 II = CurDecl->getIdentifier(); 1308 return true; 1309 } 1310 1311 return false; 1312 } 1313 1314 /// \brief Determine whether the given class is a base class of the given 1315 /// class, including looking at dependent bases. 1316 static bool findCircularInheritance(const CXXRecordDecl *Class, 1317 const CXXRecordDecl *Current) { 1318 SmallVector<const CXXRecordDecl*, 8> Queue; 1319 1320 Class = Class->getCanonicalDecl(); 1321 while (true) { 1322 for (const auto &I : Current->bases()) { 1323 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1324 if (!Base) 1325 continue; 1326 1327 Base = Base->getDefinition(); 1328 if (!Base) 1329 continue; 1330 1331 if (Base->getCanonicalDecl() == Class) 1332 return true; 1333 1334 Queue.push_back(Base); 1335 } 1336 1337 if (Queue.empty()) 1338 return false; 1339 1340 Current = Queue.pop_back_val(); 1341 } 1342 1343 return false; 1344 } 1345 1346 /// \brief Check the validity of a C++ base class specifier. 1347 /// 1348 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1349 /// and returns NULL otherwise. 1350 CXXBaseSpecifier * 1351 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1352 SourceRange SpecifierRange, 1353 bool Virtual, AccessSpecifier Access, 1354 TypeSourceInfo *TInfo, 1355 SourceLocation EllipsisLoc) { 1356 QualType BaseType = TInfo->getType(); 1357 1358 // C++ [class.union]p1: 1359 // A union shall not have base classes. 1360 if (Class->isUnion()) { 1361 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1362 << SpecifierRange; 1363 return nullptr; 1364 } 1365 1366 if (EllipsisLoc.isValid() && 1367 !TInfo->getType()->containsUnexpandedParameterPack()) { 1368 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1369 << TInfo->getTypeLoc().getSourceRange(); 1370 EllipsisLoc = SourceLocation(); 1371 } 1372 1373 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1374 1375 if (BaseType->isDependentType()) { 1376 // Make sure that we don't have circular inheritance among our dependent 1377 // bases. For non-dependent bases, the check for completeness below handles 1378 // this. 1379 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1380 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1381 ((BaseDecl = BaseDecl->getDefinition()) && 1382 findCircularInheritance(Class, BaseDecl))) { 1383 Diag(BaseLoc, diag::err_circular_inheritance) 1384 << BaseType << Context.getTypeDeclType(Class); 1385 1386 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1387 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1388 << BaseType; 1389 1390 return nullptr; 1391 } 1392 } 1393 1394 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1395 Class->getTagKind() == TTK_Class, 1396 Access, TInfo, EllipsisLoc); 1397 } 1398 1399 // Base specifiers must be record types. 1400 if (!BaseType->isRecordType()) { 1401 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1402 return nullptr; 1403 } 1404 1405 // C++ [class.union]p1: 1406 // A union shall not be used as a base class. 1407 if (BaseType->isUnionType()) { 1408 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1409 return nullptr; 1410 } 1411 1412 // For the MS ABI, propagate DLL attributes to base class templates. 1413 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1414 if (Attr *ClassAttr = getDLLAttr(Class)) { 1415 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1416 BaseType->getAsCXXRecordDecl())) { 1417 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 1418 BaseLoc); 1419 } 1420 } 1421 } 1422 1423 // C++ [class.derived]p2: 1424 // The class-name in a base-specifier shall not be an incompletely 1425 // defined class. 1426 if (RequireCompleteType(BaseLoc, BaseType, 1427 diag::err_incomplete_base_class, SpecifierRange)) { 1428 Class->setInvalidDecl(); 1429 return nullptr; 1430 } 1431 1432 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1433 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1434 assert(BaseDecl && "Record type has no declaration"); 1435 BaseDecl = BaseDecl->getDefinition(); 1436 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1437 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1438 assert(CXXBaseDecl && "Base type is not a C++ type"); 1439 1440 // A class which contains a flexible array member is not suitable for use as a 1441 // base class: 1442 // - If the layout determines that a base comes before another base, 1443 // the flexible array member would index into the subsequent base. 1444 // - If the layout determines that base comes before the derived class, 1445 // the flexible array member would index into the derived class. 1446 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1447 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1448 << CXXBaseDecl->getDeclName(); 1449 return nullptr; 1450 } 1451 1452 // C++ [class]p3: 1453 // If a class is marked final and it appears as a base-type-specifier in 1454 // base-clause, the program is ill-formed. 1455 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1456 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1457 << CXXBaseDecl->getDeclName() 1458 << FA->isSpelledAsSealed(); 1459 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1460 << CXXBaseDecl->getDeclName() << FA->getRange(); 1461 return nullptr; 1462 } 1463 1464 if (BaseDecl->isInvalidDecl()) 1465 Class->setInvalidDecl(); 1466 1467 // Create the base specifier. 1468 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1469 Class->getTagKind() == TTK_Class, 1470 Access, TInfo, EllipsisLoc); 1471 } 1472 1473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1474 /// one entry in the base class list of a class specifier, for 1475 /// example: 1476 /// class foo : public bar, virtual private baz { 1477 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1478 BaseResult 1479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1480 ParsedAttributes &Attributes, 1481 bool Virtual, AccessSpecifier Access, 1482 ParsedType basetype, SourceLocation BaseLoc, 1483 SourceLocation EllipsisLoc) { 1484 if (!classdecl) 1485 return true; 1486 1487 AdjustDeclIfTemplate(classdecl); 1488 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1489 if (!Class) 1490 return true; 1491 1492 // We haven't yet attached the base specifiers. 1493 Class->setIsParsingBaseSpecifiers(); 1494 1495 // We do not support any C++11 attributes on base-specifiers yet. 1496 // Diagnose any attributes we see. 1497 if (!Attributes.empty()) { 1498 for (AttributeList *Attr = Attributes.getList(); Attr; 1499 Attr = Attr->getNext()) { 1500 if (Attr->isInvalid() || 1501 Attr->getKind() == AttributeList::IgnoredAttribute) 1502 continue; 1503 Diag(Attr->getLoc(), 1504 Attr->getKind() == AttributeList::UnknownAttribute 1505 ? diag::warn_unknown_attribute_ignored 1506 : diag::err_base_specifier_attribute) 1507 << Attr->getName(); 1508 } 1509 } 1510 1511 TypeSourceInfo *TInfo = nullptr; 1512 GetTypeFromParser(basetype, &TInfo); 1513 1514 if (EllipsisLoc.isInvalid() && 1515 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1516 UPPC_BaseType)) 1517 return true; 1518 1519 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1520 Virtual, Access, TInfo, 1521 EllipsisLoc)) 1522 return BaseSpec; 1523 else 1524 Class->setInvalidDecl(); 1525 1526 return true; 1527 } 1528 1529 /// Use small set to collect indirect bases. As this is only used 1530 /// locally, there's no need to abstract the small size parameter. 1531 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 1532 1533 /// \brief Recursively add the bases of Type. Don't add Type itself. 1534 static void 1535 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 1536 const QualType &Type) 1537 { 1538 // Even though the incoming type is a base, it might not be 1539 // a class -- it could be a template parm, for instance. 1540 if (auto Rec = Type->getAs<RecordType>()) { 1541 auto Decl = Rec->getAsCXXRecordDecl(); 1542 1543 // Iterate over its bases. 1544 for (const auto &BaseSpec : Decl->bases()) { 1545 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 1546 .getUnqualifiedType(); 1547 if (Set.insert(Base).second) 1548 // If we've not already seen it, recurse. 1549 NoteIndirectBases(Context, Set, Base); 1550 } 1551 } 1552 } 1553 1554 /// \brief Performs the actual work of attaching the given base class 1555 /// specifiers to a C++ class. 1556 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1557 unsigned NumBases) { 1558 if (NumBases == 0) 1559 return false; 1560 1561 // Used to keep track of which base types we have already seen, so 1562 // that we can properly diagnose redundant direct base types. Note 1563 // that the key is always the unqualified canonical type of the base 1564 // class. 1565 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1566 1567 // Used to track indirect bases so we can see if a direct base is 1568 // ambiguous. 1569 IndirectBaseSet IndirectBaseTypes; 1570 1571 // Copy non-redundant base specifiers into permanent storage. 1572 unsigned NumGoodBases = 0; 1573 bool Invalid = false; 1574 for (unsigned idx = 0; idx < NumBases; ++idx) { 1575 QualType NewBaseType 1576 = Context.getCanonicalType(Bases[idx]->getType()); 1577 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1578 1579 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1580 if (KnownBase) { 1581 // C++ [class.mi]p3: 1582 // A class shall not be specified as a direct base class of a 1583 // derived class more than once. 1584 Diag(Bases[idx]->getLocStart(), 1585 diag::err_duplicate_base_class) 1586 << KnownBase->getType() 1587 << Bases[idx]->getSourceRange(); 1588 1589 // Delete the duplicate base class specifier; we're going to 1590 // overwrite its pointer later. 1591 Context.Deallocate(Bases[idx]); 1592 1593 Invalid = true; 1594 } else { 1595 // Okay, add this new base class. 1596 KnownBase = Bases[idx]; 1597 Bases[NumGoodBases++] = Bases[idx]; 1598 1599 // Note this base's direct & indirect bases, if there could be ambiguity. 1600 if (NumBases > 1) 1601 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 1602 1603 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1604 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1605 if (Class->isInterface() && 1606 (!RD->isInterface() || 1607 KnownBase->getAccessSpecifier() != AS_public)) { 1608 // The Microsoft extension __interface does not permit bases that 1609 // are not themselves public interfaces. 1610 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1611 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1612 << RD->getSourceRange(); 1613 Invalid = true; 1614 } 1615 if (RD->hasAttr<WeakAttr>()) 1616 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1617 } 1618 } 1619 } 1620 1621 // Attach the remaining base class specifiers to the derived class. 1622 Class->setBases(Bases, NumGoodBases); 1623 1624 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 1625 // Check whether this direct base is inaccessible due to ambiguity. 1626 QualType BaseType = Bases[idx]->getType(); 1627 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 1628 .getUnqualifiedType(); 1629 1630 if (IndirectBaseTypes.count(CanonicalBase)) { 1631 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1632 /*DetectVirtual=*/true); 1633 bool found 1634 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 1635 assert(found); 1636 (void)found; 1637 1638 if (Paths.isAmbiguous(CanonicalBase)) 1639 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 1640 << BaseType << getAmbiguousPathsDisplayString(Paths) 1641 << Bases[idx]->getSourceRange(); 1642 else 1643 assert(Bases[idx]->isVirtual()); 1644 } 1645 1646 // Delete the base class specifier, since its data has been copied 1647 // into the CXXRecordDecl. 1648 Context.Deallocate(Bases[idx]); 1649 } 1650 1651 return Invalid; 1652 } 1653 1654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1655 /// class, after checking whether there are any duplicate base 1656 /// classes. 1657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1658 unsigned NumBases) { 1659 if (!ClassDecl || !Bases || !NumBases) 1660 return; 1661 1662 AdjustDeclIfTemplate(ClassDecl); 1663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1664 } 1665 1666 /// \brief Determine whether the type \p Derived is a C++ class that is 1667 /// derived from the type \p Base. 1668 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1669 if (!getLangOpts().CPlusPlus) 1670 return false; 1671 1672 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1673 if (!DerivedRD) 1674 return false; 1675 1676 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1677 if (!BaseRD) 1678 return false; 1679 1680 // If either the base or the derived type is invalid, don't try to 1681 // check whether one is derived from the other. 1682 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1683 return false; 1684 1685 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1686 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1687 } 1688 1689 /// \brief Determine whether the type \p Derived is a C++ class that is 1690 /// derived from the type \p Base. 1691 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1692 if (!getLangOpts().CPlusPlus) 1693 return false; 1694 1695 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1696 if (!DerivedRD) 1697 return false; 1698 1699 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1700 if (!BaseRD) 1701 return false; 1702 1703 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1704 } 1705 1706 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1707 CXXCastPath &BasePathArray) { 1708 assert(BasePathArray.empty() && "Base path array must be empty!"); 1709 assert(Paths.isRecordingPaths() && "Must record paths!"); 1710 1711 const CXXBasePath &Path = Paths.front(); 1712 1713 // We first go backward and check if we have a virtual base. 1714 // FIXME: It would be better if CXXBasePath had the base specifier for 1715 // the nearest virtual base. 1716 unsigned Start = 0; 1717 for (unsigned I = Path.size(); I != 0; --I) { 1718 if (Path[I - 1].Base->isVirtual()) { 1719 Start = I - 1; 1720 break; 1721 } 1722 } 1723 1724 // Now add all bases. 1725 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1726 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1727 } 1728 1729 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1730 /// conversion (where Derived and Base are class types) is 1731 /// well-formed, meaning that the conversion is unambiguous (and 1732 /// that all of the base classes are accessible). Returns true 1733 /// and emits a diagnostic if the code is ill-formed, returns false 1734 /// otherwise. Loc is the location where this routine should point to 1735 /// if there is an error, and Range is the source range to highlight 1736 /// if there is an error. 1737 bool 1738 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1739 unsigned InaccessibleBaseID, 1740 unsigned AmbigiousBaseConvID, 1741 SourceLocation Loc, SourceRange Range, 1742 DeclarationName Name, 1743 CXXCastPath *BasePath) { 1744 // First, determine whether the path from Derived to Base is 1745 // ambiguous. This is slightly more expensive than checking whether 1746 // the Derived to Base conversion exists, because here we need to 1747 // explore multiple paths to determine if there is an ambiguity. 1748 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1749 /*DetectVirtual=*/false); 1750 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1751 assert(DerivationOkay && 1752 "Can only be used with a derived-to-base conversion"); 1753 (void)DerivationOkay; 1754 1755 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1756 if (InaccessibleBaseID) { 1757 // Check that the base class can be accessed. 1758 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1759 InaccessibleBaseID)) { 1760 case AR_inaccessible: 1761 return true; 1762 case AR_accessible: 1763 case AR_dependent: 1764 case AR_delayed: 1765 break; 1766 } 1767 } 1768 1769 // Build a base path if necessary. 1770 if (BasePath) 1771 BuildBasePathArray(Paths, *BasePath); 1772 return false; 1773 } 1774 1775 if (AmbigiousBaseConvID) { 1776 // We know that the derived-to-base conversion is ambiguous, and 1777 // we're going to produce a diagnostic. Perform the derived-to-base 1778 // search just one more time to compute all of the possible paths so 1779 // that we can print them out. This is more expensive than any of 1780 // the previous derived-to-base checks we've done, but at this point 1781 // performance isn't as much of an issue. 1782 Paths.clear(); 1783 Paths.setRecordingPaths(true); 1784 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1785 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1786 (void)StillOkay; 1787 1788 // Build up a textual representation of the ambiguous paths, e.g., 1789 // D -> B -> A, that will be used to illustrate the ambiguous 1790 // conversions in the diagnostic. We only print one of the paths 1791 // to each base class subobject. 1792 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1793 1794 Diag(Loc, AmbigiousBaseConvID) 1795 << Derived << Base << PathDisplayStr << Range << Name; 1796 } 1797 return true; 1798 } 1799 1800 bool 1801 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1802 SourceLocation Loc, SourceRange Range, 1803 CXXCastPath *BasePath, 1804 bool IgnoreAccess) { 1805 return CheckDerivedToBaseConversion(Derived, Base, 1806 IgnoreAccess ? 0 1807 : diag::err_upcast_to_inaccessible_base, 1808 diag::err_ambiguous_derived_to_base_conv, 1809 Loc, Range, DeclarationName(), 1810 BasePath); 1811 } 1812 1813 1814 /// @brief Builds a string representing ambiguous paths from a 1815 /// specific derived class to different subobjects of the same base 1816 /// class. 1817 /// 1818 /// This function builds a string that can be used in error messages 1819 /// to show the different paths that one can take through the 1820 /// inheritance hierarchy to go from the derived class to different 1821 /// subobjects of a base class. The result looks something like this: 1822 /// @code 1823 /// struct D -> struct B -> struct A 1824 /// struct D -> struct C -> struct A 1825 /// @endcode 1826 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1827 std::string PathDisplayStr; 1828 std::set<unsigned> DisplayedPaths; 1829 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1830 Path != Paths.end(); ++Path) { 1831 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1832 // We haven't displayed a path to this particular base 1833 // class subobject yet. 1834 PathDisplayStr += "\n "; 1835 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1836 for (CXXBasePath::const_iterator Element = Path->begin(); 1837 Element != Path->end(); ++Element) 1838 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1839 } 1840 } 1841 1842 return PathDisplayStr; 1843 } 1844 1845 //===----------------------------------------------------------------------===// 1846 // C++ class member Handling 1847 //===----------------------------------------------------------------------===// 1848 1849 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1850 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1851 SourceLocation ASLoc, 1852 SourceLocation ColonLoc, 1853 AttributeList *Attrs) { 1854 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1855 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1856 ASLoc, ColonLoc); 1857 CurContext->addHiddenDecl(ASDecl); 1858 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1859 } 1860 1861 /// CheckOverrideControl - Check C++11 override control semantics. 1862 void Sema::CheckOverrideControl(NamedDecl *D) { 1863 if (D->isInvalidDecl()) 1864 return; 1865 1866 // We only care about "override" and "final" declarations. 1867 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1868 return; 1869 1870 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1871 1872 // We can't check dependent instance methods. 1873 if (MD && MD->isInstance() && 1874 (MD->getParent()->hasAnyDependentBases() || 1875 MD->getType()->isDependentType())) 1876 return; 1877 1878 if (MD && !MD->isVirtual()) { 1879 // If we have a non-virtual method, check if if hides a virtual method. 1880 // (In that case, it's most likely the method has the wrong type.) 1881 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1882 FindHiddenVirtualMethods(MD, OverloadedMethods); 1883 1884 if (!OverloadedMethods.empty()) { 1885 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1886 Diag(OA->getLocation(), 1887 diag::override_keyword_hides_virtual_member_function) 1888 << "override" << (OverloadedMethods.size() > 1); 1889 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1890 Diag(FA->getLocation(), 1891 diag::override_keyword_hides_virtual_member_function) 1892 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1893 << (OverloadedMethods.size() > 1); 1894 } 1895 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1896 MD->setInvalidDecl(); 1897 return; 1898 } 1899 // Fall through into the general case diagnostic. 1900 // FIXME: We might want to attempt typo correction here. 1901 } 1902 1903 if (!MD || !MD->isVirtual()) { 1904 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1905 Diag(OA->getLocation(), 1906 diag::override_keyword_only_allowed_on_virtual_member_functions) 1907 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1908 D->dropAttr<OverrideAttr>(); 1909 } 1910 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1911 Diag(FA->getLocation(), 1912 diag::override_keyword_only_allowed_on_virtual_member_functions) 1913 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1914 << FixItHint::CreateRemoval(FA->getLocation()); 1915 D->dropAttr<FinalAttr>(); 1916 } 1917 return; 1918 } 1919 1920 // C++11 [class.virtual]p5: 1921 // If a function is marked with the virt-specifier override and 1922 // does not override a member function of a base class, the program is 1923 // ill-formed. 1924 bool HasOverriddenMethods = 1925 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1926 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1927 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1928 << MD->getDeclName(); 1929 } 1930 1931 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1932 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1933 return; 1934 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1935 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1936 isa<CXXDestructorDecl>(MD)) 1937 return; 1938 1939 SourceLocation Loc = MD->getLocation(); 1940 SourceLocation SpellingLoc = Loc; 1941 if (getSourceManager().isMacroArgExpansion(Loc)) 1942 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1943 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1944 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1945 return; 1946 1947 if (MD->size_overridden_methods() > 0) { 1948 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 1949 << MD->getDeclName(); 1950 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 1951 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 1952 } 1953 } 1954 1955 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1956 /// function overrides a virtual member function marked 'final', according to 1957 /// C++11 [class.virtual]p4. 1958 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1959 const CXXMethodDecl *Old) { 1960 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1961 if (!FA) 1962 return false; 1963 1964 Diag(New->getLocation(), diag::err_final_function_overridden) 1965 << New->getDeclName() 1966 << FA->isSpelledAsSealed(); 1967 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1968 return true; 1969 } 1970 1971 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1972 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1973 // FIXME: Destruction of ObjC lifetime types has side-effects. 1974 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1975 return !RD->isCompleteDefinition() || 1976 !RD->hasTrivialDefaultConstructor() || 1977 !RD->hasTrivialDestructor(); 1978 return false; 1979 } 1980 1981 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1982 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1983 if (it->isDeclspecPropertyAttribute()) 1984 return it; 1985 return nullptr; 1986 } 1987 1988 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1989 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1990 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1991 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1992 /// present (but parsing it has been deferred). 1993 NamedDecl * 1994 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1995 MultiTemplateParamsArg TemplateParameterLists, 1996 Expr *BW, const VirtSpecifiers &VS, 1997 InClassInitStyle InitStyle) { 1998 const DeclSpec &DS = D.getDeclSpec(); 1999 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2000 DeclarationName Name = NameInfo.getName(); 2001 SourceLocation Loc = NameInfo.getLoc(); 2002 2003 // For anonymous bitfields, the location should point to the type. 2004 if (Loc.isInvalid()) 2005 Loc = D.getLocStart(); 2006 2007 Expr *BitWidth = static_cast<Expr*>(BW); 2008 2009 assert(isa<CXXRecordDecl>(CurContext)); 2010 assert(!DS.isFriendSpecified()); 2011 2012 bool isFunc = D.isDeclarationOfFunction(); 2013 2014 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2015 // The Microsoft extension __interface only permits public member functions 2016 // and prohibits constructors, destructors, operators, non-public member 2017 // functions, static methods and data members. 2018 unsigned InvalidDecl; 2019 bool ShowDeclName = true; 2020 if (!isFunc) 2021 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2022 else if (AS != AS_public) 2023 InvalidDecl = 2; 2024 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2025 InvalidDecl = 3; 2026 else switch (Name.getNameKind()) { 2027 case DeclarationName::CXXConstructorName: 2028 InvalidDecl = 4; 2029 ShowDeclName = false; 2030 break; 2031 2032 case DeclarationName::CXXDestructorName: 2033 InvalidDecl = 5; 2034 ShowDeclName = false; 2035 break; 2036 2037 case DeclarationName::CXXOperatorName: 2038 case DeclarationName::CXXConversionFunctionName: 2039 InvalidDecl = 6; 2040 break; 2041 2042 default: 2043 InvalidDecl = 0; 2044 break; 2045 } 2046 2047 if (InvalidDecl) { 2048 if (ShowDeclName) 2049 Diag(Loc, diag::err_invalid_member_in_interface) 2050 << (InvalidDecl-1) << Name; 2051 else 2052 Diag(Loc, diag::err_invalid_member_in_interface) 2053 << (InvalidDecl-1) << ""; 2054 return nullptr; 2055 } 2056 } 2057 2058 // C++ 9.2p6: A member shall not be declared to have automatic storage 2059 // duration (auto, register) or with the extern storage-class-specifier. 2060 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2061 // data members and cannot be applied to names declared const or static, 2062 // and cannot be applied to reference members. 2063 switch (DS.getStorageClassSpec()) { 2064 case DeclSpec::SCS_unspecified: 2065 case DeclSpec::SCS_typedef: 2066 case DeclSpec::SCS_static: 2067 break; 2068 case DeclSpec::SCS_mutable: 2069 if (isFunc) { 2070 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2071 2072 // FIXME: It would be nicer if the keyword was ignored only for this 2073 // declarator. Otherwise we could get follow-up errors. 2074 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2075 } 2076 break; 2077 default: 2078 Diag(DS.getStorageClassSpecLoc(), 2079 diag::err_storageclass_invalid_for_member); 2080 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2081 break; 2082 } 2083 2084 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2085 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2086 !isFunc); 2087 2088 if (DS.isConstexprSpecified() && isInstField) { 2089 SemaDiagnosticBuilder B = 2090 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2091 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2092 if (InitStyle == ICIS_NoInit) { 2093 B << 0 << 0; 2094 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2095 B << FixItHint::CreateRemoval(ConstexprLoc); 2096 else { 2097 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2098 D.getMutableDeclSpec().ClearConstexprSpec(); 2099 const char *PrevSpec; 2100 unsigned DiagID; 2101 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2102 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2103 (void)Failed; 2104 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2105 } 2106 } else { 2107 B << 1; 2108 const char *PrevSpec; 2109 unsigned DiagID; 2110 if (D.getMutableDeclSpec().SetStorageClassSpec( 2111 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2112 Context.getPrintingPolicy())) { 2113 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2114 "This is the only DeclSpec that should fail to be applied"); 2115 B << 1; 2116 } else { 2117 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2118 isInstField = false; 2119 } 2120 } 2121 } 2122 2123 NamedDecl *Member; 2124 if (isInstField) { 2125 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2126 2127 // Data members must have identifiers for names. 2128 if (!Name.isIdentifier()) { 2129 Diag(Loc, diag::err_bad_variable_name) 2130 << Name; 2131 return nullptr; 2132 } 2133 2134 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2135 2136 // Member field could not be with "template" keyword. 2137 // So TemplateParameterLists should be empty in this case. 2138 if (TemplateParameterLists.size()) { 2139 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2140 if (TemplateParams->size()) { 2141 // There is no such thing as a member field template. 2142 Diag(D.getIdentifierLoc(), diag::err_template_member) 2143 << II 2144 << SourceRange(TemplateParams->getTemplateLoc(), 2145 TemplateParams->getRAngleLoc()); 2146 } else { 2147 // There is an extraneous 'template<>' for this member. 2148 Diag(TemplateParams->getTemplateLoc(), 2149 diag::err_template_member_noparams) 2150 << II 2151 << SourceRange(TemplateParams->getTemplateLoc(), 2152 TemplateParams->getRAngleLoc()); 2153 } 2154 return nullptr; 2155 } 2156 2157 if (SS.isSet() && !SS.isInvalid()) { 2158 // The user provided a superfluous scope specifier inside a class 2159 // definition: 2160 // 2161 // class X { 2162 // int X::member; 2163 // }; 2164 if (DeclContext *DC = computeDeclContext(SS, false)) 2165 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2166 else 2167 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2168 << Name << SS.getRange(); 2169 2170 SS.clear(); 2171 } 2172 2173 AttributeList *MSPropertyAttr = 2174 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2175 if (MSPropertyAttr) { 2176 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2177 BitWidth, InitStyle, AS, MSPropertyAttr); 2178 if (!Member) 2179 return nullptr; 2180 isInstField = false; 2181 } else { 2182 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2183 BitWidth, InitStyle, AS); 2184 assert(Member && "HandleField never returns null"); 2185 } 2186 } else { 2187 Member = HandleDeclarator(S, D, TemplateParameterLists); 2188 if (!Member) 2189 return nullptr; 2190 2191 // Non-instance-fields can't have a bitfield. 2192 if (BitWidth) { 2193 if (Member->isInvalidDecl()) { 2194 // don't emit another diagnostic. 2195 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 2196 // C++ 9.6p3: A bit-field shall not be a static member. 2197 // "static member 'A' cannot be a bit-field" 2198 Diag(Loc, diag::err_static_not_bitfield) 2199 << Name << BitWidth->getSourceRange(); 2200 } else if (isa<TypedefDecl>(Member)) { 2201 // "typedef member 'x' cannot be a bit-field" 2202 Diag(Loc, diag::err_typedef_not_bitfield) 2203 << Name << BitWidth->getSourceRange(); 2204 } else { 2205 // A function typedef ("typedef int f(); f a;"). 2206 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2207 Diag(Loc, diag::err_not_integral_type_bitfield) 2208 << Name << cast<ValueDecl>(Member)->getType() 2209 << BitWidth->getSourceRange(); 2210 } 2211 2212 BitWidth = nullptr; 2213 Member->setInvalidDecl(); 2214 } 2215 2216 Member->setAccess(AS); 2217 2218 // If we have declared a member function template or static data member 2219 // template, set the access of the templated declaration as well. 2220 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2221 FunTmpl->getTemplatedDecl()->setAccess(AS); 2222 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2223 VarTmpl->getTemplatedDecl()->setAccess(AS); 2224 } 2225 2226 if (VS.isOverrideSpecified()) 2227 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2228 if (VS.isFinalSpecified()) 2229 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2230 VS.isFinalSpelledSealed())); 2231 2232 if (VS.getLastLocation().isValid()) { 2233 // Update the end location of a method that has a virt-specifiers. 2234 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2235 MD->setRangeEnd(VS.getLastLocation()); 2236 } 2237 2238 CheckOverrideControl(Member); 2239 2240 assert((Name || isInstField) && "No identifier for non-field ?"); 2241 2242 if (isInstField) { 2243 FieldDecl *FD = cast<FieldDecl>(Member); 2244 FieldCollector->Add(FD); 2245 2246 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2247 // Remember all explicit private FieldDecls that have a name, no side 2248 // effects and are not part of a dependent type declaration. 2249 if (!FD->isImplicit() && FD->getDeclName() && 2250 FD->getAccess() == AS_private && 2251 !FD->hasAttr<UnusedAttr>() && 2252 !FD->getParent()->isDependentContext() && 2253 !InitializationHasSideEffects(*FD)) 2254 UnusedPrivateFields.insert(FD); 2255 } 2256 } 2257 2258 return Member; 2259 } 2260 2261 namespace { 2262 class UninitializedFieldVisitor 2263 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2264 Sema &S; 2265 // List of Decls to generate a warning on. Also remove Decls that become 2266 // initialized. 2267 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2268 // List of base classes of the record. Classes are removed after their 2269 // initializers. 2270 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 2271 // Vector of decls to be removed from the Decl set prior to visiting the 2272 // nodes. These Decls may have been initialized in the prior initializer. 2273 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2274 // If non-null, add a note to the warning pointing back to the constructor. 2275 const CXXConstructorDecl *Constructor; 2276 // Variables to hold state when processing an initializer list. When 2277 // InitList is true, special case initialization of FieldDecls matching 2278 // InitListFieldDecl. 2279 bool InitList; 2280 FieldDecl *InitListFieldDecl; 2281 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2282 2283 public: 2284 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2285 UninitializedFieldVisitor(Sema &S, 2286 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 2287 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 2288 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 2289 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 2290 2291 // Returns true if the use of ME is not an uninitialized use. 2292 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2293 bool CheckReferenceOnly) { 2294 llvm::SmallVector<FieldDecl*, 4> Fields; 2295 bool ReferenceField = false; 2296 while (ME) { 2297 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2298 if (!FD) 2299 return false; 2300 Fields.push_back(FD); 2301 if (FD->getType()->isReferenceType()) 2302 ReferenceField = true; 2303 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2304 } 2305 2306 // Binding a reference to an unintialized field is not an 2307 // uninitialized use. 2308 if (CheckReferenceOnly && !ReferenceField) 2309 return true; 2310 2311 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2312 // Discard the first field since it is the field decl that is being 2313 // initialized. 2314 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2315 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2316 } 2317 2318 for (auto UsedIter = UsedFieldIndex.begin(), 2319 UsedEnd = UsedFieldIndex.end(), 2320 OrigIter = InitFieldIndex.begin(), 2321 OrigEnd = InitFieldIndex.end(); 2322 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2323 if (*UsedIter < *OrigIter) 2324 return true; 2325 if (*UsedIter > *OrigIter) 2326 break; 2327 } 2328 2329 return false; 2330 } 2331 2332 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2333 bool AddressOf) { 2334 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2335 return; 2336 2337 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2338 // or union. 2339 MemberExpr *FieldME = ME; 2340 2341 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2342 2343 Expr *Base = ME; 2344 while (MemberExpr *SubME = 2345 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 2346 2347 if (isa<VarDecl>(SubME->getMemberDecl())) 2348 return; 2349 2350 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2351 if (!FD->isAnonymousStructOrUnion()) 2352 FieldME = SubME; 2353 2354 if (!FieldME->getType().isPODType(S.Context)) 2355 AllPODFields = false; 2356 2357 Base = SubME->getBase(); 2358 } 2359 2360 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 2361 return; 2362 2363 if (AddressOf && AllPODFields) 2364 return; 2365 2366 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2367 2368 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 2369 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 2370 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 2371 } 2372 2373 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 2374 QualType T = BaseCast->getType(); 2375 if (T->isPointerType() && 2376 BaseClasses.count(T->getPointeeType())) { 2377 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 2378 << T->getPointeeType() << FoundVD; 2379 } 2380 } 2381 } 2382 2383 if (!Decls.count(FoundVD)) 2384 return; 2385 2386 const bool IsReference = FoundVD->getType()->isReferenceType(); 2387 2388 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2389 // Special checking for initializer lists. 2390 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2391 return; 2392 } 2393 } else { 2394 // Prevent double warnings on use of unbounded references. 2395 if (CheckReferenceOnly && !IsReference) 2396 return; 2397 } 2398 2399 unsigned diag = IsReference 2400 ? diag::warn_reference_field_is_uninit 2401 : diag::warn_field_is_uninit; 2402 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2403 if (Constructor) 2404 S.Diag(Constructor->getLocation(), 2405 diag::note_uninit_in_this_constructor) 2406 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2407 2408 } 2409 2410 void HandleValue(Expr *E, bool AddressOf) { 2411 E = E->IgnoreParens(); 2412 2413 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2414 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2415 AddressOf /*AddressOf*/); 2416 return; 2417 } 2418 2419 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2420 Visit(CO->getCond()); 2421 HandleValue(CO->getTrueExpr(), AddressOf); 2422 HandleValue(CO->getFalseExpr(), AddressOf); 2423 return; 2424 } 2425 2426 if (BinaryConditionalOperator *BCO = 2427 dyn_cast<BinaryConditionalOperator>(E)) { 2428 Visit(BCO->getCond()); 2429 HandleValue(BCO->getFalseExpr(), AddressOf); 2430 return; 2431 } 2432 2433 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2434 HandleValue(OVE->getSourceExpr(), AddressOf); 2435 return; 2436 } 2437 2438 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2439 switch (BO->getOpcode()) { 2440 default: 2441 break; 2442 case(BO_PtrMemD): 2443 case(BO_PtrMemI): 2444 HandleValue(BO->getLHS(), AddressOf); 2445 Visit(BO->getRHS()); 2446 return; 2447 case(BO_Comma): 2448 Visit(BO->getLHS()); 2449 HandleValue(BO->getRHS(), AddressOf); 2450 return; 2451 } 2452 } 2453 2454 Visit(E); 2455 } 2456 2457 void CheckInitListExpr(InitListExpr *ILE) { 2458 InitFieldIndex.push_back(0); 2459 for (auto Child : ILE->children()) { 2460 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2461 CheckInitListExpr(SubList); 2462 } else { 2463 Visit(Child); 2464 } 2465 ++InitFieldIndex.back(); 2466 } 2467 InitFieldIndex.pop_back(); 2468 } 2469 2470 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2471 FieldDecl *Field, const Type *BaseClass) { 2472 // Remove Decls that may have been initialized in the previous 2473 // initializer. 2474 for (ValueDecl* VD : DeclsToRemove) 2475 Decls.erase(VD); 2476 DeclsToRemove.clear(); 2477 2478 Constructor = FieldConstructor; 2479 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2480 2481 if (ILE && Field) { 2482 InitList = true; 2483 InitListFieldDecl = Field; 2484 InitFieldIndex.clear(); 2485 CheckInitListExpr(ILE); 2486 } else { 2487 InitList = false; 2488 Visit(E); 2489 } 2490 2491 if (Field) 2492 Decls.erase(Field); 2493 if (BaseClass) 2494 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 2495 } 2496 2497 void VisitMemberExpr(MemberExpr *ME) { 2498 // All uses of unbounded reference fields will warn. 2499 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2500 } 2501 2502 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2503 if (E->getCastKind() == CK_LValueToRValue) { 2504 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2505 return; 2506 } 2507 2508 Inherited::VisitImplicitCastExpr(E); 2509 } 2510 2511 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2512 if (E->getConstructor()->isCopyConstructor()) { 2513 Expr *ArgExpr = E->getArg(0); 2514 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2515 if (ILE->getNumInits() == 1) 2516 ArgExpr = ILE->getInit(0); 2517 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2518 if (ICE->getCastKind() == CK_NoOp) 2519 ArgExpr = ICE->getSubExpr(); 2520 HandleValue(ArgExpr, false /*AddressOf*/); 2521 return; 2522 } 2523 Inherited::VisitCXXConstructExpr(E); 2524 } 2525 2526 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2527 Expr *Callee = E->getCallee(); 2528 if (isa<MemberExpr>(Callee)) { 2529 HandleValue(Callee, false /*AddressOf*/); 2530 for (auto Arg : E->arguments()) 2531 Visit(Arg); 2532 return; 2533 } 2534 2535 Inherited::VisitCXXMemberCallExpr(E); 2536 } 2537 2538 void VisitCallExpr(CallExpr *E) { 2539 // Treat std::move as a use. 2540 if (E->getNumArgs() == 1) { 2541 if (FunctionDecl *FD = E->getDirectCallee()) { 2542 if (FD->isInStdNamespace() && FD->getIdentifier() && 2543 FD->getIdentifier()->isStr("move")) { 2544 HandleValue(E->getArg(0), false /*AddressOf*/); 2545 return; 2546 } 2547 } 2548 } 2549 2550 Inherited::VisitCallExpr(E); 2551 } 2552 2553 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2554 Expr *Callee = E->getCallee(); 2555 2556 if (isa<UnresolvedLookupExpr>(Callee)) 2557 return Inherited::VisitCXXOperatorCallExpr(E); 2558 2559 Visit(Callee); 2560 for (auto Arg : E->arguments()) 2561 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2562 } 2563 2564 void VisitBinaryOperator(BinaryOperator *E) { 2565 // If a field assignment is detected, remove the field from the 2566 // uninitiailized field set. 2567 if (E->getOpcode() == BO_Assign) 2568 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2569 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2570 if (!FD->getType()->isReferenceType()) 2571 DeclsToRemove.push_back(FD); 2572 2573 if (E->isCompoundAssignmentOp()) { 2574 HandleValue(E->getLHS(), false /*AddressOf*/); 2575 Visit(E->getRHS()); 2576 return; 2577 } 2578 2579 Inherited::VisitBinaryOperator(E); 2580 } 2581 2582 void VisitUnaryOperator(UnaryOperator *E) { 2583 if (E->isIncrementDecrementOp()) { 2584 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2585 return; 2586 } 2587 if (E->getOpcode() == UO_AddrOf) { 2588 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2589 HandleValue(ME->getBase(), true /*AddressOf*/); 2590 return; 2591 } 2592 } 2593 2594 Inherited::VisitUnaryOperator(E); 2595 } 2596 }; 2597 2598 // Diagnose value-uses of fields to initialize themselves, e.g. 2599 // foo(foo) 2600 // where foo is not also a parameter to the constructor. 2601 // Also diagnose across field uninitialized use such as 2602 // x(y), y(x) 2603 // TODO: implement -Wuninitialized and fold this into that framework. 2604 static void DiagnoseUninitializedFields( 2605 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2606 2607 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2608 Constructor->getLocation())) { 2609 return; 2610 } 2611 2612 if (Constructor->isInvalidDecl()) 2613 return; 2614 2615 const CXXRecordDecl *RD = Constructor->getParent(); 2616 2617 if (RD->getDescribedClassTemplate()) 2618 return; 2619 2620 // Holds fields that are uninitialized. 2621 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2622 2623 // At the beginning, all fields are uninitialized. 2624 for (auto *I : RD->decls()) { 2625 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2626 UninitializedFields.insert(FD); 2627 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2628 UninitializedFields.insert(IFD->getAnonField()); 2629 } 2630 } 2631 2632 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 2633 for (auto I : RD->bases()) 2634 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 2635 2636 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2637 return; 2638 2639 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2640 UninitializedFields, 2641 UninitializedBaseClasses); 2642 2643 for (const auto *FieldInit : Constructor->inits()) { 2644 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2645 break; 2646 2647 Expr *InitExpr = FieldInit->getInit(); 2648 if (!InitExpr) 2649 continue; 2650 2651 if (CXXDefaultInitExpr *Default = 2652 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2653 InitExpr = Default->getExpr(); 2654 if (!InitExpr) 2655 continue; 2656 // In class initializers will point to the constructor. 2657 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2658 FieldInit->getAnyMember(), 2659 FieldInit->getBaseClass()); 2660 } else { 2661 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2662 FieldInit->getAnyMember(), 2663 FieldInit->getBaseClass()); 2664 } 2665 } 2666 } 2667 } // namespace 2668 2669 /// \brief Enter a new C++ default initializer scope. After calling this, the 2670 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2671 /// parsing or instantiating the initializer failed. 2672 void Sema::ActOnStartCXXInClassMemberInitializer() { 2673 // Create a synthetic function scope to represent the call to the constructor 2674 // that notionally surrounds a use of this initializer. 2675 PushFunctionScope(); 2676 } 2677 2678 /// \brief This is invoked after parsing an in-class initializer for a 2679 /// non-static C++ class member, and after instantiating an in-class initializer 2680 /// in a class template. Such actions are deferred until the class is complete. 2681 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2682 SourceLocation InitLoc, 2683 Expr *InitExpr) { 2684 // Pop the notional constructor scope we created earlier. 2685 PopFunctionScopeInfo(nullptr, D); 2686 2687 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2688 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 2689 "must set init style when field is created"); 2690 2691 if (!InitExpr) { 2692 D->setInvalidDecl(); 2693 if (FD) 2694 FD->removeInClassInitializer(); 2695 return; 2696 } 2697 2698 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2699 FD->setInvalidDecl(); 2700 FD->removeInClassInitializer(); 2701 return; 2702 } 2703 2704 ExprResult Init = InitExpr; 2705 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2706 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2707 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2708 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2709 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2710 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2711 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2712 if (Init.isInvalid()) { 2713 FD->setInvalidDecl(); 2714 return; 2715 } 2716 } 2717 2718 // C++11 [class.base.init]p7: 2719 // The initialization of each base and member constitutes a 2720 // full-expression. 2721 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2722 if (Init.isInvalid()) { 2723 FD->setInvalidDecl(); 2724 return; 2725 } 2726 2727 InitExpr = Init.get(); 2728 2729 FD->setInClassInitializer(InitExpr); 2730 } 2731 2732 /// \brief Find the direct and/or virtual base specifiers that 2733 /// correspond to the given base type, for use in base initialization 2734 /// within a constructor. 2735 static bool FindBaseInitializer(Sema &SemaRef, 2736 CXXRecordDecl *ClassDecl, 2737 QualType BaseType, 2738 const CXXBaseSpecifier *&DirectBaseSpec, 2739 const CXXBaseSpecifier *&VirtualBaseSpec) { 2740 // First, check for a direct base class. 2741 DirectBaseSpec = nullptr; 2742 for (const auto &Base : ClassDecl->bases()) { 2743 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2744 // We found a direct base of this type. That's what we're 2745 // initializing. 2746 DirectBaseSpec = &Base; 2747 break; 2748 } 2749 } 2750 2751 // Check for a virtual base class. 2752 // FIXME: We might be able to short-circuit this if we know in advance that 2753 // there are no virtual bases. 2754 VirtualBaseSpec = nullptr; 2755 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2756 // We haven't found a base yet; search the class hierarchy for a 2757 // virtual base class. 2758 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2759 /*DetectVirtual=*/false); 2760 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2761 BaseType, Paths)) { 2762 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2763 Path != Paths.end(); ++Path) { 2764 if (Path->back().Base->isVirtual()) { 2765 VirtualBaseSpec = Path->back().Base; 2766 break; 2767 } 2768 } 2769 } 2770 } 2771 2772 return DirectBaseSpec || VirtualBaseSpec; 2773 } 2774 2775 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2776 MemInitResult 2777 Sema::ActOnMemInitializer(Decl *ConstructorD, 2778 Scope *S, 2779 CXXScopeSpec &SS, 2780 IdentifierInfo *MemberOrBase, 2781 ParsedType TemplateTypeTy, 2782 const DeclSpec &DS, 2783 SourceLocation IdLoc, 2784 Expr *InitList, 2785 SourceLocation EllipsisLoc) { 2786 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2787 DS, IdLoc, InitList, 2788 EllipsisLoc); 2789 } 2790 2791 /// \brief Handle a C++ member initializer using parentheses syntax. 2792 MemInitResult 2793 Sema::ActOnMemInitializer(Decl *ConstructorD, 2794 Scope *S, 2795 CXXScopeSpec &SS, 2796 IdentifierInfo *MemberOrBase, 2797 ParsedType TemplateTypeTy, 2798 const DeclSpec &DS, 2799 SourceLocation IdLoc, 2800 SourceLocation LParenLoc, 2801 ArrayRef<Expr *> Args, 2802 SourceLocation RParenLoc, 2803 SourceLocation EllipsisLoc) { 2804 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2805 Args, RParenLoc); 2806 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2807 DS, IdLoc, List, EllipsisLoc); 2808 } 2809 2810 namespace { 2811 2812 // Callback to only accept typo corrections that can be a valid C++ member 2813 // intializer: either a non-static field member or a base class. 2814 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2815 public: 2816 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2817 : ClassDecl(ClassDecl) {} 2818 2819 bool ValidateCandidate(const TypoCorrection &candidate) override { 2820 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2821 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2822 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2823 return isa<TypeDecl>(ND); 2824 } 2825 return false; 2826 } 2827 2828 private: 2829 CXXRecordDecl *ClassDecl; 2830 }; 2831 2832 } 2833 2834 /// \brief Handle a C++ member initializer. 2835 MemInitResult 2836 Sema::BuildMemInitializer(Decl *ConstructorD, 2837 Scope *S, 2838 CXXScopeSpec &SS, 2839 IdentifierInfo *MemberOrBase, 2840 ParsedType TemplateTypeTy, 2841 const DeclSpec &DS, 2842 SourceLocation IdLoc, 2843 Expr *Init, 2844 SourceLocation EllipsisLoc) { 2845 ExprResult Res = CorrectDelayedTyposInExpr(Init); 2846 if (!Res.isUsable()) 2847 return true; 2848 Init = Res.get(); 2849 2850 if (!ConstructorD) 2851 return true; 2852 2853 AdjustDeclIfTemplate(ConstructorD); 2854 2855 CXXConstructorDecl *Constructor 2856 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2857 if (!Constructor) { 2858 // The user wrote a constructor initializer on a function that is 2859 // not a C++ constructor. Ignore the error for now, because we may 2860 // have more member initializers coming; we'll diagnose it just 2861 // once in ActOnMemInitializers. 2862 return true; 2863 } 2864 2865 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2866 2867 // C++ [class.base.init]p2: 2868 // Names in a mem-initializer-id are looked up in the scope of the 2869 // constructor's class and, if not found in that scope, are looked 2870 // up in the scope containing the constructor's definition. 2871 // [Note: if the constructor's class contains a member with the 2872 // same name as a direct or virtual base class of the class, a 2873 // mem-initializer-id naming the member or base class and composed 2874 // of a single identifier refers to the class member. A 2875 // mem-initializer-id for the hidden base class may be specified 2876 // using a qualified name. ] 2877 if (!SS.getScopeRep() && !TemplateTypeTy) { 2878 // Look for a member, first. 2879 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2880 if (!Result.empty()) { 2881 ValueDecl *Member; 2882 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2883 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2884 if (EllipsisLoc.isValid()) 2885 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2886 << MemberOrBase 2887 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2888 2889 return BuildMemberInitializer(Member, Init, IdLoc); 2890 } 2891 } 2892 } 2893 // It didn't name a member, so see if it names a class. 2894 QualType BaseType; 2895 TypeSourceInfo *TInfo = nullptr; 2896 2897 if (TemplateTypeTy) { 2898 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2899 } else if (DS.getTypeSpecType() == TST_decltype) { 2900 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2901 } else { 2902 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2903 LookupParsedName(R, S, &SS); 2904 2905 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2906 if (!TyD) { 2907 if (R.isAmbiguous()) return true; 2908 2909 // We don't want access-control diagnostics here. 2910 R.suppressDiagnostics(); 2911 2912 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2913 bool NotUnknownSpecialization = false; 2914 DeclContext *DC = computeDeclContext(SS, false); 2915 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2916 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2917 2918 if (!NotUnknownSpecialization) { 2919 // When the scope specifier can refer to a member of an unknown 2920 // specialization, we take it as a type name. 2921 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2922 SS.getWithLocInContext(Context), 2923 *MemberOrBase, IdLoc); 2924 if (BaseType.isNull()) 2925 return true; 2926 2927 R.clear(); 2928 R.setLookupName(MemberOrBase); 2929 } 2930 } 2931 2932 // If no results were found, try to correct typos. 2933 TypoCorrection Corr; 2934 if (R.empty() && BaseType.isNull() && 2935 (Corr = CorrectTypo( 2936 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2937 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2938 CTK_ErrorRecovery, ClassDecl))) { 2939 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2940 // We have found a non-static data member with a similar 2941 // name to what was typed; complain and initialize that 2942 // member. 2943 diagnoseTypo(Corr, 2944 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2945 << MemberOrBase << true); 2946 return BuildMemberInitializer(Member, Init, IdLoc); 2947 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2948 const CXXBaseSpecifier *DirectBaseSpec; 2949 const CXXBaseSpecifier *VirtualBaseSpec; 2950 if (FindBaseInitializer(*this, ClassDecl, 2951 Context.getTypeDeclType(Type), 2952 DirectBaseSpec, VirtualBaseSpec)) { 2953 // We have found a direct or virtual base class with a 2954 // similar name to what was typed; complain and initialize 2955 // that base class. 2956 diagnoseTypo(Corr, 2957 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2958 << MemberOrBase << false, 2959 PDiag() /*Suppress note, we provide our own.*/); 2960 2961 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2962 : VirtualBaseSpec; 2963 Diag(BaseSpec->getLocStart(), 2964 diag::note_base_class_specified_here) 2965 << BaseSpec->getType() 2966 << BaseSpec->getSourceRange(); 2967 2968 TyD = Type; 2969 } 2970 } 2971 } 2972 2973 if (!TyD && BaseType.isNull()) { 2974 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2975 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2976 return true; 2977 } 2978 } 2979 2980 if (BaseType.isNull()) { 2981 BaseType = Context.getTypeDeclType(TyD); 2982 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 2983 if (SS.isSet()) 2984 // FIXME: preserve source range information 2985 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2986 BaseType); 2987 } 2988 } 2989 2990 if (!TInfo) 2991 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2992 2993 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2994 } 2995 2996 /// Checks a member initializer expression for cases where reference (or 2997 /// pointer) members are bound to by-value parameters (or their addresses). 2998 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2999 Expr *Init, 3000 SourceLocation IdLoc) { 3001 QualType MemberTy = Member->getType(); 3002 3003 // We only handle pointers and references currently. 3004 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3005 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3006 return; 3007 3008 const bool IsPointer = MemberTy->isPointerType(); 3009 if (IsPointer) { 3010 if (const UnaryOperator *Op 3011 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3012 // The only case we're worried about with pointers requires taking the 3013 // address. 3014 if (Op->getOpcode() != UO_AddrOf) 3015 return; 3016 3017 Init = Op->getSubExpr(); 3018 } else { 3019 // We only handle address-of expression initializers for pointers. 3020 return; 3021 } 3022 } 3023 3024 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3025 // We only warn when referring to a non-reference parameter declaration. 3026 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3027 if (!Parameter || Parameter->getType()->isReferenceType()) 3028 return; 3029 3030 S.Diag(Init->getExprLoc(), 3031 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3032 : diag::warn_bind_ref_member_to_parameter) 3033 << Member << Parameter << Init->getSourceRange(); 3034 } else { 3035 // Other initializers are fine. 3036 return; 3037 } 3038 3039 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3040 << (unsigned)IsPointer; 3041 } 3042 3043 MemInitResult 3044 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3045 SourceLocation IdLoc) { 3046 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3047 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3048 assert((DirectMember || IndirectMember) && 3049 "Member must be a FieldDecl or IndirectFieldDecl"); 3050 3051 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3052 return true; 3053 3054 if (Member->isInvalidDecl()) 3055 return true; 3056 3057 MultiExprArg Args; 3058 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3059 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3060 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3061 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3062 } else { 3063 // Template instantiation doesn't reconstruct ParenListExprs for us. 3064 Args = Init; 3065 } 3066 3067 SourceRange InitRange = Init->getSourceRange(); 3068 3069 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3070 // Can't check initialization for a member of dependent type or when 3071 // any of the arguments are type-dependent expressions. 3072 DiscardCleanupsInEvaluationContext(); 3073 } else { 3074 bool InitList = false; 3075 if (isa<InitListExpr>(Init)) { 3076 InitList = true; 3077 Args = Init; 3078 } 3079 3080 // Initialize the member. 3081 InitializedEntity MemberEntity = 3082 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3083 : InitializedEntity::InitializeMember(IndirectMember, 3084 nullptr); 3085 InitializationKind Kind = 3086 InitList ? InitializationKind::CreateDirectList(IdLoc) 3087 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3088 InitRange.getEnd()); 3089 3090 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3091 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3092 nullptr); 3093 if (MemberInit.isInvalid()) 3094 return true; 3095 3096 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3097 3098 // C++11 [class.base.init]p7: 3099 // The initialization of each base and member constitutes a 3100 // full-expression. 3101 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3102 if (MemberInit.isInvalid()) 3103 return true; 3104 3105 Init = MemberInit.get(); 3106 } 3107 3108 if (DirectMember) { 3109 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3110 InitRange.getBegin(), Init, 3111 InitRange.getEnd()); 3112 } else { 3113 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3114 InitRange.getBegin(), Init, 3115 InitRange.getEnd()); 3116 } 3117 } 3118 3119 MemInitResult 3120 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3121 CXXRecordDecl *ClassDecl) { 3122 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3123 if (!LangOpts.CPlusPlus11) 3124 return Diag(NameLoc, diag::err_delegating_ctor) 3125 << TInfo->getTypeLoc().getLocalSourceRange(); 3126 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3127 3128 bool InitList = true; 3129 MultiExprArg Args = Init; 3130 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3131 InitList = false; 3132 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3133 } 3134 3135 SourceRange InitRange = Init->getSourceRange(); 3136 // Initialize the object. 3137 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3138 QualType(ClassDecl->getTypeForDecl(), 0)); 3139 InitializationKind Kind = 3140 InitList ? InitializationKind::CreateDirectList(NameLoc) 3141 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3142 InitRange.getEnd()); 3143 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3144 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3145 Args, nullptr); 3146 if (DelegationInit.isInvalid()) 3147 return true; 3148 3149 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3150 "Delegating constructor with no target?"); 3151 3152 // C++11 [class.base.init]p7: 3153 // The initialization of each base and member constitutes a 3154 // full-expression. 3155 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3156 InitRange.getBegin()); 3157 if (DelegationInit.isInvalid()) 3158 return true; 3159 3160 // If we are in a dependent context, template instantiation will 3161 // perform this type-checking again. Just save the arguments that we 3162 // received in a ParenListExpr. 3163 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3164 // of the information that we have about the base 3165 // initializer. However, deconstructing the ASTs is a dicey process, 3166 // and this approach is far more likely to get the corner cases right. 3167 if (CurContext->isDependentContext()) 3168 DelegationInit = Init; 3169 3170 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3171 DelegationInit.getAs<Expr>(), 3172 InitRange.getEnd()); 3173 } 3174 3175 MemInitResult 3176 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3177 Expr *Init, CXXRecordDecl *ClassDecl, 3178 SourceLocation EllipsisLoc) { 3179 SourceLocation BaseLoc 3180 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3181 3182 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3183 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3184 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3185 3186 // C++ [class.base.init]p2: 3187 // [...] Unless the mem-initializer-id names a nonstatic data 3188 // member of the constructor's class or a direct or virtual base 3189 // of that class, the mem-initializer is ill-formed. A 3190 // mem-initializer-list can initialize a base class using any 3191 // name that denotes that base class type. 3192 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3193 3194 SourceRange InitRange = Init->getSourceRange(); 3195 if (EllipsisLoc.isValid()) { 3196 // This is a pack expansion. 3197 if (!BaseType->containsUnexpandedParameterPack()) { 3198 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3199 << SourceRange(BaseLoc, InitRange.getEnd()); 3200 3201 EllipsisLoc = SourceLocation(); 3202 } 3203 } else { 3204 // Check for any unexpanded parameter packs. 3205 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3206 return true; 3207 3208 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3209 return true; 3210 } 3211 3212 // Check for direct and virtual base classes. 3213 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3214 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3215 if (!Dependent) { 3216 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3217 BaseType)) 3218 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3219 3220 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3221 VirtualBaseSpec); 3222 3223 // C++ [base.class.init]p2: 3224 // Unless the mem-initializer-id names a nonstatic data member of the 3225 // constructor's class or a direct or virtual base of that class, the 3226 // mem-initializer is ill-formed. 3227 if (!DirectBaseSpec && !VirtualBaseSpec) { 3228 // If the class has any dependent bases, then it's possible that 3229 // one of those types will resolve to the same type as 3230 // BaseType. Therefore, just treat this as a dependent base 3231 // class initialization. FIXME: Should we try to check the 3232 // initialization anyway? It seems odd. 3233 if (ClassDecl->hasAnyDependentBases()) 3234 Dependent = true; 3235 else 3236 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3237 << BaseType << Context.getTypeDeclType(ClassDecl) 3238 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3239 } 3240 } 3241 3242 if (Dependent) { 3243 DiscardCleanupsInEvaluationContext(); 3244 3245 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3246 /*IsVirtual=*/false, 3247 InitRange.getBegin(), Init, 3248 InitRange.getEnd(), EllipsisLoc); 3249 } 3250 3251 // C++ [base.class.init]p2: 3252 // If a mem-initializer-id is ambiguous because it designates both 3253 // a direct non-virtual base class and an inherited virtual base 3254 // class, the mem-initializer is ill-formed. 3255 if (DirectBaseSpec && VirtualBaseSpec) 3256 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3257 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3258 3259 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3260 if (!BaseSpec) 3261 BaseSpec = VirtualBaseSpec; 3262 3263 // Initialize the base. 3264 bool InitList = true; 3265 MultiExprArg Args = Init; 3266 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3267 InitList = false; 3268 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3269 } 3270 3271 InitializedEntity BaseEntity = 3272 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3273 InitializationKind Kind = 3274 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3275 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3276 InitRange.getEnd()); 3277 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3278 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3279 if (BaseInit.isInvalid()) 3280 return true; 3281 3282 // C++11 [class.base.init]p7: 3283 // The initialization of each base and member constitutes a 3284 // full-expression. 3285 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3286 if (BaseInit.isInvalid()) 3287 return true; 3288 3289 // If we are in a dependent context, template instantiation will 3290 // perform this type-checking again. Just save the arguments that we 3291 // received in a ParenListExpr. 3292 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3293 // of the information that we have about the base 3294 // initializer. However, deconstructing the ASTs is a dicey process, 3295 // and this approach is far more likely to get the corner cases right. 3296 if (CurContext->isDependentContext()) 3297 BaseInit = Init; 3298 3299 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3300 BaseSpec->isVirtual(), 3301 InitRange.getBegin(), 3302 BaseInit.getAs<Expr>(), 3303 InitRange.getEnd(), EllipsisLoc); 3304 } 3305 3306 // Create a static_cast\<T&&>(expr). 3307 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3308 if (T.isNull()) T = E->getType(); 3309 QualType TargetType = SemaRef.BuildReferenceType( 3310 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3311 SourceLocation ExprLoc = E->getLocStart(); 3312 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3313 TargetType, ExprLoc); 3314 3315 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3316 SourceRange(ExprLoc, ExprLoc), 3317 E->getSourceRange()).get(); 3318 } 3319 3320 /// ImplicitInitializerKind - How an implicit base or member initializer should 3321 /// initialize its base or member. 3322 enum ImplicitInitializerKind { 3323 IIK_Default, 3324 IIK_Copy, 3325 IIK_Move, 3326 IIK_Inherit 3327 }; 3328 3329 static bool 3330 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3331 ImplicitInitializerKind ImplicitInitKind, 3332 CXXBaseSpecifier *BaseSpec, 3333 bool IsInheritedVirtualBase, 3334 CXXCtorInitializer *&CXXBaseInit) { 3335 InitializedEntity InitEntity 3336 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3337 IsInheritedVirtualBase); 3338 3339 ExprResult BaseInit; 3340 3341 switch (ImplicitInitKind) { 3342 case IIK_Inherit: { 3343 const CXXRecordDecl *Inherited = 3344 Constructor->getInheritedConstructor()->getParent(); 3345 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3346 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3347 // C++11 [class.inhctor]p8: 3348 // Each expression in the expression-list is of the form 3349 // static_cast<T&&>(p), where p is the name of the corresponding 3350 // constructor parameter and T is the declared type of p. 3351 SmallVector<Expr*, 16> Args; 3352 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3353 ParmVarDecl *PD = Constructor->getParamDecl(I); 3354 ExprResult ArgExpr = 3355 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3356 VK_LValue, SourceLocation()); 3357 if (ArgExpr.isInvalid()) 3358 return true; 3359 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3360 } 3361 3362 InitializationKind InitKind = InitializationKind::CreateDirect( 3363 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3364 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3365 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3366 break; 3367 } 3368 } 3369 // Fall through. 3370 case IIK_Default: { 3371 InitializationKind InitKind 3372 = InitializationKind::CreateDefault(Constructor->getLocation()); 3373 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3374 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3375 break; 3376 } 3377 3378 case IIK_Move: 3379 case IIK_Copy: { 3380 bool Moving = ImplicitInitKind == IIK_Move; 3381 ParmVarDecl *Param = Constructor->getParamDecl(0); 3382 QualType ParamType = Param->getType().getNonReferenceType(); 3383 3384 Expr *CopyCtorArg = 3385 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3386 SourceLocation(), Param, false, 3387 Constructor->getLocation(), ParamType, 3388 VK_LValue, nullptr); 3389 3390 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3391 3392 // Cast to the base class to avoid ambiguities. 3393 QualType ArgTy = 3394 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3395 ParamType.getQualifiers()); 3396 3397 if (Moving) { 3398 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3399 } 3400 3401 CXXCastPath BasePath; 3402 BasePath.push_back(BaseSpec); 3403 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3404 CK_UncheckedDerivedToBase, 3405 Moving ? VK_XValue : VK_LValue, 3406 &BasePath).get(); 3407 3408 InitializationKind InitKind 3409 = InitializationKind::CreateDirect(Constructor->getLocation(), 3410 SourceLocation(), SourceLocation()); 3411 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3412 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3413 break; 3414 } 3415 } 3416 3417 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3418 if (BaseInit.isInvalid()) 3419 return true; 3420 3421 CXXBaseInit = 3422 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3423 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3424 SourceLocation()), 3425 BaseSpec->isVirtual(), 3426 SourceLocation(), 3427 BaseInit.getAs<Expr>(), 3428 SourceLocation(), 3429 SourceLocation()); 3430 3431 return false; 3432 } 3433 3434 static bool RefersToRValueRef(Expr *MemRef) { 3435 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3436 return Referenced->getType()->isRValueReferenceType(); 3437 } 3438 3439 static bool 3440 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3441 ImplicitInitializerKind ImplicitInitKind, 3442 FieldDecl *Field, IndirectFieldDecl *Indirect, 3443 CXXCtorInitializer *&CXXMemberInit) { 3444 if (Field->isInvalidDecl()) 3445 return true; 3446 3447 SourceLocation Loc = Constructor->getLocation(); 3448 3449 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3450 bool Moving = ImplicitInitKind == IIK_Move; 3451 ParmVarDecl *Param = Constructor->getParamDecl(0); 3452 QualType ParamType = Param->getType().getNonReferenceType(); 3453 3454 // Suppress copying zero-width bitfields. 3455 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3456 return false; 3457 3458 Expr *MemberExprBase = 3459 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3460 SourceLocation(), Param, false, 3461 Loc, ParamType, VK_LValue, nullptr); 3462 3463 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3464 3465 if (Moving) { 3466 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3467 } 3468 3469 // Build a reference to this field within the parameter. 3470 CXXScopeSpec SS; 3471 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3472 Sema::LookupMemberName); 3473 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3474 : cast<ValueDecl>(Field), AS_public); 3475 MemberLookup.resolveKind(); 3476 ExprResult CtorArg 3477 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3478 ParamType, Loc, 3479 /*IsArrow=*/false, 3480 SS, 3481 /*TemplateKWLoc=*/SourceLocation(), 3482 /*FirstQualifierInScope=*/nullptr, 3483 MemberLookup, 3484 /*TemplateArgs=*/nullptr, 3485 /*S*/nullptr); 3486 if (CtorArg.isInvalid()) 3487 return true; 3488 3489 // C++11 [class.copy]p15: 3490 // - if a member m has rvalue reference type T&&, it is direct-initialized 3491 // with static_cast<T&&>(x.m); 3492 if (RefersToRValueRef(CtorArg.get())) { 3493 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3494 } 3495 3496 // When the field we are copying is an array, create index variables for 3497 // each dimension of the array. We use these index variables to subscript 3498 // the source array, and other clients (e.g., CodeGen) will perform the 3499 // necessary iteration with these index variables. 3500 SmallVector<VarDecl *, 4> IndexVariables; 3501 QualType BaseType = Field->getType(); 3502 QualType SizeType = SemaRef.Context.getSizeType(); 3503 bool InitializingArray = false; 3504 while (const ConstantArrayType *Array 3505 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3506 InitializingArray = true; 3507 // Create the iteration variable for this array index. 3508 IdentifierInfo *IterationVarName = nullptr; 3509 { 3510 SmallString<8> Str; 3511 llvm::raw_svector_ostream OS(Str); 3512 OS << "__i" << IndexVariables.size(); 3513 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3514 } 3515 VarDecl *IterationVar 3516 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3517 IterationVarName, SizeType, 3518 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3519 SC_None); 3520 IndexVariables.push_back(IterationVar); 3521 3522 // Create a reference to the iteration variable. 3523 ExprResult IterationVarRef 3524 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3525 assert(!IterationVarRef.isInvalid() && 3526 "Reference to invented variable cannot fail!"); 3527 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3528 assert(!IterationVarRef.isInvalid() && 3529 "Conversion of invented variable cannot fail!"); 3530 3531 // Subscript the array with this iteration variable. 3532 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3533 IterationVarRef.get(), 3534 Loc); 3535 if (CtorArg.isInvalid()) 3536 return true; 3537 3538 BaseType = Array->getElementType(); 3539 } 3540 3541 // The array subscript expression is an lvalue, which is wrong for moving. 3542 if (Moving && InitializingArray) 3543 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3544 3545 // Construct the entity that we will be initializing. For an array, this 3546 // will be first element in the array, which may require several levels 3547 // of array-subscript entities. 3548 SmallVector<InitializedEntity, 4> Entities; 3549 Entities.reserve(1 + IndexVariables.size()); 3550 if (Indirect) 3551 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3552 else 3553 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3554 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3555 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3556 0, 3557 Entities.back())); 3558 3559 // Direct-initialize to use the copy constructor. 3560 InitializationKind InitKind = 3561 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3562 3563 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3564 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 3565 CtorArgE); 3566 3567 ExprResult MemberInit 3568 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3569 MultiExprArg(&CtorArgE, 1)); 3570 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3571 if (MemberInit.isInvalid()) 3572 return true; 3573 3574 if (Indirect) { 3575 assert(IndexVariables.size() == 0 && 3576 "Indirect field improperly initialized"); 3577 CXXMemberInit 3578 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3579 Loc, Loc, 3580 MemberInit.getAs<Expr>(), 3581 Loc); 3582 } else 3583 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3584 Loc, MemberInit.getAs<Expr>(), 3585 Loc, 3586 IndexVariables.data(), 3587 IndexVariables.size()); 3588 return false; 3589 } 3590 3591 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3592 "Unhandled implicit init kind!"); 3593 3594 QualType FieldBaseElementType = 3595 SemaRef.Context.getBaseElementType(Field->getType()); 3596 3597 if (FieldBaseElementType->isRecordType()) { 3598 InitializedEntity InitEntity 3599 = Indirect? InitializedEntity::InitializeMember(Indirect) 3600 : InitializedEntity::InitializeMember(Field); 3601 InitializationKind InitKind = 3602 InitializationKind::CreateDefault(Loc); 3603 3604 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3605 ExprResult MemberInit = 3606 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3607 3608 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3609 if (MemberInit.isInvalid()) 3610 return true; 3611 3612 if (Indirect) 3613 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3614 Indirect, Loc, 3615 Loc, 3616 MemberInit.get(), 3617 Loc); 3618 else 3619 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3620 Field, Loc, Loc, 3621 MemberInit.get(), 3622 Loc); 3623 return false; 3624 } 3625 3626 if (!Field->getParent()->isUnion()) { 3627 if (FieldBaseElementType->isReferenceType()) { 3628 SemaRef.Diag(Constructor->getLocation(), 3629 diag::err_uninitialized_member_in_ctor) 3630 << (int)Constructor->isImplicit() 3631 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3632 << 0 << Field->getDeclName(); 3633 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3634 return true; 3635 } 3636 3637 if (FieldBaseElementType.isConstQualified()) { 3638 SemaRef.Diag(Constructor->getLocation(), 3639 diag::err_uninitialized_member_in_ctor) 3640 << (int)Constructor->isImplicit() 3641 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3642 << 1 << Field->getDeclName(); 3643 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3644 return true; 3645 } 3646 } 3647 3648 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3649 FieldBaseElementType->isObjCRetainableType() && 3650 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3651 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3652 // ARC: 3653 // Default-initialize Objective-C pointers to NULL. 3654 CXXMemberInit 3655 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3656 Loc, Loc, 3657 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3658 Loc); 3659 return false; 3660 } 3661 3662 // Nothing to initialize. 3663 CXXMemberInit = nullptr; 3664 return false; 3665 } 3666 3667 namespace { 3668 struct BaseAndFieldInfo { 3669 Sema &S; 3670 CXXConstructorDecl *Ctor; 3671 bool AnyErrorsInInits; 3672 ImplicitInitializerKind IIK; 3673 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3674 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3675 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3676 3677 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3678 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3679 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3680 if (Generated && Ctor->isCopyConstructor()) 3681 IIK = IIK_Copy; 3682 else if (Generated && Ctor->isMoveConstructor()) 3683 IIK = IIK_Move; 3684 else if (Ctor->getInheritedConstructor()) 3685 IIK = IIK_Inherit; 3686 else 3687 IIK = IIK_Default; 3688 } 3689 3690 bool isImplicitCopyOrMove() const { 3691 switch (IIK) { 3692 case IIK_Copy: 3693 case IIK_Move: 3694 return true; 3695 3696 case IIK_Default: 3697 case IIK_Inherit: 3698 return false; 3699 } 3700 3701 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3702 } 3703 3704 bool addFieldInitializer(CXXCtorInitializer *Init) { 3705 AllToInit.push_back(Init); 3706 3707 // Check whether this initializer makes the field "used". 3708 if (Init->getInit()->HasSideEffects(S.Context)) 3709 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3710 3711 return false; 3712 } 3713 3714 bool isInactiveUnionMember(FieldDecl *Field) { 3715 RecordDecl *Record = Field->getParent(); 3716 if (!Record->isUnion()) 3717 return false; 3718 3719 if (FieldDecl *Active = 3720 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3721 return Active != Field->getCanonicalDecl(); 3722 3723 // In an implicit copy or move constructor, ignore any in-class initializer. 3724 if (isImplicitCopyOrMove()) 3725 return true; 3726 3727 // If there's no explicit initialization, the field is active only if it 3728 // has an in-class initializer... 3729 if (Field->hasInClassInitializer()) 3730 return false; 3731 // ... or it's an anonymous struct or union whose class has an in-class 3732 // initializer. 3733 if (!Field->isAnonymousStructOrUnion()) 3734 return true; 3735 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3736 return !FieldRD->hasInClassInitializer(); 3737 } 3738 3739 /// \brief Determine whether the given field is, or is within, a union member 3740 /// that is inactive (because there was an initializer given for a different 3741 /// member of the union, or because the union was not initialized at all). 3742 bool isWithinInactiveUnionMember(FieldDecl *Field, 3743 IndirectFieldDecl *Indirect) { 3744 if (!Indirect) 3745 return isInactiveUnionMember(Field); 3746 3747 for (auto *C : Indirect->chain()) { 3748 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3749 if (Field && isInactiveUnionMember(Field)) 3750 return true; 3751 } 3752 return false; 3753 } 3754 }; 3755 } 3756 3757 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3758 /// array type. 3759 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3760 if (T->isIncompleteArrayType()) 3761 return true; 3762 3763 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3764 if (!ArrayT->getSize()) 3765 return true; 3766 3767 T = ArrayT->getElementType(); 3768 } 3769 3770 return false; 3771 } 3772 3773 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3774 FieldDecl *Field, 3775 IndirectFieldDecl *Indirect = nullptr) { 3776 if (Field->isInvalidDecl()) 3777 return false; 3778 3779 // Overwhelmingly common case: we have a direct initializer for this field. 3780 if (CXXCtorInitializer *Init = 3781 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3782 return Info.addFieldInitializer(Init); 3783 3784 // C++11 [class.base.init]p8: 3785 // if the entity is a non-static data member that has a 3786 // brace-or-equal-initializer and either 3787 // -- the constructor's class is a union and no other variant member of that 3788 // union is designated by a mem-initializer-id or 3789 // -- the constructor's class is not a union, and, if the entity is a member 3790 // of an anonymous union, no other member of that union is designated by 3791 // a mem-initializer-id, 3792 // the entity is initialized as specified in [dcl.init]. 3793 // 3794 // We also apply the same rules to handle anonymous structs within anonymous 3795 // unions. 3796 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3797 return false; 3798 3799 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3800 ExprResult DIE = 3801 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3802 if (DIE.isInvalid()) 3803 return true; 3804 CXXCtorInitializer *Init; 3805 if (Indirect) 3806 Init = new (SemaRef.Context) 3807 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3808 SourceLocation(), DIE.get(), SourceLocation()); 3809 else 3810 Init = new (SemaRef.Context) 3811 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3812 SourceLocation(), DIE.get(), SourceLocation()); 3813 return Info.addFieldInitializer(Init); 3814 } 3815 3816 // Don't initialize incomplete or zero-length arrays. 3817 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3818 return false; 3819 3820 // Don't try to build an implicit initializer if there were semantic 3821 // errors in any of the initializers (and therefore we might be 3822 // missing some that the user actually wrote). 3823 if (Info.AnyErrorsInInits) 3824 return false; 3825 3826 CXXCtorInitializer *Init = nullptr; 3827 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3828 Indirect, Init)) 3829 return true; 3830 3831 if (!Init) 3832 return false; 3833 3834 return Info.addFieldInitializer(Init); 3835 } 3836 3837 bool 3838 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3839 CXXCtorInitializer *Initializer) { 3840 assert(Initializer->isDelegatingInitializer()); 3841 Constructor->setNumCtorInitializers(1); 3842 CXXCtorInitializer **initializer = 3843 new (Context) CXXCtorInitializer*[1]; 3844 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3845 Constructor->setCtorInitializers(initializer); 3846 3847 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3848 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3849 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3850 } 3851 3852 DelegatingCtorDecls.push_back(Constructor); 3853 3854 DiagnoseUninitializedFields(*this, Constructor); 3855 3856 return false; 3857 } 3858 3859 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3860 ArrayRef<CXXCtorInitializer *> Initializers) { 3861 if (Constructor->isDependentContext()) { 3862 // Just store the initializers as written, they will be checked during 3863 // instantiation. 3864 if (!Initializers.empty()) { 3865 Constructor->setNumCtorInitializers(Initializers.size()); 3866 CXXCtorInitializer **baseOrMemberInitializers = 3867 new (Context) CXXCtorInitializer*[Initializers.size()]; 3868 memcpy(baseOrMemberInitializers, Initializers.data(), 3869 Initializers.size() * sizeof(CXXCtorInitializer*)); 3870 Constructor->setCtorInitializers(baseOrMemberInitializers); 3871 } 3872 3873 // Let template instantiation know whether we had errors. 3874 if (AnyErrors) 3875 Constructor->setInvalidDecl(); 3876 3877 return false; 3878 } 3879 3880 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3881 3882 // We need to build the initializer AST according to order of construction 3883 // and not what user specified in the Initializers list. 3884 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3885 if (!ClassDecl) 3886 return true; 3887 3888 bool HadError = false; 3889 3890 for (unsigned i = 0; i < Initializers.size(); i++) { 3891 CXXCtorInitializer *Member = Initializers[i]; 3892 3893 if (Member->isBaseInitializer()) 3894 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3895 else { 3896 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3897 3898 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3899 for (auto *C : F->chain()) { 3900 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3901 if (FD && FD->getParent()->isUnion()) 3902 Info.ActiveUnionMember.insert(std::make_pair( 3903 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3904 } 3905 } else if (FieldDecl *FD = Member->getMember()) { 3906 if (FD->getParent()->isUnion()) 3907 Info.ActiveUnionMember.insert(std::make_pair( 3908 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3909 } 3910 } 3911 } 3912 3913 // Keep track of the direct virtual bases. 3914 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3915 for (auto &I : ClassDecl->bases()) { 3916 if (I.isVirtual()) 3917 DirectVBases.insert(&I); 3918 } 3919 3920 // Push virtual bases before others. 3921 for (auto &VBase : ClassDecl->vbases()) { 3922 if (CXXCtorInitializer *Value 3923 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3924 // [class.base.init]p7, per DR257: 3925 // A mem-initializer where the mem-initializer-id names a virtual base 3926 // class is ignored during execution of a constructor of any class that 3927 // is not the most derived class. 3928 if (ClassDecl->isAbstract()) { 3929 // FIXME: Provide a fixit to remove the base specifier. This requires 3930 // tracking the location of the associated comma for a base specifier. 3931 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3932 << VBase.getType() << ClassDecl; 3933 DiagnoseAbstractType(ClassDecl); 3934 } 3935 3936 Info.AllToInit.push_back(Value); 3937 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3938 // [class.base.init]p8, per DR257: 3939 // If a given [...] base class is not named by a mem-initializer-id 3940 // [...] and the entity is not a virtual base class of an abstract 3941 // class, then [...] the entity is default-initialized. 3942 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3943 CXXCtorInitializer *CXXBaseInit; 3944 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3945 &VBase, IsInheritedVirtualBase, 3946 CXXBaseInit)) { 3947 HadError = true; 3948 continue; 3949 } 3950 3951 Info.AllToInit.push_back(CXXBaseInit); 3952 } 3953 } 3954 3955 // Non-virtual bases. 3956 for (auto &Base : ClassDecl->bases()) { 3957 // Virtuals are in the virtual base list and already constructed. 3958 if (Base.isVirtual()) 3959 continue; 3960 3961 if (CXXCtorInitializer *Value 3962 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3963 Info.AllToInit.push_back(Value); 3964 } else if (!AnyErrors) { 3965 CXXCtorInitializer *CXXBaseInit; 3966 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3967 &Base, /*IsInheritedVirtualBase=*/false, 3968 CXXBaseInit)) { 3969 HadError = true; 3970 continue; 3971 } 3972 3973 Info.AllToInit.push_back(CXXBaseInit); 3974 } 3975 } 3976 3977 // Fields. 3978 for (auto *Mem : ClassDecl->decls()) { 3979 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3980 // C++ [class.bit]p2: 3981 // A declaration for a bit-field that omits the identifier declares an 3982 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3983 // initialized. 3984 if (F->isUnnamedBitfield()) 3985 continue; 3986 3987 // If we're not generating the implicit copy/move constructor, then we'll 3988 // handle anonymous struct/union fields based on their individual 3989 // indirect fields. 3990 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3991 continue; 3992 3993 if (CollectFieldInitializer(*this, Info, F)) 3994 HadError = true; 3995 continue; 3996 } 3997 3998 // Beyond this point, we only consider default initialization. 3999 if (Info.isImplicitCopyOrMove()) 4000 continue; 4001 4002 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4003 if (F->getType()->isIncompleteArrayType()) { 4004 assert(ClassDecl->hasFlexibleArrayMember() && 4005 "Incomplete array type is not valid"); 4006 continue; 4007 } 4008 4009 // Initialize each field of an anonymous struct individually. 4010 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4011 HadError = true; 4012 4013 continue; 4014 } 4015 } 4016 4017 unsigned NumInitializers = Info.AllToInit.size(); 4018 if (NumInitializers > 0) { 4019 Constructor->setNumCtorInitializers(NumInitializers); 4020 CXXCtorInitializer **baseOrMemberInitializers = 4021 new (Context) CXXCtorInitializer*[NumInitializers]; 4022 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4023 NumInitializers * sizeof(CXXCtorInitializer*)); 4024 Constructor->setCtorInitializers(baseOrMemberInitializers); 4025 4026 // Constructors implicitly reference the base and member 4027 // destructors. 4028 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4029 Constructor->getParent()); 4030 } 4031 4032 return HadError; 4033 } 4034 4035 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4036 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4037 const RecordDecl *RD = RT->getDecl(); 4038 if (RD->isAnonymousStructOrUnion()) { 4039 for (auto *Field : RD->fields()) 4040 PopulateKeysForFields(Field, IdealInits); 4041 return; 4042 } 4043 } 4044 IdealInits.push_back(Field->getCanonicalDecl()); 4045 } 4046 4047 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4048 return Context.getCanonicalType(BaseType).getTypePtr(); 4049 } 4050 4051 static const void *GetKeyForMember(ASTContext &Context, 4052 CXXCtorInitializer *Member) { 4053 if (!Member->isAnyMemberInitializer()) 4054 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4055 4056 return Member->getAnyMember()->getCanonicalDecl(); 4057 } 4058 4059 static void DiagnoseBaseOrMemInitializerOrder( 4060 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4061 ArrayRef<CXXCtorInitializer *> Inits) { 4062 if (Constructor->getDeclContext()->isDependentContext()) 4063 return; 4064 4065 // Don't check initializers order unless the warning is enabled at the 4066 // location of at least one initializer. 4067 bool ShouldCheckOrder = false; 4068 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4069 CXXCtorInitializer *Init = Inits[InitIndex]; 4070 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4071 Init->getSourceLocation())) { 4072 ShouldCheckOrder = true; 4073 break; 4074 } 4075 } 4076 if (!ShouldCheckOrder) 4077 return; 4078 4079 // Build the list of bases and members in the order that they'll 4080 // actually be initialized. The explicit initializers should be in 4081 // this same order but may be missing things. 4082 SmallVector<const void*, 32> IdealInitKeys; 4083 4084 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4085 4086 // 1. Virtual bases. 4087 for (const auto &VBase : ClassDecl->vbases()) 4088 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4089 4090 // 2. Non-virtual bases. 4091 for (const auto &Base : ClassDecl->bases()) { 4092 if (Base.isVirtual()) 4093 continue; 4094 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4095 } 4096 4097 // 3. Direct fields. 4098 for (auto *Field : ClassDecl->fields()) { 4099 if (Field->isUnnamedBitfield()) 4100 continue; 4101 4102 PopulateKeysForFields(Field, IdealInitKeys); 4103 } 4104 4105 unsigned NumIdealInits = IdealInitKeys.size(); 4106 unsigned IdealIndex = 0; 4107 4108 CXXCtorInitializer *PrevInit = nullptr; 4109 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4110 CXXCtorInitializer *Init = Inits[InitIndex]; 4111 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4112 4113 // Scan forward to try to find this initializer in the idealized 4114 // initializers list. 4115 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4116 if (InitKey == IdealInitKeys[IdealIndex]) 4117 break; 4118 4119 // If we didn't find this initializer, it must be because we 4120 // scanned past it on a previous iteration. That can only 4121 // happen if we're out of order; emit a warning. 4122 if (IdealIndex == NumIdealInits && PrevInit) { 4123 Sema::SemaDiagnosticBuilder D = 4124 SemaRef.Diag(PrevInit->getSourceLocation(), 4125 diag::warn_initializer_out_of_order); 4126 4127 if (PrevInit->isAnyMemberInitializer()) 4128 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4129 else 4130 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4131 4132 if (Init->isAnyMemberInitializer()) 4133 D << 0 << Init->getAnyMember()->getDeclName(); 4134 else 4135 D << 1 << Init->getTypeSourceInfo()->getType(); 4136 4137 // Move back to the initializer's location in the ideal list. 4138 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4139 if (InitKey == IdealInitKeys[IdealIndex]) 4140 break; 4141 4142 assert(IdealIndex < NumIdealInits && 4143 "initializer not found in initializer list"); 4144 } 4145 4146 PrevInit = Init; 4147 } 4148 } 4149 4150 namespace { 4151 bool CheckRedundantInit(Sema &S, 4152 CXXCtorInitializer *Init, 4153 CXXCtorInitializer *&PrevInit) { 4154 if (!PrevInit) { 4155 PrevInit = Init; 4156 return false; 4157 } 4158 4159 if (FieldDecl *Field = Init->getAnyMember()) 4160 S.Diag(Init->getSourceLocation(), 4161 diag::err_multiple_mem_initialization) 4162 << Field->getDeclName() 4163 << Init->getSourceRange(); 4164 else { 4165 const Type *BaseClass = Init->getBaseClass(); 4166 assert(BaseClass && "neither field nor base"); 4167 S.Diag(Init->getSourceLocation(), 4168 diag::err_multiple_base_initialization) 4169 << QualType(BaseClass, 0) 4170 << Init->getSourceRange(); 4171 } 4172 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4173 << 0 << PrevInit->getSourceRange(); 4174 4175 return true; 4176 } 4177 4178 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4179 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4180 4181 bool CheckRedundantUnionInit(Sema &S, 4182 CXXCtorInitializer *Init, 4183 RedundantUnionMap &Unions) { 4184 FieldDecl *Field = Init->getAnyMember(); 4185 RecordDecl *Parent = Field->getParent(); 4186 NamedDecl *Child = Field; 4187 4188 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4189 if (Parent->isUnion()) { 4190 UnionEntry &En = Unions[Parent]; 4191 if (En.first && En.first != Child) { 4192 S.Diag(Init->getSourceLocation(), 4193 diag::err_multiple_mem_union_initialization) 4194 << Field->getDeclName() 4195 << Init->getSourceRange(); 4196 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4197 << 0 << En.second->getSourceRange(); 4198 return true; 4199 } 4200 if (!En.first) { 4201 En.first = Child; 4202 En.second = Init; 4203 } 4204 if (!Parent->isAnonymousStructOrUnion()) 4205 return false; 4206 } 4207 4208 Child = Parent; 4209 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4210 } 4211 4212 return false; 4213 } 4214 } 4215 4216 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4217 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4218 SourceLocation ColonLoc, 4219 ArrayRef<CXXCtorInitializer*> MemInits, 4220 bool AnyErrors) { 4221 if (!ConstructorDecl) 4222 return; 4223 4224 AdjustDeclIfTemplate(ConstructorDecl); 4225 4226 CXXConstructorDecl *Constructor 4227 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4228 4229 if (!Constructor) { 4230 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4231 return; 4232 } 4233 4234 // Mapping for the duplicate initializers check. 4235 // For member initializers, this is keyed with a FieldDecl*. 4236 // For base initializers, this is keyed with a Type*. 4237 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4238 4239 // Mapping for the inconsistent anonymous-union initializers check. 4240 RedundantUnionMap MemberUnions; 4241 4242 bool HadError = false; 4243 for (unsigned i = 0; i < MemInits.size(); i++) { 4244 CXXCtorInitializer *Init = MemInits[i]; 4245 4246 // Set the source order index. 4247 Init->setSourceOrder(i); 4248 4249 if (Init->isAnyMemberInitializer()) { 4250 const void *Key = GetKeyForMember(Context, Init); 4251 if (CheckRedundantInit(*this, Init, Members[Key]) || 4252 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4253 HadError = true; 4254 } else if (Init->isBaseInitializer()) { 4255 const void *Key = GetKeyForMember(Context, Init); 4256 if (CheckRedundantInit(*this, Init, Members[Key])) 4257 HadError = true; 4258 } else { 4259 assert(Init->isDelegatingInitializer()); 4260 // This must be the only initializer 4261 if (MemInits.size() != 1) { 4262 Diag(Init->getSourceLocation(), 4263 diag::err_delegating_initializer_alone) 4264 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4265 // We will treat this as being the only initializer. 4266 } 4267 SetDelegatingInitializer(Constructor, MemInits[i]); 4268 // Return immediately as the initializer is set. 4269 return; 4270 } 4271 } 4272 4273 if (HadError) 4274 return; 4275 4276 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4277 4278 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4279 4280 DiagnoseUninitializedFields(*this, Constructor); 4281 } 4282 4283 void 4284 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4285 CXXRecordDecl *ClassDecl) { 4286 // Ignore dependent contexts. Also ignore unions, since their members never 4287 // have destructors implicitly called. 4288 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4289 return; 4290 4291 // FIXME: all the access-control diagnostics are positioned on the 4292 // field/base declaration. That's probably good; that said, the 4293 // user might reasonably want to know why the destructor is being 4294 // emitted, and we currently don't say. 4295 4296 // Non-static data members. 4297 for (auto *Field : ClassDecl->fields()) { 4298 if (Field->isInvalidDecl()) 4299 continue; 4300 4301 // Don't destroy incomplete or zero-length arrays. 4302 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4303 continue; 4304 4305 QualType FieldType = Context.getBaseElementType(Field->getType()); 4306 4307 const RecordType* RT = FieldType->getAs<RecordType>(); 4308 if (!RT) 4309 continue; 4310 4311 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4312 if (FieldClassDecl->isInvalidDecl()) 4313 continue; 4314 if (FieldClassDecl->hasIrrelevantDestructor()) 4315 continue; 4316 // The destructor for an implicit anonymous union member is never invoked. 4317 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4318 continue; 4319 4320 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4321 assert(Dtor && "No dtor found for FieldClassDecl!"); 4322 CheckDestructorAccess(Field->getLocation(), Dtor, 4323 PDiag(diag::err_access_dtor_field) 4324 << Field->getDeclName() 4325 << FieldType); 4326 4327 MarkFunctionReferenced(Location, Dtor); 4328 DiagnoseUseOfDecl(Dtor, Location); 4329 } 4330 4331 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4332 4333 // Bases. 4334 for (const auto &Base : ClassDecl->bases()) { 4335 // Bases are always records in a well-formed non-dependent class. 4336 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4337 4338 // Remember direct virtual bases. 4339 if (Base.isVirtual()) 4340 DirectVirtualBases.insert(RT); 4341 4342 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4343 // If our base class is invalid, we probably can't get its dtor anyway. 4344 if (BaseClassDecl->isInvalidDecl()) 4345 continue; 4346 if (BaseClassDecl->hasIrrelevantDestructor()) 4347 continue; 4348 4349 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4350 assert(Dtor && "No dtor found for BaseClassDecl!"); 4351 4352 // FIXME: caret should be on the start of the class name 4353 CheckDestructorAccess(Base.getLocStart(), Dtor, 4354 PDiag(diag::err_access_dtor_base) 4355 << Base.getType() 4356 << Base.getSourceRange(), 4357 Context.getTypeDeclType(ClassDecl)); 4358 4359 MarkFunctionReferenced(Location, Dtor); 4360 DiagnoseUseOfDecl(Dtor, Location); 4361 } 4362 4363 // Virtual bases. 4364 for (const auto &VBase : ClassDecl->vbases()) { 4365 // Bases are always records in a well-formed non-dependent class. 4366 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4367 4368 // Ignore direct virtual bases. 4369 if (DirectVirtualBases.count(RT)) 4370 continue; 4371 4372 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4373 // If our base class is invalid, we probably can't get its dtor anyway. 4374 if (BaseClassDecl->isInvalidDecl()) 4375 continue; 4376 if (BaseClassDecl->hasIrrelevantDestructor()) 4377 continue; 4378 4379 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4380 assert(Dtor && "No dtor found for BaseClassDecl!"); 4381 if (CheckDestructorAccess( 4382 ClassDecl->getLocation(), Dtor, 4383 PDiag(diag::err_access_dtor_vbase) 4384 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4385 Context.getTypeDeclType(ClassDecl)) == 4386 AR_accessible) { 4387 CheckDerivedToBaseConversion( 4388 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4389 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4390 SourceRange(), DeclarationName(), nullptr); 4391 } 4392 4393 MarkFunctionReferenced(Location, Dtor); 4394 DiagnoseUseOfDecl(Dtor, Location); 4395 } 4396 } 4397 4398 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4399 if (!CDtorDecl) 4400 return; 4401 4402 if (CXXConstructorDecl *Constructor 4403 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4404 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4405 DiagnoseUninitializedFields(*this, Constructor); 4406 } 4407 } 4408 4409 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4410 unsigned DiagID, AbstractDiagSelID SelID) { 4411 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4412 unsigned DiagID; 4413 AbstractDiagSelID SelID; 4414 4415 public: 4416 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4417 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4418 4419 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4420 if (Suppressed) return; 4421 if (SelID == -1) 4422 S.Diag(Loc, DiagID) << T; 4423 else 4424 S.Diag(Loc, DiagID) << SelID << T; 4425 } 4426 } Diagnoser(DiagID, SelID); 4427 4428 return RequireNonAbstractType(Loc, T, Diagnoser); 4429 } 4430 4431 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4432 TypeDiagnoser &Diagnoser) { 4433 if (!getLangOpts().CPlusPlus) 4434 return false; 4435 4436 if (const ArrayType *AT = Context.getAsArrayType(T)) 4437 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4438 4439 if (const PointerType *PT = T->getAs<PointerType>()) { 4440 // Find the innermost pointer type. 4441 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4442 PT = T; 4443 4444 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4445 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4446 } 4447 4448 const RecordType *RT = T->getAs<RecordType>(); 4449 if (!RT) 4450 return false; 4451 4452 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4453 4454 // We can't answer whether something is abstract until it has a 4455 // definition. If it's currently being defined, we'll walk back 4456 // over all the declarations when we have a full definition. 4457 const CXXRecordDecl *Def = RD->getDefinition(); 4458 if (!Def || Def->isBeingDefined()) 4459 return false; 4460 4461 if (!RD->isAbstract()) 4462 return false; 4463 4464 Diagnoser.diagnose(*this, Loc, T); 4465 DiagnoseAbstractType(RD); 4466 4467 return true; 4468 } 4469 4470 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4471 // Check if we've already emitted the list of pure virtual functions 4472 // for this class. 4473 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4474 return; 4475 4476 // If the diagnostic is suppressed, don't emit the notes. We're only 4477 // going to emit them once, so try to attach them to a diagnostic we're 4478 // actually going to show. 4479 if (Diags.isLastDiagnosticIgnored()) 4480 return; 4481 4482 CXXFinalOverriderMap FinalOverriders; 4483 RD->getFinalOverriders(FinalOverriders); 4484 4485 // Keep a set of seen pure methods so we won't diagnose the same method 4486 // more than once. 4487 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4488 4489 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4490 MEnd = FinalOverriders.end(); 4491 M != MEnd; 4492 ++M) { 4493 for (OverridingMethods::iterator SO = M->second.begin(), 4494 SOEnd = M->second.end(); 4495 SO != SOEnd; ++SO) { 4496 // C++ [class.abstract]p4: 4497 // A class is abstract if it contains or inherits at least one 4498 // pure virtual function for which the final overrider is pure 4499 // virtual. 4500 4501 // 4502 if (SO->second.size() != 1) 4503 continue; 4504 4505 if (!SO->second.front().Method->isPure()) 4506 continue; 4507 4508 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4509 continue; 4510 4511 Diag(SO->second.front().Method->getLocation(), 4512 diag::note_pure_virtual_function) 4513 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4514 } 4515 } 4516 4517 if (!PureVirtualClassDiagSet) 4518 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4519 PureVirtualClassDiagSet->insert(RD); 4520 } 4521 4522 namespace { 4523 struct AbstractUsageInfo { 4524 Sema &S; 4525 CXXRecordDecl *Record; 4526 CanQualType AbstractType; 4527 bool Invalid; 4528 4529 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4530 : S(S), Record(Record), 4531 AbstractType(S.Context.getCanonicalType( 4532 S.Context.getTypeDeclType(Record))), 4533 Invalid(false) {} 4534 4535 void DiagnoseAbstractType() { 4536 if (Invalid) return; 4537 S.DiagnoseAbstractType(Record); 4538 Invalid = true; 4539 } 4540 4541 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4542 }; 4543 4544 struct CheckAbstractUsage { 4545 AbstractUsageInfo &Info; 4546 const NamedDecl *Ctx; 4547 4548 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4549 : Info(Info), Ctx(Ctx) {} 4550 4551 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4552 switch (TL.getTypeLocClass()) { 4553 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4554 #define TYPELOC(CLASS, PARENT) \ 4555 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4556 #include "clang/AST/TypeLocNodes.def" 4557 } 4558 } 4559 4560 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4561 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4562 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4563 if (!TL.getParam(I)) 4564 continue; 4565 4566 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4567 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4568 } 4569 } 4570 4571 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4572 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4573 } 4574 4575 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4576 // Visit the type parameters from a permissive context. 4577 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4578 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4579 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4580 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4581 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4582 // TODO: other template argument types? 4583 } 4584 } 4585 4586 // Visit pointee types from a permissive context. 4587 #define CheckPolymorphic(Type) \ 4588 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4589 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4590 } 4591 CheckPolymorphic(PointerTypeLoc) 4592 CheckPolymorphic(ReferenceTypeLoc) 4593 CheckPolymorphic(MemberPointerTypeLoc) 4594 CheckPolymorphic(BlockPointerTypeLoc) 4595 CheckPolymorphic(AtomicTypeLoc) 4596 4597 /// Handle all the types we haven't given a more specific 4598 /// implementation for above. 4599 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4600 // Every other kind of type that we haven't called out already 4601 // that has an inner type is either (1) sugar or (2) contains that 4602 // inner type in some way as a subobject. 4603 if (TypeLoc Next = TL.getNextTypeLoc()) 4604 return Visit(Next, Sel); 4605 4606 // If there's no inner type and we're in a permissive context, 4607 // don't diagnose. 4608 if (Sel == Sema::AbstractNone) return; 4609 4610 // Check whether the type matches the abstract type. 4611 QualType T = TL.getType(); 4612 if (T->isArrayType()) { 4613 Sel = Sema::AbstractArrayType; 4614 T = Info.S.Context.getBaseElementType(T); 4615 } 4616 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4617 if (CT != Info.AbstractType) return; 4618 4619 // It matched; do some magic. 4620 if (Sel == Sema::AbstractArrayType) { 4621 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4622 << T << TL.getSourceRange(); 4623 } else { 4624 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4625 << Sel << T << TL.getSourceRange(); 4626 } 4627 Info.DiagnoseAbstractType(); 4628 } 4629 }; 4630 4631 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4632 Sema::AbstractDiagSelID Sel) { 4633 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4634 } 4635 4636 } 4637 4638 /// Check for invalid uses of an abstract type in a method declaration. 4639 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4640 CXXMethodDecl *MD) { 4641 // No need to do the check on definitions, which require that 4642 // the return/param types be complete. 4643 if (MD->doesThisDeclarationHaveABody()) 4644 return; 4645 4646 // For safety's sake, just ignore it if we don't have type source 4647 // information. This should never happen for non-implicit methods, 4648 // but... 4649 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4650 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4651 } 4652 4653 /// Check for invalid uses of an abstract type within a class definition. 4654 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4655 CXXRecordDecl *RD) { 4656 for (auto *D : RD->decls()) { 4657 if (D->isImplicit()) continue; 4658 4659 // Methods and method templates. 4660 if (isa<CXXMethodDecl>(D)) { 4661 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4662 } else if (isa<FunctionTemplateDecl>(D)) { 4663 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4664 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4665 4666 // Fields and static variables. 4667 } else if (isa<FieldDecl>(D)) { 4668 FieldDecl *FD = cast<FieldDecl>(D); 4669 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4670 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4671 } else if (isa<VarDecl>(D)) { 4672 VarDecl *VD = cast<VarDecl>(D); 4673 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4674 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4675 4676 // Nested classes and class templates. 4677 } else if (isa<CXXRecordDecl>(D)) { 4678 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4679 } else if (isa<ClassTemplateDecl>(D)) { 4680 CheckAbstractClassUsage(Info, 4681 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4682 } 4683 } 4684 } 4685 4686 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 4687 Attr *ClassAttr = getDLLAttr(Class); 4688 if (!ClassAttr) 4689 return; 4690 4691 assert(ClassAttr->getKind() == attr::DLLExport); 4692 4693 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4694 4695 if (TSK == TSK_ExplicitInstantiationDeclaration) 4696 // Don't go any further if this is just an explicit instantiation 4697 // declaration. 4698 return; 4699 4700 for (Decl *Member : Class->decls()) { 4701 auto *MD = dyn_cast<CXXMethodDecl>(Member); 4702 if (!MD) 4703 continue; 4704 4705 if (Member->getAttr<DLLExportAttr>()) { 4706 if (MD->isUserProvided()) { 4707 // Instantiate non-default class member functions ... 4708 4709 // .. except for certain kinds of template specializations. 4710 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4711 continue; 4712 4713 S.MarkFunctionReferenced(Class->getLocation(), MD); 4714 4715 // The function will be passed to the consumer when its definition is 4716 // encountered. 4717 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4718 MD->isCopyAssignmentOperator() || 4719 MD->isMoveAssignmentOperator()) { 4720 // Synthesize and instantiate non-trivial implicit methods, explicitly 4721 // defaulted methods, and the copy and move assignment operators. The 4722 // latter are exported even if they are trivial, because the address of 4723 // an operator can be taken and should compare equal accross libraries. 4724 DiagnosticErrorTrap Trap(S.Diags); 4725 S.MarkFunctionReferenced(Class->getLocation(), MD); 4726 if (Trap.hasErrorOccurred()) { 4727 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 4728 << Class->getName() << !S.getLangOpts().CPlusPlus11; 4729 break; 4730 } 4731 4732 // There is no later point when we will see the definition of this 4733 // function, so pass it to the consumer now. 4734 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 4735 } 4736 } 4737 } 4738 } 4739 4740 /// \brief Check class-level dllimport/dllexport attribute. 4741 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 4742 Attr *ClassAttr = getDLLAttr(Class); 4743 4744 // MSVC inherits DLL attributes to partial class template specializations. 4745 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4746 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4747 if (Attr *TemplateAttr = 4748 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4749 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 4750 A->setInherited(true); 4751 ClassAttr = A; 4752 } 4753 } 4754 } 4755 4756 if (!ClassAttr) 4757 return; 4758 4759 if (!Class->isExternallyVisible()) { 4760 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4761 << Class << ClassAttr; 4762 return; 4763 } 4764 4765 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 4766 !ClassAttr->isInherited()) { 4767 // Diagnose dll attributes on members of class with dll attribute. 4768 for (Decl *Member : Class->decls()) { 4769 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4770 continue; 4771 InheritableAttr *MemberAttr = getDLLAttr(Member); 4772 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4773 continue; 4774 4775 Diag(MemberAttr->getLocation(), 4776 diag::err_attribute_dll_member_of_dll_class) 4777 << MemberAttr << ClassAttr; 4778 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4779 Member->setInvalidDecl(); 4780 } 4781 } 4782 4783 if (Class->getDescribedClassTemplate()) 4784 // Don't inherit dll attribute until the template is instantiated. 4785 return; 4786 4787 // The class is either imported or exported. 4788 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4789 const bool ClassImported = !ClassExported; 4790 4791 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4792 4793 // Ignore explicit dllexport on explicit class template instantiation declarations. 4794 if (ClassExported && !ClassAttr->isInherited() && 4795 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 4843 if (ClassExported) 4844 DelayedDllExportClasses.push_back(Class); 4845 } 4846 4847 /// \brief Perform propagation of DLL attributes from a derived class to a 4848 /// templated base class for MS compatibility. 4849 void Sema::propagateDLLAttrToBaseClassTemplate( 4850 CXXRecordDecl *Class, Attr *ClassAttr, 4851 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 4852 if (getDLLAttr( 4853 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 4854 // If the base class template has a DLL attribute, don't try to change it. 4855 return; 4856 } 4857 4858 auto TSK = BaseTemplateSpec->getSpecializationKind(); 4859 if (!getDLLAttr(BaseTemplateSpec) && 4860 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 4861 TSK == TSK_ImplicitInstantiation)) { 4862 // The template hasn't been instantiated yet (or it has, but only as an 4863 // explicit instantiation declaration or implicit instantiation, which means 4864 // we haven't codegenned any members yet), so propagate the attribute. 4865 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 4866 NewAttr->setInherited(true); 4867 BaseTemplateSpec->addAttr(NewAttr); 4868 4869 // If the template is already instantiated, checkDLLAttributeRedeclaration() 4870 // needs to be run again to work see the new attribute. Otherwise this will 4871 // get run whenever the template is instantiated. 4872 if (TSK != TSK_Undeclared) 4873 checkClassLevelDLLAttribute(BaseTemplateSpec); 4874 4875 return; 4876 } 4877 4878 if (getDLLAttr(BaseTemplateSpec)) { 4879 // The template has already been specialized or instantiated with an 4880 // attribute, explicitly or through propagation. We should not try to change 4881 // it. 4882 return; 4883 } 4884 4885 // The template was previously instantiated or explicitly specialized without 4886 // a dll attribute, It's too late for us to add an attribute, so warn that 4887 // this is unsupported. 4888 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 4889 << BaseTemplateSpec->isExplicitSpecialization(); 4890 Diag(ClassAttr->getLocation(), diag::note_attribute); 4891 if (BaseTemplateSpec->isExplicitSpecialization()) { 4892 Diag(BaseTemplateSpec->getLocation(), 4893 diag::note_template_class_explicit_specialization_was_here) 4894 << BaseTemplateSpec; 4895 } else { 4896 Diag(BaseTemplateSpec->getPointOfInstantiation(), 4897 diag::note_template_class_instantiation_was_here) 4898 << BaseTemplateSpec; 4899 } 4900 } 4901 4902 /// \brief Perform semantic checks on a class definition that has been 4903 /// completing, introducing implicitly-declared members, checking for 4904 /// abstract types, etc. 4905 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4906 if (!Record) 4907 return; 4908 4909 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4910 AbstractUsageInfo Info(*this, Record); 4911 CheckAbstractClassUsage(Info, Record); 4912 } 4913 4914 // If this is not an aggregate type and has no user-declared constructor, 4915 // complain about any non-static data members of reference or const scalar 4916 // type, since they will never get initializers. 4917 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4918 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4919 !Record->isLambda()) { 4920 bool Complained = false; 4921 for (const auto *F : Record->fields()) { 4922 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4923 continue; 4924 4925 if (F->getType()->isReferenceType() || 4926 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4927 if (!Complained) { 4928 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4929 << Record->getTagKind() << Record; 4930 Complained = true; 4931 } 4932 4933 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4934 << F->getType()->isReferenceType() 4935 << F->getDeclName(); 4936 } 4937 } 4938 } 4939 4940 if (Record->getIdentifier()) { 4941 // C++ [class.mem]p13: 4942 // If T is the name of a class, then each of the following shall have a 4943 // name different from T: 4944 // - every member of every anonymous union that is a member of class T. 4945 // 4946 // C++ [class.mem]p14: 4947 // In addition, if class T has a user-declared constructor (12.1), every 4948 // non-static data member of class T shall have a name different from T. 4949 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4950 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4951 ++I) { 4952 NamedDecl *D = *I; 4953 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4954 isa<IndirectFieldDecl>(D)) { 4955 Diag(D->getLocation(), diag::err_member_name_of_class) 4956 << D->getDeclName(); 4957 break; 4958 } 4959 } 4960 } 4961 4962 // Warn if the class has virtual methods but non-virtual public destructor. 4963 if (Record->isPolymorphic() && !Record->isDependentType()) { 4964 CXXDestructorDecl *dtor = Record->getDestructor(); 4965 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4966 !Record->hasAttr<FinalAttr>()) 4967 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4968 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4969 } 4970 4971 if (Record->isAbstract()) { 4972 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4973 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4974 << FA->isSpelledAsSealed(); 4975 DiagnoseAbstractType(Record); 4976 } 4977 } 4978 4979 bool HasMethodWithOverrideControl = false, 4980 HasOverridingMethodWithoutOverrideControl = false; 4981 if (!Record->isDependentType()) { 4982 for (auto *M : Record->methods()) { 4983 // See if a method overloads virtual methods in a base 4984 // class without overriding any. 4985 if (!M->isStatic()) 4986 DiagnoseHiddenVirtualMethods(M); 4987 if (M->hasAttr<OverrideAttr>()) 4988 HasMethodWithOverrideControl = true; 4989 else if (M->size_overridden_methods() > 0) 4990 HasOverridingMethodWithoutOverrideControl = true; 4991 // Check whether the explicitly-defaulted special members are valid. 4992 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4993 CheckExplicitlyDefaultedSpecialMember(M); 4994 4995 // For an explicitly defaulted or deleted special member, we defer 4996 // determining triviality until the class is complete. That time is now! 4997 if (!M->isImplicit() && !M->isUserProvided()) { 4998 CXXSpecialMember CSM = getSpecialMember(M); 4999 if (CSM != CXXInvalid) { 5000 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5001 5002 // Inform the class that we've finished declaring this member. 5003 Record->finishedDefaultedOrDeletedMember(M); 5004 } 5005 } 5006 } 5007 } 5008 5009 if (HasMethodWithOverrideControl && 5010 HasOverridingMethodWithoutOverrideControl) { 5011 // At least one method has the 'override' control declared. 5012 // Diagnose all other overridden methods which do not have 'override' specified on them. 5013 for (auto *M : Record->methods()) 5014 DiagnoseAbsenceOfOverrideControl(M); 5015 } 5016 5017 // ms_struct is a request to use the same ABI rules as MSVC. Check 5018 // whether this class uses any C++ features that are implemented 5019 // completely differently in MSVC, and if so, emit a diagnostic. 5020 // That diagnostic defaults to an error, but we allow projects to 5021 // map it down to a warning (or ignore it). It's a fairly common 5022 // practice among users of the ms_struct pragma to mass-annotate 5023 // headers, sweeping up a bunch of types that the project doesn't 5024 // really rely on MSVC-compatible layout for. We must therefore 5025 // support "ms_struct except for C++ stuff" as a secondary ABI. 5026 if (Record->isMsStruct(Context) && 5027 (Record->isPolymorphic() || Record->getNumBases())) { 5028 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5029 } 5030 5031 // Declare inheriting constructors. We do this eagerly here because: 5032 // - The standard requires an eager diagnostic for conflicting inheriting 5033 // constructors from different classes. 5034 // - The lazy declaration of the other implicit constructors is so as to not 5035 // waste space and performance on classes that are not meant to be 5036 // instantiated (e.g. meta-functions). This doesn't apply to classes that 5037 // have inheriting constructors. 5038 DeclareInheritingConstructors(Record); 5039 5040 checkClassLevelDLLAttribute(Record); 5041 } 5042 5043 /// Look up the special member function that would be called by a special 5044 /// member function for a subobject of class type. 5045 /// 5046 /// \param Class The class type of the subobject. 5047 /// \param CSM The kind of special member function. 5048 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5049 /// \param ConstRHS True if this is a copy operation with a const object 5050 /// on its RHS, that is, if the argument to the outer special member 5051 /// function is 'const' and this is not a field marked 'mutable'. 5052 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 5053 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5054 unsigned FieldQuals, bool ConstRHS) { 5055 unsigned LHSQuals = 0; 5056 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5057 LHSQuals = FieldQuals; 5058 5059 unsigned RHSQuals = FieldQuals; 5060 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5061 RHSQuals = 0; 5062 else if (ConstRHS) 5063 RHSQuals |= Qualifiers::Const; 5064 5065 return S.LookupSpecialMember(Class, CSM, 5066 RHSQuals & Qualifiers::Const, 5067 RHSQuals & Qualifiers::Volatile, 5068 false, 5069 LHSQuals & Qualifiers::Const, 5070 LHSQuals & Qualifiers::Volatile); 5071 } 5072 5073 /// Is the special member function which would be selected to perform the 5074 /// specified operation on the specified class type a constexpr constructor? 5075 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5076 Sema::CXXSpecialMember CSM, 5077 unsigned Quals, bool ConstRHS) { 5078 Sema::SpecialMemberOverloadResult *SMOR = 5079 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5080 if (!SMOR || !SMOR->getMethod()) 5081 // A constructor we wouldn't select can't be "involved in initializing" 5082 // anything. 5083 return true; 5084 return SMOR->getMethod()->isConstexpr(); 5085 } 5086 5087 /// Determine whether the specified special member function would be constexpr 5088 /// if it were implicitly defined. 5089 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5090 Sema::CXXSpecialMember CSM, 5091 bool ConstArg) { 5092 if (!S.getLangOpts().CPlusPlus11) 5093 return false; 5094 5095 // C++11 [dcl.constexpr]p4: 5096 // In the definition of a constexpr constructor [...] 5097 bool Ctor = true; 5098 switch (CSM) { 5099 case Sema::CXXDefaultConstructor: 5100 // Since default constructor lookup is essentially trivial (and cannot 5101 // involve, for instance, template instantiation), we compute whether a 5102 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5103 // 5104 // This is important for performance; we need to know whether the default 5105 // constructor is constexpr to determine whether the type is a literal type. 5106 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5107 5108 case Sema::CXXCopyConstructor: 5109 case Sema::CXXMoveConstructor: 5110 // For copy or move constructors, we need to perform overload resolution. 5111 break; 5112 5113 case Sema::CXXCopyAssignment: 5114 case Sema::CXXMoveAssignment: 5115 if (!S.getLangOpts().CPlusPlus14) 5116 return false; 5117 // In C++1y, we need to perform overload resolution. 5118 Ctor = false; 5119 break; 5120 5121 case Sema::CXXDestructor: 5122 case Sema::CXXInvalid: 5123 return false; 5124 } 5125 5126 // -- if the class is a non-empty union, or for each non-empty anonymous 5127 // union member of a non-union class, exactly one non-static data member 5128 // shall be initialized; [DR1359] 5129 // 5130 // If we squint, this is guaranteed, since exactly one non-static data member 5131 // will be initialized (if the constructor isn't deleted), we just don't know 5132 // which one. 5133 if (Ctor && ClassDecl->isUnion()) 5134 return true; 5135 5136 // -- the class shall not have any virtual base classes; 5137 if (Ctor && ClassDecl->getNumVBases()) 5138 return false; 5139 5140 // C++1y [class.copy]p26: 5141 // -- [the class] is a literal type, and 5142 if (!Ctor && !ClassDecl->isLiteral()) 5143 return false; 5144 5145 // -- every constructor involved in initializing [...] base class 5146 // sub-objects shall be a constexpr constructor; 5147 // -- the assignment operator selected to copy/move each direct base 5148 // class is a constexpr function, and 5149 for (const auto &B : ClassDecl->bases()) { 5150 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5151 if (!BaseType) continue; 5152 5153 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5154 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5155 return false; 5156 } 5157 5158 // -- every constructor involved in initializing non-static data members 5159 // [...] shall be a constexpr constructor; 5160 // -- every non-static data member and base class sub-object shall be 5161 // initialized 5162 // -- for each non-static data member of X that is of class type (or array 5163 // thereof), the assignment operator selected to copy/move that member is 5164 // a constexpr function 5165 for (const auto *F : ClassDecl->fields()) { 5166 if (F->isInvalidDecl()) 5167 continue; 5168 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5169 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5170 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5171 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5172 BaseType.getCVRQualifiers(), 5173 ConstArg && !F->isMutable())) 5174 return false; 5175 } 5176 } 5177 5178 // All OK, it's constexpr! 5179 return true; 5180 } 5181 5182 static Sema::ImplicitExceptionSpecification 5183 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5184 switch (S.getSpecialMember(MD)) { 5185 case Sema::CXXDefaultConstructor: 5186 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5187 case Sema::CXXCopyConstructor: 5188 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5189 case Sema::CXXCopyAssignment: 5190 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5191 case Sema::CXXMoveConstructor: 5192 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5193 case Sema::CXXMoveAssignment: 5194 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5195 case Sema::CXXDestructor: 5196 return S.ComputeDefaultedDtorExceptionSpec(MD); 5197 case Sema::CXXInvalid: 5198 break; 5199 } 5200 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5201 "only special members have implicit exception specs"); 5202 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5203 } 5204 5205 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5206 CXXMethodDecl *MD) { 5207 FunctionProtoType::ExtProtoInfo EPI; 5208 5209 // Build an exception specification pointing back at this member. 5210 EPI.ExceptionSpec.Type = EST_Unevaluated; 5211 EPI.ExceptionSpec.SourceDecl = MD; 5212 5213 // Set the calling convention to the default for C++ instance methods. 5214 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5215 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5216 /*IsCXXMethod=*/true)); 5217 return EPI; 5218 } 5219 5220 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5221 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5222 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5223 return; 5224 5225 // Evaluate the exception specification. 5226 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5227 5228 // Update the type of the special member to use it. 5229 UpdateExceptionSpec(MD, ESI); 5230 5231 // A user-provided destructor can be defined outside the class. When that 5232 // happens, be sure to update the exception specification on both 5233 // declarations. 5234 const FunctionProtoType *CanonicalFPT = 5235 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5236 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5237 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5238 } 5239 5240 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5241 CXXRecordDecl *RD = MD->getParent(); 5242 CXXSpecialMember CSM = getSpecialMember(MD); 5243 5244 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5245 "not an explicitly-defaulted special member"); 5246 5247 // Whether this was the first-declared instance of the constructor. 5248 // This affects whether we implicitly add an exception spec and constexpr. 5249 bool First = MD == MD->getCanonicalDecl(); 5250 5251 bool HadError = false; 5252 5253 // C++11 [dcl.fct.def.default]p1: 5254 // A function that is explicitly defaulted shall 5255 // -- be a special member function (checked elsewhere), 5256 // -- have the same type (except for ref-qualifiers, and except that a 5257 // copy operation can take a non-const reference) as an implicit 5258 // declaration, and 5259 // -- not have default arguments. 5260 unsigned ExpectedParams = 1; 5261 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5262 ExpectedParams = 0; 5263 if (MD->getNumParams() != ExpectedParams) { 5264 // This also checks for default arguments: a copy or move constructor with a 5265 // default argument is classified as a default constructor, and assignment 5266 // operations and destructors can't have default arguments. 5267 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5268 << CSM << MD->getSourceRange(); 5269 HadError = true; 5270 } else if (MD->isVariadic()) { 5271 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5272 << CSM << MD->getSourceRange(); 5273 HadError = true; 5274 } 5275 5276 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5277 5278 bool CanHaveConstParam = false; 5279 if (CSM == CXXCopyConstructor) 5280 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5281 else if (CSM == CXXCopyAssignment) 5282 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5283 5284 QualType ReturnType = Context.VoidTy; 5285 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5286 // Check for return type matching. 5287 ReturnType = Type->getReturnType(); 5288 QualType ExpectedReturnType = 5289 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5290 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5291 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5292 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5293 HadError = true; 5294 } 5295 5296 // A defaulted special member cannot have cv-qualifiers. 5297 if (Type->getTypeQuals()) { 5298 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5299 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5300 HadError = true; 5301 } 5302 } 5303 5304 // Check for parameter type matching. 5305 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5306 bool HasConstParam = false; 5307 if (ExpectedParams && ArgType->isReferenceType()) { 5308 // Argument must be reference to possibly-const T. 5309 QualType ReferentType = ArgType->getPointeeType(); 5310 HasConstParam = ReferentType.isConstQualified(); 5311 5312 if (ReferentType.isVolatileQualified()) { 5313 Diag(MD->getLocation(), 5314 diag::err_defaulted_special_member_volatile_param) << CSM; 5315 HadError = true; 5316 } 5317 5318 if (HasConstParam && !CanHaveConstParam) { 5319 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5320 Diag(MD->getLocation(), 5321 diag::err_defaulted_special_member_copy_const_param) 5322 << (CSM == CXXCopyAssignment); 5323 // FIXME: Explain why this special member can't be const. 5324 } else { 5325 Diag(MD->getLocation(), 5326 diag::err_defaulted_special_member_move_const_param) 5327 << (CSM == CXXMoveAssignment); 5328 } 5329 HadError = true; 5330 } 5331 } else if (ExpectedParams) { 5332 // A copy assignment operator can take its argument by value, but a 5333 // defaulted one cannot. 5334 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5335 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5336 HadError = true; 5337 } 5338 5339 // C++11 [dcl.fct.def.default]p2: 5340 // An explicitly-defaulted function may be declared constexpr only if it 5341 // would have been implicitly declared as constexpr, 5342 // Do not apply this rule to members of class templates, since core issue 1358 5343 // makes such functions always instantiate to constexpr functions. For 5344 // functions which cannot be constexpr (for non-constructors in C++11 and for 5345 // destructors in C++1y), this is checked elsewhere. 5346 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5347 HasConstParam); 5348 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5349 : isa<CXXConstructorDecl>(MD)) && 5350 MD->isConstexpr() && !Constexpr && 5351 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5352 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5353 // FIXME: Explain why the special member can't be constexpr. 5354 HadError = true; 5355 } 5356 5357 // and may have an explicit exception-specification only if it is compatible 5358 // with the exception-specification on the implicit declaration. 5359 if (Type->hasExceptionSpec()) { 5360 // Delay the check if this is the first declaration of the special member, 5361 // since we may not have parsed some necessary in-class initializers yet. 5362 if (First) { 5363 // If the exception specification needs to be instantiated, do so now, 5364 // before we clobber it with an EST_Unevaluated specification below. 5365 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5366 InstantiateExceptionSpec(MD->getLocStart(), MD); 5367 Type = MD->getType()->getAs<FunctionProtoType>(); 5368 } 5369 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5370 } else 5371 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5372 } 5373 5374 // If a function is explicitly defaulted on its first declaration, 5375 if (First) { 5376 // -- it is implicitly considered to be constexpr if the implicit 5377 // definition would be, 5378 MD->setConstexpr(Constexpr); 5379 5380 // -- it is implicitly considered to have the same exception-specification 5381 // as if it had been implicitly declared, 5382 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5383 EPI.ExceptionSpec.Type = EST_Unevaluated; 5384 EPI.ExceptionSpec.SourceDecl = MD; 5385 MD->setType(Context.getFunctionType(ReturnType, 5386 llvm::makeArrayRef(&ArgType, 5387 ExpectedParams), 5388 EPI)); 5389 } 5390 5391 if (ShouldDeleteSpecialMember(MD, CSM)) { 5392 if (First) { 5393 SetDeclDeleted(MD, MD->getLocation()); 5394 } else { 5395 // C++11 [dcl.fct.def.default]p4: 5396 // [For a] user-provided explicitly-defaulted function [...] if such a 5397 // function is implicitly defined as deleted, the program is ill-formed. 5398 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5399 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5400 HadError = true; 5401 } 5402 } 5403 5404 if (HadError) 5405 MD->setInvalidDecl(); 5406 } 5407 5408 /// Check whether the exception specification provided for an 5409 /// explicitly-defaulted special member matches the exception specification 5410 /// that would have been generated for an implicit special member, per 5411 /// C++11 [dcl.fct.def.default]p2. 5412 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5413 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5414 // If the exception specification was explicitly specified but hadn't been 5415 // parsed when the method was defaulted, grab it now. 5416 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5417 SpecifiedType = 5418 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5419 5420 // Compute the implicit exception specification. 5421 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5422 /*IsCXXMethod=*/true); 5423 FunctionProtoType::ExtProtoInfo EPI(CC); 5424 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5425 .getExceptionSpec(); 5426 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5427 Context.getFunctionType(Context.VoidTy, None, EPI)); 5428 5429 // Ensure that it matches. 5430 CheckEquivalentExceptionSpec( 5431 PDiag(diag::err_incorrect_defaulted_exception_spec) 5432 << getSpecialMember(MD), PDiag(), 5433 ImplicitType, SourceLocation(), 5434 SpecifiedType, MD->getLocation()); 5435 } 5436 5437 void Sema::CheckDelayedMemberExceptionSpecs() { 5438 decltype(DelayedExceptionSpecChecks) Checks; 5439 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 5440 5441 std::swap(Checks, DelayedExceptionSpecChecks); 5442 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5443 5444 // Perform any deferred checking of exception specifications for virtual 5445 // destructors. 5446 for (auto &Check : Checks) 5447 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 5448 5449 // Check that any explicitly-defaulted methods have exception specifications 5450 // compatible with their implicit exception specifications. 5451 for (auto &Spec : Specs) 5452 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 5453 } 5454 5455 namespace { 5456 struct SpecialMemberDeletionInfo { 5457 Sema &S; 5458 CXXMethodDecl *MD; 5459 Sema::CXXSpecialMember CSM; 5460 bool Diagnose; 5461 5462 // Properties of the special member, computed for convenience. 5463 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5464 SourceLocation Loc; 5465 5466 bool AllFieldsAreConst; 5467 5468 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5469 Sema::CXXSpecialMember CSM, bool Diagnose) 5470 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5471 IsConstructor(false), IsAssignment(false), IsMove(false), 5472 ConstArg(false), Loc(MD->getLocation()), 5473 AllFieldsAreConst(true) { 5474 switch (CSM) { 5475 case Sema::CXXDefaultConstructor: 5476 case Sema::CXXCopyConstructor: 5477 IsConstructor = true; 5478 break; 5479 case Sema::CXXMoveConstructor: 5480 IsConstructor = true; 5481 IsMove = true; 5482 break; 5483 case Sema::CXXCopyAssignment: 5484 IsAssignment = true; 5485 break; 5486 case Sema::CXXMoveAssignment: 5487 IsAssignment = true; 5488 IsMove = true; 5489 break; 5490 case Sema::CXXDestructor: 5491 break; 5492 case Sema::CXXInvalid: 5493 llvm_unreachable("invalid special member kind"); 5494 } 5495 5496 if (MD->getNumParams()) { 5497 if (const ReferenceType *RT = 5498 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5499 ConstArg = RT->getPointeeType().isConstQualified(); 5500 } 5501 } 5502 5503 bool inUnion() const { return MD->getParent()->isUnion(); } 5504 5505 /// Look up the corresponding special member in the given class. 5506 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5507 unsigned Quals, bool IsMutable) { 5508 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5509 ConstArg && !IsMutable); 5510 } 5511 5512 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5513 5514 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5515 bool shouldDeleteForField(FieldDecl *FD); 5516 bool shouldDeleteForAllConstMembers(); 5517 5518 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5519 unsigned Quals); 5520 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5521 Sema::SpecialMemberOverloadResult *SMOR, 5522 bool IsDtorCallInCtor); 5523 5524 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5525 }; 5526 } 5527 5528 /// Is the given special member inaccessible when used on the given 5529 /// sub-object. 5530 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5531 CXXMethodDecl *target) { 5532 /// If we're operating on a base class, the object type is the 5533 /// type of this special member. 5534 QualType objectTy; 5535 AccessSpecifier access = target->getAccess(); 5536 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5537 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5538 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5539 5540 // If we're operating on a field, the object type is the type of the field. 5541 } else { 5542 objectTy = S.Context.getTypeDeclType(target->getParent()); 5543 } 5544 5545 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5546 } 5547 5548 /// Check whether we should delete a special member due to the implicit 5549 /// definition containing a call to a special member of a subobject. 5550 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5551 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5552 bool IsDtorCallInCtor) { 5553 CXXMethodDecl *Decl = SMOR->getMethod(); 5554 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5555 5556 int DiagKind = -1; 5557 5558 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5559 DiagKind = !Decl ? 0 : 1; 5560 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5561 DiagKind = 2; 5562 else if (!isAccessible(Subobj, Decl)) 5563 DiagKind = 3; 5564 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5565 !Decl->isTrivial()) { 5566 // A member of a union must have a trivial corresponding special member. 5567 // As a weird special case, a destructor call from a union's constructor 5568 // must be accessible and non-deleted, but need not be trivial. Such a 5569 // destructor is never actually called, but is semantically checked as 5570 // if it were. 5571 DiagKind = 4; 5572 } 5573 5574 if (DiagKind == -1) 5575 return false; 5576 5577 if (Diagnose) { 5578 if (Field) { 5579 S.Diag(Field->getLocation(), 5580 diag::note_deleted_special_member_class_subobject) 5581 << CSM << MD->getParent() << /*IsField*/true 5582 << Field << DiagKind << IsDtorCallInCtor; 5583 } else { 5584 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5585 S.Diag(Base->getLocStart(), 5586 diag::note_deleted_special_member_class_subobject) 5587 << CSM << MD->getParent() << /*IsField*/false 5588 << Base->getType() << DiagKind << IsDtorCallInCtor; 5589 } 5590 5591 if (DiagKind == 1) 5592 S.NoteDeletedFunction(Decl); 5593 // FIXME: Explain inaccessibility if DiagKind == 3. 5594 } 5595 5596 return true; 5597 } 5598 5599 /// Check whether we should delete a special member function due to having a 5600 /// direct or virtual base class or non-static data member of class type M. 5601 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5602 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5603 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5604 bool IsMutable = Field && Field->isMutable(); 5605 5606 // C++11 [class.ctor]p5: 5607 // -- any direct or virtual base class, or non-static data member with no 5608 // brace-or-equal-initializer, has class type M (or array thereof) and 5609 // either M has no default constructor or overload resolution as applied 5610 // to M's default constructor results in an ambiguity or in a function 5611 // that is deleted or inaccessible 5612 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5613 // -- a direct or virtual base class B that cannot be copied/moved because 5614 // overload resolution, as applied to B's corresponding special member, 5615 // results in an ambiguity or a function that is deleted or inaccessible 5616 // from the defaulted special member 5617 // C++11 [class.dtor]p5: 5618 // -- any direct or virtual base class [...] has a type with a destructor 5619 // that is deleted or inaccessible 5620 if (!(CSM == Sema::CXXDefaultConstructor && 5621 Field && Field->hasInClassInitializer()) && 5622 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5623 false)) 5624 return true; 5625 5626 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5627 // -- any direct or virtual base class or non-static data member has a 5628 // type with a destructor that is deleted or inaccessible 5629 if (IsConstructor) { 5630 Sema::SpecialMemberOverloadResult *SMOR = 5631 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5632 false, false, false, false, false); 5633 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5634 return true; 5635 } 5636 5637 return false; 5638 } 5639 5640 /// Check whether we should delete a special member function due to the class 5641 /// having a particular direct or virtual base class. 5642 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5643 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5644 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5645 } 5646 5647 /// Check whether we should delete a special member function due to the class 5648 /// having a particular non-static data member. 5649 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5650 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5651 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5652 5653 if (CSM == Sema::CXXDefaultConstructor) { 5654 // For a default constructor, all references must be initialized in-class 5655 // and, if a union, it must have a non-const member. 5656 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5657 if (Diagnose) 5658 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5659 << MD->getParent() << FD << FieldType << /*Reference*/0; 5660 return true; 5661 } 5662 // C++11 [class.ctor]p5: any non-variant non-static data member of 5663 // const-qualified type (or array thereof) with no 5664 // brace-or-equal-initializer does not have a user-provided default 5665 // constructor. 5666 if (!inUnion() && FieldType.isConstQualified() && 5667 !FD->hasInClassInitializer() && 5668 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5669 if (Diagnose) 5670 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5671 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5672 return true; 5673 } 5674 5675 if (inUnion() && !FieldType.isConstQualified()) 5676 AllFieldsAreConst = false; 5677 } else if (CSM == Sema::CXXCopyConstructor) { 5678 // For a copy constructor, data members must not be of rvalue reference 5679 // type. 5680 if (FieldType->isRValueReferenceType()) { 5681 if (Diagnose) 5682 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5683 << MD->getParent() << FD << FieldType; 5684 return true; 5685 } 5686 } else if (IsAssignment) { 5687 // For an assignment operator, data members must not be of reference type. 5688 if (FieldType->isReferenceType()) { 5689 if (Diagnose) 5690 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5691 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5692 return true; 5693 } 5694 if (!FieldRecord && FieldType.isConstQualified()) { 5695 // C++11 [class.copy]p23: 5696 // -- a non-static data member of const non-class type (or array thereof) 5697 if (Diagnose) 5698 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5699 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5700 return true; 5701 } 5702 } 5703 5704 if (FieldRecord) { 5705 // Some additional restrictions exist on the variant members. 5706 if (!inUnion() && FieldRecord->isUnion() && 5707 FieldRecord->isAnonymousStructOrUnion()) { 5708 bool AllVariantFieldsAreConst = true; 5709 5710 // FIXME: Handle anonymous unions declared within anonymous unions. 5711 for (auto *UI : FieldRecord->fields()) { 5712 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5713 5714 if (!UnionFieldType.isConstQualified()) 5715 AllVariantFieldsAreConst = false; 5716 5717 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5718 if (UnionFieldRecord && 5719 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5720 UnionFieldType.getCVRQualifiers())) 5721 return true; 5722 } 5723 5724 // At least one member in each anonymous union must be non-const 5725 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5726 !FieldRecord->field_empty()) { 5727 if (Diagnose) 5728 S.Diag(FieldRecord->getLocation(), 5729 diag::note_deleted_default_ctor_all_const) 5730 << MD->getParent() << /*anonymous union*/1; 5731 return true; 5732 } 5733 5734 // Don't check the implicit member of the anonymous union type. 5735 // This is technically non-conformant, but sanity demands it. 5736 return false; 5737 } 5738 5739 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5740 FieldType.getCVRQualifiers())) 5741 return true; 5742 } 5743 5744 return false; 5745 } 5746 5747 /// C++11 [class.ctor] p5: 5748 /// A defaulted default constructor for a class X is defined as deleted if 5749 /// X is a union and all of its variant members are of const-qualified type. 5750 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5751 // This is a silly definition, because it gives an empty union a deleted 5752 // default constructor. Don't do that. 5753 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5754 !MD->getParent()->field_empty()) { 5755 if (Diagnose) 5756 S.Diag(MD->getParent()->getLocation(), 5757 diag::note_deleted_default_ctor_all_const) 5758 << MD->getParent() << /*not anonymous union*/0; 5759 return true; 5760 } 5761 return false; 5762 } 5763 5764 /// Determine whether a defaulted special member function should be defined as 5765 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5766 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5767 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5768 bool Diagnose) { 5769 if (MD->isInvalidDecl()) 5770 return false; 5771 CXXRecordDecl *RD = MD->getParent(); 5772 assert(!RD->isDependentType() && "do deletion after instantiation"); 5773 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5774 return false; 5775 5776 // C++11 [expr.lambda.prim]p19: 5777 // The closure type associated with a lambda-expression has a 5778 // deleted (8.4.3) default constructor and a deleted copy 5779 // assignment operator. 5780 if (RD->isLambda() && 5781 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5782 if (Diagnose) 5783 Diag(RD->getLocation(), diag::note_lambda_decl); 5784 return true; 5785 } 5786 5787 // For an anonymous struct or union, the copy and assignment special members 5788 // will never be used, so skip the check. For an anonymous union declared at 5789 // namespace scope, the constructor and destructor are used. 5790 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5791 RD->isAnonymousStructOrUnion()) 5792 return false; 5793 5794 // C++11 [class.copy]p7, p18: 5795 // If the class definition declares a move constructor or move assignment 5796 // operator, an implicitly declared copy constructor or copy assignment 5797 // operator is defined as deleted. 5798 if (MD->isImplicit() && 5799 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5800 CXXMethodDecl *UserDeclaredMove = nullptr; 5801 5802 // In Microsoft mode, a user-declared move only causes the deletion of the 5803 // corresponding copy operation, not both copy operations. 5804 if (RD->hasUserDeclaredMoveConstructor() && 5805 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5806 if (!Diagnose) return true; 5807 5808 // Find any user-declared move constructor. 5809 for (auto *I : RD->ctors()) { 5810 if (I->isMoveConstructor()) { 5811 UserDeclaredMove = I; 5812 break; 5813 } 5814 } 5815 assert(UserDeclaredMove); 5816 } else if (RD->hasUserDeclaredMoveAssignment() && 5817 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5818 if (!Diagnose) return true; 5819 5820 // Find any user-declared move assignment operator. 5821 for (auto *I : RD->methods()) { 5822 if (I->isMoveAssignmentOperator()) { 5823 UserDeclaredMove = I; 5824 break; 5825 } 5826 } 5827 assert(UserDeclaredMove); 5828 } 5829 5830 if (UserDeclaredMove) { 5831 Diag(UserDeclaredMove->getLocation(), 5832 diag::note_deleted_copy_user_declared_move) 5833 << (CSM == CXXCopyAssignment) << RD 5834 << UserDeclaredMove->isMoveAssignmentOperator(); 5835 return true; 5836 } 5837 } 5838 5839 // Do access control from the special member function 5840 ContextRAII MethodContext(*this, MD); 5841 5842 // C++11 [class.dtor]p5: 5843 // -- for a virtual destructor, lookup of the non-array deallocation function 5844 // results in an ambiguity or in a function that is deleted or inaccessible 5845 if (CSM == CXXDestructor && MD->isVirtual()) { 5846 FunctionDecl *OperatorDelete = nullptr; 5847 DeclarationName Name = 5848 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5849 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5850 OperatorDelete, false)) { 5851 if (Diagnose) 5852 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5853 return true; 5854 } 5855 } 5856 5857 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5858 5859 for (auto &BI : RD->bases()) 5860 if (!BI.isVirtual() && 5861 SMI.shouldDeleteForBase(&BI)) 5862 return true; 5863 5864 // Per DR1611, do not consider virtual bases of constructors of abstract 5865 // classes, since we are not going to construct them. 5866 if (!RD->isAbstract() || !SMI.IsConstructor) { 5867 for (auto &BI : RD->vbases()) 5868 if (SMI.shouldDeleteForBase(&BI)) 5869 return true; 5870 } 5871 5872 for (auto *FI : RD->fields()) 5873 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5874 SMI.shouldDeleteForField(FI)) 5875 return true; 5876 5877 if (SMI.shouldDeleteForAllConstMembers()) 5878 return true; 5879 5880 if (getLangOpts().CUDA) { 5881 // We should delete the special member in CUDA mode if target inference 5882 // failed. 5883 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5884 Diagnose); 5885 } 5886 5887 return false; 5888 } 5889 5890 /// Perform lookup for a special member of the specified kind, and determine 5891 /// whether it is trivial. If the triviality can be determined without the 5892 /// lookup, skip it. This is intended for use when determining whether a 5893 /// special member of a containing object is trivial, and thus does not ever 5894 /// perform overload resolution for default constructors. 5895 /// 5896 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5897 /// member that was most likely to be intended to be trivial, if any. 5898 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5899 Sema::CXXSpecialMember CSM, unsigned Quals, 5900 bool ConstRHS, CXXMethodDecl **Selected) { 5901 if (Selected) 5902 *Selected = nullptr; 5903 5904 switch (CSM) { 5905 case Sema::CXXInvalid: 5906 llvm_unreachable("not a special member"); 5907 5908 case Sema::CXXDefaultConstructor: 5909 // C++11 [class.ctor]p5: 5910 // A default constructor is trivial if: 5911 // - all the [direct subobjects] have trivial default constructors 5912 // 5913 // Note, no overload resolution is performed in this case. 5914 if (RD->hasTrivialDefaultConstructor()) 5915 return true; 5916 5917 if (Selected) { 5918 // If there's a default constructor which could have been trivial, dig it 5919 // out. Otherwise, if there's any user-provided default constructor, point 5920 // to that as an example of why there's not a trivial one. 5921 CXXConstructorDecl *DefCtor = nullptr; 5922 if (RD->needsImplicitDefaultConstructor()) 5923 S.DeclareImplicitDefaultConstructor(RD); 5924 for (auto *CI : RD->ctors()) { 5925 if (!CI->isDefaultConstructor()) 5926 continue; 5927 DefCtor = CI; 5928 if (!DefCtor->isUserProvided()) 5929 break; 5930 } 5931 5932 *Selected = DefCtor; 5933 } 5934 5935 return false; 5936 5937 case Sema::CXXDestructor: 5938 // C++11 [class.dtor]p5: 5939 // A destructor is trivial if: 5940 // - all the direct [subobjects] have trivial destructors 5941 if (RD->hasTrivialDestructor()) 5942 return true; 5943 5944 if (Selected) { 5945 if (RD->needsImplicitDestructor()) 5946 S.DeclareImplicitDestructor(RD); 5947 *Selected = RD->getDestructor(); 5948 } 5949 5950 return false; 5951 5952 case Sema::CXXCopyConstructor: 5953 // C++11 [class.copy]p12: 5954 // A copy constructor is trivial if: 5955 // - the constructor selected to copy each direct [subobject] is trivial 5956 if (RD->hasTrivialCopyConstructor()) { 5957 if (Quals == Qualifiers::Const) 5958 // We must either select the trivial copy constructor or reach an 5959 // ambiguity; no need to actually perform overload resolution. 5960 return true; 5961 } else if (!Selected) { 5962 return false; 5963 } 5964 // In C++98, we are not supposed to perform overload resolution here, but we 5965 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5966 // cases like B as having a non-trivial copy constructor: 5967 // struct A { template<typename T> A(T&); }; 5968 // struct B { mutable A a; }; 5969 goto NeedOverloadResolution; 5970 5971 case Sema::CXXCopyAssignment: 5972 // C++11 [class.copy]p25: 5973 // A copy assignment operator is trivial if: 5974 // - the assignment operator selected to copy each direct [subobject] is 5975 // trivial 5976 if (RD->hasTrivialCopyAssignment()) { 5977 if (Quals == Qualifiers::Const) 5978 return true; 5979 } else if (!Selected) { 5980 return false; 5981 } 5982 // In C++98, we are not supposed to perform overload resolution here, but we 5983 // treat that as a language defect. 5984 goto NeedOverloadResolution; 5985 5986 case Sema::CXXMoveConstructor: 5987 case Sema::CXXMoveAssignment: 5988 NeedOverloadResolution: 5989 Sema::SpecialMemberOverloadResult *SMOR = 5990 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5991 5992 // The standard doesn't describe how to behave if the lookup is ambiguous. 5993 // We treat it as not making the member non-trivial, just like the standard 5994 // mandates for the default constructor. This should rarely matter, because 5995 // the member will also be deleted. 5996 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5997 return true; 5998 5999 if (!SMOR->getMethod()) { 6000 assert(SMOR->getKind() == 6001 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 6002 return false; 6003 } 6004 6005 // We deliberately don't check if we found a deleted special member. We're 6006 // not supposed to! 6007 if (Selected) 6008 *Selected = SMOR->getMethod(); 6009 return SMOR->getMethod()->isTrivial(); 6010 } 6011 6012 llvm_unreachable("unknown special method kind"); 6013 } 6014 6015 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 6016 for (auto *CI : RD->ctors()) 6017 if (!CI->isImplicit()) 6018 return CI; 6019 6020 // Look for constructor templates. 6021 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 6022 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 6023 if (CXXConstructorDecl *CD = 6024 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 6025 return CD; 6026 } 6027 6028 return nullptr; 6029 } 6030 6031 /// The kind of subobject we are checking for triviality. The values of this 6032 /// enumeration are used in diagnostics. 6033 enum TrivialSubobjectKind { 6034 /// The subobject is a base class. 6035 TSK_BaseClass, 6036 /// The subobject is a non-static data member. 6037 TSK_Field, 6038 /// The object is actually the complete object. 6039 TSK_CompleteObject 6040 }; 6041 6042 /// Check whether the special member selected for a given type would be trivial. 6043 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 6044 QualType SubType, bool ConstRHS, 6045 Sema::CXXSpecialMember CSM, 6046 TrivialSubobjectKind Kind, 6047 bool Diagnose) { 6048 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 6049 if (!SubRD) 6050 return true; 6051 6052 CXXMethodDecl *Selected; 6053 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 6054 ConstRHS, Diagnose ? &Selected : nullptr)) 6055 return true; 6056 6057 if (Diagnose) { 6058 if (ConstRHS) 6059 SubType.addConst(); 6060 6061 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 6062 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 6063 << Kind << SubType.getUnqualifiedType(); 6064 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6065 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6066 } else if (!Selected) 6067 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6068 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6069 else if (Selected->isUserProvided()) { 6070 if (Kind == TSK_CompleteObject) 6071 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6072 << Kind << SubType.getUnqualifiedType() << CSM; 6073 else { 6074 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6075 << Kind << SubType.getUnqualifiedType() << CSM; 6076 S.Diag(Selected->getLocation(), diag::note_declared_at); 6077 } 6078 } else { 6079 if (Kind != TSK_CompleteObject) 6080 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6081 << Kind << SubType.getUnqualifiedType() << CSM; 6082 6083 // Explain why the defaulted or deleted special member isn't trivial. 6084 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6085 } 6086 } 6087 6088 return false; 6089 } 6090 6091 /// Check whether the members of a class type allow a special member to be 6092 /// trivial. 6093 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 6094 Sema::CXXSpecialMember CSM, 6095 bool ConstArg, bool Diagnose) { 6096 for (const auto *FI : RD->fields()) { 6097 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 6098 continue; 6099 6100 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 6101 6102 // Pretend anonymous struct or union members are members of this class. 6103 if (FI->isAnonymousStructOrUnion()) { 6104 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 6105 CSM, ConstArg, Diagnose)) 6106 return false; 6107 continue; 6108 } 6109 6110 // C++11 [class.ctor]p5: 6111 // A default constructor is trivial if [...] 6112 // -- no non-static data member of its class has a 6113 // brace-or-equal-initializer 6114 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 6115 if (Diagnose) 6116 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 6117 return false; 6118 } 6119 6120 // Objective C ARC 4.3.5: 6121 // [...] nontrivally ownership-qualified types are [...] not trivially 6122 // default constructible, copy constructible, move constructible, copy 6123 // assignable, move assignable, or destructible [...] 6124 if (S.getLangOpts().ObjCAutoRefCount && 6125 FieldType.hasNonTrivialObjCLifetime()) { 6126 if (Diagnose) 6127 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6128 << RD << FieldType.getObjCLifetime(); 6129 return false; 6130 } 6131 6132 bool ConstRHS = ConstArg && !FI->isMutable(); 6133 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6134 CSM, TSK_Field, Diagnose)) 6135 return false; 6136 } 6137 6138 return true; 6139 } 6140 6141 /// Diagnose why the specified class does not have a trivial special member of 6142 /// the given kind. 6143 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6144 QualType Ty = Context.getRecordType(RD); 6145 6146 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6147 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6148 TSK_CompleteObject, /*Diagnose*/true); 6149 } 6150 6151 /// Determine whether a defaulted or deleted special member function is trivial, 6152 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6153 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6154 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6155 bool Diagnose) { 6156 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6157 6158 CXXRecordDecl *RD = MD->getParent(); 6159 6160 bool ConstArg = false; 6161 6162 // C++11 [class.copy]p12, p25: [DR1593] 6163 // A [special member] is trivial if [...] its parameter-type-list is 6164 // equivalent to the parameter-type-list of an implicit declaration [...] 6165 switch (CSM) { 6166 case CXXDefaultConstructor: 6167 case CXXDestructor: 6168 // Trivial default constructors and destructors cannot have parameters. 6169 break; 6170 6171 case CXXCopyConstructor: 6172 case CXXCopyAssignment: { 6173 // Trivial copy operations always have const, non-volatile parameter types. 6174 ConstArg = true; 6175 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6176 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6177 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6178 if (Diagnose) 6179 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6180 << Param0->getSourceRange() << Param0->getType() 6181 << Context.getLValueReferenceType( 6182 Context.getRecordType(RD).withConst()); 6183 return false; 6184 } 6185 break; 6186 } 6187 6188 case CXXMoveConstructor: 6189 case CXXMoveAssignment: { 6190 // Trivial move operations always have non-cv-qualified parameters. 6191 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6192 const RValueReferenceType *RT = 6193 Param0->getType()->getAs<RValueReferenceType>(); 6194 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6195 if (Diagnose) 6196 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6197 << Param0->getSourceRange() << Param0->getType() 6198 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6199 return false; 6200 } 6201 break; 6202 } 6203 6204 case CXXInvalid: 6205 llvm_unreachable("not a special member"); 6206 } 6207 6208 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6209 if (Diagnose) 6210 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6211 diag::note_nontrivial_default_arg) 6212 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6213 return false; 6214 } 6215 if (MD->isVariadic()) { 6216 if (Diagnose) 6217 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6218 return false; 6219 } 6220 6221 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6222 // A copy/move [constructor or assignment operator] is trivial if 6223 // -- the [member] selected to copy/move each direct base class subobject 6224 // is trivial 6225 // 6226 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6227 // A [default constructor or destructor] is trivial if 6228 // -- all the direct base classes have trivial [default constructors or 6229 // destructors] 6230 for (const auto &BI : RD->bases()) 6231 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6232 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6233 return false; 6234 6235 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6236 // A copy/move [constructor or assignment operator] for a class X is 6237 // trivial if 6238 // -- for each non-static data member of X that is of class type (or array 6239 // thereof), the constructor selected to copy/move that member is 6240 // trivial 6241 // 6242 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6243 // A [default constructor or destructor] is trivial if 6244 // -- for all of the non-static data members of its class that are of class 6245 // type (or array thereof), each such class has a trivial [default 6246 // constructor or destructor] 6247 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6248 return false; 6249 6250 // C++11 [class.dtor]p5: 6251 // A destructor is trivial if [...] 6252 // -- the destructor is not virtual 6253 if (CSM == CXXDestructor && MD->isVirtual()) { 6254 if (Diagnose) 6255 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6256 return false; 6257 } 6258 6259 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6260 // A [special member] for class X is trivial if [...] 6261 // -- class X has no virtual functions and no virtual base classes 6262 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6263 if (!Diagnose) 6264 return false; 6265 6266 if (RD->getNumVBases()) { 6267 // Check for virtual bases. We already know that the corresponding 6268 // member in all bases is trivial, so vbases must all be direct. 6269 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6270 assert(BS.isVirtual()); 6271 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6272 return false; 6273 } 6274 6275 // Must have a virtual method. 6276 for (const auto *MI : RD->methods()) { 6277 if (MI->isVirtual()) { 6278 SourceLocation MLoc = MI->getLocStart(); 6279 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6280 return false; 6281 } 6282 } 6283 6284 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6285 } 6286 6287 // Looks like it's trivial! 6288 return true; 6289 } 6290 6291 namespace { 6292 struct FindHiddenVirtualMethod { 6293 Sema *S; 6294 CXXMethodDecl *Method; 6295 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6296 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6297 6298 private: 6299 /// Check whether any most overriden method from MD in Methods 6300 static bool CheckMostOverridenMethods( 6301 const CXXMethodDecl *MD, 6302 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 6303 if (MD->size_overridden_methods() == 0) 6304 return Methods.count(MD->getCanonicalDecl()); 6305 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6306 E = MD->end_overridden_methods(); 6307 I != E; ++I) 6308 if (CheckMostOverridenMethods(*I, Methods)) 6309 return true; 6310 return false; 6311 } 6312 6313 public: 6314 /// Member lookup function that determines whether a given C++ 6315 /// method overloads virtual methods in a base class without overriding any, 6316 /// to be used with CXXRecordDecl::lookupInBases(). 6317 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 6318 RecordDecl *BaseRecord = 6319 Specifier->getType()->getAs<RecordType>()->getDecl(); 6320 6321 DeclarationName Name = Method->getDeclName(); 6322 assert(Name.getNameKind() == DeclarationName::Identifier); 6323 6324 bool foundSameNameMethod = false; 6325 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6326 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 6327 Path.Decls = Path.Decls.slice(1)) { 6328 NamedDecl *D = Path.Decls.front(); 6329 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6330 MD = MD->getCanonicalDecl(); 6331 foundSameNameMethod = true; 6332 // Interested only in hidden virtual methods. 6333 if (!MD->isVirtual()) 6334 continue; 6335 // If the method we are checking overrides a method from its base 6336 // don't warn about the other overloaded methods. Clang deviates from 6337 // GCC by only diagnosing overloads of inherited virtual functions that 6338 // do not override any other virtual functions in the base. GCC's 6339 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6340 // function from a base class. These cases may be better served by a 6341 // warning (not specific to virtual functions) on call sites when the 6342 // call would select a different function from the base class, were it 6343 // visible. 6344 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6345 if (!S->IsOverload(Method, MD, false)) 6346 return true; 6347 // Collect the overload only if its hidden. 6348 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 6349 overloadedMethods.push_back(MD); 6350 } 6351 } 6352 6353 if (foundSameNameMethod) 6354 OverloadedMethods.append(overloadedMethods.begin(), 6355 overloadedMethods.end()); 6356 return foundSameNameMethod; 6357 } 6358 }; 6359 } // end anonymous namespace 6360 6361 /// \brief Add the most overriden methods from MD to Methods 6362 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6363 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6364 if (MD->size_overridden_methods() == 0) 6365 Methods.insert(MD->getCanonicalDecl()); 6366 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6367 E = MD->end_overridden_methods(); 6368 I != E; ++I) 6369 AddMostOverridenMethods(*I, Methods); 6370 } 6371 6372 /// \brief Check if a method overloads virtual methods in a base class without 6373 /// overriding any. 6374 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6375 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6376 if (!MD->getDeclName().isIdentifier()) 6377 return; 6378 6379 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6380 /*bool RecordPaths=*/false, 6381 /*bool DetectVirtual=*/false); 6382 FindHiddenVirtualMethod FHVM; 6383 FHVM.Method = MD; 6384 FHVM.S = this; 6385 6386 // Keep the base methods that were overriden or introduced in the subclass 6387 // by 'using' in a set. A base method not in this set is hidden. 6388 CXXRecordDecl *DC = MD->getParent(); 6389 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6390 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6391 NamedDecl *ND = *I; 6392 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6393 ND = shad->getTargetDecl(); 6394 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6395 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 6396 } 6397 6398 if (DC->lookupInBases(FHVM, Paths)) 6399 OverloadedMethods = FHVM.OverloadedMethods; 6400 } 6401 6402 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6403 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6404 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6405 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6406 PartialDiagnostic PD = PDiag( 6407 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6408 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6409 Diag(overloadedMD->getLocation(), PD); 6410 } 6411 } 6412 6413 /// \brief Diagnose methods which overload virtual methods in a base class 6414 /// without overriding any. 6415 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6416 if (MD->isInvalidDecl()) 6417 return; 6418 6419 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6420 return; 6421 6422 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6423 FindHiddenVirtualMethods(MD, OverloadedMethods); 6424 if (!OverloadedMethods.empty()) { 6425 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6426 << MD << (OverloadedMethods.size() > 1); 6427 6428 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6429 } 6430 } 6431 6432 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6433 Decl *TagDecl, 6434 SourceLocation LBrac, 6435 SourceLocation RBrac, 6436 AttributeList *AttrList) { 6437 if (!TagDecl) 6438 return; 6439 6440 AdjustDeclIfTemplate(TagDecl); 6441 6442 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6443 if (l->getKind() != AttributeList::AT_Visibility) 6444 continue; 6445 l->setInvalid(); 6446 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6447 l->getName(); 6448 } 6449 6450 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6451 // strict aliasing violation! 6452 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6453 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6454 6455 CheckCompletedCXXClass( 6456 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6457 } 6458 6459 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6460 /// special functions, such as the default constructor, copy 6461 /// constructor, or destructor, to the given C++ class (C++ 6462 /// [special]p1). This routine can only be executed just before the 6463 /// definition of the class is complete. 6464 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6465 if (!ClassDecl->hasUserDeclaredConstructor()) 6466 ++ASTContext::NumImplicitDefaultConstructors; 6467 6468 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6469 ++ASTContext::NumImplicitCopyConstructors; 6470 6471 // If the properties or semantics of the copy constructor couldn't be 6472 // determined while the class was being declared, force a declaration 6473 // of it now. 6474 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6475 DeclareImplicitCopyConstructor(ClassDecl); 6476 } 6477 6478 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6479 ++ASTContext::NumImplicitMoveConstructors; 6480 6481 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6482 DeclareImplicitMoveConstructor(ClassDecl); 6483 } 6484 6485 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6486 ++ASTContext::NumImplicitCopyAssignmentOperators; 6487 6488 // If we have a dynamic class, then the copy assignment operator may be 6489 // virtual, so we have to declare it immediately. This ensures that, e.g., 6490 // it shows up in the right place in the vtable and that we diagnose 6491 // problems with the implicit exception specification. 6492 if (ClassDecl->isDynamicClass() || 6493 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6494 DeclareImplicitCopyAssignment(ClassDecl); 6495 } 6496 6497 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6498 ++ASTContext::NumImplicitMoveAssignmentOperators; 6499 6500 // Likewise for the move assignment operator. 6501 if (ClassDecl->isDynamicClass() || 6502 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6503 DeclareImplicitMoveAssignment(ClassDecl); 6504 } 6505 6506 if (!ClassDecl->hasUserDeclaredDestructor()) { 6507 ++ASTContext::NumImplicitDestructors; 6508 6509 // If we have a dynamic class, then the destructor may be virtual, so we 6510 // have to declare the destructor immediately. This ensures that, e.g., it 6511 // shows up in the right place in the vtable and that we diagnose problems 6512 // with the implicit exception specification. 6513 if (ClassDecl->isDynamicClass() || 6514 ClassDecl->needsOverloadResolutionForDestructor()) 6515 DeclareImplicitDestructor(ClassDecl); 6516 } 6517 } 6518 6519 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6520 if (!D) 6521 return 0; 6522 6523 // The order of template parameters is not important here. All names 6524 // get added to the same scope. 6525 SmallVector<TemplateParameterList *, 4> ParameterLists; 6526 6527 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6528 D = TD->getTemplatedDecl(); 6529 6530 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6531 ParameterLists.push_back(PSD->getTemplateParameters()); 6532 6533 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6534 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6535 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6536 6537 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6538 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6539 ParameterLists.push_back(FTD->getTemplateParameters()); 6540 } 6541 } 6542 6543 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6544 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6545 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6546 6547 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6548 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6549 ParameterLists.push_back(CTD->getTemplateParameters()); 6550 } 6551 } 6552 6553 unsigned Count = 0; 6554 for (TemplateParameterList *Params : ParameterLists) { 6555 if (Params->size() > 0) 6556 // Ignore explicit specializations; they don't contribute to the template 6557 // depth. 6558 ++Count; 6559 for (NamedDecl *Param : *Params) { 6560 if (Param->getDeclName()) { 6561 S->AddDecl(Param); 6562 IdResolver.AddDecl(Param); 6563 } 6564 } 6565 } 6566 6567 return Count; 6568 } 6569 6570 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6571 if (!RecordD) return; 6572 AdjustDeclIfTemplate(RecordD); 6573 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6574 PushDeclContext(S, Record); 6575 } 6576 6577 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6578 if (!RecordD) return; 6579 PopDeclContext(); 6580 } 6581 6582 /// This is used to implement the constant expression evaluation part of the 6583 /// attribute enable_if extension. There is nothing in standard C++ which would 6584 /// require reentering parameters. 6585 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6586 if (!Param) 6587 return; 6588 6589 S->AddDecl(Param); 6590 if (Param->getDeclName()) 6591 IdResolver.AddDecl(Param); 6592 } 6593 6594 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6595 /// parsing a top-level (non-nested) C++ class, and we are now 6596 /// parsing those parts of the given Method declaration that could 6597 /// not be parsed earlier (C++ [class.mem]p2), such as default 6598 /// arguments. This action should enter the scope of the given 6599 /// Method declaration as if we had just parsed the qualified method 6600 /// name. However, it should not bring the parameters into scope; 6601 /// that will be performed by ActOnDelayedCXXMethodParameter. 6602 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6603 } 6604 6605 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6606 /// C++ method declaration. We're (re-)introducing the given 6607 /// function parameter into scope for use in parsing later parts of 6608 /// the method declaration. For example, we could see an 6609 /// ActOnParamDefaultArgument event for this parameter. 6610 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6611 if (!ParamD) 6612 return; 6613 6614 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6615 6616 // If this parameter has an unparsed default argument, clear it out 6617 // to make way for the parsed default argument. 6618 if (Param->hasUnparsedDefaultArg()) 6619 Param->setDefaultArg(nullptr); 6620 6621 S->AddDecl(Param); 6622 if (Param->getDeclName()) 6623 IdResolver.AddDecl(Param); 6624 } 6625 6626 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6627 /// processing the delayed method declaration for Method. The method 6628 /// declaration is now considered finished. There may be a separate 6629 /// ActOnStartOfFunctionDef action later (not necessarily 6630 /// immediately!) for this method, if it was also defined inside the 6631 /// class body. 6632 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6633 if (!MethodD) 6634 return; 6635 6636 AdjustDeclIfTemplate(MethodD); 6637 6638 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6639 6640 // Now that we have our default arguments, check the constructor 6641 // again. It could produce additional diagnostics or affect whether 6642 // the class has implicitly-declared destructors, among other 6643 // things. 6644 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6645 CheckConstructor(Constructor); 6646 6647 // Check the default arguments, which we may have added. 6648 if (!Method->isInvalidDecl()) 6649 CheckCXXDefaultArguments(Method); 6650 } 6651 6652 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6653 /// the well-formedness of the constructor declarator @p D with type @p 6654 /// R. If there are any errors in the declarator, this routine will 6655 /// emit diagnostics and set the invalid bit to true. In any case, the type 6656 /// will be updated to reflect a well-formed type for the constructor and 6657 /// returned. 6658 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6659 StorageClass &SC) { 6660 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6661 6662 // C++ [class.ctor]p3: 6663 // A constructor shall not be virtual (10.3) or static (9.4). A 6664 // constructor can be invoked for a const, volatile or const 6665 // volatile object. A constructor shall not be declared const, 6666 // volatile, or const volatile (9.3.2). 6667 if (isVirtual) { 6668 if (!D.isInvalidType()) 6669 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6670 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6671 << SourceRange(D.getIdentifierLoc()); 6672 D.setInvalidType(); 6673 } 6674 if (SC == SC_Static) { 6675 if (!D.isInvalidType()) 6676 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6677 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6678 << SourceRange(D.getIdentifierLoc()); 6679 D.setInvalidType(); 6680 SC = SC_None; 6681 } 6682 6683 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6684 diagnoseIgnoredQualifiers( 6685 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6686 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6687 D.getDeclSpec().getRestrictSpecLoc(), 6688 D.getDeclSpec().getAtomicSpecLoc()); 6689 D.setInvalidType(); 6690 } 6691 6692 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6693 if (FTI.TypeQuals != 0) { 6694 if (FTI.TypeQuals & Qualifiers::Const) 6695 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6696 << "const" << SourceRange(D.getIdentifierLoc()); 6697 if (FTI.TypeQuals & Qualifiers::Volatile) 6698 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6699 << "volatile" << SourceRange(D.getIdentifierLoc()); 6700 if (FTI.TypeQuals & Qualifiers::Restrict) 6701 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6702 << "restrict" << SourceRange(D.getIdentifierLoc()); 6703 D.setInvalidType(); 6704 } 6705 6706 // C++0x [class.ctor]p4: 6707 // A constructor shall not be declared with a ref-qualifier. 6708 if (FTI.hasRefQualifier()) { 6709 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6710 << FTI.RefQualifierIsLValueRef 6711 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6712 D.setInvalidType(); 6713 } 6714 6715 // Rebuild the function type "R" without any type qualifiers (in 6716 // case any of the errors above fired) and with "void" as the 6717 // return type, since constructors don't have return types. 6718 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6719 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6720 return R; 6721 6722 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6723 EPI.TypeQuals = 0; 6724 EPI.RefQualifier = RQ_None; 6725 6726 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6727 } 6728 6729 /// CheckConstructor - Checks a fully-formed constructor for 6730 /// well-formedness, issuing any diagnostics required. Returns true if 6731 /// the constructor declarator is invalid. 6732 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6733 CXXRecordDecl *ClassDecl 6734 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6735 if (!ClassDecl) 6736 return Constructor->setInvalidDecl(); 6737 6738 // C++ [class.copy]p3: 6739 // A declaration of a constructor for a class X is ill-formed if 6740 // its first parameter is of type (optionally cv-qualified) X and 6741 // either there are no other parameters or else all other 6742 // parameters have default arguments. 6743 if (!Constructor->isInvalidDecl() && 6744 ((Constructor->getNumParams() == 1) || 6745 (Constructor->getNumParams() > 1 && 6746 Constructor->getParamDecl(1)->hasDefaultArg())) && 6747 Constructor->getTemplateSpecializationKind() 6748 != TSK_ImplicitInstantiation) { 6749 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6750 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6751 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6752 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6753 const char *ConstRef 6754 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6755 : " const &"; 6756 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6757 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6758 6759 // FIXME: Rather that making the constructor invalid, we should endeavor 6760 // to fix the type. 6761 Constructor->setInvalidDecl(); 6762 } 6763 } 6764 } 6765 6766 /// CheckDestructor - Checks a fully-formed destructor definition for 6767 /// well-formedness, issuing any diagnostics required. Returns true 6768 /// on error. 6769 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6770 CXXRecordDecl *RD = Destructor->getParent(); 6771 6772 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6773 SourceLocation Loc; 6774 6775 if (!Destructor->isImplicit()) 6776 Loc = Destructor->getLocation(); 6777 else 6778 Loc = RD->getLocation(); 6779 6780 // If we have a virtual destructor, look up the deallocation function 6781 FunctionDecl *OperatorDelete = nullptr; 6782 DeclarationName Name = 6783 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6784 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6785 return true; 6786 // If there's no class-specific operator delete, look up the global 6787 // non-array delete. 6788 if (!OperatorDelete) 6789 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6790 6791 MarkFunctionReferenced(Loc, OperatorDelete); 6792 6793 Destructor->setOperatorDelete(OperatorDelete); 6794 } 6795 6796 return false; 6797 } 6798 6799 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6800 /// the well-formednes of the destructor declarator @p D with type @p 6801 /// R. If there are any errors in the declarator, this routine will 6802 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6803 /// will be updated to reflect a well-formed type for the destructor and 6804 /// returned. 6805 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6806 StorageClass& SC) { 6807 // C++ [class.dtor]p1: 6808 // [...] A typedef-name that names a class is a class-name 6809 // (7.1.3); however, a typedef-name that names a class shall not 6810 // be used as the identifier in the declarator for a destructor 6811 // declaration. 6812 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6813 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6814 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6815 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6816 else if (const TemplateSpecializationType *TST = 6817 DeclaratorType->getAs<TemplateSpecializationType>()) 6818 if (TST->isTypeAlias()) 6819 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6820 << DeclaratorType << 1; 6821 6822 // C++ [class.dtor]p2: 6823 // A destructor is used to destroy objects of its class type. A 6824 // destructor takes no parameters, and no return type can be 6825 // specified for it (not even void). The address of a destructor 6826 // shall not be taken. A destructor shall not be static. A 6827 // destructor can be invoked for a const, volatile or const 6828 // volatile object. A destructor shall not be declared const, 6829 // volatile or const volatile (9.3.2). 6830 if (SC == SC_Static) { 6831 if (!D.isInvalidType()) 6832 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6833 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6834 << SourceRange(D.getIdentifierLoc()) 6835 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6836 6837 SC = SC_None; 6838 } 6839 if (!D.isInvalidType()) { 6840 // Destructors don't have return types, but the parser will 6841 // happily parse something like: 6842 // 6843 // class X { 6844 // float ~X(); 6845 // }; 6846 // 6847 // The return type will be eliminated later. 6848 if (D.getDeclSpec().hasTypeSpecifier()) 6849 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6850 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6851 << SourceRange(D.getIdentifierLoc()); 6852 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6853 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6854 SourceLocation(), 6855 D.getDeclSpec().getConstSpecLoc(), 6856 D.getDeclSpec().getVolatileSpecLoc(), 6857 D.getDeclSpec().getRestrictSpecLoc(), 6858 D.getDeclSpec().getAtomicSpecLoc()); 6859 D.setInvalidType(); 6860 } 6861 } 6862 6863 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6864 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6865 if (FTI.TypeQuals & Qualifiers::Const) 6866 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6867 << "const" << SourceRange(D.getIdentifierLoc()); 6868 if (FTI.TypeQuals & Qualifiers::Volatile) 6869 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6870 << "volatile" << SourceRange(D.getIdentifierLoc()); 6871 if (FTI.TypeQuals & Qualifiers::Restrict) 6872 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6873 << "restrict" << SourceRange(D.getIdentifierLoc()); 6874 D.setInvalidType(); 6875 } 6876 6877 // C++0x [class.dtor]p2: 6878 // A destructor shall not be declared with a ref-qualifier. 6879 if (FTI.hasRefQualifier()) { 6880 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6881 << FTI.RefQualifierIsLValueRef 6882 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6883 D.setInvalidType(); 6884 } 6885 6886 // Make sure we don't have any parameters. 6887 if (FTIHasNonVoidParameters(FTI)) { 6888 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6889 6890 // Delete the parameters. 6891 FTI.freeParams(); 6892 D.setInvalidType(); 6893 } 6894 6895 // Make sure the destructor isn't variadic. 6896 if (FTI.isVariadic) { 6897 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6898 D.setInvalidType(); 6899 } 6900 6901 // Rebuild the function type "R" without any type qualifiers or 6902 // parameters (in case any of the errors above fired) and with 6903 // "void" as the return type, since destructors don't have return 6904 // types. 6905 if (!D.isInvalidType()) 6906 return R; 6907 6908 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6909 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6910 EPI.Variadic = false; 6911 EPI.TypeQuals = 0; 6912 EPI.RefQualifier = RQ_None; 6913 return Context.getFunctionType(Context.VoidTy, None, EPI); 6914 } 6915 6916 static void extendLeft(SourceRange &R, SourceRange Before) { 6917 if (Before.isInvalid()) 6918 return; 6919 R.setBegin(Before.getBegin()); 6920 if (R.getEnd().isInvalid()) 6921 R.setEnd(Before.getEnd()); 6922 } 6923 6924 static void extendRight(SourceRange &R, SourceRange After) { 6925 if (After.isInvalid()) 6926 return; 6927 if (R.getBegin().isInvalid()) 6928 R.setBegin(After.getBegin()); 6929 R.setEnd(After.getEnd()); 6930 } 6931 6932 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6933 /// well-formednes of the conversion function declarator @p D with 6934 /// type @p R. If there are any errors in the declarator, this routine 6935 /// will emit diagnostics and return true. Otherwise, it will return 6936 /// false. Either way, the type @p R will be updated to reflect a 6937 /// well-formed type for the conversion operator. 6938 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6939 StorageClass& SC) { 6940 // C++ [class.conv.fct]p1: 6941 // Neither parameter types nor return type can be specified. The 6942 // type of a conversion function (8.3.5) is "function taking no 6943 // parameter returning conversion-type-id." 6944 if (SC == SC_Static) { 6945 if (!D.isInvalidType()) 6946 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6947 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6948 << D.getName().getSourceRange(); 6949 D.setInvalidType(); 6950 SC = SC_None; 6951 } 6952 6953 TypeSourceInfo *ConvTSI = nullptr; 6954 QualType ConvType = 6955 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 6956 6957 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6958 // Conversion functions don't have return types, but the parser will 6959 // happily parse something like: 6960 // 6961 // class X { 6962 // float operator bool(); 6963 // }; 6964 // 6965 // The return type will be changed later anyway. 6966 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6967 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6968 << SourceRange(D.getIdentifierLoc()); 6969 D.setInvalidType(); 6970 } 6971 6972 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6973 6974 // Make sure we don't have any parameters. 6975 if (Proto->getNumParams() > 0) { 6976 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6977 6978 // Delete the parameters. 6979 D.getFunctionTypeInfo().freeParams(); 6980 D.setInvalidType(); 6981 } else if (Proto->isVariadic()) { 6982 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6983 D.setInvalidType(); 6984 } 6985 6986 // Diagnose "&operator bool()" and other such nonsense. This 6987 // is actually a gcc extension which we don't support. 6988 if (Proto->getReturnType() != ConvType) { 6989 bool NeedsTypedef = false; 6990 SourceRange Before, After; 6991 6992 // Walk the chunks and extract information on them for our diagnostic. 6993 bool PastFunctionChunk = false; 6994 for (auto &Chunk : D.type_objects()) { 6995 switch (Chunk.Kind) { 6996 case DeclaratorChunk::Function: 6997 if (!PastFunctionChunk) { 6998 if (Chunk.Fun.HasTrailingReturnType) { 6999 TypeSourceInfo *TRT = nullptr; 7000 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 7001 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 7002 } 7003 PastFunctionChunk = true; 7004 break; 7005 } 7006 // Fall through. 7007 case DeclaratorChunk::Array: 7008 NeedsTypedef = true; 7009 extendRight(After, Chunk.getSourceRange()); 7010 break; 7011 7012 case DeclaratorChunk::Pointer: 7013 case DeclaratorChunk::BlockPointer: 7014 case DeclaratorChunk::Reference: 7015 case DeclaratorChunk::MemberPointer: 7016 extendLeft(Before, Chunk.getSourceRange()); 7017 break; 7018 7019 case DeclaratorChunk::Paren: 7020 extendLeft(Before, Chunk.Loc); 7021 extendRight(After, Chunk.EndLoc); 7022 break; 7023 } 7024 } 7025 7026 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 7027 After.isValid() ? After.getBegin() : 7028 D.getIdentifierLoc(); 7029 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 7030 DB << Before << After; 7031 7032 if (!NeedsTypedef) { 7033 DB << /*don't need a typedef*/0; 7034 7035 // If we can provide a correct fix-it hint, do so. 7036 if (After.isInvalid() && ConvTSI) { 7037 SourceLocation InsertLoc = 7038 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 7039 DB << FixItHint::CreateInsertion(InsertLoc, " ") 7040 << FixItHint::CreateInsertionFromRange( 7041 InsertLoc, CharSourceRange::getTokenRange(Before)) 7042 << FixItHint::CreateRemoval(Before); 7043 } 7044 } else if (!Proto->getReturnType()->isDependentType()) { 7045 DB << /*typedef*/1 << Proto->getReturnType(); 7046 } else if (getLangOpts().CPlusPlus11) { 7047 DB << /*alias template*/2 << Proto->getReturnType(); 7048 } else { 7049 DB << /*might not be fixable*/3; 7050 } 7051 7052 // Recover by incorporating the other type chunks into the result type. 7053 // Note, this does *not* change the name of the function. This is compatible 7054 // with the GCC extension: 7055 // struct S { &operator int(); } s; 7056 // int &r = s.operator int(); // ok in GCC 7057 // S::operator int&() {} // error in GCC, function name is 'operator int'. 7058 ConvType = Proto->getReturnType(); 7059 } 7060 7061 // C++ [class.conv.fct]p4: 7062 // The conversion-type-id shall not represent a function type nor 7063 // an array type. 7064 if (ConvType->isArrayType()) { 7065 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7066 ConvType = Context.getPointerType(ConvType); 7067 D.setInvalidType(); 7068 } else if (ConvType->isFunctionType()) { 7069 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7070 ConvType = Context.getPointerType(ConvType); 7071 D.setInvalidType(); 7072 } 7073 7074 // Rebuild the function type "R" without any parameters (in case any 7075 // of the errors above fired) and with the conversion type as the 7076 // return type. 7077 if (D.isInvalidType()) 7078 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7079 7080 // C++0x explicit conversion operators. 7081 if (D.getDeclSpec().isExplicitSpecified()) 7082 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7083 getLangOpts().CPlusPlus11 ? 7084 diag::warn_cxx98_compat_explicit_conversion_functions : 7085 diag::ext_explicit_conversion_functions) 7086 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 7087 } 7088 7089 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 7090 /// the declaration of the given C++ conversion function. This routine 7091 /// is responsible for recording the conversion function in the C++ 7092 /// class, if possible. 7093 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 7094 assert(Conversion && "Expected to receive a conversion function declaration"); 7095 7096 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 7097 7098 // Make sure we aren't redeclaring the conversion function. 7099 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 7100 7101 // C++ [class.conv.fct]p1: 7102 // [...] A conversion function is never used to convert a 7103 // (possibly cv-qualified) object to the (possibly cv-qualified) 7104 // same object type (or a reference to it), to a (possibly 7105 // cv-qualified) base class of that type (or a reference to it), 7106 // or to (possibly cv-qualified) void. 7107 // FIXME: Suppress this warning if the conversion function ends up being a 7108 // virtual function that overrides a virtual function in a base class. 7109 QualType ClassType 7110 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7111 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 7112 ConvType = ConvTypeRef->getPointeeType(); 7113 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 7114 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 7115 /* Suppress diagnostics for instantiations. */; 7116 else if (ConvType->isRecordType()) { 7117 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 7118 if (ConvType == ClassType) 7119 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 7120 << ClassType; 7121 else if (IsDerivedFrom(ClassType, ConvType)) 7122 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 7123 << ClassType << ConvType; 7124 } else if (ConvType->isVoidType()) { 7125 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 7126 << ClassType << ConvType; 7127 } 7128 7129 if (FunctionTemplateDecl *ConversionTemplate 7130 = Conversion->getDescribedFunctionTemplate()) 7131 return ConversionTemplate; 7132 7133 return Conversion; 7134 } 7135 7136 //===----------------------------------------------------------------------===// 7137 // Namespace Handling 7138 //===----------------------------------------------------------------------===// 7139 7140 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 7141 /// reopened. 7142 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 7143 SourceLocation Loc, 7144 IdentifierInfo *II, bool *IsInline, 7145 NamespaceDecl *PrevNS) { 7146 assert(*IsInline != PrevNS->isInline()); 7147 7148 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 7149 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 7150 // inline namespaces, with the intention of bringing names into namespace std. 7151 // 7152 // We support this just well enough to get that case working; this is not 7153 // sufficient to support reopening namespaces as inline in general. 7154 if (*IsInline && II && II->getName().startswith("__atomic") && 7155 S.getSourceManager().isInSystemHeader(Loc)) { 7156 // Mark all prior declarations of the namespace as inline. 7157 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 7158 NS = NS->getPreviousDecl()) 7159 NS->setInline(*IsInline); 7160 // Patch up the lookup table for the containing namespace. This isn't really 7161 // correct, but it's good enough for this particular case. 7162 for (auto *I : PrevNS->decls()) 7163 if (auto *ND = dyn_cast<NamedDecl>(I)) 7164 PrevNS->getParent()->makeDeclVisibleInContext(ND); 7165 return; 7166 } 7167 7168 if (PrevNS->isInline()) 7169 // The user probably just forgot the 'inline', so suggest that it 7170 // be added back. 7171 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 7172 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 7173 else 7174 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 7175 7176 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 7177 *IsInline = PrevNS->isInline(); 7178 } 7179 7180 /// ActOnStartNamespaceDef - This is called at the start of a namespace 7181 /// definition. 7182 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 7183 SourceLocation InlineLoc, 7184 SourceLocation NamespaceLoc, 7185 SourceLocation IdentLoc, 7186 IdentifierInfo *II, 7187 SourceLocation LBrace, 7188 AttributeList *AttrList) { 7189 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 7190 // For anonymous namespace, take the location of the left brace. 7191 SourceLocation Loc = II ? IdentLoc : LBrace; 7192 bool IsInline = InlineLoc.isValid(); 7193 bool IsInvalid = false; 7194 bool IsStd = false; 7195 bool AddToKnown = false; 7196 Scope *DeclRegionScope = NamespcScope->getParent(); 7197 7198 NamespaceDecl *PrevNS = nullptr; 7199 if (II) { 7200 // C++ [namespace.def]p2: 7201 // The identifier in an original-namespace-definition shall not 7202 // have been previously defined in the declarative region in 7203 // which the original-namespace-definition appears. The 7204 // identifier in an original-namespace-definition is the name of 7205 // the namespace. Subsequently in that declarative region, it is 7206 // treated as an original-namespace-name. 7207 // 7208 // Since namespace names are unique in their scope, and we don't 7209 // look through using directives, just look for any ordinary names 7210 // as if by qualified name lookup. 7211 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration); 7212 LookupQualifiedName(R, CurContext->getRedeclContext()); 7213 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 7214 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7215 7216 if (PrevNS) { 7217 // This is an extended namespace definition. 7218 if (IsInline != PrevNS->isInline()) 7219 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7220 &IsInline, PrevNS); 7221 } else if (PrevDecl) { 7222 // This is an invalid name redefinition. 7223 Diag(Loc, diag::err_redefinition_different_kind) 7224 << II; 7225 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7226 IsInvalid = true; 7227 // Continue on to push Namespc as current DeclContext and return it. 7228 } else if (II->isStr("std") && 7229 CurContext->getRedeclContext()->isTranslationUnit()) { 7230 // This is the first "real" definition of the namespace "std", so update 7231 // our cache of the "std" namespace to point at this definition. 7232 PrevNS = getStdNamespace(); 7233 IsStd = true; 7234 AddToKnown = !IsInline; 7235 } else { 7236 // We've seen this namespace for the first time. 7237 AddToKnown = !IsInline; 7238 } 7239 } else { 7240 // Anonymous namespaces. 7241 7242 // Determine whether the parent already has an anonymous namespace. 7243 DeclContext *Parent = CurContext->getRedeclContext(); 7244 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7245 PrevNS = TU->getAnonymousNamespace(); 7246 } else { 7247 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7248 PrevNS = ND->getAnonymousNamespace(); 7249 } 7250 7251 if (PrevNS && IsInline != PrevNS->isInline()) 7252 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7253 &IsInline, PrevNS); 7254 } 7255 7256 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7257 StartLoc, Loc, II, PrevNS); 7258 if (IsInvalid) 7259 Namespc->setInvalidDecl(); 7260 7261 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7262 7263 // FIXME: Should we be merging attributes? 7264 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7265 PushNamespaceVisibilityAttr(Attr, Loc); 7266 7267 if (IsStd) 7268 StdNamespace = Namespc; 7269 if (AddToKnown) 7270 KnownNamespaces[Namespc] = false; 7271 7272 if (II) { 7273 PushOnScopeChains(Namespc, DeclRegionScope); 7274 } else { 7275 // Link the anonymous namespace into its parent. 7276 DeclContext *Parent = CurContext->getRedeclContext(); 7277 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7278 TU->setAnonymousNamespace(Namespc); 7279 } else { 7280 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7281 } 7282 7283 CurContext->addDecl(Namespc); 7284 7285 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7286 // behaves as if it were replaced by 7287 // namespace unique { /* empty body */ } 7288 // using namespace unique; 7289 // namespace unique { namespace-body } 7290 // where all occurrences of 'unique' in a translation unit are 7291 // replaced by the same identifier and this identifier differs 7292 // from all other identifiers in the entire program. 7293 7294 // We just create the namespace with an empty name and then add an 7295 // implicit using declaration, just like the standard suggests. 7296 // 7297 // CodeGen enforces the "universally unique" aspect by giving all 7298 // declarations semantically contained within an anonymous 7299 // namespace internal linkage. 7300 7301 if (!PrevNS) { 7302 UsingDirectiveDecl* UD 7303 = UsingDirectiveDecl::Create(Context, Parent, 7304 /* 'using' */ LBrace, 7305 /* 'namespace' */ SourceLocation(), 7306 /* qualifier */ NestedNameSpecifierLoc(), 7307 /* identifier */ SourceLocation(), 7308 Namespc, 7309 /* Ancestor */ Parent); 7310 UD->setImplicit(); 7311 Parent->addDecl(UD); 7312 } 7313 } 7314 7315 ActOnDocumentableDecl(Namespc); 7316 7317 // Although we could have an invalid decl (i.e. the namespace name is a 7318 // redefinition), push it as current DeclContext and try to continue parsing. 7319 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7320 // for the namespace has the declarations that showed up in that particular 7321 // namespace definition. 7322 PushDeclContext(NamespcScope, Namespc); 7323 return Namespc; 7324 } 7325 7326 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7327 /// is a namespace alias, returns the namespace it points to. 7328 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7329 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7330 return AD->getNamespace(); 7331 return dyn_cast_or_null<NamespaceDecl>(D); 7332 } 7333 7334 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7335 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7336 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7337 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7338 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7339 Namespc->setRBraceLoc(RBrace); 7340 PopDeclContext(); 7341 if (Namespc->hasAttr<VisibilityAttr>()) 7342 PopPragmaVisibility(true, RBrace); 7343 } 7344 7345 CXXRecordDecl *Sema::getStdBadAlloc() const { 7346 return cast_or_null<CXXRecordDecl>( 7347 StdBadAlloc.get(Context.getExternalSource())); 7348 } 7349 7350 NamespaceDecl *Sema::getStdNamespace() const { 7351 return cast_or_null<NamespaceDecl>( 7352 StdNamespace.get(Context.getExternalSource())); 7353 } 7354 7355 /// \brief Retrieve the special "std" namespace, which may require us to 7356 /// implicitly define the namespace. 7357 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7358 if (!StdNamespace) { 7359 // The "std" namespace has not yet been defined, so build one implicitly. 7360 StdNamespace = NamespaceDecl::Create(Context, 7361 Context.getTranslationUnitDecl(), 7362 /*Inline=*/false, 7363 SourceLocation(), SourceLocation(), 7364 &PP.getIdentifierTable().get("std"), 7365 /*PrevDecl=*/nullptr); 7366 getStdNamespace()->setImplicit(true); 7367 } 7368 7369 return getStdNamespace(); 7370 } 7371 7372 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7373 assert(getLangOpts().CPlusPlus && 7374 "Looking for std::initializer_list outside of C++."); 7375 7376 // We're looking for implicit instantiations of 7377 // template <typename E> class std::initializer_list. 7378 7379 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7380 return false; 7381 7382 ClassTemplateDecl *Template = nullptr; 7383 const TemplateArgument *Arguments = nullptr; 7384 7385 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7386 7387 ClassTemplateSpecializationDecl *Specialization = 7388 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7389 if (!Specialization) 7390 return false; 7391 7392 Template = Specialization->getSpecializedTemplate(); 7393 Arguments = Specialization->getTemplateArgs().data(); 7394 } else if (const TemplateSpecializationType *TST = 7395 Ty->getAs<TemplateSpecializationType>()) { 7396 Template = dyn_cast_or_null<ClassTemplateDecl>( 7397 TST->getTemplateName().getAsTemplateDecl()); 7398 Arguments = TST->getArgs(); 7399 } 7400 if (!Template) 7401 return false; 7402 7403 if (!StdInitializerList) { 7404 // Haven't recognized std::initializer_list yet, maybe this is it. 7405 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7406 if (TemplateClass->getIdentifier() != 7407 &PP.getIdentifierTable().get("initializer_list") || 7408 !getStdNamespace()->InEnclosingNamespaceSetOf( 7409 TemplateClass->getDeclContext())) 7410 return false; 7411 // This is a template called std::initializer_list, but is it the right 7412 // template? 7413 TemplateParameterList *Params = Template->getTemplateParameters(); 7414 if (Params->getMinRequiredArguments() != 1) 7415 return false; 7416 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7417 return false; 7418 7419 // It's the right template. 7420 StdInitializerList = Template; 7421 } 7422 7423 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 7424 return false; 7425 7426 // This is an instance of std::initializer_list. Find the argument type. 7427 if (Element) 7428 *Element = Arguments[0].getAsType(); 7429 return true; 7430 } 7431 7432 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7433 NamespaceDecl *Std = S.getStdNamespace(); 7434 if (!Std) { 7435 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7436 return nullptr; 7437 } 7438 7439 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7440 Loc, Sema::LookupOrdinaryName); 7441 if (!S.LookupQualifiedName(Result, Std)) { 7442 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7443 return nullptr; 7444 } 7445 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7446 if (!Template) { 7447 Result.suppressDiagnostics(); 7448 // We found something weird. Complain about the first thing we found. 7449 NamedDecl *Found = *Result.begin(); 7450 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7451 return nullptr; 7452 } 7453 7454 // We found some template called std::initializer_list. Now verify that it's 7455 // correct. 7456 TemplateParameterList *Params = Template->getTemplateParameters(); 7457 if (Params->getMinRequiredArguments() != 1 || 7458 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7459 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7460 return nullptr; 7461 } 7462 7463 return Template; 7464 } 7465 7466 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7467 if (!StdInitializerList) { 7468 StdInitializerList = LookupStdInitializerList(*this, Loc); 7469 if (!StdInitializerList) 7470 return QualType(); 7471 } 7472 7473 TemplateArgumentListInfo Args(Loc, Loc); 7474 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7475 Context.getTrivialTypeSourceInfo(Element, 7476 Loc))); 7477 return Context.getCanonicalType( 7478 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7479 } 7480 7481 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7482 // C++ [dcl.init.list]p2: 7483 // A constructor is an initializer-list constructor if its first parameter 7484 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7485 // std::initializer_list<E> for some type E, and either there are no other 7486 // parameters or else all other parameters have default arguments. 7487 if (Ctor->getNumParams() < 1 || 7488 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7489 return false; 7490 7491 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7492 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7493 ArgType = RT->getPointeeType().getUnqualifiedType(); 7494 7495 return isStdInitializerList(ArgType, nullptr); 7496 } 7497 7498 /// \brief Determine whether a using statement is in a context where it will be 7499 /// apply in all contexts. 7500 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7501 switch (CurContext->getDeclKind()) { 7502 case Decl::TranslationUnit: 7503 return true; 7504 case Decl::LinkageSpec: 7505 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7506 default: 7507 return false; 7508 } 7509 } 7510 7511 namespace { 7512 7513 // Callback to only accept typo corrections that are namespaces. 7514 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7515 public: 7516 bool ValidateCandidate(const TypoCorrection &candidate) override { 7517 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7518 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7519 return false; 7520 } 7521 }; 7522 7523 } 7524 7525 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7526 CXXScopeSpec &SS, 7527 SourceLocation IdentLoc, 7528 IdentifierInfo *Ident) { 7529 R.clear(); 7530 if (TypoCorrection Corrected = 7531 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7532 llvm::make_unique<NamespaceValidatorCCC>(), 7533 Sema::CTK_ErrorRecovery)) { 7534 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7535 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7536 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7537 Ident->getName().equals(CorrectedStr); 7538 S.diagnoseTypo(Corrected, 7539 S.PDiag(diag::err_using_directive_member_suggest) 7540 << Ident << DC << DroppedSpecifier << SS.getRange(), 7541 S.PDiag(diag::note_namespace_defined_here)); 7542 } else { 7543 S.diagnoseTypo(Corrected, 7544 S.PDiag(diag::err_using_directive_suggest) << Ident, 7545 S.PDiag(diag::note_namespace_defined_here)); 7546 } 7547 R.addDecl(Corrected.getCorrectionDecl()); 7548 return true; 7549 } 7550 return false; 7551 } 7552 7553 Decl *Sema::ActOnUsingDirective(Scope *S, 7554 SourceLocation UsingLoc, 7555 SourceLocation NamespcLoc, 7556 CXXScopeSpec &SS, 7557 SourceLocation IdentLoc, 7558 IdentifierInfo *NamespcName, 7559 AttributeList *AttrList) { 7560 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7561 assert(NamespcName && "Invalid NamespcName."); 7562 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7563 7564 // This can only happen along a recovery path. 7565 while (S->isTemplateParamScope()) 7566 S = S->getParent(); 7567 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7568 7569 UsingDirectiveDecl *UDir = nullptr; 7570 NestedNameSpecifier *Qualifier = nullptr; 7571 if (SS.isSet()) 7572 Qualifier = SS.getScopeRep(); 7573 7574 // Lookup namespace name. 7575 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7576 LookupParsedName(R, S, &SS); 7577 if (R.isAmbiguous()) 7578 return nullptr; 7579 7580 if (R.empty()) { 7581 R.clear(); 7582 // Allow "using namespace std;" or "using namespace ::std;" even if 7583 // "std" hasn't been defined yet, for GCC compatibility. 7584 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7585 NamespcName->isStr("std")) { 7586 Diag(IdentLoc, diag::ext_using_undefined_std); 7587 R.addDecl(getOrCreateStdNamespace()); 7588 R.resolveKind(); 7589 } 7590 // Otherwise, attempt typo correction. 7591 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7592 } 7593 7594 if (!R.empty()) { 7595 NamedDecl *Named = R.getFoundDecl(); 7596 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7597 && "expected namespace decl"); 7598 7599 // The use of a nested name specifier may trigger deprecation warnings. 7600 DiagnoseUseOfDecl(Named, IdentLoc); 7601 7602 // C++ [namespace.udir]p1: 7603 // A using-directive specifies that the names in the nominated 7604 // namespace can be used in the scope in which the 7605 // using-directive appears after the using-directive. During 7606 // unqualified name lookup (3.4.1), the names appear as if they 7607 // were declared in the nearest enclosing namespace which 7608 // contains both the using-directive and the nominated 7609 // namespace. [Note: in this context, "contains" means "contains 7610 // directly or indirectly". ] 7611 7612 // Find enclosing context containing both using-directive and 7613 // nominated namespace. 7614 NamespaceDecl *NS = getNamespaceDecl(Named); 7615 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7616 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7617 CommonAncestor = CommonAncestor->getParent(); 7618 7619 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7620 SS.getWithLocInContext(Context), 7621 IdentLoc, Named, CommonAncestor); 7622 7623 if (IsUsingDirectiveInToplevelContext(CurContext) && 7624 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7625 Diag(IdentLoc, diag::warn_using_directive_in_header); 7626 } 7627 7628 PushUsingDirective(S, UDir); 7629 } else { 7630 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7631 } 7632 7633 if (UDir) 7634 ProcessDeclAttributeList(S, UDir, AttrList); 7635 7636 return UDir; 7637 } 7638 7639 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7640 // If the scope has an associated entity and the using directive is at 7641 // namespace or translation unit scope, add the UsingDirectiveDecl into 7642 // its lookup structure so qualified name lookup can find it. 7643 DeclContext *Ctx = S->getEntity(); 7644 if (Ctx && !Ctx->isFunctionOrMethod()) 7645 Ctx->addDecl(UDir); 7646 else 7647 // Otherwise, it is at block scope. The using-directives will affect lookup 7648 // only to the end of the scope. 7649 S->PushUsingDirective(UDir); 7650 } 7651 7652 7653 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7654 AccessSpecifier AS, 7655 bool HasUsingKeyword, 7656 SourceLocation UsingLoc, 7657 CXXScopeSpec &SS, 7658 UnqualifiedId &Name, 7659 AttributeList *AttrList, 7660 bool HasTypenameKeyword, 7661 SourceLocation TypenameLoc) { 7662 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7663 7664 switch (Name.getKind()) { 7665 case UnqualifiedId::IK_ImplicitSelfParam: 7666 case UnqualifiedId::IK_Identifier: 7667 case UnqualifiedId::IK_OperatorFunctionId: 7668 case UnqualifiedId::IK_LiteralOperatorId: 7669 case UnqualifiedId::IK_ConversionFunctionId: 7670 break; 7671 7672 case UnqualifiedId::IK_ConstructorName: 7673 case UnqualifiedId::IK_ConstructorTemplateId: 7674 // C++11 inheriting constructors. 7675 Diag(Name.getLocStart(), 7676 getLangOpts().CPlusPlus11 ? 7677 diag::warn_cxx98_compat_using_decl_constructor : 7678 diag::err_using_decl_constructor) 7679 << SS.getRange(); 7680 7681 if (getLangOpts().CPlusPlus11) break; 7682 7683 return nullptr; 7684 7685 case UnqualifiedId::IK_DestructorName: 7686 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7687 << SS.getRange(); 7688 return nullptr; 7689 7690 case UnqualifiedId::IK_TemplateId: 7691 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7692 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7693 return nullptr; 7694 } 7695 7696 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7697 DeclarationName TargetName = TargetNameInfo.getName(); 7698 if (!TargetName) 7699 return nullptr; 7700 7701 // Warn about access declarations. 7702 if (!HasUsingKeyword) { 7703 Diag(Name.getLocStart(), 7704 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7705 : diag::warn_access_decl_deprecated) 7706 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7707 } 7708 7709 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7710 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7711 return nullptr; 7712 7713 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7714 TargetNameInfo, AttrList, 7715 /* IsInstantiation */ false, 7716 HasTypenameKeyword, TypenameLoc); 7717 if (UD) 7718 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7719 7720 return UD; 7721 } 7722 7723 /// \brief Determine whether a using declaration considers the given 7724 /// declarations as "equivalent", e.g., if they are redeclarations of 7725 /// the same entity or are both typedefs of the same type. 7726 static bool 7727 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7728 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7729 return true; 7730 7731 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7732 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7733 return Context.hasSameType(TD1->getUnderlyingType(), 7734 TD2->getUnderlyingType()); 7735 7736 return false; 7737 } 7738 7739 7740 /// Determines whether to create a using shadow decl for a particular 7741 /// decl, given the set of decls existing prior to this using lookup. 7742 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7743 const LookupResult &Previous, 7744 UsingShadowDecl *&PrevShadow) { 7745 // Diagnose finding a decl which is not from a base class of the 7746 // current class. We do this now because there are cases where this 7747 // function will silently decide not to build a shadow decl, which 7748 // will pre-empt further diagnostics. 7749 // 7750 // We don't need to do this in C++0x because we do the check once on 7751 // the qualifier. 7752 // 7753 // FIXME: diagnose the following if we care enough: 7754 // struct A { int foo; }; 7755 // struct B : A { using A::foo; }; 7756 // template <class T> struct C : A {}; 7757 // template <class T> struct D : C<T> { using B::foo; } // <--- 7758 // This is invalid (during instantiation) in C++03 because B::foo 7759 // resolves to the using decl in B, which is not a base class of D<T>. 7760 // We can't diagnose it immediately because C<T> is an unknown 7761 // specialization. The UsingShadowDecl in D<T> then points directly 7762 // to A::foo, which will look well-formed when we instantiate. 7763 // The right solution is to not collapse the shadow-decl chain. 7764 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7765 DeclContext *OrigDC = Orig->getDeclContext(); 7766 7767 // Handle enums and anonymous structs. 7768 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7769 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7770 while (OrigRec->isAnonymousStructOrUnion()) 7771 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7772 7773 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7774 if (OrigDC == CurContext) { 7775 Diag(Using->getLocation(), 7776 diag::err_using_decl_nested_name_specifier_is_current_class) 7777 << Using->getQualifierLoc().getSourceRange(); 7778 Diag(Orig->getLocation(), diag::note_using_decl_target); 7779 return true; 7780 } 7781 7782 Diag(Using->getQualifierLoc().getBeginLoc(), 7783 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7784 << Using->getQualifier() 7785 << cast<CXXRecordDecl>(CurContext) 7786 << Using->getQualifierLoc().getSourceRange(); 7787 Diag(Orig->getLocation(), diag::note_using_decl_target); 7788 return true; 7789 } 7790 } 7791 7792 if (Previous.empty()) return false; 7793 7794 NamedDecl *Target = Orig; 7795 if (isa<UsingShadowDecl>(Target)) 7796 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7797 7798 // If the target happens to be one of the previous declarations, we 7799 // don't have a conflict. 7800 // 7801 // FIXME: but we might be increasing its access, in which case we 7802 // should redeclare it. 7803 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7804 bool FoundEquivalentDecl = false; 7805 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7806 I != E; ++I) { 7807 NamedDecl *D = (*I)->getUnderlyingDecl(); 7808 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7809 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7810 PrevShadow = Shadow; 7811 FoundEquivalentDecl = true; 7812 } 7813 7814 if (isVisible(D)) 7815 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7816 } 7817 7818 if (FoundEquivalentDecl) 7819 return false; 7820 7821 if (FunctionDecl *FD = Target->getAsFunction()) { 7822 NamedDecl *OldDecl = nullptr; 7823 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7824 /*IsForUsingDecl*/ true)) { 7825 case Ovl_Overload: 7826 return false; 7827 7828 case Ovl_NonFunction: 7829 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7830 break; 7831 7832 // We found a decl with the exact signature. 7833 case Ovl_Match: 7834 // If we're in a record, we want to hide the target, so we 7835 // return true (without a diagnostic) to tell the caller not to 7836 // build a shadow decl. 7837 if (CurContext->isRecord()) 7838 return true; 7839 7840 // If we're not in a record, this is an error. 7841 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7842 break; 7843 } 7844 7845 Diag(Target->getLocation(), diag::note_using_decl_target); 7846 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7847 return true; 7848 } 7849 7850 // Target is not a function. 7851 7852 if (isa<TagDecl>(Target)) { 7853 // No conflict between a tag and a non-tag. 7854 if (!Tag) return false; 7855 7856 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7857 Diag(Target->getLocation(), diag::note_using_decl_target); 7858 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7859 return true; 7860 } 7861 7862 // No conflict between a tag and a non-tag. 7863 if (!NonTag) return false; 7864 7865 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7866 Diag(Target->getLocation(), diag::note_using_decl_target); 7867 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7868 return true; 7869 } 7870 7871 /// Builds a shadow declaration corresponding to a 'using' declaration. 7872 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7873 UsingDecl *UD, 7874 NamedDecl *Orig, 7875 UsingShadowDecl *PrevDecl) { 7876 7877 // If we resolved to another shadow declaration, just coalesce them. 7878 NamedDecl *Target = Orig; 7879 if (isa<UsingShadowDecl>(Target)) { 7880 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7881 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7882 } 7883 7884 UsingShadowDecl *Shadow 7885 = UsingShadowDecl::Create(Context, CurContext, 7886 UD->getLocation(), UD, Target); 7887 UD->addShadowDecl(Shadow); 7888 7889 Shadow->setAccess(UD->getAccess()); 7890 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7891 Shadow->setInvalidDecl(); 7892 7893 Shadow->setPreviousDecl(PrevDecl); 7894 7895 if (S) 7896 PushOnScopeChains(Shadow, S); 7897 else 7898 CurContext->addDecl(Shadow); 7899 7900 7901 return Shadow; 7902 } 7903 7904 /// Hides a using shadow declaration. This is required by the current 7905 /// using-decl implementation when a resolvable using declaration in a 7906 /// class is followed by a declaration which would hide or override 7907 /// one or more of the using decl's targets; for example: 7908 /// 7909 /// struct Base { void foo(int); }; 7910 /// struct Derived : Base { 7911 /// using Base::foo; 7912 /// void foo(int); 7913 /// }; 7914 /// 7915 /// The governing language is C++03 [namespace.udecl]p12: 7916 /// 7917 /// When a using-declaration brings names from a base class into a 7918 /// derived class scope, member functions in the derived class 7919 /// override and/or hide member functions with the same name and 7920 /// parameter types in a base class (rather than conflicting). 7921 /// 7922 /// There are two ways to implement this: 7923 /// (1) optimistically create shadow decls when they're not hidden 7924 /// by existing declarations, or 7925 /// (2) don't create any shadow decls (or at least don't make them 7926 /// visible) until we've fully parsed/instantiated the class. 7927 /// The problem with (1) is that we might have to retroactively remove 7928 /// a shadow decl, which requires several O(n) operations because the 7929 /// decl structures are (very reasonably) not designed for removal. 7930 /// (2) avoids this but is very fiddly and phase-dependent. 7931 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7932 if (Shadow->getDeclName().getNameKind() == 7933 DeclarationName::CXXConversionFunctionName) 7934 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7935 7936 // Remove it from the DeclContext... 7937 Shadow->getDeclContext()->removeDecl(Shadow); 7938 7939 // ...and the scope, if applicable... 7940 if (S) { 7941 S->RemoveDecl(Shadow); 7942 IdResolver.RemoveDecl(Shadow); 7943 } 7944 7945 // ...and the using decl. 7946 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7947 7948 // TODO: complain somehow if Shadow was used. It shouldn't 7949 // be possible for this to happen, because...? 7950 } 7951 7952 /// Find the base specifier for a base class with the given type. 7953 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7954 QualType DesiredBase, 7955 bool &AnyDependentBases) { 7956 // Check whether the named type is a direct base class. 7957 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7958 for (auto &Base : Derived->bases()) { 7959 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7960 if (CanonicalDesiredBase == BaseType) 7961 return &Base; 7962 if (BaseType->isDependentType()) 7963 AnyDependentBases = true; 7964 } 7965 return nullptr; 7966 } 7967 7968 namespace { 7969 class UsingValidatorCCC : public CorrectionCandidateCallback { 7970 public: 7971 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7972 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7973 : HasTypenameKeyword(HasTypenameKeyword), 7974 IsInstantiation(IsInstantiation), OldNNS(NNS), 7975 RequireMemberOf(RequireMemberOf) {} 7976 7977 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7978 NamedDecl *ND = Candidate.getCorrectionDecl(); 7979 7980 // Keywords are not valid here. 7981 if (!ND || isa<NamespaceDecl>(ND)) 7982 return false; 7983 7984 // Completely unqualified names are invalid for a 'using' declaration. 7985 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7986 return false; 7987 7988 if (RequireMemberOf) { 7989 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7990 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7991 // No-one ever wants a using-declaration to name an injected-class-name 7992 // of a base class, unless they're declaring an inheriting constructor. 7993 ASTContext &Ctx = ND->getASTContext(); 7994 if (!Ctx.getLangOpts().CPlusPlus11) 7995 return false; 7996 QualType FoundType = Ctx.getRecordType(FoundRecord); 7997 7998 // Check that the injected-class-name is named as a member of its own 7999 // type; we don't want to suggest 'using Derived::Base;', since that 8000 // means something else. 8001 NestedNameSpecifier *Specifier = 8002 Candidate.WillReplaceSpecifier() 8003 ? Candidate.getCorrectionSpecifier() 8004 : OldNNS; 8005 if (!Specifier->getAsType() || 8006 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 8007 return false; 8008 8009 // Check that this inheriting constructor declaration actually names a 8010 // direct base class of the current class. 8011 bool AnyDependentBases = false; 8012 if (!findDirectBaseWithType(RequireMemberOf, 8013 Ctx.getRecordType(FoundRecord), 8014 AnyDependentBases) && 8015 !AnyDependentBases) 8016 return false; 8017 } else { 8018 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 8019 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 8020 return false; 8021 8022 // FIXME: Check that the base class member is accessible? 8023 } 8024 } else { 8025 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8026 if (FoundRecord && FoundRecord->isInjectedClassName()) 8027 return false; 8028 } 8029 8030 if (isa<TypeDecl>(ND)) 8031 return HasTypenameKeyword || !IsInstantiation; 8032 8033 return !HasTypenameKeyword; 8034 } 8035 8036 private: 8037 bool HasTypenameKeyword; 8038 bool IsInstantiation; 8039 NestedNameSpecifier *OldNNS; 8040 CXXRecordDecl *RequireMemberOf; 8041 }; 8042 } // end anonymous namespace 8043 8044 /// Builds a using declaration. 8045 /// 8046 /// \param IsInstantiation - Whether this call arises from an 8047 /// instantiation of an unresolved using declaration. We treat 8048 /// the lookup differently for these declarations. 8049 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 8050 SourceLocation UsingLoc, 8051 CXXScopeSpec &SS, 8052 DeclarationNameInfo NameInfo, 8053 AttributeList *AttrList, 8054 bool IsInstantiation, 8055 bool HasTypenameKeyword, 8056 SourceLocation TypenameLoc) { 8057 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8058 SourceLocation IdentLoc = NameInfo.getLoc(); 8059 assert(IdentLoc.isValid() && "Invalid TargetName location."); 8060 8061 // FIXME: We ignore attributes for now. 8062 8063 if (SS.isEmpty()) { 8064 Diag(IdentLoc, diag::err_using_requires_qualname); 8065 return nullptr; 8066 } 8067 8068 // Do the redeclaration lookup in the current scope. 8069 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 8070 ForRedeclaration); 8071 Previous.setHideTags(false); 8072 if (S) { 8073 LookupName(Previous, S); 8074 8075 // It is really dumb that we have to do this. 8076 LookupResult::Filter F = Previous.makeFilter(); 8077 while (F.hasNext()) { 8078 NamedDecl *D = F.next(); 8079 if (!isDeclInScope(D, CurContext, S)) 8080 F.erase(); 8081 // If we found a local extern declaration that's not ordinarily visible, 8082 // and this declaration is being added to a non-block scope, ignore it. 8083 // We're only checking for scope conflicts here, not also for violations 8084 // of the linkage rules. 8085 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 8086 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 8087 F.erase(); 8088 } 8089 F.done(); 8090 } else { 8091 assert(IsInstantiation && "no scope in non-instantiation"); 8092 assert(CurContext->isRecord() && "scope not record in instantiation"); 8093 LookupQualifiedName(Previous, CurContext); 8094 } 8095 8096 // Check for invalid redeclarations. 8097 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 8098 SS, IdentLoc, Previous)) 8099 return nullptr; 8100 8101 // Check for bad qualifiers. 8102 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 8103 return nullptr; 8104 8105 DeclContext *LookupContext = computeDeclContext(SS); 8106 NamedDecl *D; 8107 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 8108 if (!LookupContext) { 8109 if (HasTypenameKeyword) { 8110 // FIXME: not all declaration name kinds are legal here 8111 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 8112 UsingLoc, TypenameLoc, 8113 QualifierLoc, 8114 IdentLoc, NameInfo.getName()); 8115 } else { 8116 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 8117 QualifierLoc, NameInfo); 8118 } 8119 D->setAccess(AS); 8120 CurContext->addDecl(D); 8121 return D; 8122 } 8123 8124 auto Build = [&](bool Invalid) { 8125 UsingDecl *UD = 8126 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 8127 HasTypenameKeyword); 8128 UD->setAccess(AS); 8129 CurContext->addDecl(UD); 8130 UD->setInvalidDecl(Invalid); 8131 return UD; 8132 }; 8133 auto BuildInvalid = [&]{ return Build(true); }; 8134 auto BuildValid = [&]{ return Build(false); }; 8135 8136 if (RequireCompleteDeclContext(SS, LookupContext)) 8137 return BuildInvalid(); 8138 8139 // Look up the target name. 8140 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8141 8142 // Unlike most lookups, we don't always want to hide tag 8143 // declarations: tag names are visible through the using declaration 8144 // even if hidden by ordinary names, *except* in a dependent context 8145 // where it's important for the sanity of two-phase lookup. 8146 if (!IsInstantiation) 8147 R.setHideTags(false); 8148 8149 // For the purposes of this lookup, we have a base object type 8150 // equal to that of the current context. 8151 if (CurContext->isRecord()) { 8152 R.setBaseObjectType( 8153 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 8154 } 8155 8156 LookupQualifiedName(R, LookupContext); 8157 8158 // Try to correct typos if possible. If constructor name lookup finds no 8159 // results, that means the named class has no explicit constructors, and we 8160 // suppressed declaring implicit ones (probably because it's dependent or 8161 // invalid). 8162 if (R.empty() && 8163 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 8164 if (TypoCorrection Corrected = CorrectTypo( 8165 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 8166 llvm::make_unique<UsingValidatorCCC>( 8167 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8168 dyn_cast<CXXRecordDecl>(CurContext)), 8169 CTK_ErrorRecovery)) { 8170 // We reject any correction for which ND would be NULL. 8171 NamedDecl *ND = Corrected.getCorrectionDecl(); 8172 8173 // We reject candidates where DroppedSpecifier == true, hence the 8174 // literal '0' below. 8175 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8176 << NameInfo.getName() << LookupContext << 0 8177 << SS.getRange()); 8178 8179 // If we corrected to an inheriting constructor, handle it as one. 8180 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8181 if (RD && RD->isInjectedClassName()) { 8182 // Fix up the information we'll use to build the using declaration. 8183 if (Corrected.WillReplaceSpecifier()) { 8184 NestedNameSpecifierLocBuilder Builder; 8185 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8186 QualifierLoc.getSourceRange()); 8187 QualifierLoc = Builder.getWithLocInContext(Context); 8188 } 8189 8190 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8191 Context.getCanonicalType(Context.getRecordType(RD)))); 8192 NameInfo.setNamedTypeInfo(nullptr); 8193 for (auto *Ctor : LookupConstructors(RD)) 8194 R.addDecl(Ctor); 8195 } else { 8196 // FIXME: Pick up all the declarations if we found an overloaded function. 8197 R.addDecl(ND); 8198 } 8199 } else { 8200 Diag(IdentLoc, diag::err_no_member) 8201 << NameInfo.getName() << LookupContext << SS.getRange(); 8202 return BuildInvalid(); 8203 } 8204 } 8205 8206 if (R.isAmbiguous()) 8207 return BuildInvalid(); 8208 8209 if (HasTypenameKeyword) { 8210 // If we asked for a typename and got a non-type decl, error out. 8211 if (!R.getAsSingle<TypeDecl>()) { 8212 Diag(IdentLoc, diag::err_using_typename_non_type); 8213 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8214 Diag((*I)->getUnderlyingDecl()->getLocation(), 8215 diag::note_using_decl_target); 8216 return BuildInvalid(); 8217 } 8218 } else { 8219 // If we asked for a non-typename and we got a type, error out, 8220 // but only if this is an instantiation of an unresolved using 8221 // decl. Otherwise just silently find the type name. 8222 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8223 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8224 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8225 return BuildInvalid(); 8226 } 8227 } 8228 8229 // C++0x N2914 [namespace.udecl]p6: 8230 // A using-declaration shall not name a namespace. 8231 if (R.getAsSingle<NamespaceDecl>()) { 8232 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8233 << SS.getRange(); 8234 return BuildInvalid(); 8235 } 8236 8237 UsingDecl *UD = BuildValid(); 8238 8239 // The normal rules do not apply to inheriting constructor declarations. 8240 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 8241 // Suppress access diagnostics; the access check is instead performed at the 8242 // point of use for an inheriting constructor. 8243 R.suppressDiagnostics(); 8244 CheckInheritingConstructorUsingDecl(UD); 8245 return UD; 8246 } 8247 8248 // Otherwise, look up the target name. 8249 8250 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8251 UsingShadowDecl *PrevDecl = nullptr; 8252 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8253 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8254 } 8255 8256 return UD; 8257 } 8258 8259 /// Additional checks for a using declaration referring to a constructor name. 8260 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8261 assert(!UD->hasTypename() && "expecting a constructor name"); 8262 8263 const Type *SourceType = UD->getQualifier()->getAsType(); 8264 assert(SourceType && 8265 "Using decl naming constructor doesn't have type in scope spec."); 8266 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8267 8268 // Check whether the named type is a direct base class. 8269 bool AnyDependentBases = false; 8270 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8271 AnyDependentBases); 8272 if (!Base && !AnyDependentBases) { 8273 Diag(UD->getUsingLoc(), 8274 diag::err_using_decl_constructor_not_in_direct_base) 8275 << UD->getNameInfo().getSourceRange() 8276 << QualType(SourceType, 0) << TargetClass; 8277 UD->setInvalidDecl(); 8278 return true; 8279 } 8280 8281 if (Base) 8282 Base->setInheritConstructors(); 8283 8284 return false; 8285 } 8286 8287 /// Checks that the given using declaration is not an invalid 8288 /// redeclaration. Note that this is checking only for the using decl 8289 /// itself, not for any ill-formedness among the UsingShadowDecls. 8290 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8291 bool HasTypenameKeyword, 8292 const CXXScopeSpec &SS, 8293 SourceLocation NameLoc, 8294 const LookupResult &Prev) { 8295 // C++03 [namespace.udecl]p8: 8296 // C++0x [namespace.udecl]p10: 8297 // A using-declaration is a declaration and can therefore be used 8298 // repeatedly where (and only where) multiple declarations are 8299 // allowed. 8300 // 8301 // That's in non-member contexts. 8302 if (!CurContext->getRedeclContext()->isRecord()) 8303 return false; 8304 8305 NestedNameSpecifier *Qual = SS.getScopeRep(); 8306 8307 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8308 NamedDecl *D = *I; 8309 8310 bool DTypename; 8311 NestedNameSpecifier *DQual; 8312 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8313 DTypename = UD->hasTypename(); 8314 DQual = UD->getQualifier(); 8315 } else if (UnresolvedUsingValueDecl *UD 8316 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8317 DTypename = false; 8318 DQual = UD->getQualifier(); 8319 } else if (UnresolvedUsingTypenameDecl *UD 8320 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8321 DTypename = true; 8322 DQual = UD->getQualifier(); 8323 } else continue; 8324 8325 // using decls differ if one says 'typename' and the other doesn't. 8326 // FIXME: non-dependent using decls? 8327 if (HasTypenameKeyword != DTypename) continue; 8328 8329 // using decls differ if they name different scopes (but note that 8330 // template instantiation can cause this check to trigger when it 8331 // didn't before instantiation). 8332 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8333 Context.getCanonicalNestedNameSpecifier(DQual)) 8334 continue; 8335 8336 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8337 Diag(D->getLocation(), diag::note_using_decl) << 1; 8338 return true; 8339 } 8340 8341 return false; 8342 } 8343 8344 8345 /// Checks that the given nested-name qualifier used in a using decl 8346 /// in the current context is appropriately related to the current 8347 /// scope. If an error is found, diagnoses it and returns true. 8348 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8349 const CXXScopeSpec &SS, 8350 const DeclarationNameInfo &NameInfo, 8351 SourceLocation NameLoc) { 8352 DeclContext *NamedContext = computeDeclContext(SS); 8353 8354 if (!CurContext->isRecord()) { 8355 // C++03 [namespace.udecl]p3: 8356 // C++0x [namespace.udecl]p8: 8357 // A using-declaration for a class member shall be a member-declaration. 8358 8359 // If we weren't able to compute a valid scope, it must be a 8360 // dependent class scope. 8361 if (!NamedContext || NamedContext->isRecord()) { 8362 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext); 8363 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8364 RD = nullptr; 8365 8366 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8367 << SS.getRange(); 8368 8369 // If we have a complete, non-dependent source type, try to suggest a 8370 // way to get the same effect. 8371 if (!RD) 8372 return true; 8373 8374 // Find what this using-declaration was referring to. 8375 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8376 R.setHideTags(false); 8377 R.suppressDiagnostics(); 8378 LookupQualifiedName(R, RD); 8379 8380 if (R.getAsSingle<TypeDecl>()) { 8381 if (getLangOpts().CPlusPlus11) { 8382 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8383 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8384 << 0 // alias declaration 8385 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8386 NameInfo.getName().getAsString() + 8387 " = "); 8388 } else { 8389 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8390 SourceLocation InsertLoc = 8391 getLocForEndOfToken(NameInfo.getLocEnd()); 8392 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8393 << 1 // typedef declaration 8394 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8395 << FixItHint::CreateInsertion( 8396 InsertLoc, " " + NameInfo.getName().getAsString()); 8397 } 8398 } else if (R.getAsSingle<VarDecl>()) { 8399 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8400 // repeating the type of the static data member here. 8401 FixItHint FixIt; 8402 if (getLangOpts().CPlusPlus11) { 8403 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8404 FixIt = FixItHint::CreateReplacement( 8405 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8406 } 8407 8408 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8409 << 2 // reference declaration 8410 << FixIt; 8411 } 8412 return true; 8413 } 8414 8415 // Otherwise, everything is known to be fine. 8416 return false; 8417 } 8418 8419 // The current scope is a record. 8420 8421 // If the named context is dependent, we can't decide much. 8422 if (!NamedContext) { 8423 // FIXME: in C++0x, we can diagnose if we can prove that the 8424 // nested-name-specifier does not refer to a base class, which is 8425 // still possible in some cases. 8426 8427 // Otherwise we have to conservatively report that things might be 8428 // okay. 8429 return false; 8430 } 8431 8432 if (!NamedContext->isRecord()) { 8433 // Ideally this would point at the last name in the specifier, 8434 // but we don't have that level of source info. 8435 Diag(SS.getRange().getBegin(), 8436 diag::err_using_decl_nested_name_specifier_is_not_class) 8437 << SS.getScopeRep() << SS.getRange(); 8438 return true; 8439 } 8440 8441 if (!NamedContext->isDependentContext() && 8442 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8443 return true; 8444 8445 if (getLangOpts().CPlusPlus11) { 8446 // C++0x [namespace.udecl]p3: 8447 // In a using-declaration used as a member-declaration, the 8448 // nested-name-specifier shall name a base class of the class 8449 // being defined. 8450 8451 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8452 cast<CXXRecordDecl>(NamedContext))) { 8453 if (CurContext == NamedContext) { 8454 Diag(NameLoc, 8455 diag::err_using_decl_nested_name_specifier_is_current_class) 8456 << SS.getRange(); 8457 return true; 8458 } 8459 8460 Diag(SS.getRange().getBegin(), 8461 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8462 << SS.getScopeRep() 8463 << cast<CXXRecordDecl>(CurContext) 8464 << SS.getRange(); 8465 return true; 8466 } 8467 8468 return false; 8469 } 8470 8471 // C++03 [namespace.udecl]p4: 8472 // A using-declaration used as a member-declaration shall refer 8473 // to a member of a base class of the class being defined [etc.]. 8474 8475 // Salient point: SS doesn't have to name a base class as long as 8476 // lookup only finds members from base classes. Therefore we can 8477 // diagnose here only if we can prove that that can't happen, 8478 // i.e. if the class hierarchies provably don't intersect. 8479 8480 // TODO: it would be nice if "definitely valid" results were cached 8481 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8482 // need to be repeated. 8483 8484 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 8485 auto Collect = [&Bases](const CXXRecordDecl *Base) { 8486 Bases.insert(Base); 8487 return true; 8488 }; 8489 8490 // Collect all bases. Return false if we find a dependent base. 8491 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 8492 return false; 8493 8494 // Returns true if the base is dependent or is one of the accumulated base 8495 // classes. 8496 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 8497 return !Bases.count(Base); 8498 }; 8499 8500 // Return false if the class has a dependent base or if it or one 8501 // of its bases is present in the base set of the current context. 8502 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 8503 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 8504 return false; 8505 8506 Diag(SS.getRange().getBegin(), 8507 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8508 << SS.getScopeRep() 8509 << cast<CXXRecordDecl>(CurContext) 8510 << SS.getRange(); 8511 8512 return true; 8513 } 8514 8515 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8516 AccessSpecifier AS, 8517 MultiTemplateParamsArg TemplateParamLists, 8518 SourceLocation UsingLoc, 8519 UnqualifiedId &Name, 8520 AttributeList *AttrList, 8521 TypeResult Type, 8522 Decl *DeclFromDeclSpec) { 8523 // Skip up to the relevant declaration scope. 8524 while (S->isTemplateParamScope()) 8525 S = S->getParent(); 8526 assert((S->getFlags() & Scope::DeclScope) && 8527 "got alias-declaration outside of declaration scope"); 8528 8529 if (Type.isInvalid()) 8530 return nullptr; 8531 8532 bool Invalid = false; 8533 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8534 TypeSourceInfo *TInfo = nullptr; 8535 GetTypeFromParser(Type.get(), &TInfo); 8536 8537 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8538 return nullptr; 8539 8540 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8541 UPPC_DeclarationType)) { 8542 Invalid = true; 8543 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8544 TInfo->getTypeLoc().getBeginLoc()); 8545 } 8546 8547 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8548 LookupName(Previous, S); 8549 8550 // Warn about shadowing the name of a template parameter. 8551 if (Previous.isSingleResult() && 8552 Previous.getFoundDecl()->isTemplateParameter()) { 8553 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8554 Previous.clear(); 8555 } 8556 8557 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8558 "name in alias declaration must be an identifier"); 8559 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8560 Name.StartLocation, 8561 Name.Identifier, TInfo); 8562 8563 NewTD->setAccess(AS); 8564 8565 if (Invalid) 8566 NewTD->setInvalidDecl(); 8567 8568 ProcessDeclAttributeList(S, NewTD, AttrList); 8569 8570 CheckTypedefForVariablyModifiedType(S, NewTD); 8571 Invalid |= NewTD->isInvalidDecl(); 8572 8573 bool Redeclaration = false; 8574 8575 NamedDecl *NewND; 8576 if (TemplateParamLists.size()) { 8577 TypeAliasTemplateDecl *OldDecl = nullptr; 8578 TemplateParameterList *OldTemplateParams = nullptr; 8579 8580 if (TemplateParamLists.size() != 1) { 8581 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8582 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8583 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8584 } 8585 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8586 8587 // Only consider previous declarations in the same scope. 8588 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8589 /*ExplicitInstantiationOrSpecialization*/false); 8590 if (!Previous.empty()) { 8591 Redeclaration = true; 8592 8593 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8594 if (!OldDecl && !Invalid) { 8595 Diag(UsingLoc, diag::err_redefinition_different_kind) 8596 << Name.Identifier; 8597 8598 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8599 if (OldD->getLocation().isValid()) 8600 Diag(OldD->getLocation(), diag::note_previous_definition); 8601 8602 Invalid = true; 8603 } 8604 8605 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8606 if (TemplateParameterListsAreEqual(TemplateParams, 8607 OldDecl->getTemplateParameters(), 8608 /*Complain=*/true, 8609 TPL_TemplateMatch)) 8610 OldTemplateParams = OldDecl->getTemplateParameters(); 8611 else 8612 Invalid = true; 8613 8614 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8615 if (!Invalid && 8616 !Context.hasSameType(OldTD->getUnderlyingType(), 8617 NewTD->getUnderlyingType())) { 8618 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8619 // but we can't reasonably accept it. 8620 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8621 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8622 if (OldTD->getLocation().isValid()) 8623 Diag(OldTD->getLocation(), diag::note_previous_definition); 8624 Invalid = true; 8625 } 8626 } 8627 } 8628 8629 // Merge any previous default template arguments into our parameters, 8630 // and check the parameter list. 8631 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8632 TPC_TypeAliasTemplate)) 8633 return nullptr; 8634 8635 TypeAliasTemplateDecl *NewDecl = 8636 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8637 Name.Identifier, TemplateParams, 8638 NewTD); 8639 NewTD->setDescribedAliasTemplate(NewDecl); 8640 8641 NewDecl->setAccess(AS); 8642 8643 if (Invalid) 8644 NewDecl->setInvalidDecl(); 8645 else if (OldDecl) 8646 NewDecl->setPreviousDecl(OldDecl); 8647 8648 NewND = NewDecl; 8649 } else { 8650 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 8651 setTagNameForLinkagePurposes(TD, NewTD); 8652 handleTagNumbering(TD, S); 8653 } 8654 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8655 NewND = NewTD; 8656 } 8657 8658 if (!Redeclaration) 8659 PushOnScopeChains(NewND, S); 8660 8661 ActOnDocumentableDecl(NewND); 8662 return NewND; 8663 } 8664 8665 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8666 SourceLocation AliasLoc, 8667 IdentifierInfo *Alias, CXXScopeSpec &SS, 8668 SourceLocation IdentLoc, 8669 IdentifierInfo *Ident) { 8670 8671 // Lookup the namespace name. 8672 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8673 LookupParsedName(R, S, &SS); 8674 8675 if (R.isAmbiguous()) 8676 return nullptr; 8677 8678 if (R.empty()) { 8679 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8680 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8681 return nullptr; 8682 } 8683 } 8684 assert(!R.isAmbiguous() && !R.empty()); 8685 8686 // Check if we have a previous declaration with the same name. 8687 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 8688 ForRedeclaration); 8689 LookupQualifiedName(PrevR, CurContext->getRedeclContext()); 8690 NamedDecl *PrevDecl = PrevR.getAsSingle<NamedDecl>(); 8691 if (PrevDecl && !isVisible(PrevDecl)) 8692 PrevDecl = nullptr; 8693 8694 NamedDecl *ND = R.getFoundDecl(); 8695 8696 if (PrevDecl) { 8697 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8698 // We already have an alias with the same name that points to the same 8699 // namespace; check that it matches. 8700 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8701 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8702 << Alias; 8703 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8704 << AD->getNamespace(); 8705 return nullptr; 8706 } 8707 } else { 8708 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8709 ? diag::err_redefinition 8710 : diag::err_redefinition_different_kind; 8711 Diag(AliasLoc, DiagID) << Alias; 8712 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8713 return nullptr; 8714 } 8715 } 8716 8717 // The use of a nested name specifier may trigger deprecation warnings. 8718 DiagnoseUseOfDecl(ND, IdentLoc); 8719 8720 NamespaceAliasDecl *AliasDecl = 8721 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8722 Alias, SS.getWithLocInContext(Context), 8723 IdentLoc, ND); 8724 if (PrevDecl) 8725 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8726 8727 PushOnScopeChains(AliasDecl, S); 8728 return AliasDecl; 8729 } 8730 8731 Sema::ImplicitExceptionSpecification 8732 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8733 CXXMethodDecl *MD) { 8734 CXXRecordDecl *ClassDecl = MD->getParent(); 8735 8736 // C++ [except.spec]p14: 8737 // An implicitly declared special member function (Clause 12) shall have an 8738 // exception-specification. [...] 8739 ImplicitExceptionSpecification ExceptSpec(*this); 8740 if (ClassDecl->isInvalidDecl()) 8741 return ExceptSpec; 8742 8743 // Direct base-class constructors. 8744 for (const auto &B : ClassDecl->bases()) { 8745 if (B.isVirtual()) // Handled below. 8746 continue; 8747 8748 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8749 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8750 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8751 // If this is a deleted function, add it anyway. This might be conformant 8752 // with the standard. This might not. I'm not sure. It might not matter. 8753 if (Constructor) 8754 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8755 } 8756 } 8757 8758 // Virtual base-class constructors. 8759 for (const auto &B : ClassDecl->vbases()) { 8760 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8761 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8762 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8763 // If this is a deleted function, add it anyway. This might be conformant 8764 // with the standard. This might not. I'm not sure. It might not matter. 8765 if (Constructor) 8766 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8767 } 8768 } 8769 8770 // Field constructors. 8771 for (const auto *F : ClassDecl->fields()) { 8772 if (F->hasInClassInitializer()) { 8773 if (Expr *E = F->getInClassInitializer()) 8774 ExceptSpec.CalledExpr(E); 8775 } else if (const RecordType *RecordTy 8776 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8777 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8778 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8779 // If this is a deleted function, add it anyway. This might be conformant 8780 // with the standard. This might not. I'm not sure. It might not matter. 8781 // In particular, the problem is that this function never gets called. It 8782 // might just be ill-formed because this function attempts to refer to 8783 // a deleted function here. 8784 if (Constructor) 8785 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8786 } 8787 } 8788 8789 return ExceptSpec; 8790 } 8791 8792 Sema::ImplicitExceptionSpecification 8793 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8794 CXXRecordDecl *ClassDecl = CD->getParent(); 8795 8796 // C++ [except.spec]p14: 8797 // An inheriting constructor [...] shall have an exception-specification. [...] 8798 ImplicitExceptionSpecification ExceptSpec(*this); 8799 if (ClassDecl->isInvalidDecl()) 8800 return ExceptSpec; 8801 8802 // Inherited constructor. 8803 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8804 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8805 // FIXME: Copying or moving the parameters could add extra exceptions to the 8806 // set, as could the default arguments for the inherited constructor. This 8807 // will be addressed when we implement the resolution of core issue 1351. 8808 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8809 8810 // Direct base-class constructors. 8811 for (const auto &B : ClassDecl->bases()) { 8812 if (B.isVirtual()) // Handled below. 8813 continue; 8814 8815 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8816 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8817 if (BaseClassDecl == InheritedDecl) 8818 continue; 8819 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8820 if (Constructor) 8821 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8822 } 8823 } 8824 8825 // Virtual base-class constructors. 8826 for (const auto &B : ClassDecl->vbases()) { 8827 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8828 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8829 if (BaseClassDecl == InheritedDecl) 8830 continue; 8831 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8832 if (Constructor) 8833 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8834 } 8835 } 8836 8837 // Field constructors. 8838 for (const auto *F : ClassDecl->fields()) { 8839 if (F->hasInClassInitializer()) { 8840 if (Expr *E = F->getInClassInitializer()) 8841 ExceptSpec.CalledExpr(E); 8842 } else if (const RecordType *RecordTy 8843 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8844 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8845 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8846 if (Constructor) 8847 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8848 } 8849 } 8850 8851 return ExceptSpec; 8852 } 8853 8854 namespace { 8855 /// RAII object to register a special member as being currently declared. 8856 struct DeclaringSpecialMember { 8857 Sema &S; 8858 Sema::SpecialMemberDecl D; 8859 bool WasAlreadyBeingDeclared; 8860 8861 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8862 : S(S), D(RD, CSM) { 8863 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8864 if (WasAlreadyBeingDeclared) 8865 // This almost never happens, but if it does, ensure that our cache 8866 // doesn't contain a stale result. 8867 S.SpecialMemberCache.clear(); 8868 8869 // FIXME: Register a note to be produced if we encounter an error while 8870 // declaring the special member. 8871 } 8872 ~DeclaringSpecialMember() { 8873 if (!WasAlreadyBeingDeclared) 8874 S.SpecialMembersBeingDeclared.erase(D); 8875 } 8876 8877 /// \brief Are we already trying to declare this special member? 8878 bool isAlreadyBeingDeclared() const { 8879 return WasAlreadyBeingDeclared; 8880 } 8881 }; 8882 } 8883 8884 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8885 CXXRecordDecl *ClassDecl) { 8886 // C++ [class.ctor]p5: 8887 // A default constructor for a class X is a constructor of class X 8888 // that can be called without an argument. If there is no 8889 // user-declared constructor for class X, a default constructor is 8890 // implicitly declared. An implicitly-declared default constructor 8891 // is an inline public member of its class. 8892 assert(ClassDecl->needsImplicitDefaultConstructor() && 8893 "Should not build implicit default constructor!"); 8894 8895 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8896 if (DSM.isAlreadyBeingDeclared()) 8897 return nullptr; 8898 8899 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8900 CXXDefaultConstructor, 8901 false); 8902 8903 // Create the actual constructor declaration. 8904 CanQualType ClassType 8905 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8906 SourceLocation ClassLoc = ClassDecl->getLocation(); 8907 DeclarationName Name 8908 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8909 DeclarationNameInfo NameInfo(Name, ClassLoc); 8910 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8911 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8912 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8913 /*isImplicitlyDeclared=*/true, Constexpr); 8914 DefaultCon->setAccess(AS_public); 8915 DefaultCon->setDefaulted(); 8916 8917 if (getLangOpts().CUDA) { 8918 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8919 DefaultCon, 8920 /* ConstRHS */ false, 8921 /* Diagnose */ false); 8922 } 8923 8924 // Build an exception specification pointing back at this constructor. 8925 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8926 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8927 8928 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8929 // constructors is easy to compute. 8930 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8931 8932 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8933 SetDeclDeleted(DefaultCon, ClassLoc); 8934 8935 // Note that we have declared this constructor. 8936 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8937 8938 if (Scope *S = getScopeForContext(ClassDecl)) 8939 PushOnScopeChains(DefaultCon, S, false); 8940 ClassDecl->addDecl(DefaultCon); 8941 8942 return DefaultCon; 8943 } 8944 8945 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8946 CXXConstructorDecl *Constructor) { 8947 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8948 !Constructor->doesThisDeclarationHaveABody() && 8949 !Constructor->isDeleted()) && 8950 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8951 8952 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8953 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8954 8955 SynthesizedFunctionScope Scope(*this, Constructor); 8956 DiagnosticErrorTrap Trap(Diags); 8957 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8958 Trap.hasErrorOccurred()) { 8959 Diag(CurrentLocation, diag::note_member_synthesized_at) 8960 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8961 Constructor->setInvalidDecl(); 8962 return; 8963 } 8964 8965 // The exception specification is needed because we are defining the 8966 // function. 8967 ResolveExceptionSpec(CurrentLocation, 8968 Constructor->getType()->castAs<FunctionProtoType>()); 8969 8970 SourceLocation Loc = Constructor->getLocEnd().isValid() 8971 ? Constructor->getLocEnd() 8972 : Constructor->getLocation(); 8973 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8974 8975 Constructor->markUsed(Context); 8976 MarkVTableUsed(CurrentLocation, ClassDecl); 8977 8978 if (ASTMutationListener *L = getASTMutationListener()) { 8979 L->CompletedImplicitDefinition(Constructor); 8980 } 8981 8982 DiagnoseUninitializedFields(*this, Constructor); 8983 } 8984 8985 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8986 // Perform any delayed checks on exception specifications. 8987 CheckDelayedMemberExceptionSpecs(); 8988 } 8989 8990 namespace { 8991 /// Information on inheriting constructors to declare. 8992 class InheritingConstructorInfo { 8993 public: 8994 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8995 : SemaRef(SemaRef), Derived(Derived) { 8996 // Mark the constructors that we already have in the derived class. 8997 // 8998 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8999 // unless there is a user-declared constructor with the same signature in 9000 // the class where the using-declaration appears. 9001 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 9002 } 9003 9004 void inheritAll(CXXRecordDecl *RD) { 9005 visitAll(RD, &InheritingConstructorInfo::inherit); 9006 } 9007 9008 private: 9009 /// Information about an inheriting constructor. 9010 struct InheritingConstructor { 9011 InheritingConstructor() 9012 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 9013 9014 /// If \c true, a constructor with this signature is already declared 9015 /// in the derived class. 9016 bool DeclaredInDerived; 9017 9018 /// The constructor which is inherited. 9019 const CXXConstructorDecl *BaseCtor; 9020 9021 /// The derived constructor we declared. 9022 CXXConstructorDecl *DerivedCtor; 9023 }; 9024 9025 /// Inheriting constructors with a given canonical type. There can be at 9026 /// most one such non-template constructor, and any number of templated 9027 /// constructors. 9028 struct InheritingConstructorsForType { 9029 InheritingConstructor NonTemplate; 9030 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 9031 Templates; 9032 9033 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 9034 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 9035 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 9036 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 9037 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 9038 false, S.TPL_TemplateMatch)) 9039 return Templates[I].second; 9040 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 9041 return Templates.back().second; 9042 } 9043 9044 return NonTemplate; 9045 } 9046 }; 9047 9048 /// Get or create the inheriting constructor record for a constructor. 9049 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 9050 QualType CtorType) { 9051 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 9052 .getEntry(SemaRef, Ctor); 9053 } 9054 9055 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 9056 9057 /// Process all constructors for a class. 9058 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 9059 for (const auto *Ctor : RD->ctors()) 9060 (this->*Callback)(Ctor); 9061 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9062 I(RD->decls_begin()), E(RD->decls_end()); 9063 I != E; ++I) { 9064 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 9065 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 9066 (this->*Callback)(CD); 9067 } 9068 } 9069 9070 /// Note that a constructor (or constructor template) was declared in Derived. 9071 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 9072 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 9073 } 9074 9075 /// Inherit a single constructor. 9076 void inherit(const CXXConstructorDecl *Ctor) { 9077 const FunctionProtoType *CtorType = 9078 Ctor->getType()->castAs<FunctionProtoType>(); 9079 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 9080 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 9081 9082 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 9083 9084 // Core issue (no number yet): the ellipsis is always discarded. 9085 if (EPI.Variadic) { 9086 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 9087 SemaRef.Diag(Ctor->getLocation(), 9088 diag::note_using_decl_constructor_ellipsis); 9089 EPI.Variadic = false; 9090 } 9091 9092 // Declare a constructor for each number of parameters. 9093 // 9094 // C++11 [class.inhctor]p1: 9095 // The candidate set of inherited constructors from the class X named in 9096 // the using-declaration consists of [... modulo defects ...] for each 9097 // constructor or constructor template of X, the set of constructors or 9098 // constructor templates that results from omitting any ellipsis parameter 9099 // specification and successively omitting parameters with a default 9100 // argument from the end of the parameter-type-list 9101 unsigned MinParams = minParamsToInherit(Ctor); 9102 unsigned Params = Ctor->getNumParams(); 9103 if (Params >= MinParams) { 9104 do 9105 declareCtor(UsingLoc, Ctor, 9106 SemaRef.Context.getFunctionType( 9107 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 9108 while (Params > MinParams && 9109 Ctor->getParamDecl(--Params)->hasDefaultArg()); 9110 } 9111 } 9112 9113 /// Find the using-declaration which specified that we should inherit the 9114 /// constructors of \p Base. 9115 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 9116 // No fancy lookup required; just look for the base constructor name 9117 // directly within the derived class. 9118 ASTContext &Context = SemaRef.Context; 9119 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9120 Context.getCanonicalType(Context.getRecordType(Base))); 9121 DeclContext::lookup_result Decls = Derived->lookup(Name); 9122 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 9123 } 9124 9125 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 9126 // C++11 [class.inhctor]p3: 9127 // [F]or each constructor template in the candidate set of inherited 9128 // constructors, a constructor template is implicitly declared 9129 if (Ctor->getDescribedFunctionTemplate()) 9130 return 0; 9131 9132 // For each non-template constructor in the candidate set of inherited 9133 // constructors other than a constructor having no parameters or a 9134 // copy/move constructor having a single parameter, a constructor is 9135 // implicitly declared [...] 9136 if (Ctor->getNumParams() == 0) 9137 return 1; 9138 if (Ctor->isCopyOrMoveConstructor()) 9139 return 2; 9140 9141 // Per discussion on core reflector, never inherit a constructor which 9142 // would become a default, copy, or move constructor of Derived either. 9143 const ParmVarDecl *PD = Ctor->getParamDecl(0); 9144 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 9145 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 9146 } 9147 9148 /// Declare a single inheriting constructor, inheriting the specified 9149 /// constructor, with the given type. 9150 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 9151 QualType DerivedType) { 9152 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 9153 9154 // C++11 [class.inhctor]p3: 9155 // ... a constructor is implicitly declared with the same constructor 9156 // characteristics unless there is a user-declared constructor with 9157 // the same signature in the class where the using-declaration appears 9158 if (Entry.DeclaredInDerived) 9159 return; 9160 9161 // C++11 [class.inhctor]p7: 9162 // If two using-declarations declare inheriting constructors with the 9163 // same signature, the program is ill-formed 9164 if (Entry.DerivedCtor) { 9165 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 9166 // Only diagnose this once per constructor. 9167 if (Entry.DerivedCtor->isInvalidDecl()) 9168 return; 9169 Entry.DerivedCtor->setInvalidDecl(); 9170 9171 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9172 SemaRef.Diag(BaseCtor->getLocation(), 9173 diag::note_using_decl_constructor_conflict_current_ctor); 9174 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9175 diag::note_using_decl_constructor_conflict_previous_ctor); 9176 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9177 diag::note_using_decl_constructor_conflict_previous_using); 9178 } else { 9179 // Core issue (no number): if the same inheriting constructor is 9180 // produced by multiple base class constructors from the same base 9181 // class, the inheriting constructor is defined as deleted. 9182 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9183 } 9184 9185 return; 9186 } 9187 9188 ASTContext &Context = SemaRef.Context; 9189 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9190 Context.getCanonicalType(Context.getRecordType(Derived))); 9191 DeclarationNameInfo NameInfo(Name, UsingLoc); 9192 9193 TemplateParameterList *TemplateParams = nullptr; 9194 if (const FunctionTemplateDecl *FTD = 9195 BaseCtor->getDescribedFunctionTemplate()) { 9196 TemplateParams = FTD->getTemplateParameters(); 9197 // We're reusing template parameters from a different DeclContext. This 9198 // is questionable at best, but works out because the template depth in 9199 // both places is guaranteed to be 0. 9200 // FIXME: Rebuild the template parameters in the new context, and 9201 // transform the function type to refer to them. 9202 } 9203 9204 // Build type source info pointing at the using-declaration. This is 9205 // required by template instantiation. 9206 TypeSourceInfo *TInfo = 9207 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9208 FunctionProtoTypeLoc ProtoLoc = 9209 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9210 9211 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9212 Context, Derived, UsingLoc, NameInfo, DerivedType, 9213 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9214 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9215 9216 // Build an unevaluated exception specification for this constructor. 9217 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9218 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9219 EPI.ExceptionSpec.Type = EST_Unevaluated; 9220 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9221 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9222 FPT->getParamTypes(), EPI)); 9223 9224 // Build the parameter declarations. 9225 SmallVector<ParmVarDecl *, 16> ParamDecls; 9226 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9227 TypeSourceInfo *TInfo = 9228 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9229 ParmVarDecl *PD = ParmVarDecl::Create( 9230 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9231 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9232 PD->setScopeInfo(0, I); 9233 PD->setImplicit(); 9234 ParamDecls.push_back(PD); 9235 ProtoLoc.setParam(I, PD); 9236 } 9237 9238 // Set up the new constructor. 9239 DerivedCtor->setAccess(BaseCtor->getAccess()); 9240 DerivedCtor->setParams(ParamDecls); 9241 DerivedCtor->setInheritedConstructor(BaseCtor); 9242 if (BaseCtor->isDeleted()) 9243 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9244 9245 // If this is a constructor template, build the template declaration. 9246 if (TemplateParams) { 9247 FunctionTemplateDecl *DerivedTemplate = 9248 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9249 TemplateParams, DerivedCtor); 9250 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9251 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9252 Derived->addDecl(DerivedTemplate); 9253 } else { 9254 Derived->addDecl(DerivedCtor); 9255 } 9256 9257 Entry.BaseCtor = BaseCtor; 9258 Entry.DerivedCtor = DerivedCtor; 9259 } 9260 9261 Sema &SemaRef; 9262 CXXRecordDecl *Derived; 9263 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9264 MapType Map; 9265 }; 9266 } 9267 9268 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9269 // Defer declaring the inheriting constructors until the class is 9270 // instantiated. 9271 if (ClassDecl->isDependentContext()) 9272 return; 9273 9274 // Find base classes from which we might inherit constructors. 9275 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9276 for (const auto &BaseIt : ClassDecl->bases()) 9277 if (BaseIt.getInheritConstructors()) 9278 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9279 9280 // Go no further if we're not inheriting any constructors. 9281 if (InheritedBases.empty()) 9282 return; 9283 9284 // Declare the inherited constructors. 9285 InheritingConstructorInfo ICI(*this, ClassDecl); 9286 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9287 ICI.inheritAll(InheritedBases[I]); 9288 } 9289 9290 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9291 CXXConstructorDecl *Constructor) { 9292 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9293 assert(Constructor->getInheritedConstructor() && 9294 !Constructor->doesThisDeclarationHaveABody() && 9295 !Constructor->isDeleted()); 9296 9297 SynthesizedFunctionScope Scope(*this, Constructor); 9298 DiagnosticErrorTrap Trap(Diags); 9299 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9300 Trap.hasErrorOccurred()) { 9301 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9302 << Context.getTagDeclType(ClassDecl); 9303 Constructor->setInvalidDecl(); 9304 return; 9305 } 9306 9307 SourceLocation Loc = Constructor->getLocation(); 9308 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9309 9310 Constructor->markUsed(Context); 9311 MarkVTableUsed(CurrentLocation, ClassDecl); 9312 9313 if (ASTMutationListener *L = getASTMutationListener()) { 9314 L->CompletedImplicitDefinition(Constructor); 9315 } 9316 } 9317 9318 9319 Sema::ImplicitExceptionSpecification 9320 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9321 CXXRecordDecl *ClassDecl = MD->getParent(); 9322 9323 // C++ [except.spec]p14: 9324 // An implicitly declared special member function (Clause 12) shall have 9325 // an exception-specification. 9326 ImplicitExceptionSpecification ExceptSpec(*this); 9327 if (ClassDecl->isInvalidDecl()) 9328 return ExceptSpec; 9329 9330 // Direct base-class destructors. 9331 for (const auto &B : ClassDecl->bases()) { 9332 if (B.isVirtual()) // Handled below. 9333 continue; 9334 9335 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9336 ExceptSpec.CalledDecl(B.getLocStart(), 9337 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9338 } 9339 9340 // Virtual base-class destructors. 9341 for (const auto &B : ClassDecl->vbases()) { 9342 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9343 ExceptSpec.CalledDecl(B.getLocStart(), 9344 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9345 } 9346 9347 // Field destructors. 9348 for (const auto *F : ClassDecl->fields()) { 9349 if (const RecordType *RecordTy 9350 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9351 ExceptSpec.CalledDecl(F->getLocation(), 9352 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9353 } 9354 9355 return ExceptSpec; 9356 } 9357 9358 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9359 // C++ [class.dtor]p2: 9360 // If a class has no user-declared destructor, a destructor is 9361 // declared implicitly. An implicitly-declared destructor is an 9362 // inline public member of its class. 9363 assert(ClassDecl->needsImplicitDestructor()); 9364 9365 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9366 if (DSM.isAlreadyBeingDeclared()) 9367 return nullptr; 9368 9369 // Create the actual destructor declaration. 9370 CanQualType ClassType 9371 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9372 SourceLocation ClassLoc = ClassDecl->getLocation(); 9373 DeclarationName Name 9374 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9375 DeclarationNameInfo NameInfo(Name, ClassLoc); 9376 CXXDestructorDecl *Destructor 9377 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9378 QualType(), nullptr, /*isInline=*/true, 9379 /*isImplicitlyDeclared=*/true); 9380 Destructor->setAccess(AS_public); 9381 Destructor->setDefaulted(); 9382 9383 if (getLangOpts().CUDA) { 9384 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9385 Destructor, 9386 /* ConstRHS */ false, 9387 /* Diagnose */ false); 9388 } 9389 9390 // Build an exception specification pointing back at this destructor. 9391 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9392 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9393 9394 AddOverriddenMethods(ClassDecl, Destructor); 9395 9396 // We don't need to use SpecialMemberIsTrivial here; triviality for 9397 // destructors is easy to compute. 9398 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9399 9400 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9401 SetDeclDeleted(Destructor, ClassLoc); 9402 9403 // Note that we have declared this destructor. 9404 ++ASTContext::NumImplicitDestructorsDeclared; 9405 9406 // Introduce this destructor into its scope. 9407 if (Scope *S = getScopeForContext(ClassDecl)) 9408 PushOnScopeChains(Destructor, S, false); 9409 ClassDecl->addDecl(Destructor); 9410 9411 return Destructor; 9412 } 9413 9414 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9415 CXXDestructorDecl *Destructor) { 9416 assert((Destructor->isDefaulted() && 9417 !Destructor->doesThisDeclarationHaveABody() && 9418 !Destructor->isDeleted()) && 9419 "DefineImplicitDestructor - call it for implicit default dtor"); 9420 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9421 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9422 9423 if (Destructor->isInvalidDecl()) 9424 return; 9425 9426 SynthesizedFunctionScope Scope(*this, Destructor); 9427 9428 DiagnosticErrorTrap Trap(Diags); 9429 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9430 Destructor->getParent()); 9431 9432 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9433 Diag(CurrentLocation, diag::note_member_synthesized_at) 9434 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9435 9436 Destructor->setInvalidDecl(); 9437 return; 9438 } 9439 9440 // The exception specification is needed because we are defining the 9441 // function. 9442 ResolveExceptionSpec(CurrentLocation, 9443 Destructor->getType()->castAs<FunctionProtoType>()); 9444 9445 SourceLocation Loc = Destructor->getLocEnd().isValid() 9446 ? Destructor->getLocEnd() 9447 : Destructor->getLocation(); 9448 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9449 Destructor->markUsed(Context); 9450 MarkVTableUsed(CurrentLocation, ClassDecl); 9451 9452 if (ASTMutationListener *L = getASTMutationListener()) { 9453 L->CompletedImplicitDefinition(Destructor); 9454 } 9455 } 9456 9457 /// \brief Perform any semantic analysis which needs to be delayed until all 9458 /// pending class member declarations have been parsed. 9459 void Sema::ActOnFinishCXXMemberDecls() { 9460 // If the context is an invalid C++ class, just suppress these checks. 9461 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9462 if (Record->isInvalidDecl()) { 9463 DelayedDefaultedMemberExceptionSpecs.clear(); 9464 DelayedExceptionSpecChecks.clear(); 9465 return; 9466 } 9467 } 9468 } 9469 9470 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) { 9471 // Don't do anything for template patterns. 9472 if (Class->getDescribedClassTemplate()) 9473 return; 9474 9475 for (Decl *Member : Class->decls()) { 9476 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 9477 if (!CD) { 9478 // Recurse on nested classes. 9479 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member)) 9480 getDefaultArgExprsForConstructors(S, NestedRD); 9481 continue; 9482 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) { 9483 continue; 9484 } 9485 9486 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) { 9487 // Skip any default arguments that we've already instantiated. 9488 if (S.Context.getDefaultArgExprForConstructor(CD, I)) 9489 continue; 9490 9491 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD, 9492 CD->getParamDecl(I)).get(); 9493 S.DiscardCleanupsInEvaluationContext(); 9494 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 9495 } 9496 } 9497 } 9498 9499 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 9500 auto *RD = dyn_cast<CXXRecordDecl>(D); 9501 9502 // Default constructors that are annotated with __declspec(dllexport) which 9503 // have default arguments or don't use the standard calling convention are 9504 // wrapped with a thunk called the default constructor closure. 9505 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft()) 9506 getDefaultArgExprsForConstructors(*this, RD); 9507 9508 if (!DelayedDllExportClasses.empty()) { 9509 // Calling ReferenceDllExportedMethods might cause the current function to 9510 // be called again, so use a local copy of DelayedDllExportClasses. 9511 SmallVector<CXXRecordDecl *, 4> WorkList; 9512 std::swap(DelayedDllExportClasses, WorkList); 9513 for (CXXRecordDecl *Class : WorkList) 9514 ReferenceDllExportedMethods(*this, Class); 9515 } 9516 } 9517 9518 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9519 CXXDestructorDecl *Destructor) { 9520 assert(getLangOpts().CPlusPlus11 && 9521 "adjusting dtor exception specs was introduced in c++11"); 9522 9523 // C++11 [class.dtor]p3: 9524 // A declaration of a destructor that does not have an exception- 9525 // specification is implicitly considered to have the same exception- 9526 // specification as an implicit declaration. 9527 const FunctionProtoType *DtorType = Destructor->getType()-> 9528 getAs<FunctionProtoType>(); 9529 if (DtorType->hasExceptionSpec()) 9530 return; 9531 9532 // Replace the destructor's type, building off the existing one. Fortunately, 9533 // the only thing of interest in the destructor type is its extended info. 9534 // The return and arguments are fixed. 9535 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9536 EPI.ExceptionSpec.Type = EST_Unevaluated; 9537 EPI.ExceptionSpec.SourceDecl = Destructor; 9538 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9539 9540 // FIXME: If the destructor has a body that could throw, and the newly created 9541 // spec doesn't allow exceptions, we should emit a warning, because this 9542 // change in behavior can break conforming C++03 programs at runtime. 9543 // However, we don't have a body or an exception specification yet, so it 9544 // needs to be done somewhere else. 9545 } 9546 9547 namespace { 9548 /// \brief An abstract base class for all helper classes used in building the 9549 // copy/move operators. These classes serve as factory functions and help us 9550 // avoid using the same Expr* in the AST twice. 9551 class ExprBuilder { 9552 ExprBuilder(const ExprBuilder&) = delete; 9553 ExprBuilder &operator=(const ExprBuilder&) = delete; 9554 9555 protected: 9556 static Expr *assertNotNull(Expr *E) { 9557 assert(E && "Expression construction must not fail."); 9558 return E; 9559 } 9560 9561 public: 9562 ExprBuilder() {} 9563 virtual ~ExprBuilder() {} 9564 9565 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9566 }; 9567 9568 class RefBuilder: public ExprBuilder { 9569 VarDecl *Var; 9570 QualType VarType; 9571 9572 public: 9573 Expr *build(Sema &S, SourceLocation Loc) const override { 9574 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9575 } 9576 9577 RefBuilder(VarDecl *Var, QualType VarType) 9578 : Var(Var), VarType(VarType) {} 9579 }; 9580 9581 class ThisBuilder: public ExprBuilder { 9582 public: 9583 Expr *build(Sema &S, SourceLocation Loc) const override { 9584 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9585 } 9586 }; 9587 9588 class CastBuilder: public ExprBuilder { 9589 const ExprBuilder &Builder; 9590 QualType Type; 9591 ExprValueKind Kind; 9592 const CXXCastPath &Path; 9593 9594 public: 9595 Expr *build(Sema &S, SourceLocation Loc) const override { 9596 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9597 CK_UncheckedDerivedToBase, Kind, 9598 &Path).get()); 9599 } 9600 9601 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9602 const CXXCastPath &Path) 9603 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9604 }; 9605 9606 class DerefBuilder: public ExprBuilder { 9607 const ExprBuilder &Builder; 9608 9609 public: 9610 Expr *build(Sema &S, SourceLocation Loc) const override { 9611 return assertNotNull( 9612 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9613 } 9614 9615 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9616 }; 9617 9618 class MemberBuilder: public ExprBuilder { 9619 const ExprBuilder &Builder; 9620 QualType Type; 9621 CXXScopeSpec SS; 9622 bool IsArrow; 9623 LookupResult &MemberLookup; 9624 9625 public: 9626 Expr *build(Sema &S, SourceLocation Loc) const override { 9627 return assertNotNull(S.BuildMemberReferenceExpr( 9628 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9629 nullptr, MemberLookup, nullptr, nullptr).get()); 9630 } 9631 9632 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9633 LookupResult &MemberLookup) 9634 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9635 MemberLookup(MemberLookup) {} 9636 }; 9637 9638 class MoveCastBuilder: public ExprBuilder { 9639 const ExprBuilder &Builder; 9640 9641 public: 9642 Expr *build(Sema &S, SourceLocation Loc) const override { 9643 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9644 } 9645 9646 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9647 }; 9648 9649 class LvalueConvBuilder: public ExprBuilder { 9650 const ExprBuilder &Builder; 9651 9652 public: 9653 Expr *build(Sema &S, SourceLocation Loc) const override { 9654 return assertNotNull( 9655 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9656 } 9657 9658 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9659 }; 9660 9661 class SubscriptBuilder: public ExprBuilder { 9662 const ExprBuilder &Base; 9663 const ExprBuilder &Index; 9664 9665 public: 9666 Expr *build(Sema &S, SourceLocation Loc) const override { 9667 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9668 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9669 } 9670 9671 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9672 : Base(Base), Index(Index) {} 9673 }; 9674 9675 } // end anonymous namespace 9676 9677 /// When generating a defaulted copy or move assignment operator, if a field 9678 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9679 /// do so. This optimization only applies for arrays of scalars, and for arrays 9680 /// of class type where the selected copy/move-assignment operator is trivial. 9681 static StmtResult 9682 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9683 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9684 // Compute the size of the memory buffer to be copied. 9685 QualType SizeType = S.Context.getSizeType(); 9686 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9687 S.Context.getTypeSizeInChars(T).getQuantity()); 9688 9689 // Take the address of the field references for "from" and "to". We 9690 // directly construct UnaryOperators here because semantic analysis 9691 // does not permit us to take the address of an xvalue. 9692 Expr *From = FromB.build(S, Loc); 9693 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9694 S.Context.getPointerType(From->getType()), 9695 VK_RValue, OK_Ordinary, Loc); 9696 Expr *To = ToB.build(S, Loc); 9697 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9698 S.Context.getPointerType(To->getType()), 9699 VK_RValue, OK_Ordinary, Loc); 9700 9701 const Type *E = T->getBaseElementTypeUnsafe(); 9702 bool NeedsCollectableMemCpy = 9703 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9704 9705 // Create a reference to the __builtin_objc_memmove_collectable function 9706 StringRef MemCpyName = NeedsCollectableMemCpy ? 9707 "__builtin_objc_memmove_collectable" : 9708 "__builtin_memcpy"; 9709 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9710 Sema::LookupOrdinaryName); 9711 S.LookupName(R, S.TUScope, true); 9712 9713 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9714 if (!MemCpy) 9715 // Something went horribly wrong earlier, and we will have complained 9716 // about it. 9717 return StmtError(); 9718 9719 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9720 VK_RValue, Loc, nullptr); 9721 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9722 9723 Expr *CallArgs[] = { 9724 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9725 }; 9726 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9727 Loc, CallArgs, Loc); 9728 9729 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9730 return Call.getAs<Stmt>(); 9731 } 9732 9733 /// \brief Builds a statement that copies/moves the given entity from \p From to 9734 /// \c To. 9735 /// 9736 /// This routine is used to copy/move the members of a class with an 9737 /// implicitly-declared copy/move assignment operator. When the entities being 9738 /// copied are arrays, this routine builds for loops to copy them. 9739 /// 9740 /// \param S The Sema object used for type-checking. 9741 /// 9742 /// \param Loc The location where the implicit copy/move is being generated. 9743 /// 9744 /// \param T The type of the expressions being copied/moved. Both expressions 9745 /// must have this type. 9746 /// 9747 /// \param To The expression we are copying/moving to. 9748 /// 9749 /// \param From The expression we are copying/moving from. 9750 /// 9751 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9752 /// Otherwise, it's a non-static member subobject. 9753 /// 9754 /// \param Copying Whether we're copying or moving. 9755 /// 9756 /// \param Depth Internal parameter recording the depth of the recursion. 9757 /// 9758 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9759 /// if a memcpy should be used instead. 9760 static StmtResult 9761 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9762 const ExprBuilder &To, const ExprBuilder &From, 9763 bool CopyingBaseSubobject, bool Copying, 9764 unsigned Depth = 0) { 9765 // C++11 [class.copy]p28: 9766 // Each subobject is assigned in the manner appropriate to its type: 9767 // 9768 // - if the subobject is of class type, as if by a call to operator= with 9769 // the subobject as the object expression and the corresponding 9770 // subobject of x as a single function argument (as if by explicit 9771 // qualification; that is, ignoring any possible virtual overriding 9772 // functions in more derived classes); 9773 // 9774 // C++03 [class.copy]p13: 9775 // - if the subobject is of class type, the copy assignment operator for 9776 // the class is used (as if by explicit qualification; that is, 9777 // ignoring any possible virtual overriding functions in more derived 9778 // classes); 9779 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9780 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9781 9782 // Look for operator=. 9783 DeclarationName Name 9784 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9785 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9786 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9787 9788 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9789 // operator. 9790 if (!S.getLangOpts().CPlusPlus11) { 9791 LookupResult::Filter F = OpLookup.makeFilter(); 9792 while (F.hasNext()) { 9793 NamedDecl *D = F.next(); 9794 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9795 if (Method->isCopyAssignmentOperator() || 9796 (!Copying && Method->isMoveAssignmentOperator())) 9797 continue; 9798 9799 F.erase(); 9800 } 9801 F.done(); 9802 } 9803 9804 // Suppress the protected check (C++ [class.protected]) for each of the 9805 // assignment operators we found. This strange dance is required when 9806 // we're assigning via a base classes's copy-assignment operator. To 9807 // ensure that we're getting the right base class subobject (without 9808 // ambiguities), we need to cast "this" to that subobject type; to 9809 // ensure that we don't go through the virtual call mechanism, we need 9810 // to qualify the operator= name with the base class (see below). However, 9811 // this means that if the base class has a protected copy assignment 9812 // operator, the protected member access check will fail. So, we 9813 // rewrite "protected" access to "public" access in this case, since we 9814 // know by construction that we're calling from a derived class. 9815 if (CopyingBaseSubobject) { 9816 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9817 L != LEnd; ++L) { 9818 if (L.getAccess() == AS_protected) 9819 L.setAccess(AS_public); 9820 } 9821 } 9822 9823 // Create the nested-name-specifier that will be used to qualify the 9824 // reference to operator=; this is required to suppress the virtual 9825 // call mechanism. 9826 CXXScopeSpec SS; 9827 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9828 SS.MakeTrivial(S.Context, 9829 NestedNameSpecifier::Create(S.Context, nullptr, false, 9830 CanonicalT), 9831 Loc); 9832 9833 // Create the reference to operator=. 9834 ExprResult OpEqualRef 9835 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9836 SS, /*TemplateKWLoc=*/SourceLocation(), 9837 /*FirstQualifierInScope=*/nullptr, 9838 OpLookup, 9839 /*TemplateArgs=*/nullptr, /*S*/nullptr, 9840 /*SuppressQualifierCheck=*/true); 9841 if (OpEqualRef.isInvalid()) 9842 return StmtError(); 9843 9844 // Build the call to the assignment operator. 9845 9846 Expr *FromInst = From.build(S, Loc); 9847 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9848 OpEqualRef.getAs<Expr>(), 9849 Loc, FromInst, Loc); 9850 if (Call.isInvalid()) 9851 return StmtError(); 9852 9853 // If we built a call to a trivial 'operator=' while copying an array, 9854 // bail out. We'll replace the whole shebang with a memcpy. 9855 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9856 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9857 return StmtResult((Stmt*)nullptr); 9858 9859 // Convert to an expression-statement, and clean up any produced 9860 // temporaries. 9861 return S.ActOnExprStmt(Call); 9862 } 9863 9864 // - if the subobject is of scalar type, the built-in assignment 9865 // operator is used. 9866 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9867 if (!ArrayTy) { 9868 ExprResult Assignment = S.CreateBuiltinBinOp( 9869 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9870 if (Assignment.isInvalid()) 9871 return StmtError(); 9872 return S.ActOnExprStmt(Assignment); 9873 } 9874 9875 // - if the subobject is an array, each element is assigned, in the 9876 // manner appropriate to the element type; 9877 9878 // Construct a loop over the array bounds, e.g., 9879 // 9880 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9881 // 9882 // that will copy each of the array elements. 9883 QualType SizeType = S.Context.getSizeType(); 9884 9885 // Create the iteration variable. 9886 IdentifierInfo *IterationVarName = nullptr; 9887 { 9888 SmallString<8> Str; 9889 llvm::raw_svector_ostream OS(Str); 9890 OS << "__i" << Depth; 9891 IterationVarName = &S.Context.Idents.get(OS.str()); 9892 } 9893 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9894 IterationVarName, SizeType, 9895 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9896 SC_None); 9897 9898 // Initialize the iteration variable to zero. 9899 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9900 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9901 9902 // Creates a reference to the iteration variable. 9903 RefBuilder IterationVarRef(IterationVar, SizeType); 9904 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9905 9906 // Create the DeclStmt that holds the iteration variable. 9907 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9908 9909 // Subscript the "from" and "to" expressions with the iteration variable. 9910 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9911 MoveCastBuilder FromIndexMove(FromIndexCopy); 9912 const ExprBuilder *FromIndex; 9913 if (Copying) 9914 FromIndex = &FromIndexCopy; 9915 else 9916 FromIndex = &FromIndexMove; 9917 9918 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9919 9920 // Build the copy/move for an individual element of the array. 9921 StmtResult Copy = 9922 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9923 ToIndex, *FromIndex, CopyingBaseSubobject, 9924 Copying, Depth + 1); 9925 // Bail out if copying fails or if we determined that we should use memcpy. 9926 if (Copy.isInvalid() || !Copy.get()) 9927 return Copy; 9928 9929 // Create the comparison against the array bound. 9930 llvm::APInt Upper 9931 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9932 Expr *Comparison 9933 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9934 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9935 BO_NE, S.Context.BoolTy, 9936 VK_RValue, OK_Ordinary, Loc, false); 9937 9938 // Create the pre-increment of the iteration variable. 9939 Expr *Increment 9940 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9941 SizeType, VK_LValue, OK_Ordinary, Loc); 9942 9943 // Construct the loop that copies all elements of this array. 9944 return S.ActOnForStmt(Loc, Loc, InitStmt, 9945 S.MakeFullExpr(Comparison), 9946 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9947 Loc, Copy.get()); 9948 } 9949 9950 static StmtResult 9951 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9952 const ExprBuilder &To, const ExprBuilder &From, 9953 bool CopyingBaseSubobject, bool Copying) { 9954 // Maybe we should use a memcpy? 9955 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9956 T.isTriviallyCopyableType(S.Context)) 9957 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9958 9959 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9960 CopyingBaseSubobject, 9961 Copying, 0)); 9962 9963 // If we ended up picking a trivial assignment operator for an array of a 9964 // non-trivially-copyable class type, just emit a memcpy. 9965 if (!Result.isInvalid() && !Result.get()) 9966 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9967 9968 return Result; 9969 } 9970 9971 Sema::ImplicitExceptionSpecification 9972 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9973 CXXRecordDecl *ClassDecl = MD->getParent(); 9974 9975 ImplicitExceptionSpecification ExceptSpec(*this); 9976 if (ClassDecl->isInvalidDecl()) 9977 return ExceptSpec; 9978 9979 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9980 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9981 unsigned ArgQuals = 9982 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9983 9984 // C++ [except.spec]p14: 9985 // An implicitly declared special member function (Clause 12) shall have an 9986 // exception-specification. [...] 9987 9988 // It is unspecified whether or not an implicit copy assignment operator 9989 // attempts to deduplicate calls to assignment operators of virtual bases are 9990 // made. As such, this exception specification is effectively unspecified. 9991 // Based on a similar decision made for constness in C++0x, we're erring on 9992 // the side of assuming such calls to be made regardless of whether they 9993 // actually happen. 9994 for (const auto &Base : ClassDecl->bases()) { 9995 if (Base.isVirtual()) 9996 continue; 9997 9998 CXXRecordDecl *BaseClassDecl 9999 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10000 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10001 ArgQuals, false, 0)) 10002 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10003 } 10004 10005 for (const auto &Base : ClassDecl->vbases()) { 10006 CXXRecordDecl *BaseClassDecl 10007 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10008 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10009 ArgQuals, false, 0)) 10010 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10011 } 10012 10013 for (const auto *Field : ClassDecl->fields()) { 10014 QualType FieldType = Context.getBaseElementType(Field->getType()); 10015 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10016 if (CXXMethodDecl *CopyAssign = 10017 LookupCopyingAssignment(FieldClassDecl, 10018 ArgQuals | FieldType.getCVRQualifiers(), 10019 false, 0)) 10020 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 10021 } 10022 } 10023 10024 return ExceptSpec; 10025 } 10026 10027 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 10028 // Note: The following rules are largely analoguous to the copy 10029 // constructor rules. Note that virtual bases are not taken into account 10030 // for determining the argument type of the operator. Note also that 10031 // operators taking an object instead of a reference are allowed. 10032 assert(ClassDecl->needsImplicitCopyAssignment()); 10033 10034 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 10035 if (DSM.isAlreadyBeingDeclared()) 10036 return nullptr; 10037 10038 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10039 QualType RetType = Context.getLValueReferenceType(ArgType); 10040 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 10041 if (Const) 10042 ArgType = ArgType.withConst(); 10043 ArgType = Context.getLValueReferenceType(ArgType); 10044 10045 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10046 CXXCopyAssignment, 10047 Const); 10048 10049 // An implicitly-declared copy assignment operator is an inline public 10050 // member of its class. 10051 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10052 SourceLocation ClassLoc = ClassDecl->getLocation(); 10053 DeclarationNameInfo NameInfo(Name, ClassLoc); 10054 CXXMethodDecl *CopyAssignment = 10055 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10056 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10057 /*isInline=*/true, Constexpr, SourceLocation()); 10058 CopyAssignment->setAccess(AS_public); 10059 CopyAssignment->setDefaulted(); 10060 CopyAssignment->setImplicit(); 10061 10062 if (getLangOpts().CUDA) { 10063 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 10064 CopyAssignment, 10065 /* ConstRHS */ Const, 10066 /* Diagnose */ false); 10067 } 10068 10069 // Build an exception specification pointing back at this member. 10070 FunctionProtoType::ExtProtoInfo EPI = 10071 getImplicitMethodEPI(*this, CopyAssignment); 10072 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10073 10074 // Add the parameter to the operator. 10075 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 10076 ClassLoc, ClassLoc, 10077 /*Id=*/nullptr, ArgType, 10078 /*TInfo=*/nullptr, SC_None, 10079 nullptr); 10080 CopyAssignment->setParams(FromParam); 10081 10082 AddOverriddenMethods(ClassDecl, CopyAssignment); 10083 10084 CopyAssignment->setTrivial( 10085 ClassDecl->needsOverloadResolutionForCopyAssignment() 10086 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 10087 : ClassDecl->hasTrivialCopyAssignment()); 10088 10089 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 10090 SetDeclDeleted(CopyAssignment, ClassLoc); 10091 10092 // Note that we have added this copy-assignment operator. 10093 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10094 10095 if (Scope *S = getScopeForContext(ClassDecl)) 10096 PushOnScopeChains(CopyAssignment, S, false); 10097 ClassDecl->addDecl(CopyAssignment); 10098 10099 return CopyAssignment; 10100 } 10101 10102 /// Diagnose an implicit copy operation for a class which is odr-used, but 10103 /// which is deprecated because the class has a user-declared copy constructor, 10104 /// copy assignment operator, or destructor. 10105 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 10106 SourceLocation UseLoc) { 10107 assert(CopyOp->isImplicit()); 10108 10109 CXXRecordDecl *RD = CopyOp->getParent(); 10110 CXXMethodDecl *UserDeclaredOperation = nullptr; 10111 10112 // In Microsoft mode, assignment operations don't affect constructors and 10113 // vice versa. 10114 if (RD->hasUserDeclaredDestructor()) { 10115 UserDeclaredOperation = RD->getDestructor(); 10116 } else if (!isa<CXXConstructorDecl>(CopyOp) && 10117 RD->hasUserDeclaredCopyConstructor() && 10118 !S.getLangOpts().MSVCCompat) { 10119 // Find any user-declared copy constructor. 10120 for (auto *I : RD->ctors()) { 10121 if (I->isCopyConstructor()) { 10122 UserDeclaredOperation = I; 10123 break; 10124 } 10125 } 10126 assert(UserDeclaredOperation); 10127 } else if (isa<CXXConstructorDecl>(CopyOp) && 10128 RD->hasUserDeclaredCopyAssignment() && 10129 !S.getLangOpts().MSVCCompat) { 10130 // Find any user-declared move assignment operator. 10131 for (auto *I : RD->methods()) { 10132 if (I->isCopyAssignmentOperator()) { 10133 UserDeclaredOperation = I; 10134 break; 10135 } 10136 } 10137 assert(UserDeclaredOperation); 10138 } 10139 10140 if (UserDeclaredOperation) { 10141 S.Diag(UserDeclaredOperation->getLocation(), 10142 diag::warn_deprecated_copy_operation) 10143 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 10144 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 10145 S.Diag(UseLoc, diag::note_member_synthesized_at) 10146 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 10147 : Sema::CXXCopyAssignment) 10148 << RD; 10149 } 10150 } 10151 10152 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 10153 CXXMethodDecl *CopyAssignOperator) { 10154 assert((CopyAssignOperator->isDefaulted() && 10155 CopyAssignOperator->isOverloadedOperator() && 10156 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 10157 !CopyAssignOperator->doesThisDeclarationHaveABody() && 10158 !CopyAssignOperator->isDeleted()) && 10159 "DefineImplicitCopyAssignment called for wrong function"); 10160 10161 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 10162 10163 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 10164 CopyAssignOperator->setInvalidDecl(); 10165 return; 10166 } 10167 10168 // C++11 [class.copy]p18: 10169 // The [definition of an implicitly declared copy assignment operator] is 10170 // deprecated if the class has a user-declared copy constructor or a 10171 // user-declared destructor. 10172 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 10173 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 10174 10175 CopyAssignOperator->markUsed(Context); 10176 10177 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 10178 DiagnosticErrorTrap Trap(Diags); 10179 10180 // C++0x [class.copy]p30: 10181 // The implicitly-defined or explicitly-defaulted copy assignment operator 10182 // for a non-union class X performs memberwise copy assignment of its 10183 // subobjects. The direct base classes of X are assigned first, in the 10184 // order of their declaration in the base-specifier-list, and then the 10185 // immediate non-static data members of X are assigned, in the order in 10186 // which they were declared in the class definition. 10187 10188 // The statements that form the synthesized function body. 10189 SmallVector<Stmt*, 8> Statements; 10190 10191 // The parameter for the "other" object, which we are copying from. 10192 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 10193 Qualifiers OtherQuals = Other->getType().getQualifiers(); 10194 QualType OtherRefType = Other->getType(); 10195 if (const LValueReferenceType *OtherRef 10196 = OtherRefType->getAs<LValueReferenceType>()) { 10197 OtherRefType = OtherRef->getPointeeType(); 10198 OtherQuals = OtherRefType.getQualifiers(); 10199 } 10200 10201 // Our location for everything implicitly-generated. 10202 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 10203 ? CopyAssignOperator->getLocEnd() 10204 : CopyAssignOperator->getLocation(); 10205 10206 // Builds a DeclRefExpr for the "other" object. 10207 RefBuilder OtherRef(Other, OtherRefType); 10208 10209 // Builds the "this" pointer. 10210 ThisBuilder This; 10211 10212 // Assign base classes. 10213 bool Invalid = false; 10214 for (auto &Base : ClassDecl->bases()) { 10215 // Form the assignment: 10216 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10217 QualType BaseType = Base.getType().getUnqualifiedType(); 10218 if (!BaseType->isRecordType()) { 10219 Invalid = true; 10220 continue; 10221 } 10222 10223 CXXCastPath BasePath; 10224 BasePath.push_back(&Base); 10225 10226 // Construct the "from" expression, which is an implicit cast to the 10227 // appropriately-qualified base type. 10228 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10229 VK_LValue, BasePath); 10230 10231 // Dereference "this". 10232 DerefBuilder DerefThis(This); 10233 CastBuilder To(DerefThis, 10234 Context.getCVRQualifiedType( 10235 BaseType, CopyAssignOperator->getTypeQualifiers()), 10236 VK_LValue, BasePath); 10237 10238 // Build the copy. 10239 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10240 To, From, 10241 /*CopyingBaseSubobject=*/true, 10242 /*Copying=*/true); 10243 if (Copy.isInvalid()) { 10244 Diag(CurrentLocation, diag::note_member_synthesized_at) 10245 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10246 CopyAssignOperator->setInvalidDecl(); 10247 return; 10248 } 10249 10250 // Success! Record the copy. 10251 Statements.push_back(Copy.getAs<Expr>()); 10252 } 10253 10254 // Assign non-static members. 10255 for (auto *Field : ClassDecl->fields()) { 10256 // FIXME: We should form some kind of AST representation for the implied 10257 // memcpy in a union copy operation. 10258 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10259 continue; 10260 10261 if (Field->isInvalidDecl()) { 10262 Invalid = true; 10263 continue; 10264 } 10265 10266 // Check for members of reference type; we can't copy those. 10267 if (Field->getType()->isReferenceType()) { 10268 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10269 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10270 Diag(Field->getLocation(), diag::note_declared_at); 10271 Diag(CurrentLocation, diag::note_member_synthesized_at) 10272 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10273 Invalid = true; 10274 continue; 10275 } 10276 10277 // Check for members of const-qualified, non-class type. 10278 QualType BaseType = Context.getBaseElementType(Field->getType()); 10279 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10280 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10281 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10282 Diag(Field->getLocation(), diag::note_declared_at); 10283 Diag(CurrentLocation, diag::note_member_synthesized_at) 10284 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10285 Invalid = true; 10286 continue; 10287 } 10288 10289 // Suppress assigning zero-width bitfields. 10290 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10291 continue; 10292 10293 QualType FieldType = Field->getType().getNonReferenceType(); 10294 if (FieldType->isIncompleteArrayType()) { 10295 assert(ClassDecl->hasFlexibleArrayMember() && 10296 "Incomplete array type is not valid"); 10297 continue; 10298 } 10299 10300 // Build references to the field in the object we're copying from and to. 10301 CXXScopeSpec SS; // Intentionally empty 10302 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10303 LookupMemberName); 10304 MemberLookup.addDecl(Field); 10305 MemberLookup.resolveKind(); 10306 10307 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10308 10309 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10310 10311 // Build the copy of this field. 10312 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10313 To, From, 10314 /*CopyingBaseSubobject=*/false, 10315 /*Copying=*/true); 10316 if (Copy.isInvalid()) { 10317 Diag(CurrentLocation, diag::note_member_synthesized_at) 10318 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10319 CopyAssignOperator->setInvalidDecl(); 10320 return; 10321 } 10322 10323 // Success! Record the copy. 10324 Statements.push_back(Copy.getAs<Stmt>()); 10325 } 10326 10327 if (!Invalid) { 10328 // Add a "return *this;" 10329 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10330 10331 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10332 if (Return.isInvalid()) 10333 Invalid = true; 10334 else { 10335 Statements.push_back(Return.getAs<Stmt>()); 10336 10337 if (Trap.hasErrorOccurred()) { 10338 Diag(CurrentLocation, diag::note_member_synthesized_at) 10339 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10340 Invalid = true; 10341 } 10342 } 10343 } 10344 10345 // The exception specification is needed because we are defining the 10346 // function. 10347 ResolveExceptionSpec(CurrentLocation, 10348 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10349 10350 if (Invalid) { 10351 CopyAssignOperator->setInvalidDecl(); 10352 return; 10353 } 10354 10355 StmtResult Body; 10356 { 10357 CompoundScopeRAII CompoundScope(*this); 10358 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10359 /*isStmtExpr=*/false); 10360 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10361 } 10362 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10363 10364 if (ASTMutationListener *L = getASTMutationListener()) { 10365 L->CompletedImplicitDefinition(CopyAssignOperator); 10366 } 10367 } 10368 10369 Sema::ImplicitExceptionSpecification 10370 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10371 CXXRecordDecl *ClassDecl = MD->getParent(); 10372 10373 ImplicitExceptionSpecification ExceptSpec(*this); 10374 if (ClassDecl->isInvalidDecl()) 10375 return ExceptSpec; 10376 10377 // C++0x [except.spec]p14: 10378 // An implicitly declared special member function (Clause 12) shall have an 10379 // exception-specification. [...] 10380 10381 // It is unspecified whether or not an implicit move assignment operator 10382 // attempts to deduplicate calls to assignment operators of virtual bases are 10383 // made. As such, this exception specification is effectively unspecified. 10384 // Based on a similar decision made for constness in C++0x, we're erring on 10385 // the side of assuming such calls to be made regardless of whether they 10386 // actually happen. 10387 // Note that a move constructor is not implicitly declared when there are 10388 // virtual bases, but it can still be user-declared and explicitly defaulted. 10389 for (const auto &Base : ClassDecl->bases()) { 10390 if (Base.isVirtual()) 10391 continue; 10392 10393 CXXRecordDecl *BaseClassDecl 10394 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10395 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10396 0, false, 0)) 10397 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10398 } 10399 10400 for (const auto &Base : ClassDecl->vbases()) { 10401 CXXRecordDecl *BaseClassDecl 10402 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10403 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10404 0, false, 0)) 10405 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10406 } 10407 10408 for (const auto *Field : ClassDecl->fields()) { 10409 QualType FieldType = Context.getBaseElementType(Field->getType()); 10410 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10411 if (CXXMethodDecl *MoveAssign = 10412 LookupMovingAssignment(FieldClassDecl, 10413 FieldType.getCVRQualifiers(), 10414 false, 0)) 10415 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10416 } 10417 } 10418 10419 return ExceptSpec; 10420 } 10421 10422 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10423 assert(ClassDecl->needsImplicitMoveAssignment()); 10424 10425 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10426 if (DSM.isAlreadyBeingDeclared()) 10427 return nullptr; 10428 10429 // Note: The following rules are largely analoguous to the move 10430 // constructor rules. 10431 10432 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10433 QualType RetType = Context.getLValueReferenceType(ArgType); 10434 ArgType = Context.getRValueReferenceType(ArgType); 10435 10436 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10437 CXXMoveAssignment, 10438 false); 10439 10440 // An implicitly-declared move assignment operator is an inline public 10441 // member of its class. 10442 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10443 SourceLocation ClassLoc = ClassDecl->getLocation(); 10444 DeclarationNameInfo NameInfo(Name, ClassLoc); 10445 CXXMethodDecl *MoveAssignment = 10446 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10447 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10448 /*isInline=*/true, Constexpr, SourceLocation()); 10449 MoveAssignment->setAccess(AS_public); 10450 MoveAssignment->setDefaulted(); 10451 MoveAssignment->setImplicit(); 10452 10453 if (getLangOpts().CUDA) { 10454 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10455 MoveAssignment, 10456 /* ConstRHS */ false, 10457 /* Diagnose */ false); 10458 } 10459 10460 // Build an exception specification pointing back at this member. 10461 FunctionProtoType::ExtProtoInfo EPI = 10462 getImplicitMethodEPI(*this, MoveAssignment); 10463 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10464 10465 // Add the parameter to the operator. 10466 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10467 ClassLoc, ClassLoc, 10468 /*Id=*/nullptr, ArgType, 10469 /*TInfo=*/nullptr, SC_None, 10470 nullptr); 10471 MoveAssignment->setParams(FromParam); 10472 10473 AddOverriddenMethods(ClassDecl, MoveAssignment); 10474 10475 MoveAssignment->setTrivial( 10476 ClassDecl->needsOverloadResolutionForMoveAssignment() 10477 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10478 : ClassDecl->hasTrivialMoveAssignment()); 10479 10480 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10481 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10482 SetDeclDeleted(MoveAssignment, ClassLoc); 10483 } 10484 10485 // Note that we have added this copy-assignment operator. 10486 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10487 10488 if (Scope *S = getScopeForContext(ClassDecl)) 10489 PushOnScopeChains(MoveAssignment, S, false); 10490 ClassDecl->addDecl(MoveAssignment); 10491 10492 return MoveAssignment; 10493 } 10494 10495 /// Check if we're implicitly defining a move assignment operator for a class 10496 /// with virtual bases. Such a move assignment might move-assign the virtual 10497 /// base multiple times. 10498 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10499 SourceLocation CurrentLocation) { 10500 assert(!Class->isDependentContext() && "should not define dependent move"); 10501 10502 // Only a virtual base could get implicitly move-assigned multiple times. 10503 // Only a non-trivial move assignment can observe this. We only want to 10504 // diagnose if we implicitly define an assignment operator that assigns 10505 // two base classes, both of which move-assign the same virtual base. 10506 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10507 Class->getNumBases() < 2) 10508 return; 10509 10510 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10511 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10512 VBaseMap VBases; 10513 10514 for (auto &BI : Class->bases()) { 10515 Worklist.push_back(&BI); 10516 while (!Worklist.empty()) { 10517 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10518 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10519 10520 // If the base has no non-trivial move assignment operators, 10521 // we don't care about moves from it. 10522 if (!Base->hasNonTrivialMoveAssignment()) 10523 continue; 10524 10525 // If there's nothing virtual here, skip it. 10526 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10527 continue; 10528 10529 // If we're not actually going to call a move assignment for this base, 10530 // or the selected move assignment is trivial, skip it. 10531 Sema::SpecialMemberOverloadResult *SMOR = 10532 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10533 /*ConstArg*/false, /*VolatileArg*/false, 10534 /*RValueThis*/true, /*ConstThis*/false, 10535 /*VolatileThis*/false); 10536 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10537 !SMOR->getMethod()->isMoveAssignmentOperator()) 10538 continue; 10539 10540 if (BaseSpec->isVirtual()) { 10541 // We're going to move-assign this virtual base, and its move 10542 // assignment operator is not trivial. If this can happen for 10543 // multiple distinct direct bases of Class, diagnose it. (If it 10544 // only happens in one base, we'll diagnose it when synthesizing 10545 // that base class's move assignment operator.) 10546 CXXBaseSpecifier *&Existing = 10547 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10548 .first->second; 10549 if (Existing && Existing != &BI) { 10550 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10551 << Class << Base; 10552 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10553 << (Base->getCanonicalDecl() == 10554 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10555 << Base << Existing->getType() << Existing->getSourceRange(); 10556 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10557 << (Base->getCanonicalDecl() == 10558 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10559 << Base << BI.getType() << BaseSpec->getSourceRange(); 10560 10561 // Only diagnose each vbase once. 10562 Existing = nullptr; 10563 } 10564 } else { 10565 // Only walk over bases that have defaulted move assignment operators. 10566 // We assume that any user-provided move assignment operator handles 10567 // the multiple-moves-of-vbase case itself somehow. 10568 if (!SMOR->getMethod()->isDefaulted()) 10569 continue; 10570 10571 // We're going to move the base classes of Base. Add them to the list. 10572 for (auto &BI : Base->bases()) 10573 Worklist.push_back(&BI); 10574 } 10575 } 10576 } 10577 } 10578 10579 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10580 CXXMethodDecl *MoveAssignOperator) { 10581 assert((MoveAssignOperator->isDefaulted() && 10582 MoveAssignOperator->isOverloadedOperator() && 10583 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10584 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10585 !MoveAssignOperator->isDeleted()) && 10586 "DefineImplicitMoveAssignment called for wrong function"); 10587 10588 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10589 10590 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10591 MoveAssignOperator->setInvalidDecl(); 10592 return; 10593 } 10594 10595 MoveAssignOperator->markUsed(Context); 10596 10597 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10598 DiagnosticErrorTrap Trap(Diags); 10599 10600 // C++0x [class.copy]p28: 10601 // The implicitly-defined or move assignment operator for a non-union class 10602 // X performs memberwise move assignment of its subobjects. The direct base 10603 // classes of X are assigned first, in the order of their declaration in the 10604 // base-specifier-list, and then the immediate non-static data members of X 10605 // are assigned, in the order in which they were declared in the class 10606 // definition. 10607 10608 // Issue a warning if our implicit move assignment operator will move 10609 // from a virtual base more than once. 10610 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10611 10612 // The statements that form the synthesized function body. 10613 SmallVector<Stmt*, 8> Statements; 10614 10615 // The parameter for the "other" object, which we are move from. 10616 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10617 QualType OtherRefType = Other->getType()-> 10618 getAs<RValueReferenceType>()->getPointeeType(); 10619 assert(!OtherRefType.getQualifiers() && 10620 "Bad argument type of defaulted move assignment"); 10621 10622 // Our location for everything implicitly-generated. 10623 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10624 ? MoveAssignOperator->getLocEnd() 10625 : MoveAssignOperator->getLocation(); 10626 10627 // Builds a reference to the "other" object. 10628 RefBuilder OtherRef(Other, OtherRefType); 10629 // Cast to rvalue. 10630 MoveCastBuilder MoveOther(OtherRef); 10631 10632 // Builds the "this" pointer. 10633 ThisBuilder This; 10634 10635 // Assign base classes. 10636 bool Invalid = false; 10637 for (auto &Base : ClassDecl->bases()) { 10638 // C++11 [class.copy]p28: 10639 // It is unspecified whether subobjects representing virtual base classes 10640 // are assigned more than once by the implicitly-defined copy assignment 10641 // operator. 10642 // FIXME: Do not assign to a vbase that will be assigned by some other base 10643 // class. For a move-assignment, this can result in the vbase being moved 10644 // multiple times. 10645 10646 // Form the assignment: 10647 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10648 QualType BaseType = Base.getType().getUnqualifiedType(); 10649 if (!BaseType->isRecordType()) { 10650 Invalid = true; 10651 continue; 10652 } 10653 10654 CXXCastPath BasePath; 10655 BasePath.push_back(&Base); 10656 10657 // Construct the "from" expression, which is an implicit cast to the 10658 // appropriately-qualified base type. 10659 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10660 10661 // Dereference "this". 10662 DerefBuilder DerefThis(This); 10663 10664 // Implicitly cast "this" to the appropriately-qualified base type. 10665 CastBuilder To(DerefThis, 10666 Context.getCVRQualifiedType( 10667 BaseType, MoveAssignOperator->getTypeQualifiers()), 10668 VK_LValue, BasePath); 10669 10670 // Build the move. 10671 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10672 To, From, 10673 /*CopyingBaseSubobject=*/true, 10674 /*Copying=*/false); 10675 if (Move.isInvalid()) { 10676 Diag(CurrentLocation, diag::note_member_synthesized_at) 10677 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10678 MoveAssignOperator->setInvalidDecl(); 10679 return; 10680 } 10681 10682 // Success! Record the move. 10683 Statements.push_back(Move.getAs<Expr>()); 10684 } 10685 10686 // Assign non-static members. 10687 for (auto *Field : ClassDecl->fields()) { 10688 // FIXME: We should form some kind of AST representation for the implied 10689 // memcpy in a union copy operation. 10690 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10691 continue; 10692 10693 if (Field->isInvalidDecl()) { 10694 Invalid = true; 10695 continue; 10696 } 10697 10698 // Check for members of reference type; we can't move those. 10699 if (Field->getType()->isReferenceType()) { 10700 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10701 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10702 Diag(Field->getLocation(), diag::note_declared_at); 10703 Diag(CurrentLocation, diag::note_member_synthesized_at) 10704 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10705 Invalid = true; 10706 continue; 10707 } 10708 10709 // Check for members of const-qualified, non-class type. 10710 QualType BaseType = Context.getBaseElementType(Field->getType()); 10711 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10712 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10713 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10714 Diag(Field->getLocation(), diag::note_declared_at); 10715 Diag(CurrentLocation, diag::note_member_synthesized_at) 10716 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10717 Invalid = true; 10718 continue; 10719 } 10720 10721 // Suppress assigning zero-width bitfields. 10722 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10723 continue; 10724 10725 QualType FieldType = Field->getType().getNonReferenceType(); 10726 if (FieldType->isIncompleteArrayType()) { 10727 assert(ClassDecl->hasFlexibleArrayMember() && 10728 "Incomplete array type is not valid"); 10729 continue; 10730 } 10731 10732 // Build references to the field in the object we're copying from and to. 10733 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10734 LookupMemberName); 10735 MemberLookup.addDecl(Field); 10736 MemberLookup.resolveKind(); 10737 MemberBuilder From(MoveOther, OtherRefType, 10738 /*IsArrow=*/false, MemberLookup); 10739 MemberBuilder To(This, getCurrentThisType(), 10740 /*IsArrow=*/true, MemberLookup); 10741 10742 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10743 "Member reference with rvalue base must be rvalue except for reference " 10744 "members, which aren't allowed for move assignment."); 10745 10746 // Build the move of this field. 10747 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10748 To, From, 10749 /*CopyingBaseSubobject=*/false, 10750 /*Copying=*/false); 10751 if (Move.isInvalid()) { 10752 Diag(CurrentLocation, diag::note_member_synthesized_at) 10753 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10754 MoveAssignOperator->setInvalidDecl(); 10755 return; 10756 } 10757 10758 // Success! Record the copy. 10759 Statements.push_back(Move.getAs<Stmt>()); 10760 } 10761 10762 if (!Invalid) { 10763 // Add a "return *this;" 10764 ExprResult ThisObj = 10765 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10766 10767 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10768 if (Return.isInvalid()) 10769 Invalid = true; 10770 else { 10771 Statements.push_back(Return.getAs<Stmt>()); 10772 10773 if (Trap.hasErrorOccurred()) { 10774 Diag(CurrentLocation, diag::note_member_synthesized_at) 10775 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10776 Invalid = true; 10777 } 10778 } 10779 } 10780 10781 // The exception specification is needed because we are defining the 10782 // function. 10783 ResolveExceptionSpec(CurrentLocation, 10784 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10785 10786 if (Invalid) { 10787 MoveAssignOperator->setInvalidDecl(); 10788 return; 10789 } 10790 10791 StmtResult Body; 10792 { 10793 CompoundScopeRAII CompoundScope(*this); 10794 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10795 /*isStmtExpr=*/false); 10796 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10797 } 10798 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10799 10800 if (ASTMutationListener *L = getASTMutationListener()) { 10801 L->CompletedImplicitDefinition(MoveAssignOperator); 10802 } 10803 } 10804 10805 Sema::ImplicitExceptionSpecification 10806 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10807 CXXRecordDecl *ClassDecl = MD->getParent(); 10808 10809 ImplicitExceptionSpecification ExceptSpec(*this); 10810 if (ClassDecl->isInvalidDecl()) 10811 return ExceptSpec; 10812 10813 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10814 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10815 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10816 10817 // C++ [except.spec]p14: 10818 // An implicitly declared special member function (Clause 12) shall have an 10819 // exception-specification. [...] 10820 for (const auto &Base : ClassDecl->bases()) { 10821 // Virtual bases are handled below. 10822 if (Base.isVirtual()) 10823 continue; 10824 10825 CXXRecordDecl *BaseClassDecl 10826 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10827 if (CXXConstructorDecl *CopyConstructor = 10828 LookupCopyingConstructor(BaseClassDecl, Quals)) 10829 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10830 } 10831 for (const auto &Base : ClassDecl->vbases()) { 10832 CXXRecordDecl *BaseClassDecl 10833 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10834 if (CXXConstructorDecl *CopyConstructor = 10835 LookupCopyingConstructor(BaseClassDecl, Quals)) 10836 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10837 } 10838 for (const auto *Field : ClassDecl->fields()) { 10839 QualType FieldType = Context.getBaseElementType(Field->getType()); 10840 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10841 if (CXXConstructorDecl *CopyConstructor = 10842 LookupCopyingConstructor(FieldClassDecl, 10843 Quals | FieldType.getCVRQualifiers())) 10844 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10845 } 10846 } 10847 10848 return ExceptSpec; 10849 } 10850 10851 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10852 CXXRecordDecl *ClassDecl) { 10853 // C++ [class.copy]p4: 10854 // If the class definition does not explicitly declare a copy 10855 // constructor, one is declared implicitly. 10856 assert(ClassDecl->needsImplicitCopyConstructor()); 10857 10858 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10859 if (DSM.isAlreadyBeingDeclared()) 10860 return nullptr; 10861 10862 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10863 QualType ArgType = ClassType; 10864 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10865 if (Const) 10866 ArgType = ArgType.withConst(); 10867 ArgType = Context.getLValueReferenceType(ArgType); 10868 10869 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10870 CXXCopyConstructor, 10871 Const); 10872 10873 DeclarationName Name 10874 = Context.DeclarationNames.getCXXConstructorName( 10875 Context.getCanonicalType(ClassType)); 10876 SourceLocation ClassLoc = ClassDecl->getLocation(); 10877 DeclarationNameInfo NameInfo(Name, ClassLoc); 10878 10879 // An implicitly-declared copy constructor is an inline public 10880 // member of its class. 10881 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10882 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10883 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10884 Constexpr); 10885 CopyConstructor->setAccess(AS_public); 10886 CopyConstructor->setDefaulted(); 10887 10888 if (getLangOpts().CUDA) { 10889 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10890 CopyConstructor, 10891 /* ConstRHS */ Const, 10892 /* Diagnose */ false); 10893 } 10894 10895 // Build an exception specification pointing back at this member. 10896 FunctionProtoType::ExtProtoInfo EPI = 10897 getImplicitMethodEPI(*this, CopyConstructor); 10898 CopyConstructor->setType( 10899 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10900 10901 // Add the parameter to the constructor. 10902 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10903 ClassLoc, ClassLoc, 10904 /*IdentifierInfo=*/nullptr, 10905 ArgType, /*TInfo=*/nullptr, 10906 SC_None, nullptr); 10907 CopyConstructor->setParams(FromParam); 10908 10909 CopyConstructor->setTrivial( 10910 ClassDecl->needsOverloadResolutionForCopyConstructor() 10911 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10912 : ClassDecl->hasTrivialCopyConstructor()); 10913 10914 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10915 SetDeclDeleted(CopyConstructor, ClassLoc); 10916 10917 // Note that we have declared this constructor. 10918 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10919 10920 if (Scope *S = getScopeForContext(ClassDecl)) 10921 PushOnScopeChains(CopyConstructor, S, false); 10922 ClassDecl->addDecl(CopyConstructor); 10923 10924 return CopyConstructor; 10925 } 10926 10927 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10928 CXXConstructorDecl *CopyConstructor) { 10929 assert((CopyConstructor->isDefaulted() && 10930 CopyConstructor->isCopyConstructor() && 10931 !CopyConstructor->doesThisDeclarationHaveABody() && 10932 !CopyConstructor->isDeleted()) && 10933 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10934 10935 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10936 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10937 10938 // C++11 [class.copy]p7: 10939 // The [definition of an implicitly declared copy constructor] is 10940 // deprecated if the class has a user-declared copy assignment operator 10941 // or a user-declared destructor. 10942 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10943 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10944 10945 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10946 DiagnosticErrorTrap Trap(Diags); 10947 10948 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10949 Trap.hasErrorOccurred()) { 10950 Diag(CurrentLocation, diag::note_member_synthesized_at) 10951 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10952 CopyConstructor->setInvalidDecl(); 10953 } else { 10954 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10955 ? CopyConstructor->getLocEnd() 10956 : CopyConstructor->getLocation(); 10957 Sema::CompoundScopeRAII CompoundScope(*this); 10958 CopyConstructor->setBody( 10959 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10960 } 10961 10962 // The exception specification is needed because we are defining the 10963 // function. 10964 ResolveExceptionSpec(CurrentLocation, 10965 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10966 10967 CopyConstructor->markUsed(Context); 10968 MarkVTableUsed(CurrentLocation, ClassDecl); 10969 10970 if (ASTMutationListener *L = getASTMutationListener()) { 10971 L->CompletedImplicitDefinition(CopyConstructor); 10972 } 10973 } 10974 10975 Sema::ImplicitExceptionSpecification 10976 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10977 CXXRecordDecl *ClassDecl = MD->getParent(); 10978 10979 // C++ [except.spec]p14: 10980 // An implicitly declared special member function (Clause 12) shall have an 10981 // exception-specification. [...] 10982 ImplicitExceptionSpecification ExceptSpec(*this); 10983 if (ClassDecl->isInvalidDecl()) 10984 return ExceptSpec; 10985 10986 // Direct base-class constructors. 10987 for (const auto &B : ClassDecl->bases()) { 10988 if (B.isVirtual()) // Handled below. 10989 continue; 10990 10991 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10992 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10993 CXXConstructorDecl *Constructor = 10994 LookupMovingConstructor(BaseClassDecl, 0); 10995 // If this is a deleted function, add it anyway. This might be conformant 10996 // with the standard. This might not. I'm not sure. It might not matter. 10997 if (Constructor) 10998 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10999 } 11000 } 11001 11002 // Virtual base-class constructors. 11003 for (const auto &B : ClassDecl->vbases()) { 11004 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11005 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11006 CXXConstructorDecl *Constructor = 11007 LookupMovingConstructor(BaseClassDecl, 0); 11008 // If this is a deleted function, add it anyway. This might be conformant 11009 // with the standard. This might not. I'm not sure. It might not matter. 11010 if (Constructor) 11011 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11012 } 11013 } 11014 11015 // Field constructors. 11016 for (const auto *F : ClassDecl->fields()) { 11017 QualType FieldType = Context.getBaseElementType(F->getType()); 11018 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 11019 CXXConstructorDecl *Constructor = 11020 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 11021 // If this is a deleted function, add it anyway. This might be conformant 11022 // with the standard. This might not. I'm not sure. It might not matter. 11023 // In particular, the problem is that this function never gets called. It 11024 // might just be ill-formed because this function attempts to refer to 11025 // a deleted function here. 11026 if (Constructor) 11027 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 11028 } 11029 } 11030 11031 return ExceptSpec; 11032 } 11033 11034 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 11035 CXXRecordDecl *ClassDecl) { 11036 assert(ClassDecl->needsImplicitMoveConstructor()); 11037 11038 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 11039 if (DSM.isAlreadyBeingDeclared()) 11040 return nullptr; 11041 11042 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11043 QualType ArgType = Context.getRValueReferenceType(ClassType); 11044 11045 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11046 CXXMoveConstructor, 11047 false); 11048 11049 DeclarationName Name 11050 = Context.DeclarationNames.getCXXConstructorName( 11051 Context.getCanonicalType(ClassType)); 11052 SourceLocation ClassLoc = ClassDecl->getLocation(); 11053 DeclarationNameInfo NameInfo(Name, ClassLoc); 11054 11055 // C++11 [class.copy]p11: 11056 // An implicitly-declared copy/move constructor is an inline public 11057 // member of its class. 11058 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 11059 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11060 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11061 Constexpr); 11062 MoveConstructor->setAccess(AS_public); 11063 MoveConstructor->setDefaulted(); 11064 11065 if (getLangOpts().CUDA) { 11066 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 11067 MoveConstructor, 11068 /* ConstRHS */ false, 11069 /* Diagnose */ false); 11070 } 11071 11072 // Build an exception specification pointing back at this member. 11073 FunctionProtoType::ExtProtoInfo EPI = 11074 getImplicitMethodEPI(*this, MoveConstructor); 11075 MoveConstructor->setType( 11076 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11077 11078 // Add the parameter to the constructor. 11079 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 11080 ClassLoc, ClassLoc, 11081 /*IdentifierInfo=*/nullptr, 11082 ArgType, /*TInfo=*/nullptr, 11083 SC_None, nullptr); 11084 MoveConstructor->setParams(FromParam); 11085 11086 MoveConstructor->setTrivial( 11087 ClassDecl->needsOverloadResolutionForMoveConstructor() 11088 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 11089 : ClassDecl->hasTrivialMoveConstructor()); 11090 11091 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 11092 ClassDecl->setImplicitMoveConstructorIsDeleted(); 11093 SetDeclDeleted(MoveConstructor, ClassLoc); 11094 } 11095 11096 // Note that we have declared this constructor. 11097 ++ASTContext::NumImplicitMoveConstructorsDeclared; 11098 11099 if (Scope *S = getScopeForContext(ClassDecl)) 11100 PushOnScopeChains(MoveConstructor, S, false); 11101 ClassDecl->addDecl(MoveConstructor); 11102 11103 return MoveConstructor; 11104 } 11105 11106 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 11107 CXXConstructorDecl *MoveConstructor) { 11108 assert((MoveConstructor->isDefaulted() && 11109 MoveConstructor->isMoveConstructor() && 11110 !MoveConstructor->doesThisDeclarationHaveABody() && 11111 !MoveConstructor->isDeleted()) && 11112 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 11113 11114 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 11115 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 11116 11117 SynthesizedFunctionScope Scope(*this, MoveConstructor); 11118 DiagnosticErrorTrap Trap(Diags); 11119 11120 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 11121 Trap.hasErrorOccurred()) { 11122 Diag(CurrentLocation, diag::note_member_synthesized_at) 11123 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 11124 MoveConstructor->setInvalidDecl(); 11125 } else { 11126 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 11127 ? MoveConstructor->getLocEnd() 11128 : MoveConstructor->getLocation(); 11129 Sema::CompoundScopeRAII CompoundScope(*this); 11130 MoveConstructor->setBody(ActOnCompoundStmt( 11131 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 11132 } 11133 11134 // The exception specification is needed because we are defining the 11135 // function. 11136 ResolveExceptionSpec(CurrentLocation, 11137 MoveConstructor->getType()->castAs<FunctionProtoType>()); 11138 11139 MoveConstructor->markUsed(Context); 11140 MarkVTableUsed(CurrentLocation, ClassDecl); 11141 11142 if (ASTMutationListener *L = getASTMutationListener()) { 11143 L->CompletedImplicitDefinition(MoveConstructor); 11144 } 11145 } 11146 11147 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 11148 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 11149 } 11150 11151 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 11152 SourceLocation CurrentLocation, 11153 CXXConversionDecl *Conv) { 11154 CXXRecordDecl *Lambda = Conv->getParent(); 11155 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 11156 // If we are defining a specialization of a conversion to function-ptr 11157 // cache the deduced template arguments for this specialization 11158 // so that we can use them to retrieve the corresponding call-operator 11159 // and static-invoker. 11160 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 11161 11162 // Retrieve the corresponding call-operator specialization. 11163 if (Lambda->isGenericLambda()) { 11164 assert(Conv->isFunctionTemplateSpecialization()); 11165 FunctionTemplateDecl *CallOpTemplate = 11166 CallOp->getDescribedFunctionTemplate(); 11167 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 11168 void *InsertPos = nullptr; 11169 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 11170 DeducedTemplateArgs->asArray(), 11171 InsertPos); 11172 assert(CallOpSpec && 11173 "Conversion operator must have a corresponding call operator"); 11174 CallOp = cast<CXXMethodDecl>(CallOpSpec); 11175 } 11176 // Mark the call operator referenced (and add to pending instantiations 11177 // if necessary). 11178 // For both the conversion and static-invoker template specializations 11179 // we construct their body's in this function, so no need to add them 11180 // to the PendingInstantiations. 11181 MarkFunctionReferenced(CurrentLocation, CallOp); 11182 11183 SynthesizedFunctionScope Scope(*this, Conv); 11184 DiagnosticErrorTrap Trap(Diags); 11185 11186 // Retrieve the static invoker... 11187 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 11188 // ... and get the corresponding specialization for a generic lambda. 11189 if (Lambda->isGenericLambda()) { 11190 assert(DeducedTemplateArgs && 11191 "Must have deduced template arguments from Conversion Operator"); 11192 FunctionTemplateDecl *InvokeTemplate = 11193 Invoker->getDescribedFunctionTemplate(); 11194 void *InsertPos = nullptr; 11195 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 11196 DeducedTemplateArgs->asArray(), 11197 InsertPos); 11198 assert(InvokeSpec && 11199 "Must have a corresponding static invoker specialization"); 11200 Invoker = cast<CXXMethodDecl>(InvokeSpec); 11201 } 11202 // Construct the body of the conversion function { return __invoke; }. 11203 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 11204 VK_LValue, Conv->getLocation()).get(); 11205 assert(FunctionRef && "Can't refer to __invoke function?"); 11206 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 11207 Conv->setBody(new (Context) CompoundStmt(Context, Return, 11208 Conv->getLocation(), 11209 Conv->getLocation())); 11210 11211 Conv->markUsed(Context); 11212 Conv->setReferenced(); 11213 11214 // Fill in the __invoke function with a dummy implementation. IR generation 11215 // will fill in the actual details. 11216 Invoker->markUsed(Context); 11217 Invoker->setReferenced(); 11218 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 11219 11220 if (ASTMutationListener *L = getASTMutationListener()) { 11221 L->CompletedImplicitDefinition(Conv); 11222 L->CompletedImplicitDefinition(Invoker); 11223 } 11224 } 11225 11226 11227 11228 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11229 SourceLocation CurrentLocation, 11230 CXXConversionDecl *Conv) 11231 { 11232 assert(!Conv->getParent()->isGenericLambda()); 11233 11234 Conv->markUsed(Context); 11235 11236 SynthesizedFunctionScope Scope(*this, Conv); 11237 DiagnosticErrorTrap Trap(Diags); 11238 11239 // Copy-initialize the lambda object as needed to capture it. 11240 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11241 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11242 11243 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11244 Conv->getLocation(), 11245 Conv, DerefThis); 11246 11247 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11248 // behavior. Note that only the general conversion function does this 11249 // (since it's unusable otherwise); in the case where we inline the 11250 // block literal, it has block literal lifetime semantics. 11251 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11252 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11253 CK_CopyAndAutoreleaseBlockObject, 11254 BuildBlock.get(), nullptr, VK_RValue); 11255 11256 if (BuildBlock.isInvalid()) { 11257 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11258 Conv->setInvalidDecl(); 11259 return; 11260 } 11261 11262 // Create the return statement that returns the block from the conversion 11263 // function. 11264 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11265 if (Return.isInvalid()) { 11266 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11267 Conv->setInvalidDecl(); 11268 return; 11269 } 11270 11271 // Set the body of the conversion function. 11272 Stmt *ReturnS = Return.get(); 11273 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11274 Conv->getLocation(), 11275 Conv->getLocation())); 11276 11277 // We're done; notify the mutation listener, if any. 11278 if (ASTMutationListener *L = getASTMutationListener()) { 11279 L->CompletedImplicitDefinition(Conv); 11280 } 11281 } 11282 11283 /// \brief Determine whether the given list arguments contains exactly one 11284 /// "real" (non-default) argument. 11285 static bool hasOneRealArgument(MultiExprArg Args) { 11286 switch (Args.size()) { 11287 case 0: 11288 return false; 11289 11290 default: 11291 if (!Args[1]->isDefaultArgument()) 11292 return false; 11293 11294 // fall through 11295 case 1: 11296 return !Args[0]->isDefaultArgument(); 11297 } 11298 11299 return false; 11300 } 11301 11302 ExprResult 11303 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11304 CXXConstructorDecl *Constructor, 11305 MultiExprArg ExprArgs, 11306 bool HadMultipleCandidates, 11307 bool IsListInitialization, 11308 bool IsStdInitListInitialization, 11309 bool RequiresZeroInit, 11310 unsigned ConstructKind, 11311 SourceRange ParenRange) { 11312 bool Elidable = false; 11313 11314 // C++0x [class.copy]p34: 11315 // When certain criteria are met, an implementation is allowed to 11316 // omit the copy/move construction of a class object, even if the 11317 // copy/move constructor and/or destructor for the object have 11318 // side effects. [...] 11319 // - when a temporary class object that has not been bound to a 11320 // reference (12.2) would be copied/moved to a class object 11321 // with the same cv-unqualified type, the copy/move operation 11322 // can be omitted by constructing the temporary object 11323 // directly into the target of the omitted copy/move 11324 if (ConstructKind == CXXConstructExpr::CK_Complete && 11325 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11326 Expr *SubExpr = ExprArgs[0]; 11327 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11328 } 11329 11330 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11331 Elidable, ExprArgs, HadMultipleCandidates, 11332 IsListInitialization, 11333 IsStdInitListInitialization, RequiresZeroInit, 11334 ConstructKind, ParenRange); 11335 } 11336 11337 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11338 /// including handling of its default argument expressions. 11339 ExprResult 11340 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11341 CXXConstructorDecl *Constructor, bool Elidable, 11342 MultiExprArg ExprArgs, 11343 bool HadMultipleCandidates, 11344 bool IsListInitialization, 11345 bool IsStdInitListInitialization, 11346 bool RequiresZeroInit, 11347 unsigned ConstructKind, 11348 SourceRange ParenRange) { 11349 MarkFunctionReferenced(ConstructLoc, Constructor); 11350 return CXXConstructExpr::Create( 11351 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11352 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11353 RequiresZeroInit, 11354 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11355 ParenRange); 11356 } 11357 11358 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11359 assert(Field->hasInClassInitializer()); 11360 11361 // If we already have the in-class initializer nothing needs to be done. 11362 if (Field->getInClassInitializer()) 11363 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11364 11365 // Maybe we haven't instantiated the in-class initializer. Go check the 11366 // pattern FieldDecl to see if it has one. 11367 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11368 11369 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11370 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11371 DeclContext::lookup_result Lookup = 11372 ClassPattern->lookup(Field->getDeclName()); 11373 assert(Lookup.size() == 1); 11374 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11375 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11376 getTemplateInstantiationArgs(Field))) 11377 return ExprError(); 11378 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11379 } 11380 11381 // DR1351: 11382 // If the brace-or-equal-initializer of a non-static data member 11383 // invokes a defaulted default constructor of its class or of an 11384 // enclosing class in a potentially evaluated subexpression, the 11385 // program is ill-formed. 11386 // 11387 // This resolution is unworkable: the exception specification of the 11388 // default constructor can be needed in an unevaluated context, in 11389 // particular, in the operand of a noexcept-expression, and we can be 11390 // unable to compute an exception specification for an enclosed class. 11391 // 11392 // Any attempt to resolve the exception specification of a defaulted default 11393 // constructor before the initializer is lexically complete will ultimately 11394 // come here at which point we can diagnose it. 11395 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11396 if (OutermostClass == ParentRD) { 11397 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11398 << ParentRD << Field; 11399 } else { 11400 Diag(Field->getLocEnd(), 11401 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11402 << ParentRD << OutermostClass << Field; 11403 } 11404 11405 return ExprError(); 11406 } 11407 11408 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11409 if (VD->isInvalidDecl()) return; 11410 11411 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11412 if (ClassDecl->isInvalidDecl()) return; 11413 if (ClassDecl->hasIrrelevantDestructor()) return; 11414 if (ClassDecl->isDependentContext()) return; 11415 11416 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11417 MarkFunctionReferenced(VD->getLocation(), Destructor); 11418 CheckDestructorAccess(VD->getLocation(), Destructor, 11419 PDiag(diag::err_access_dtor_var) 11420 << VD->getDeclName() 11421 << VD->getType()); 11422 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11423 11424 if (Destructor->isTrivial()) return; 11425 if (!VD->hasGlobalStorage()) return; 11426 11427 // Emit warning for non-trivial dtor in global scope (a real global, 11428 // class-static, function-static). 11429 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11430 11431 // TODO: this should be re-enabled for static locals by !CXAAtExit 11432 if (!VD->isStaticLocal()) 11433 Diag(VD->getLocation(), diag::warn_global_destructor); 11434 } 11435 11436 /// \brief Given a constructor and the set of arguments provided for the 11437 /// constructor, convert the arguments and add any required default arguments 11438 /// to form a proper call to this constructor. 11439 /// 11440 /// \returns true if an error occurred, false otherwise. 11441 bool 11442 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11443 MultiExprArg ArgsPtr, 11444 SourceLocation Loc, 11445 SmallVectorImpl<Expr*> &ConvertedArgs, 11446 bool AllowExplicit, 11447 bool IsListInitialization) { 11448 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11449 unsigned NumArgs = ArgsPtr.size(); 11450 Expr **Args = ArgsPtr.data(); 11451 11452 const FunctionProtoType *Proto 11453 = Constructor->getType()->getAs<FunctionProtoType>(); 11454 assert(Proto && "Constructor without a prototype?"); 11455 unsigned NumParams = Proto->getNumParams(); 11456 11457 // If too few arguments are available, we'll fill in the rest with defaults. 11458 if (NumArgs < NumParams) 11459 ConvertedArgs.reserve(NumParams); 11460 else 11461 ConvertedArgs.reserve(NumArgs); 11462 11463 VariadicCallType CallType = 11464 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11465 SmallVector<Expr *, 8> AllArgs; 11466 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11467 Proto, 0, 11468 llvm::makeArrayRef(Args, NumArgs), 11469 AllArgs, 11470 CallType, AllowExplicit, 11471 IsListInitialization); 11472 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11473 11474 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11475 11476 CheckConstructorCall(Constructor, 11477 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11478 Proto, Loc); 11479 11480 return Invalid; 11481 } 11482 11483 static inline bool 11484 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11485 const FunctionDecl *FnDecl) { 11486 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11487 if (isa<NamespaceDecl>(DC)) { 11488 return SemaRef.Diag(FnDecl->getLocation(), 11489 diag::err_operator_new_delete_declared_in_namespace) 11490 << FnDecl->getDeclName(); 11491 } 11492 11493 if (isa<TranslationUnitDecl>(DC) && 11494 FnDecl->getStorageClass() == SC_Static) { 11495 return SemaRef.Diag(FnDecl->getLocation(), 11496 diag::err_operator_new_delete_declared_static) 11497 << FnDecl->getDeclName(); 11498 } 11499 11500 return false; 11501 } 11502 11503 static inline bool 11504 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11505 CanQualType ExpectedResultType, 11506 CanQualType ExpectedFirstParamType, 11507 unsigned DependentParamTypeDiag, 11508 unsigned InvalidParamTypeDiag) { 11509 QualType ResultType = 11510 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11511 11512 // Check that the result type is not dependent. 11513 if (ResultType->isDependentType()) 11514 return SemaRef.Diag(FnDecl->getLocation(), 11515 diag::err_operator_new_delete_dependent_result_type) 11516 << FnDecl->getDeclName() << ExpectedResultType; 11517 11518 // Check that the result type is what we expect. 11519 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11520 return SemaRef.Diag(FnDecl->getLocation(), 11521 diag::err_operator_new_delete_invalid_result_type) 11522 << FnDecl->getDeclName() << ExpectedResultType; 11523 11524 // A function template must have at least 2 parameters. 11525 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11526 return SemaRef.Diag(FnDecl->getLocation(), 11527 diag::err_operator_new_delete_template_too_few_parameters) 11528 << FnDecl->getDeclName(); 11529 11530 // The function decl must have at least 1 parameter. 11531 if (FnDecl->getNumParams() == 0) 11532 return SemaRef.Diag(FnDecl->getLocation(), 11533 diag::err_operator_new_delete_too_few_parameters) 11534 << FnDecl->getDeclName(); 11535 11536 // Check the first parameter type is not dependent. 11537 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11538 if (FirstParamType->isDependentType()) 11539 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11540 << FnDecl->getDeclName() << ExpectedFirstParamType; 11541 11542 // Check that the first parameter type is what we expect. 11543 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11544 ExpectedFirstParamType) 11545 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11546 << FnDecl->getDeclName() << ExpectedFirstParamType; 11547 11548 return false; 11549 } 11550 11551 static bool 11552 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11553 // C++ [basic.stc.dynamic.allocation]p1: 11554 // A program is ill-formed if an allocation function is declared in a 11555 // namespace scope other than global scope or declared static in global 11556 // scope. 11557 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11558 return true; 11559 11560 CanQualType SizeTy = 11561 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11562 11563 // C++ [basic.stc.dynamic.allocation]p1: 11564 // The return type shall be void*. The first parameter shall have type 11565 // std::size_t. 11566 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11567 SizeTy, 11568 diag::err_operator_new_dependent_param_type, 11569 diag::err_operator_new_param_type)) 11570 return true; 11571 11572 // C++ [basic.stc.dynamic.allocation]p1: 11573 // The first parameter shall not have an associated default argument. 11574 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11575 return SemaRef.Diag(FnDecl->getLocation(), 11576 diag::err_operator_new_default_arg) 11577 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11578 11579 return false; 11580 } 11581 11582 static bool 11583 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11584 // C++ [basic.stc.dynamic.deallocation]p1: 11585 // A program is ill-formed if deallocation functions are declared in a 11586 // namespace scope other than global scope or declared static in global 11587 // scope. 11588 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11589 return true; 11590 11591 // C++ [basic.stc.dynamic.deallocation]p2: 11592 // Each deallocation function shall return void and its first parameter 11593 // shall be void*. 11594 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11595 SemaRef.Context.VoidPtrTy, 11596 diag::err_operator_delete_dependent_param_type, 11597 diag::err_operator_delete_param_type)) 11598 return true; 11599 11600 return false; 11601 } 11602 11603 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11604 /// of this overloaded operator is well-formed. If so, returns false; 11605 /// otherwise, emits appropriate diagnostics and returns true. 11606 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11607 assert(FnDecl && FnDecl->isOverloadedOperator() && 11608 "Expected an overloaded operator declaration"); 11609 11610 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11611 11612 // C++ [over.oper]p5: 11613 // The allocation and deallocation functions, operator new, 11614 // operator new[], operator delete and operator delete[], are 11615 // described completely in 3.7.3. The attributes and restrictions 11616 // found in the rest of this subclause do not apply to them unless 11617 // explicitly stated in 3.7.3. 11618 if (Op == OO_Delete || Op == OO_Array_Delete) 11619 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11620 11621 if (Op == OO_New || Op == OO_Array_New) 11622 return CheckOperatorNewDeclaration(*this, FnDecl); 11623 11624 // C++ [over.oper]p6: 11625 // An operator function shall either be a non-static member 11626 // function or be a non-member function and have at least one 11627 // parameter whose type is a class, a reference to a class, an 11628 // enumeration, or a reference to an enumeration. 11629 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11630 if (MethodDecl->isStatic()) 11631 return Diag(FnDecl->getLocation(), 11632 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11633 } else { 11634 bool ClassOrEnumParam = false; 11635 for (auto Param : FnDecl->params()) { 11636 QualType ParamType = Param->getType().getNonReferenceType(); 11637 if (ParamType->isDependentType() || ParamType->isRecordType() || 11638 ParamType->isEnumeralType()) { 11639 ClassOrEnumParam = true; 11640 break; 11641 } 11642 } 11643 11644 if (!ClassOrEnumParam) 11645 return Diag(FnDecl->getLocation(), 11646 diag::err_operator_overload_needs_class_or_enum) 11647 << FnDecl->getDeclName(); 11648 } 11649 11650 // C++ [over.oper]p8: 11651 // An operator function cannot have default arguments (8.3.6), 11652 // except where explicitly stated below. 11653 // 11654 // Only the function-call operator allows default arguments 11655 // (C++ [over.call]p1). 11656 if (Op != OO_Call) { 11657 for (auto Param : FnDecl->params()) { 11658 if (Param->hasDefaultArg()) 11659 return Diag(Param->getLocation(), 11660 diag::err_operator_overload_default_arg) 11661 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11662 } 11663 } 11664 11665 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11666 { false, false, false } 11667 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11668 , { Unary, Binary, MemberOnly } 11669 #include "clang/Basic/OperatorKinds.def" 11670 }; 11671 11672 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11673 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11674 bool MustBeMemberOperator = OperatorUses[Op][2]; 11675 11676 // C++ [over.oper]p8: 11677 // [...] Operator functions cannot have more or fewer parameters 11678 // than the number required for the corresponding operator, as 11679 // described in the rest of this subclause. 11680 unsigned NumParams = FnDecl->getNumParams() 11681 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11682 if (Op != OO_Call && 11683 ((NumParams == 1 && !CanBeUnaryOperator) || 11684 (NumParams == 2 && !CanBeBinaryOperator) || 11685 (NumParams < 1) || (NumParams > 2))) { 11686 // We have the wrong number of parameters. 11687 unsigned ErrorKind; 11688 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11689 ErrorKind = 2; // 2 -> unary or binary. 11690 } else if (CanBeUnaryOperator) { 11691 ErrorKind = 0; // 0 -> unary 11692 } else { 11693 assert(CanBeBinaryOperator && 11694 "All non-call overloaded operators are unary or binary!"); 11695 ErrorKind = 1; // 1 -> binary 11696 } 11697 11698 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11699 << FnDecl->getDeclName() << NumParams << ErrorKind; 11700 } 11701 11702 // Overloaded operators other than operator() cannot be variadic. 11703 if (Op != OO_Call && 11704 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11705 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11706 << FnDecl->getDeclName(); 11707 } 11708 11709 // Some operators must be non-static member functions. 11710 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11711 return Diag(FnDecl->getLocation(), 11712 diag::err_operator_overload_must_be_member) 11713 << FnDecl->getDeclName(); 11714 } 11715 11716 // C++ [over.inc]p1: 11717 // The user-defined function called operator++ implements the 11718 // prefix and postfix ++ operator. If this function is a member 11719 // function with no parameters, or a non-member function with one 11720 // parameter of class or enumeration type, it defines the prefix 11721 // increment operator ++ for objects of that type. If the function 11722 // is a member function with one parameter (which shall be of type 11723 // int) or a non-member function with two parameters (the second 11724 // of which shall be of type int), it defines the postfix 11725 // increment operator ++ for objects of that type. 11726 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11727 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11728 QualType ParamType = LastParam->getType(); 11729 11730 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11731 !ParamType->isDependentType()) 11732 return Diag(LastParam->getLocation(), 11733 diag::err_operator_overload_post_incdec_must_be_int) 11734 << LastParam->getType() << (Op == OO_MinusMinus); 11735 } 11736 11737 return false; 11738 } 11739 11740 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11741 /// of this literal operator function is well-formed. If so, returns 11742 /// false; otherwise, emits appropriate diagnostics and returns true. 11743 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11744 if (isa<CXXMethodDecl>(FnDecl)) { 11745 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11746 << FnDecl->getDeclName(); 11747 return true; 11748 } 11749 11750 if (FnDecl->isExternC()) { 11751 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11752 return true; 11753 } 11754 11755 bool Valid = false; 11756 11757 // This might be the definition of a literal operator template. 11758 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11759 // This might be a specialization of a literal operator template. 11760 if (!TpDecl) 11761 TpDecl = FnDecl->getPrimaryTemplate(); 11762 11763 // template <char...> type operator "" name() and 11764 // template <class T, T...> type operator "" name() are the only valid 11765 // template signatures, and the only valid signatures with no parameters. 11766 if (TpDecl) { 11767 if (FnDecl->param_size() == 0) { 11768 // Must have one or two template parameters 11769 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11770 if (Params->size() == 1) { 11771 NonTypeTemplateParmDecl *PmDecl = 11772 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11773 11774 // The template parameter must be a char parameter pack. 11775 if (PmDecl && PmDecl->isTemplateParameterPack() && 11776 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11777 Valid = true; 11778 } else if (Params->size() == 2) { 11779 TemplateTypeParmDecl *PmType = 11780 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11781 NonTypeTemplateParmDecl *PmArgs = 11782 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11783 11784 // The second template parameter must be a parameter pack with the 11785 // first template parameter as its type. 11786 if (PmType && PmArgs && 11787 !PmType->isTemplateParameterPack() && 11788 PmArgs->isTemplateParameterPack()) { 11789 const TemplateTypeParmType *TArgs = 11790 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11791 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11792 TArgs->getIndex() == PmType->getIndex()) { 11793 Valid = true; 11794 if (ActiveTemplateInstantiations.empty()) 11795 Diag(FnDecl->getLocation(), 11796 diag::ext_string_literal_operator_template); 11797 } 11798 } 11799 } 11800 } 11801 } else if (FnDecl->param_size()) { 11802 // Check the first parameter 11803 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11804 11805 QualType T = (*Param)->getType().getUnqualifiedType(); 11806 11807 // unsigned long long int, long double, and any character type are allowed 11808 // as the only parameters. 11809 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11810 Context.hasSameType(T, Context.LongDoubleTy) || 11811 Context.hasSameType(T, Context.CharTy) || 11812 Context.hasSameType(T, Context.WideCharTy) || 11813 Context.hasSameType(T, Context.Char16Ty) || 11814 Context.hasSameType(T, Context.Char32Ty)) { 11815 if (++Param == FnDecl->param_end()) 11816 Valid = true; 11817 goto FinishedParams; 11818 } 11819 11820 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11821 const PointerType *PT = T->getAs<PointerType>(); 11822 if (!PT) 11823 goto FinishedParams; 11824 T = PT->getPointeeType(); 11825 if (!T.isConstQualified() || T.isVolatileQualified()) 11826 goto FinishedParams; 11827 T = T.getUnqualifiedType(); 11828 11829 // Move on to the second parameter; 11830 ++Param; 11831 11832 // If there is no second parameter, the first must be a const char * 11833 if (Param == FnDecl->param_end()) { 11834 if (Context.hasSameType(T, Context.CharTy)) 11835 Valid = true; 11836 goto FinishedParams; 11837 } 11838 11839 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11840 // are allowed as the first parameter to a two-parameter function 11841 if (!(Context.hasSameType(T, Context.CharTy) || 11842 Context.hasSameType(T, Context.WideCharTy) || 11843 Context.hasSameType(T, Context.Char16Ty) || 11844 Context.hasSameType(T, Context.Char32Ty))) 11845 goto FinishedParams; 11846 11847 // The second and final parameter must be an std::size_t 11848 T = (*Param)->getType().getUnqualifiedType(); 11849 if (Context.hasSameType(T, Context.getSizeType()) && 11850 ++Param == FnDecl->param_end()) 11851 Valid = true; 11852 } 11853 11854 // FIXME: This diagnostic is absolutely terrible. 11855 FinishedParams: 11856 if (!Valid) { 11857 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11858 << FnDecl->getDeclName(); 11859 return true; 11860 } 11861 11862 // A parameter-declaration-clause containing a default argument is not 11863 // equivalent to any of the permitted forms. 11864 for (auto Param : FnDecl->params()) { 11865 if (Param->hasDefaultArg()) { 11866 Diag(Param->getDefaultArgRange().getBegin(), 11867 diag::err_literal_operator_default_argument) 11868 << Param->getDefaultArgRange(); 11869 break; 11870 } 11871 } 11872 11873 StringRef LiteralName 11874 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11875 if (LiteralName[0] != '_') { 11876 // C++11 [usrlit.suffix]p1: 11877 // Literal suffix identifiers that do not start with an underscore 11878 // are reserved for future standardization. 11879 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11880 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11881 } 11882 11883 return false; 11884 } 11885 11886 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11887 /// linkage specification, including the language and (if present) 11888 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11889 /// language string literal. LBraceLoc, if valid, provides the location of 11890 /// the '{' brace. Otherwise, this linkage specification does not 11891 /// have any braces. 11892 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11893 Expr *LangStr, 11894 SourceLocation LBraceLoc) { 11895 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11896 if (!Lit->isAscii()) { 11897 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11898 << LangStr->getSourceRange(); 11899 return nullptr; 11900 } 11901 11902 StringRef Lang = Lit->getString(); 11903 LinkageSpecDecl::LanguageIDs Language; 11904 if (Lang == "C") 11905 Language = LinkageSpecDecl::lang_c; 11906 else if (Lang == "C++") 11907 Language = LinkageSpecDecl::lang_cxx; 11908 else { 11909 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11910 << LangStr->getSourceRange(); 11911 return nullptr; 11912 } 11913 11914 // FIXME: Add all the various semantics of linkage specifications 11915 11916 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11917 LangStr->getExprLoc(), Language, 11918 LBraceLoc.isValid()); 11919 CurContext->addDecl(D); 11920 PushDeclContext(S, D); 11921 return D; 11922 } 11923 11924 /// ActOnFinishLinkageSpecification - Complete the definition of 11925 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11926 /// valid, it's the position of the closing '}' brace in a linkage 11927 /// specification that uses braces. 11928 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11929 Decl *LinkageSpec, 11930 SourceLocation RBraceLoc) { 11931 if (RBraceLoc.isValid()) { 11932 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11933 LSDecl->setRBraceLoc(RBraceLoc); 11934 } 11935 PopDeclContext(); 11936 return LinkageSpec; 11937 } 11938 11939 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11940 AttributeList *AttrList, 11941 SourceLocation SemiLoc) { 11942 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11943 // Attribute declarations appertain to empty declaration so we handle 11944 // them here. 11945 if (AttrList) 11946 ProcessDeclAttributeList(S, ED, AttrList); 11947 11948 CurContext->addDecl(ED); 11949 return ED; 11950 } 11951 11952 /// \brief Perform semantic analysis for the variable declaration that 11953 /// occurs within a C++ catch clause, returning the newly-created 11954 /// variable. 11955 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11956 TypeSourceInfo *TInfo, 11957 SourceLocation StartLoc, 11958 SourceLocation Loc, 11959 IdentifierInfo *Name) { 11960 bool Invalid = false; 11961 QualType ExDeclType = TInfo->getType(); 11962 11963 // Arrays and functions decay. 11964 if (ExDeclType->isArrayType()) 11965 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11966 else if (ExDeclType->isFunctionType()) 11967 ExDeclType = Context.getPointerType(ExDeclType); 11968 11969 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11970 // The exception-declaration shall not denote a pointer or reference to an 11971 // incomplete type, other than [cv] void*. 11972 // N2844 forbids rvalue references. 11973 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11974 Diag(Loc, diag::err_catch_rvalue_ref); 11975 Invalid = true; 11976 } 11977 11978 QualType BaseType = ExDeclType; 11979 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11980 unsigned DK = diag::err_catch_incomplete; 11981 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11982 BaseType = Ptr->getPointeeType(); 11983 Mode = 1; 11984 DK = diag::err_catch_incomplete_ptr; 11985 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11986 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11987 BaseType = Ref->getPointeeType(); 11988 Mode = 2; 11989 DK = diag::err_catch_incomplete_ref; 11990 } 11991 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11992 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11993 Invalid = true; 11994 11995 if (!Invalid && !ExDeclType->isDependentType() && 11996 RequireNonAbstractType(Loc, ExDeclType, 11997 diag::err_abstract_type_in_decl, 11998 AbstractVariableType)) 11999 Invalid = true; 12000 12001 // Only the non-fragile NeXT runtime currently supports C++ catches 12002 // of ObjC types, and no runtime supports catching ObjC types by value. 12003 if (!Invalid && getLangOpts().ObjC1) { 12004 QualType T = ExDeclType; 12005 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 12006 T = RT->getPointeeType(); 12007 12008 if (T->isObjCObjectType()) { 12009 Diag(Loc, diag::err_objc_object_catch); 12010 Invalid = true; 12011 } else if (T->isObjCObjectPointerType()) { 12012 // FIXME: should this be a test for macosx-fragile specifically? 12013 if (getLangOpts().ObjCRuntime.isFragile()) 12014 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 12015 } 12016 } 12017 12018 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 12019 ExDeclType, TInfo, SC_None); 12020 ExDecl->setExceptionVariable(true); 12021 12022 // In ARC, infer 'retaining' for variables of retainable type. 12023 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 12024 Invalid = true; 12025 12026 if (!Invalid && !ExDeclType->isDependentType()) { 12027 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 12028 // Insulate this from anything else we might currently be parsing. 12029 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 12030 12031 // C++ [except.handle]p16: 12032 // The object declared in an exception-declaration or, if the 12033 // exception-declaration does not specify a name, a temporary (12.2) is 12034 // copy-initialized (8.5) from the exception object. [...] 12035 // The object is destroyed when the handler exits, after the destruction 12036 // of any automatic objects initialized within the handler. 12037 // 12038 // We just pretend to initialize the object with itself, then make sure 12039 // it can be destroyed later. 12040 QualType initType = Context.getExceptionObjectType(ExDeclType); 12041 12042 InitializedEntity entity = 12043 InitializedEntity::InitializeVariable(ExDecl); 12044 InitializationKind initKind = 12045 InitializationKind::CreateCopy(Loc, SourceLocation()); 12046 12047 Expr *opaqueValue = 12048 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 12049 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 12050 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 12051 if (result.isInvalid()) 12052 Invalid = true; 12053 else { 12054 // If the constructor used was non-trivial, set this as the 12055 // "initializer". 12056 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 12057 if (!construct->getConstructor()->isTrivial()) { 12058 Expr *init = MaybeCreateExprWithCleanups(construct); 12059 ExDecl->setInit(init); 12060 } 12061 12062 // And make sure it's destructable. 12063 FinalizeVarWithDestructor(ExDecl, recordType); 12064 } 12065 } 12066 } 12067 12068 if (Invalid) 12069 ExDecl->setInvalidDecl(); 12070 12071 return ExDecl; 12072 } 12073 12074 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 12075 /// handler. 12076 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 12077 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12078 bool Invalid = D.isInvalidType(); 12079 12080 // Check for unexpanded parameter packs. 12081 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12082 UPPC_ExceptionType)) { 12083 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12084 D.getIdentifierLoc()); 12085 Invalid = true; 12086 } 12087 12088 IdentifierInfo *II = D.getIdentifier(); 12089 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 12090 LookupOrdinaryName, 12091 ForRedeclaration)) { 12092 // The scope should be freshly made just for us. There is just no way 12093 // it contains any previous declaration, except for function parameters in 12094 // a function-try-block's catch statement. 12095 assert(!S->isDeclScope(PrevDecl)); 12096 if (isDeclInScope(PrevDecl, CurContext, S)) { 12097 Diag(D.getIdentifierLoc(), diag::err_redefinition) 12098 << D.getIdentifier(); 12099 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12100 Invalid = true; 12101 } else if (PrevDecl->isTemplateParameter()) 12102 // Maybe we will complain about the shadowed template parameter. 12103 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12104 } 12105 12106 if (D.getCXXScopeSpec().isSet() && !Invalid) { 12107 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 12108 << D.getCXXScopeSpec().getRange(); 12109 Invalid = true; 12110 } 12111 12112 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 12113 D.getLocStart(), 12114 D.getIdentifierLoc(), 12115 D.getIdentifier()); 12116 if (Invalid) 12117 ExDecl->setInvalidDecl(); 12118 12119 // Add the exception declaration into this scope. 12120 if (II) 12121 PushOnScopeChains(ExDecl, S); 12122 else 12123 CurContext->addDecl(ExDecl); 12124 12125 ProcessDeclAttributes(S, ExDecl, D); 12126 return ExDecl; 12127 } 12128 12129 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12130 Expr *AssertExpr, 12131 Expr *AssertMessageExpr, 12132 SourceLocation RParenLoc) { 12133 StringLiteral *AssertMessage = 12134 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 12135 12136 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 12137 return nullptr; 12138 12139 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 12140 AssertMessage, RParenLoc, false); 12141 } 12142 12143 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12144 Expr *AssertExpr, 12145 StringLiteral *AssertMessage, 12146 SourceLocation RParenLoc, 12147 bool Failed) { 12148 assert(AssertExpr != nullptr && "Expected non-null condition"); 12149 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 12150 !Failed) { 12151 // In a static_assert-declaration, the constant-expression shall be a 12152 // constant expression that can be contextually converted to bool. 12153 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 12154 if (Converted.isInvalid()) 12155 Failed = true; 12156 12157 llvm::APSInt Cond; 12158 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 12159 diag::err_static_assert_expression_is_not_constant, 12160 /*AllowFold=*/false).isInvalid()) 12161 Failed = true; 12162 12163 if (!Failed && !Cond) { 12164 SmallString<256> MsgBuffer; 12165 llvm::raw_svector_ostream Msg(MsgBuffer); 12166 if (AssertMessage) 12167 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 12168 Diag(StaticAssertLoc, diag::err_static_assert_failed) 12169 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 12170 Failed = true; 12171 } 12172 } 12173 12174 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 12175 AssertExpr, AssertMessage, RParenLoc, 12176 Failed); 12177 12178 CurContext->addDecl(Decl); 12179 return Decl; 12180 } 12181 12182 /// \brief Perform semantic analysis of the given friend type declaration. 12183 /// 12184 /// \returns A friend declaration that. 12185 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 12186 SourceLocation FriendLoc, 12187 TypeSourceInfo *TSInfo) { 12188 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 12189 12190 QualType T = TSInfo->getType(); 12191 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 12192 12193 // C++03 [class.friend]p2: 12194 // An elaborated-type-specifier shall be used in a friend declaration 12195 // for a class.* 12196 // 12197 // * The class-key of the elaborated-type-specifier is required. 12198 if (!ActiveTemplateInstantiations.empty()) { 12199 // Do not complain about the form of friend template types during 12200 // template instantiation; we will already have complained when the 12201 // template was declared. 12202 } else { 12203 if (!T->isElaboratedTypeSpecifier()) { 12204 // If we evaluated the type to a record type, suggest putting 12205 // a tag in front. 12206 if (const RecordType *RT = T->getAs<RecordType>()) { 12207 RecordDecl *RD = RT->getDecl(); 12208 12209 SmallString<16> InsertionText(" "); 12210 InsertionText += RD->getKindName(); 12211 12212 Diag(TypeRange.getBegin(), 12213 getLangOpts().CPlusPlus11 ? 12214 diag::warn_cxx98_compat_unelaborated_friend_type : 12215 diag::ext_unelaborated_friend_type) 12216 << (unsigned) RD->getTagKind() 12217 << T 12218 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 12219 InsertionText); 12220 } else { 12221 Diag(FriendLoc, 12222 getLangOpts().CPlusPlus11 ? 12223 diag::warn_cxx98_compat_nonclass_type_friend : 12224 diag::ext_nonclass_type_friend) 12225 << T 12226 << TypeRange; 12227 } 12228 } else if (T->getAs<EnumType>()) { 12229 Diag(FriendLoc, 12230 getLangOpts().CPlusPlus11 ? 12231 diag::warn_cxx98_compat_enum_friend : 12232 diag::ext_enum_friend) 12233 << T 12234 << TypeRange; 12235 } 12236 12237 // C++11 [class.friend]p3: 12238 // A friend declaration that does not declare a function shall have one 12239 // of the following forms: 12240 // friend elaborated-type-specifier ; 12241 // friend simple-type-specifier ; 12242 // friend typename-specifier ; 12243 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12244 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12245 } 12246 12247 // If the type specifier in a friend declaration designates a (possibly 12248 // cv-qualified) class type, that class is declared as a friend; otherwise, 12249 // the friend declaration is ignored. 12250 return FriendDecl::Create(Context, CurContext, 12251 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12252 FriendLoc); 12253 } 12254 12255 /// Handle a friend tag declaration where the scope specifier was 12256 /// templated. 12257 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12258 unsigned TagSpec, SourceLocation TagLoc, 12259 CXXScopeSpec &SS, 12260 IdentifierInfo *Name, 12261 SourceLocation NameLoc, 12262 AttributeList *Attr, 12263 MultiTemplateParamsArg TempParamLists) { 12264 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12265 12266 bool isExplicitSpecialization = false; 12267 bool Invalid = false; 12268 12269 if (TemplateParameterList *TemplateParams = 12270 MatchTemplateParametersToScopeSpecifier( 12271 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12272 isExplicitSpecialization, Invalid)) { 12273 if (TemplateParams->size() > 0) { 12274 // This is a declaration of a class template. 12275 if (Invalid) 12276 return nullptr; 12277 12278 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12279 NameLoc, Attr, TemplateParams, AS_public, 12280 /*ModulePrivateLoc=*/SourceLocation(), 12281 FriendLoc, TempParamLists.size() - 1, 12282 TempParamLists.data()).get(); 12283 } else { 12284 // The "template<>" header is extraneous. 12285 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12286 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12287 isExplicitSpecialization = true; 12288 } 12289 } 12290 12291 if (Invalid) return nullptr; 12292 12293 bool isAllExplicitSpecializations = true; 12294 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12295 if (TempParamLists[I]->size()) { 12296 isAllExplicitSpecializations = false; 12297 break; 12298 } 12299 } 12300 12301 // FIXME: don't ignore attributes. 12302 12303 // If it's explicit specializations all the way down, just forget 12304 // about the template header and build an appropriate non-templated 12305 // friend. TODO: for source fidelity, remember the headers. 12306 if (isAllExplicitSpecializations) { 12307 if (SS.isEmpty()) { 12308 bool Owned = false; 12309 bool IsDependent = false; 12310 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12311 Attr, AS_public, 12312 /*ModulePrivateLoc=*/SourceLocation(), 12313 MultiTemplateParamsArg(), Owned, IsDependent, 12314 /*ScopedEnumKWLoc=*/SourceLocation(), 12315 /*ScopedEnumUsesClassTag=*/false, 12316 /*UnderlyingType=*/TypeResult(), 12317 /*IsTypeSpecifier=*/false); 12318 } 12319 12320 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12321 ElaboratedTypeKeyword Keyword 12322 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12323 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12324 *Name, NameLoc); 12325 if (T.isNull()) 12326 return nullptr; 12327 12328 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12329 if (isa<DependentNameType>(T)) { 12330 DependentNameTypeLoc TL = 12331 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12332 TL.setElaboratedKeywordLoc(TagLoc); 12333 TL.setQualifierLoc(QualifierLoc); 12334 TL.setNameLoc(NameLoc); 12335 } else { 12336 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12337 TL.setElaboratedKeywordLoc(TagLoc); 12338 TL.setQualifierLoc(QualifierLoc); 12339 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12340 } 12341 12342 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12343 TSI, FriendLoc, TempParamLists); 12344 Friend->setAccess(AS_public); 12345 CurContext->addDecl(Friend); 12346 return Friend; 12347 } 12348 12349 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12350 12351 12352 12353 // Handle the case of a templated-scope friend class. e.g. 12354 // template <class T> class A<T>::B; 12355 // FIXME: we don't support these right now. 12356 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12357 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12358 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12359 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12360 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12361 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12362 TL.setElaboratedKeywordLoc(TagLoc); 12363 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12364 TL.setNameLoc(NameLoc); 12365 12366 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12367 TSI, FriendLoc, TempParamLists); 12368 Friend->setAccess(AS_public); 12369 Friend->setUnsupportedFriend(true); 12370 CurContext->addDecl(Friend); 12371 return Friend; 12372 } 12373 12374 12375 /// Handle a friend type declaration. This works in tandem with 12376 /// ActOnTag. 12377 /// 12378 /// Notes on friend class templates: 12379 /// 12380 /// We generally treat friend class declarations as if they were 12381 /// declaring a class. So, for example, the elaborated type specifier 12382 /// in a friend declaration is required to obey the restrictions of a 12383 /// class-head (i.e. no typedefs in the scope chain), template 12384 /// parameters are required to match up with simple template-ids, &c. 12385 /// However, unlike when declaring a template specialization, it's 12386 /// okay to refer to a template specialization without an empty 12387 /// template parameter declaration, e.g. 12388 /// friend class A<T>::B<unsigned>; 12389 /// We permit this as a special case; if there are any template 12390 /// parameters present at all, require proper matching, i.e. 12391 /// template <> template \<class T> friend class A<int>::B; 12392 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12393 MultiTemplateParamsArg TempParams) { 12394 SourceLocation Loc = DS.getLocStart(); 12395 12396 assert(DS.isFriendSpecified()); 12397 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12398 12399 // Try to convert the decl specifier to a type. This works for 12400 // friend templates because ActOnTag never produces a ClassTemplateDecl 12401 // for a TUK_Friend. 12402 Declarator TheDeclarator(DS, Declarator::MemberContext); 12403 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12404 QualType T = TSI->getType(); 12405 if (TheDeclarator.isInvalidType()) 12406 return nullptr; 12407 12408 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12409 return nullptr; 12410 12411 // This is definitely an error in C++98. It's probably meant to 12412 // be forbidden in C++0x, too, but the specification is just 12413 // poorly written. 12414 // 12415 // The problem is with declarations like the following: 12416 // template <T> friend A<T>::foo; 12417 // where deciding whether a class C is a friend or not now hinges 12418 // on whether there exists an instantiation of A that causes 12419 // 'foo' to equal C. There are restrictions on class-heads 12420 // (which we declare (by fiat) elaborated friend declarations to 12421 // be) that makes this tractable. 12422 // 12423 // FIXME: handle "template <> friend class A<T>;", which 12424 // is possibly well-formed? Who even knows? 12425 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12426 Diag(Loc, diag::err_tagless_friend_type_template) 12427 << DS.getSourceRange(); 12428 return nullptr; 12429 } 12430 12431 // C++98 [class.friend]p1: A friend of a class is a function 12432 // or class that is not a member of the class . . . 12433 // This is fixed in DR77, which just barely didn't make the C++03 12434 // deadline. It's also a very silly restriction that seriously 12435 // affects inner classes and which nobody else seems to implement; 12436 // thus we never diagnose it, not even in -pedantic. 12437 // 12438 // But note that we could warn about it: it's always useless to 12439 // friend one of your own members (it's not, however, worthless to 12440 // friend a member of an arbitrary specialization of your template). 12441 12442 Decl *D; 12443 if (unsigned NumTempParamLists = TempParams.size()) 12444 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12445 NumTempParamLists, 12446 TempParams.data(), 12447 TSI, 12448 DS.getFriendSpecLoc()); 12449 else 12450 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12451 12452 if (!D) 12453 return nullptr; 12454 12455 D->setAccess(AS_public); 12456 CurContext->addDecl(D); 12457 12458 return D; 12459 } 12460 12461 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12462 MultiTemplateParamsArg TemplateParams) { 12463 const DeclSpec &DS = D.getDeclSpec(); 12464 12465 assert(DS.isFriendSpecified()); 12466 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12467 12468 SourceLocation Loc = D.getIdentifierLoc(); 12469 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12470 12471 // C++ [class.friend]p1 12472 // A friend of a class is a function or class.... 12473 // Note that this sees through typedefs, which is intended. 12474 // It *doesn't* see through dependent types, which is correct 12475 // according to [temp.arg.type]p3: 12476 // If a declaration acquires a function type through a 12477 // type dependent on a template-parameter and this causes 12478 // a declaration that does not use the syntactic form of a 12479 // function declarator to have a function type, the program 12480 // is ill-formed. 12481 if (!TInfo->getType()->isFunctionType()) { 12482 Diag(Loc, diag::err_unexpected_friend); 12483 12484 // It might be worthwhile to try to recover by creating an 12485 // appropriate declaration. 12486 return nullptr; 12487 } 12488 12489 // C++ [namespace.memdef]p3 12490 // - If a friend declaration in a non-local class first declares a 12491 // class or function, the friend class or function is a member 12492 // of the innermost enclosing namespace. 12493 // - The name of the friend is not found by simple name lookup 12494 // until a matching declaration is provided in that namespace 12495 // scope (either before or after the class declaration granting 12496 // friendship). 12497 // - If a friend function is called, its name may be found by the 12498 // name lookup that considers functions from namespaces and 12499 // classes associated with the types of the function arguments. 12500 // - When looking for a prior declaration of a class or a function 12501 // declared as a friend, scopes outside the innermost enclosing 12502 // namespace scope are not considered. 12503 12504 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12505 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12506 DeclarationName Name = NameInfo.getName(); 12507 assert(Name); 12508 12509 // Check for unexpanded parameter packs. 12510 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12511 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12512 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12513 return nullptr; 12514 12515 // The context we found the declaration in, or in which we should 12516 // create the declaration. 12517 DeclContext *DC; 12518 Scope *DCScope = S; 12519 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12520 ForRedeclaration); 12521 12522 // There are five cases here. 12523 // - There's no scope specifier and we're in a local class. Only look 12524 // for functions declared in the immediately-enclosing block scope. 12525 // We recover from invalid scope qualifiers as if they just weren't there. 12526 FunctionDecl *FunctionContainingLocalClass = nullptr; 12527 if ((SS.isInvalid() || !SS.isSet()) && 12528 (FunctionContainingLocalClass = 12529 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12530 // C++11 [class.friend]p11: 12531 // If a friend declaration appears in a local class and the name 12532 // specified is an unqualified name, a prior declaration is 12533 // looked up without considering scopes that are outside the 12534 // innermost enclosing non-class scope. For a friend function 12535 // declaration, if there is no prior declaration, the program is 12536 // ill-formed. 12537 12538 // Find the innermost enclosing non-class scope. This is the block 12539 // scope containing the local class definition (or for a nested class, 12540 // the outer local class). 12541 DCScope = S->getFnParent(); 12542 12543 // Look up the function name in the scope. 12544 Previous.clear(LookupLocalFriendName); 12545 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12546 12547 if (!Previous.empty()) { 12548 // All possible previous declarations must have the same context: 12549 // either they were declared at block scope or they are members of 12550 // one of the enclosing local classes. 12551 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12552 } else { 12553 // This is ill-formed, but provide the context that we would have 12554 // declared the function in, if we were permitted to, for error recovery. 12555 DC = FunctionContainingLocalClass; 12556 } 12557 adjustContextForLocalExternDecl(DC); 12558 12559 // C++ [class.friend]p6: 12560 // A function can be defined in a friend declaration of a class if and 12561 // only if the class is a non-local class (9.8), the function name is 12562 // unqualified, and the function has namespace scope. 12563 if (D.isFunctionDefinition()) { 12564 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12565 } 12566 12567 // - There's no scope specifier, in which case we just go to the 12568 // appropriate scope and look for a function or function template 12569 // there as appropriate. 12570 } else if (SS.isInvalid() || !SS.isSet()) { 12571 // C++11 [namespace.memdef]p3: 12572 // If the name in a friend declaration is neither qualified nor 12573 // a template-id and the declaration is a function or an 12574 // elaborated-type-specifier, the lookup to determine whether 12575 // the entity has been previously declared shall not consider 12576 // any scopes outside the innermost enclosing namespace. 12577 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12578 12579 // Find the appropriate context according to the above. 12580 DC = CurContext; 12581 12582 // Skip class contexts. If someone can cite chapter and verse 12583 // for this behavior, that would be nice --- it's what GCC and 12584 // EDG do, and it seems like a reasonable intent, but the spec 12585 // really only says that checks for unqualified existing 12586 // declarations should stop at the nearest enclosing namespace, 12587 // not that they should only consider the nearest enclosing 12588 // namespace. 12589 while (DC->isRecord()) 12590 DC = DC->getParent(); 12591 12592 DeclContext *LookupDC = DC; 12593 while (LookupDC->isTransparentContext()) 12594 LookupDC = LookupDC->getParent(); 12595 12596 while (true) { 12597 LookupQualifiedName(Previous, LookupDC); 12598 12599 if (!Previous.empty()) { 12600 DC = LookupDC; 12601 break; 12602 } 12603 12604 if (isTemplateId) { 12605 if (isa<TranslationUnitDecl>(LookupDC)) break; 12606 } else { 12607 if (LookupDC->isFileContext()) break; 12608 } 12609 LookupDC = LookupDC->getParent(); 12610 } 12611 12612 DCScope = getScopeForDeclContext(S, DC); 12613 12614 // - There's a non-dependent scope specifier, in which case we 12615 // compute it and do a previous lookup there for a function 12616 // or function template. 12617 } else if (!SS.getScopeRep()->isDependent()) { 12618 DC = computeDeclContext(SS); 12619 if (!DC) return nullptr; 12620 12621 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12622 12623 LookupQualifiedName(Previous, DC); 12624 12625 // Ignore things found implicitly in the wrong scope. 12626 // TODO: better diagnostics for this case. Suggesting the right 12627 // qualified scope would be nice... 12628 LookupResult::Filter F = Previous.makeFilter(); 12629 while (F.hasNext()) { 12630 NamedDecl *D = F.next(); 12631 if (!DC->InEnclosingNamespaceSetOf( 12632 D->getDeclContext()->getRedeclContext())) 12633 F.erase(); 12634 } 12635 F.done(); 12636 12637 if (Previous.empty()) { 12638 D.setInvalidType(); 12639 Diag(Loc, diag::err_qualified_friend_not_found) 12640 << Name << TInfo->getType(); 12641 return nullptr; 12642 } 12643 12644 // C++ [class.friend]p1: A friend of a class is a function or 12645 // class that is not a member of the class . . . 12646 if (DC->Equals(CurContext)) 12647 Diag(DS.getFriendSpecLoc(), 12648 getLangOpts().CPlusPlus11 ? 12649 diag::warn_cxx98_compat_friend_is_member : 12650 diag::err_friend_is_member); 12651 12652 if (D.isFunctionDefinition()) { 12653 // C++ [class.friend]p6: 12654 // A function can be defined in a friend declaration of a class if and 12655 // only if the class is a non-local class (9.8), the function name is 12656 // unqualified, and the function has namespace scope. 12657 SemaDiagnosticBuilder DB 12658 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12659 12660 DB << SS.getScopeRep(); 12661 if (DC->isFileContext()) 12662 DB << FixItHint::CreateRemoval(SS.getRange()); 12663 SS.clear(); 12664 } 12665 12666 // - There's a scope specifier that does not match any template 12667 // parameter lists, in which case we use some arbitrary context, 12668 // create a method or method template, and wait for instantiation. 12669 // - There's a scope specifier that does match some template 12670 // parameter lists, which we don't handle right now. 12671 } else { 12672 if (D.isFunctionDefinition()) { 12673 // C++ [class.friend]p6: 12674 // A function can be defined in a friend declaration of a class if and 12675 // only if the class is a non-local class (9.8), the function name is 12676 // unqualified, and the function has namespace scope. 12677 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12678 << SS.getScopeRep(); 12679 } 12680 12681 DC = CurContext; 12682 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12683 } 12684 12685 if (!DC->isRecord()) { 12686 int DiagArg = -1; 12687 switch (D.getName().getKind()) { 12688 case UnqualifiedId::IK_ConstructorTemplateId: 12689 case UnqualifiedId::IK_ConstructorName: 12690 DiagArg = 0; 12691 break; 12692 case UnqualifiedId::IK_DestructorName: 12693 DiagArg = 1; 12694 break; 12695 case UnqualifiedId::IK_ConversionFunctionId: 12696 DiagArg = 2; 12697 break; 12698 case UnqualifiedId::IK_Identifier: 12699 case UnqualifiedId::IK_ImplicitSelfParam: 12700 case UnqualifiedId::IK_LiteralOperatorId: 12701 case UnqualifiedId::IK_OperatorFunctionId: 12702 case UnqualifiedId::IK_TemplateId: 12703 break; 12704 } 12705 // This implies that it has to be an operator or function. 12706 if (DiagArg >= 0) { 12707 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 12708 return nullptr; 12709 } 12710 } 12711 12712 // FIXME: This is an egregious hack to cope with cases where the scope stack 12713 // does not contain the declaration context, i.e., in an out-of-line 12714 // definition of a class. 12715 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12716 if (!DCScope) { 12717 FakeDCScope.setEntity(DC); 12718 DCScope = &FakeDCScope; 12719 } 12720 12721 bool AddToScope = true; 12722 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12723 TemplateParams, AddToScope); 12724 if (!ND) return nullptr; 12725 12726 assert(ND->getLexicalDeclContext() == CurContext); 12727 12728 // If we performed typo correction, we might have added a scope specifier 12729 // and changed the decl context. 12730 DC = ND->getDeclContext(); 12731 12732 // Add the function declaration to the appropriate lookup tables, 12733 // adjusting the redeclarations list as necessary. We don't 12734 // want to do this yet if the friending class is dependent. 12735 // 12736 // Also update the scope-based lookup if the target context's 12737 // lookup context is in lexical scope. 12738 if (!CurContext->isDependentContext()) { 12739 DC = DC->getRedeclContext(); 12740 DC->makeDeclVisibleInContext(ND); 12741 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12742 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12743 } 12744 12745 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12746 D.getIdentifierLoc(), ND, 12747 DS.getFriendSpecLoc()); 12748 FrD->setAccess(AS_public); 12749 CurContext->addDecl(FrD); 12750 12751 if (ND->isInvalidDecl()) { 12752 FrD->setInvalidDecl(); 12753 } else { 12754 if (DC->isRecord()) CheckFriendAccess(ND); 12755 12756 FunctionDecl *FD; 12757 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12758 FD = FTD->getTemplatedDecl(); 12759 else 12760 FD = cast<FunctionDecl>(ND); 12761 12762 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12763 // default argument expression, that declaration shall be a definition 12764 // and shall be the only declaration of the function or function 12765 // template in the translation unit. 12766 if (functionDeclHasDefaultArgument(FD)) { 12767 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12768 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12769 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12770 } else if (!D.isFunctionDefinition()) 12771 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12772 } 12773 12774 // Mark templated-scope function declarations as unsupported. 12775 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12776 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12777 << SS.getScopeRep() << SS.getRange() 12778 << cast<CXXRecordDecl>(CurContext); 12779 FrD->setUnsupportedFriend(true); 12780 } 12781 } 12782 12783 return ND; 12784 } 12785 12786 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12787 AdjustDeclIfTemplate(Dcl); 12788 12789 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12790 if (!Fn) { 12791 Diag(DelLoc, diag::err_deleted_non_function); 12792 return; 12793 } 12794 12795 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12796 // Don't consider the implicit declaration we generate for explicit 12797 // specializations. FIXME: Do not generate these implicit declarations. 12798 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12799 Prev->getPreviousDecl()) && 12800 !Prev->isDefined()) { 12801 Diag(DelLoc, diag::err_deleted_decl_not_first); 12802 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12803 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12804 : diag::note_previous_declaration); 12805 } 12806 // If the declaration wasn't the first, we delete the function anyway for 12807 // recovery. 12808 Fn = Fn->getCanonicalDecl(); 12809 } 12810 12811 // dllimport/dllexport cannot be deleted. 12812 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12813 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12814 Fn->setInvalidDecl(); 12815 } 12816 12817 if (Fn->isDeleted()) 12818 return; 12819 12820 // See if we're deleting a function which is already known to override a 12821 // non-deleted virtual function. 12822 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12823 bool IssuedDiagnostic = false; 12824 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12825 E = MD->end_overridden_methods(); 12826 I != E; ++I) { 12827 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12828 if (!IssuedDiagnostic) { 12829 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12830 IssuedDiagnostic = true; 12831 } 12832 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12833 } 12834 } 12835 } 12836 12837 // C++11 [basic.start.main]p3: 12838 // A program that defines main as deleted [...] is ill-formed. 12839 if (Fn->isMain()) 12840 Diag(DelLoc, diag::err_deleted_main); 12841 12842 Fn->setDeletedAsWritten(); 12843 } 12844 12845 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12846 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12847 12848 if (MD) { 12849 if (MD->getParent()->isDependentType()) { 12850 MD->setDefaulted(); 12851 MD->setExplicitlyDefaulted(); 12852 return; 12853 } 12854 12855 CXXSpecialMember Member = getSpecialMember(MD); 12856 if (Member == CXXInvalid) { 12857 if (!MD->isInvalidDecl()) 12858 Diag(DefaultLoc, diag::err_default_special_members); 12859 return; 12860 } 12861 12862 MD->setDefaulted(); 12863 MD->setExplicitlyDefaulted(); 12864 12865 // If this definition appears within the record, do the checking when 12866 // the record is complete. 12867 const FunctionDecl *Primary = MD; 12868 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12869 // Find the uninstantiated declaration that actually had the '= default' 12870 // on it. 12871 Pattern->isDefined(Primary); 12872 12873 // If the method was defaulted on its first declaration, we will have 12874 // already performed the checking in CheckCompletedCXXClass. Such a 12875 // declaration doesn't trigger an implicit definition. 12876 if (Primary == Primary->getCanonicalDecl()) 12877 return; 12878 12879 CheckExplicitlyDefaultedSpecialMember(MD); 12880 12881 if (MD->isInvalidDecl()) 12882 return; 12883 12884 switch (Member) { 12885 case CXXDefaultConstructor: 12886 DefineImplicitDefaultConstructor(DefaultLoc, 12887 cast<CXXConstructorDecl>(MD)); 12888 break; 12889 case CXXCopyConstructor: 12890 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12891 break; 12892 case CXXCopyAssignment: 12893 DefineImplicitCopyAssignment(DefaultLoc, MD); 12894 break; 12895 case CXXDestructor: 12896 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12897 break; 12898 case CXXMoveConstructor: 12899 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12900 break; 12901 case CXXMoveAssignment: 12902 DefineImplicitMoveAssignment(DefaultLoc, MD); 12903 break; 12904 case CXXInvalid: 12905 llvm_unreachable("Invalid special member."); 12906 } 12907 } else { 12908 Diag(DefaultLoc, diag::err_default_special_members); 12909 } 12910 } 12911 12912 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12913 for (Stmt *SubStmt : S->children()) { 12914 if (!SubStmt) 12915 continue; 12916 if (isa<ReturnStmt>(SubStmt)) 12917 Self.Diag(SubStmt->getLocStart(), 12918 diag::err_return_in_constructor_handler); 12919 if (!isa<Expr>(SubStmt)) 12920 SearchForReturnInStmt(Self, SubStmt); 12921 } 12922 } 12923 12924 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12925 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12926 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12927 SearchForReturnInStmt(*this, Handler); 12928 } 12929 } 12930 12931 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12932 const CXXMethodDecl *Old) { 12933 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12934 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12935 12936 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12937 12938 // If the calling conventions match, everything is fine 12939 if (NewCC == OldCC) 12940 return false; 12941 12942 // If the calling conventions mismatch because the new function is static, 12943 // suppress the calling convention mismatch error; the error about static 12944 // function override (err_static_overrides_virtual from 12945 // Sema::CheckFunctionDeclaration) is more clear. 12946 if (New->getStorageClass() == SC_Static) 12947 return false; 12948 12949 Diag(New->getLocation(), 12950 diag::err_conflicting_overriding_cc_attributes) 12951 << New->getDeclName() << New->getType() << Old->getType(); 12952 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12953 return true; 12954 } 12955 12956 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12957 const CXXMethodDecl *Old) { 12958 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12959 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12960 12961 if (Context.hasSameType(NewTy, OldTy) || 12962 NewTy->isDependentType() || OldTy->isDependentType()) 12963 return false; 12964 12965 // Check if the return types are covariant 12966 QualType NewClassTy, OldClassTy; 12967 12968 /// Both types must be pointers or references to classes. 12969 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12970 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12971 NewClassTy = NewPT->getPointeeType(); 12972 OldClassTy = OldPT->getPointeeType(); 12973 } 12974 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12975 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12976 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12977 NewClassTy = NewRT->getPointeeType(); 12978 OldClassTy = OldRT->getPointeeType(); 12979 } 12980 } 12981 } 12982 12983 // The return types aren't either both pointers or references to a class type. 12984 if (NewClassTy.isNull()) { 12985 Diag(New->getLocation(), 12986 diag::err_different_return_type_for_overriding_virtual_function) 12987 << New->getDeclName() << NewTy << OldTy 12988 << New->getReturnTypeSourceRange(); 12989 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12990 << Old->getReturnTypeSourceRange(); 12991 12992 return true; 12993 } 12994 12995 // C++ [class.virtual]p6: 12996 // If the return type of D::f differs from the return type of B::f, the 12997 // class type in the return type of D::f shall be complete at the point of 12998 // declaration of D::f or shall be the class type D. 12999 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 13000 if (!RT->isBeingDefined() && 13001 RequireCompleteType(New->getLocation(), NewClassTy, 13002 diag::err_covariant_return_incomplete, 13003 New->getDeclName())) 13004 return true; 13005 } 13006 13007 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 13008 // Check if the new class derives from the old class. 13009 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 13010 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 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 // Check if we the conversion from derived to base is valid. 13019 if (CheckDerivedToBaseConversion( 13020 NewClassTy, OldClassTy, 13021 diag::err_covariant_return_inaccessible_base, 13022 diag::err_covariant_return_ambiguous_derived_to_base_conv, 13023 New->getLocation(), New->getReturnTypeSourceRange(), 13024 New->getDeclName(), nullptr)) { 13025 // FIXME: this note won't trigger for delayed access control 13026 // diagnostics, and it's impossible to get an undelayed error 13027 // here from access control during the original parse because 13028 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 13029 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13030 << Old->getReturnTypeSourceRange(); 13031 return true; 13032 } 13033 } 13034 13035 // The qualifiers of the return types must be the same. 13036 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 13037 Diag(New->getLocation(), 13038 diag::err_covariant_return_type_different_qualifications) 13039 << New->getDeclName() << NewTy << OldTy 13040 << New->getReturnTypeSourceRange(); 13041 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13042 << Old->getReturnTypeSourceRange(); 13043 return true; 13044 }; 13045 13046 13047 // The new class type must have the same or less qualifiers as the old type. 13048 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 13049 Diag(New->getLocation(), 13050 diag::err_covariant_return_type_class_type_more_qualified) 13051 << New->getDeclName() << NewTy << OldTy 13052 << New->getReturnTypeSourceRange(); 13053 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13054 << Old->getReturnTypeSourceRange(); 13055 return true; 13056 }; 13057 13058 return false; 13059 } 13060 13061 /// \brief Mark the given method pure. 13062 /// 13063 /// \param Method the method to be marked pure. 13064 /// 13065 /// \param InitRange the source range that covers the "0" initializer. 13066 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 13067 SourceLocation EndLoc = InitRange.getEnd(); 13068 if (EndLoc.isValid()) 13069 Method->setRangeEnd(EndLoc); 13070 13071 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 13072 Method->setPure(); 13073 return false; 13074 } 13075 13076 if (!Method->isInvalidDecl()) 13077 Diag(Method->getLocation(), diag::err_non_virtual_pure) 13078 << Method->getDeclName() << InitRange; 13079 return true; 13080 } 13081 13082 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 13083 if (D->getFriendObjectKind()) 13084 Diag(D->getLocation(), diag::err_pure_friend); 13085 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 13086 CheckPureMethod(M, ZeroLoc); 13087 else 13088 Diag(D->getLocation(), diag::err_illegal_initializer); 13089 } 13090 13091 /// \brief Determine whether the given declaration is a static data member. 13092 static bool isStaticDataMember(const Decl *D) { 13093 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 13094 return Var->isStaticDataMember(); 13095 13096 return false; 13097 } 13098 13099 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 13100 /// an initializer for the out-of-line declaration 'Dcl'. The scope 13101 /// is a fresh scope pushed for just this purpose. 13102 /// 13103 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 13104 /// static data member of class X, names should be looked up in the scope of 13105 /// class X. 13106 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 13107 // If there is no declaration, there was an error parsing it. 13108 if (!D || D->isInvalidDecl()) 13109 return; 13110 13111 // We will always have a nested name specifier here, but this declaration 13112 // might not be out of line if the specifier names the current namespace: 13113 // extern int n; 13114 // int ::n = 0; 13115 if (D->isOutOfLine()) 13116 EnterDeclaratorContext(S, D->getDeclContext()); 13117 13118 // If we are parsing the initializer for a static data member, push a 13119 // new expression evaluation context that is associated with this static 13120 // data member. 13121 if (isStaticDataMember(D)) 13122 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 13123 } 13124 13125 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 13126 /// initializer for the out-of-line declaration 'D'. 13127 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 13128 // If there is no declaration, there was an error parsing it. 13129 if (!D || D->isInvalidDecl()) 13130 return; 13131 13132 if (isStaticDataMember(D)) 13133 PopExpressionEvaluationContext(); 13134 13135 if (D->isOutOfLine()) 13136 ExitDeclaratorContext(S); 13137 } 13138 13139 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 13140 /// C++ if/switch/while/for statement. 13141 /// e.g: "if (int x = f()) {...}" 13142 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 13143 // C++ 6.4p2: 13144 // The declarator shall not specify a function or an array. 13145 // The type-specifier-seq shall not contain typedef and shall not declare a 13146 // new class or enumeration. 13147 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 13148 "Parser allowed 'typedef' as storage class of condition decl."); 13149 13150 Decl *Dcl = ActOnDeclarator(S, D); 13151 if (!Dcl) 13152 return true; 13153 13154 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 13155 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 13156 << D.getSourceRange(); 13157 return true; 13158 } 13159 13160 return Dcl; 13161 } 13162 13163 void Sema::LoadExternalVTableUses() { 13164 if (!ExternalSource) 13165 return; 13166 13167 SmallVector<ExternalVTableUse, 4> VTables; 13168 ExternalSource->ReadUsedVTables(VTables); 13169 SmallVector<VTableUse, 4> NewUses; 13170 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 13171 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 13172 = VTablesUsed.find(VTables[I].Record); 13173 // Even if a definition wasn't required before, it may be required now. 13174 if (Pos != VTablesUsed.end()) { 13175 if (!Pos->second && VTables[I].DefinitionRequired) 13176 Pos->second = true; 13177 continue; 13178 } 13179 13180 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 13181 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 13182 } 13183 13184 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 13185 } 13186 13187 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 13188 bool DefinitionRequired) { 13189 // Ignore any vtable uses in unevaluated operands or for classes that do 13190 // not have a vtable. 13191 if (!Class->isDynamicClass() || Class->isDependentContext() || 13192 CurContext->isDependentContext() || isUnevaluatedContext()) 13193 return; 13194 13195 // Try to insert this class into the map. 13196 LoadExternalVTableUses(); 13197 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13198 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 13199 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 13200 if (!Pos.second) { 13201 // If we already had an entry, check to see if we are promoting this vtable 13202 // to require a definition. If so, we need to reappend to the VTableUses 13203 // list, since we may have already processed the first entry. 13204 if (DefinitionRequired && !Pos.first->second) { 13205 Pos.first->second = true; 13206 } else { 13207 // Otherwise, we can early exit. 13208 return; 13209 } 13210 } else { 13211 // The Microsoft ABI requires that we perform the destructor body 13212 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 13213 // the deleting destructor is emitted with the vtable, not with the 13214 // destructor definition as in the Itanium ABI. 13215 // If it has a definition, we do the check at that point instead. 13216 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13217 Class->hasUserDeclaredDestructor() && 13218 !Class->getDestructor()->isDefined() && 13219 !Class->getDestructor()->isDeleted()) { 13220 CXXDestructorDecl *DD = Class->getDestructor(); 13221 ContextRAII SavedContext(*this, DD); 13222 CheckDestructor(DD); 13223 } 13224 } 13225 13226 // Local classes need to have their virtual members marked 13227 // immediately. For all other classes, we mark their virtual members 13228 // at the end of the translation unit. 13229 if (Class->isLocalClass()) 13230 MarkVirtualMembersReferenced(Loc, Class); 13231 else 13232 VTableUses.push_back(std::make_pair(Class, Loc)); 13233 } 13234 13235 bool Sema::DefineUsedVTables() { 13236 LoadExternalVTableUses(); 13237 if (VTableUses.empty()) 13238 return false; 13239 13240 // Note: The VTableUses vector could grow as a result of marking 13241 // the members of a class as "used", so we check the size each 13242 // time through the loop and prefer indices (which are stable) to 13243 // iterators (which are not). 13244 bool DefinedAnything = false; 13245 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13246 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13247 if (!Class) 13248 continue; 13249 13250 SourceLocation Loc = VTableUses[I].second; 13251 13252 bool DefineVTable = true; 13253 13254 // If this class has a key function, but that key function is 13255 // defined in another translation unit, we don't need to emit the 13256 // vtable even though we're using it. 13257 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13258 if (KeyFunction && !KeyFunction->hasBody()) { 13259 // The key function is in another translation unit. 13260 DefineVTable = false; 13261 TemplateSpecializationKind TSK = 13262 KeyFunction->getTemplateSpecializationKind(); 13263 assert(TSK != TSK_ExplicitInstantiationDefinition && 13264 TSK != TSK_ImplicitInstantiation && 13265 "Instantiations don't have key functions"); 13266 (void)TSK; 13267 } else if (!KeyFunction) { 13268 // If we have a class with no key function that is the subject 13269 // of an explicit instantiation declaration, suppress the 13270 // vtable; it will live with the explicit instantiation 13271 // definition. 13272 bool IsExplicitInstantiationDeclaration 13273 = Class->getTemplateSpecializationKind() 13274 == TSK_ExplicitInstantiationDeclaration; 13275 for (auto R : Class->redecls()) { 13276 TemplateSpecializationKind TSK 13277 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13278 if (TSK == TSK_ExplicitInstantiationDeclaration) 13279 IsExplicitInstantiationDeclaration = true; 13280 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13281 IsExplicitInstantiationDeclaration = false; 13282 break; 13283 } 13284 } 13285 13286 if (IsExplicitInstantiationDeclaration) 13287 DefineVTable = false; 13288 } 13289 13290 // The exception specifications for all virtual members may be needed even 13291 // if we are not providing an authoritative form of the vtable in this TU. 13292 // We may choose to emit it available_externally anyway. 13293 if (!DefineVTable) { 13294 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13295 continue; 13296 } 13297 13298 // Mark all of the virtual members of this class as referenced, so 13299 // that we can build a vtable. Then, tell the AST consumer that a 13300 // vtable for this class is required. 13301 DefinedAnything = true; 13302 MarkVirtualMembersReferenced(Loc, Class); 13303 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13304 if (VTablesUsed[Canonical]) 13305 Consumer.HandleVTable(Class); 13306 13307 // Optionally warn if we're emitting a weak vtable. 13308 if (Class->isExternallyVisible() && 13309 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13310 const FunctionDecl *KeyFunctionDef = nullptr; 13311 if (!KeyFunction || 13312 (KeyFunction->hasBody(KeyFunctionDef) && 13313 KeyFunctionDef->isInlined())) 13314 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13315 TSK_ExplicitInstantiationDefinition 13316 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13317 << Class; 13318 } 13319 } 13320 VTableUses.clear(); 13321 13322 return DefinedAnything; 13323 } 13324 13325 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13326 const CXXRecordDecl *RD) { 13327 for (const auto *I : RD->methods()) 13328 if (I->isVirtual() && !I->isPure()) 13329 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13330 } 13331 13332 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13333 const CXXRecordDecl *RD) { 13334 // Mark all functions which will appear in RD's vtable as used. 13335 CXXFinalOverriderMap FinalOverriders; 13336 RD->getFinalOverriders(FinalOverriders); 13337 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13338 E = FinalOverriders.end(); 13339 I != E; ++I) { 13340 for (OverridingMethods::const_iterator OI = I->second.begin(), 13341 OE = I->second.end(); 13342 OI != OE; ++OI) { 13343 assert(OI->second.size() > 0 && "no final overrider"); 13344 CXXMethodDecl *Overrider = OI->second.front().Method; 13345 13346 // C++ [basic.def.odr]p2: 13347 // [...] A virtual member function is used if it is not pure. [...] 13348 if (!Overrider->isPure()) 13349 MarkFunctionReferenced(Loc, Overrider); 13350 } 13351 } 13352 13353 // Only classes that have virtual bases need a VTT. 13354 if (RD->getNumVBases() == 0) 13355 return; 13356 13357 for (const auto &I : RD->bases()) { 13358 const CXXRecordDecl *Base = 13359 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13360 if (Base->getNumVBases() == 0) 13361 continue; 13362 MarkVirtualMembersReferenced(Loc, Base); 13363 } 13364 } 13365 13366 /// SetIvarInitializers - This routine builds initialization ASTs for the 13367 /// Objective-C implementation whose ivars need be initialized. 13368 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13369 if (!getLangOpts().CPlusPlus) 13370 return; 13371 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13372 SmallVector<ObjCIvarDecl*, 8> ivars; 13373 CollectIvarsToConstructOrDestruct(OID, ivars); 13374 if (ivars.empty()) 13375 return; 13376 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13377 for (unsigned i = 0; i < ivars.size(); i++) { 13378 FieldDecl *Field = ivars[i]; 13379 if (Field->isInvalidDecl()) 13380 continue; 13381 13382 CXXCtorInitializer *Member; 13383 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13384 InitializationKind InitKind = 13385 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13386 13387 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13388 ExprResult MemberInit = 13389 InitSeq.Perform(*this, InitEntity, InitKind, None); 13390 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13391 // Note, MemberInit could actually come back empty if no initialization 13392 // is required (e.g., because it would call a trivial default constructor) 13393 if (!MemberInit.get() || MemberInit.isInvalid()) 13394 continue; 13395 13396 Member = 13397 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13398 SourceLocation(), 13399 MemberInit.getAs<Expr>(), 13400 SourceLocation()); 13401 AllToInit.push_back(Member); 13402 13403 // Be sure that the destructor is accessible and is marked as referenced. 13404 if (const RecordType *RecordTy = 13405 Context.getBaseElementType(Field->getType()) 13406 ->getAs<RecordType>()) { 13407 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13408 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13409 MarkFunctionReferenced(Field->getLocation(), Destructor); 13410 CheckDestructorAccess(Field->getLocation(), Destructor, 13411 PDiag(diag::err_access_dtor_ivar) 13412 << Context.getBaseElementType(Field->getType())); 13413 } 13414 } 13415 } 13416 ObjCImplementation->setIvarInitializers(Context, 13417 AllToInit.data(), AllToInit.size()); 13418 } 13419 } 13420 13421 static 13422 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13423 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13424 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13425 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13426 Sema &S) { 13427 if (Ctor->isInvalidDecl()) 13428 return; 13429 13430 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13431 13432 // Target may not be determinable yet, for instance if this is a dependent 13433 // call in an uninstantiated template. 13434 if (Target) { 13435 const FunctionDecl *FNTarget = nullptr; 13436 (void)Target->hasBody(FNTarget); 13437 Target = const_cast<CXXConstructorDecl*>( 13438 cast_or_null<CXXConstructorDecl>(FNTarget)); 13439 } 13440 13441 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13442 // Avoid dereferencing a null pointer here. 13443 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13444 13445 if (!Current.insert(Canonical).second) 13446 return; 13447 13448 // We know that beyond here, we aren't chaining into a cycle. 13449 if (!Target || !Target->isDelegatingConstructor() || 13450 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13451 Valid.insert(Current.begin(), Current.end()); 13452 Current.clear(); 13453 // We've hit a cycle. 13454 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13455 Current.count(TCanonical)) { 13456 // If we haven't diagnosed this cycle yet, do so now. 13457 if (!Invalid.count(TCanonical)) { 13458 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13459 diag::warn_delegating_ctor_cycle) 13460 << Ctor; 13461 13462 // Don't add a note for a function delegating directly to itself. 13463 if (TCanonical != Canonical) 13464 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13465 13466 CXXConstructorDecl *C = Target; 13467 while (C->getCanonicalDecl() != Canonical) { 13468 const FunctionDecl *FNTarget = nullptr; 13469 (void)C->getTargetConstructor()->hasBody(FNTarget); 13470 assert(FNTarget && "Ctor cycle through bodiless function"); 13471 13472 C = const_cast<CXXConstructorDecl*>( 13473 cast<CXXConstructorDecl>(FNTarget)); 13474 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13475 } 13476 } 13477 13478 Invalid.insert(Current.begin(), Current.end()); 13479 Current.clear(); 13480 } else { 13481 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13482 } 13483 } 13484 13485 13486 void Sema::CheckDelegatingCtorCycles() { 13487 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13488 13489 for (DelegatingCtorDeclsType::iterator 13490 I = DelegatingCtorDecls.begin(ExternalSource), 13491 E = DelegatingCtorDecls.end(); 13492 I != E; ++I) 13493 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13494 13495 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13496 CE = Invalid.end(); 13497 CI != CE; ++CI) 13498 (*CI)->setInvalidDecl(); 13499 } 13500 13501 namespace { 13502 /// \brief AST visitor that finds references to the 'this' expression. 13503 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13504 Sema &S; 13505 13506 public: 13507 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13508 13509 bool VisitCXXThisExpr(CXXThisExpr *E) { 13510 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13511 << E->isImplicit(); 13512 return false; 13513 } 13514 }; 13515 } 13516 13517 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13518 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13519 if (!TSInfo) 13520 return false; 13521 13522 TypeLoc TL = TSInfo->getTypeLoc(); 13523 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13524 if (!ProtoTL) 13525 return false; 13526 13527 // C++11 [expr.prim.general]p3: 13528 // [The expression this] shall not appear before the optional 13529 // cv-qualifier-seq and it shall not appear within the declaration of a 13530 // static member function (although its type and value category are defined 13531 // within a static member function as they are within a non-static member 13532 // function). [ Note: this is because declaration matching does not occur 13533 // until the complete declarator is known. - end note ] 13534 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13535 FindCXXThisExpr Finder(*this); 13536 13537 // If the return type came after the cv-qualifier-seq, check it now. 13538 if (Proto->hasTrailingReturn() && 13539 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13540 return true; 13541 13542 // Check the exception specification. 13543 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13544 return true; 13545 13546 return checkThisInStaticMemberFunctionAttributes(Method); 13547 } 13548 13549 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13550 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13551 if (!TSInfo) 13552 return false; 13553 13554 TypeLoc TL = TSInfo->getTypeLoc(); 13555 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13556 if (!ProtoTL) 13557 return false; 13558 13559 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13560 FindCXXThisExpr Finder(*this); 13561 13562 switch (Proto->getExceptionSpecType()) { 13563 case EST_Unparsed: 13564 case EST_Uninstantiated: 13565 case EST_Unevaluated: 13566 case EST_BasicNoexcept: 13567 case EST_DynamicNone: 13568 case EST_MSAny: 13569 case EST_None: 13570 break; 13571 13572 case EST_ComputedNoexcept: 13573 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13574 return true; 13575 13576 case EST_Dynamic: 13577 for (const auto &E : Proto->exceptions()) { 13578 if (!Finder.TraverseType(E)) 13579 return true; 13580 } 13581 break; 13582 } 13583 13584 return false; 13585 } 13586 13587 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13588 FindCXXThisExpr Finder(*this); 13589 13590 // Check attributes. 13591 for (const auto *A : Method->attrs()) { 13592 // FIXME: This should be emitted by tblgen. 13593 Expr *Arg = nullptr; 13594 ArrayRef<Expr *> Args; 13595 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13596 Arg = G->getArg(); 13597 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13598 Arg = G->getArg(); 13599 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13600 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13601 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13602 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13603 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13604 Arg = ETLF->getSuccessValue(); 13605 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13606 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13607 Arg = STLF->getSuccessValue(); 13608 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13609 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13610 Arg = LR->getArg(); 13611 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13612 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13613 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13614 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13615 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13616 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13617 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13618 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13619 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13620 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13621 13622 if (Arg && !Finder.TraverseStmt(Arg)) 13623 return true; 13624 13625 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13626 if (!Finder.TraverseStmt(Args[I])) 13627 return true; 13628 } 13629 } 13630 13631 return false; 13632 } 13633 13634 void Sema::checkExceptionSpecification( 13635 bool IsTopLevel, ExceptionSpecificationType EST, 13636 ArrayRef<ParsedType> DynamicExceptions, 13637 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13638 SmallVectorImpl<QualType> &Exceptions, 13639 FunctionProtoType::ExceptionSpecInfo &ESI) { 13640 Exceptions.clear(); 13641 ESI.Type = EST; 13642 if (EST == EST_Dynamic) { 13643 Exceptions.reserve(DynamicExceptions.size()); 13644 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13645 // FIXME: Preserve type source info. 13646 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13647 13648 if (IsTopLevel) { 13649 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13650 collectUnexpandedParameterPacks(ET, Unexpanded); 13651 if (!Unexpanded.empty()) { 13652 DiagnoseUnexpandedParameterPacks( 13653 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13654 Unexpanded); 13655 continue; 13656 } 13657 } 13658 13659 // Check that the type is valid for an exception spec, and 13660 // drop it if not. 13661 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13662 Exceptions.push_back(ET); 13663 } 13664 ESI.Exceptions = Exceptions; 13665 return; 13666 } 13667 13668 if (EST == EST_ComputedNoexcept) { 13669 // If an error occurred, there's no expression here. 13670 if (NoexceptExpr) { 13671 assert((NoexceptExpr->isTypeDependent() || 13672 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13673 Context.BoolTy) && 13674 "Parser should have made sure that the expression is boolean"); 13675 if (IsTopLevel && NoexceptExpr && 13676 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13677 ESI.Type = EST_BasicNoexcept; 13678 return; 13679 } 13680 13681 if (!NoexceptExpr->isValueDependent()) 13682 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13683 diag::err_noexcept_needs_constant_expression, 13684 /*AllowFold*/ false).get(); 13685 ESI.NoexceptExpr = NoexceptExpr; 13686 } 13687 return; 13688 } 13689 } 13690 13691 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13692 ExceptionSpecificationType EST, 13693 SourceRange SpecificationRange, 13694 ArrayRef<ParsedType> DynamicExceptions, 13695 ArrayRef<SourceRange> DynamicExceptionRanges, 13696 Expr *NoexceptExpr) { 13697 if (!MethodD) 13698 return; 13699 13700 // Dig out the method we're referring to. 13701 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13702 MethodD = FunTmpl->getTemplatedDecl(); 13703 13704 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13705 if (!Method) 13706 return; 13707 13708 // Check the exception specification. 13709 llvm::SmallVector<QualType, 4> Exceptions; 13710 FunctionProtoType::ExceptionSpecInfo ESI; 13711 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13712 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13713 ESI); 13714 13715 // Update the exception specification on the function type. 13716 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13717 13718 if (Method->isStatic()) 13719 checkThisInStaticMemberFunctionExceptionSpec(Method); 13720 13721 if (Method->isVirtual()) { 13722 // Check overrides, which we previously had to delay. 13723 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13724 OEnd = Method->end_overridden_methods(); 13725 O != OEnd; ++O) 13726 CheckOverridingFunctionExceptionSpec(Method, *O); 13727 } 13728 } 13729 13730 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13731 /// 13732 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13733 SourceLocation DeclStart, 13734 Declarator &D, Expr *BitWidth, 13735 InClassInitStyle InitStyle, 13736 AccessSpecifier AS, 13737 AttributeList *MSPropertyAttr) { 13738 IdentifierInfo *II = D.getIdentifier(); 13739 if (!II) { 13740 Diag(DeclStart, diag::err_anonymous_property); 13741 return nullptr; 13742 } 13743 SourceLocation Loc = D.getIdentifierLoc(); 13744 13745 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13746 QualType T = TInfo->getType(); 13747 if (getLangOpts().CPlusPlus) { 13748 CheckExtraCXXDefaultArguments(D); 13749 13750 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13751 UPPC_DataMemberType)) { 13752 D.setInvalidType(); 13753 T = Context.IntTy; 13754 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13755 } 13756 } 13757 13758 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13759 13760 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13761 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13762 diag::err_invalid_thread) 13763 << DeclSpec::getSpecifierName(TSCS); 13764 13765 // Check to see if this name was declared as a member previously 13766 NamedDecl *PrevDecl = nullptr; 13767 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13768 LookupName(Previous, S); 13769 switch (Previous.getResultKind()) { 13770 case LookupResult::Found: 13771 case LookupResult::FoundUnresolvedValue: 13772 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13773 break; 13774 13775 case LookupResult::FoundOverloaded: 13776 PrevDecl = Previous.getRepresentativeDecl(); 13777 break; 13778 13779 case LookupResult::NotFound: 13780 case LookupResult::NotFoundInCurrentInstantiation: 13781 case LookupResult::Ambiguous: 13782 break; 13783 } 13784 13785 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13786 // Maybe we will complain about the shadowed template parameter. 13787 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13788 // Just pretend that we didn't see the previous declaration. 13789 PrevDecl = nullptr; 13790 } 13791 13792 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13793 PrevDecl = nullptr; 13794 13795 SourceLocation TSSL = D.getLocStart(); 13796 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13797 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13798 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13799 ProcessDeclAttributes(TUScope, NewPD, D); 13800 NewPD->setAccess(AS); 13801 13802 if (NewPD->isInvalidDecl()) 13803 Record->setInvalidDecl(); 13804 13805 if (D.getDeclSpec().isModulePrivateSpecified()) 13806 NewPD->setModulePrivate(); 13807 13808 if (NewPD->isInvalidDecl() && PrevDecl) { 13809 // Don't introduce NewFD into scope; there's already something 13810 // with the same name in the same scope. 13811 } else if (II) { 13812 PushOnScopeChains(NewPD, S); 13813 } else 13814 Record->addDecl(NewPD); 13815 13816 return NewPD; 13817 } 13818