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 PP.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 7211 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 7212 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 7213 Decl::IDNS_Namespace; 7214 NamedDecl *PrevDecl = nullptr; 7215 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 7216 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 7217 ++I) { 7218 if ((*I)->getIdentifierNamespace() & IDNS) { 7219 PrevDecl = *I; 7220 break; 7221 } 7222 } 7223 7224 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7225 7226 if (PrevNS) { 7227 // This is an extended namespace definition. 7228 if (IsInline != PrevNS->isInline()) 7229 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7230 &IsInline, PrevNS); 7231 } else if (PrevDecl) { 7232 // This is an invalid name redefinition. 7233 Diag(Loc, diag::err_redefinition_different_kind) 7234 << II; 7235 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7236 IsInvalid = true; 7237 // Continue on to push Namespc as current DeclContext and return it. 7238 } else if (II->isStr("std") && 7239 CurContext->getRedeclContext()->isTranslationUnit()) { 7240 // This is the first "real" definition of the namespace "std", so update 7241 // our cache of the "std" namespace to point at this definition. 7242 PrevNS = getStdNamespace(); 7243 IsStd = true; 7244 AddToKnown = !IsInline; 7245 } else { 7246 // We've seen this namespace for the first time. 7247 AddToKnown = !IsInline; 7248 } 7249 } else { 7250 // Anonymous namespaces. 7251 7252 // Determine whether the parent already has an anonymous namespace. 7253 DeclContext *Parent = CurContext->getRedeclContext(); 7254 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7255 PrevNS = TU->getAnonymousNamespace(); 7256 } else { 7257 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7258 PrevNS = ND->getAnonymousNamespace(); 7259 } 7260 7261 if (PrevNS && IsInline != PrevNS->isInline()) 7262 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7263 &IsInline, PrevNS); 7264 } 7265 7266 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7267 StartLoc, Loc, II, PrevNS); 7268 if (IsInvalid) 7269 Namespc->setInvalidDecl(); 7270 7271 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7272 7273 // FIXME: Should we be merging attributes? 7274 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7275 PushNamespaceVisibilityAttr(Attr, Loc); 7276 7277 if (IsStd) 7278 StdNamespace = Namespc; 7279 if (AddToKnown) 7280 KnownNamespaces[Namespc] = false; 7281 7282 if (II) { 7283 PushOnScopeChains(Namespc, DeclRegionScope); 7284 } else { 7285 // Link the anonymous namespace into its parent. 7286 DeclContext *Parent = CurContext->getRedeclContext(); 7287 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7288 TU->setAnonymousNamespace(Namespc); 7289 } else { 7290 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7291 } 7292 7293 CurContext->addDecl(Namespc); 7294 7295 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7296 // behaves as if it were replaced by 7297 // namespace unique { /* empty body */ } 7298 // using namespace unique; 7299 // namespace unique { namespace-body } 7300 // where all occurrences of 'unique' in a translation unit are 7301 // replaced by the same identifier and this identifier differs 7302 // from all other identifiers in the entire program. 7303 7304 // We just create the namespace with an empty name and then add an 7305 // implicit using declaration, just like the standard suggests. 7306 // 7307 // CodeGen enforces the "universally unique" aspect by giving all 7308 // declarations semantically contained within an anonymous 7309 // namespace internal linkage. 7310 7311 if (!PrevNS) { 7312 UsingDirectiveDecl* UD 7313 = UsingDirectiveDecl::Create(Context, Parent, 7314 /* 'using' */ LBrace, 7315 /* 'namespace' */ SourceLocation(), 7316 /* qualifier */ NestedNameSpecifierLoc(), 7317 /* identifier */ SourceLocation(), 7318 Namespc, 7319 /* Ancestor */ Parent); 7320 UD->setImplicit(); 7321 Parent->addDecl(UD); 7322 } 7323 } 7324 7325 ActOnDocumentableDecl(Namespc); 7326 7327 // Although we could have an invalid decl (i.e. the namespace name is a 7328 // redefinition), push it as current DeclContext and try to continue parsing. 7329 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7330 // for the namespace has the declarations that showed up in that particular 7331 // namespace definition. 7332 PushDeclContext(NamespcScope, Namespc); 7333 return Namespc; 7334 } 7335 7336 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7337 /// is a namespace alias, returns the namespace it points to. 7338 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7339 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7340 return AD->getNamespace(); 7341 return dyn_cast_or_null<NamespaceDecl>(D); 7342 } 7343 7344 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7345 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7346 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7347 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7348 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7349 Namespc->setRBraceLoc(RBrace); 7350 PopDeclContext(); 7351 if (Namespc->hasAttr<VisibilityAttr>()) 7352 PopPragmaVisibility(true, RBrace); 7353 } 7354 7355 CXXRecordDecl *Sema::getStdBadAlloc() const { 7356 return cast_or_null<CXXRecordDecl>( 7357 StdBadAlloc.get(Context.getExternalSource())); 7358 } 7359 7360 NamespaceDecl *Sema::getStdNamespace() const { 7361 return cast_or_null<NamespaceDecl>( 7362 StdNamespace.get(Context.getExternalSource())); 7363 } 7364 7365 /// \brief Retrieve the special "std" namespace, which may require us to 7366 /// implicitly define the namespace. 7367 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7368 if (!StdNamespace) { 7369 // The "std" namespace has not yet been defined, so build one implicitly. 7370 StdNamespace = NamespaceDecl::Create(Context, 7371 Context.getTranslationUnitDecl(), 7372 /*Inline=*/false, 7373 SourceLocation(), SourceLocation(), 7374 &PP.getIdentifierTable().get("std"), 7375 /*PrevDecl=*/nullptr); 7376 getStdNamespace()->setImplicit(true); 7377 } 7378 7379 return getStdNamespace(); 7380 } 7381 7382 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7383 assert(getLangOpts().CPlusPlus && 7384 "Looking for std::initializer_list outside of C++."); 7385 7386 // We're looking for implicit instantiations of 7387 // template <typename E> class std::initializer_list. 7388 7389 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7390 return false; 7391 7392 ClassTemplateDecl *Template = nullptr; 7393 const TemplateArgument *Arguments = nullptr; 7394 7395 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7396 7397 ClassTemplateSpecializationDecl *Specialization = 7398 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7399 if (!Specialization) 7400 return false; 7401 7402 Template = Specialization->getSpecializedTemplate(); 7403 Arguments = Specialization->getTemplateArgs().data(); 7404 } else if (const TemplateSpecializationType *TST = 7405 Ty->getAs<TemplateSpecializationType>()) { 7406 Template = dyn_cast_or_null<ClassTemplateDecl>( 7407 TST->getTemplateName().getAsTemplateDecl()); 7408 Arguments = TST->getArgs(); 7409 } 7410 if (!Template) 7411 return false; 7412 7413 if (!StdInitializerList) { 7414 // Haven't recognized std::initializer_list yet, maybe this is it. 7415 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7416 if (TemplateClass->getIdentifier() != 7417 &PP.getIdentifierTable().get("initializer_list") || 7418 !getStdNamespace()->InEnclosingNamespaceSetOf( 7419 TemplateClass->getDeclContext())) 7420 return false; 7421 // This is a template called std::initializer_list, but is it the right 7422 // template? 7423 TemplateParameterList *Params = Template->getTemplateParameters(); 7424 if (Params->getMinRequiredArguments() != 1) 7425 return false; 7426 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7427 return false; 7428 7429 // It's the right template. 7430 StdInitializerList = Template; 7431 } 7432 7433 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 7434 return false; 7435 7436 // This is an instance of std::initializer_list. Find the argument type. 7437 if (Element) 7438 *Element = Arguments[0].getAsType(); 7439 return true; 7440 } 7441 7442 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7443 NamespaceDecl *Std = S.getStdNamespace(); 7444 if (!Std) { 7445 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7446 return nullptr; 7447 } 7448 7449 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7450 Loc, Sema::LookupOrdinaryName); 7451 if (!S.LookupQualifiedName(Result, Std)) { 7452 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7453 return nullptr; 7454 } 7455 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7456 if (!Template) { 7457 Result.suppressDiagnostics(); 7458 // We found something weird. Complain about the first thing we found. 7459 NamedDecl *Found = *Result.begin(); 7460 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7461 return nullptr; 7462 } 7463 7464 // We found some template called std::initializer_list. Now verify that it's 7465 // correct. 7466 TemplateParameterList *Params = Template->getTemplateParameters(); 7467 if (Params->getMinRequiredArguments() != 1 || 7468 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7469 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7470 return nullptr; 7471 } 7472 7473 return Template; 7474 } 7475 7476 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7477 if (!StdInitializerList) { 7478 StdInitializerList = LookupStdInitializerList(*this, Loc); 7479 if (!StdInitializerList) 7480 return QualType(); 7481 } 7482 7483 TemplateArgumentListInfo Args(Loc, Loc); 7484 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7485 Context.getTrivialTypeSourceInfo(Element, 7486 Loc))); 7487 return Context.getCanonicalType( 7488 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7489 } 7490 7491 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7492 // C++ [dcl.init.list]p2: 7493 // A constructor is an initializer-list constructor if its first parameter 7494 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7495 // std::initializer_list<E> for some type E, and either there are no other 7496 // parameters or else all other parameters have default arguments. 7497 if (Ctor->getNumParams() < 1 || 7498 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7499 return false; 7500 7501 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7502 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7503 ArgType = RT->getPointeeType().getUnqualifiedType(); 7504 7505 return isStdInitializerList(ArgType, nullptr); 7506 } 7507 7508 /// \brief Determine whether a using statement is in a context where it will be 7509 /// apply in all contexts. 7510 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7511 switch (CurContext->getDeclKind()) { 7512 case Decl::TranslationUnit: 7513 return true; 7514 case Decl::LinkageSpec: 7515 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7516 default: 7517 return false; 7518 } 7519 } 7520 7521 namespace { 7522 7523 // Callback to only accept typo corrections that are namespaces. 7524 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7525 public: 7526 bool ValidateCandidate(const TypoCorrection &candidate) override { 7527 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7528 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7529 return false; 7530 } 7531 }; 7532 7533 } 7534 7535 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7536 CXXScopeSpec &SS, 7537 SourceLocation IdentLoc, 7538 IdentifierInfo *Ident) { 7539 R.clear(); 7540 if (TypoCorrection Corrected = 7541 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7542 llvm::make_unique<NamespaceValidatorCCC>(), 7543 Sema::CTK_ErrorRecovery)) { 7544 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7545 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7546 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7547 Ident->getName().equals(CorrectedStr); 7548 S.diagnoseTypo(Corrected, 7549 S.PDiag(diag::err_using_directive_member_suggest) 7550 << Ident << DC << DroppedSpecifier << SS.getRange(), 7551 S.PDiag(diag::note_namespace_defined_here)); 7552 } else { 7553 S.diagnoseTypo(Corrected, 7554 S.PDiag(diag::err_using_directive_suggest) << Ident, 7555 S.PDiag(diag::note_namespace_defined_here)); 7556 } 7557 R.addDecl(Corrected.getCorrectionDecl()); 7558 return true; 7559 } 7560 return false; 7561 } 7562 7563 Decl *Sema::ActOnUsingDirective(Scope *S, 7564 SourceLocation UsingLoc, 7565 SourceLocation NamespcLoc, 7566 CXXScopeSpec &SS, 7567 SourceLocation IdentLoc, 7568 IdentifierInfo *NamespcName, 7569 AttributeList *AttrList) { 7570 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7571 assert(NamespcName && "Invalid NamespcName."); 7572 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7573 7574 // This can only happen along a recovery path. 7575 while (S->getFlags() & Scope::TemplateParamScope) 7576 S = S->getParent(); 7577 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7578 7579 UsingDirectiveDecl *UDir = nullptr; 7580 NestedNameSpecifier *Qualifier = nullptr; 7581 if (SS.isSet()) 7582 Qualifier = SS.getScopeRep(); 7583 7584 // Lookup namespace name. 7585 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7586 LookupParsedName(R, S, &SS); 7587 if (R.isAmbiguous()) 7588 return nullptr; 7589 7590 if (R.empty()) { 7591 R.clear(); 7592 // Allow "using namespace std;" or "using namespace ::std;" even if 7593 // "std" hasn't been defined yet, for GCC compatibility. 7594 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7595 NamespcName->isStr("std")) { 7596 Diag(IdentLoc, diag::ext_using_undefined_std); 7597 R.addDecl(getOrCreateStdNamespace()); 7598 R.resolveKind(); 7599 } 7600 // Otherwise, attempt typo correction. 7601 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7602 } 7603 7604 if (!R.empty()) { 7605 NamedDecl *Named = R.getFoundDecl(); 7606 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7607 && "expected namespace decl"); 7608 7609 // The use of a nested name specifier may trigger deprecation warnings. 7610 DiagnoseUseOfDecl(Named, IdentLoc); 7611 7612 // C++ [namespace.udir]p1: 7613 // A using-directive specifies that the names in the nominated 7614 // namespace can be used in the scope in which the 7615 // using-directive appears after the using-directive. During 7616 // unqualified name lookup (3.4.1), the names appear as if they 7617 // were declared in the nearest enclosing namespace which 7618 // contains both the using-directive and the nominated 7619 // namespace. [Note: in this context, "contains" means "contains 7620 // directly or indirectly". ] 7621 7622 // Find enclosing context containing both using-directive and 7623 // nominated namespace. 7624 NamespaceDecl *NS = getNamespaceDecl(Named); 7625 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7626 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7627 CommonAncestor = CommonAncestor->getParent(); 7628 7629 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7630 SS.getWithLocInContext(Context), 7631 IdentLoc, Named, CommonAncestor); 7632 7633 if (IsUsingDirectiveInToplevelContext(CurContext) && 7634 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7635 Diag(IdentLoc, diag::warn_using_directive_in_header); 7636 } 7637 7638 PushUsingDirective(S, UDir); 7639 } else { 7640 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7641 } 7642 7643 if (UDir) 7644 ProcessDeclAttributeList(S, UDir, AttrList); 7645 7646 return UDir; 7647 } 7648 7649 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7650 // If the scope has an associated entity and the using directive is at 7651 // namespace or translation unit scope, add the UsingDirectiveDecl into 7652 // its lookup structure so qualified name lookup can find it. 7653 DeclContext *Ctx = S->getEntity(); 7654 if (Ctx && !Ctx->isFunctionOrMethod()) 7655 Ctx->addDecl(UDir); 7656 else 7657 // Otherwise, it is at block scope. The using-directives will affect lookup 7658 // only to the end of the scope. 7659 S->PushUsingDirective(UDir); 7660 } 7661 7662 7663 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7664 AccessSpecifier AS, 7665 bool HasUsingKeyword, 7666 SourceLocation UsingLoc, 7667 CXXScopeSpec &SS, 7668 UnqualifiedId &Name, 7669 AttributeList *AttrList, 7670 bool HasTypenameKeyword, 7671 SourceLocation TypenameLoc) { 7672 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7673 7674 switch (Name.getKind()) { 7675 case UnqualifiedId::IK_ImplicitSelfParam: 7676 case UnqualifiedId::IK_Identifier: 7677 case UnqualifiedId::IK_OperatorFunctionId: 7678 case UnqualifiedId::IK_LiteralOperatorId: 7679 case UnqualifiedId::IK_ConversionFunctionId: 7680 break; 7681 7682 case UnqualifiedId::IK_ConstructorName: 7683 case UnqualifiedId::IK_ConstructorTemplateId: 7684 // C++11 inheriting constructors. 7685 Diag(Name.getLocStart(), 7686 getLangOpts().CPlusPlus11 ? 7687 diag::warn_cxx98_compat_using_decl_constructor : 7688 diag::err_using_decl_constructor) 7689 << SS.getRange(); 7690 7691 if (getLangOpts().CPlusPlus11) break; 7692 7693 return nullptr; 7694 7695 case UnqualifiedId::IK_DestructorName: 7696 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7697 << SS.getRange(); 7698 return nullptr; 7699 7700 case UnqualifiedId::IK_TemplateId: 7701 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7702 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7703 return nullptr; 7704 } 7705 7706 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7707 DeclarationName TargetName = TargetNameInfo.getName(); 7708 if (!TargetName) 7709 return nullptr; 7710 7711 // Warn about access declarations. 7712 if (!HasUsingKeyword) { 7713 Diag(Name.getLocStart(), 7714 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7715 : diag::warn_access_decl_deprecated) 7716 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7717 } 7718 7719 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7720 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7721 return nullptr; 7722 7723 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7724 TargetNameInfo, AttrList, 7725 /* IsInstantiation */ false, 7726 HasTypenameKeyword, TypenameLoc); 7727 if (UD) 7728 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7729 7730 return UD; 7731 } 7732 7733 /// \brief Determine whether a using declaration considers the given 7734 /// declarations as "equivalent", e.g., if they are redeclarations of 7735 /// the same entity or are both typedefs of the same type. 7736 static bool 7737 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7738 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7739 return true; 7740 7741 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7742 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7743 return Context.hasSameType(TD1->getUnderlyingType(), 7744 TD2->getUnderlyingType()); 7745 7746 return false; 7747 } 7748 7749 7750 /// Determines whether to create a using shadow decl for a particular 7751 /// decl, given the set of decls existing prior to this using lookup. 7752 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7753 const LookupResult &Previous, 7754 UsingShadowDecl *&PrevShadow) { 7755 // Diagnose finding a decl which is not from a base class of the 7756 // current class. We do this now because there are cases where this 7757 // function will silently decide not to build a shadow decl, which 7758 // will pre-empt further diagnostics. 7759 // 7760 // We don't need to do this in C++0x because we do the check once on 7761 // the qualifier. 7762 // 7763 // FIXME: diagnose the following if we care enough: 7764 // struct A { int foo; }; 7765 // struct B : A { using A::foo; }; 7766 // template <class T> struct C : A {}; 7767 // template <class T> struct D : C<T> { using B::foo; } // <--- 7768 // This is invalid (during instantiation) in C++03 because B::foo 7769 // resolves to the using decl in B, which is not a base class of D<T>. 7770 // We can't diagnose it immediately because C<T> is an unknown 7771 // specialization. The UsingShadowDecl in D<T> then points directly 7772 // to A::foo, which will look well-formed when we instantiate. 7773 // The right solution is to not collapse the shadow-decl chain. 7774 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7775 DeclContext *OrigDC = Orig->getDeclContext(); 7776 7777 // Handle enums and anonymous structs. 7778 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7779 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7780 while (OrigRec->isAnonymousStructOrUnion()) 7781 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7782 7783 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7784 if (OrigDC == CurContext) { 7785 Diag(Using->getLocation(), 7786 diag::err_using_decl_nested_name_specifier_is_current_class) 7787 << Using->getQualifierLoc().getSourceRange(); 7788 Diag(Orig->getLocation(), diag::note_using_decl_target); 7789 return true; 7790 } 7791 7792 Diag(Using->getQualifierLoc().getBeginLoc(), 7793 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7794 << Using->getQualifier() 7795 << cast<CXXRecordDecl>(CurContext) 7796 << Using->getQualifierLoc().getSourceRange(); 7797 Diag(Orig->getLocation(), diag::note_using_decl_target); 7798 return true; 7799 } 7800 } 7801 7802 if (Previous.empty()) return false; 7803 7804 NamedDecl *Target = Orig; 7805 if (isa<UsingShadowDecl>(Target)) 7806 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7807 7808 // If the target happens to be one of the previous declarations, we 7809 // don't have a conflict. 7810 // 7811 // FIXME: but we might be increasing its access, in which case we 7812 // should redeclare it. 7813 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7814 bool FoundEquivalentDecl = false; 7815 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7816 I != E; ++I) { 7817 NamedDecl *D = (*I)->getUnderlyingDecl(); 7818 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7819 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7820 PrevShadow = Shadow; 7821 FoundEquivalentDecl = true; 7822 } 7823 7824 if (isVisible(D)) 7825 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7826 } 7827 7828 if (FoundEquivalentDecl) 7829 return false; 7830 7831 if (FunctionDecl *FD = Target->getAsFunction()) { 7832 NamedDecl *OldDecl = nullptr; 7833 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7834 /*IsForUsingDecl*/ true)) { 7835 case Ovl_Overload: 7836 return false; 7837 7838 case Ovl_NonFunction: 7839 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7840 break; 7841 7842 // We found a decl with the exact signature. 7843 case Ovl_Match: 7844 // If we're in a record, we want to hide the target, so we 7845 // return true (without a diagnostic) to tell the caller not to 7846 // build a shadow decl. 7847 if (CurContext->isRecord()) 7848 return true; 7849 7850 // If we're not in a record, this is an error. 7851 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7852 break; 7853 } 7854 7855 Diag(Target->getLocation(), diag::note_using_decl_target); 7856 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7857 return true; 7858 } 7859 7860 // Target is not a function. 7861 7862 if (isa<TagDecl>(Target)) { 7863 // No conflict between a tag and a non-tag. 7864 if (!Tag) return false; 7865 7866 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7867 Diag(Target->getLocation(), diag::note_using_decl_target); 7868 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7869 return true; 7870 } 7871 7872 // No conflict between a tag and a non-tag. 7873 if (!NonTag) return false; 7874 7875 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7876 Diag(Target->getLocation(), diag::note_using_decl_target); 7877 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7878 return true; 7879 } 7880 7881 /// Builds a shadow declaration corresponding to a 'using' declaration. 7882 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7883 UsingDecl *UD, 7884 NamedDecl *Orig, 7885 UsingShadowDecl *PrevDecl) { 7886 7887 // If we resolved to another shadow declaration, just coalesce them. 7888 NamedDecl *Target = Orig; 7889 if (isa<UsingShadowDecl>(Target)) { 7890 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7891 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7892 } 7893 7894 UsingShadowDecl *Shadow 7895 = UsingShadowDecl::Create(Context, CurContext, 7896 UD->getLocation(), UD, Target); 7897 UD->addShadowDecl(Shadow); 7898 7899 Shadow->setAccess(UD->getAccess()); 7900 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7901 Shadow->setInvalidDecl(); 7902 7903 Shadow->setPreviousDecl(PrevDecl); 7904 7905 if (S) 7906 PushOnScopeChains(Shadow, S); 7907 else 7908 CurContext->addDecl(Shadow); 7909 7910 7911 return Shadow; 7912 } 7913 7914 /// Hides a using shadow declaration. This is required by the current 7915 /// using-decl implementation when a resolvable using declaration in a 7916 /// class is followed by a declaration which would hide or override 7917 /// one or more of the using decl's targets; for example: 7918 /// 7919 /// struct Base { void foo(int); }; 7920 /// struct Derived : Base { 7921 /// using Base::foo; 7922 /// void foo(int); 7923 /// }; 7924 /// 7925 /// The governing language is C++03 [namespace.udecl]p12: 7926 /// 7927 /// When a using-declaration brings names from a base class into a 7928 /// derived class scope, member functions in the derived class 7929 /// override and/or hide member functions with the same name and 7930 /// parameter types in a base class (rather than conflicting). 7931 /// 7932 /// There are two ways to implement this: 7933 /// (1) optimistically create shadow decls when they're not hidden 7934 /// by existing declarations, or 7935 /// (2) don't create any shadow decls (or at least don't make them 7936 /// visible) until we've fully parsed/instantiated the class. 7937 /// The problem with (1) is that we might have to retroactively remove 7938 /// a shadow decl, which requires several O(n) operations because the 7939 /// decl structures are (very reasonably) not designed for removal. 7940 /// (2) avoids this but is very fiddly and phase-dependent. 7941 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7942 if (Shadow->getDeclName().getNameKind() == 7943 DeclarationName::CXXConversionFunctionName) 7944 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7945 7946 // Remove it from the DeclContext... 7947 Shadow->getDeclContext()->removeDecl(Shadow); 7948 7949 // ...and the scope, if applicable... 7950 if (S) { 7951 S->RemoveDecl(Shadow); 7952 IdResolver.RemoveDecl(Shadow); 7953 } 7954 7955 // ...and the using decl. 7956 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7957 7958 // TODO: complain somehow if Shadow was used. It shouldn't 7959 // be possible for this to happen, because...? 7960 } 7961 7962 /// Find the base specifier for a base class with the given type. 7963 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7964 QualType DesiredBase, 7965 bool &AnyDependentBases) { 7966 // Check whether the named type is a direct base class. 7967 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7968 for (auto &Base : Derived->bases()) { 7969 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7970 if (CanonicalDesiredBase == BaseType) 7971 return &Base; 7972 if (BaseType->isDependentType()) 7973 AnyDependentBases = true; 7974 } 7975 return nullptr; 7976 } 7977 7978 namespace { 7979 class UsingValidatorCCC : public CorrectionCandidateCallback { 7980 public: 7981 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7982 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7983 : HasTypenameKeyword(HasTypenameKeyword), 7984 IsInstantiation(IsInstantiation), OldNNS(NNS), 7985 RequireMemberOf(RequireMemberOf) {} 7986 7987 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7988 NamedDecl *ND = Candidate.getCorrectionDecl(); 7989 7990 // Keywords are not valid here. 7991 if (!ND || isa<NamespaceDecl>(ND)) 7992 return false; 7993 7994 // Completely unqualified names are invalid for a 'using' declaration. 7995 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7996 return false; 7997 7998 if (RequireMemberOf) { 7999 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8000 if (FoundRecord && FoundRecord->isInjectedClassName()) { 8001 // No-one ever wants a using-declaration to name an injected-class-name 8002 // of a base class, unless they're declaring an inheriting constructor. 8003 ASTContext &Ctx = ND->getASTContext(); 8004 if (!Ctx.getLangOpts().CPlusPlus11) 8005 return false; 8006 QualType FoundType = Ctx.getRecordType(FoundRecord); 8007 8008 // Check that the injected-class-name is named as a member of its own 8009 // type; we don't want to suggest 'using Derived::Base;', since that 8010 // means something else. 8011 NestedNameSpecifier *Specifier = 8012 Candidate.WillReplaceSpecifier() 8013 ? Candidate.getCorrectionSpecifier() 8014 : OldNNS; 8015 if (!Specifier->getAsType() || 8016 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 8017 return false; 8018 8019 // Check that this inheriting constructor declaration actually names a 8020 // direct base class of the current class. 8021 bool AnyDependentBases = false; 8022 if (!findDirectBaseWithType(RequireMemberOf, 8023 Ctx.getRecordType(FoundRecord), 8024 AnyDependentBases) && 8025 !AnyDependentBases) 8026 return false; 8027 } else { 8028 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 8029 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 8030 return false; 8031 8032 // FIXME: Check that the base class member is accessible? 8033 } 8034 } else { 8035 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8036 if (FoundRecord && FoundRecord->isInjectedClassName()) 8037 return false; 8038 } 8039 8040 if (isa<TypeDecl>(ND)) 8041 return HasTypenameKeyword || !IsInstantiation; 8042 8043 return !HasTypenameKeyword; 8044 } 8045 8046 private: 8047 bool HasTypenameKeyword; 8048 bool IsInstantiation; 8049 NestedNameSpecifier *OldNNS; 8050 CXXRecordDecl *RequireMemberOf; 8051 }; 8052 } // end anonymous namespace 8053 8054 /// Builds a using declaration. 8055 /// 8056 /// \param IsInstantiation - Whether this call arises from an 8057 /// instantiation of an unresolved using declaration. We treat 8058 /// the lookup differently for these declarations. 8059 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 8060 SourceLocation UsingLoc, 8061 CXXScopeSpec &SS, 8062 DeclarationNameInfo NameInfo, 8063 AttributeList *AttrList, 8064 bool IsInstantiation, 8065 bool HasTypenameKeyword, 8066 SourceLocation TypenameLoc) { 8067 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8068 SourceLocation IdentLoc = NameInfo.getLoc(); 8069 assert(IdentLoc.isValid() && "Invalid TargetName location."); 8070 8071 // FIXME: We ignore attributes for now. 8072 8073 if (SS.isEmpty()) { 8074 Diag(IdentLoc, diag::err_using_requires_qualname); 8075 return nullptr; 8076 } 8077 8078 // Do the redeclaration lookup in the current scope. 8079 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 8080 ForRedeclaration); 8081 Previous.setHideTags(false); 8082 if (S) { 8083 LookupName(Previous, S); 8084 8085 // It is really dumb that we have to do this. 8086 LookupResult::Filter F = Previous.makeFilter(); 8087 while (F.hasNext()) { 8088 NamedDecl *D = F.next(); 8089 if (!isDeclInScope(D, CurContext, S)) 8090 F.erase(); 8091 // If we found a local extern declaration that's not ordinarily visible, 8092 // and this declaration is being added to a non-block scope, ignore it. 8093 // We're only checking for scope conflicts here, not also for violations 8094 // of the linkage rules. 8095 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 8096 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 8097 F.erase(); 8098 } 8099 F.done(); 8100 } else { 8101 assert(IsInstantiation && "no scope in non-instantiation"); 8102 assert(CurContext->isRecord() && "scope not record in instantiation"); 8103 LookupQualifiedName(Previous, CurContext); 8104 } 8105 8106 // Check for invalid redeclarations. 8107 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 8108 SS, IdentLoc, Previous)) 8109 return nullptr; 8110 8111 // Check for bad qualifiers. 8112 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 8113 return nullptr; 8114 8115 DeclContext *LookupContext = computeDeclContext(SS); 8116 NamedDecl *D; 8117 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 8118 if (!LookupContext) { 8119 if (HasTypenameKeyword) { 8120 // FIXME: not all declaration name kinds are legal here 8121 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 8122 UsingLoc, TypenameLoc, 8123 QualifierLoc, 8124 IdentLoc, NameInfo.getName()); 8125 } else { 8126 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 8127 QualifierLoc, NameInfo); 8128 } 8129 D->setAccess(AS); 8130 CurContext->addDecl(D); 8131 return D; 8132 } 8133 8134 auto Build = [&](bool Invalid) { 8135 UsingDecl *UD = 8136 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 8137 HasTypenameKeyword); 8138 UD->setAccess(AS); 8139 CurContext->addDecl(UD); 8140 UD->setInvalidDecl(Invalid); 8141 return UD; 8142 }; 8143 auto BuildInvalid = [&]{ return Build(true); }; 8144 auto BuildValid = [&]{ return Build(false); }; 8145 8146 if (RequireCompleteDeclContext(SS, LookupContext)) 8147 return BuildInvalid(); 8148 8149 // Look up the target name. 8150 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8151 8152 // Unlike most lookups, we don't always want to hide tag 8153 // declarations: tag names are visible through the using declaration 8154 // even if hidden by ordinary names, *except* in a dependent context 8155 // where it's important for the sanity of two-phase lookup. 8156 if (!IsInstantiation) 8157 R.setHideTags(false); 8158 8159 // For the purposes of this lookup, we have a base object type 8160 // equal to that of the current context. 8161 if (CurContext->isRecord()) { 8162 R.setBaseObjectType( 8163 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 8164 } 8165 8166 LookupQualifiedName(R, LookupContext); 8167 8168 // Try to correct typos if possible. If constructor name lookup finds no 8169 // results, that means the named class has no explicit constructors, and we 8170 // suppressed declaring implicit ones (probably because it's dependent or 8171 // invalid). 8172 if (R.empty() && 8173 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 8174 if (TypoCorrection Corrected = CorrectTypo( 8175 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 8176 llvm::make_unique<UsingValidatorCCC>( 8177 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8178 dyn_cast<CXXRecordDecl>(CurContext)), 8179 CTK_ErrorRecovery)) { 8180 // We reject any correction for which ND would be NULL. 8181 NamedDecl *ND = Corrected.getCorrectionDecl(); 8182 8183 // We reject candidates where DroppedSpecifier == true, hence the 8184 // literal '0' below. 8185 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8186 << NameInfo.getName() << LookupContext << 0 8187 << SS.getRange()); 8188 8189 // If we corrected to an inheriting constructor, handle it as one. 8190 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8191 if (RD && RD->isInjectedClassName()) { 8192 // Fix up the information we'll use to build the using declaration. 8193 if (Corrected.WillReplaceSpecifier()) { 8194 NestedNameSpecifierLocBuilder Builder; 8195 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8196 QualifierLoc.getSourceRange()); 8197 QualifierLoc = Builder.getWithLocInContext(Context); 8198 } 8199 8200 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8201 Context.getCanonicalType(Context.getRecordType(RD)))); 8202 NameInfo.setNamedTypeInfo(nullptr); 8203 for (auto *Ctor : LookupConstructors(RD)) 8204 R.addDecl(Ctor); 8205 } else { 8206 // FIXME: Pick up all the declarations if we found an overloaded function. 8207 R.addDecl(ND); 8208 } 8209 } else { 8210 Diag(IdentLoc, diag::err_no_member) 8211 << NameInfo.getName() << LookupContext << SS.getRange(); 8212 return BuildInvalid(); 8213 } 8214 } 8215 8216 if (R.isAmbiguous()) 8217 return BuildInvalid(); 8218 8219 if (HasTypenameKeyword) { 8220 // If we asked for a typename and got a non-type decl, error out. 8221 if (!R.getAsSingle<TypeDecl>()) { 8222 Diag(IdentLoc, diag::err_using_typename_non_type); 8223 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8224 Diag((*I)->getUnderlyingDecl()->getLocation(), 8225 diag::note_using_decl_target); 8226 return BuildInvalid(); 8227 } 8228 } else { 8229 // If we asked for a non-typename and we got a type, error out, 8230 // but only if this is an instantiation of an unresolved using 8231 // decl. Otherwise just silently find the type name. 8232 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8233 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8234 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8235 return BuildInvalid(); 8236 } 8237 } 8238 8239 // C++0x N2914 [namespace.udecl]p6: 8240 // A using-declaration shall not name a namespace. 8241 if (R.getAsSingle<NamespaceDecl>()) { 8242 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8243 << SS.getRange(); 8244 return BuildInvalid(); 8245 } 8246 8247 UsingDecl *UD = BuildValid(); 8248 8249 // The normal rules do not apply to inheriting constructor declarations. 8250 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 8251 // Suppress access diagnostics; the access check is instead performed at the 8252 // point of use for an inheriting constructor. 8253 R.suppressDiagnostics(); 8254 CheckInheritingConstructorUsingDecl(UD); 8255 return UD; 8256 } 8257 8258 // Otherwise, look up the target name. 8259 8260 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8261 UsingShadowDecl *PrevDecl = nullptr; 8262 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8263 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8264 } 8265 8266 return UD; 8267 } 8268 8269 /// Additional checks for a using declaration referring to a constructor name. 8270 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8271 assert(!UD->hasTypename() && "expecting a constructor name"); 8272 8273 const Type *SourceType = UD->getQualifier()->getAsType(); 8274 assert(SourceType && 8275 "Using decl naming constructor doesn't have type in scope spec."); 8276 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8277 8278 // Check whether the named type is a direct base class. 8279 bool AnyDependentBases = false; 8280 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8281 AnyDependentBases); 8282 if (!Base && !AnyDependentBases) { 8283 Diag(UD->getUsingLoc(), 8284 diag::err_using_decl_constructor_not_in_direct_base) 8285 << UD->getNameInfo().getSourceRange() 8286 << QualType(SourceType, 0) << TargetClass; 8287 UD->setInvalidDecl(); 8288 return true; 8289 } 8290 8291 if (Base) 8292 Base->setInheritConstructors(); 8293 8294 return false; 8295 } 8296 8297 /// Checks that the given using declaration is not an invalid 8298 /// redeclaration. Note that this is checking only for the using decl 8299 /// itself, not for any ill-formedness among the UsingShadowDecls. 8300 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8301 bool HasTypenameKeyword, 8302 const CXXScopeSpec &SS, 8303 SourceLocation NameLoc, 8304 const LookupResult &Prev) { 8305 // C++03 [namespace.udecl]p8: 8306 // C++0x [namespace.udecl]p10: 8307 // A using-declaration is a declaration and can therefore be used 8308 // repeatedly where (and only where) multiple declarations are 8309 // allowed. 8310 // 8311 // That's in non-member contexts. 8312 if (!CurContext->getRedeclContext()->isRecord()) 8313 return false; 8314 8315 NestedNameSpecifier *Qual = SS.getScopeRep(); 8316 8317 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8318 NamedDecl *D = *I; 8319 8320 bool DTypename; 8321 NestedNameSpecifier *DQual; 8322 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8323 DTypename = UD->hasTypename(); 8324 DQual = UD->getQualifier(); 8325 } else if (UnresolvedUsingValueDecl *UD 8326 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8327 DTypename = false; 8328 DQual = UD->getQualifier(); 8329 } else if (UnresolvedUsingTypenameDecl *UD 8330 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8331 DTypename = true; 8332 DQual = UD->getQualifier(); 8333 } else continue; 8334 8335 // using decls differ if one says 'typename' and the other doesn't. 8336 // FIXME: non-dependent using decls? 8337 if (HasTypenameKeyword != DTypename) continue; 8338 8339 // using decls differ if they name different scopes (but note that 8340 // template instantiation can cause this check to trigger when it 8341 // didn't before instantiation). 8342 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8343 Context.getCanonicalNestedNameSpecifier(DQual)) 8344 continue; 8345 8346 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8347 Diag(D->getLocation(), diag::note_using_decl) << 1; 8348 return true; 8349 } 8350 8351 return false; 8352 } 8353 8354 8355 /// Checks that the given nested-name qualifier used in a using decl 8356 /// in the current context is appropriately related to the current 8357 /// scope. If an error is found, diagnoses it and returns true. 8358 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8359 const CXXScopeSpec &SS, 8360 const DeclarationNameInfo &NameInfo, 8361 SourceLocation NameLoc) { 8362 DeclContext *NamedContext = computeDeclContext(SS); 8363 8364 if (!CurContext->isRecord()) { 8365 // C++03 [namespace.udecl]p3: 8366 // C++0x [namespace.udecl]p8: 8367 // A using-declaration for a class member shall be a member-declaration. 8368 8369 // If we weren't able to compute a valid scope, it must be a 8370 // dependent class scope. 8371 if (!NamedContext || NamedContext->isRecord()) { 8372 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext); 8373 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8374 RD = nullptr; 8375 8376 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8377 << SS.getRange(); 8378 8379 // If we have a complete, non-dependent source type, try to suggest a 8380 // way to get the same effect. 8381 if (!RD) 8382 return true; 8383 8384 // Find what this using-declaration was referring to. 8385 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8386 R.setHideTags(false); 8387 R.suppressDiagnostics(); 8388 LookupQualifiedName(R, RD); 8389 8390 if (R.getAsSingle<TypeDecl>()) { 8391 if (getLangOpts().CPlusPlus11) { 8392 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8393 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8394 << 0 // alias declaration 8395 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8396 NameInfo.getName().getAsString() + 8397 " = "); 8398 } else { 8399 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8400 SourceLocation InsertLoc = 8401 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8402 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8403 << 1 // typedef declaration 8404 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8405 << FixItHint::CreateInsertion( 8406 InsertLoc, " " + NameInfo.getName().getAsString()); 8407 } 8408 } else if (R.getAsSingle<VarDecl>()) { 8409 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8410 // repeating the type of the static data member here. 8411 FixItHint FixIt; 8412 if (getLangOpts().CPlusPlus11) { 8413 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8414 FixIt = FixItHint::CreateReplacement( 8415 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8416 } 8417 8418 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8419 << 2 // reference declaration 8420 << FixIt; 8421 } 8422 return true; 8423 } 8424 8425 // Otherwise, everything is known to be fine. 8426 return false; 8427 } 8428 8429 // The current scope is a record. 8430 8431 // If the named context is dependent, we can't decide much. 8432 if (!NamedContext) { 8433 // FIXME: in C++0x, we can diagnose if we can prove that the 8434 // nested-name-specifier does not refer to a base class, which is 8435 // still possible in some cases. 8436 8437 // Otherwise we have to conservatively report that things might be 8438 // okay. 8439 return false; 8440 } 8441 8442 if (!NamedContext->isRecord()) { 8443 // Ideally this would point at the last name in the specifier, 8444 // but we don't have that level of source info. 8445 Diag(SS.getRange().getBegin(), 8446 diag::err_using_decl_nested_name_specifier_is_not_class) 8447 << SS.getScopeRep() << SS.getRange(); 8448 return true; 8449 } 8450 8451 if (!NamedContext->isDependentContext() && 8452 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8453 return true; 8454 8455 if (getLangOpts().CPlusPlus11) { 8456 // C++0x [namespace.udecl]p3: 8457 // In a using-declaration used as a member-declaration, the 8458 // nested-name-specifier shall name a base class of the class 8459 // being defined. 8460 8461 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8462 cast<CXXRecordDecl>(NamedContext))) { 8463 if (CurContext == NamedContext) { 8464 Diag(NameLoc, 8465 diag::err_using_decl_nested_name_specifier_is_current_class) 8466 << SS.getRange(); 8467 return true; 8468 } 8469 8470 Diag(SS.getRange().getBegin(), 8471 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8472 << SS.getScopeRep() 8473 << cast<CXXRecordDecl>(CurContext) 8474 << SS.getRange(); 8475 return true; 8476 } 8477 8478 return false; 8479 } 8480 8481 // C++03 [namespace.udecl]p4: 8482 // A using-declaration used as a member-declaration shall refer 8483 // to a member of a base class of the class being defined [etc.]. 8484 8485 // Salient point: SS doesn't have to name a base class as long as 8486 // lookup only finds members from base classes. Therefore we can 8487 // diagnose here only if we can prove that that can't happen, 8488 // i.e. if the class hierarchies provably don't intersect. 8489 8490 // TODO: it would be nice if "definitely valid" results were cached 8491 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8492 // need to be repeated. 8493 8494 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 8495 auto Collect = [&Bases](const CXXRecordDecl *Base) { 8496 Bases.insert(Base); 8497 return true; 8498 }; 8499 8500 // Collect all bases. Return false if we find a dependent base. 8501 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 8502 return false; 8503 8504 // Returns true if the base is dependent or is one of the accumulated base 8505 // classes. 8506 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 8507 return !Bases.count(Base); 8508 }; 8509 8510 // Return false if the class has a dependent base or if it or one 8511 // of its bases is present in the base set of the current context. 8512 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 8513 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 8514 return false; 8515 8516 Diag(SS.getRange().getBegin(), 8517 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8518 << SS.getScopeRep() 8519 << cast<CXXRecordDecl>(CurContext) 8520 << SS.getRange(); 8521 8522 return true; 8523 } 8524 8525 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8526 AccessSpecifier AS, 8527 MultiTemplateParamsArg TemplateParamLists, 8528 SourceLocation UsingLoc, 8529 UnqualifiedId &Name, 8530 AttributeList *AttrList, 8531 TypeResult Type, 8532 Decl *DeclFromDeclSpec) { 8533 // Skip up to the relevant declaration scope. 8534 while (S->getFlags() & Scope::TemplateParamScope) 8535 S = S->getParent(); 8536 assert((S->getFlags() & Scope::DeclScope) && 8537 "got alias-declaration outside of declaration scope"); 8538 8539 if (Type.isInvalid()) 8540 return nullptr; 8541 8542 bool Invalid = false; 8543 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8544 TypeSourceInfo *TInfo = nullptr; 8545 GetTypeFromParser(Type.get(), &TInfo); 8546 8547 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8548 return nullptr; 8549 8550 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8551 UPPC_DeclarationType)) { 8552 Invalid = true; 8553 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8554 TInfo->getTypeLoc().getBeginLoc()); 8555 } 8556 8557 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8558 LookupName(Previous, S); 8559 8560 // Warn about shadowing the name of a template parameter. 8561 if (Previous.isSingleResult() && 8562 Previous.getFoundDecl()->isTemplateParameter()) { 8563 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8564 Previous.clear(); 8565 } 8566 8567 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8568 "name in alias declaration must be an identifier"); 8569 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8570 Name.StartLocation, 8571 Name.Identifier, TInfo); 8572 8573 NewTD->setAccess(AS); 8574 8575 if (Invalid) 8576 NewTD->setInvalidDecl(); 8577 8578 ProcessDeclAttributeList(S, NewTD, AttrList); 8579 8580 CheckTypedefForVariablyModifiedType(S, NewTD); 8581 Invalid |= NewTD->isInvalidDecl(); 8582 8583 bool Redeclaration = false; 8584 8585 NamedDecl *NewND; 8586 if (TemplateParamLists.size()) { 8587 TypeAliasTemplateDecl *OldDecl = nullptr; 8588 TemplateParameterList *OldTemplateParams = nullptr; 8589 8590 if (TemplateParamLists.size() != 1) { 8591 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8592 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8593 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8594 } 8595 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8596 8597 // Only consider previous declarations in the same scope. 8598 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8599 /*ExplicitInstantiationOrSpecialization*/false); 8600 if (!Previous.empty()) { 8601 Redeclaration = true; 8602 8603 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8604 if (!OldDecl && !Invalid) { 8605 Diag(UsingLoc, diag::err_redefinition_different_kind) 8606 << Name.Identifier; 8607 8608 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8609 if (OldD->getLocation().isValid()) 8610 Diag(OldD->getLocation(), diag::note_previous_definition); 8611 8612 Invalid = true; 8613 } 8614 8615 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8616 if (TemplateParameterListsAreEqual(TemplateParams, 8617 OldDecl->getTemplateParameters(), 8618 /*Complain=*/true, 8619 TPL_TemplateMatch)) 8620 OldTemplateParams = OldDecl->getTemplateParameters(); 8621 else 8622 Invalid = true; 8623 8624 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8625 if (!Invalid && 8626 !Context.hasSameType(OldTD->getUnderlyingType(), 8627 NewTD->getUnderlyingType())) { 8628 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8629 // but we can't reasonably accept it. 8630 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8631 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8632 if (OldTD->getLocation().isValid()) 8633 Diag(OldTD->getLocation(), diag::note_previous_definition); 8634 Invalid = true; 8635 } 8636 } 8637 } 8638 8639 // Merge any previous default template arguments into our parameters, 8640 // and check the parameter list. 8641 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8642 TPC_TypeAliasTemplate)) 8643 return nullptr; 8644 8645 TypeAliasTemplateDecl *NewDecl = 8646 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8647 Name.Identifier, TemplateParams, 8648 NewTD); 8649 NewTD->setDescribedAliasTemplate(NewDecl); 8650 8651 NewDecl->setAccess(AS); 8652 8653 if (Invalid) 8654 NewDecl->setInvalidDecl(); 8655 else if (OldDecl) 8656 NewDecl->setPreviousDecl(OldDecl); 8657 8658 NewND = NewDecl; 8659 } else { 8660 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 8661 setTagNameForLinkagePurposes(TD, NewTD); 8662 handleTagNumbering(TD, S); 8663 } 8664 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8665 NewND = NewTD; 8666 } 8667 8668 if (!Redeclaration) 8669 PushOnScopeChains(NewND, S); 8670 8671 ActOnDocumentableDecl(NewND); 8672 return NewND; 8673 } 8674 8675 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8676 SourceLocation AliasLoc, 8677 IdentifierInfo *Alias, CXXScopeSpec &SS, 8678 SourceLocation IdentLoc, 8679 IdentifierInfo *Ident) { 8680 8681 // Lookup the namespace name. 8682 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8683 LookupParsedName(R, S, &SS); 8684 8685 if (R.isAmbiguous()) 8686 return nullptr; 8687 8688 if (R.empty()) { 8689 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8690 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8691 return nullptr; 8692 } 8693 } 8694 assert(!R.isAmbiguous() && !R.empty()); 8695 8696 // Check if we have a previous declaration with the same name. 8697 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8698 ForRedeclaration); 8699 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8700 PrevDecl = nullptr; 8701 8702 NamedDecl *ND = R.getFoundDecl(); 8703 8704 if (PrevDecl) { 8705 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8706 // We already have an alias with the same name that points to the same 8707 // namespace; check that it matches. 8708 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8709 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8710 << Alias; 8711 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8712 << AD->getNamespace(); 8713 return nullptr; 8714 } 8715 } else { 8716 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8717 ? diag::err_redefinition 8718 : diag::err_redefinition_different_kind; 8719 Diag(AliasLoc, DiagID) << Alias; 8720 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8721 return nullptr; 8722 } 8723 } 8724 8725 // The use of a nested name specifier may trigger deprecation warnings. 8726 DiagnoseUseOfDecl(ND, IdentLoc); 8727 8728 NamespaceAliasDecl *AliasDecl = 8729 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8730 Alias, SS.getWithLocInContext(Context), 8731 IdentLoc, ND); 8732 if (PrevDecl) 8733 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8734 8735 PushOnScopeChains(AliasDecl, S); 8736 return AliasDecl; 8737 } 8738 8739 Sema::ImplicitExceptionSpecification 8740 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8741 CXXMethodDecl *MD) { 8742 CXXRecordDecl *ClassDecl = MD->getParent(); 8743 8744 // C++ [except.spec]p14: 8745 // An implicitly declared special member function (Clause 12) shall have an 8746 // exception-specification. [...] 8747 ImplicitExceptionSpecification ExceptSpec(*this); 8748 if (ClassDecl->isInvalidDecl()) 8749 return ExceptSpec; 8750 8751 // Direct base-class constructors. 8752 for (const auto &B : ClassDecl->bases()) { 8753 if (B.isVirtual()) // Handled below. 8754 continue; 8755 8756 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8757 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8758 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8759 // If this is a deleted function, add it anyway. This might be conformant 8760 // with the standard. This might not. I'm not sure. It might not matter. 8761 if (Constructor) 8762 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8763 } 8764 } 8765 8766 // Virtual base-class constructors. 8767 for (const auto &B : ClassDecl->vbases()) { 8768 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8769 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8770 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8771 // If this is a deleted function, add it anyway. This might be conformant 8772 // with the standard. This might not. I'm not sure. It might not matter. 8773 if (Constructor) 8774 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8775 } 8776 } 8777 8778 // Field constructors. 8779 for (const auto *F : ClassDecl->fields()) { 8780 if (F->hasInClassInitializer()) { 8781 if (Expr *E = F->getInClassInitializer()) 8782 ExceptSpec.CalledExpr(E); 8783 } else if (const RecordType *RecordTy 8784 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8785 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8786 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8787 // If this is a deleted function, add it anyway. This might be conformant 8788 // with the standard. This might not. I'm not sure. It might not matter. 8789 // In particular, the problem is that this function never gets called. It 8790 // might just be ill-formed because this function attempts to refer to 8791 // a deleted function here. 8792 if (Constructor) 8793 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8794 } 8795 } 8796 8797 return ExceptSpec; 8798 } 8799 8800 Sema::ImplicitExceptionSpecification 8801 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8802 CXXRecordDecl *ClassDecl = CD->getParent(); 8803 8804 // C++ [except.spec]p14: 8805 // An inheriting constructor [...] shall have an exception-specification. [...] 8806 ImplicitExceptionSpecification ExceptSpec(*this); 8807 if (ClassDecl->isInvalidDecl()) 8808 return ExceptSpec; 8809 8810 // Inherited constructor. 8811 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8812 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8813 // FIXME: Copying or moving the parameters could add extra exceptions to the 8814 // set, as could the default arguments for the inherited constructor. This 8815 // will be addressed when we implement the resolution of core issue 1351. 8816 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8817 8818 // Direct base-class constructors. 8819 for (const auto &B : ClassDecl->bases()) { 8820 if (B.isVirtual()) // Handled below. 8821 continue; 8822 8823 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8824 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8825 if (BaseClassDecl == InheritedDecl) 8826 continue; 8827 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8828 if (Constructor) 8829 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8830 } 8831 } 8832 8833 // Virtual base-class constructors. 8834 for (const auto &B : ClassDecl->vbases()) { 8835 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8836 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8837 if (BaseClassDecl == InheritedDecl) 8838 continue; 8839 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8840 if (Constructor) 8841 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8842 } 8843 } 8844 8845 // Field constructors. 8846 for (const auto *F : ClassDecl->fields()) { 8847 if (F->hasInClassInitializer()) { 8848 if (Expr *E = F->getInClassInitializer()) 8849 ExceptSpec.CalledExpr(E); 8850 } else if (const RecordType *RecordTy 8851 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8852 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8853 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8854 if (Constructor) 8855 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8856 } 8857 } 8858 8859 return ExceptSpec; 8860 } 8861 8862 namespace { 8863 /// RAII object to register a special member as being currently declared. 8864 struct DeclaringSpecialMember { 8865 Sema &S; 8866 Sema::SpecialMemberDecl D; 8867 bool WasAlreadyBeingDeclared; 8868 8869 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8870 : S(S), D(RD, CSM) { 8871 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8872 if (WasAlreadyBeingDeclared) 8873 // This almost never happens, but if it does, ensure that our cache 8874 // doesn't contain a stale result. 8875 S.SpecialMemberCache.clear(); 8876 8877 // FIXME: Register a note to be produced if we encounter an error while 8878 // declaring the special member. 8879 } 8880 ~DeclaringSpecialMember() { 8881 if (!WasAlreadyBeingDeclared) 8882 S.SpecialMembersBeingDeclared.erase(D); 8883 } 8884 8885 /// \brief Are we already trying to declare this special member? 8886 bool isAlreadyBeingDeclared() const { 8887 return WasAlreadyBeingDeclared; 8888 } 8889 }; 8890 } 8891 8892 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8893 CXXRecordDecl *ClassDecl) { 8894 // C++ [class.ctor]p5: 8895 // A default constructor for a class X is a constructor of class X 8896 // that can be called without an argument. If there is no 8897 // user-declared constructor for class X, a default constructor is 8898 // implicitly declared. An implicitly-declared default constructor 8899 // is an inline public member of its class. 8900 assert(ClassDecl->needsImplicitDefaultConstructor() && 8901 "Should not build implicit default constructor!"); 8902 8903 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8904 if (DSM.isAlreadyBeingDeclared()) 8905 return nullptr; 8906 8907 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8908 CXXDefaultConstructor, 8909 false); 8910 8911 // Create the actual constructor declaration. 8912 CanQualType ClassType 8913 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8914 SourceLocation ClassLoc = ClassDecl->getLocation(); 8915 DeclarationName Name 8916 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8917 DeclarationNameInfo NameInfo(Name, ClassLoc); 8918 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8919 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8920 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8921 /*isImplicitlyDeclared=*/true, Constexpr); 8922 DefaultCon->setAccess(AS_public); 8923 DefaultCon->setDefaulted(); 8924 8925 if (getLangOpts().CUDA) { 8926 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8927 DefaultCon, 8928 /* ConstRHS */ false, 8929 /* Diagnose */ false); 8930 } 8931 8932 // Build an exception specification pointing back at this constructor. 8933 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8934 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8935 8936 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8937 // constructors is easy to compute. 8938 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8939 8940 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8941 SetDeclDeleted(DefaultCon, ClassLoc); 8942 8943 // Note that we have declared this constructor. 8944 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8945 8946 if (Scope *S = getScopeForContext(ClassDecl)) 8947 PushOnScopeChains(DefaultCon, S, false); 8948 ClassDecl->addDecl(DefaultCon); 8949 8950 return DefaultCon; 8951 } 8952 8953 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8954 CXXConstructorDecl *Constructor) { 8955 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8956 !Constructor->doesThisDeclarationHaveABody() && 8957 !Constructor->isDeleted()) && 8958 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8959 8960 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8961 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8962 8963 SynthesizedFunctionScope Scope(*this, Constructor); 8964 DiagnosticErrorTrap Trap(Diags); 8965 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8966 Trap.hasErrorOccurred()) { 8967 Diag(CurrentLocation, diag::note_member_synthesized_at) 8968 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8969 Constructor->setInvalidDecl(); 8970 return; 8971 } 8972 8973 // The exception specification is needed because we are defining the 8974 // function. 8975 ResolveExceptionSpec(CurrentLocation, 8976 Constructor->getType()->castAs<FunctionProtoType>()); 8977 8978 SourceLocation Loc = Constructor->getLocEnd().isValid() 8979 ? Constructor->getLocEnd() 8980 : Constructor->getLocation(); 8981 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8982 8983 Constructor->markUsed(Context); 8984 MarkVTableUsed(CurrentLocation, ClassDecl); 8985 8986 if (ASTMutationListener *L = getASTMutationListener()) { 8987 L->CompletedImplicitDefinition(Constructor); 8988 } 8989 8990 DiagnoseUninitializedFields(*this, Constructor); 8991 } 8992 8993 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8994 // Perform any delayed checks on exception specifications. 8995 CheckDelayedMemberExceptionSpecs(); 8996 } 8997 8998 namespace { 8999 /// Information on inheriting constructors to declare. 9000 class InheritingConstructorInfo { 9001 public: 9002 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 9003 : SemaRef(SemaRef), Derived(Derived) { 9004 // Mark the constructors that we already have in the derived class. 9005 // 9006 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 9007 // unless there is a user-declared constructor with the same signature in 9008 // the class where the using-declaration appears. 9009 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 9010 } 9011 9012 void inheritAll(CXXRecordDecl *RD) { 9013 visitAll(RD, &InheritingConstructorInfo::inherit); 9014 } 9015 9016 private: 9017 /// Information about an inheriting constructor. 9018 struct InheritingConstructor { 9019 InheritingConstructor() 9020 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 9021 9022 /// If \c true, a constructor with this signature is already declared 9023 /// in the derived class. 9024 bool DeclaredInDerived; 9025 9026 /// The constructor which is inherited. 9027 const CXXConstructorDecl *BaseCtor; 9028 9029 /// The derived constructor we declared. 9030 CXXConstructorDecl *DerivedCtor; 9031 }; 9032 9033 /// Inheriting constructors with a given canonical type. There can be at 9034 /// most one such non-template constructor, and any number of templated 9035 /// constructors. 9036 struct InheritingConstructorsForType { 9037 InheritingConstructor NonTemplate; 9038 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 9039 Templates; 9040 9041 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 9042 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 9043 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 9044 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 9045 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 9046 false, S.TPL_TemplateMatch)) 9047 return Templates[I].second; 9048 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 9049 return Templates.back().second; 9050 } 9051 9052 return NonTemplate; 9053 } 9054 }; 9055 9056 /// Get or create the inheriting constructor record for a constructor. 9057 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 9058 QualType CtorType) { 9059 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 9060 .getEntry(SemaRef, Ctor); 9061 } 9062 9063 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 9064 9065 /// Process all constructors for a class. 9066 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 9067 for (const auto *Ctor : RD->ctors()) 9068 (this->*Callback)(Ctor); 9069 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9070 I(RD->decls_begin()), E(RD->decls_end()); 9071 I != E; ++I) { 9072 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 9073 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 9074 (this->*Callback)(CD); 9075 } 9076 } 9077 9078 /// Note that a constructor (or constructor template) was declared in Derived. 9079 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 9080 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 9081 } 9082 9083 /// Inherit a single constructor. 9084 void inherit(const CXXConstructorDecl *Ctor) { 9085 const FunctionProtoType *CtorType = 9086 Ctor->getType()->castAs<FunctionProtoType>(); 9087 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 9088 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 9089 9090 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 9091 9092 // Core issue (no number yet): the ellipsis is always discarded. 9093 if (EPI.Variadic) { 9094 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 9095 SemaRef.Diag(Ctor->getLocation(), 9096 diag::note_using_decl_constructor_ellipsis); 9097 EPI.Variadic = false; 9098 } 9099 9100 // Declare a constructor for each number of parameters. 9101 // 9102 // C++11 [class.inhctor]p1: 9103 // The candidate set of inherited constructors from the class X named in 9104 // the using-declaration consists of [... modulo defects ...] for each 9105 // constructor or constructor template of X, the set of constructors or 9106 // constructor templates that results from omitting any ellipsis parameter 9107 // specification and successively omitting parameters with a default 9108 // argument from the end of the parameter-type-list 9109 unsigned MinParams = minParamsToInherit(Ctor); 9110 unsigned Params = Ctor->getNumParams(); 9111 if (Params >= MinParams) { 9112 do 9113 declareCtor(UsingLoc, Ctor, 9114 SemaRef.Context.getFunctionType( 9115 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 9116 while (Params > MinParams && 9117 Ctor->getParamDecl(--Params)->hasDefaultArg()); 9118 } 9119 } 9120 9121 /// Find the using-declaration which specified that we should inherit the 9122 /// constructors of \p Base. 9123 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 9124 // No fancy lookup required; just look for the base constructor name 9125 // directly within the derived class. 9126 ASTContext &Context = SemaRef.Context; 9127 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9128 Context.getCanonicalType(Context.getRecordType(Base))); 9129 DeclContext::lookup_result Decls = Derived->lookup(Name); 9130 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 9131 } 9132 9133 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 9134 // C++11 [class.inhctor]p3: 9135 // [F]or each constructor template in the candidate set of inherited 9136 // constructors, a constructor template is implicitly declared 9137 if (Ctor->getDescribedFunctionTemplate()) 9138 return 0; 9139 9140 // For each non-template constructor in the candidate set of inherited 9141 // constructors other than a constructor having no parameters or a 9142 // copy/move constructor having a single parameter, a constructor is 9143 // implicitly declared [...] 9144 if (Ctor->getNumParams() == 0) 9145 return 1; 9146 if (Ctor->isCopyOrMoveConstructor()) 9147 return 2; 9148 9149 // Per discussion on core reflector, never inherit a constructor which 9150 // would become a default, copy, or move constructor of Derived either. 9151 const ParmVarDecl *PD = Ctor->getParamDecl(0); 9152 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 9153 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 9154 } 9155 9156 /// Declare a single inheriting constructor, inheriting the specified 9157 /// constructor, with the given type. 9158 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 9159 QualType DerivedType) { 9160 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 9161 9162 // C++11 [class.inhctor]p3: 9163 // ... a constructor is implicitly declared with the same constructor 9164 // characteristics unless there is a user-declared constructor with 9165 // the same signature in the class where the using-declaration appears 9166 if (Entry.DeclaredInDerived) 9167 return; 9168 9169 // C++11 [class.inhctor]p7: 9170 // If two using-declarations declare inheriting constructors with the 9171 // same signature, the program is ill-formed 9172 if (Entry.DerivedCtor) { 9173 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 9174 // Only diagnose this once per constructor. 9175 if (Entry.DerivedCtor->isInvalidDecl()) 9176 return; 9177 Entry.DerivedCtor->setInvalidDecl(); 9178 9179 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9180 SemaRef.Diag(BaseCtor->getLocation(), 9181 diag::note_using_decl_constructor_conflict_current_ctor); 9182 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9183 diag::note_using_decl_constructor_conflict_previous_ctor); 9184 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9185 diag::note_using_decl_constructor_conflict_previous_using); 9186 } else { 9187 // Core issue (no number): if the same inheriting constructor is 9188 // produced by multiple base class constructors from the same base 9189 // class, the inheriting constructor is defined as deleted. 9190 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9191 } 9192 9193 return; 9194 } 9195 9196 ASTContext &Context = SemaRef.Context; 9197 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9198 Context.getCanonicalType(Context.getRecordType(Derived))); 9199 DeclarationNameInfo NameInfo(Name, UsingLoc); 9200 9201 TemplateParameterList *TemplateParams = nullptr; 9202 if (const FunctionTemplateDecl *FTD = 9203 BaseCtor->getDescribedFunctionTemplate()) { 9204 TemplateParams = FTD->getTemplateParameters(); 9205 // We're reusing template parameters from a different DeclContext. This 9206 // is questionable at best, but works out because the template depth in 9207 // both places is guaranteed to be 0. 9208 // FIXME: Rebuild the template parameters in the new context, and 9209 // transform the function type to refer to them. 9210 } 9211 9212 // Build type source info pointing at the using-declaration. This is 9213 // required by template instantiation. 9214 TypeSourceInfo *TInfo = 9215 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9216 FunctionProtoTypeLoc ProtoLoc = 9217 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9218 9219 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9220 Context, Derived, UsingLoc, NameInfo, DerivedType, 9221 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9222 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9223 9224 // Build an unevaluated exception specification for this constructor. 9225 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9226 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9227 EPI.ExceptionSpec.Type = EST_Unevaluated; 9228 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9229 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9230 FPT->getParamTypes(), EPI)); 9231 9232 // Build the parameter declarations. 9233 SmallVector<ParmVarDecl *, 16> ParamDecls; 9234 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9235 TypeSourceInfo *TInfo = 9236 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9237 ParmVarDecl *PD = ParmVarDecl::Create( 9238 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9239 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9240 PD->setScopeInfo(0, I); 9241 PD->setImplicit(); 9242 ParamDecls.push_back(PD); 9243 ProtoLoc.setParam(I, PD); 9244 } 9245 9246 // Set up the new constructor. 9247 DerivedCtor->setAccess(BaseCtor->getAccess()); 9248 DerivedCtor->setParams(ParamDecls); 9249 DerivedCtor->setInheritedConstructor(BaseCtor); 9250 if (BaseCtor->isDeleted()) 9251 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9252 9253 // If this is a constructor template, build the template declaration. 9254 if (TemplateParams) { 9255 FunctionTemplateDecl *DerivedTemplate = 9256 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9257 TemplateParams, DerivedCtor); 9258 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9259 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9260 Derived->addDecl(DerivedTemplate); 9261 } else { 9262 Derived->addDecl(DerivedCtor); 9263 } 9264 9265 Entry.BaseCtor = BaseCtor; 9266 Entry.DerivedCtor = DerivedCtor; 9267 } 9268 9269 Sema &SemaRef; 9270 CXXRecordDecl *Derived; 9271 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9272 MapType Map; 9273 }; 9274 } 9275 9276 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9277 // Defer declaring the inheriting constructors until the class is 9278 // instantiated. 9279 if (ClassDecl->isDependentContext()) 9280 return; 9281 9282 // Find base classes from which we might inherit constructors. 9283 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9284 for (const auto &BaseIt : ClassDecl->bases()) 9285 if (BaseIt.getInheritConstructors()) 9286 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9287 9288 // Go no further if we're not inheriting any constructors. 9289 if (InheritedBases.empty()) 9290 return; 9291 9292 // Declare the inherited constructors. 9293 InheritingConstructorInfo ICI(*this, ClassDecl); 9294 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9295 ICI.inheritAll(InheritedBases[I]); 9296 } 9297 9298 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9299 CXXConstructorDecl *Constructor) { 9300 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9301 assert(Constructor->getInheritedConstructor() && 9302 !Constructor->doesThisDeclarationHaveABody() && 9303 !Constructor->isDeleted()); 9304 9305 SynthesizedFunctionScope Scope(*this, Constructor); 9306 DiagnosticErrorTrap Trap(Diags); 9307 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9308 Trap.hasErrorOccurred()) { 9309 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9310 << Context.getTagDeclType(ClassDecl); 9311 Constructor->setInvalidDecl(); 9312 return; 9313 } 9314 9315 SourceLocation Loc = Constructor->getLocation(); 9316 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9317 9318 Constructor->markUsed(Context); 9319 MarkVTableUsed(CurrentLocation, ClassDecl); 9320 9321 if (ASTMutationListener *L = getASTMutationListener()) { 9322 L->CompletedImplicitDefinition(Constructor); 9323 } 9324 } 9325 9326 9327 Sema::ImplicitExceptionSpecification 9328 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9329 CXXRecordDecl *ClassDecl = MD->getParent(); 9330 9331 // C++ [except.spec]p14: 9332 // An implicitly declared special member function (Clause 12) shall have 9333 // an exception-specification. 9334 ImplicitExceptionSpecification ExceptSpec(*this); 9335 if (ClassDecl->isInvalidDecl()) 9336 return ExceptSpec; 9337 9338 // Direct base-class destructors. 9339 for (const auto &B : ClassDecl->bases()) { 9340 if (B.isVirtual()) // Handled below. 9341 continue; 9342 9343 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9344 ExceptSpec.CalledDecl(B.getLocStart(), 9345 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9346 } 9347 9348 // Virtual base-class destructors. 9349 for (const auto &B : ClassDecl->vbases()) { 9350 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9351 ExceptSpec.CalledDecl(B.getLocStart(), 9352 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9353 } 9354 9355 // Field destructors. 9356 for (const auto *F : ClassDecl->fields()) { 9357 if (const RecordType *RecordTy 9358 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9359 ExceptSpec.CalledDecl(F->getLocation(), 9360 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9361 } 9362 9363 return ExceptSpec; 9364 } 9365 9366 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9367 // C++ [class.dtor]p2: 9368 // If a class has no user-declared destructor, a destructor is 9369 // declared implicitly. An implicitly-declared destructor is an 9370 // inline public member of its class. 9371 assert(ClassDecl->needsImplicitDestructor()); 9372 9373 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9374 if (DSM.isAlreadyBeingDeclared()) 9375 return nullptr; 9376 9377 // Create the actual destructor declaration. 9378 CanQualType ClassType 9379 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9380 SourceLocation ClassLoc = ClassDecl->getLocation(); 9381 DeclarationName Name 9382 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9383 DeclarationNameInfo NameInfo(Name, ClassLoc); 9384 CXXDestructorDecl *Destructor 9385 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9386 QualType(), nullptr, /*isInline=*/true, 9387 /*isImplicitlyDeclared=*/true); 9388 Destructor->setAccess(AS_public); 9389 Destructor->setDefaulted(); 9390 9391 if (getLangOpts().CUDA) { 9392 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9393 Destructor, 9394 /* ConstRHS */ false, 9395 /* Diagnose */ false); 9396 } 9397 9398 // Build an exception specification pointing back at this destructor. 9399 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9400 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9401 9402 AddOverriddenMethods(ClassDecl, Destructor); 9403 9404 // We don't need to use SpecialMemberIsTrivial here; triviality for 9405 // destructors is easy to compute. 9406 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9407 9408 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9409 SetDeclDeleted(Destructor, ClassLoc); 9410 9411 // Note that we have declared this destructor. 9412 ++ASTContext::NumImplicitDestructorsDeclared; 9413 9414 // Introduce this destructor into its scope. 9415 if (Scope *S = getScopeForContext(ClassDecl)) 9416 PushOnScopeChains(Destructor, S, false); 9417 ClassDecl->addDecl(Destructor); 9418 9419 return Destructor; 9420 } 9421 9422 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9423 CXXDestructorDecl *Destructor) { 9424 assert((Destructor->isDefaulted() && 9425 !Destructor->doesThisDeclarationHaveABody() && 9426 !Destructor->isDeleted()) && 9427 "DefineImplicitDestructor - call it for implicit default dtor"); 9428 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9429 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9430 9431 if (Destructor->isInvalidDecl()) 9432 return; 9433 9434 SynthesizedFunctionScope Scope(*this, Destructor); 9435 9436 DiagnosticErrorTrap Trap(Diags); 9437 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9438 Destructor->getParent()); 9439 9440 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9441 Diag(CurrentLocation, diag::note_member_synthesized_at) 9442 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9443 9444 Destructor->setInvalidDecl(); 9445 return; 9446 } 9447 9448 // The exception specification is needed because we are defining the 9449 // function. 9450 ResolveExceptionSpec(CurrentLocation, 9451 Destructor->getType()->castAs<FunctionProtoType>()); 9452 9453 SourceLocation Loc = Destructor->getLocEnd().isValid() 9454 ? Destructor->getLocEnd() 9455 : Destructor->getLocation(); 9456 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9457 Destructor->markUsed(Context); 9458 MarkVTableUsed(CurrentLocation, ClassDecl); 9459 9460 if (ASTMutationListener *L = getASTMutationListener()) { 9461 L->CompletedImplicitDefinition(Destructor); 9462 } 9463 } 9464 9465 /// \brief Perform any semantic analysis which needs to be delayed until all 9466 /// pending class member declarations have been parsed. 9467 void Sema::ActOnFinishCXXMemberDecls() { 9468 // If the context is an invalid C++ class, just suppress these checks. 9469 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9470 if (Record->isInvalidDecl()) { 9471 DelayedDefaultedMemberExceptionSpecs.clear(); 9472 DelayedExceptionSpecChecks.clear(); 9473 return; 9474 } 9475 } 9476 } 9477 9478 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) { 9479 // Don't do anything for template patterns. 9480 if (Class->getDescribedClassTemplate()) 9481 return; 9482 9483 for (Decl *Member : Class->decls()) { 9484 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 9485 if (!CD) { 9486 // Recurse on nested classes. 9487 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member)) 9488 getDefaultArgExprsForConstructors(S, NestedRD); 9489 continue; 9490 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) { 9491 continue; 9492 } 9493 9494 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) { 9495 // Skip any default arguments that we've already instantiated. 9496 if (S.Context.getDefaultArgExprForConstructor(CD, I)) 9497 continue; 9498 9499 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD, 9500 CD->getParamDecl(I)).get(); 9501 S.DiscardCleanupsInEvaluationContext(); 9502 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 9503 } 9504 } 9505 } 9506 9507 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 9508 auto *RD = dyn_cast<CXXRecordDecl>(D); 9509 9510 // Default constructors that are annotated with __declspec(dllexport) which 9511 // have default arguments or don't use the standard calling convention are 9512 // wrapped with a thunk called the default constructor closure. 9513 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft()) 9514 getDefaultArgExprsForConstructors(*this, RD); 9515 9516 if (!DelayedDllExportClasses.empty()) { 9517 // Calling ReferenceDllExportedMethods might cause the current function to 9518 // be called again, so use a local copy of DelayedDllExportClasses. 9519 SmallVector<CXXRecordDecl *, 4> WorkList; 9520 std::swap(DelayedDllExportClasses, WorkList); 9521 for (CXXRecordDecl *Class : WorkList) 9522 ReferenceDllExportedMethods(*this, Class); 9523 } 9524 } 9525 9526 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9527 CXXDestructorDecl *Destructor) { 9528 assert(getLangOpts().CPlusPlus11 && 9529 "adjusting dtor exception specs was introduced in c++11"); 9530 9531 // C++11 [class.dtor]p3: 9532 // A declaration of a destructor that does not have an exception- 9533 // specification is implicitly considered to have the same exception- 9534 // specification as an implicit declaration. 9535 const FunctionProtoType *DtorType = Destructor->getType()-> 9536 getAs<FunctionProtoType>(); 9537 if (DtorType->hasExceptionSpec()) 9538 return; 9539 9540 // Replace the destructor's type, building off the existing one. Fortunately, 9541 // the only thing of interest in the destructor type is its extended info. 9542 // The return and arguments are fixed. 9543 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9544 EPI.ExceptionSpec.Type = EST_Unevaluated; 9545 EPI.ExceptionSpec.SourceDecl = Destructor; 9546 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9547 9548 // FIXME: If the destructor has a body that could throw, and the newly created 9549 // spec doesn't allow exceptions, we should emit a warning, because this 9550 // change in behavior can break conforming C++03 programs at runtime. 9551 // However, we don't have a body or an exception specification yet, so it 9552 // needs to be done somewhere else. 9553 } 9554 9555 namespace { 9556 /// \brief An abstract base class for all helper classes used in building the 9557 // copy/move operators. These classes serve as factory functions and help us 9558 // avoid using the same Expr* in the AST twice. 9559 class ExprBuilder { 9560 ExprBuilder(const ExprBuilder&) = delete; 9561 ExprBuilder &operator=(const ExprBuilder&) = delete; 9562 9563 protected: 9564 static Expr *assertNotNull(Expr *E) { 9565 assert(E && "Expression construction must not fail."); 9566 return E; 9567 } 9568 9569 public: 9570 ExprBuilder() {} 9571 virtual ~ExprBuilder() {} 9572 9573 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9574 }; 9575 9576 class RefBuilder: public ExprBuilder { 9577 VarDecl *Var; 9578 QualType VarType; 9579 9580 public: 9581 Expr *build(Sema &S, SourceLocation Loc) const override { 9582 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9583 } 9584 9585 RefBuilder(VarDecl *Var, QualType VarType) 9586 : Var(Var), VarType(VarType) {} 9587 }; 9588 9589 class ThisBuilder: public ExprBuilder { 9590 public: 9591 Expr *build(Sema &S, SourceLocation Loc) const override { 9592 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9593 } 9594 }; 9595 9596 class CastBuilder: public ExprBuilder { 9597 const ExprBuilder &Builder; 9598 QualType Type; 9599 ExprValueKind Kind; 9600 const CXXCastPath &Path; 9601 9602 public: 9603 Expr *build(Sema &S, SourceLocation Loc) const override { 9604 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9605 CK_UncheckedDerivedToBase, Kind, 9606 &Path).get()); 9607 } 9608 9609 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9610 const CXXCastPath &Path) 9611 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9612 }; 9613 9614 class DerefBuilder: public ExprBuilder { 9615 const ExprBuilder &Builder; 9616 9617 public: 9618 Expr *build(Sema &S, SourceLocation Loc) const override { 9619 return assertNotNull( 9620 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9621 } 9622 9623 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9624 }; 9625 9626 class MemberBuilder: public ExprBuilder { 9627 const ExprBuilder &Builder; 9628 QualType Type; 9629 CXXScopeSpec SS; 9630 bool IsArrow; 9631 LookupResult &MemberLookup; 9632 9633 public: 9634 Expr *build(Sema &S, SourceLocation Loc) const override { 9635 return assertNotNull(S.BuildMemberReferenceExpr( 9636 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9637 nullptr, MemberLookup, nullptr, nullptr).get()); 9638 } 9639 9640 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9641 LookupResult &MemberLookup) 9642 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9643 MemberLookup(MemberLookup) {} 9644 }; 9645 9646 class MoveCastBuilder: public ExprBuilder { 9647 const ExprBuilder &Builder; 9648 9649 public: 9650 Expr *build(Sema &S, SourceLocation Loc) const override { 9651 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9652 } 9653 9654 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9655 }; 9656 9657 class LvalueConvBuilder: public ExprBuilder { 9658 const ExprBuilder &Builder; 9659 9660 public: 9661 Expr *build(Sema &S, SourceLocation Loc) const override { 9662 return assertNotNull( 9663 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9664 } 9665 9666 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9667 }; 9668 9669 class SubscriptBuilder: public ExprBuilder { 9670 const ExprBuilder &Base; 9671 const ExprBuilder &Index; 9672 9673 public: 9674 Expr *build(Sema &S, SourceLocation Loc) const override { 9675 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9676 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9677 } 9678 9679 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9680 : Base(Base), Index(Index) {} 9681 }; 9682 9683 } // end anonymous namespace 9684 9685 /// When generating a defaulted copy or move assignment operator, if a field 9686 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9687 /// do so. This optimization only applies for arrays of scalars, and for arrays 9688 /// of class type where the selected copy/move-assignment operator is trivial. 9689 static StmtResult 9690 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9691 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9692 // Compute the size of the memory buffer to be copied. 9693 QualType SizeType = S.Context.getSizeType(); 9694 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9695 S.Context.getTypeSizeInChars(T).getQuantity()); 9696 9697 // Take the address of the field references for "from" and "to". We 9698 // directly construct UnaryOperators here because semantic analysis 9699 // does not permit us to take the address of an xvalue. 9700 Expr *From = FromB.build(S, Loc); 9701 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9702 S.Context.getPointerType(From->getType()), 9703 VK_RValue, OK_Ordinary, Loc); 9704 Expr *To = ToB.build(S, Loc); 9705 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9706 S.Context.getPointerType(To->getType()), 9707 VK_RValue, OK_Ordinary, Loc); 9708 9709 const Type *E = T->getBaseElementTypeUnsafe(); 9710 bool NeedsCollectableMemCpy = 9711 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9712 9713 // Create a reference to the __builtin_objc_memmove_collectable function 9714 StringRef MemCpyName = NeedsCollectableMemCpy ? 9715 "__builtin_objc_memmove_collectable" : 9716 "__builtin_memcpy"; 9717 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9718 Sema::LookupOrdinaryName); 9719 S.LookupName(R, S.TUScope, true); 9720 9721 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9722 if (!MemCpy) 9723 // Something went horribly wrong earlier, and we will have complained 9724 // about it. 9725 return StmtError(); 9726 9727 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9728 VK_RValue, Loc, nullptr); 9729 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9730 9731 Expr *CallArgs[] = { 9732 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9733 }; 9734 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9735 Loc, CallArgs, Loc); 9736 9737 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9738 return Call.getAs<Stmt>(); 9739 } 9740 9741 /// \brief Builds a statement that copies/moves the given entity from \p From to 9742 /// \c To. 9743 /// 9744 /// This routine is used to copy/move the members of a class with an 9745 /// implicitly-declared copy/move assignment operator. When the entities being 9746 /// copied are arrays, this routine builds for loops to copy them. 9747 /// 9748 /// \param S The Sema object used for type-checking. 9749 /// 9750 /// \param Loc The location where the implicit copy/move is being generated. 9751 /// 9752 /// \param T The type of the expressions being copied/moved. Both expressions 9753 /// must have this type. 9754 /// 9755 /// \param To The expression we are copying/moving to. 9756 /// 9757 /// \param From The expression we are copying/moving from. 9758 /// 9759 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9760 /// Otherwise, it's a non-static member subobject. 9761 /// 9762 /// \param Copying Whether we're copying or moving. 9763 /// 9764 /// \param Depth Internal parameter recording the depth of the recursion. 9765 /// 9766 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9767 /// if a memcpy should be used instead. 9768 static StmtResult 9769 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9770 const ExprBuilder &To, const ExprBuilder &From, 9771 bool CopyingBaseSubobject, bool Copying, 9772 unsigned Depth = 0) { 9773 // C++11 [class.copy]p28: 9774 // Each subobject is assigned in the manner appropriate to its type: 9775 // 9776 // - if the subobject is of class type, as if by a call to operator= with 9777 // the subobject as the object expression and the corresponding 9778 // subobject of x as a single function argument (as if by explicit 9779 // qualification; that is, ignoring any possible virtual overriding 9780 // functions in more derived classes); 9781 // 9782 // C++03 [class.copy]p13: 9783 // - if the subobject is of class type, the copy assignment operator for 9784 // the class is used (as if by explicit qualification; that is, 9785 // ignoring any possible virtual overriding functions in more derived 9786 // classes); 9787 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9788 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9789 9790 // Look for operator=. 9791 DeclarationName Name 9792 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9793 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9794 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9795 9796 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9797 // operator. 9798 if (!S.getLangOpts().CPlusPlus11) { 9799 LookupResult::Filter F = OpLookup.makeFilter(); 9800 while (F.hasNext()) { 9801 NamedDecl *D = F.next(); 9802 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9803 if (Method->isCopyAssignmentOperator() || 9804 (!Copying && Method->isMoveAssignmentOperator())) 9805 continue; 9806 9807 F.erase(); 9808 } 9809 F.done(); 9810 } 9811 9812 // Suppress the protected check (C++ [class.protected]) for each of the 9813 // assignment operators we found. This strange dance is required when 9814 // we're assigning via a base classes's copy-assignment operator. To 9815 // ensure that we're getting the right base class subobject (without 9816 // ambiguities), we need to cast "this" to that subobject type; to 9817 // ensure that we don't go through the virtual call mechanism, we need 9818 // to qualify the operator= name with the base class (see below). However, 9819 // this means that if the base class has a protected copy assignment 9820 // operator, the protected member access check will fail. So, we 9821 // rewrite "protected" access to "public" access in this case, since we 9822 // know by construction that we're calling from a derived class. 9823 if (CopyingBaseSubobject) { 9824 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9825 L != LEnd; ++L) { 9826 if (L.getAccess() == AS_protected) 9827 L.setAccess(AS_public); 9828 } 9829 } 9830 9831 // Create the nested-name-specifier that will be used to qualify the 9832 // reference to operator=; this is required to suppress the virtual 9833 // call mechanism. 9834 CXXScopeSpec SS; 9835 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9836 SS.MakeTrivial(S.Context, 9837 NestedNameSpecifier::Create(S.Context, nullptr, false, 9838 CanonicalT), 9839 Loc); 9840 9841 // Create the reference to operator=. 9842 ExprResult OpEqualRef 9843 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9844 SS, /*TemplateKWLoc=*/SourceLocation(), 9845 /*FirstQualifierInScope=*/nullptr, 9846 OpLookup, 9847 /*TemplateArgs=*/nullptr, /*S*/nullptr, 9848 /*SuppressQualifierCheck=*/true); 9849 if (OpEqualRef.isInvalid()) 9850 return StmtError(); 9851 9852 // Build the call to the assignment operator. 9853 9854 Expr *FromInst = From.build(S, Loc); 9855 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9856 OpEqualRef.getAs<Expr>(), 9857 Loc, FromInst, Loc); 9858 if (Call.isInvalid()) 9859 return StmtError(); 9860 9861 // If we built a call to a trivial 'operator=' while copying an array, 9862 // bail out. We'll replace the whole shebang with a memcpy. 9863 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9864 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9865 return StmtResult((Stmt*)nullptr); 9866 9867 // Convert to an expression-statement, and clean up any produced 9868 // temporaries. 9869 return S.ActOnExprStmt(Call); 9870 } 9871 9872 // - if the subobject is of scalar type, the built-in assignment 9873 // operator is used. 9874 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9875 if (!ArrayTy) { 9876 ExprResult Assignment = S.CreateBuiltinBinOp( 9877 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9878 if (Assignment.isInvalid()) 9879 return StmtError(); 9880 return S.ActOnExprStmt(Assignment); 9881 } 9882 9883 // - if the subobject is an array, each element is assigned, in the 9884 // manner appropriate to the element type; 9885 9886 // Construct a loop over the array bounds, e.g., 9887 // 9888 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9889 // 9890 // that will copy each of the array elements. 9891 QualType SizeType = S.Context.getSizeType(); 9892 9893 // Create the iteration variable. 9894 IdentifierInfo *IterationVarName = nullptr; 9895 { 9896 SmallString<8> Str; 9897 llvm::raw_svector_ostream OS(Str); 9898 OS << "__i" << Depth; 9899 IterationVarName = &S.Context.Idents.get(OS.str()); 9900 } 9901 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9902 IterationVarName, SizeType, 9903 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9904 SC_None); 9905 9906 // Initialize the iteration variable to zero. 9907 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9908 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9909 9910 // Creates a reference to the iteration variable. 9911 RefBuilder IterationVarRef(IterationVar, SizeType); 9912 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9913 9914 // Create the DeclStmt that holds the iteration variable. 9915 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9916 9917 // Subscript the "from" and "to" expressions with the iteration variable. 9918 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9919 MoveCastBuilder FromIndexMove(FromIndexCopy); 9920 const ExprBuilder *FromIndex; 9921 if (Copying) 9922 FromIndex = &FromIndexCopy; 9923 else 9924 FromIndex = &FromIndexMove; 9925 9926 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9927 9928 // Build the copy/move for an individual element of the array. 9929 StmtResult Copy = 9930 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9931 ToIndex, *FromIndex, CopyingBaseSubobject, 9932 Copying, Depth + 1); 9933 // Bail out if copying fails or if we determined that we should use memcpy. 9934 if (Copy.isInvalid() || !Copy.get()) 9935 return Copy; 9936 9937 // Create the comparison against the array bound. 9938 llvm::APInt Upper 9939 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9940 Expr *Comparison 9941 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9942 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9943 BO_NE, S.Context.BoolTy, 9944 VK_RValue, OK_Ordinary, Loc, false); 9945 9946 // Create the pre-increment of the iteration variable. 9947 Expr *Increment 9948 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9949 SizeType, VK_LValue, OK_Ordinary, Loc); 9950 9951 // Construct the loop that copies all elements of this array. 9952 return S.ActOnForStmt(Loc, Loc, InitStmt, 9953 S.MakeFullExpr(Comparison), 9954 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9955 Loc, Copy.get()); 9956 } 9957 9958 static StmtResult 9959 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9960 const ExprBuilder &To, const ExprBuilder &From, 9961 bool CopyingBaseSubobject, bool Copying) { 9962 // Maybe we should use a memcpy? 9963 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9964 T.isTriviallyCopyableType(S.Context)) 9965 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9966 9967 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9968 CopyingBaseSubobject, 9969 Copying, 0)); 9970 9971 // If we ended up picking a trivial assignment operator for an array of a 9972 // non-trivially-copyable class type, just emit a memcpy. 9973 if (!Result.isInvalid() && !Result.get()) 9974 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9975 9976 return Result; 9977 } 9978 9979 Sema::ImplicitExceptionSpecification 9980 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9981 CXXRecordDecl *ClassDecl = MD->getParent(); 9982 9983 ImplicitExceptionSpecification ExceptSpec(*this); 9984 if (ClassDecl->isInvalidDecl()) 9985 return ExceptSpec; 9986 9987 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9988 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9989 unsigned ArgQuals = 9990 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9991 9992 // C++ [except.spec]p14: 9993 // An implicitly declared special member function (Clause 12) shall have an 9994 // exception-specification. [...] 9995 9996 // It is unspecified whether or not an implicit copy assignment operator 9997 // attempts to deduplicate calls to assignment operators of virtual bases are 9998 // made. As such, this exception specification is effectively unspecified. 9999 // Based on a similar decision made for constness in C++0x, we're erring on 10000 // the side of assuming such calls to be made regardless of whether they 10001 // actually happen. 10002 for (const auto &Base : ClassDecl->bases()) { 10003 if (Base.isVirtual()) 10004 continue; 10005 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 &Base : ClassDecl->vbases()) { 10014 CXXRecordDecl *BaseClassDecl 10015 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10016 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10017 ArgQuals, false, 0)) 10018 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10019 } 10020 10021 for (const auto *Field : ClassDecl->fields()) { 10022 QualType FieldType = Context.getBaseElementType(Field->getType()); 10023 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10024 if (CXXMethodDecl *CopyAssign = 10025 LookupCopyingAssignment(FieldClassDecl, 10026 ArgQuals | FieldType.getCVRQualifiers(), 10027 false, 0)) 10028 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 10029 } 10030 } 10031 10032 return ExceptSpec; 10033 } 10034 10035 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 10036 // Note: The following rules are largely analoguous to the copy 10037 // constructor rules. Note that virtual bases are not taken into account 10038 // for determining the argument type of the operator. Note also that 10039 // operators taking an object instead of a reference are allowed. 10040 assert(ClassDecl->needsImplicitCopyAssignment()); 10041 10042 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 10043 if (DSM.isAlreadyBeingDeclared()) 10044 return nullptr; 10045 10046 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10047 QualType RetType = Context.getLValueReferenceType(ArgType); 10048 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 10049 if (Const) 10050 ArgType = ArgType.withConst(); 10051 ArgType = Context.getLValueReferenceType(ArgType); 10052 10053 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10054 CXXCopyAssignment, 10055 Const); 10056 10057 // An implicitly-declared copy assignment operator is an inline public 10058 // member of its class. 10059 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10060 SourceLocation ClassLoc = ClassDecl->getLocation(); 10061 DeclarationNameInfo NameInfo(Name, ClassLoc); 10062 CXXMethodDecl *CopyAssignment = 10063 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10064 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10065 /*isInline=*/true, Constexpr, SourceLocation()); 10066 CopyAssignment->setAccess(AS_public); 10067 CopyAssignment->setDefaulted(); 10068 CopyAssignment->setImplicit(); 10069 10070 if (getLangOpts().CUDA) { 10071 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 10072 CopyAssignment, 10073 /* ConstRHS */ Const, 10074 /* Diagnose */ false); 10075 } 10076 10077 // Build an exception specification pointing back at this member. 10078 FunctionProtoType::ExtProtoInfo EPI = 10079 getImplicitMethodEPI(*this, CopyAssignment); 10080 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10081 10082 // Add the parameter to the operator. 10083 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 10084 ClassLoc, ClassLoc, 10085 /*Id=*/nullptr, ArgType, 10086 /*TInfo=*/nullptr, SC_None, 10087 nullptr); 10088 CopyAssignment->setParams(FromParam); 10089 10090 AddOverriddenMethods(ClassDecl, CopyAssignment); 10091 10092 CopyAssignment->setTrivial( 10093 ClassDecl->needsOverloadResolutionForCopyAssignment() 10094 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 10095 : ClassDecl->hasTrivialCopyAssignment()); 10096 10097 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 10098 SetDeclDeleted(CopyAssignment, ClassLoc); 10099 10100 // Note that we have added this copy-assignment operator. 10101 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10102 10103 if (Scope *S = getScopeForContext(ClassDecl)) 10104 PushOnScopeChains(CopyAssignment, S, false); 10105 ClassDecl->addDecl(CopyAssignment); 10106 10107 return CopyAssignment; 10108 } 10109 10110 /// Diagnose an implicit copy operation for a class which is odr-used, but 10111 /// which is deprecated because the class has a user-declared copy constructor, 10112 /// copy assignment operator, or destructor. 10113 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 10114 SourceLocation UseLoc) { 10115 assert(CopyOp->isImplicit()); 10116 10117 CXXRecordDecl *RD = CopyOp->getParent(); 10118 CXXMethodDecl *UserDeclaredOperation = nullptr; 10119 10120 // In Microsoft mode, assignment operations don't affect constructors and 10121 // vice versa. 10122 if (RD->hasUserDeclaredDestructor()) { 10123 UserDeclaredOperation = RD->getDestructor(); 10124 } else if (!isa<CXXConstructorDecl>(CopyOp) && 10125 RD->hasUserDeclaredCopyConstructor() && 10126 !S.getLangOpts().MSVCCompat) { 10127 // Find any user-declared copy constructor. 10128 for (auto *I : RD->ctors()) { 10129 if (I->isCopyConstructor()) { 10130 UserDeclaredOperation = I; 10131 break; 10132 } 10133 } 10134 assert(UserDeclaredOperation); 10135 } else if (isa<CXXConstructorDecl>(CopyOp) && 10136 RD->hasUserDeclaredCopyAssignment() && 10137 !S.getLangOpts().MSVCCompat) { 10138 // Find any user-declared move assignment operator. 10139 for (auto *I : RD->methods()) { 10140 if (I->isCopyAssignmentOperator()) { 10141 UserDeclaredOperation = I; 10142 break; 10143 } 10144 } 10145 assert(UserDeclaredOperation); 10146 } 10147 10148 if (UserDeclaredOperation) { 10149 S.Diag(UserDeclaredOperation->getLocation(), 10150 diag::warn_deprecated_copy_operation) 10151 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 10152 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 10153 S.Diag(UseLoc, diag::note_member_synthesized_at) 10154 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 10155 : Sema::CXXCopyAssignment) 10156 << RD; 10157 } 10158 } 10159 10160 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 10161 CXXMethodDecl *CopyAssignOperator) { 10162 assert((CopyAssignOperator->isDefaulted() && 10163 CopyAssignOperator->isOverloadedOperator() && 10164 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 10165 !CopyAssignOperator->doesThisDeclarationHaveABody() && 10166 !CopyAssignOperator->isDeleted()) && 10167 "DefineImplicitCopyAssignment called for wrong function"); 10168 10169 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 10170 10171 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 10172 CopyAssignOperator->setInvalidDecl(); 10173 return; 10174 } 10175 10176 // C++11 [class.copy]p18: 10177 // The [definition of an implicitly declared copy assignment operator] is 10178 // deprecated if the class has a user-declared copy constructor or a 10179 // user-declared destructor. 10180 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 10181 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 10182 10183 CopyAssignOperator->markUsed(Context); 10184 10185 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 10186 DiagnosticErrorTrap Trap(Diags); 10187 10188 // C++0x [class.copy]p30: 10189 // The implicitly-defined or explicitly-defaulted copy assignment operator 10190 // for a non-union class X performs memberwise copy assignment of its 10191 // subobjects. The direct base classes of X are assigned first, in the 10192 // order of their declaration in the base-specifier-list, and then the 10193 // immediate non-static data members of X are assigned, in the order in 10194 // which they were declared in the class definition. 10195 10196 // The statements that form the synthesized function body. 10197 SmallVector<Stmt*, 8> Statements; 10198 10199 // The parameter for the "other" object, which we are copying from. 10200 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 10201 Qualifiers OtherQuals = Other->getType().getQualifiers(); 10202 QualType OtherRefType = Other->getType(); 10203 if (const LValueReferenceType *OtherRef 10204 = OtherRefType->getAs<LValueReferenceType>()) { 10205 OtherRefType = OtherRef->getPointeeType(); 10206 OtherQuals = OtherRefType.getQualifiers(); 10207 } 10208 10209 // Our location for everything implicitly-generated. 10210 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 10211 ? CopyAssignOperator->getLocEnd() 10212 : CopyAssignOperator->getLocation(); 10213 10214 // Builds a DeclRefExpr for the "other" object. 10215 RefBuilder OtherRef(Other, OtherRefType); 10216 10217 // Builds the "this" pointer. 10218 ThisBuilder This; 10219 10220 // Assign base classes. 10221 bool Invalid = false; 10222 for (auto &Base : ClassDecl->bases()) { 10223 // Form the assignment: 10224 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10225 QualType BaseType = Base.getType().getUnqualifiedType(); 10226 if (!BaseType->isRecordType()) { 10227 Invalid = true; 10228 continue; 10229 } 10230 10231 CXXCastPath BasePath; 10232 BasePath.push_back(&Base); 10233 10234 // Construct the "from" expression, which is an implicit cast to the 10235 // appropriately-qualified base type. 10236 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10237 VK_LValue, BasePath); 10238 10239 // Dereference "this". 10240 DerefBuilder DerefThis(This); 10241 CastBuilder To(DerefThis, 10242 Context.getCVRQualifiedType( 10243 BaseType, CopyAssignOperator->getTypeQualifiers()), 10244 VK_LValue, BasePath); 10245 10246 // Build the copy. 10247 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10248 To, From, 10249 /*CopyingBaseSubobject=*/true, 10250 /*Copying=*/true); 10251 if (Copy.isInvalid()) { 10252 Diag(CurrentLocation, diag::note_member_synthesized_at) 10253 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10254 CopyAssignOperator->setInvalidDecl(); 10255 return; 10256 } 10257 10258 // Success! Record the copy. 10259 Statements.push_back(Copy.getAs<Expr>()); 10260 } 10261 10262 // Assign non-static members. 10263 for (auto *Field : ClassDecl->fields()) { 10264 // FIXME: We should form some kind of AST representation for the implied 10265 // memcpy in a union copy operation. 10266 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10267 continue; 10268 10269 if (Field->isInvalidDecl()) { 10270 Invalid = true; 10271 continue; 10272 } 10273 10274 // Check for members of reference type; we can't copy those. 10275 if (Field->getType()->isReferenceType()) { 10276 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10277 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10278 Diag(Field->getLocation(), diag::note_declared_at); 10279 Diag(CurrentLocation, diag::note_member_synthesized_at) 10280 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10281 Invalid = true; 10282 continue; 10283 } 10284 10285 // Check for members of const-qualified, non-class type. 10286 QualType BaseType = Context.getBaseElementType(Field->getType()); 10287 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10288 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10289 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10290 Diag(Field->getLocation(), diag::note_declared_at); 10291 Diag(CurrentLocation, diag::note_member_synthesized_at) 10292 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10293 Invalid = true; 10294 continue; 10295 } 10296 10297 // Suppress assigning zero-width bitfields. 10298 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10299 continue; 10300 10301 QualType FieldType = Field->getType().getNonReferenceType(); 10302 if (FieldType->isIncompleteArrayType()) { 10303 assert(ClassDecl->hasFlexibleArrayMember() && 10304 "Incomplete array type is not valid"); 10305 continue; 10306 } 10307 10308 // Build references to the field in the object we're copying from and to. 10309 CXXScopeSpec SS; // Intentionally empty 10310 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10311 LookupMemberName); 10312 MemberLookup.addDecl(Field); 10313 MemberLookup.resolveKind(); 10314 10315 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10316 10317 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10318 10319 // Build the copy of this field. 10320 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10321 To, From, 10322 /*CopyingBaseSubobject=*/false, 10323 /*Copying=*/true); 10324 if (Copy.isInvalid()) { 10325 Diag(CurrentLocation, diag::note_member_synthesized_at) 10326 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10327 CopyAssignOperator->setInvalidDecl(); 10328 return; 10329 } 10330 10331 // Success! Record the copy. 10332 Statements.push_back(Copy.getAs<Stmt>()); 10333 } 10334 10335 if (!Invalid) { 10336 // Add a "return *this;" 10337 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10338 10339 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10340 if (Return.isInvalid()) 10341 Invalid = true; 10342 else { 10343 Statements.push_back(Return.getAs<Stmt>()); 10344 10345 if (Trap.hasErrorOccurred()) { 10346 Diag(CurrentLocation, diag::note_member_synthesized_at) 10347 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10348 Invalid = true; 10349 } 10350 } 10351 } 10352 10353 // The exception specification is needed because we are defining the 10354 // function. 10355 ResolveExceptionSpec(CurrentLocation, 10356 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10357 10358 if (Invalid) { 10359 CopyAssignOperator->setInvalidDecl(); 10360 return; 10361 } 10362 10363 StmtResult Body; 10364 { 10365 CompoundScopeRAII CompoundScope(*this); 10366 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10367 /*isStmtExpr=*/false); 10368 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10369 } 10370 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10371 10372 if (ASTMutationListener *L = getASTMutationListener()) { 10373 L->CompletedImplicitDefinition(CopyAssignOperator); 10374 } 10375 } 10376 10377 Sema::ImplicitExceptionSpecification 10378 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10379 CXXRecordDecl *ClassDecl = MD->getParent(); 10380 10381 ImplicitExceptionSpecification ExceptSpec(*this); 10382 if (ClassDecl->isInvalidDecl()) 10383 return ExceptSpec; 10384 10385 // C++0x [except.spec]p14: 10386 // An implicitly declared special member function (Clause 12) shall have an 10387 // exception-specification. [...] 10388 10389 // It is unspecified whether or not an implicit move assignment operator 10390 // attempts to deduplicate calls to assignment operators of virtual bases are 10391 // made. As such, this exception specification is effectively unspecified. 10392 // Based on a similar decision made for constness in C++0x, we're erring on 10393 // the side of assuming such calls to be made regardless of whether they 10394 // actually happen. 10395 // Note that a move constructor is not implicitly declared when there are 10396 // virtual bases, but it can still be user-declared and explicitly defaulted. 10397 for (const auto &Base : ClassDecl->bases()) { 10398 if (Base.isVirtual()) 10399 continue; 10400 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 &Base : ClassDecl->vbases()) { 10409 CXXRecordDecl *BaseClassDecl 10410 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10411 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10412 0, false, 0)) 10413 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10414 } 10415 10416 for (const auto *Field : ClassDecl->fields()) { 10417 QualType FieldType = Context.getBaseElementType(Field->getType()); 10418 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10419 if (CXXMethodDecl *MoveAssign = 10420 LookupMovingAssignment(FieldClassDecl, 10421 FieldType.getCVRQualifiers(), 10422 false, 0)) 10423 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10424 } 10425 } 10426 10427 return ExceptSpec; 10428 } 10429 10430 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10431 assert(ClassDecl->needsImplicitMoveAssignment()); 10432 10433 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10434 if (DSM.isAlreadyBeingDeclared()) 10435 return nullptr; 10436 10437 // Note: The following rules are largely analoguous to the move 10438 // constructor rules. 10439 10440 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10441 QualType RetType = Context.getLValueReferenceType(ArgType); 10442 ArgType = Context.getRValueReferenceType(ArgType); 10443 10444 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10445 CXXMoveAssignment, 10446 false); 10447 10448 // An implicitly-declared move assignment operator is an inline public 10449 // member of its class. 10450 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10451 SourceLocation ClassLoc = ClassDecl->getLocation(); 10452 DeclarationNameInfo NameInfo(Name, ClassLoc); 10453 CXXMethodDecl *MoveAssignment = 10454 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10455 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10456 /*isInline=*/true, Constexpr, SourceLocation()); 10457 MoveAssignment->setAccess(AS_public); 10458 MoveAssignment->setDefaulted(); 10459 MoveAssignment->setImplicit(); 10460 10461 if (getLangOpts().CUDA) { 10462 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10463 MoveAssignment, 10464 /* ConstRHS */ false, 10465 /* Diagnose */ false); 10466 } 10467 10468 // Build an exception specification pointing back at this member. 10469 FunctionProtoType::ExtProtoInfo EPI = 10470 getImplicitMethodEPI(*this, MoveAssignment); 10471 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10472 10473 // Add the parameter to the operator. 10474 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10475 ClassLoc, ClassLoc, 10476 /*Id=*/nullptr, ArgType, 10477 /*TInfo=*/nullptr, SC_None, 10478 nullptr); 10479 MoveAssignment->setParams(FromParam); 10480 10481 AddOverriddenMethods(ClassDecl, MoveAssignment); 10482 10483 MoveAssignment->setTrivial( 10484 ClassDecl->needsOverloadResolutionForMoveAssignment() 10485 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10486 : ClassDecl->hasTrivialMoveAssignment()); 10487 10488 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10489 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10490 SetDeclDeleted(MoveAssignment, ClassLoc); 10491 } 10492 10493 // Note that we have added this copy-assignment operator. 10494 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10495 10496 if (Scope *S = getScopeForContext(ClassDecl)) 10497 PushOnScopeChains(MoveAssignment, S, false); 10498 ClassDecl->addDecl(MoveAssignment); 10499 10500 return MoveAssignment; 10501 } 10502 10503 /// Check if we're implicitly defining a move assignment operator for a class 10504 /// with virtual bases. Such a move assignment might move-assign the virtual 10505 /// base multiple times. 10506 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10507 SourceLocation CurrentLocation) { 10508 assert(!Class->isDependentContext() && "should not define dependent move"); 10509 10510 // Only a virtual base could get implicitly move-assigned multiple times. 10511 // Only a non-trivial move assignment can observe this. We only want to 10512 // diagnose if we implicitly define an assignment operator that assigns 10513 // two base classes, both of which move-assign the same virtual base. 10514 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10515 Class->getNumBases() < 2) 10516 return; 10517 10518 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10519 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10520 VBaseMap VBases; 10521 10522 for (auto &BI : Class->bases()) { 10523 Worklist.push_back(&BI); 10524 while (!Worklist.empty()) { 10525 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10526 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10527 10528 // If the base has no non-trivial move assignment operators, 10529 // we don't care about moves from it. 10530 if (!Base->hasNonTrivialMoveAssignment()) 10531 continue; 10532 10533 // If there's nothing virtual here, skip it. 10534 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10535 continue; 10536 10537 // If we're not actually going to call a move assignment for this base, 10538 // or the selected move assignment is trivial, skip it. 10539 Sema::SpecialMemberOverloadResult *SMOR = 10540 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10541 /*ConstArg*/false, /*VolatileArg*/false, 10542 /*RValueThis*/true, /*ConstThis*/false, 10543 /*VolatileThis*/false); 10544 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10545 !SMOR->getMethod()->isMoveAssignmentOperator()) 10546 continue; 10547 10548 if (BaseSpec->isVirtual()) { 10549 // We're going to move-assign this virtual base, and its move 10550 // assignment operator is not trivial. If this can happen for 10551 // multiple distinct direct bases of Class, diagnose it. (If it 10552 // only happens in one base, we'll diagnose it when synthesizing 10553 // that base class's move assignment operator.) 10554 CXXBaseSpecifier *&Existing = 10555 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10556 .first->second; 10557 if (Existing && Existing != &BI) { 10558 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10559 << Class << Base; 10560 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10561 << (Base->getCanonicalDecl() == 10562 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10563 << Base << Existing->getType() << Existing->getSourceRange(); 10564 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10565 << (Base->getCanonicalDecl() == 10566 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10567 << Base << BI.getType() << BaseSpec->getSourceRange(); 10568 10569 // Only diagnose each vbase once. 10570 Existing = nullptr; 10571 } 10572 } else { 10573 // Only walk over bases that have defaulted move assignment operators. 10574 // We assume that any user-provided move assignment operator handles 10575 // the multiple-moves-of-vbase case itself somehow. 10576 if (!SMOR->getMethod()->isDefaulted()) 10577 continue; 10578 10579 // We're going to move the base classes of Base. Add them to the list. 10580 for (auto &BI : Base->bases()) 10581 Worklist.push_back(&BI); 10582 } 10583 } 10584 } 10585 } 10586 10587 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10588 CXXMethodDecl *MoveAssignOperator) { 10589 assert((MoveAssignOperator->isDefaulted() && 10590 MoveAssignOperator->isOverloadedOperator() && 10591 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10592 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10593 !MoveAssignOperator->isDeleted()) && 10594 "DefineImplicitMoveAssignment called for wrong function"); 10595 10596 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10597 10598 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10599 MoveAssignOperator->setInvalidDecl(); 10600 return; 10601 } 10602 10603 MoveAssignOperator->markUsed(Context); 10604 10605 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10606 DiagnosticErrorTrap Trap(Diags); 10607 10608 // C++0x [class.copy]p28: 10609 // The implicitly-defined or move assignment operator for a non-union class 10610 // X performs memberwise move assignment of its subobjects. The direct base 10611 // classes of X are assigned first, in the order of their declaration in the 10612 // base-specifier-list, and then the immediate non-static data members of X 10613 // are assigned, in the order in which they were declared in the class 10614 // definition. 10615 10616 // Issue a warning if our implicit move assignment operator will move 10617 // from a virtual base more than once. 10618 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10619 10620 // The statements that form the synthesized function body. 10621 SmallVector<Stmt*, 8> Statements; 10622 10623 // The parameter for the "other" object, which we are move from. 10624 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10625 QualType OtherRefType = Other->getType()-> 10626 getAs<RValueReferenceType>()->getPointeeType(); 10627 assert(!OtherRefType.getQualifiers() && 10628 "Bad argument type of defaulted move assignment"); 10629 10630 // Our location for everything implicitly-generated. 10631 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10632 ? MoveAssignOperator->getLocEnd() 10633 : MoveAssignOperator->getLocation(); 10634 10635 // Builds a reference to the "other" object. 10636 RefBuilder OtherRef(Other, OtherRefType); 10637 // Cast to rvalue. 10638 MoveCastBuilder MoveOther(OtherRef); 10639 10640 // Builds the "this" pointer. 10641 ThisBuilder This; 10642 10643 // Assign base classes. 10644 bool Invalid = false; 10645 for (auto &Base : ClassDecl->bases()) { 10646 // C++11 [class.copy]p28: 10647 // It is unspecified whether subobjects representing virtual base classes 10648 // are assigned more than once by the implicitly-defined copy assignment 10649 // operator. 10650 // FIXME: Do not assign to a vbase that will be assigned by some other base 10651 // class. For a move-assignment, this can result in the vbase being moved 10652 // multiple times. 10653 10654 // Form the assignment: 10655 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10656 QualType BaseType = Base.getType().getUnqualifiedType(); 10657 if (!BaseType->isRecordType()) { 10658 Invalid = true; 10659 continue; 10660 } 10661 10662 CXXCastPath BasePath; 10663 BasePath.push_back(&Base); 10664 10665 // Construct the "from" expression, which is an implicit cast to the 10666 // appropriately-qualified base type. 10667 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10668 10669 // Dereference "this". 10670 DerefBuilder DerefThis(This); 10671 10672 // Implicitly cast "this" to the appropriately-qualified base type. 10673 CastBuilder To(DerefThis, 10674 Context.getCVRQualifiedType( 10675 BaseType, MoveAssignOperator->getTypeQualifiers()), 10676 VK_LValue, BasePath); 10677 10678 // Build the move. 10679 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10680 To, From, 10681 /*CopyingBaseSubobject=*/true, 10682 /*Copying=*/false); 10683 if (Move.isInvalid()) { 10684 Diag(CurrentLocation, diag::note_member_synthesized_at) 10685 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10686 MoveAssignOperator->setInvalidDecl(); 10687 return; 10688 } 10689 10690 // Success! Record the move. 10691 Statements.push_back(Move.getAs<Expr>()); 10692 } 10693 10694 // Assign non-static members. 10695 for (auto *Field : ClassDecl->fields()) { 10696 // FIXME: We should form some kind of AST representation for the implied 10697 // memcpy in a union copy operation. 10698 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10699 continue; 10700 10701 if (Field->isInvalidDecl()) { 10702 Invalid = true; 10703 continue; 10704 } 10705 10706 // Check for members of reference type; we can't move those. 10707 if (Field->getType()->isReferenceType()) { 10708 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10709 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10710 Diag(Field->getLocation(), diag::note_declared_at); 10711 Diag(CurrentLocation, diag::note_member_synthesized_at) 10712 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10713 Invalid = true; 10714 continue; 10715 } 10716 10717 // Check for members of const-qualified, non-class type. 10718 QualType BaseType = Context.getBaseElementType(Field->getType()); 10719 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10720 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10721 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10722 Diag(Field->getLocation(), diag::note_declared_at); 10723 Diag(CurrentLocation, diag::note_member_synthesized_at) 10724 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10725 Invalid = true; 10726 continue; 10727 } 10728 10729 // Suppress assigning zero-width bitfields. 10730 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10731 continue; 10732 10733 QualType FieldType = Field->getType().getNonReferenceType(); 10734 if (FieldType->isIncompleteArrayType()) { 10735 assert(ClassDecl->hasFlexibleArrayMember() && 10736 "Incomplete array type is not valid"); 10737 continue; 10738 } 10739 10740 // Build references to the field in the object we're copying from and to. 10741 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10742 LookupMemberName); 10743 MemberLookup.addDecl(Field); 10744 MemberLookup.resolveKind(); 10745 MemberBuilder From(MoveOther, OtherRefType, 10746 /*IsArrow=*/false, MemberLookup); 10747 MemberBuilder To(This, getCurrentThisType(), 10748 /*IsArrow=*/true, MemberLookup); 10749 10750 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10751 "Member reference with rvalue base must be rvalue except for reference " 10752 "members, which aren't allowed for move assignment."); 10753 10754 // Build the move of this field. 10755 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10756 To, From, 10757 /*CopyingBaseSubobject=*/false, 10758 /*Copying=*/false); 10759 if (Move.isInvalid()) { 10760 Diag(CurrentLocation, diag::note_member_synthesized_at) 10761 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10762 MoveAssignOperator->setInvalidDecl(); 10763 return; 10764 } 10765 10766 // Success! Record the copy. 10767 Statements.push_back(Move.getAs<Stmt>()); 10768 } 10769 10770 if (!Invalid) { 10771 // Add a "return *this;" 10772 ExprResult ThisObj = 10773 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10774 10775 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10776 if (Return.isInvalid()) 10777 Invalid = true; 10778 else { 10779 Statements.push_back(Return.getAs<Stmt>()); 10780 10781 if (Trap.hasErrorOccurred()) { 10782 Diag(CurrentLocation, diag::note_member_synthesized_at) 10783 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10784 Invalid = true; 10785 } 10786 } 10787 } 10788 10789 // The exception specification is needed because we are defining the 10790 // function. 10791 ResolveExceptionSpec(CurrentLocation, 10792 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10793 10794 if (Invalid) { 10795 MoveAssignOperator->setInvalidDecl(); 10796 return; 10797 } 10798 10799 StmtResult Body; 10800 { 10801 CompoundScopeRAII CompoundScope(*this); 10802 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10803 /*isStmtExpr=*/false); 10804 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10805 } 10806 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10807 10808 if (ASTMutationListener *L = getASTMutationListener()) { 10809 L->CompletedImplicitDefinition(MoveAssignOperator); 10810 } 10811 } 10812 10813 Sema::ImplicitExceptionSpecification 10814 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10815 CXXRecordDecl *ClassDecl = MD->getParent(); 10816 10817 ImplicitExceptionSpecification ExceptSpec(*this); 10818 if (ClassDecl->isInvalidDecl()) 10819 return ExceptSpec; 10820 10821 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10822 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10823 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10824 10825 // C++ [except.spec]p14: 10826 // An implicitly declared special member function (Clause 12) shall have an 10827 // exception-specification. [...] 10828 for (const auto &Base : ClassDecl->bases()) { 10829 // Virtual bases are handled below. 10830 if (Base.isVirtual()) 10831 continue; 10832 10833 CXXRecordDecl *BaseClassDecl 10834 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10835 if (CXXConstructorDecl *CopyConstructor = 10836 LookupCopyingConstructor(BaseClassDecl, Quals)) 10837 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10838 } 10839 for (const auto &Base : ClassDecl->vbases()) { 10840 CXXRecordDecl *BaseClassDecl 10841 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10842 if (CXXConstructorDecl *CopyConstructor = 10843 LookupCopyingConstructor(BaseClassDecl, Quals)) 10844 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10845 } 10846 for (const auto *Field : ClassDecl->fields()) { 10847 QualType FieldType = Context.getBaseElementType(Field->getType()); 10848 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10849 if (CXXConstructorDecl *CopyConstructor = 10850 LookupCopyingConstructor(FieldClassDecl, 10851 Quals | FieldType.getCVRQualifiers())) 10852 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10853 } 10854 } 10855 10856 return ExceptSpec; 10857 } 10858 10859 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10860 CXXRecordDecl *ClassDecl) { 10861 // C++ [class.copy]p4: 10862 // If the class definition does not explicitly declare a copy 10863 // constructor, one is declared implicitly. 10864 assert(ClassDecl->needsImplicitCopyConstructor()); 10865 10866 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10867 if (DSM.isAlreadyBeingDeclared()) 10868 return nullptr; 10869 10870 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10871 QualType ArgType = ClassType; 10872 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10873 if (Const) 10874 ArgType = ArgType.withConst(); 10875 ArgType = Context.getLValueReferenceType(ArgType); 10876 10877 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10878 CXXCopyConstructor, 10879 Const); 10880 10881 DeclarationName Name 10882 = Context.DeclarationNames.getCXXConstructorName( 10883 Context.getCanonicalType(ClassType)); 10884 SourceLocation ClassLoc = ClassDecl->getLocation(); 10885 DeclarationNameInfo NameInfo(Name, ClassLoc); 10886 10887 // An implicitly-declared copy constructor is an inline public 10888 // member of its class. 10889 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10890 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10891 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10892 Constexpr); 10893 CopyConstructor->setAccess(AS_public); 10894 CopyConstructor->setDefaulted(); 10895 10896 if (getLangOpts().CUDA) { 10897 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10898 CopyConstructor, 10899 /* ConstRHS */ Const, 10900 /* Diagnose */ false); 10901 } 10902 10903 // Build an exception specification pointing back at this member. 10904 FunctionProtoType::ExtProtoInfo EPI = 10905 getImplicitMethodEPI(*this, CopyConstructor); 10906 CopyConstructor->setType( 10907 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10908 10909 // Add the parameter to the constructor. 10910 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10911 ClassLoc, ClassLoc, 10912 /*IdentifierInfo=*/nullptr, 10913 ArgType, /*TInfo=*/nullptr, 10914 SC_None, nullptr); 10915 CopyConstructor->setParams(FromParam); 10916 10917 CopyConstructor->setTrivial( 10918 ClassDecl->needsOverloadResolutionForCopyConstructor() 10919 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10920 : ClassDecl->hasTrivialCopyConstructor()); 10921 10922 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10923 SetDeclDeleted(CopyConstructor, ClassLoc); 10924 10925 // Note that we have declared this constructor. 10926 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10927 10928 if (Scope *S = getScopeForContext(ClassDecl)) 10929 PushOnScopeChains(CopyConstructor, S, false); 10930 ClassDecl->addDecl(CopyConstructor); 10931 10932 return CopyConstructor; 10933 } 10934 10935 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10936 CXXConstructorDecl *CopyConstructor) { 10937 assert((CopyConstructor->isDefaulted() && 10938 CopyConstructor->isCopyConstructor() && 10939 !CopyConstructor->doesThisDeclarationHaveABody() && 10940 !CopyConstructor->isDeleted()) && 10941 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10942 10943 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10944 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10945 10946 // C++11 [class.copy]p7: 10947 // The [definition of an implicitly declared copy constructor] is 10948 // deprecated if the class has a user-declared copy assignment operator 10949 // or a user-declared destructor. 10950 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10951 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10952 10953 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10954 DiagnosticErrorTrap Trap(Diags); 10955 10956 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10957 Trap.hasErrorOccurred()) { 10958 Diag(CurrentLocation, diag::note_member_synthesized_at) 10959 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10960 CopyConstructor->setInvalidDecl(); 10961 } else { 10962 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10963 ? CopyConstructor->getLocEnd() 10964 : CopyConstructor->getLocation(); 10965 Sema::CompoundScopeRAII CompoundScope(*this); 10966 CopyConstructor->setBody( 10967 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10968 } 10969 10970 // The exception specification is needed because we are defining the 10971 // function. 10972 ResolveExceptionSpec(CurrentLocation, 10973 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10974 10975 CopyConstructor->markUsed(Context); 10976 MarkVTableUsed(CurrentLocation, ClassDecl); 10977 10978 if (ASTMutationListener *L = getASTMutationListener()) { 10979 L->CompletedImplicitDefinition(CopyConstructor); 10980 } 10981 } 10982 10983 Sema::ImplicitExceptionSpecification 10984 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10985 CXXRecordDecl *ClassDecl = MD->getParent(); 10986 10987 // C++ [except.spec]p14: 10988 // An implicitly declared special member function (Clause 12) shall have an 10989 // exception-specification. [...] 10990 ImplicitExceptionSpecification ExceptSpec(*this); 10991 if (ClassDecl->isInvalidDecl()) 10992 return ExceptSpec; 10993 10994 // Direct base-class constructors. 10995 for (const auto &B : ClassDecl->bases()) { 10996 if (B.isVirtual()) // Handled below. 10997 continue; 10998 10999 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11000 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11001 CXXConstructorDecl *Constructor = 11002 LookupMovingConstructor(BaseClassDecl, 0); 11003 // If this is a deleted function, add it anyway. This might be conformant 11004 // with the standard. This might not. I'm not sure. It might not matter. 11005 if (Constructor) 11006 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11007 } 11008 } 11009 11010 // Virtual base-class constructors. 11011 for (const auto &B : ClassDecl->vbases()) { 11012 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11013 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11014 CXXConstructorDecl *Constructor = 11015 LookupMovingConstructor(BaseClassDecl, 0); 11016 // If this is a deleted function, add it anyway. This might be conformant 11017 // with the standard. This might not. I'm not sure. It might not matter. 11018 if (Constructor) 11019 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11020 } 11021 } 11022 11023 // Field constructors. 11024 for (const auto *F : ClassDecl->fields()) { 11025 QualType FieldType = Context.getBaseElementType(F->getType()); 11026 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 11027 CXXConstructorDecl *Constructor = 11028 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 11029 // If this is a deleted function, add it anyway. This might be conformant 11030 // with the standard. This might not. I'm not sure. It might not matter. 11031 // In particular, the problem is that this function never gets called. It 11032 // might just be ill-formed because this function attempts to refer to 11033 // a deleted function here. 11034 if (Constructor) 11035 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 11036 } 11037 } 11038 11039 return ExceptSpec; 11040 } 11041 11042 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 11043 CXXRecordDecl *ClassDecl) { 11044 assert(ClassDecl->needsImplicitMoveConstructor()); 11045 11046 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 11047 if (DSM.isAlreadyBeingDeclared()) 11048 return nullptr; 11049 11050 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11051 QualType ArgType = Context.getRValueReferenceType(ClassType); 11052 11053 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11054 CXXMoveConstructor, 11055 false); 11056 11057 DeclarationName Name 11058 = Context.DeclarationNames.getCXXConstructorName( 11059 Context.getCanonicalType(ClassType)); 11060 SourceLocation ClassLoc = ClassDecl->getLocation(); 11061 DeclarationNameInfo NameInfo(Name, ClassLoc); 11062 11063 // C++11 [class.copy]p11: 11064 // An implicitly-declared copy/move constructor is an inline public 11065 // member of its class. 11066 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 11067 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11068 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11069 Constexpr); 11070 MoveConstructor->setAccess(AS_public); 11071 MoveConstructor->setDefaulted(); 11072 11073 if (getLangOpts().CUDA) { 11074 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 11075 MoveConstructor, 11076 /* ConstRHS */ false, 11077 /* Diagnose */ false); 11078 } 11079 11080 // Build an exception specification pointing back at this member. 11081 FunctionProtoType::ExtProtoInfo EPI = 11082 getImplicitMethodEPI(*this, MoveConstructor); 11083 MoveConstructor->setType( 11084 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11085 11086 // Add the parameter to the constructor. 11087 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 11088 ClassLoc, ClassLoc, 11089 /*IdentifierInfo=*/nullptr, 11090 ArgType, /*TInfo=*/nullptr, 11091 SC_None, nullptr); 11092 MoveConstructor->setParams(FromParam); 11093 11094 MoveConstructor->setTrivial( 11095 ClassDecl->needsOverloadResolutionForMoveConstructor() 11096 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 11097 : ClassDecl->hasTrivialMoveConstructor()); 11098 11099 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 11100 ClassDecl->setImplicitMoveConstructorIsDeleted(); 11101 SetDeclDeleted(MoveConstructor, ClassLoc); 11102 } 11103 11104 // Note that we have declared this constructor. 11105 ++ASTContext::NumImplicitMoveConstructorsDeclared; 11106 11107 if (Scope *S = getScopeForContext(ClassDecl)) 11108 PushOnScopeChains(MoveConstructor, S, false); 11109 ClassDecl->addDecl(MoveConstructor); 11110 11111 return MoveConstructor; 11112 } 11113 11114 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 11115 CXXConstructorDecl *MoveConstructor) { 11116 assert((MoveConstructor->isDefaulted() && 11117 MoveConstructor->isMoveConstructor() && 11118 !MoveConstructor->doesThisDeclarationHaveABody() && 11119 !MoveConstructor->isDeleted()) && 11120 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 11121 11122 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 11123 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 11124 11125 SynthesizedFunctionScope Scope(*this, MoveConstructor); 11126 DiagnosticErrorTrap Trap(Diags); 11127 11128 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 11129 Trap.hasErrorOccurred()) { 11130 Diag(CurrentLocation, diag::note_member_synthesized_at) 11131 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 11132 MoveConstructor->setInvalidDecl(); 11133 } else { 11134 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 11135 ? MoveConstructor->getLocEnd() 11136 : MoveConstructor->getLocation(); 11137 Sema::CompoundScopeRAII CompoundScope(*this); 11138 MoveConstructor->setBody(ActOnCompoundStmt( 11139 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 11140 } 11141 11142 // The exception specification is needed because we are defining the 11143 // function. 11144 ResolveExceptionSpec(CurrentLocation, 11145 MoveConstructor->getType()->castAs<FunctionProtoType>()); 11146 11147 MoveConstructor->markUsed(Context); 11148 MarkVTableUsed(CurrentLocation, ClassDecl); 11149 11150 if (ASTMutationListener *L = getASTMutationListener()) { 11151 L->CompletedImplicitDefinition(MoveConstructor); 11152 } 11153 } 11154 11155 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 11156 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 11157 } 11158 11159 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 11160 SourceLocation CurrentLocation, 11161 CXXConversionDecl *Conv) { 11162 CXXRecordDecl *Lambda = Conv->getParent(); 11163 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 11164 // If we are defining a specialization of a conversion to function-ptr 11165 // cache the deduced template arguments for this specialization 11166 // so that we can use them to retrieve the corresponding call-operator 11167 // and static-invoker. 11168 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 11169 11170 // Retrieve the corresponding call-operator specialization. 11171 if (Lambda->isGenericLambda()) { 11172 assert(Conv->isFunctionTemplateSpecialization()); 11173 FunctionTemplateDecl *CallOpTemplate = 11174 CallOp->getDescribedFunctionTemplate(); 11175 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 11176 void *InsertPos = nullptr; 11177 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 11178 DeducedTemplateArgs->asArray(), 11179 InsertPos); 11180 assert(CallOpSpec && 11181 "Conversion operator must have a corresponding call operator"); 11182 CallOp = cast<CXXMethodDecl>(CallOpSpec); 11183 } 11184 // Mark the call operator referenced (and add to pending instantiations 11185 // if necessary). 11186 // For both the conversion and static-invoker template specializations 11187 // we construct their body's in this function, so no need to add them 11188 // to the PendingInstantiations. 11189 MarkFunctionReferenced(CurrentLocation, CallOp); 11190 11191 SynthesizedFunctionScope Scope(*this, Conv); 11192 DiagnosticErrorTrap Trap(Diags); 11193 11194 // Retrieve the static invoker... 11195 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 11196 // ... and get the corresponding specialization for a generic lambda. 11197 if (Lambda->isGenericLambda()) { 11198 assert(DeducedTemplateArgs && 11199 "Must have deduced template arguments from Conversion Operator"); 11200 FunctionTemplateDecl *InvokeTemplate = 11201 Invoker->getDescribedFunctionTemplate(); 11202 void *InsertPos = nullptr; 11203 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 11204 DeducedTemplateArgs->asArray(), 11205 InsertPos); 11206 assert(InvokeSpec && 11207 "Must have a corresponding static invoker specialization"); 11208 Invoker = cast<CXXMethodDecl>(InvokeSpec); 11209 } 11210 // Construct the body of the conversion function { return __invoke; }. 11211 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 11212 VK_LValue, Conv->getLocation()).get(); 11213 assert(FunctionRef && "Can't refer to __invoke function?"); 11214 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 11215 Conv->setBody(new (Context) CompoundStmt(Context, Return, 11216 Conv->getLocation(), 11217 Conv->getLocation())); 11218 11219 Conv->markUsed(Context); 11220 Conv->setReferenced(); 11221 11222 // Fill in the __invoke function with a dummy implementation. IR generation 11223 // will fill in the actual details. 11224 Invoker->markUsed(Context); 11225 Invoker->setReferenced(); 11226 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 11227 11228 if (ASTMutationListener *L = getASTMutationListener()) { 11229 L->CompletedImplicitDefinition(Conv); 11230 L->CompletedImplicitDefinition(Invoker); 11231 } 11232 } 11233 11234 11235 11236 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11237 SourceLocation CurrentLocation, 11238 CXXConversionDecl *Conv) 11239 { 11240 assert(!Conv->getParent()->isGenericLambda()); 11241 11242 Conv->markUsed(Context); 11243 11244 SynthesizedFunctionScope Scope(*this, Conv); 11245 DiagnosticErrorTrap Trap(Diags); 11246 11247 // Copy-initialize the lambda object as needed to capture it. 11248 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11249 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11250 11251 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11252 Conv->getLocation(), 11253 Conv, DerefThis); 11254 11255 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11256 // behavior. Note that only the general conversion function does this 11257 // (since it's unusable otherwise); in the case where we inline the 11258 // block literal, it has block literal lifetime semantics. 11259 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11260 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11261 CK_CopyAndAutoreleaseBlockObject, 11262 BuildBlock.get(), nullptr, VK_RValue); 11263 11264 if (BuildBlock.isInvalid()) { 11265 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11266 Conv->setInvalidDecl(); 11267 return; 11268 } 11269 11270 // Create the return statement that returns the block from the conversion 11271 // function. 11272 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11273 if (Return.isInvalid()) { 11274 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11275 Conv->setInvalidDecl(); 11276 return; 11277 } 11278 11279 // Set the body of the conversion function. 11280 Stmt *ReturnS = Return.get(); 11281 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11282 Conv->getLocation(), 11283 Conv->getLocation())); 11284 11285 // We're done; notify the mutation listener, if any. 11286 if (ASTMutationListener *L = getASTMutationListener()) { 11287 L->CompletedImplicitDefinition(Conv); 11288 } 11289 } 11290 11291 /// \brief Determine whether the given list arguments contains exactly one 11292 /// "real" (non-default) argument. 11293 static bool hasOneRealArgument(MultiExprArg Args) { 11294 switch (Args.size()) { 11295 case 0: 11296 return false; 11297 11298 default: 11299 if (!Args[1]->isDefaultArgument()) 11300 return false; 11301 11302 // fall through 11303 case 1: 11304 return !Args[0]->isDefaultArgument(); 11305 } 11306 11307 return false; 11308 } 11309 11310 ExprResult 11311 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11312 CXXConstructorDecl *Constructor, 11313 MultiExprArg ExprArgs, 11314 bool HadMultipleCandidates, 11315 bool IsListInitialization, 11316 bool IsStdInitListInitialization, 11317 bool RequiresZeroInit, 11318 unsigned ConstructKind, 11319 SourceRange ParenRange) { 11320 bool Elidable = false; 11321 11322 // C++0x [class.copy]p34: 11323 // When certain criteria are met, an implementation is allowed to 11324 // omit the copy/move construction of a class object, even if the 11325 // copy/move constructor and/or destructor for the object have 11326 // side effects. [...] 11327 // - when a temporary class object that has not been bound to a 11328 // reference (12.2) would be copied/moved to a class object 11329 // with the same cv-unqualified type, the copy/move operation 11330 // can be omitted by constructing the temporary object 11331 // directly into the target of the omitted copy/move 11332 if (ConstructKind == CXXConstructExpr::CK_Complete && 11333 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11334 Expr *SubExpr = ExprArgs[0]; 11335 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11336 } 11337 11338 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11339 Elidable, ExprArgs, HadMultipleCandidates, 11340 IsListInitialization, 11341 IsStdInitListInitialization, RequiresZeroInit, 11342 ConstructKind, ParenRange); 11343 } 11344 11345 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11346 /// including handling of its default argument expressions. 11347 ExprResult 11348 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11349 CXXConstructorDecl *Constructor, bool Elidable, 11350 MultiExprArg ExprArgs, 11351 bool HadMultipleCandidates, 11352 bool IsListInitialization, 11353 bool IsStdInitListInitialization, 11354 bool RequiresZeroInit, 11355 unsigned ConstructKind, 11356 SourceRange ParenRange) { 11357 MarkFunctionReferenced(ConstructLoc, Constructor); 11358 return CXXConstructExpr::Create( 11359 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11360 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11361 RequiresZeroInit, 11362 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11363 ParenRange); 11364 } 11365 11366 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11367 assert(Field->hasInClassInitializer()); 11368 11369 // If we already have the in-class initializer nothing needs to be done. 11370 if (Field->getInClassInitializer()) 11371 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11372 11373 // Maybe we haven't instantiated the in-class initializer. Go check the 11374 // pattern FieldDecl to see if it has one. 11375 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11376 11377 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11378 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11379 DeclContext::lookup_result Lookup = 11380 ClassPattern->lookup(Field->getDeclName()); 11381 assert(Lookup.size() == 1); 11382 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11383 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11384 getTemplateInstantiationArgs(Field))) 11385 return ExprError(); 11386 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11387 } 11388 11389 // DR1351: 11390 // If the brace-or-equal-initializer of a non-static data member 11391 // invokes a defaulted default constructor of its class or of an 11392 // enclosing class in a potentially evaluated subexpression, the 11393 // program is ill-formed. 11394 // 11395 // This resolution is unworkable: the exception specification of the 11396 // default constructor can be needed in an unevaluated context, in 11397 // particular, in the operand of a noexcept-expression, and we can be 11398 // unable to compute an exception specification for an enclosed class. 11399 // 11400 // Any attempt to resolve the exception specification of a defaulted default 11401 // constructor before the initializer is lexically complete will ultimately 11402 // come here at which point we can diagnose it. 11403 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11404 if (OutermostClass == ParentRD) { 11405 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11406 << ParentRD << Field; 11407 } else { 11408 Diag(Field->getLocEnd(), 11409 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11410 << ParentRD << OutermostClass << Field; 11411 } 11412 11413 return ExprError(); 11414 } 11415 11416 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11417 if (VD->isInvalidDecl()) return; 11418 11419 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11420 if (ClassDecl->isInvalidDecl()) return; 11421 if (ClassDecl->hasIrrelevantDestructor()) return; 11422 if (ClassDecl->isDependentContext()) return; 11423 11424 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11425 MarkFunctionReferenced(VD->getLocation(), Destructor); 11426 CheckDestructorAccess(VD->getLocation(), Destructor, 11427 PDiag(diag::err_access_dtor_var) 11428 << VD->getDeclName() 11429 << VD->getType()); 11430 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11431 11432 if (Destructor->isTrivial()) return; 11433 if (!VD->hasGlobalStorage()) return; 11434 11435 // Emit warning for non-trivial dtor in global scope (a real global, 11436 // class-static, function-static). 11437 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11438 11439 // TODO: this should be re-enabled for static locals by !CXAAtExit 11440 if (!VD->isStaticLocal()) 11441 Diag(VD->getLocation(), diag::warn_global_destructor); 11442 } 11443 11444 /// \brief Given a constructor and the set of arguments provided for the 11445 /// constructor, convert the arguments and add any required default arguments 11446 /// to form a proper call to this constructor. 11447 /// 11448 /// \returns true if an error occurred, false otherwise. 11449 bool 11450 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11451 MultiExprArg ArgsPtr, 11452 SourceLocation Loc, 11453 SmallVectorImpl<Expr*> &ConvertedArgs, 11454 bool AllowExplicit, 11455 bool IsListInitialization) { 11456 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11457 unsigned NumArgs = ArgsPtr.size(); 11458 Expr **Args = ArgsPtr.data(); 11459 11460 const FunctionProtoType *Proto 11461 = Constructor->getType()->getAs<FunctionProtoType>(); 11462 assert(Proto && "Constructor without a prototype?"); 11463 unsigned NumParams = Proto->getNumParams(); 11464 11465 // If too few arguments are available, we'll fill in the rest with defaults. 11466 if (NumArgs < NumParams) 11467 ConvertedArgs.reserve(NumParams); 11468 else 11469 ConvertedArgs.reserve(NumArgs); 11470 11471 VariadicCallType CallType = 11472 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11473 SmallVector<Expr *, 8> AllArgs; 11474 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11475 Proto, 0, 11476 llvm::makeArrayRef(Args, NumArgs), 11477 AllArgs, 11478 CallType, AllowExplicit, 11479 IsListInitialization); 11480 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11481 11482 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11483 11484 CheckConstructorCall(Constructor, 11485 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11486 Proto, Loc); 11487 11488 return Invalid; 11489 } 11490 11491 static inline bool 11492 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11493 const FunctionDecl *FnDecl) { 11494 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11495 if (isa<NamespaceDecl>(DC)) { 11496 return SemaRef.Diag(FnDecl->getLocation(), 11497 diag::err_operator_new_delete_declared_in_namespace) 11498 << FnDecl->getDeclName(); 11499 } 11500 11501 if (isa<TranslationUnitDecl>(DC) && 11502 FnDecl->getStorageClass() == SC_Static) { 11503 return SemaRef.Diag(FnDecl->getLocation(), 11504 diag::err_operator_new_delete_declared_static) 11505 << FnDecl->getDeclName(); 11506 } 11507 11508 return false; 11509 } 11510 11511 static inline bool 11512 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11513 CanQualType ExpectedResultType, 11514 CanQualType ExpectedFirstParamType, 11515 unsigned DependentParamTypeDiag, 11516 unsigned InvalidParamTypeDiag) { 11517 QualType ResultType = 11518 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11519 11520 // Check that the result type is not dependent. 11521 if (ResultType->isDependentType()) 11522 return SemaRef.Diag(FnDecl->getLocation(), 11523 diag::err_operator_new_delete_dependent_result_type) 11524 << FnDecl->getDeclName() << ExpectedResultType; 11525 11526 // Check that the result type is what we expect. 11527 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11528 return SemaRef.Diag(FnDecl->getLocation(), 11529 diag::err_operator_new_delete_invalid_result_type) 11530 << FnDecl->getDeclName() << ExpectedResultType; 11531 11532 // A function template must have at least 2 parameters. 11533 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11534 return SemaRef.Diag(FnDecl->getLocation(), 11535 diag::err_operator_new_delete_template_too_few_parameters) 11536 << FnDecl->getDeclName(); 11537 11538 // The function decl must have at least 1 parameter. 11539 if (FnDecl->getNumParams() == 0) 11540 return SemaRef.Diag(FnDecl->getLocation(), 11541 diag::err_operator_new_delete_too_few_parameters) 11542 << FnDecl->getDeclName(); 11543 11544 // Check the first parameter type is not dependent. 11545 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11546 if (FirstParamType->isDependentType()) 11547 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11548 << FnDecl->getDeclName() << ExpectedFirstParamType; 11549 11550 // Check that the first parameter type is what we expect. 11551 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11552 ExpectedFirstParamType) 11553 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11554 << FnDecl->getDeclName() << ExpectedFirstParamType; 11555 11556 return false; 11557 } 11558 11559 static bool 11560 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11561 // C++ [basic.stc.dynamic.allocation]p1: 11562 // A program is ill-formed if an allocation function is declared in a 11563 // namespace scope other than global scope or declared static in global 11564 // scope. 11565 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11566 return true; 11567 11568 CanQualType SizeTy = 11569 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11570 11571 // C++ [basic.stc.dynamic.allocation]p1: 11572 // The return type shall be void*. The first parameter shall have type 11573 // std::size_t. 11574 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11575 SizeTy, 11576 diag::err_operator_new_dependent_param_type, 11577 diag::err_operator_new_param_type)) 11578 return true; 11579 11580 // C++ [basic.stc.dynamic.allocation]p1: 11581 // The first parameter shall not have an associated default argument. 11582 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11583 return SemaRef.Diag(FnDecl->getLocation(), 11584 diag::err_operator_new_default_arg) 11585 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11586 11587 return false; 11588 } 11589 11590 static bool 11591 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11592 // C++ [basic.stc.dynamic.deallocation]p1: 11593 // A program is ill-formed if deallocation functions are declared in a 11594 // namespace scope other than global scope or declared static in global 11595 // scope. 11596 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11597 return true; 11598 11599 // C++ [basic.stc.dynamic.deallocation]p2: 11600 // Each deallocation function shall return void and its first parameter 11601 // shall be void*. 11602 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11603 SemaRef.Context.VoidPtrTy, 11604 diag::err_operator_delete_dependent_param_type, 11605 diag::err_operator_delete_param_type)) 11606 return true; 11607 11608 return false; 11609 } 11610 11611 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11612 /// of this overloaded operator is well-formed. If so, returns false; 11613 /// otherwise, emits appropriate diagnostics and returns true. 11614 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11615 assert(FnDecl && FnDecl->isOverloadedOperator() && 11616 "Expected an overloaded operator declaration"); 11617 11618 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11619 11620 // C++ [over.oper]p5: 11621 // The allocation and deallocation functions, operator new, 11622 // operator new[], operator delete and operator delete[], are 11623 // described completely in 3.7.3. The attributes and restrictions 11624 // found in the rest of this subclause do not apply to them unless 11625 // explicitly stated in 3.7.3. 11626 if (Op == OO_Delete || Op == OO_Array_Delete) 11627 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11628 11629 if (Op == OO_New || Op == OO_Array_New) 11630 return CheckOperatorNewDeclaration(*this, FnDecl); 11631 11632 // C++ [over.oper]p6: 11633 // An operator function shall either be a non-static member 11634 // function or be a non-member function and have at least one 11635 // parameter whose type is a class, a reference to a class, an 11636 // enumeration, or a reference to an enumeration. 11637 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11638 if (MethodDecl->isStatic()) 11639 return Diag(FnDecl->getLocation(), 11640 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11641 } else { 11642 bool ClassOrEnumParam = false; 11643 for (auto Param : FnDecl->params()) { 11644 QualType ParamType = Param->getType().getNonReferenceType(); 11645 if (ParamType->isDependentType() || ParamType->isRecordType() || 11646 ParamType->isEnumeralType()) { 11647 ClassOrEnumParam = true; 11648 break; 11649 } 11650 } 11651 11652 if (!ClassOrEnumParam) 11653 return Diag(FnDecl->getLocation(), 11654 diag::err_operator_overload_needs_class_or_enum) 11655 << FnDecl->getDeclName(); 11656 } 11657 11658 // C++ [over.oper]p8: 11659 // An operator function cannot have default arguments (8.3.6), 11660 // except where explicitly stated below. 11661 // 11662 // Only the function-call operator allows default arguments 11663 // (C++ [over.call]p1). 11664 if (Op != OO_Call) { 11665 for (auto Param : FnDecl->params()) { 11666 if (Param->hasDefaultArg()) 11667 return Diag(Param->getLocation(), 11668 diag::err_operator_overload_default_arg) 11669 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11670 } 11671 } 11672 11673 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11674 { false, false, false } 11675 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11676 , { Unary, Binary, MemberOnly } 11677 #include "clang/Basic/OperatorKinds.def" 11678 }; 11679 11680 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11681 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11682 bool MustBeMemberOperator = OperatorUses[Op][2]; 11683 11684 // C++ [over.oper]p8: 11685 // [...] Operator functions cannot have more or fewer parameters 11686 // than the number required for the corresponding operator, as 11687 // described in the rest of this subclause. 11688 unsigned NumParams = FnDecl->getNumParams() 11689 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11690 if (Op != OO_Call && 11691 ((NumParams == 1 && !CanBeUnaryOperator) || 11692 (NumParams == 2 && !CanBeBinaryOperator) || 11693 (NumParams < 1) || (NumParams > 2))) { 11694 // We have the wrong number of parameters. 11695 unsigned ErrorKind; 11696 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11697 ErrorKind = 2; // 2 -> unary or binary. 11698 } else if (CanBeUnaryOperator) { 11699 ErrorKind = 0; // 0 -> unary 11700 } else { 11701 assert(CanBeBinaryOperator && 11702 "All non-call overloaded operators are unary or binary!"); 11703 ErrorKind = 1; // 1 -> binary 11704 } 11705 11706 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11707 << FnDecl->getDeclName() << NumParams << ErrorKind; 11708 } 11709 11710 // Overloaded operators other than operator() cannot be variadic. 11711 if (Op != OO_Call && 11712 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11713 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11714 << FnDecl->getDeclName(); 11715 } 11716 11717 // Some operators must be non-static member functions. 11718 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11719 return Diag(FnDecl->getLocation(), 11720 diag::err_operator_overload_must_be_member) 11721 << FnDecl->getDeclName(); 11722 } 11723 11724 // C++ [over.inc]p1: 11725 // The user-defined function called operator++ implements the 11726 // prefix and postfix ++ operator. If this function is a member 11727 // function with no parameters, or a non-member function with one 11728 // parameter of class or enumeration type, it defines the prefix 11729 // increment operator ++ for objects of that type. If the function 11730 // is a member function with one parameter (which shall be of type 11731 // int) or a non-member function with two parameters (the second 11732 // of which shall be of type int), it defines the postfix 11733 // increment operator ++ for objects of that type. 11734 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11735 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11736 QualType ParamType = LastParam->getType(); 11737 11738 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11739 !ParamType->isDependentType()) 11740 return Diag(LastParam->getLocation(), 11741 diag::err_operator_overload_post_incdec_must_be_int) 11742 << LastParam->getType() << (Op == OO_MinusMinus); 11743 } 11744 11745 return false; 11746 } 11747 11748 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11749 /// of this literal operator function is well-formed. If so, returns 11750 /// false; otherwise, emits appropriate diagnostics and returns true. 11751 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11752 if (isa<CXXMethodDecl>(FnDecl)) { 11753 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11754 << FnDecl->getDeclName(); 11755 return true; 11756 } 11757 11758 if (FnDecl->isExternC()) { 11759 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11760 return true; 11761 } 11762 11763 bool Valid = false; 11764 11765 // This might be the definition of a literal operator template. 11766 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11767 // This might be a specialization of a literal operator template. 11768 if (!TpDecl) 11769 TpDecl = FnDecl->getPrimaryTemplate(); 11770 11771 // template <char...> type operator "" name() and 11772 // template <class T, T...> type operator "" name() are the only valid 11773 // template signatures, and the only valid signatures with no parameters. 11774 if (TpDecl) { 11775 if (FnDecl->param_size() == 0) { 11776 // Must have one or two template parameters 11777 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11778 if (Params->size() == 1) { 11779 NonTypeTemplateParmDecl *PmDecl = 11780 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11781 11782 // The template parameter must be a char parameter pack. 11783 if (PmDecl && PmDecl->isTemplateParameterPack() && 11784 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11785 Valid = true; 11786 } else if (Params->size() == 2) { 11787 TemplateTypeParmDecl *PmType = 11788 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11789 NonTypeTemplateParmDecl *PmArgs = 11790 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11791 11792 // The second template parameter must be a parameter pack with the 11793 // first template parameter as its type. 11794 if (PmType && PmArgs && 11795 !PmType->isTemplateParameterPack() && 11796 PmArgs->isTemplateParameterPack()) { 11797 const TemplateTypeParmType *TArgs = 11798 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11799 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11800 TArgs->getIndex() == PmType->getIndex()) { 11801 Valid = true; 11802 if (ActiveTemplateInstantiations.empty()) 11803 Diag(FnDecl->getLocation(), 11804 diag::ext_string_literal_operator_template); 11805 } 11806 } 11807 } 11808 } 11809 } else if (FnDecl->param_size()) { 11810 // Check the first parameter 11811 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11812 11813 QualType T = (*Param)->getType().getUnqualifiedType(); 11814 11815 // unsigned long long int, long double, and any character type are allowed 11816 // as the only parameters. 11817 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11818 Context.hasSameType(T, Context.LongDoubleTy) || 11819 Context.hasSameType(T, Context.CharTy) || 11820 Context.hasSameType(T, Context.WideCharTy) || 11821 Context.hasSameType(T, Context.Char16Ty) || 11822 Context.hasSameType(T, Context.Char32Ty)) { 11823 if (++Param == FnDecl->param_end()) 11824 Valid = true; 11825 goto FinishedParams; 11826 } 11827 11828 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11829 const PointerType *PT = T->getAs<PointerType>(); 11830 if (!PT) 11831 goto FinishedParams; 11832 T = PT->getPointeeType(); 11833 if (!T.isConstQualified() || T.isVolatileQualified()) 11834 goto FinishedParams; 11835 T = T.getUnqualifiedType(); 11836 11837 // Move on to the second parameter; 11838 ++Param; 11839 11840 // If there is no second parameter, the first must be a const char * 11841 if (Param == FnDecl->param_end()) { 11842 if (Context.hasSameType(T, Context.CharTy)) 11843 Valid = true; 11844 goto FinishedParams; 11845 } 11846 11847 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11848 // are allowed as the first parameter to a two-parameter function 11849 if (!(Context.hasSameType(T, Context.CharTy) || 11850 Context.hasSameType(T, Context.WideCharTy) || 11851 Context.hasSameType(T, Context.Char16Ty) || 11852 Context.hasSameType(T, Context.Char32Ty))) 11853 goto FinishedParams; 11854 11855 // The second and final parameter must be an std::size_t 11856 T = (*Param)->getType().getUnqualifiedType(); 11857 if (Context.hasSameType(T, Context.getSizeType()) && 11858 ++Param == FnDecl->param_end()) 11859 Valid = true; 11860 } 11861 11862 // FIXME: This diagnostic is absolutely terrible. 11863 FinishedParams: 11864 if (!Valid) { 11865 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11866 << FnDecl->getDeclName(); 11867 return true; 11868 } 11869 11870 // A parameter-declaration-clause containing a default argument is not 11871 // equivalent to any of the permitted forms. 11872 for (auto Param : FnDecl->params()) { 11873 if (Param->hasDefaultArg()) { 11874 Diag(Param->getDefaultArgRange().getBegin(), 11875 diag::err_literal_operator_default_argument) 11876 << Param->getDefaultArgRange(); 11877 break; 11878 } 11879 } 11880 11881 StringRef LiteralName 11882 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11883 if (LiteralName[0] != '_') { 11884 // C++11 [usrlit.suffix]p1: 11885 // Literal suffix identifiers that do not start with an underscore 11886 // are reserved for future standardization. 11887 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11888 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11889 } 11890 11891 return false; 11892 } 11893 11894 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11895 /// linkage specification, including the language and (if present) 11896 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11897 /// language string literal. LBraceLoc, if valid, provides the location of 11898 /// the '{' brace. Otherwise, this linkage specification does not 11899 /// have any braces. 11900 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11901 Expr *LangStr, 11902 SourceLocation LBraceLoc) { 11903 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11904 if (!Lit->isAscii()) { 11905 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11906 << LangStr->getSourceRange(); 11907 return nullptr; 11908 } 11909 11910 StringRef Lang = Lit->getString(); 11911 LinkageSpecDecl::LanguageIDs Language; 11912 if (Lang == "C") 11913 Language = LinkageSpecDecl::lang_c; 11914 else if (Lang == "C++") 11915 Language = LinkageSpecDecl::lang_cxx; 11916 else { 11917 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11918 << LangStr->getSourceRange(); 11919 return nullptr; 11920 } 11921 11922 // FIXME: Add all the various semantics of linkage specifications 11923 11924 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11925 LangStr->getExprLoc(), Language, 11926 LBraceLoc.isValid()); 11927 CurContext->addDecl(D); 11928 PushDeclContext(S, D); 11929 return D; 11930 } 11931 11932 /// ActOnFinishLinkageSpecification - Complete the definition of 11933 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11934 /// valid, it's the position of the closing '}' brace in a linkage 11935 /// specification that uses braces. 11936 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11937 Decl *LinkageSpec, 11938 SourceLocation RBraceLoc) { 11939 if (RBraceLoc.isValid()) { 11940 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11941 LSDecl->setRBraceLoc(RBraceLoc); 11942 } 11943 PopDeclContext(); 11944 return LinkageSpec; 11945 } 11946 11947 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11948 AttributeList *AttrList, 11949 SourceLocation SemiLoc) { 11950 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11951 // Attribute declarations appertain to empty declaration so we handle 11952 // them here. 11953 if (AttrList) 11954 ProcessDeclAttributeList(S, ED, AttrList); 11955 11956 CurContext->addDecl(ED); 11957 return ED; 11958 } 11959 11960 /// \brief Perform semantic analysis for the variable declaration that 11961 /// occurs within a C++ catch clause, returning the newly-created 11962 /// variable. 11963 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11964 TypeSourceInfo *TInfo, 11965 SourceLocation StartLoc, 11966 SourceLocation Loc, 11967 IdentifierInfo *Name) { 11968 bool Invalid = false; 11969 QualType ExDeclType = TInfo->getType(); 11970 11971 // Arrays and functions decay. 11972 if (ExDeclType->isArrayType()) 11973 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11974 else if (ExDeclType->isFunctionType()) 11975 ExDeclType = Context.getPointerType(ExDeclType); 11976 11977 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11978 // The exception-declaration shall not denote a pointer or reference to an 11979 // incomplete type, other than [cv] void*. 11980 // N2844 forbids rvalue references. 11981 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11982 Diag(Loc, diag::err_catch_rvalue_ref); 11983 Invalid = true; 11984 } 11985 11986 QualType BaseType = ExDeclType; 11987 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11988 unsigned DK = diag::err_catch_incomplete; 11989 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11990 BaseType = Ptr->getPointeeType(); 11991 Mode = 1; 11992 DK = diag::err_catch_incomplete_ptr; 11993 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11994 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11995 BaseType = Ref->getPointeeType(); 11996 Mode = 2; 11997 DK = diag::err_catch_incomplete_ref; 11998 } 11999 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 12000 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 12001 Invalid = true; 12002 12003 if (!Invalid && !ExDeclType->isDependentType() && 12004 RequireNonAbstractType(Loc, ExDeclType, 12005 diag::err_abstract_type_in_decl, 12006 AbstractVariableType)) 12007 Invalid = true; 12008 12009 // Only the non-fragile NeXT runtime currently supports C++ catches 12010 // of ObjC types, and no runtime supports catching ObjC types by value. 12011 if (!Invalid && getLangOpts().ObjC1) { 12012 QualType T = ExDeclType; 12013 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 12014 T = RT->getPointeeType(); 12015 12016 if (T->isObjCObjectType()) { 12017 Diag(Loc, diag::err_objc_object_catch); 12018 Invalid = true; 12019 } else if (T->isObjCObjectPointerType()) { 12020 // FIXME: should this be a test for macosx-fragile specifically? 12021 if (getLangOpts().ObjCRuntime.isFragile()) 12022 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 12023 } 12024 } 12025 12026 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 12027 ExDeclType, TInfo, SC_None); 12028 ExDecl->setExceptionVariable(true); 12029 12030 // In ARC, infer 'retaining' for variables of retainable type. 12031 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 12032 Invalid = true; 12033 12034 if (!Invalid && !ExDeclType->isDependentType()) { 12035 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 12036 // Insulate this from anything else we might currently be parsing. 12037 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 12038 12039 // C++ [except.handle]p16: 12040 // The object declared in an exception-declaration or, if the 12041 // exception-declaration does not specify a name, a temporary (12.2) is 12042 // copy-initialized (8.5) from the exception object. [...] 12043 // The object is destroyed when the handler exits, after the destruction 12044 // of any automatic objects initialized within the handler. 12045 // 12046 // We just pretend to initialize the object with itself, then make sure 12047 // it can be destroyed later. 12048 QualType initType = Context.getExceptionObjectType(ExDeclType); 12049 12050 InitializedEntity entity = 12051 InitializedEntity::InitializeVariable(ExDecl); 12052 InitializationKind initKind = 12053 InitializationKind::CreateCopy(Loc, SourceLocation()); 12054 12055 Expr *opaqueValue = 12056 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 12057 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 12058 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 12059 if (result.isInvalid()) 12060 Invalid = true; 12061 else { 12062 // If the constructor used was non-trivial, set this as the 12063 // "initializer". 12064 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 12065 if (!construct->getConstructor()->isTrivial()) { 12066 Expr *init = MaybeCreateExprWithCleanups(construct); 12067 ExDecl->setInit(init); 12068 } 12069 12070 // And make sure it's destructable. 12071 FinalizeVarWithDestructor(ExDecl, recordType); 12072 } 12073 } 12074 } 12075 12076 if (Invalid) 12077 ExDecl->setInvalidDecl(); 12078 12079 return ExDecl; 12080 } 12081 12082 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 12083 /// handler. 12084 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 12085 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12086 bool Invalid = D.isInvalidType(); 12087 12088 // Check for unexpanded parameter packs. 12089 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12090 UPPC_ExceptionType)) { 12091 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12092 D.getIdentifierLoc()); 12093 Invalid = true; 12094 } 12095 12096 IdentifierInfo *II = D.getIdentifier(); 12097 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 12098 LookupOrdinaryName, 12099 ForRedeclaration)) { 12100 // The scope should be freshly made just for us. There is just no way 12101 // it contains any previous declaration, except for function parameters in 12102 // a function-try-block's catch statement. 12103 assert(!S->isDeclScope(PrevDecl)); 12104 if (isDeclInScope(PrevDecl, CurContext, S)) { 12105 Diag(D.getIdentifierLoc(), diag::err_redefinition) 12106 << D.getIdentifier(); 12107 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12108 Invalid = true; 12109 } else if (PrevDecl->isTemplateParameter()) 12110 // Maybe we will complain about the shadowed template parameter. 12111 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12112 } 12113 12114 if (D.getCXXScopeSpec().isSet() && !Invalid) { 12115 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 12116 << D.getCXXScopeSpec().getRange(); 12117 Invalid = true; 12118 } 12119 12120 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 12121 D.getLocStart(), 12122 D.getIdentifierLoc(), 12123 D.getIdentifier()); 12124 if (Invalid) 12125 ExDecl->setInvalidDecl(); 12126 12127 // Add the exception declaration into this scope. 12128 if (II) 12129 PushOnScopeChains(ExDecl, S); 12130 else 12131 CurContext->addDecl(ExDecl); 12132 12133 ProcessDeclAttributes(S, ExDecl, D); 12134 return ExDecl; 12135 } 12136 12137 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12138 Expr *AssertExpr, 12139 Expr *AssertMessageExpr, 12140 SourceLocation RParenLoc) { 12141 StringLiteral *AssertMessage = 12142 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 12143 12144 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 12145 return nullptr; 12146 12147 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 12148 AssertMessage, RParenLoc, false); 12149 } 12150 12151 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12152 Expr *AssertExpr, 12153 StringLiteral *AssertMessage, 12154 SourceLocation RParenLoc, 12155 bool Failed) { 12156 assert(AssertExpr != nullptr && "Expected non-null condition"); 12157 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 12158 !Failed) { 12159 // In a static_assert-declaration, the constant-expression shall be a 12160 // constant expression that can be contextually converted to bool. 12161 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 12162 if (Converted.isInvalid()) 12163 Failed = true; 12164 12165 llvm::APSInt Cond; 12166 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 12167 diag::err_static_assert_expression_is_not_constant, 12168 /*AllowFold=*/false).isInvalid()) 12169 Failed = true; 12170 12171 if (!Failed && !Cond) { 12172 SmallString<256> MsgBuffer; 12173 llvm::raw_svector_ostream Msg(MsgBuffer); 12174 if (AssertMessage) 12175 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 12176 Diag(StaticAssertLoc, diag::err_static_assert_failed) 12177 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 12178 Failed = true; 12179 } 12180 } 12181 12182 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 12183 AssertExpr, AssertMessage, RParenLoc, 12184 Failed); 12185 12186 CurContext->addDecl(Decl); 12187 return Decl; 12188 } 12189 12190 /// \brief Perform semantic analysis of the given friend type declaration. 12191 /// 12192 /// \returns A friend declaration that. 12193 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 12194 SourceLocation FriendLoc, 12195 TypeSourceInfo *TSInfo) { 12196 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 12197 12198 QualType T = TSInfo->getType(); 12199 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 12200 12201 // C++03 [class.friend]p2: 12202 // An elaborated-type-specifier shall be used in a friend declaration 12203 // for a class.* 12204 // 12205 // * The class-key of the elaborated-type-specifier is required. 12206 if (!ActiveTemplateInstantiations.empty()) { 12207 // Do not complain about the form of friend template types during 12208 // template instantiation; we will already have complained when the 12209 // template was declared. 12210 } else { 12211 if (!T->isElaboratedTypeSpecifier()) { 12212 // If we evaluated the type to a record type, suggest putting 12213 // a tag in front. 12214 if (const RecordType *RT = T->getAs<RecordType>()) { 12215 RecordDecl *RD = RT->getDecl(); 12216 12217 SmallString<16> InsertionText(" "); 12218 InsertionText += RD->getKindName(); 12219 12220 Diag(TypeRange.getBegin(), 12221 getLangOpts().CPlusPlus11 ? 12222 diag::warn_cxx98_compat_unelaborated_friend_type : 12223 diag::ext_unelaborated_friend_type) 12224 << (unsigned) RD->getTagKind() 12225 << T 12226 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 12227 InsertionText); 12228 } else { 12229 Diag(FriendLoc, 12230 getLangOpts().CPlusPlus11 ? 12231 diag::warn_cxx98_compat_nonclass_type_friend : 12232 diag::ext_nonclass_type_friend) 12233 << T 12234 << TypeRange; 12235 } 12236 } else if (T->getAs<EnumType>()) { 12237 Diag(FriendLoc, 12238 getLangOpts().CPlusPlus11 ? 12239 diag::warn_cxx98_compat_enum_friend : 12240 diag::ext_enum_friend) 12241 << T 12242 << TypeRange; 12243 } 12244 12245 // C++11 [class.friend]p3: 12246 // A friend declaration that does not declare a function shall have one 12247 // of the following forms: 12248 // friend elaborated-type-specifier ; 12249 // friend simple-type-specifier ; 12250 // friend typename-specifier ; 12251 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12252 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12253 } 12254 12255 // If the type specifier in a friend declaration designates a (possibly 12256 // cv-qualified) class type, that class is declared as a friend; otherwise, 12257 // the friend declaration is ignored. 12258 return FriendDecl::Create(Context, CurContext, 12259 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12260 FriendLoc); 12261 } 12262 12263 /// Handle a friend tag declaration where the scope specifier was 12264 /// templated. 12265 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12266 unsigned TagSpec, SourceLocation TagLoc, 12267 CXXScopeSpec &SS, 12268 IdentifierInfo *Name, 12269 SourceLocation NameLoc, 12270 AttributeList *Attr, 12271 MultiTemplateParamsArg TempParamLists) { 12272 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12273 12274 bool isExplicitSpecialization = false; 12275 bool Invalid = false; 12276 12277 if (TemplateParameterList *TemplateParams = 12278 MatchTemplateParametersToScopeSpecifier( 12279 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12280 isExplicitSpecialization, Invalid)) { 12281 if (TemplateParams->size() > 0) { 12282 // This is a declaration of a class template. 12283 if (Invalid) 12284 return nullptr; 12285 12286 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12287 NameLoc, Attr, TemplateParams, AS_public, 12288 /*ModulePrivateLoc=*/SourceLocation(), 12289 FriendLoc, TempParamLists.size() - 1, 12290 TempParamLists.data()).get(); 12291 } else { 12292 // The "template<>" header is extraneous. 12293 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12294 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12295 isExplicitSpecialization = true; 12296 } 12297 } 12298 12299 if (Invalid) return nullptr; 12300 12301 bool isAllExplicitSpecializations = true; 12302 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12303 if (TempParamLists[I]->size()) { 12304 isAllExplicitSpecializations = false; 12305 break; 12306 } 12307 } 12308 12309 // FIXME: don't ignore attributes. 12310 12311 // If it's explicit specializations all the way down, just forget 12312 // about the template header and build an appropriate non-templated 12313 // friend. TODO: for source fidelity, remember the headers. 12314 if (isAllExplicitSpecializations) { 12315 if (SS.isEmpty()) { 12316 bool Owned = false; 12317 bool IsDependent = false; 12318 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12319 Attr, AS_public, 12320 /*ModulePrivateLoc=*/SourceLocation(), 12321 MultiTemplateParamsArg(), Owned, IsDependent, 12322 /*ScopedEnumKWLoc=*/SourceLocation(), 12323 /*ScopedEnumUsesClassTag=*/false, 12324 /*UnderlyingType=*/TypeResult(), 12325 /*IsTypeSpecifier=*/false); 12326 } 12327 12328 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12329 ElaboratedTypeKeyword Keyword 12330 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12331 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12332 *Name, NameLoc); 12333 if (T.isNull()) 12334 return nullptr; 12335 12336 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12337 if (isa<DependentNameType>(T)) { 12338 DependentNameTypeLoc TL = 12339 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12340 TL.setElaboratedKeywordLoc(TagLoc); 12341 TL.setQualifierLoc(QualifierLoc); 12342 TL.setNameLoc(NameLoc); 12343 } else { 12344 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12345 TL.setElaboratedKeywordLoc(TagLoc); 12346 TL.setQualifierLoc(QualifierLoc); 12347 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12348 } 12349 12350 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12351 TSI, FriendLoc, TempParamLists); 12352 Friend->setAccess(AS_public); 12353 CurContext->addDecl(Friend); 12354 return Friend; 12355 } 12356 12357 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12358 12359 12360 12361 // Handle the case of a templated-scope friend class. e.g. 12362 // template <class T> class A<T>::B; 12363 // FIXME: we don't support these right now. 12364 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12365 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12366 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12367 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12368 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12369 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12370 TL.setElaboratedKeywordLoc(TagLoc); 12371 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12372 TL.setNameLoc(NameLoc); 12373 12374 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12375 TSI, FriendLoc, TempParamLists); 12376 Friend->setAccess(AS_public); 12377 Friend->setUnsupportedFriend(true); 12378 CurContext->addDecl(Friend); 12379 return Friend; 12380 } 12381 12382 12383 /// Handle a friend type declaration. This works in tandem with 12384 /// ActOnTag. 12385 /// 12386 /// Notes on friend class templates: 12387 /// 12388 /// We generally treat friend class declarations as if they were 12389 /// declaring a class. So, for example, the elaborated type specifier 12390 /// in a friend declaration is required to obey the restrictions of a 12391 /// class-head (i.e. no typedefs in the scope chain), template 12392 /// parameters are required to match up with simple template-ids, &c. 12393 /// However, unlike when declaring a template specialization, it's 12394 /// okay to refer to a template specialization without an empty 12395 /// template parameter declaration, e.g. 12396 /// friend class A<T>::B<unsigned>; 12397 /// We permit this as a special case; if there are any template 12398 /// parameters present at all, require proper matching, i.e. 12399 /// template <> template \<class T> friend class A<int>::B; 12400 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12401 MultiTemplateParamsArg TempParams) { 12402 SourceLocation Loc = DS.getLocStart(); 12403 12404 assert(DS.isFriendSpecified()); 12405 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12406 12407 // Try to convert the decl specifier to a type. This works for 12408 // friend templates because ActOnTag never produces a ClassTemplateDecl 12409 // for a TUK_Friend. 12410 Declarator TheDeclarator(DS, Declarator::MemberContext); 12411 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12412 QualType T = TSI->getType(); 12413 if (TheDeclarator.isInvalidType()) 12414 return nullptr; 12415 12416 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12417 return nullptr; 12418 12419 // This is definitely an error in C++98. It's probably meant to 12420 // be forbidden in C++0x, too, but the specification is just 12421 // poorly written. 12422 // 12423 // The problem is with declarations like the following: 12424 // template <T> friend A<T>::foo; 12425 // where deciding whether a class C is a friend or not now hinges 12426 // on whether there exists an instantiation of A that causes 12427 // 'foo' to equal C. There are restrictions on class-heads 12428 // (which we declare (by fiat) elaborated friend declarations to 12429 // be) that makes this tractable. 12430 // 12431 // FIXME: handle "template <> friend class A<T>;", which 12432 // is possibly well-formed? Who even knows? 12433 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12434 Diag(Loc, diag::err_tagless_friend_type_template) 12435 << DS.getSourceRange(); 12436 return nullptr; 12437 } 12438 12439 // C++98 [class.friend]p1: A friend of a class is a function 12440 // or class that is not a member of the class . . . 12441 // This is fixed in DR77, which just barely didn't make the C++03 12442 // deadline. It's also a very silly restriction that seriously 12443 // affects inner classes and which nobody else seems to implement; 12444 // thus we never diagnose it, not even in -pedantic. 12445 // 12446 // But note that we could warn about it: it's always useless to 12447 // friend one of your own members (it's not, however, worthless to 12448 // friend a member of an arbitrary specialization of your template). 12449 12450 Decl *D; 12451 if (unsigned NumTempParamLists = TempParams.size()) 12452 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12453 NumTempParamLists, 12454 TempParams.data(), 12455 TSI, 12456 DS.getFriendSpecLoc()); 12457 else 12458 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12459 12460 if (!D) 12461 return nullptr; 12462 12463 D->setAccess(AS_public); 12464 CurContext->addDecl(D); 12465 12466 return D; 12467 } 12468 12469 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12470 MultiTemplateParamsArg TemplateParams) { 12471 const DeclSpec &DS = D.getDeclSpec(); 12472 12473 assert(DS.isFriendSpecified()); 12474 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12475 12476 SourceLocation Loc = D.getIdentifierLoc(); 12477 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12478 12479 // C++ [class.friend]p1 12480 // A friend of a class is a function or class.... 12481 // Note that this sees through typedefs, which is intended. 12482 // It *doesn't* see through dependent types, which is correct 12483 // according to [temp.arg.type]p3: 12484 // If a declaration acquires a function type through a 12485 // type dependent on a template-parameter and this causes 12486 // a declaration that does not use the syntactic form of a 12487 // function declarator to have a function type, the program 12488 // is ill-formed. 12489 if (!TInfo->getType()->isFunctionType()) { 12490 Diag(Loc, diag::err_unexpected_friend); 12491 12492 // It might be worthwhile to try to recover by creating an 12493 // appropriate declaration. 12494 return nullptr; 12495 } 12496 12497 // C++ [namespace.memdef]p3 12498 // - If a friend declaration in a non-local class first declares a 12499 // class or function, the friend class or function is a member 12500 // of the innermost enclosing namespace. 12501 // - The name of the friend is not found by simple name lookup 12502 // until a matching declaration is provided in that namespace 12503 // scope (either before or after the class declaration granting 12504 // friendship). 12505 // - If a friend function is called, its name may be found by the 12506 // name lookup that considers functions from namespaces and 12507 // classes associated with the types of the function arguments. 12508 // - When looking for a prior declaration of a class or a function 12509 // declared as a friend, scopes outside the innermost enclosing 12510 // namespace scope are not considered. 12511 12512 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12513 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12514 DeclarationName Name = NameInfo.getName(); 12515 assert(Name); 12516 12517 // Check for unexpanded parameter packs. 12518 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12519 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12520 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12521 return nullptr; 12522 12523 // The context we found the declaration in, or in which we should 12524 // create the declaration. 12525 DeclContext *DC; 12526 Scope *DCScope = S; 12527 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12528 ForRedeclaration); 12529 12530 // There are five cases here. 12531 // - There's no scope specifier and we're in a local class. Only look 12532 // for functions declared in the immediately-enclosing block scope. 12533 // We recover from invalid scope qualifiers as if they just weren't there. 12534 FunctionDecl *FunctionContainingLocalClass = nullptr; 12535 if ((SS.isInvalid() || !SS.isSet()) && 12536 (FunctionContainingLocalClass = 12537 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12538 // C++11 [class.friend]p11: 12539 // If a friend declaration appears in a local class and the name 12540 // specified is an unqualified name, a prior declaration is 12541 // looked up without considering scopes that are outside the 12542 // innermost enclosing non-class scope. For a friend function 12543 // declaration, if there is no prior declaration, the program is 12544 // ill-formed. 12545 12546 // Find the innermost enclosing non-class scope. This is the block 12547 // scope containing the local class definition (or for a nested class, 12548 // the outer local class). 12549 DCScope = S->getFnParent(); 12550 12551 // Look up the function name in the scope. 12552 Previous.clear(LookupLocalFriendName); 12553 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12554 12555 if (!Previous.empty()) { 12556 // All possible previous declarations must have the same context: 12557 // either they were declared at block scope or they are members of 12558 // one of the enclosing local classes. 12559 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12560 } else { 12561 // This is ill-formed, but provide the context that we would have 12562 // declared the function in, if we were permitted to, for error recovery. 12563 DC = FunctionContainingLocalClass; 12564 } 12565 adjustContextForLocalExternDecl(DC); 12566 12567 // C++ [class.friend]p6: 12568 // A function can be defined in a friend declaration of a class if and 12569 // only if the class is a non-local class (9.8), the function name is 12570 // unqualified, and the function has namespace scope. 12571 if (D.isFunctionDefinition()) { 12572 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12573 } 12574 12575 // - There's no scope specifier, in which case we just go to the 12576 // appropriate scope and look for a function or function template 12577 // there as appropriate. 12578 } else if (SS.isInvalid() || !SS.isSet()) { 12579 // C++11 [namespace.memdef]p3: 12580 // If the name in a friend declaration is neither qualified nor 12581 // a template-id and the declaration is a function or an 12582 // elaborated-type-specifier, the lookup to determine whether 12583 // the entity has been previously declared shall not consider 12584 // any scopes outside the innermost enclosing namespace. 12585 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12586 12587 // Find the appropriate context according to the above. 12588 DC = CurContext; 12589 12590 // Skip class contexts. If someone can cite chapter and verse 12591 // for this behavior, that would be nice --- it's what GCC and 12592 // EDG do, and it seems like a reasonable intent, but the spec 12593 // really only says that checks for unqualified existing 12594 // declarations should stop at the nearest enclosing namespace, 12595 // not that they should only consider the nearest enclosing 12596 // namespace. 12597 while (DC->isRecord()) 12598 DC = DC->getParent(); 12599 12600 DeclContext *LookupDC = DC; 12601 while (LookupDC->isTransparentContext()) 12602 LookupDC = LookupDC->getParent(); 12603 12604 while (true) { 12605 LookupQualifiedName(Previous, LookupDC); 12606 12607 if (!Previous.empty()) { 12608 DC = LookupDC; 12609 break; 12610 } 12611 12612 if (isTemplateId) { 12613 if (isa<TranslationUnitDecl>(LookupDC)) break; 12614 } else { 12615 if (LookupDC->isFileContext()) break; 12616 } 12617 LookupDC = LookupDC->getParent(); 12618 } 12619 12620 DCScope = getScopeForDeclContext(S, DC); 12621 12622 // - There's a non-dependent scope specifier, in which case we 12623 // compute it and do a previous lookup there for a function 12624 // or function template. 12625 } else if (!SS.getScopeRep()->isDependent()) { 12626 DC = computeDeclContext(SS); 12627 if (!DC) return nullptr; 12628 12629 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12630 12631 LookupQualifiedName(Previous, DC); 12632 12633 // Ignore things found implicitly in the wrong scope. 12634 // TODO: better diagnostics for this case. Suggesting the right 12635 // qualified scope would be nice... 12636 LookupResult::Filter F = Previous.makeFilter(); 12637 while (F.hasNext()) { 12638 NamedDecl *D = F.next(); 12639 if (!DC->InEnclosingNamespaceSetOf( 12640 D->getDeclContext()->getRedeclContext())) 12641 F.erase(); 12642 } 12643 F.done(); 12644 12645 if (Previous.empty()) { 12646 D.setInvalidType(); 12647 Diag(Loc, diag::err_qualified_friend_not_found) 12648 << Name << TInfo->getType(); 12649 return nullptr; 12650 } 12651 12652 // C++ [class.friend]p1: A friend of a class is a function or 12653 // class that is not a member of the class . . . 12654 if (DC->Equals(CurContext)) 12655 Diag(DS.getFriendSpecLoc(), 12656 getLangOpts().CPlusPlus11 ? 12657 diag::warn_cxx98_compat_friend_is_member : 12658 diag::err_friend_is_member); 12659 12660 if (D.isFunctionDefinition()) { 12661 // C++ [class.friend]p6: 12662 // A function can be defined in a friend declaration of a class if and 12663 // only if the class is a non-local class (9.8), the function name is 12664 // unqualified, and the function has namespace scope. 12665 SemaDiagnosticBuilder DB 12666 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12667 12668 DB << SS.getScopeRep(); 12669 if (DC->isFileContext()) 12670 DB << FixItHint::CreateRemoval(SS.getRange()); 12671 SS.clear(); 12672 } 12673 12674 // - There's a scope specifier that does not match any template 12675 // parameter lists, in which case we use some arbitrary context, 12676 // create a method or method template, and wait for instantiation. 12677 // - There's a scope specifier that does match some template 12678 // parameter lists, which we don't handle right now. 12679 } else { 12680 if (D.isFunctionDefinition()) { 12681 // C++ [class.friend]p6: 12682 // A function can be defined in a friend declaration of a class if and 12683 // only if the class is a non-local class (9.8), the function name is 12684 // unqualified, and the function has namespace scope. 12685 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12686 << SS.getScopeRep(); 12687 } 12688 12689 DC = CurContext; 12690 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12691 } 12692 12693 if (!DC->isRecord()) { 12694 int DiagArg = -1; 12695 switch (D.getName().getKind()) { 12696 case UnqualifiedId::IK_ConstructorTemplateId: 12697 case UnqualifiedId::IK_ConstructorName: 12698 DiagArg = 0; 12699 break; 12700 case UnqualifiedId::IK_DestructorName: 12701 DiagArg = 1; 12702 break; 12703 case UnqualifiedId::IK_ConversionFunctionId: 12704 DiagArg = 2; 12705 break; 12706 case UnqualifiedId::IK_Identifier: 12707 case UnqualifiedId::IK_ImplicitSelfParam: 12708 case UnqualifiedId::IK_LiteralOperatorId: 12709 case UnqualifiedId::IK_OperatorFunctionId: 12710 case UnqualifiedId::IK_TemplateId: 12711 break; 12712 } 12713 // This implies that it has to be an operator or function. 12714 if (DiagArg >= 0) { 12715 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 12716 return nullptr; 12717 } 12718 } 12719 12720 // FIXME: This is an egregious hack to cope with cases where the scope stack 12721 // does not contain the declaration context, i.e., in an out-of-line 12722 // definition of a class. 12723 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12724 if (!DCScope) { 12725 FakeDCScope.setEntity(DC); 12726 DCScope = &FakeDCScope; 12727 } 12728 12729 bool AddToScope = true; 12730 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12731 TemplateParams, AddToScope); 12732 if (!ND) return nullptr; 12733 12734 assert(ND->getLexicalDeclContext() == CurContext); 12735 12736 // If we performed typo correction, we might have added a scope specifier 12737 // and changed the decl context. 12738 DC = ND->getDeclContext(); 12739 12740 // Add the function declaration to the appropriate lookup tables, 12741 // adjusting the redeclarations list as necessary. We don't 12742 // want to do this yet if the friending class is dependent. 12743 // 12744 // Also update the scope-based lookup if the target context's 12745 // lookup context is in lexical scope. 12746 if (!CurContext->isDependentContext()) { 12747 DC = DC->getRedeclContext(); 12748 DC->makeDeclVisibleInContext(ND); 12749 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12750 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12751 } 12752 12753 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12754 D.getIdentifierLoc(), ND, 12755 DS.getFriendSpecLoc()); 12756 FrD->setAccess(AS_public); 12757 CurContext->addDecl(FrD); 12758 12759 if (ND->isInvalidDecl()) { 12760 FrD->setInvalidDecl(); 12761 } else { 12762 if (DC->isRecord()) CheckFriendAccess(ND); 12763 12764 FunctionDecl *FD; 12765 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12766 FD = FTD->getTemplatedDecl(); 12767 else 12768 FD = cast<FunctionDecl>(ND); 12769 12770 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12771 // default argument expression, that declaration shall be a definition 12772 // and shall be the only declaration of the function or function 12773 // template in the translation unit. 12774 if (functionDeclHasDefaultArgument(FD)) { 12775 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12776 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12777 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12778 } else if (!D.isFunctionDefinition()) 12779 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12780 } 12781 12782 // Mark templated-scope function declarations as unsupported. 12783 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12784 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12785 << SS.getScopeRep() << SS.getRange() 12786 << cast<CXXRecordDecl>(CurContext); 12787 FrD->setUnsupportedFriend(true); 12788 } 12789 } 12790 12791 return ND; 12792 } 12793 12794 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12795 AdjustDeclIfTemplate(Dcl); 12796 12797 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12798 if (!Fn) { 12799 Diag(DelLoc, diag::err_deleted_non_function); 12800 return; 12801 } 12802 12803 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12804 // Don't consider the implicit declaration we generate for explicit 12805 // specializations. FIXME: Do not generate these implicit declarations. 12806 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12807 Prev->getPreviousDecl()) && 12808 !Prev->isDefined()) { 12809 Diag(DelLoc, diag::err_deleted_decl_not_first); 12810 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12811 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12812 : diag::note_previous_declaration); 12813 } 12814 // If the declaration wasn't the first, we delete the function anyway for 12815 // recovery. 12816 Fn = Fn->getCanonicalDecl(); 12817 } 12818 12819 // dllimport/dllexport cannot be deleted. 12820 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12821 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12822 Fn->setInvalidDecl(); 12823 } 12824 12825 if (Fn->isDeleted()) 12826 return; 12827 12828 // See if we're deleting a function which is already known to override a 12829 // non-deleted virtual function. 12830 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12831 bool IssuedDiagnostic = false; 12832 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12833 E = MD->end_overridden_methods(); 12834 I != E; ++I) { 12835 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12836 if (!IssuedDiagnostic) { 12837 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12838 IssuedDiagnostic = true; 12839 } 12840 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12841 } 12842 } 12843 } 12844 12845 // C++11 [basic.start.main]p3: 12846 // A program that defines main as deleted [...] is ill-formed. 12847 if (Fn->isMain()) 12848 Diag(DelLoc, diag::err_deleted_main); 12849 12850 Fn->setDeletedAsWritten(); 12851 } 12852 12853 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12854 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12855 12856 if (MD) { 12857 if (MD->getParent()->isDependentType()) { 12858 MD->setDefaulted(); 12859 MD->setExplicitlyDefaulted(); 12860 return; 12861 } 12862 12863 CXXSpecialMember Member = getSpecialMember(MD); 12864 if (Member == CXXInvalid) { 12865 if (!MD->isInvalidDecl()) 12866 Diag(DefaultLoc, diag::err_default_special_members); 12867 return; 12868 } 12869 12870 MD->setDefaulted(); 12871 MD->setExplicitlyDefaulted(); 12872 12873 // If this definition appears within the record, do the checking when 12874 // the record is complete. 12875 const FunctionDecl *Primary = MD; 12876 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12877 // Find the uninstantiated declaration that actually had the '= default' 12878 // on it. 12879 Pattern->isDefined(Primary); 12880 12881 // If the method was defaulted on its first declaration, we will have 12882 // already performed the checking in CheckCompletedCXXClass. Such a 12883 // declaration doesn't trigger an implicit definition. 12884 if (Primary == Primary->getCanonicalDecl()) 12885 return; 12886 12887 CheckExplicitlyDefaultedSpecialMember(MD); 12888 12889 if (MD->isInvalidDecl()) 12890 return; 12891 12892 switch (Member) { 12893 case CXXDefaultConstructor: 12894 DefineImplicitDefaultConstructor(DefaultLoc, 12895 cast<CXXConstructorDecl>(MD)); 12896 break; 12897 case CXXCopyConstructor: 12898 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12899 break; 12900 case CXXCopyAssignment: 12901 DefineImplicitCopyAssignment(DefaultLoc, MD); 12902 break; 12903 case CXXDestructor: 12904 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12905 break; 12906 case CXXMoveConstructor: 12907 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12908 break; 12909 case CXXMoveAssignment: 12910 DefineImplicitMoveAssignment(DefaultLoc, MD); 12911 break; 12912 case CXXInvalid: 12913 llvm_unreachable("Invalid special member."); 12914 } 12915 } else { 12916 Diag(DefaultLoc, diag::err_default_special_members); 12917 } 12918 } 12919 12920 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12921 for (Stmt *SubStmt : S->children()) { 12922 if (!SubStmt) 12923 continue; 12924 if (isa<ReturnStmt>(SubStmt)) 12925 Self.Diag(SubStmt->getLocStart(), 12926 diag::err_return_in_constructor_handler); 12927 if (!isa<Expr>(SubStmt)) 12928 SearchForReturnInStmt(Self, SubStmt); 12929 } 12930 } 12931 12932 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12933 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12934 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12935 SearchForReturnInStmt(*this, Handler); 12936 } 12937 } 12938 12939 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12940 const CXXMethodDecl *Old) { 12941 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12942 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12943 12944 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12945 12946 // If the calling conventions match, everything is fine 12947 if (NewCC == OldCC) 12948 return false; 12949 12950 // If the calling conventions mismatch because the new function is static, 12951 // suppress the calling convention mismatch error; the error about static 12952 // function override (err_static_overrides_virtual from 12953 // Sema::CheckFunctionDeclaration) is more clear. 12954 if (New->getStorageClass() == SC_Static) 12955 return false; 12956 12957 Diag(New->getLocation(), 12958 diag::err_conflicting_overriding_cc_attributes) 12959 << New->getDeclName() << New->getType() << Old->getType(); 12960 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12961 return true; 12962 } 12963 12964 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12965 const CXXMethodDecl *Old) { 12966 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12967 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12968 12969 if (Context.hasSameType(NewTy, OldTy) || 12970 NewTy->isDependentType() || OldTy->isDependentType()) 12971 return false; 12972 12973 // Check if the return types are covariant 12974 QualType NewClassTy, OldClassTy; 12975 12976 /// Both types must be pointers or references to classes. 12977 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12978 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12979 NewClassTy = NewPT->getPointeeType(); 12980 OldClassTy = OldPT->getPointeeType(); 12981 } 12982 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12983 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12984 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12985 NewClassTy = NewRT->getPointeeType(); 12986 OldClassTy = OldRT->getPointeeType(); 12987 } 12988 } 12989 } 12990 12991 // The return types aren't either both pointers or references to a class type. 12992 if (NewClassTy.isNull()) { 12993 Diag(New->getLocation(), 12994 diag::err_different_return_type_for_overriding_virtual_function) 12995 << New->getDeclName() << NewTy << OldTy 12996 << New->getReturnTypeSourceRange(); 12997 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12998 << Old->getReturnTypeSourceRange(); 12999 13000 return true; 13001 } 13002 13003 // C++ [class.virtual]p6: 13004 // If the return type of D::f differs from the return type of B::f, the 13005 // class type in the return type of D::f shall be complete at the point of 13006 // declaration of D::f or shall be the class type D. 13007 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 13008 if (!RT->isBeingDefined() && 13009 RequireCompleteType(New->getLocation(), NewClassTy, 13010 diag::err_covariant_return_incomplete, 13011 New->getDeclName())) 13012 return true; 13013 } 13014 13015 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 13016 // Check if the new class derives from the old class. 13017 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 13018 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 13019 << New->getDeclName() << NewTy << OldTy 13020 << New->getReturnTypeSourceRange(); 13021 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13022 << Old->getReturnTypeSourceRange(); 13023 return true; 13024 } 13025 13026 // Check if we the conversion from derived to base is valid. 13027 if (CheckDerivedToBaseConversion( 13028 NewClassTy, OldClassTy, 13029 diag::err_covariant_return_inaccessible_base, 13030 diag::err_covariant_return_ambiguous_derived_to_base_conv, 13031 New->getLocation(), New->getReturnTypeSourceRange(), 13032 New->getDeclName(), nullptr)) { 13033 // FIXME: this note won't trigger for delayed access control 13034 // diagnostics, and it's impossible to get an undelayed error 13035 // here from access control during the original parse because 13036 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 13037 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13038 << Old->getReturnTypeSourceRange(); 13039 return true; 13040 } 13041 } 13042 13043 // The qualifiers of the return types must be the same. 13044 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 13045 Diag(New->getLocation(), 13046 diag::err_covariant_return_type_different_qualifications) 13047 << New->getDeclName() << NewTy << OldTy 13048 << New->getReturnTypeSourceRange(); 13049 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13050 << Old->getReturnTypeSourceRange(); 13051 return true; 13052 }; 13053 13054 13055 // The new class type must have the same or less qualifiers as the old type. 13056 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 13057 Diag(New->getLocation(), 13058 diag::err_covariant_return_type_class_type_more_qualified) 13059 << New->getDeclName() << NewTy << OldTy 13060 << New->getReturnTypeSourceRange(); 13061 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13062 << Old->getReturnTypeSourceRange(); 13063 return true; 13064 }; 13065 13066 return false; 13067 } 13068 13069 /// \brief Mark the given method pure. 13070 /// 13071 /// \param Method the method to be marked pure. 13072 /// 13073 /// \param InitRange the source range that covers the "0" initializer. 13074 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 13075 SourceLocation EndLoc = InitRange.getEnd(); 13076 if (EndLoc.isValid()) 13077 Method->setRangeEnd(EndLoc); 13078 13079 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 13080 Method->setPure(); 13081 return false; 13082 } 13083 13084 if (!Method->isInvalidDecl()) 13085 Diag(Method->getLocation(), diag::err_non_virtual_pure) 13086 << Method->getDeclName() << InitRange; 13087 return true; 13088 } 13089 13090 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 13091 if (D->getFriendObjectKind()) 13092 Diag(D->getLocation(), diag::err_pure_friend); 13093 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 13094 CheckPureMethod(M, ZeroLoc); 13095 else 13096 Diag(D->getLocation(), diag::err_illegal_initializer); 13097 } 13098 13099 /// \brief Determine whether the given declaration is a static data member. 13100 static bool isStaticDataMember(const Decl *D) { 13101 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 13102 return Var->isStaticDataMember(); 13103 13104 return false; 13105 } 13106 13107 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 13108 /// an initializer for the out-of-line declaration 'Dcl'. The scope 13109 /// is a fresh scope pushed for just this purpose. 13110 /// 13111 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 13112 /// static data member of class X, names should be looked up in the scope of 13113 /// class X. 13114 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 13115 // If there is no declaration, there was an error parsing it. 13116 if (!D || D->isInvalidDecl()) 13117 return; 13118 13119 // We will always have a nested name specifier here, but this declaration 13120 // might not be out of line if the specifier names the current namespace: 13121 // extern int n; 13122 // int ::n = 0; 13123 if (D->isOutOfLine()) 13124 EnterDeclaratorContext(S, D->getDeclContext()); 13125 13126 // If we are parsing the initializer for a static data member, push a 13127 // new expression evaluation context that is associated with this static 13128 // data member. 13129 if (isStaticDataMember(D)) 13130 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 13131 } 13132 13133 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 13134 /// initializer for the out-of-line declaration 'D'. 13135 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 13136 // If there is no declaration, there was an error parsing it. 13137 if (!D || D->isInvalidDecl()) 13138 return; 13139 13140 if (isStaticDataMember(D)) 13141 PopExpressionEvaluationContext(); 13142 13143 if (D->isOutOfLine()) 13144 ExitDeclaratorContext(S); 13145 } 13146 13147 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 13148 /// C++ if/switch/while/for statement. 13149 /// e.g: "if (int x = f()) {...}" 13150 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 13151 // C++ 6.4p2: 13152 // The declarator shall not specify a function or an array. 13153 // The type-specifier-seq shall not contain typedef and shall not declare a 13154 // new class or enumeration. 13155 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 13156 "Parser allowed 'typedef' as storage class of condition decl."); 13157 13158 Decl *Dcl = ActOnDeclarator(S, D); 13159 if (!Dcl) 13160 return true; 13161 13162 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 13163 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 13164 << D.getSourceRange(); 13165 return true; 13166 } 13167 13168 return Dcl; 13169 } 13170 13171 void Sema::LoadExternalVTableUses() { 13172 if (!ExternalSource) 13173 return; 13174 13175 SmallVector<ExternalVTableUse, 4> VTables; 13176 ExternalSource->ReadUsedVTables(VTables); 13177 SmallVector<VTableUse, 4> NewUses; 13178 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 13179 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 13180 = VTablesUsed.find(VTables[I].Record); 13181 // Even if a definition wasn't required before, it may be required now. 13182 if (Pos != VTablesUsed.end()) { 13183 if (!Pos->second && VTables[I].DefinitionRequired) 13184 Pos->second = true; 13185 continue; 13186 } 13187 13188 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 13189 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 13190 } 13191 13192 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 13193 } 13194 13195 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 13196 bool DefinitionRequired) { 13197 // Ignore any vtable uses in unevaluated operands or for classes that do 13198 // not have a vtable. 13199 if (!Class->isDynamicClass() || Class->isDependentContext() || 13200 CurContext->isDependentContext() || isUnevaluatedContext()) 13201 return; 13202 13203 // Try to insert this class into the map. 13204 LoadExternalVTableUses(); 13205 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13206 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 13207 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 13208 if (!Pos.second) { 13209 // If we already had an entry, check to see if we are promoting this vtable 13210 // to require a definition. If so, we need to reappend to the VTableUses 13211 // list, since we may have already processed the first entry. 13212 if (DefinitionRequired && !Pos.first->second) { 13213 Pos.first->second = true; 13214 } else { 13215 // Otherwise, we can early exit. 13216 return; 13217 } 13218 } else { 13219 // The Microsoft ABI requires that we perform the destructor body 13220 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 13221 // the deleting destructor is emitted with the vtable, not with the 13222 // destructor definition as in the Itanium ABI. 13223 // If it has a definition, we do the check at that point instead. 13224 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13225 Class->hasUserDeclaredDestructor() && 13226 !Class->getDestructor()->isDefined() && 13227 !Class->getDestructor()->isDeleted()) { 13228 CXXDestructorDecl *DD = Class->getDestructor(); 13229 ContextRAII SavedContext(*this, DD); 13230 CheckDestructor(DD); 13231 } 13232 } 13233 13234 // Local classes need to have their virtual members marked 13235 // immediately. For all other classes, we mark their virtual members 13236 // at the end of the translation unit. 13237 if (Class->isLocalClass()) 13238 MarkVirtualMembersReferenced(Loc, Class); 13239 else 13240 VTableUses.push_back(std::make_pair(Class, Loc)); 13241 } 13242 13243 bool Sema::DefineUsedVTables() { 13244 LoadExternalVTableUses(); 13245 if (VTableUses.empty()) 13246 return false; 13247 13248 // Note: The VTableUses vector could grow as a result of marking 13249 // the members of a class as "used", so we check the size each 13250 // time through the loop and prefer indices (which are stable) to 13251 // iterators (which are not). 13252 bool DefinedAnything = false; 13253 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13254 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13255 if (!Class) 13256 continue; 13257 13258 SourceLocation Loc = VTableUses[I].second; 13259 13260 bool DefineVTable = true; 13261 13262 // If this class has a key function, but that key function is 13263 // defined in another translation unit, we don't need to emit the 13264 // vtable even though we're using it. 13265 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13266 if (KeyFunction && !KeyFunction->hasBody()) { 13267 // The key function is in another translation unit. 13268 DefineVTable = false; 13269 TemplateSpecializationKind TSK = 13270 KeyFunction->getTemplateSpecializationKind(); 13271 assert(TSK != TSK_ExplicitInstantiationDefinition && 13272 TSK != TSK_ImplicitInstantiation && 13273 "Instantiations don't have key functions"); 13274 (void)TSK; 13275 } else if (!KeyFunction) { 13276 // If we have a class with no key function that is the subject 13277 // of an explicit instantiation declaration, suppress the 13278 // vtable; it will live with the explicit instantiation 13279 // definition. 13280 bool IsExplicitInstantiationDeclaration 13281 = Class->getTemplateSpecializationKind() 13282 == TSK_ExplicitInstantiationDeclaration; 13283 for (auto R : Class->redecls()) { 13284 TemplateSpecializationKind TSK 13285 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13286 if (TSK == TSK_ExplicitInstantiationDeclaration) 13287 IsExplicitInstantiationDeclaration = true; 13288 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13289 IsExplicitInstantiationDeclaration = false; 13290 break; 13291 } 13292 } 13293 13294 if (IsExplicitInstantiationDeclaration) 13295 DefineVTable = false; 13296 } 13297 13298 // The exception specifications for all virtual members may be needed even 13299 // if we are not providing an authoritative form of the vtable in this TU. 13300 // We may choose to emit it available_externally anyway. 13301 if (!DefineVTable) { 13302 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13303 continue; 13304 } 13305 13306 // Mark all of the virtual members of this class as referenced, so 13307 // that we can build a vtable. Then, tell the AST consumer that a 13308 // vtable for this class is required. 13309 DefinedAnything = true; 13310 MarkVirtualMembersReferenced(Loc, Class); 13311 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13312 if (VTablesUsed[Canonical]) 13313 Consumer.HandleVTable(Class); 13314 13315 // Optionally warn if we're emitting a weak vtable. 13316 if (Class->isExternallyVisible() && 13317 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13318 const FunctionDecl *KeyFunctionDef = nullptr; 13319 if (!KeyFunction || 13320 (KeyFunction->hasBody(KeyFunctionDef) && 13321 KeyFunctionDef->isInlined())) 13322 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13323 TSK_ExplicitInstantiationDefinition 13324 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13325 << Class; 13326 } 13327 } 13328 VTableUses.clear(); 13329 13330 return DefinedAnything; 13331 } 13332 13333 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13334 const CXXRecordDecl *RD) { 13335 for (const auto *I : RD->methods()) 13336 if (I->isVirtual() && !I->isPure()) 13337 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13338 } 13339 13340 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13341 const CXXRecordDecl *RD) { 13342 // Mark all functions which will appear in RD's vtable as used. 13343 CXXFinalOverriderMap FinalOverriders; 13344 RD->getFinalOverriders(FinalOverriders); 13345 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13346 E = FinalOverriders.end(); 13347 I != E; ++I) { 13348 for (OverridingMethods::const_iterator OI = I->second.begin(), 13349 OE = I->second.end(); 13350 OI != OE; ++OI) { 13351 assert(OI->second.size() > 0 && "no final overrider"); 13352 CXXMethodDecl *Overrider = OI->second.front().Method; 13353 13354 // C++ [basic.def.odr]p2: 13355 // [...] A virtual member function is used if it is not pure. [...] 13356 if (!Overrider->isPure()) 13357 MarkFunctionReferenced(Loc, Overrider); 13358 } 13359 } 13360 13361 // Only classes that have virtual bases need a VTT. 13362 if (RD->getNumVBases() == 0) 13363 return; 13364 13365 for (const auto &I : RD->bases()) { 13366 const CXXRecordDecl *Base = 13367 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13368 if (Base->getNumVBases() == 0) 13369 continue; 13370 MarkVirtualMembersReferenced(Loc, Base); 13371 } 13372 } 13373 13374 /// SetIvarInitializers - This routine builds initialization ASTs for the 13375 /// Objective-C implementation whose ivars need be initialized. 13376 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13377 if (!getLangOpts().CPlusPlus) 13378 return; 13379 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13380 SmallVector<ObjCIvarDecl*, 8> ivars; 13381 CollectIvarsToConstructOrDestruct(OID, ivars); 13382 if (ivars.empty()) 13383 return; 13384 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13385 for (unsigned i = 0; i < ivars.size(); i++) { 13386 FieldDecl *Field = ivars[i]; 13387 if (Field->isInvalidDecl()) 13388 continue; 13389 13390 CXXCtorInitializer *Member; 13391 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13392 InitializationKind InitKind = 13393 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13394 13395 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13396 ExprResult MemberInit = 13397 InitSeq.Perform(*this, InitEntity, InitKind, None); 13398 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13399 // Note, MemberInit could actually come back empty if no initialization 13400 // is required (e.g., because it would call a trivial default constructor) 13401 if (!MemberInit.get() || MemberInit.isInvalid()) 13402 continue; 13403 13404 Member = 13405 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13406 SourceLocation(), 13407 MemberInit.getAs<Expr>(), 13408 SourceLocation()); 13409 AllToInit.push_back(Member); 13410 13411 // Be sure that the destructor is accessible and is marked as referenced. 13412 if (const RecordType *RecordTy = 13413 Context.getBaseElementType(Field->getType()) 13414 ->getAs<RecordType>()) { 13415 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13416 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13417 MarkFunctionReferenced(Field->getLocation(), Destructor); 13418 CheckDestructorAccess(Field->getLocation(), Destructor, 13419 PDiag(diag::err_access_dtor_ivar) 13420 << Context.getBaseElementType(Field->getType())); 13421 } 13422 } 13423 } 13424 ObjCImplementation->setIvarInitializers(Context, 13425 AllToInit.data(), AllToInit.size()); 13426 } 13427 } 13428 13429 static 13430 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13431 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13432 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13433 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13434 Sema &S) { 13435 if (Ctor->isInvalidDecl()) 13436 return; 13437 13438 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13439 13440 // Target may not be determinable yet, for instance if this is a dependent 13441 // call in an uninstantiated template. 13442 if (Target) { 13443 const FunctionDecl *FNTarget = nullptr; 13444 (void)Target->hasBody(FNTarget); 13445 Target = const_cast<CXXConstructorDecl*>( 13446 cast_or_null<CXXConstructorDecl>(FNTarget)); 13447 } 13448 13449 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13450 // Avoid dereferencing a null pointer here. 13451 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13452 13453 if (!Current.insert(Canonical).second) 13454 return; 13455 13456 // We know that beyond here, we aren't chaining into a cycle. 13457 if (!Target || !Target->isDelegatingConstructor() || 13458 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13459 Valid.insert(Current.begin(), Current.end()); 13460 Current.clear(); 13461 // We've hit a cycle. 13462 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13463 Current.count(TCanonical)) { 13464 // If we haven't diagnosed this cycle yet, do so now. 13465 if (!Invalid.count(TCanonical)) { 13466 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13467 diag::warn_delegating_ctor_cycle) 13468 << Ctor; 13469 13470 // Don't add a note for a function delegating directly to itself. 13471 if (TCanonical != Canonical) 13472 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13473 13474 CXXConstructorDecl *C = Target; 13475 while (C->getCanonicalDecl() != Canonical) { 13476 const FunctionDecl *FNTarget = nullptr; 13477 (void)C->getTargetConstructor()->hasBody(FNTarget); 13478 assert(FNTarget && "Ctor cycle through bodiless function"); 13479 13480 C = const_cast<CXXConstructorDecl*>( 13481 cast<CXXConstructorDecl>(FNTarget)); 13482 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13483 } 13484 } 13485 13486 Invalid.insert(Current.begin(), Current.end()); 13487 Current.clear(); 13488 } else { 13489 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13490 } 13491 } 13492 13493 13494 void Sema::CheckDelegatingCtorCycles() { 13495 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13496 13497 for (DelegatingCtorDeclsType::iterator 13498 I = DelegatingCtorDecls.begin(ExternalSource), 13499 E = DelegatingCtorDecls.end(); 13500 I != E; ++I) 13501 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13502 13503 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13504 CE = Invalid.end(); 13505 CI != CE; ++CI) 13506 (*CI)->setInvalidDecl(); 13507 } 13508 13509 namespace { 13510 /// \brief AST visitor that finds references to the 'this' expression. 13511 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13512 Sema &S; 13513 13514 public: 13515 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13516 13517 bool VisitCXXThisExpr(CXXThisExpr *E) { 13518 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13519 << E->isImplicit(); 13520 return false; 13521 } 13522 }; 13523 } 13524 13525 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13526 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13527 if (!TSInfo) 13528 return false; 13529 13530 TypeLoc TL = TSInfo->getTypeLoc(); 13531 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13532 if (!ProtoTL) 13533 return false; 13534 13535 // C++11 [expr.prim.general]p3: 13536 // [The expression this] shall not appear before the optional 13537 // cv-qualifier-seq and it shall not appear within the declaration of a 13538 // static member function (although its type and value category are defined 13539 // within a static member function as they are within a non-static member 13540 // function). [ Note: this is because declaration matching does not occur 13541 // until the complete declarator is known. - end note ] 13542 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13543 FindCXXThisExpr Finder(*this); 13544 13545 // If the return type came after the cv-qualifier-seq, check it now. 13546 if (Proto->hasTrailingReturn() && 13547 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13548 return true; 13549 13550 // Check the exception specification. 13551 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13552 return true; 13553 13554 return checkThisInStaticMemberFunctionAttributes(Method); 13555 } 13556 13557 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13558 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13559 if (!TSInfo) 13560 return false; 13561 13562 TypeLoc TL = TSInfo->getTypeLoc(); 13563 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13564 if (!ProtoTL) 13565 return false; 13566 13567 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13568 FindCXXThisExpr Finder(*this); 13569 13570 switch (Proto->getExceptionSpecType()) { 13571 case EST_Unparsed: 13572 case EST_Uninstantiated: 13573 case EST_Unevaluated: 13574 case EST_BasicNoexcept: 13575 case EST_DynamicNone: 13576 case EST_MSAny: 13577 case EST_None: 13578 break; 13579 13580 case EST_ComputedNoexcept: 13581 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13582 return true; 13583 13584 case EST_Dynamic: 13585 for (const auto &E : Proto->exceptions()) { 13586 if (!Finder.TraverseType(E)) 13587 return true; 13588 } 13589 break; 13590 } 13591 13592 return false; 13593 } 13594 13595 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13596 FindCXXThisExpr Finder(*this); 13597 13598 // Check attributes. 13599 for (const auto *A : Method->attrs()) { 13600 // FIXME: This should be emitted by tblgen. 13601 Expr *Arg = nullptr; 13602 ArrayRef<Expr *> Args; 13603 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13604 Arg = G->getArg(); 13605 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13606 Arg = G->getArg(); 13607 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13608 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13609 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13610 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13611 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13612 Arg = ETLF->getSuccessValue(); 13613 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13614 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13615 Arg = STLF->getSuccessValue(); 13616 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13617 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13618 Arg = LR->getArg(); 13619 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13620 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13621 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13622 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13623 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13624 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13625 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13626 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13627 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13628 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13629 13630 if (Arg && !Finder.TraverseStmt(Arg)) 13631 return true; 13632 13633 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13634 if (!Finder.TraverseStmt(Args[I])) 13635 return true; 13636 } 13637 } 13638 13639 return false; 13640 } 13641 13642 void Sema::checkExceptionSpecification( 13643 bool IsTopLevel, ExceptionSpecificationType EST, 13644 ArrayRef<ParsedType> DynamicExceptions, 13645 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13646 SmallVectorImpl<QualType> &Exceptions, 13647 FunctionProtoType::ExceptionSpecInfo &ESI) { 13648 Exceptions.clear(); 13649 ESI.Type = EST; 13650 if (EST == EST_Dynamic) { 13651 Exceptions.reserve(DynamicExceptions.size()); 13652 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13653 // FIXME: Preserve type source info. 13654 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13655 13656 if (IsTopLevel) { 13657 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13658 collectUnexpandedParameterPacks(ET, Unexpanded); 13659 if (!Unexpanded.empty()) { 13660 DiagnoseUnexpandedParameterPacks( 13661 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13662 Unexpanded); 13663 continue; 13664 } 13665 } 13666 13667 // Check that the type is valid for an exception spec, and 13668 // drop it if not. 13669 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13670 Exceptions.push_back(ET); 13671 } 13672 ESI.Exceptions = Exceptions; 13673 return; 13674 } 13675 13676 if (EST == EST_ComputedNoexcept) { 13677 // If an error occurred, there's no expression here. 13678 if (NoexceptExpr) { 13679 assert((NoexceptExpr->isTypeDependent() || 13680 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13681 Context.BoolTy) && 13682 "Parser should have made sure that the expression is boolean"); 13683 if (IsTopLevel && NoexceptExpr && 13684 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13685 ESI.Type = EST_BasicNoexcept; 13686 return; 13687 } 13688 13689 if (!NoexceptExpr->isValueDependent()) 13690 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13691 diag::err_noexcept_needs_constant_expression, 13692 /*AllowFold*/ false).get(); 13693 ESI.NoexceptExpr = NoexceptExpr; 13694 } 13695 return; 13696 } 13697 } 13698 13699 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13700 ExceptionSpecificationType EST, 13701 SourceRange SpecificationRange, 13702 ArrayRef<ParsedType> DynamicExceptions, 13703 ArrayRef<SourceRange> DynamicExceptionRanges, 13704 Expr *NoexceptExpr) { 13705 if (!MethodD) 13706 return; 13707 13708 // Dig out the method we're referring to. 13709 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13710 MethodD = FunTmpl->getTemplatedDecl(); 13711 13712 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13713 if (!Method) 13714 return; 13715 13716 // Check the exception specification. 13717 llvm::SmallVector<QualType, 4> Exceptions; 13718 FunctionProtoType::ExceptionSpecInfo ESI; 13719 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13720 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13721 ESI); 13722 13723 // Update the exception specification on the function type. 13724 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13725 13726 if (Method->isStatic()) 13727 checkThisInStaticMemberFunctionExceptionSpec(Method); 13728 13729 if (Method->isVirtual()) { 13730 // Check overrides, which we previously had to delay. 13731 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13732 OEnd = Method->end_overridden_methods(); 13733 O != OEnd; ++O) 13734 CheckOverridingFunctionExceptionSpec(Method, *O); 13735 } 13736 } 13737 13738 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13739 /// 13740 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13741 SourceLocation DeclStart, 13742 Declarator &D, Expr *BitWidth, 13743 InClassInitStyle InitStyle, 13744 AccessSpecifier AS, 13745 AttributeList *MSPropertyAttr) { 13746 IdentifierInfo *II = D.getIdentifier(); 13747 if (!II) { 13748 Diag(DeclStart, diag::err_anonymous_property); 13749 return nullptr; 13750 } 13751 SourceLocation Loc = D.getIdentifierLoc(); 13752 13753 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13754 QualType T = TInfo->getType(); 13755 if (getLangOpts().CPlusPlus) { 13756 CheckExtraCXXDefaultArguments(D); 13757 13758 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13759 UPPC_DataMemberType)) { 13760 D.setInvalidType(); 13761 T = Context.IntTy; 13762 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13763 } 13764 } 13765 13766 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13767 13768 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13769 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13770 diag::err_invalid_thread) 13771 << DeclSpec::getSpecifierName(TSCS); 13772 13773 // Check to see if this name was declared as a member previously 13774 NamedDecl *PrevDecl = nullptr; 13775 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13776 LookupName(Previous, S); 13777 switch (Previous.getResultKind()) { 13778 case LookupResult::Found: 13779 case LookupResult::FoundUnresolvedValue: 13780 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13781 break; 13782 13783 case LookupResult::FoundOverloaded: 13784 PrevDecl = Previous.getRepresentativeDecl(); 13785 break; 13786 13787 case LookupResult::NotFound: 13788 case LookupResult::NotFoundInCurrentInstantiation: 13789 case LookupResult::Ambiguous: 13790 break; 13791 } 13792 13793 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13794 // Maybe we will complain about the shadowed template parameter. 13795 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13796 // Just pretend that we didn't see the previous declaration. 13797 PrevDecl = nullptr; 13798 } 13799 13800 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13801 PrevDecl = nullptr; 13802 13803 SourceLocation TSSL = D.getLocStart(); 13804 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13805 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13806 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13807 ProcessDeclAttributes(TUScope, NewPD, D); 13808 NewPD->setAccess(AS); 13809 13810 if (NewPD->isInvalidDecl()) 13811 Record->setInvalidDecl(); 13812 13813 if (D.getDeclSpec().isModulePrivateSpecified()) 13814 NewPD->setModulePrivate(); 13815 13816 if (NewPD->isInvalidDecl() && PrevDecl) { 13817 // Don't introduce NewFD into scope; there's already something 13818 // with the same name in the same scope. 13819 } else if (II) { 13820 PushOnScopeChains(NewPD, S); 13821 } else 13822 Record->addDecl(NewPD); 13823 13824 return NewPD; 13825 } 13826