1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for C++ declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt *SubStmt : Node->children()) 77 IsInvalid |= Visit(SubStmt); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If we have a throw-all spec at this point, ignore the function. 166 if (ComputedEST == EST_None) 167 return; 168 169 switch(EST) { 170 // If this function can throw any exceptions, make a note of that. 171 case EST_MSAny: 172 case EST_None: 173 ClearExceptions(); 174 ComputedEST = EST; 175 return; 176 // FIXME: If the call to this decl is using any of its default arguments, we 177 // need to search them for potentially-throwing calls. 178 // If this function has a basic noexcept, it doesn't affect the outcome. 179 case EST_BasicNoexcept: 180 return; 181 // If we're still at noexcept(true) and there's a nothrow() callee, 182 // change to that specification. 183 case EST_DynamicNone: 184 if (ComputedEST == EST_BasicNoexcept) 185 ComputedEST = EST_DynamicNone; 186 return; 187 // Check out noexcept specs. 188 case EST_ComputedNoexcept: 189 { 190 FunctionProtoType::NoexceptResult NR = 191 Proto->getNoexceptSpec(Self->Context); 192 assert(NR != FunctionProtoType::NR_NoNoexcept && 193 "Must have noexcept result for EST_ComputedNoexcept."); 194 assert(NR != FunctionProtoType::NR_Dependent && 195 "Should not generate implicit declarations for dependent cases, " 196 "and don't know how to handle them anyway."); 197 // noexcept(false) -> no spec on the new function 198 if (NR == FunctionProtoType::NR_Throw) { 199 ClearExceptions(); 200 ComputedEST = EST_None; 201 } 202 // noexcept(true) won't change anything either. 203 return; 204 } 205 default: 206 break; 207 } 208 assert(EST == EST_Dynamic && "EST case not considered earlier."); 209 assert(ComputedEST != EST_None && 210 "Shouldn't collect exceptions when throw-all is guaranteed."); 211 ComputedEST = EST_Dynamic; 212 // Record the exceptions in this function's exception specification. 213 for (const auto &E : Proto->exceptions()) 214 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 215 Exceptions.push_back(E); 216 } 217 218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 219 if (!E || ComputedEST == EST_MSAny) 220 return; 221 222 // FIXME: 223 // 224 // C++0x [except.spec]p14: 225 // [An] implicit exception-specification specifies the type-id T if and 226 // only if T is allowed by the exception-specification of a function directly 227 // invoked by f's implicit definition; f shall allow all exceptions if any 228 // function it directly invokes allows all exceptions, and f shall allow no 229 // exceptions if every function it directly invokes allows no exceptions. 230 // 231 // Note in particular that if an implicit exception-specification is generated 232 // for a function containing a throw-expression, that specification can still 233 // be noexcept(true). 234 // 235 // Note also that 'directly invoked' is not defined in the standard, and there 236 // is no indication that we should only consider potentially-evaluated calls. 237 // 238 // Ultimately we should implement the intent of the standard: the exception 239 // specification should be the set of exceptions which can be thrown by the 240 // implicit definition. For now, we assume that any non-nothrow expression can 241 // throw any exception. 242 243 if (Self->canThrow(E)) 244 ComputedEST = EST_None; 245 } 246 247 bool 248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 249 SourceLocation EqualLoc) { 250 if (RequireCompleteType(Param->getLocation(), Param->getType(), 251 diag::err_typecheck_decl_incomplete_type)) { 252 Param->setInvalidDecl(); 253 return true; 254 } 255 256 // C++ [dcl.fct.default]p5 257 // A default argument expression is implicitly converted (clause 258 // 4) to the parameter type. The default argument expression has 259 // the same semantic constraints as the initializer expression in 260 // a declaration of a variable of the parameter type, using the 261 // copy-initialization semantics (8.5). 262 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 263 Param); 264 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 265 EqualLoc); 266 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 268 if (Result.isInvalid()) 269 return true; 270 Arg = Result.getAs<Expr>(); 271 272 CheckCompletedExpr(Arg, EqualLoc); 273 Arg = MaybeCreateExprWithCleanups(Arg); 274 275 // Okay: add the default argument to the parameter 276 Param->setDefaultArg(Arg); 277 278 // We have already instantiated this parameter; provide each of the 279 // instantiations with the uninstantiated default argument. 280 UnparsedDefaultArgInstantiationsMap::iterator InstPos 281 = UnparsedDefaultArgInstantiations.find(Param); 282 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 283 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 284 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 285 286 // We're done tracking this parameter's instantiations. 287 UnparsedDefaultArgInstantiations.erase(InstPos); 288 } 289 290 return false; 291 } 292 293 /// ActOnParamDefaultArgument - Check whether the default argument 294 /// provided for a function parameter is well-formed. If so, attach it 295 /// to the parameter declaration. 296 void 297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 298 Expr *DefaultArg) { 299 if (!param || !DefaultArg) 300 return; 301 302 ParmVarDecl *Param = cast<ParmVarDecl>(param); 303 UnparsedDefaultArgLocs.erase(Param); 304 305 // Default arguments are only permitted in C++ 306 if (!getLangOpts().CPlusPlus) { 307 Diag(EqualLoc, diag::err_param_default_argument) 308 << DefaultArg->getSourceRange(); 309 Param->setInvalidDecl(); 310 return; 311 } 312 313 // Check for unexpanded parameter packs. 314 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 315 Param->setInvalidDecl(); 316 return; 317 } 318 319 // C++11 [dcl.fct.default]p3 320 // A default argument expression [...] shall not be specified for a 321 // parameter pack. 322 if (Param->isParameterPack()) { 323 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 324 << DefaultArg->getSourceRange(); 325 return; 326 } 327 328 // Check that the default argument is well-formed 329 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 330 if (DefaultArgChecker.Visit(DefaultArg)) { 331 Param->setInvalidDecl(); 332 return; 333 } 334 335 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 336 } 337 338 /// ActOnParamUnparsedDefaultArgument - We've seen a default 339 /// argument for a function parameter, but we can't parse it yet 340 /// because we're inside a class definition. Note that this default 341 /// argument will be parsed later. 342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 343 SourceLocation EqualLoc, 344 SourceLocation ArgLoc) { 345 if (!param) 346 return; 347 348 ParmVarDecl *Param = cast<ParmVarDecl>(param); 349 Param->setUnparsedDefaultArg(); 350 UnparsedDefaultArgLocs[Param] = ArgLoc; 351 } 352 353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 354 /// the default argument for the parameter param failed. 355 void Sema::ActOnParamDefaultArgumentError(Decl *param, 356 SourceLocation EqualLoc) { 357 if (!param) 358 return; 359 360 ParmVarDecl *Param = cast<ParmVarDecl>(param); 361 Param->setInvalidDecl(); 362 UnparsedDefaultArgLocs.erase(Param); 363 Param->setDefaultArg(new(Context) 364 OpaqueValueExpr(EqualLoc, 365 Param->getType().getNonReferenceType(), 366 VK_RValue)); 367 } 368 369 /// CheckExtraCXXDefaultArguments - Check for any extra default 370 /// arguments in the declarator, which is not a function declaration 371 /// or definition and therefore is not permitted to have default 372 /// arguments. This routine should be invoked for every declarator 373 /// that is not a function declaration or definition. 374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 375 // C++ [dcl.fct.default]p3 376 // A default argument expression shall be specified only in the 377 // parameter-declaration-clause of a function declaration or in a 378 // template-parameter (14.1). It shall not be specified for a 379 // parameter pack. If it is specified in a 380 // parameter-declaration-clause, it shall not occur within a 381 // declarator or abstract-declarator of a parameter-declaration. 382 bool MightBeFunction = D.isFunctionDeclarationContext(); 383 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 384 DeclaratorChunk &chunk = D.getTypeObject(i); 385 if (chunk.Kind == DeclaratorChunk::Function) { 386 if (MightBeFunction) { 387 // This is a function declaration. It can have default arguments, but 388 // keep looking in case its return type is a function type with default 389 // arguments. 390 MightBeFunction = false; 391 continue; 392 } 393 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 394 ++argIdx) { 395 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 396 if (Param->hasUnparsedDefaultArg()) { 397 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 398 SourceRange SR; 399 if (Toks->size() > 1) 400 SR = SourceRange((*Toks)[1].getLocation(), 401 Toks->back().getLocation()); 402 else 403 SR = UnparsedDefaultArgLocs[Param]; 404 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 405 << SR; 406 delete Toks; 407 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 408 } else if (Param->getDefaultArg()) { 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << Param->getDefaultArg()->getSourceRange(); 411 Param->setDefaultArg(nullptr); 412 } 413 } 414 } else if (chunk.Kind != DeclaratorChunk::Paren) { 415 MightBeFunction = false; 416 } 417 } 418 } 419 420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 423 if (!PVD->hasDefaultArg()) 424 return false; 425 if (!PVD->hasInheritedDefaultArg()) 426 return true; 427 } 428 return false; 429 } 430 431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 432 /// function, once we already know that they have the same 433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 434 /// error, false otherwise. 435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 436 Scope *S) { 437 bool Invalid = false; 438 439 // The declaration context corresponding to the scope is the semantic 440 // parent, unless this is a local function declaration, in which case 441 // it is that surrounding function. 442 DeclContext *ScopeDC = New->isLocalExternDecl() 443 ? New->getLexicalDeclContext() 444 : New->getDeclContext(); 445 446 // Find the previous declaration for the purpose of default arguments. 447 FunctionDecl *PrevForDefaultArgs = Old; 448 for (/**/; PrevForDefaultArgs; 449 // Don't bother looking back past the latest decl if this is a local 450 // extern declaration; nothing else could work. 451 PrevForDefaultArgs = New->isLocalExternDecl() 452 ? nullptr 453 : PrevForDefaultArgs->getPreviousDecl()) { 454 // Ignore hidden declarations. 455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 456 continue; 457 458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 459 !New->isCXXClassMember()) { 460 // Ignore default arguments of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 continue; 464 } 465 466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 467 // If only one of these is a local function declaration, then they are 468 // declared in different scopes, even though isDeclInScope may think 469 // they're in the same scope. (If both are local, the scope check is 470 // sufficent, and if neither is local, then they are in the same scope.) 471 continue; 472 } 473 474 // We found our guy. 475 break; 476 } 477 478 // C++ [dcl.fct.default]p4: 479 // For non-template functions, default arguments can be added in 480 // later declarations of a function in the same 481 // scope. Declarations in different scopes have completely 482 // distinct sets of default arguments. That is, declarations in 483 // inner scopes do not acquire default arguments from 484 // declarations in outer scopes, and vice versa. In a given 485 // function declaration, all parameters subsequent to a 486 // parameter with a default argument shall have default 487 // arguments supplied in this or previous declarations. A 488 // default argument shall not be redefined by a later 489 // declaration (not even to the same value). 490 // 491 // C++ [dcl.fct.default]p6: 492 // Except for member functions of class templates, the default arguments 493 // in a member function definition that appears outside of the class 494 // definition are added to the set of default arguments provided by the 495 // member function declaration in the class definition. 496 for (unsigned p = 0, NumParams = PrevForDefaultArgs 497 ? PrevForDefaultArgs->getNumParams() 498 : 0; 499 p < NumParams; ++p) { 500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 501 ParmVarDecl *NewParam = New->getParamDecl(p); 502 503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 504 bool NewParamHasDfl = NewParam->hasDefaultArg(); 505 506 if (OldParamHasDfl && NewParamHasDfl) { 507 unsigned DiagDefaultParamID = 508 diag::err_param_default_argument_redefinition; 509 510 // MSVC accepts that default parameters be redefined for member functions 511 // of template class. The new default parameter's value is ignored. 512 Invalid = true; 513 if (getLangOpts().MicrosoftExt) { 514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 515 if (MD && MD->getParent()->getDescribedClassTemplate()) { 516 // Merge the old default argument into the new parameter. 517 NewParam->setHasInheritedDefaultArg(); 518 if (OldParam->hasUninstantiatedDefaultArg()) 519 NewParam->setUninstantiatedDefaultArg( 520 OldParam->getUninstantiatedDefaultArg()); 521 else 522 NewParam->setDefaultArg(OldParam->getInit()); 523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 524 Invalid = false; 525 } 526 } 527 528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 529 // hint here. Alternatively, we could walk the type-source information 530 // for NewParam to find the last source location in the type... but it 531 // isn't worth the effort right now. This is the kind of test case that 532 // is hard to get right: 533 // int f(int); 534 // void g(int (*fp)(int) = f); 535 // void g(int (*fp)(int) = &f); 536 Diag(NewParam->getLocation(), DiagDefaultParamID) 537 << NewParam->getDefaultArgRange(); 538 539 // Look for the function declaration where the default argument was 540 // actually written, which may be a declaration prior to Old. 541 for (auto Older = PrevForDefaultArgs; 542 OldParam->hasInheritedDefaultArg(); /**/) { 543 Older = Older->getPreviousDecl(); 544 OldParam = Older->getParamDecl(p); 545 } 546 547 Diag(OldParam->getLocation(), diag::note_previous_definition) 548 << OldParam->getDefaultArgRange(); 549 } else if (OldParamHasDfl) { 550 // Merge the old default argument into the new parameter. 551 // It's important to use getInit() here; getDefaultArg() 552 // strips off any top-level ExprWithCleanups. 553 NewParam->setHasInheritedDefaultArg(); 554 if (OldParam->hasUnparsedDefaultArg()) 555 NewParam->setUnparsedDefaultArg(); 556 else if (OldParam->hasUninstantiatedDefaultArg()) 557 NewParam->setUninstantiatedDefaultArg( 558 OldParam->getUninstantiatedDefaultArg()); 559 else 560 NewParam->setDefaultArg(OldParam->getInit()); 561 } else if (NewParamHasDfl) { 562 if (New->getDescribedFunctionTemplate()) { 563 // Paragraph 4, quoted above, only applies to non-template functions. 564 Diag(NewParam->getLocation(), 565 diag::err_param_default_argument_template_redecl) 566 << NewParam->getDefaultArgRange(); 567 Diag(PrevForDefaultArgs->getLocation(), 568 diag::note_template_prev_declaration) 569 << false; 570 } else if (New->getTemplateSpecializationKind() 571 != TSK_ImplicitInstantiation && 572 New->getTemplateSpecializationKind() != TSK_Undeclared) { 573 // C++ [temp.expr.spec]p21: 574 // Default function arguments shall not be specified in a declaration 575 // or a definition for one of the following explicit specializations: 576 // - the explicit specialization of a function template; 577 // - the explicit specialization of a member function template; 578 // - the explicit specialization of a member function of a class 579 // template where the class template specialization to which the 580 // member function specialization belongs is implicitly 581 // instantiated. 582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 584 << New->getDeclName() 585 << NewParam->getDefaultArgRange(); 586 } else if (New->getDeclContext()->isDependentContext()) { 587 // C++ [dcl.fct.default]p6 (DR217): 588 // Default arguments for a member function of a class template shall 589 // be specified on the initial declaration of the member function 590 // within the class template. 591 // 592 // Reading the tea leaves a bit in DR217 and its reference to DR205 593 // leads me to the conclusion that one cannot add default function 594 // arguments for an out-of-line definition of a member function of a 595 // dependent type. 596 int WhichKind = 2; 597 if (CXXRecordDecl *Record 598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 599 if (Record->getDescribedClassTemplate()) 600 WhichKind = 0; 601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 602 WhichKind = 1; 603 else 604 WhichKind = 2; 605 } 606 607 Diag(NewParam->getLocation(), 608 diag::err_param_default_argument_member_template_redecl) 609 << WhichKind 610 << NewParam->getDefaultArgRange(); 611 } 612 } 613 } 614 615 // DR1344: If a default argument is added outside a class definition and that 616 // default argument makes the function a special member function, the program 617 // is ill-formed. This can only happen for constructors. 618 if (isa<CXXConstructorDecl>(New) && 619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 622 if (NewSM != OldSM) { 623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 624 assert(NewParam->hasDefaultArg()); 625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 626 << NewParam->getDefaultArgRange() << NewSM; 627 Diag(Old->getLocation(), diag::note_previous_declaration); 628 } 629 } 630 631 const FunctionDecl *Def; 632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 633 // template has a constexpr specifier then all its declarations shall 634 // contain the constexpr specifier. 635 if (New->isConstexpr() != Old->isConstexpr()) { 636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 637 << New << New->isConstexpr(); 638 Diag(Old->getLocation(), diag::note_previous_declaration); 639 Invalid = true; 640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 641 Old->isDefined(Def)) { 642 // C++11 [dcl.fcn.spec]p4: 643 // If the definition of a function appears in a translation unit before its 644 // first declaration as inline, the program is ill-formed. 645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 646 Diag(Def->getLocation(), diag::note_previous_definition); 647 Invalid = true; 648 } 649 650 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 651 // argument expression, that declaration shall be a definition and shall be 652 // the only declaration of the function or function template in the 653 // translation unit. 654 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 655 functionDeclHasDefaultArgument(Old)) { 656 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 657 Diag(Old->getLocation(), diag::note_previous_declaration); 658 Invalid = true; 659 } 660 661 if (CheckEquivalentExceptionSpec(Old, New)) 662 Invalid = true; 663 664 return Invalid; 665 } 666 667 /// \brief Merge the exception specifications of two variable declarations. 668 /// 669 /// This is called when there's a redeclaration of a VarDecl. The function 670 /// checks if the redeclaration might have an exception specification and 671 /// validates compatibility and merges the specs if necessary. 672 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 673 // Shortcut if exceptions are disabled. 674 if (!getLangOpts().CXXExceptions) 675 return; 676 677 assert(Context.hasSameType(New->getType(), Old->getType()) && 678 "Should only be called if types are otherwise the same."); 679 680 QualType NewType = New->getType(); 681 QualType OldType = Old->getType(); 682 683 // We're only interested in pointers and references to functions, as well 684 // as pointers to member functions. 685 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 686 NewType = R->getPointeeType(); 687 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 688 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 689 NewType = P->getPointeeType(); 690 OldType = OldType->getAs<PointerType>()->getPointeeType(); 691 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 692 NewType = M->getPointeeType(); 693 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 694 } 695 696 if (!NewType->isFunctionProtoType()) 697 return; 698 699 // There's lots of special cases for functions. For function pointers, system 700 // libraries are hopefully not as broken so that we don't need these 701 // workarounds. 702 if (CheckEquivalentExceptionSpec( 703 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 704 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 705 New->setInvalidDecl(); 706 } 707 } 708 709 /// CheckCXXDefaultArguments - Verify that the default arguments for a 710 /// function declaration are well-formed according to C++ 711 /// [dcl.fct.default]. 712 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 713 unsigned NumParams = FD->getNumParams(); 714 unsigned p; 715 716 // Find first parameter with a default argument 717 for (p = 0; p < NumParams; ++p) { 718 ParmVarDecl *Param = FD->getParamDecl(p); 719 if (Param->hasDefaultArg()) 720 break; 721 } 722 723 // C++11 [dcl.fct.default]p4: 724 // In a given function declaration, each parameter subsequent to a parameter 725 // with a default argument shall have a default argument supplied in this or 726 // a previous declaration or shall be a function parameter pack. A default 727 // argument shall not be redefined by a later declaration (not even to the 728 // same value). 729 unsigned LastMissingDefaultArg = 0; 730 for (; p < NumParams; ++p) { 731 ParmVarDecl *Param = FD->getParamDecl(p); 732 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 733 if (Param->isInvalidDecl()) 734 /* We already complained about this parameter. */; 735 else if (Param->getIdentifier()) 736 Diag(Param->getLocation(), 737 diag::err_param_default_argument_missing_name) 738 << Param->getIdentifier(); 739 else 740 Diag(Param->getLocation(), 741 diag::err_param_default_argument_missing); 742 743 LastMissingDefaultArg = p; 744 } 745 } 746 747 if (LastMissingDefaultArg > 0) { 748 // Some default arguments were missing. Clear out all of the 749 // default arguments up to (and including) the last missing 750 // default argument, so that we leave the function parameters 751 // in a semantically valid state. 752 for (p = 0; p <= LastMissingDefaultArg; ++p) { 753 ParmVarDecl *Param = FD->getParamDecl(p); 754 if (Param->hasDefaultArg()) { 755 Param->setDefaultArg(nullptr); 756 } 757 } 758 } 759 } 760 761 // CheckConstexprParameterTypes - Check whether a function's parameter types 762 // are all literal types. If so, return true. If not, produce a suitable 763 // diagnostic and return false. 764 static bool CheckConstexprParameterTypes(Sema &SemaRef, 765 const FunctionDecl *FD) { 766 unsigned ArgIndex = 0; 767 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 768 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 769 e = FT->param_type_end(); 770 i != e; ++i, ++ArgIndex) { 771 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 772 SourceLocation ParamLoc = PD->getLocation(); 773 if (!(*i)->isDependentType() && 774 SemaRef.RequireLiteralType(ParamLoc, *i, 775 diag::err_constexpr_non_literal_param, 776 ArgIndex+1, PD->getSourceRange(), 777 isa<CXXConstructorDecl>(FD))) 778 return false; 779 } 780 return true; 781 } 782 783 /// \brief Get diagnostic %select index for tag kind for 784 /// record diagnostic message. 785 /// WARNING: Indexes apply to particular diagnostics only! 786 /// 787 /// \returns diagnostic %select index. 788 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 789 switch (Tag) { 790 case TTK_Struct: return 0; 791 case TTK_Interface: return 1; 792 case TTK_Class: return 2; 793 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 794 } 795 } 796 797 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 798 // the requirements of a constexpr function definition or a constexpr 799 // constructor definition. If so, return true. If not, produce appropriate 800 // diagnostics and return false. 801 // 802 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 803 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 804 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 805 if (MD && MD->isInstance()) { 806 // C++11 [dcl.constexpr]p4: 807 // The definition of a constexpr constructor shall satisfy the following 808 // constraints: 809 // - the class shall not have any virtual base classes; 810 const CXXRecordDecl *RD = MD->getParent(); 811 if (RD->getNumVBases()) { 812 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 813 << isa<CXXConstructorDecl>(NewFD) 814 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 815 for (const auto &I : RD->vbases()) 816 Diag(I.getLocStart(), 817 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 818 return false; 819 } 820 } 821 822 if (!isa<CXXConstructorDecl>(NewFD)) { 823 // C++11 [dcl.constexpr]p3: 824 // The definition of a constexpr function shall satisfy the following 825 // constraints: 826 // - it shall not be virtual; 827 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 828 if (Method && Method->isVirtual()) { 829 Method = Method->getCanonicalDecl(); 830 Diag(Method->getLocation(), diag::err_constexpr_virtual); 831 832 // If it's not obvious why this function is virtual, find an overridden 833 // function which uses the 'virtual' keyword. 834 const CXXMethodDecl *WrittenVirtual = Method; 835 while (!WrittenVirtual->isVirtualAsWritten()) 836 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 837 if (WrittenVirtual != Method) 838 Diag(WrittenVirtual->getLocation(), 839 diag::note_overridden_virtual_function); 840 return false; 841 } 842 843 // - its return type shall be a literal type; 844 QualType RT = NewFD->getReturnType(); 845 if (!RT->isDependentType() && 846 RequireLiteralType(NewFD->getLocation(), RT, 847 diag::err_constexpr_non_literal_return)) 848 return false; 849 } 850 851 // - each of its parameter types shall be a literal type; 852 if (!CheckConstexprParameterTypes(*this, NewFD)) 853 return false; 854 855 return true; 856 } 857 858 /// Check the given declaration statement is legal within a constexpr function 859 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 860 /// 861 /// \return true if the body is OK (maybe only as an extension), false if we 862 /// have diagnosed a problem. 863 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 864 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 865 // C++11 [dcl.constexpr]p3 and p4: 866 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 867 // contain only 868 for (const auto *DclIt : DS->decls()) { 869 switch (DclIt->getKind()) { 870 case Decl::StaticAssert: 871 case Decl::Using: 872 case Decl::UsingShadow: 873 case Decl::UsingDirective: 874 case Decl::UnresolvedUsingTypename: 875 case Decl::UnresolvedUsingValue: 876 // - static_assert-declarations 877 // - using-declarations, 878 // - using-directives, 879 continue; 880 881 case Decl::Typedef: 882 case Decl::TypeAlias: { 883 // - typedef declarations and alias-declarations that do not define 884 // classes or enumerations, 885 const auto *TN = cast<TypedefNameDecl>(DclIt); 886 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 887 // Don't allow variably-modified types in constexpr functions. 888 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 889 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 890 << TL.getSourceRange() << TL.getType() 891 << isa<CXXConstructorDecl>(Dcl); 892 return false; 893 } 894 continue; 895 } 896 897 case Decl::Enum: 898 case Decl::CXXRecord: 899 // C++1y allows types to be defined, not just declared. 900 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 901 SemaRef.Diag(DS->getLocStart(), 902 SemaRef.getLangOpts().CPlusPlus14 903 ? diag::warn_cxx11_compat_constexpr_type_definition 904 : diag::ext_constexpr_type_definition) 905 << isa<CXXConstructorDecl>(Dcl); 906 continue; 907 908 case Decl::EnumConstant: 909 case Decl::IndirectField: 910 case Decl::ParmVar: 911 // These can only appear with other declarations which are banned in 912 // C++11 and permitted in C++1y, so ignore them. 913 continue; 914 915 case Decl::Var: { 916 // C++1y [dcl.constexpr]p3 allows anything except: 917 // a definition of a variable of non-literal type or of static or 918 // thread storage duration or for which no initialization is performed. 919 const auto *VD = cast<VarDecl>(DclIt); 920 if (VD->isThisDeclarationADefinition()) { 921 if (VD->isStaticLocal()) { 922 SemaRef.Diag(VD->getLocation(), 923 diag::err_constexpr_local_var_static) 924 << isa<CXXConstructorDecl>(Dcl) 925 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 926 return false; 927 } 928 if (!VD->getType()->isDependentType() && 929 SemaRef.RequireLiteralType( 930 VD->getLocation(), VD->getType(), 931 diag::err_constexpr_local_var_non_literal_type, 932 isa<CXXConstructorDecl>(Dcl))) 933 return false; 934 if (!VD->getType()->isDependentType() && 935 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 936 SemaRef.Diag(VD->getLocation(), 937 diag::err_constexpr_local_var_no_init) 938 << isa<CXXConstructorDecl>(Dcl); 939 return false; 940 } 941 } 942 SemaRef.Diag(VD->getLocation(), 943 SemaRef.getLangOpts().CPlusPlus14 944 ? diag::warn_cxx11_compat_constexpr_local_var 945 : diag::ext_constexpr_local_var) 946 << isa<CXXConstructorDecl>(Dcl); 947 continue; 948 } 949 950 case Decl::NamespaceAlias: 951 case Decl::Function: 952 // These are disallowed in C++11 and permitted in C++1y. Allow them 953 // everywhere as an extension. 954 if (!Cxx1yLoc.isValid()) 955 Cxx1yLoc = DS->getLocStart(); 956 continue; 957 958 default: 959 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 960 << isa<CXXConstructorDecl>(Dcl); 961 return false; 962 } 963 } 964 965 return true; 966 } 967 968 /// Check that the given field is initialized within a constexpr constructor. 969 /// 970 /// \param Dcl The constexpr constructor being checked. 971 /// \param Field The field being checked. This may be a member of an anonymous 972 /// struct or union nested within the class being checked. 973 /// \param Inits All declarations, including anonymous struct/union members and 974 /// indirect members, for which any initialization was provided. 975 /// \param Diagnosed Set to true if an error is produced. 976 static void CheckConstexprCtorInitializer(Sema &SemaRef, 977 const FunctionDecl *Dcl, 978 FieldDecl *Field, 979 llvm::SmallSet<Decl*, 16> &Inits, 980 bool &Diagnosed) { 981 if (Field->isInvalidDecl()) 982 return; 983 984 if (Field->isUnnamedBitfield()) 985 return; 986 987 // Anonymous unions with no variant members and empty anonymous structs do not 988 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 989 // indirect fields don't need initializing. 990 if (Field->isAnonymousStructOrUnion() && 991 (Field->getType()->isUnionType() 992 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 993 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 994 return; 995 996 if (!Inits.count(Field)) { 997 if (!Diagnosed) { 998 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 999 Diagnosed = true; 1000 } 1001 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1002 } else if (Field->isAnonymousStructOrUnion()) { 1003 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1004 for (auto *I : RD->fields()) 1005 // If an anonymous union contains an anonymous struct of which any member 1006 // is initialized, all members must be initialized. 1007 if (!RD->isUnion() || Inits.count(I)) 1008 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1009 } 1010 } 1011 1012 /// Check the provided statement is allowed in a constexpr function 1013 /// definition. 1014 static bool 1015 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1016 SmallVectorImpl<SourceLocation> &ReturnStmts, 1017 SourceLocation &Cxx1yLoc) { 1018 // - its function-body shall be [...] a compound-statement that contains only 1019 switch (S->getStmtClass()) { 1020 case Stmt::NullStmtClass: 1021 // - null statements, 1022 return true; 1023 1024 case Stmt::DeclStmtClass: 1025 // - static_assert-declarations 1026 // - using-declarations, 1027 // - using-directives, 1028 // - typedef declarations and alias-declarations that do not define 1029 // classes or enumerations, 1030 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1031 return false; 1032 return true; 1033 1034 case Stmt::ReturnStmtClass: 1035 // - and exactly one return statement; 1036 if (isa<CXXConstructorDecl>(Dcl)) { 1037 // C++1y allows return statements in constexpr constructors. 1038 if (!Cxx1yLoc.isValid()) 1039 Cxx1yLoc = S->getLocStart(); 1040 return true; 1041 } 1042 1043 ReturnStmts.push_back(S->getLocStart()); 1044 return true; 1045 1046 case Stmt::CompoundStmtClass: { 1047 // C++1y allows compound-statements. 1048 if (!Cxx1yLoc.isValid()) 1049 Cxx1yLoc = S->getLocStart(); 1050 1051 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1052 for (auto *BodyIt : CompStmt->body()) { 1053 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1054 Cxx1yLoc)) 1055 return false; 1056 } 1057 return true; 1058 } 1059 1060 case Stmt::AttributedStmtClass: 1061 if (!Cxx1yLoc.isValid()) 1062 Cxx1yLoc = S->getLocStart(); 1063 return true; 1064 1065 case Stmt::IfStmtClass: { 1066 // C++1y allows if-statements. 1067 if (!Cxx1yLoc.isValid()) 1068 Cxx1yLoc = S->getLocStart(); 1069 1070 IfStmt *If = cast<IfStmt>(S); 1071 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1072 Cxx1yLoc)) 1073 return false; 1074 if (If->getElse() && 1075 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1076 Cxx1yLoc)) 1077 return false; 1078 return true; 1079 } 1080 1081 case Stmt::WhileStmtClass: 1082 case Stmt::DoStmtClass: 1083 case Stmt::ForStmtClass: 1084 case Stmt::CXXForRangeStmtClass: 1085 case Stmt::ContinueStmtClass: 1086 // C++1y allows all of these. We don't allow them as extensions in C++11, 1087 // because they don't make sense without variable mutation. 1088 if (!SemaRef.getLangOpts().CPlusPlus14) 1089 break; 1090 if (!Cxx1yLoc.isValid()) 1091 Cxx1yLoc = S->getLocStart(); 1092 for (Stmt *SubStmt : S->children()) 1093 if (SubStmt && 1094 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1095 Cxx1yLoc)) 1096 return false; 1097 return true; 1098 1099 case Stmt::SwitchStmtClass: 1100 case Stmt::CaseStmtClass: 1101 case Stmt::DefaultStmtClass: 1102 case Stmt::BreakStmtClass: 1103 // C++1y allows switch-statements, and since they don't need variable 1104 // mutation, we can reasonably allow them in C++11 as an extension. 1105 if (!Cxx1yLoc.isValid()) 1106 Cxx1yLoc = S->getLocStart(); 1107 for (Stmt *SubStmt : S->children()) 1108 if (SubStmt && 1109 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1110 Cxx1yLoc)) 1111 return false; 1112 return true; 1113 1114 default: 1115 if (!isa<Expr>(S)) 1116 break; 1117 1118 // C++1y allows expression-statements. 1119 if (!Cxx1yLoc.isValid()) 1120 Cxx1yLoc = S->getLocStart(); 1121 return true; 1122 } 1123 1124 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1125 << isa<CXXConstructorDecl>(Dcl); 1126 return false; 1127 } 1128 1129 /// Check the body for the given constexpr function declaration only contains 1130 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1131 /// 1132 /// \return true if the body is OK, false if we have diagnosed a problem. 1133 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1134 if (isa<CXXTryStmt>(Body)) { 1135 // C++11 [dcl.constexpr]p3: 1136 // The definition of a constexpr function shall satisfy the following 1137 // constraints: [...] 1138 // - its function-body shall be = delete, = default, or a 1139 // compound-statement 1140 // 1141 // C++11 [dcl.constexpr]p4: 1142 // In the definition of a constexpr constructor, [...] 1143 // - its function-body shall not be a function-try-block; 1144 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1145 << isa<CXXConstructorDecl>(Dcl); 1146 return false; 1147 } 1148 1149 SmallVector<SourceLocation, 4> ReturnStmts; 1150 1151 // - its function-body shall be [...] a compound-statement that contains only 1152 // [... list of cases ...] 1153 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1154 SourceLocation Cxx1yLoc; 1155 for (auto *BodyIt : CompBody->body()) { 1156 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1157 return false; 1158 } 1159 1160 if (Cxx1yLoc.isValid()) 1161 Diag(Cxx1yLoc, 1162 getLangOpts().CPlusPlus14 1163 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1164 : diag::ext_constexpr_body_invalid_stmt) 1165 << isa<CXXConstructorDecl>(Dcl); 1166 1167 if (const CXXConstructorDecl *Constructor 1168 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1169 const CXXRecordDecl *RD = Constructor->getParent(); 1170 // DR1359: 1171 // - every non-variant non-static data member and base class sub-object 1172 // shall be initialized; 1173 // DR1460: 1174 // - if the class is a union having variant members, exactly one of them 1175 // shall be initialized; 1176 if (RD->isUnion()) { 1177 if (Constructor->getNumCtorInitializers() == 0 && 1178 RD->hasVariantMembers()) { 1179 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1180 return false; 1181 } 1182 } else if (!Constructor->isDependentContext() && 1183 !Constructor->isDelegatingConstructor()) { 1184 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1185 1186 // Skip detailed checking if we have enough initializers, and we would 1187 // allow at most one initializer per member. 1188 bool AnyAnonStructUnionMembers = false; 1189 unsigned Fields = 0; 1190 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1191 E = RD->field_end(); I != E; ++I, ++Fields) { 1192 if (I->isAnonymousStructOrUnion()) { 1193 AnyAnonStructUnionMembers = true; 1194 break; 1195 } 1196 } 1197 // DR1460: 1198 // - if the class is a union-like class, but is not a union, for each of 1199 // its anonymous union members having variant members, exactly one of 1200 // them shall be initialized; 1201 if (AnyAnonStructUnionMembers || 1202 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1203 // Check initialization of non-static data members. Base classes are 1204 // always initialized so do not need to be checked. Dependent bases 1205 // might not have initializers in the member initializer list. 1206 llvm::SmallSet<Decl*, 16> Inits; 1207 for (const auto *I: Constructor->inits()) { 1208 if (FieldDecl *FD = I->getMember()) 1209 Inits.insert(FD); 1210 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1211 Inits.insert(ID->chain_begin(), ID->chain_end()); 1212 } 1213 1214 bool Diagnosed = false; 1215 for (auto *I : RD->fields()) 1216 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1217 if (Diagnosed) 1218 return false; 1219 } 1220 } 1221 } else { 1222 if (ReturnStmts.empty()) { 1223 // C++1y doesn't require constexpr functions to contain a 'return' 1224 // statement. We still do, unless the return type might be void, because 1225 // otherwise if there's no return statement, the function cannot 1226 // be used in a core constant expression. 1227 bool OK = getLangOpts().CPlusPlus14 && 1228 (Dcl->getReturnType()->isVoidType() || 1229 Dcl->getReturnType()->isDependentType()); 1230 Diag(Dcl->getLocation(), 1231 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1232 : diag::err_constexpr_body_no_return); 1233 if (!OK) 1234 return false; 1235 } else if (ReturnStmts.size() > 1) { 1236 Diag(ReturnStmts.back(), 1237 getLangOpts().CPlusPlus14 1238 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1239 : diag::ext_constexpr_body_multiple_return); 1240 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1241 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1242 } 1243 } 1244 1245 // C++11 [dcl.constexpr]p5: 1246 // if no function argument values exist such that the function invocation 1247 // substitution would produce a constant expression, the program is 1248 // ill-formed; no diagnostic required. 1249 // C++11 [dcl.constexpr]p3: 1250 // - every constructor call and implicit conversion used in initializing the 1251 // return value shall be one of those allowed in a constant expression. 1252 // C++11 [dcl.constexpr]p4: 1253 // - every constructor involved in initializing non-static data members and 1254 // base class sub-objects shall be a constexpr constructor. 1255 SmallVector<PartialDiagnosticAt, 8> Diags; 1256 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1257 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1258 << isa<CXXConstructorDecl>(Dcl); 1259 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1260 Diag(Diags[I].first, Diags[I].second); 1261 // Don't return false here: we allow this for compatibility in 1262 // system headers. 1263 } 1264 1265 return true; 1266 } 1267 1268 /// isCurrentClassName - Determine whether the identifier II is the 1269 /// name of the class type currently being defined. In the case of 1270 /// nested classes, this will only return true if II is the name of 1271 /// the innermost class. 1272 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1273 const CXXScopeSpec *SS) { 1274 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1275 1276 CXXRecordDecl *CurDecl; 1277 if (SS && SS->isSet() && !SS->isInvalid()) { 1278 DeclContext *DC = computeDeclContext(*SS, true); 1279 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1280 } else 1281 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1282 1283 if (CurDecl && CurDecl->getIdentifier()) 1284 return &II == CurDecl->getIdentifier(); 1285 return false; 1286 } 1287 1288 /// \brief Determine whether the identifier II is a typo for the name of 1289 /// the class type currently being defined. If so, update it to the identifier 1290 /// that should have been used. 1291 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1292 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1293 1294 if (!getLangOpts().SpellChecking) 1295 return false; 1296 1297 CXXRecordDecl *CurDecl; 1298 if (SS && SS->isSet() && !SS->isInvalid()) { 1299 DeclContext *DC = computeDeclContext(*SS, true); 1300 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1301 } else 1302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1303 1304 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1305 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1306 < II->getLength()) { 1307 II = CurDecl->getIdentifier(); 1308 return true; 1309 } 1310 1311 return false; 1312 } 1313 1314 /// \brief Determine whether the given class is a base class of the given 1315 /// class, including looking at dependent bases. 1316 static bool findCircularInheritance(const CXXRecordDecl *Class, 1317 const CXXRecordDecl *Current) { 1318 SmallVector<const CXXRecordDecl*, 8> Queue; 1319 1320 Class = Class->getCanonicalDecl(); 1321 while (true) { 1322 for (const auto &I : Current->bases()) { 1323 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1324 if (!Base) 1325 continue; 1326 1327 Base = Base->getDefinition(); 1328 if (!Base) 1329 continue; 1330 1331 if (Base->getCanonicalDecl() == Class) 1332 return true; 1333 1334 Queue.push_back(Base); 1335 } 1336 1337 if (Queue.empty()) 1338 return false; 1339 1340 Current = Queue.pop_back_val(); 1341 } 1342 1343 return false; 1344 } 1345 1346 /// \brief Check the validity of a C++ base class specifier. 1347 /// 1348 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1349 /// and returns NULL otherwise. 1350 CXXBaseSpecifier * 1351 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1352 SourceRange SpecifierRange, 1353 bool Virtual, AccessSpecifier Access, 1354 TypeSourceInfo *TInfo, 1355 SourceLocation EllipsisLoc) { 1356 QualType BaseType = TInfo->getType(); 1357 1358 // C++ [class.union]p1: 1359 // A union shall not have base classes. 1360 if (Class->isUnion()) { 1361 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1362 << SpecifierRange; 1363 return nullptr; 1364 } 1365 1366 if (EllipsisLoc.isValid() && 1367 !TInfo->getType()->containsUnexpandedParameterPack()) { 1368 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1369 << TInfo->getTypeLoc().getSourceRange(); 1370 EllipsisLoc = SourceLocation(); 1371 } 1372 1373 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1374 1375 if (BaseType->isDependentType()) { 1376 // Make sure that we don't have circular inheritance among our dependent 1377 // bases. For non-dependent bases, the check for completeness below handles 1378 // this. 1379 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1380 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1381 ((BaseDecl = BaseDecl->getDefinition()) && 1382 findCircularInheritance(Class, BaseDecl))) { 1383 Diag(BaseLoc, diag::err_circular_inheritance) 1384 << BaseType << Context.getTypeDeclType(Class); 1385 1386 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1387 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1388 << BaseType; 1389 1390 return nullptr; 1391 } 1392 } 1393 1394 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1395 Class->getTagKind() == TTK_Class, 1396 Access, TInfo, EllipsisLoc); 1397 } 1398 1399 // Base specifiers must be record types. 1400 if (!BaseType->isRecordType()) { 1401 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1402 return nullptr; 1403 } 1404 1405 // C++ [class.union]p1: 1406 // A union shall not be used as a base class. 1407 if (BaseType->isUnionType()) { 1408 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1409 return nullptr; 1410 } 1411 1412 // For the MS ABI, propagate DLL attributes to base class templates. 1413 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1414 if (Attr *ClassAttr = getDLLAttr(Class)) { 1415 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1416 BaseType->getAsCXXRecordDecl())) { 1417 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 1418 BaseLoc); 1419 } 1420 } 1421 } 1422 1423 // C++ [class.derived]p2: 1424 // The class-name in a base-specifier shall not be an incompletely 1425 // defined class. 1426 if (RequireCompleteType(BaseLoc, BaseType, 1427 diag::err_incomplete_base_class, SpecifierRange)) { 1428 Class->setInvalidDecl(); 1429 return nullptr; 1430 } 1431 1432 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1433 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1434 assert(BaseDecl && "Record type has no declaration"); 1435 BaseDecl = BaseDecl->getDefinition(); 1436 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1437 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1438 assert(CXXBaseDecl && "Base type is not a C++ type"); 1439 1440 // A class which contains a flexible array member is not suitable for use as a 1441 // base class: 1442 // - If the layout determines that a base comes before another base, 1443 // the flexible array member would index into the subsequent base. 1444 // - If the layout determines that base comes before the derived class, 1445 // the flexible array member would index into the derived class. 1446 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1447 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1448 << CXXBaseDecl->getDeclName(); 1449 return nullptr; 1450 } 1451 1452 // C++ [class]p3: 1453 // If a class is marked final and it appears as a base-type-specifier in 1454 // base-clause, the program is ill-formed. 1455 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1456 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1457 << CXXBaseDecl->getDeclName() 1458 << FA->isSpelledAsSealed(); 1459 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1460 << CXXBaseDecl->getDeclName() << FA->getRange(); 1461 return nullptr; 1462 } 1463 1464 if (BaseDecl->isInvalidDecl()) 1465 Class->setInvalidDecl(); 1466 1467 // Create the base specifier. 1468 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1469 Class->getTagKind() == TTK_Class, 1470 Access, TInfo, EllipsisLoc); 1471 } 1472 1473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1474 /// one entry in the base class list of a class specifier, for 1475 /// example: 1476 /// class foo : public bar, virtual private baz { 1477 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1478 BaseResult 1479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1480 ParsedAttributes &Attributes, 1481 bool Virtual, AccessSpecifier Access, 1482 ParsedType basetype, SourceLocation BaseLoc, 1483 SourceLocation EllipsisLoc) { 1484 if (!classdecl) 1485 return true; 1486 1487 AdjustDeclIfTemplate(classdecl); 1488 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1489 if (!Class) 1490 return true; 1491 1492 // We haven't yet attached the base specifiers. 1493 Class->setIsParsingBaseSpecifiers(); 1494 1495 // We do not support any C++11 attributes on base-specifiers yet. 1496 // Diagnose any attributes we see. 1497 if (!Attributes.empty()) { 1498 for (AttributeList *Attr = Attributes.getList(); Attr; 1499 Attr = Attr->getNext()) { 1500 if (Attr->isInvalid() || 1501 Attr->getKind() == AttributeList::IgnoredAttribute) 1502 continue; 1503 Diag(Attr->getLoc(), 1504 Attr->getKind() == AttributeList::UnknownAttribute 1505 ? diag::warn_unknown_attribute_ignored 1506 : diag::err_base_specifier_attribute) 1507 << Attr->getName(); 1508 } 1509 } 1510 1511 TypeSourceInfo *TInfo = nullptr; 1512 GetTypeFromParser(basetype, &TInfo); 1513 1514 if (EllipsisLoc.isInvalid() && 1515 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1516 UPPC_BaseType)) 1517 return true; 1518 1519 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1520 Virtual, Access, TInfo, 1521 EllipsisLoc)) 1522 return BaseSpec; 1523 else 1524 Class->setInvalidDecl(); 1525 1526 return true; 1527 } 1528 1529 /// Use small set to collect indirect bases. As this is only used 1530 /// locally, there's no need to abstract the small size parameter. 1531 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 1532 1533 /// \brief Recursively add the bases of Type. Don't add Type itself. 1534 static void 1535 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 1536 const QualType &Type) 1537 { 1538 // Even though the incoming type is a base, it might not be 1539 // a class -- it could be a template parm, for instance. 1540 if (auto Rec = Type->getAs<RecordType>()) { 1541 auto Decl = Rec->getAsCXXRecordDecl(); 1542 1543 // Iterate over its bases. 1544 for (const auto &BaseSpec : Decl->bases()) { 1545 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 1546 .getUnqualifiedType(); 1547 if (Set.insert(Base).second) 1548 // If we've not already seen it, recurse. 1549 NoteIndirectBases(Context, Set, Base); 1550 } 1551 } 1552 } 1553 1554 /// \brief Performs the actual work of attaching the given base class 1555 /// specifiers to a C++ class. 1556 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1557 unsigned NumBases) { 1558 if (NumBases == 0) 1559 return false; 1560 1561 // Used to keep track of which base types we have already seen, so 1562 // that we can properly diagnose redundant direct base types. Note 1563 // that the key is always the unqualified canonical type of the base 1564 // class. 1565 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1566 1567 // Used to track indirect bases so we can see if a direct base is 1568 // ambiguous. 1569 IndirectBaseSet IndirectBaseTypes; 1570 1571 // Copy non-redundant base specifiers into permanent storage. 1572 unsigned NumGoodBases = 0; 1573 bool Invalid = false; 1574 for (unsigned idx = 0; idx < NumBases; ++idx) { 1575 QualType NewBaseType 1576 = Context.getCanonicalType(Bases[idx]->getType()); 1577 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1578 1579 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1580 if (KnownBase) { 1581 // C++ [class.mi]p3: 1582 // A class shall not be specified as a direct base class of a 1583 // derived class more than once. 1584 Diag(Bases[idx]->getLocStart(), 1585 diag::err_duplicate_base_class) 1586 << KnownBase->getType() 1587 << Bases[idx]->getSourceRange(); 1588 1589 // Delete the duplicate base class specifier; we're going to 1590 // overwrite its pointer later. 1591 Context.Deallocate(Bases[idx]); 1592 1593 Invalid = true; 1594 } else { 1595 // Okay, add this new base class. 1596 KnownBase = Bases[idx]; 1597 Bases[NumGoodBases++] = Bases[idx]; 1598 1599 // Note this base's direct & indirect bases, if there could be ambiguity. 1600 if (NumBases > 1) 1601 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 1602 1603 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1604 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1605 if (Class->isInterface() && 1606 (!RD->isInterface() || 1607 KnownBase->getAccessSpecifier() != AS_public)) { 1608 // The Microsoft extension __interface does not permit bases that 1609 // are not themselves public interfaces. 1610 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1611 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1612 << RD->getSourceRange(); 1613 Invalid = true; 1614 } 1615 if (RD->hasAttr<WeakAttr>()) 1616 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1617 } 1618 } 1619 } 1620 1621 // Attach the remaining base class specifiers to the derived class. 1622 Class->setBases(Bases, NumGoodBases); 1623 1624 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 1625 // Check whether this direct base is inaccessible due to ambiguity. 1626 QualType BaseType = Bases[idx]->getType(); 1627 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 1628 .getUnqualifiedType(); 1629 1630 if (IndirectBaseTypes.count(CanonicalBase)) { 1631 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1632 /*DetectVirtual=*/true); 1633 bool found 1634 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 1635 assert(found); 1636 (void)found; 1637 1638 if (Paths.isAmbiguous(CanonicalBase)) 1639 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 1640 << BaseType << getAmbiguousPathsDisplayString(Paths) 1641 << Bases[idx]->getSourceRange(); 1642 else 1643 assert(Bases[idx]->isVirtual()); 1644 } 1645 1646 // Delete the base class specifier, since its data has been copied 1647 // into the CXXRecordDecl. 1648 Context.Deallocate(Bases[idx]); 1649 } 1650 1651 return Invalid; 1652 } 1653 1654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1655 /// class, after checking whether there are any duplicate base 1656 /// classes. 1657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1658 unsigned NumBases) { 1659 if (!ClassDecl || !Bases || !NumBases) 1660 return; 1661 1662 AdjustDeclIfTemplate(ClassDecl); 1663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1664 } 1665 1666 /// \brief Determine whether the type \p Derived is a C++ class that is 1667 /// derived from the type \p Base. 1668 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1669 if (!getLangOpts().CPlusPlus) 1670 return false; 1671 1672 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1673 if (!DerivedRD) 1674 return false; 1675 1676 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1677 if (!BaseRD) 1678 return false; 1679 1680 // If either the base or the derived type is invalid, don't try to 1681 // check whether one is derived from the other. 1682 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1683 return false; 1684 1685 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1686 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1687 } 1688 1689 /// \brief Determine whether the type \p Derived is a C++ class that is 1690 /// derived from the type \p Base. 1691 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1692 if (!getLangOpts().CPlusPlus) 1693 return false; 1694 1695 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1696 if (!DerivedRD) 1697 return false; 1698 1699 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1700 if (!BaseRD) 1701 return false; 1702 1703 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1704 } 1705 1706 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1707 CXXCastPath &BasePathArray) { 1708 assert(BasePathArray.empty() && "Base path array must be empty!"); 1709 assert(Paths.isRecordingPaths() && "Must record paths!"); 1710 1711 const CXXBasePath &Path = Paths.front(); 1712 1713 // We first go backward and check if we have a virtual base. 1714 // FIXME: It would be better if CXXBasePath had the base specifier for 1715 // the nearest virtual base. 1716 unsigned Start = 0; 1717 for (unsigned I = Path.size(); I != 0; --I) { 1718 if (Path[I - 1].Base->isVirtual()) { 1719 Start = I - 1; 1720 break; 1721 } 1722 } 1723 1724 // Now add all bases. 1725 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1726 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1727 } 1728 1729 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1730 /// conversion (where Derived and Base are class types) is 1731 /// well-formed, meaning that the conversion is unambiguous (and 1732 /// that all of the base classes are accessible). Returns true 1733 /// and emits a diagnostic if the code is ill-formed, returns false 1734 /// otherwise. Loc is the location where this routine should point to 1735 /// if there is an error, and Range is the source range to highlight 1736 /// if there is an error. 1737 bool 1738 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1739 unsigned InaccessibleBaseID, 1740 unsigned AmbigiousBaseConvID, 1741 SourceLocation Loc, SourceRange Range, 1742 DeclarationName Name, 1743 CXXCastPath *BasePath) { 1744 // First, determine whether the path from Derived to Base is 1745 // ambiguous. This is slightly more expensive than checking whether 1746 // the Derived to Base conversion exists, because here we need to 1747 // explore multiple paths to determine if there is an ambiguity. 1748 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1749 /*DetectVirtual=*/false); 1750 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1751 assert(DerivationOkay && 1752 "Can only be used with a derived-to-base conversion"); 1753 (void)DerivationOkay; 1754 1755 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1756 if (InaccessibleBaseID) { 1757 // Check that the base class can be accessed. 1758 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1759 InaccessibleBaseID)) { 1760 case AR_inaccessible: 1761 return true; 1762 case AR_accessible: 1763 case AR_dependent: 1764 case AR_delayed: 1765 break; 1766 } 1767 } 1768 1769 // Build a base path if necessary. 1770 if (BasePath) 1771 BuildBasePathArray(Paths, *BasePath); 1772 return false; 1773 } 1774 1775 if (AmbigiousBaseConvID) { 1776 // We know that the derived-to-base conversion is ambiguous, and 1777 // we're going to produce a diagnostic. Perform the derived-to-base 1778 // search just one more time to compute all of the possible paths so 1779 // that we can print them out. This is more expensive than any of 1780 // the previous derived-to-base checks we've done, but at this point 1781 // performance isn't as much of an issue. 1782 Paths.clear(); 1783 Paths.setRecordingPaths(true); 1784 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1785 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1786 (void)StillOkay; 1787 1788 // Build up a textual representation of the ambiguous paths, e.g., 1789 // D -> B -> A, that will be used to illustrate the ambiguous 1790 // conversions in the diagnostic. We only print one of the paths 1791 // to each base class subobject. 1792 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1793 1794 Diag(Loc, AmbigiousBaseConvID) 1795 << Derived << Base << PathDisplayStr << Range << Name; 1796 } 1797 return true; 1798 } 1799 1800 bool 1801 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1802 SourceLocation Loc, SourceRange Range, 1803 CXXCastPath *BasePath, 1804 bool IgnoreAccess) { 1805 return CheckDerivedToBaseConversion(Derived, Base, 1806 IgnoreAccess ? 0 1807 : diag::err_upcast_to_inaccessible_base, 1808 diag::err_ambiguous_derived_to_base_conv, 1809 Loc, Range, DeclarationName(), 1810 BasePath); 1811 } 1812 1813 1814 /// @brief Builds a string representing ambiguous paths from a 1815 /// specific derived class to different subobjects of the same base 1816 /// class. 1817 /// 1818 /// This function builds a string that can be used in error messages 1819 /// to show the different paths that one can take through the 1820 /// inheritance hierarchy to go from the derived class to different 1821 /// subobjects of a base class. The result looks something like this: 1822 /// @code 1823 /// struct D -> struct B -> struct A 1824 /// struct D -> struct C -> struct A 1825 /// @endcode 1826 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1827 std::string PathDisplayStr; 1828 std::set<unsigned> DisplayedPaths; 1829 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1830 Path != Paths.end(); ++Path) { 1831 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1832 // We haven't displayed a path to this particular base 1833 // class subobject yet. 1834 PathDisplayStr += "\n "; 1835 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1836 for (CXXBasePath::const_iterator Element = Path->begin(); 1837 Element != Path->end(); ++Element) 1838 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1839 } 1840 } 1841 1842 return PathDisplayStr; 1843 } 1844 1845 //===----------------------------------------------------------------------===// 1846 // C++ class member Handling 1847 //===----------------------------------------------------------------------===// 1848 1849 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1850 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1851 SourceLocation ASLoc, 1852 SourceLocation ColonLoc, 1853 AttributeList *Attrs) { 1854 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1855 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1856 ASLoc, ColonLoc); 1857 CurContext->addHiddenDecl(ASDecl); 1858 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1859 } 1860 1861 /// CheckOverrideControl - Check C++11 override control semantics. 1862 void Sema::CheckOverrideControl(NamedDecl *D) { 1863 if (D->isInvalidDecl()) 1864 return; 1865 1866 // We only care about "override" and "final" declarations. 1867 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1868 return; 1869 1870 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1871 1872 // We can't check dependent instance methods. 1873 if (MD && MD->isInstance() && 1874 (MD->getParent()->hasAnyDependentBases() || 1875 MD->getType()->isDependentType())) 1876 return; 1877 1878 if (MD && !MD->isVirtual()) { 1879 // If we have a non-virtual method, check if if hides a virtual method. 1880 // (In that case, it's most likely the method has the wrong type.) 1881 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1882 FindHiddenVirtualMethods(MD, OverloadedMethods); 1883 1884 if (!OverloadedMethods.empty()) { 1885 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1886 Diag(OA->getLocation(), 1887 diag::override_keyword_hides_virtual_member_function) 1888 << "override" << (OverloadedMethods.size() > 1); 1889 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1890 Diag(FA->getLocation(), 1891 diag::override_keyword_hides_virtual_member_function) 1892 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1893 << (OverloadedMethods.size() > 1); 1894 } 1895 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1896 MD->setInvalidDecl(); 1897 return; 1898 } 1899 // Fall through into the general case diagnostic. 1900 // FIXME: We might want to attempt typo correction here. 1901 } 1902 1903 if (!MD || !MD->isVirtual()) { 1904 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1905 Diag(OA->getLocation(), 1906 diag::override_keyword_only_allowed_on_virtual_member_functions) 1907 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1908 D->dropAttr<OverrideAttr>(); 1909 } 1910 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1911 Diag(FA->getLocation(), 1912 diag::override_keyword_only_allowed_on_virtual_member_functions) 1913 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1914 << FixItHint::CreateRemoval(FA->getLocation()); 1915 D->dropAttr<FinalAttr>(); 1916 } 1917 return; 1918 } 1919 1920 // C++11 [class.virtual]p5: 1921 // If a function is marked with the virt-specifier override and 1922 // does not override a member function of a base class, the program is 1923 // ill-formed. 1924 bool HasOverriddenMethods = 1925 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1926 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1927 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1928 << MD->getDeclName(); 1929 } 1930 1931 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1932 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1933 return; 1934 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1935 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1936 isa<CXXDestructorDecl>(MD)) 1937 return; 1938 1939 SourceLocation Loc = MD->getLocation(); 1940 SourceLocation SpellingLoc = Loc; 1941 if (getSourceManager().isMacroArgExpansion(Loc)) 1942 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1943 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1944 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1945 return; 1946 1947 if (MD->size_overridden_methods() > 0) { 1948 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 1949 << MD->getDeclName(); 1950 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 1951 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 1952 } 1953 } 1954 1955 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1956 /// function overrides a virtual member function marked 'final', according to 1957 /// C++11 [class.virtual]p4. 1958 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1959 const CXXMethodDecl *Old) { 1960 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1961 if (!FA) 1962 return false; 1963 1964 Diag(New->getLocation(), diag::err_final_function_overridden) 1965 << New->getDeclName() 1966 << FA->isSpelledAsSealed(); 1967 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1968 return true; 1969 } 1970 1971 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1972 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1973 // FIXME: Destruction of ObjC lifetime types has side-effects. 1974 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1975 return !RD->isCompleteDefinition() || 1976 !RD->hasTrivialDefaultConstructor() || 1977 !RD->hasTrivialDestructor(); 1978 return false; 1979 } 1980 1981 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1982 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1983 if (it->isDeclspecPropertyAttribute()) 1984 return it; 1985 return nullptr; 1986 } 1987 1988 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1989 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1990 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1991 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1992 /// present (but parsing it has been deferred). 1993 NamedDecl * 1994 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1995 MultiTemplateParamsArg TemplateParameterLists, 1996 Expr *BW, const VirtSpecifiers &VS, 1997 InClassInitStyle InitStyle) { 1998 const DeclSpec &DS = D.getDeclSpec(); 1999 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2000 DeclarationName Name = NameInfo.getName(); 2001 SourceLocation Loc = NameInfo.getLoc(); 2002 2003 // For anonymous bitfields, the location should point to the type. 2004 if (Loc.isInvalid()) 2005 Loc = D.getLocStart(); 2006 2007 Expr *BitWidth = static_cast<Expr*>(BW); 2008 2009 assert(isa<CXXRecordDecl>(CurContext)); 2010 assert(!DS.isFriendSpecified()); 2011 2012 bool isFunc = D.isDeclarationOfFunction(); 2013 2014 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2015 // The Microsoft extension __interface only permits public member functions 2016 // and prohibits constructors, destructors, operators, non-public member 2017 // functions, static methods and data members. 2018 unsigned InvalidDecl; 2019 bool ShowDeclName = true; 2020 if (!isFunc) 2021 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2022 else if (AS != AS_public) 2023 InvalidDecl = 2; 2024 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2025 InvalidDecl = 3; 2026 else switch (Name.getNameKind()) { 2027 case DeclarationName::CXXConstructorName: 2028 InvalidDecl = 4; 2029 ShowDeclName = false; 2030 break; 2031 2032 case DeclarationName::CXXDestructorName: 2033 InvalidDecl = 5; 2034 ShowDeclName = false; 2035 break; 2036 2037 case DeclarationName::CXXOperatorName: 2038 case DeclarationName::CXXConversionFunctionName: 2039 InvalidDecl = 6; 2040 break; 2041 2042 default: 2043 InvalidDecl = 0; 2044 break; 2045 } 2046 2047 if (InvalidDecl) { 2048 if (ShowDeclName) 2049 Diag(Loc, diag::err_invalid_member_in_interface) 2050 << (InvalidDecl-1) << Name; 2051 else 2052 Diag(Loc, diag::err_invalid_member_in_interface) 2053 << (InvalidDecl-1) << ""; 2054 return nullptr; 2055 } 2056 } 2057 2058 // C++ 9.2p6: A member shall not be declared to have automatic storage 2059 // duration (auto, register) or with the extern storage-class-specifier. 2060 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2061 // data members and cannot be applied to names declared const or static, 2062 // and cannot be applied to reference members. 2063 switch (DS.getStorageClassSpec()) { 2064 case DeclSpec::SCS_unspecified: 2065 case DeclSpec::SCS_typedef: 2066 case DeclSpec::SCS_static: 2067 break; 2068 case DeclSpec::SCS_mutable: 2069 if (isFunc) { 2070 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2071 2072 // FIXME: It would be nicer if the keyword was ignored only for this 2073 // declarator. Otherwise we could get follow-up errors. 2074 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2075 } 2076 break; 2077 default: 2078 Diag(DS.getStorageClassSpecLoc(), 2079 diag::err_storageclass_invalid_for_member); 2080 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2081 break; 2082 } 2083 2084 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2085 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2086 !isFunc); 2087 2088 if (DS.isConstexprSpecified() && isInstField) { 2089 SemaDiagnosticBuilder B = 2090 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2091 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2092 if (InitStyle == ICIS_NoInit) { 2093 B << 0 << 0; 2094 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2095 B << FixItHint::CreateRemoval(ConstexprLoc); 2096 else { 2097 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2098 D.getMutableDeclSpec().ClearConstexprSpec(); 2099 const char *PrevSpec; 2100 unsigned DiagID; 2101 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2102 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2103 (void)Failed; 2104 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2105 } 2106 } else { 2107 B << 1; 2108 const char *PrevSpec; 2109 unsigned DiagID; 2110 if (D.getMutableDeclSpec().SetStorageClassSpec( 2111 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2112 Context.getPrintingPolicy())) { 2113 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2114 "This is the only DeclSpec that should fail to be applied"); 2115 B << 1; 2116 } else { 2117 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2118 isInstField = false; 2119 } 2120 } 2121 } 2122 2123 NamedDecl *Member; 2124 if (isInstField) { 2125 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2126 2127 // Data members must have identifiers for names. 2128 if (!Name.isIdentifier()) { 2129 Diag(Loc, diag::err_bad_variable_name) 2130 << Name; 2131 return nullptr; 2132 } 2133 2134 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2135 2136 // Member field could not be with "template" keyword. 2137 // So TemplateParameterLists should be empty in this case. 2138 if (TemplateParameterLists.size()) { 2139 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2140 if (TemplateParams->size()) { 2141 // There is no such thing as a member field template. 2142 Diag(D.getIdentifierLoc(), diag::err_template_member) 2143 << II 2144 << SourceRange(TemplateParams->getTemplateLoc(), 2145 TemplateParams->getRAngleLoc()); 2146 } else { 2147 // There is an extraneous 'template<>' for this member. 2148 Diag(TemplateParams->getTemplateLoc(), 2149 diag::err_template_member_noparams) 2150 << II 2151 << SourceRange(TemplateParams->getTemplateLoc(), 2152 TemplateParams->getRAngleLoc()); 2153 } 2154 return nullptr; 2155 } 2156 2157 if (SS.isSet() && !SS.isInvalid()) { 2158 // The user provided a superfluous scope specifier inside a class 2159 // definition: 2160 // 2161 // class X { 2162 // int X::member; 2163 // }; 2164 if (DeclContext *DC = computeDeclContext(SS, false)) 2165 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2166 else 2167 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2168 << Name << SS.getRange(); 2169 2170 SS.clear(); 2171 } 2172 2173 AttributeList *MSPropertyAttr = 2174 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2175 if (MSPropertyAttr) { 2176 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2177 BitWidth, InitStyle, AS, MSPropertyAttr); 2178 if (!Member) 2179 return nullptr; 2180 isInstField = false; 2181 } else { 2182 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2183 BitWidth, InitStyle, AS); 2184 assert(Member && "HandleField never returns null"); 2185 } 2186 } else { 2187 Member = HandleDeclarator(S, D, TemplateParameterLists); 2188 if (!Member) 2189 return nullptr; 2190 2191 // Non-instance-fields can't have a bitfield. 2192 if (BitWidth) { 2193 if (Member->isInvalidDecl()) { 2194 // don't emit another diagnostic. 2195 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 2196 // C++ 9.6p3: A bit-field shall not be a static member. 2197 // "static member 'A' cannot be a bit-field" 2198 Diag(Loc, diag::err_static_not_bitfield) 2199 << Name << BitWidth->getSourceRange(); 2200 } else if (isa<TypedefDecl>(Member)) { 2201 // "typedef member 'x' cannot be a bit-field" 2202 Diag(Loc, diag::err_typedef_not_bitfield) 2203 << Name << BitWidth->getSourceRange(); 2204 } else { 2205 // A function typedef ("typedef int f(); f a;"). 2206 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2207 Diag(Loc, diag::err_not_integral_type_bitfield) 2208 << Name << cast<ValueDecl>(Member)->getType() 2209 << BitWidth->getSourceRange(); 2210 } 2211 2212 BitWidth = nullptr; 2213 Member->setInvalidDecl(); 2214 } 2215 2216 Member->setAccess(AS); 2217 2218 // If we have declared a member function template or static data member 2219 // template, set the access of the templated declaration as well. 2220 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2221 FunTmpl->getTemplatedDecl()->setAccess(AS); 2222 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2223 VarTmpl->getTemplatedDecl()->setAccess(AS); 2224 } 2225 2226 if (VS.isOverrideSpecified()) 2227 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2228 if (VS.isFinalSpecified()) 2229 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2230 VS.isFinalSpelledSealed())); 2231 2232 if (VS.getLastLocation().isValid()) { 2233 // Update the end location of a method that has a virt-specifiers. 2234 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2235 MD->setRangeEnd(VS.getLastLocation()); 2236 } 2237 2238 CheckOverrideControl(Member); 2239 2240 assert((Name || isInstField) && "No identifier for non-field ?"); 2241 2242 if (isInstField) { 2243 FieldDecl *FD = cast<FieldDecl>(Member); 2244 FieldCollector->Add(FD); 2245 2246 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2247 // Remember all explicit private FieldDecls that have a name, no side 2248 // effects and are not part of a dependent type declaration. 2249 if (!FD->isImplicit() && FD->getDeclName() && 2250 FD->getAccess() == AS_private && 2251 !FD->hasAttr<UnusedAttr>() && 2252 !FD->getParent()->isDependentContext() && 2253 !InitializationHasSideEffects(*FD)) 2254 UnusedPrivateFields.insert(FD); 2255 } 2256 } 2257 2258 return Member; 2259 } 2260 2261 namespace { 2262 class UninitializedFieldVisitor 2263 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2264 Sema &S; 2265 // List of Decls to generate a warning on. Also remove Decls that become 2266 // initialized. 2267 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2268 // List of base classes of the record. Classes are removed after their 2269 // initializers. 2270 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 2271 // Vector of decls to be removed from the Decl set prior to visiting the 2272 // nodes. These Decls may have been initialized in the prior initializer. 2273 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2274 // If non-null, add a note to the warning pointing back to the constructor. 2275 const CXXConstructorDecl *Constructor; 2276 // Variables to hold state when processing an initializer list. When 2277 // InitList is true, special case initialization of FieldDecls matching 2278 // InitListFieldDecl. 2279 bool InitList; 2280 FieldDecl *InitListFieldDecl; 2281 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2282 2283 public: 2284 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2285 UninitializedFieldVisitor(Sema &S, 2286 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 2287 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 2288 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 2289 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 2290 2291 // Returns true if the use of ME is not an uninitialized use. 2292 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2293 bool CheckReferenceOnly) { 2294 llvm::SmallVector<FieldDecl*, 4> Fields; 2295 bool ReferenceField = false; 2296 while (ME) { 2297 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2298 if (!FD) 2299 return false; 2300 Fields.push_back(FD); 2301 if (FD->getType()->isReferenceType()) 2302 ReferenceField = true; 2303 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2304 } 2305 2306 // Binding a reference to an unintialized field is not an 2307 // uninitialized use. 2308 if (CheckReferenceOnly && !ReferenceField) 2309 return true; 2310 2311 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2312 // Discard the first field since it is the field decl that is being 2313 // initialized. 2314 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2315 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2316 } 2317 2318 for (auto UsedIter = UsedFieldIndex.begin(), 2319 UsedEnd = UsedFieldIndex.end(), 2320 OrigIter = InitFieldIndex.begin(), 2321 OrigEnd = InitFieldIndex.end(); 2322 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2323 if (*UsedIter < *OrigIter) 2324 return true; 2325 if (*UsedIter > *OrigIter) 2326 break; 2327 } 2328 2329 return false; 2330 } 2331 2332 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2333 bool AddressOf) { 2334 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2335 return; 2336 2337 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2338 // or union. 2339 MemberExpr *FieldME = ME; 2340 2341 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2342 2343 Expr *Base = ME; 2344 while (MemberExpr *SubME = 2345 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 2346 2347 if (isa<VarDecl>(SubME->getMemberDecl())) 2348 return; 2349 2350 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2351 if (!FD->isAnonymousStructOrUnion()) 2352 FieldME = SubME; 2353 2354 if (!FieldME->getType().isPODType(S.Context)) 2355 AllPODFields = false; 2356 2357 Base = SubME->getBase(); 2358 } 2359 2360 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 2361 return; 2362 2363 if (AddressOf && AllPODFields) 2364 return; 2365 2366 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2367 2368 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 2369 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 2370 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 2371 } 2372 2373 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 2374 QualType T = BaseCast->getType(); 2375 if (T->isPointerType() && 2376 BaseClasses.count(T->getPointeeType())) { 2377 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 2378 << T->getPointeeType() << FoundVD; 2379 } 2380 } 2381 } 2382 2383 if (!Decls.count(FoundVD)) 2384 return; 2385 2386 const bool IsReference = FoundVD->getType()->isReferenceType(); 2387 2388 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2389 // Special checking for initializer lists. 2390 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2391 return; 2392 } 2393 } else { 2394 // Prevent double warnings on use of unbounded references. 2395 if (CheckReferenceOnly && !IsReference) 2396 return; 2397 } 2398 2399 unsigned diag = IsReference 2400 ? diag::warn_reference_field_is_uninit 2401 : diag::warn_field_is_uninit; 2402 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2403 if (Constructor) 2404 S.Diag(Constructor->getLocation(), 2405 diag::note_uninit_in_this_constructor) 2406 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2407 2408 } 2409 2410 void HandleValue(Expr *E, bool AddressOf) { 2411 E = E->IgnoreParens(); 2412 2413 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2414 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2415 AddressOf /*AddressOf*/); 2416 return; 2417 } 2418 2419 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2420 Visit(CO->getCond()); 2421 HandleValue(CO->getTrueExpr(), AddressOf); 2422 HandleValue(CO->getFalseExpr(), AddressOf); 2423 return; 2424 } 2425 2426 if (BinaryConditionalOperator *BCO = 2427 dyn_cast<BinaryConditionalOperator>(E)) { 2428 Visit(BCO->getCond()); 2429 HandleValue(BCO->getFalseExpr(), AddressOf); 2430 return; 2431 } 2432 2433 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2434 HandleValue(OVE->getSourceExpr(), AddressOf); 2435 return; 2436 } 2437 2438 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2439 switch (BO->getOpcode()) { 2440 default: 2441 break; 2442 case(BO_PtrMemD): 2443 case(BO_PtrMemI): 2444 HandleValue(BO->getLHS(), AddressOf); 2445 Visit(BO->getRHS()); 2446 return; 2447 case(BO_Comma): 2448 Visit(BO->getLHS()); 2449 HandleValue(BO->getRHS(), AddressOf); 2450 return; 2451 } 2452 } 2453 2454 Visit(E); 2455 } 2456 2457 void CheckInitListExpr(InitListExpr *ILE) { 2458 InitFieldIndex.push_back(0); 2459 for (auto Child : ILE->children()) { 2460 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2461 CheckInitListExpr(SubList); 2462 } else { 2463 Visit(Child); 2464 } 2465 ++InitFieldIndex.back(); 2466 } 2467 InitFieldIndex.pop_back(); 2468 } 2469 2470 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2471 FieldDecl *Field, const Type *BaseClass) { 2472 // Remove Decls that may have been initialized in the previous 2473 // initializer. 2474 for (ValueDecl* VD : DeclsToRemove) 2475 Decls.erase(VD); 2476 DeclsToRemove.clear(); 2477 2478 Constructor = FieldConstructor; 2479 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2480 2481 if (ILE && Field) { 2482 InitList = true; 2483 InitListFieldDecl = Field; 2484 InitFieldIndex.clear(); 2485 CheckInitListExpr(ILE); 2486 } else { 2487 InitList = false; 2488 Visit(E); 2489 } 2490 2491 if (Field) 2492 Decls.erase(Field); 2493 if (BaseClass) 2494 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 2495 } 2496 2497 void VisitMemberExpr(MemberExpr *ME) { 2498 // All uses of unbounded reference fields will warn. 2499 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2500 } 2501 2502 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2503 if (E->getCastKind() == CK_LValueToRValue) { 2504 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2505 return; 2506 } 2507 2508 Inherited::VisitImplicitCastExpr(E); 2509 } 2510 2511 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2512 if (E->getConstructor()->isCopyConstructor()) { 2513 Expr *ArgExpr = E->getArg(0); 2514 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2515 if (ILE->getNumInits() == 1) 2516 ArgExpr = ILE->getInit(0); 2517 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2518 if (ICE->getCastKind() == CK_NoOp) 2519 ArgExpr = ICE->getSubExpr(); 2520 HandleValue(ArgExpr, false /*AddressOf*/); 2521 return; 2522 } 2523 Inherited::VisitCXXConstructExpr(E); 2524 } 2525 2526 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2527 Expr *Callee = E->getCallee(); 2528 if (isa<MemberExpr>(Callee)) { 2529 HandleValue(Callee, false /*AddressOf*/); 2530 for (auto Arg : E->arguments()) 2531 Visit(Arg); 2532 return; 2533 } 2534 2535 Inherited::VisitCXXMemberCallExpr(E); 2536 } 2537 2538 void VisitCallExpr(CallExpr *E) { 2539 // Treat std::move as a use. 2540 if (E->getNumArgs() == 1) { 2541 if (FunctionDecl *FD = E->getDirectCallee()) { 2542 if (FD->isInStdNamespace() && FD->getIdentifier() && 2543 FD->getIdentifier()->isStr("move")) { 2544 HandleValue(E->getArg(0), false /*AddressOf*/); 2545 return; 2546 } 2547 } 2548 } 2549 2550 Inherited::VisitCallExpr(E); 2551 } 2552 2553 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2554 Expr *Callee = E->getCallee(); 2555 2556 if (isa<UnresolvedLookupExpr>(Callee)) 2557 return Inherited::VisitCXXOperatorCallExpr(E); 2558 2559 Visit(Callee); 2560 for (auto Arg : E->arguments()) 2561 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2562 } 2563 2564 void VisitBinaryOperator(BinaryOperator *E) { 2565 // If a field assignment is detected, remove the field from the 2566 // uninitiailized field set. 2567 if (E->getOpcode() == BO_Assign) 2568 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2569 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2570 if (!FD->getType()->isReferenceType()) 2571 DeclsToRemove.push_back(FD); 2572 2573 if (E->isCompoundAssignmentOp()) { 2574 HandleValue(E->getLHS(), false /*AddressOf*/); 2575 Visit(E->getRHS()); 2576 return; 2577 } 2578 2579 Inherited::VisitBinaryOperator(E); 2580 } 2581 2582 void VisitUnaryOperator(UnaryOperator *E) { 2583 if (E->isIncrementDecrementOp()) { 2584 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2585 return; 2586 } 2587 if (E->getOpcode() == UO_AddrOf) { 2588 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2589 HandleValue(ME->getBase(), true /*AddressOf*/); 2590 return; 2591 } 2592 } 2593 2594 Inherited::VisitUnaryOperator(E); 2595 } 2596 }; 2597 2598 // Diagnose value-uses of fields to initialize themselves, e.g. 2599 // foo(foo) 2600 // where foo is not also a parameter to the constructor. 2601 // Also diagnose across field uninitialized use such as 2602 // x(y), y(x) 2603 // TODO: implement -Wuninitialized and fold this into that framework. 2604 static void DiagnoseUninitializedFields( 2605 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2606 2607 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2608 Constructor->getLocation())) { 2609 return; 2610 } 2611 2612 if (Constructor->isInvalidDecl()) 2613 return; 2614 2615 const CXXRecordDecl *RD = Constructor->getParent(); 2616 2617 if (RD->getDescribedClassTemplate()) 2618 return; 2619 2620 // Holds fields that are uninitialized. 2621 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2622 2623 // At the beginning, all fields are uninitialized. 2624 for (auto *I : RD->decls()) { 2625 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2626 UninitializedFields.insert(FD); 2627 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2628 UninitializedFields.insert(IFD->getAnonField()); 2629 } 2630 } 2631 2632 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 2633 for (auto I : RD->bases()) 2634 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 2635 2636 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2637 return; 2638 2639 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2640 UninitializedFields, 2641 UninitializedBaseClasses); 2642 2643 for (const auto *FieldInit : Constructor->inits()) { 2644 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2645 break; 2646 2647 Expr *InitExpr = FieldInit->getInit(); 2648 if (!InitExpr) 2649 continue; 2650 2651 if (CXXDefaultInitExpr *Default = 2652 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2653 InitExpr = Default->getExpr(); 2654 if (!InitExpr) 2655 continue; 2656 // In class initializers will point to the constructor. 2657 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2658 FieldInit->getAnyMember(), 2659 FieldInit->getBaseClass()); 2660 } else { 2661 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2662 FieldInit->getAnyMember(), 2663 FieldInit->getBaseClass()); 2664 } 2665 } 2666 } 2667 } // namespace 2668 2669 /// \brief Enter a new C++ default initializer scope. After calling this, the 2670 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2671 /// parsing or instantiating the initializer failed. 2672 void Sema::ActOnStartCXXInClassMemberInitializer() { 2673 // Create a synthetic function scope to represent the call to the constructor 2674 // that notionally surrounds a use of this initializer. 2675 PushFunctionScope(); 2676 } 2677 2678 /// \brief This is invoked after parsing an in-class initializer for a 2679 /// non-static C++ class member, and after instantiating an in-class initializer 2680 /// in a class template. Such actions are deferred until the class is complete. 2681 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2682 SourceLocation InitLoc, 2683 Expr *InitExpr) { 2684 // Pop the notional constructor scope we created earlier. 2685 PopFunctionScopeInfo(nullptr, D); 2686 2687 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2688 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 2689 "must set init style when field is created"); 2690 2691 if (!InitExpr) { 2692 D->setInvalidDecl(); 2693 if (FD) 2694 FD->removeInClassInitializer(); 2695 return; 2696 } 2697 2698 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2699 FD->setInvalidDecl(); 2700 FD->removeInClassInitializer(); 2701 return; 2702 } 2703 2704 ExprResult Init = InitExpr; 2705 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2706 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2707 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2708 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2709 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2710 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2711 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2712 if (Init.isInvalid()) { 2713 FD->setInvalidDecl(); 2714 return; 2715 } 2716 } 2717 2718 // C++11 [class.base.init]p7: 2719 // The initialization of each base and member constitutes a 2720 // full-expression. 2721 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2722 if (Init.isInvalid()) { 2723 FD->setInvalidDecl(); 2724 return; 2725 } 2726 2727 InitExpr = Init.get(); 2728 2729 FD->setInClassInitializer(InitExpr); 2730 } 2731 2732 /// \brief Find the direct and/or virtual base specifiers that 2733 /// correspond to the given base type, for use in base initialization 2734 /// within a constructor. 2735 static bool FindBaseInitializer(Sema &SemaRef, 2736 CXXRecordDecl *ClassDecl, 2737 QualType BaseType, 2738 const CXXBaseSpecifier *&DirectBaseSpec, 2739 const CXXBaseSpecifier *&VirtualBaseSpec) { 2740 // First, check for a direct base class. 2741 DirectBaseSpec = nullptr; 2742 for (const auto &Base : ClassDecl->bases()) { 2743 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2744 // We found a direct base of this type. That's what we're 2745 // initializing. 2746 DirectBaseSpec = &Base; 2747 break; 2748 } 2749 } 2750 2751 // Check for a virtual base class. 2752 // FIXME: We might be able to short-circuit this if we know in advance that 2753 // there are no virtual bases. 2754 VirtualBaseSpec = nullptr; 2755 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2756 // We haven't found a base yet; search the class hierarchy for a 2757 // virtual base class. 2758 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2759 /*DetectVirtual=*/false); 2760 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2761 BaseType, Paths)) { 2762 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2763 Path != Paths.end(); ++Path) { 2764 if (Path->back().Base->isVirtual()) { 2765 VirtualBaseSpec = Path->back().Base; 2766 break; 2767 } 2768 } 2769 } 2770 } 2771 2772 return DirectBaseSpec || VirtualBaseSpec; 2773 } 2774 2775 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2776 MemInitResult 2777 Sema::ActOnMemInitializer(Decl *ConstructorD, 2778 Scope *S, 2779 CXXScopeSpec &SS, 2780 IdentifierInfo *MemberOrBase, 2781 ParsedType TemplateTypeTy, 2782 const DeclSpec &DS, 2783 SourceLocation IdLoc, 2784 Expr *InitList, 2785 SourceLocation EllipsisLoc) { 2786 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2787 DS, IdLoc, InitList, 2788 EllipsisLoc); 2789 } 2790 2791 /// \brief Handle a C++ member initializer using parentheses syntax. 2792 MemInitResult 2793 Sema::ActOnMemInitializer(Decl *ConstructorD, 2794 Scope *S, 2795 CXXScopeSpec &SS, 2796 IdentifierInfo *MemberOrBase, 2797 ParsedType TemplateTypeTy, 2798 const DeclSpec &DS, 2799 SourceLocation IdLoc, 2800 SourceLocation LParenLoc, 2801 ArrayRef<Expr *> Args, 2802 SourceLocation RParenLoc, 2803 SourceLocation EllipsisLoc) { 2804 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2805 Args, RParenLoc); 2806 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2807 DS, IdLoc, List, EllipsisLoc); 2808 } 2809 2810 namespace { 2811 2812 // Callback to only accept typo corrections that can be a valid C++ member 2813 // intializer: either a non-static field member or a base class. 2814 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2815 public: 2816 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2817 : ClassDecl(ClassDecl) {} 2818 2819 bool ValidateCandidate(const TypoCorrection &candidate) override { 2820 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2821 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2822 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2823 return isa<TypeDecl>(ND); 2824 } 2825 return false; 2826 } 2827 2828 private: 2829 CXXRecordDecl *ClassDecl; 2830 }; 2831 2832 } 2833 2834 /// \brief Handle a C++ member initializer. 2835 MemInitResult 2836 Sema::BuildMemInitializer(Decl *ConstructorD, 2837 Scope *S, 2838 CXXScopeSpec &SS, 2839 IdentifierInfo *MemberOrBase, 2840 ParsedType TemplateTypeTy, 2841 const DeclSpec &DS, 2842 SourceLocation IdLoc, 2843 Expr *Init, 2844 SourceLocation EllipsisLoc) { 2845 ExprResult Res = CorrectDelayedTyposInExpr(Init); 2846 if (!Res.isUsable()) 2847 return true; 2848 Init = Res.get(); 2849 2850 if (!ConstructorD) 2851 return true; 2852 2853 AdjustDeclIfTemplate(ConstructorD); 2854 2855 CXXConstructorDecl *Constructor 2856 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2857 if (!Constructor) { 2858 // The user wrote a constructor initializer on a function that is 2859 // not a C++ constructor. Ignore the error for now, because we may 2860 // have more member initializers coming; we'll diagnose it just 2861 // once in ActOnMemInitializers. 2862 return true; 2863 } 2864 2865 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2866 2867 // C++ [class.base.init]p2: 2868 // Names in a mem-initializer-id are looked up in the scope of the 2869 // constructor's class and, if not found in that scope, are looked 2870 // up in the scope containing the constructor's definition. 2871 // [Note: if the constructor's class contains a member with the 2872 // same name as a direct or virtual base class of the class, a 2873 // mem-initializer-id naming the member or base class and composed 2874 // of a single identifier refers to the class member. A 2875 // mem-initializer-id for the hidden base class may be specified 2876 // using a qualified name. ] 2877 if (!SS.getScopeRep() && !TemplateTypeTy) { 2878 // Look for a member, first. 2879 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2880 if (!Result.empty()) { 2881 ValueDecl *Member; 2882 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2883 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2884 if (EllipsisLoc.isValid()) 2885 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2886 << MemberOrBase 2887 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2888 2889 return BuildMemberInitializer(Member, Init, IdLoc); 2890 } 2891 } 2892 } 2893 // It didn't name a member, so see if it names a class. 2894 QualType BaseType; 2895 TypeSourceInfo *TInfo = nullptr; 2896 2897 if (TemplateTypeTy) { 2898 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2899 } else if (DS.getTypeSpecType() == TST_decltype) { 2900 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2901 } else { 2902 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2903 LookupParsedName(R, S, &SS); 2904 2905 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2906 if (!TyD) { 2907 if (R.isAmbiguous()) return true; 2908 2909 // We don't want access-control diagnostics here. 2910 R.suppressDiagnostics(); 2911 2912 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2913 bool NotUnknownSpecialization = false; 2914 DeclContext *DC = computeDeclContext(SS, false); 2915 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2916 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2917 2918 if (!NotUnknownSpecialization) { 2919 // When the scope specifier can refer to a member of an unknown 2920 // specialization, we take it as a type name. 2921 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2922 SS.getWithLocInContext(Context), 2923 *MemberOrBase, IdLoc); 2924 if (BaseType.isNull()) 2925 return true; 2926 2927 R.clear(); 2928 R.setLookupName(MemberOrBase); 2929 } 2930 } 2931 2932 // If no results were found, try to correct typos. 2933 TypoCorrection Corr; 2934 if (R.empty() && BaseType.isNull() && 2935 (Corr = CorrectTypo( 2936 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2937 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2938 CTK_ErrorRecovery, ClassDecl))) { 2939 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2940 // We have found a non-static data member with a similar 2941 // name to what was typed; complain and initialize that 2942 // member. 2943 diagnoseTypo(Corr, 2944 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2945 << MemberOrBase << true); 2946 return BuildMemberInitializer(Member, Init, IdLoc); 2947 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2948 const CXXBaseSpecifier *DirectBaseSpec; 2949 const CXXBaseSpecifier *VirtualBaseSpec; 2950 if (FindBaseInitializer(*this, ClassDecl, 2951 Context.getTypeDeclType(Type), 2952 DirectBaseSpec, VirtualBaseSpec)) { 2953 // We have found a direct or virtual base class with a 2954 // similar name to what was typed; complain and initialize 2955 // that base class. 2956 diagnoseTypo(Corr, 2957 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2958 << MemberOrBase << false, 2959 PDiag() /*Suppress note, we provide our own.*/); 2960 2961 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2962 : VirtualBaseSpec; 2963 Diag(BaseSpec->getLocStart(), 2964 diag::note_base_class_specified_here) 2965 << BaseSpec->getType() 2966 << BaseSpec->getSourceRange(); 2967 2968 TyD = Type; 2969 } 2970 } 2971 } 2972 2973 if (!TyD && BaseType.isNull()) { 2974 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2975 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2976 return true; 2977 } 2978 } 2979 2980 if (BaseType.isNull()) { 2981 BaseType = Context.getTypeDeclType(TyD); 2982 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 2983 if (SS.isSet()) 2984 // FIXME: preserve source range information 2985 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2986 BaseType); 2987 } 2988 } 2989 2990 if (!TInfo) 2991 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2992 2993 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2994 } 2995 2996 /// Checks a member initializer expression for cases where reference (or 2997 /// pointer) members are bound to by-value parameters (or their addresses). 2998 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2999 Expr *Init, 3000 SourceLocation IdLoc) { 3001 QualType MemberTy = Member->getType(); 3002 3003 // We only handle pointers and references currently. 3004 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3005 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3006 return; 3007 3008 const bool IsPointer = MemberTy->isPointerType(); 3009 if (IsPointer) { 3010 if (const UnaryOperator *Op 3011 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3012 // The only case we're worried about with pointers requires taking the 3013 // address. 3014 if (Op->getOpcode() != UO_AddrOf) 3015 return; 3016 3017 Init = Op->getSubExpr(); 3018 } else { 3019 // We only handle address-of expression initializers for pointers. 3020 return; 3021 } 3022 } 3023 3024 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3025 // We only warn when referring to a non-reference parameter declaration. 3026 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3027 if (!Parameter || Parameter->getType()->isReferenceType()) 3028 return; 3029 3030 S.Diag(Init->getExprLoc(), 3031 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3032 : diag::warn_bind_ref_member_to_parameter) 3033 << Member << Parameter << Init->getSourceRange(); 3034 } else { 3035 // Other initializers are fine. 3036 return; 3037 } 3038 3039 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3040 << (unsigned)IsPointer; 3041 } 3042 3043 MemInitResult 3044 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3045 SourceLocation IdLoc) { 3046 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3047 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3048 assert((DirectMember || IndirectMember) && 3049 "Member must be a FieldDecl or IndirectFieldDecl"); 3050 3051 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3052 return true; 3053 3054 if (Member->isInvalidDecl()) 3055 return true; 3056 3057 MultiExprArg Args; 3058 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3059 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3060 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3061 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3062 } else { 3063 // Template instantiation doesn't reconstruct ParenListExprs for us. 3064 Args = Init; 3065 } 3066 3067 SourceRange InitRange = Init->getSourceRange(); 3068 3069 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3070 // Can't check initialization for a member of dependent type or when 3071 // any of the arguments are type-dependent expressions. 3072 DiscardCleanupsInEvaluationContext(); 3073 } else { 3074 bool InitList = false; 3075 if (isa<InitListExpr>(Init)) { 3076 InitList = true; 3077 Args = Init; 3078 } 3079 3080 // Initialize the member. 3081 InitializedEntity MemberEntity = 3082 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3083 : InitializedEntity::InitializeMember(IndirectMember, 3084 nullptr); 3085 InitializationKind Kind = 3086 InitList ? InitializationKind::CreateDirectList(IdLoc) 3087 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3088 InitRange.getEnd()); 3089 3090 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3091 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3092 nullptr); 3093 if (MemberInit.isInvalid()) 3094 return true; 3095 3096 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3097 3098 // C++11 [class.base.init]p7: 3099 // The initialization of each base and member constitutes a 3100 // full-expression. 3101 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3102 if (MemberInit.isInvalid()) 3103 return true; 3104 3105 Init = MemberInit.get(); 3106 } 3107 3108 if (DirectMember) { 3109 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3110 InitRange.getBegin(), Init, 3111 InitRange.getEnd()); 3112 } else { 3113 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3114 InitRange.getBegin(), Init, 3115 InitRange.getEnd()); 3116 } 3117 } 3118 3119 MemInitResult 3120 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3121 CXXRecordDecl *ClassDecl) { 3122 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3123 if (!LangOpts.CPlusPlus11) 3124 return Diag(NameLoc, diag::err_delegating_ctor) 3125 << TInfo->getTypeLoc().getLocalSourceRange(); 3126 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3127 3128 bool InitList = true; 3129 MultiExprArg Args = Init; 3130 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3131 InitList = false; 3132 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3133 } 3134 3135 SourceRange InitRange = Init->getSourceRange(); 3136 // Initialize the object. 3137 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3138 QualType(ClassDecl->getTypeForDecl(), 0)); 3139 InitializationKind Kind = 3140 InitList ? InitializationKind::CreateDirectList(NameLoc) 3141 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3142 InitRange.getEnd()); 3143 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3144 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3145 Args, nullptr); 3146 if (DelegationInit.isInvalid()) 3147 return true; 3148 3149 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3150 "Delegating constructor with no target?"); 3151 3152 // C++11 [class.base.init]p7: 3153 // The initialization of each base and member constitutes a 3154 // full-expression. 3155 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3156 InitRange.getBegin()); 3157 if (DelegationInit.isInvalid()) 3158 return true; 3159 3160 // If we are in a dependent context, template instantiation will 3161 // perform this type-checking again. Just save the arguments that we 3162 // received in a ParenListExpr. 3163 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3164 // of the information that we have about the base 3165 // initializer. However, deconstructing the ASTs is a dicey process, 3166 // and this approach is far more likely to get the corner cases right. 3167 if (CurContext->isDependentContext()) 3168 DelegationInit = Init; 3169 3170 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3171 DelegationInit.getAs<Expr>(), 3172 InitRange.getEnd()); 3173 } 3174 3175 MemInitResult 3176 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3177 Expr *Init, CXXRecordDecl *ClassDecl, 3178 SourceLocation EllipsisLoc) { 3179 SourceLocation BaseLoc 3180 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3181 3182 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3183 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3184 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3185 3186 // C++ [class.base.init]p2: 3187 // [...] Unless the mem-initializer-id names a nonstatic data 3188 // member of the constructor's class or a direct or virtual base 3189 // of that class, the mem-initializer is ill-formed. A 3190 // mem-initializer-list can initialize a base class using any 3191 // name that denotes that base class type. 3192 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3193 3194 SourceRange InitRange = Init->getSourceRange(); 3195 if (EllipsisLoc.isValid()) { 3196 // This is a pack expansion. 3197 if (!BaseType->containsUnexpandedParameterPack()) { 3198 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3199 << SourceRange(BaseLoc, InitRange.getEnd()); 3200 3201 EllipsisLoc = SourceLocation(); 3202 } 3203 } else { 3204 // Check for any unexpanded parameter packs. 3205 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3206 return true; 3207 3208 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3209 return true; 3210 } 3211 3212 // Check for direct and virtual base classes. 3213 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3214 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3215 if (!Dependent) { 3216 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3217 BaseType)) 3218 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3219 3220 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3221 VirtualBaseSpec); 3222 3223 // C++ [base.class.init]p2: 3224 // Unless the mem-initializer-id names a nonstatic data member of the 3225 // constructor's class or a direct or virtual base of that class, the 3226 // mem-initializer is ill-formed. 3227 if (!DirectBaseSpec && !VirtualBaseSpec) { 3228 // If the class has any dependent bases, then it's possible that 3229 // one of those types will resolve to the same type as 3230 // BaseType. Therefore, just treat this as a dependent base 3231 // class initialization. FIXME: Should we try to check the 3232 // initialization anyway? It seems odd. 3233 if (ClassDecl->hasAnyDependentBases()) 3234 Dependent = true; 3235 else 3236 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3237 << BaseType << Context.getTypeDeclType(ClassDecl) 3238 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3239 } 3240 } 3241 3242 if (Dependent) { 3243 DiscardCleanupsInEvaluationContext(); 3244 3245 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3246 /*IsVirtual=*/false, 3247 InitRange.getBegin(), Init, 3248 InitRange.getEnd(), EllipsisLoc); 3249 } 3250 3251 // C++ [base.class.init]p2: 3252 // If a mem-initializer-id is ambiguous because it designates both 3253 // a direct non-virtual base class and an inherited virtual base 3254 // class, the mem-initializer is ill-formed. 3255 if (DirectBaseSpec && VirtualBaseSpec) 3256 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3257 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3258 3259 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3260 if (!BaseSpec) 3261 BaseSpec = VirtualBaseSpec; 3262 3263 // Initialize the base. 3264 bool InitList = true; 3265 MultiExprArg Args = Init; 3266 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3267 InitList = false; 3268 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3269 } 3270 3271 InitializedEntity BaseEntity = 3272 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3273 InitializationKind Kind = 3274 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3275 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3276 InitRange.getEnd()); 3277 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3278 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3279 if (BaseInit.isInvalid()) 3280 return true; 3281 3282 // C++11 [class.base.init]p7: 3283 // The initialization of each base and member constitutes a 3284 // full-expression. 3285 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3286 if (BaseInit.isInvalid()) 3287 return true; 3288 3289 // If we are in a dependent context, template instantiation will 3290 // perform this type-checking again. Just save the arguments that we 3291 // received in a ParenListExpr. 3292 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3293 // of the information that we have about the base 3294 // initializer. However, deconstructing the ASTs is a dicey process, 3295 // and this approach is far more likely to get the corner cases right. 3296 if (CurContext->isDependentContext()) 3297 BaseInit = Init; 3298 3299 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3300 BaseSpec->isVirtual(), 3301 InitRange.getBegin(), 3302 BaseInit.getAs<Expr>(), 3303 InitRange.getEnd(), EllipsisLoc); 3304 } 3305 3306 // Create a static_cast\<T&&>(expr). 3307 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3308 if (T.isNull()) T = E->getType(); 3309 QualType TargetType = SemaRef.BuildReferenceType( 3310 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3311 SourceLocation ExprLoc = E->getLocStart(); 3312 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3313 TargetType, ExprLoc); 3314 3315 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3316 SourceRange(ExprLoc, ExprLoc), 3317 E->getSourceRange()).get(); 3318 } 3319 3320 /// ImplicitInitializerKind - How an implicit base or member initializer should 3321 /// initialize its base or member. 3322 enum ImplicitInitializerKind { 3323 IIK_Default, 3324 IIK_Copy, 3325 IIK_Move, 3326 IIK_Inherit 3327 }; 3328 3329 static bool 3330 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3331 ImplicitInitializerKind ImplicitInitKind, 3332 CXXBaseSpecifier *BaseSpec, 3333 bool IsInheritedVirtualBase, 3334 CXXCtorInitializer *&CXXBaseInit) { 3335 InitializedEntity InitEntity 3336 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3337 IsInheritedVirtualBase); 3338 3339 ExprResult BaseInit; 3340 3341 switch (ImplicitInitKind) { 3342 case IIK_Inherit: { 3343 const CXXRecordDecl *Inherited = 3344 Constructor->getInheritedConstructor()->getParent(); 3345 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3346 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3347 // C++11 [class.inhctor]p8: 3348 // Each expression in the expression-list is of the form 3349 // static_cast<T&&>(p), where p is the name of the corresponding 3350 // constructor parameter and T is the declared type of p. 3351 SmallVector<Expr*, 16> Args; 3352 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3353 ParmVarDecl *PD = Constructor->getParamDecl(I); 3354 ExprResult ArgExpr = 3355 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3356 VK_LValue, SourceLocation()); 3357 if (ArgExpr.isInvalid()) 3358 return true; 3359 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3360 } 3361 3362 InitializationKind InitKind = InitializationKind::CreateDirect( 3363 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3364 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3365 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3366 break; 3367 } 3368 } 3369 // Fall through. 3370 case IIK_Default: { 3371 InitializationKind InitKind 3372 = InitializationKind::CreateDefault(Constructor->getLocation()); 3373 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3374 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3375 break; 3376 } 3377 3378 case IIK_Move: 3379 case IIK_Copy: { 3380 bool Moving = ImplicitInitKind == IIK_Move; 3381 ParmVarDecl *Param = Constructor->getParamDecl(0); 3382 QualType ParamType = Param->getType().getNonReferenceType(); 3383 3384 Expr *CopyCtorArg = 3385 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3386 SourceLocation(), Param, false, 3387 Constructor->getLocation(), ParamType, 3388 VK_LValue, nullptr); 3389 3390 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3391 3392 // Cast to the base class to avoid ambiguities. 3393 QualType ArgTy = 3394 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3395 ParamType.getQualifiers()); 3396 3397 if (Moving) { 3398 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3399 } 3400 3401 CXXCastPath BasePath; 3402 BasePath.push_back(BaseSpec); 3403 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3404 CK_UncheckedDerivedToBase, 3405 Moving ? VK_XValue : VK_LValue, 3406 &BasePath).get(); 3407 3408 InitializationKind InitKind 3409 = InitializationKind::CreateDirect(Constructor->getLocation(), 3410 SourceLocation(), SourceLocation()); 3411 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3412 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3413 break; 3414 } 3415 } 3416 3417 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3418 if (BaseInit.isInvalid()) 3419 return true; 3420 3421 CXXBaseInit = 3422 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3423 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3424 SourceLocation()), 3425 BaseSpec->isVirtual(), 3426 SourceLocation(), 3427 BaseInit.getAs<Expr>(), 3428 SourceLocation(), 3429 SourceLocation()); 3430 3431 return false; 3432 } 3433 3434 static bool RefersToRValueRef(Expr *MemRef) { 3435 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3436 return Referenced->getType()->isRValueReferenceType(); 3437 } 3438 3439 static bool 3440 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3441 ImplicitInitializerKind ImplicitInitKind, 3442 FieldDecl *Field, IndirectFieldDecl *Indirect, 3443 CXXCtorInitializer *&CXXMemberInit) { 3444 if (Field->isInvalidDecl()) 3445 return true; 3446 3447 SourceLocation Loc = Constructor->getLocation(); 3448 3449 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3450 bool Moving = ImplicitInitKind == IIK_Move; 3451 ParmVarDecl *Param = Constructor->getParamDecl(0); 3452 QualType ParamType = Param->getType().getNonReferenceType(); 3453 3454 // Suppress copying zero-width bitfields. 3455 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3456 return false; 3457 3458 Expr *MemberExprBase = 3459 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3460 SourceLocation(), Param, false, 3461 Loc, ParamType, VK_LValue, nullptr); 3462 3463 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3464 3465 if (Moving) { 3466 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3467 } 3468 3469 // Build a reference to this field within the parameter. 3470 CXXScopeSpec SS; 3471 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3472 Sema::LookupMemberName); 3473 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3474 : cast<ValueDecl>(Field), AS_public); 3475 MemberLookup.resolveKind(); 3476 ExprResult CtorArg 3477 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3478 ParamType, Loc, 3479 /*IsArrow=*/false, 3480 SS, 3481 /*TemplateKWLoc=*/SourceLocation(), 3482 /*FirstQualifierInScope=*/nullptr, 3483 MemberLookup, 3484 /*TemplateArgs=*/nullptr, 3485 /*S*/nullptr); 3486 if (CtorArg.isInvalid()) 3487 return true; 3488 3489 // C++11 [class.copy]p15: 3490 // - if a member m has rvalue reference type T&&, it is direct-initialized 3491 // with static_cast<T&&>(x.m); 3492 if (RefersToRValueRef(CtorArg.get())) { 3493 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3494 } 3495 3496 // When the field we are copying is an array, create index variables for 3497 // each dimension of the array. We use these index variables to subscript 3498 // the source array, and other clients (e.g., CodeGen) will perform the 3499 // necessary iteration with these index variables. 3500 SmallVector<VarDecl *, 4> IndexVariables; 3501 QualType BaseType = Field->getType(); 3502 QualType SizeType = SemaRef.Context.getSizeType(); 3503 bool InitializingArray = false; 3504 while (const ConstantArrayType *Array 3505 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3506 InitializingArray = true; 3507 // Create the iteration variable for this array index. 3508 IdentifierInfo *IterationVarName = nullptr; 3509 { 3510 SmallString<8> Str; 3511 llvm::raw_svector_ostream OS(Str); 3512 OS << "__i" << IndexVariables.size(); 3513 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3514 } 3515 VarDecl *IterationVar 3516 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3517 IterationVarName, SizeType, 3518 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3519 SC_None); 3520 IndexVariables.push_back(IterationVar); 3521 3522 // Create a reference to the iteration variable. 3523 ExprResult IterationVarRef 3524 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3525 assert(!IterationVarRef.isInvalid() && 3526 "Reference to invented variable cannot fail!"); 3527 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3528 assert(!IterationVarRef.isInvalid() && 3529 "Conversion of invented variable cannot fail!"); 3530 3531 // Subscript the array with this iteration variable. 3532 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3533 IterationVarRef.get(), 3534 Loc); 3535 if (CtorArg.isInvalid()) 3536 return true; 3537 3538 BaseType = Array->getElementType(); 3539 } 3540 3541 // The array subscript expression is an lvalue, which is wrong for moving. 3542 if (Moving && InitializingArray) 3543 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3544 3545 // Construct the entity that we will be initializing. For an array, this 3546 // will be first element in the array, which may require several levels 3547 // of array-subscript entities. 3548 SmallVector<InitializedEntity, 4> Entities; 3549 Entities.reserve(1 + IndexVariables.size()); 3550 if (Indirect) 3551 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3552 else 3553 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3554 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3555 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3556 0, 3557 Entities.back())); 3558 3559 // Direct-initialize to use the copy constructor. 3560 InitializationKind InitKind = 3561 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3562 3563 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3564 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 3565 CtorArgE); 3566 3567 ExprResult MemberInit 3568 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3569 MultiExprArg(&CtorArgE, 1)); 3570 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3571 if (MemberInit.isInvalid()) 3572 return true; 3573 3574 if (Indirect) { 3575 assert(IndexVariables.size() == 0 && 3576 "Indirect field improperly initialized"); 3577 CXXMemberInit 3578 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3579 Loc, Loc, 3580 MemberInit.getAs<Expr>(), 3581 Loc); 3582 } else 3583 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3584 Loc, MemberInit.getAs<Expr>(), 3585 Loc, 3586 IndexVariables.data(), 3587 IndexVariables.size()); 3588 return false; 3589 } 3590 3591 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3592 "Unhandled implicit init kind!"); 3593 3594 QualType FieldBaseElementType = 3595 SemaRef.Context.getBaseElementType(Field->getType()); 3596 3597 if (FieldBaseElementType->isRecordType()) { 3598 InitializedEntity InitEntity 3599 = Indirect? InitializedEntity::InitializeMember(Indirect) 3600 : InitializedEntity::InitializeMember(Field); 3601 InitializationKind InitKind = 3602 InitializationKind::CreateDefault(Loc); 3603 3604 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3605 ExprResult MemberInit = 3606 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3607 3608 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3609 if (MemberInit.isInvalid()) 3610 return true; 3611 3612 if (Indirect) 3613 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3614 Indirect, Loc, 3615 Loc, 3616 MemberInit.get(), 3617 Loc); 3618 else 3619 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3620 Field, Loc, Loc, 3621 MemberInit.get(), 3622 Loc); 3623 return false; 3624 } 3625 3626 if (!Field->getParent()->isUnion()) { 3627 if (FieldBaseElementType->isReferenceType()) { 3628 SemaRef.Diag(Constructor->getLocation(), 3629 diag::err_uninitialized_member_in_ctor) 3630 << (int)Constructor->isImplicit() 3631 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3632 << 0 << Field->getDeclName(); 3633 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3634 return true; 3635 } 3636 3637 if (FieldBaseElementType.isConstQualified()) { 3638 SemaRef.Diag(Constructor->getLocation(), 3639 diag::err_uninitialized_member_in_ctor) 3640 << (int)Constructor->isImplicit() 3641 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3642 << 1 << Field->getDeclName(); 3643 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3644 return true; 3645 } 3646 } 3647 3648 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3649 FieldBaseElementType->isObjCRetainableType() && 3650 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3651 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3652 // ARC: 3653 // Default-initialize Objective-C pointers to NULL. 3654 CXXMemberInit 3655 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3656 Loc, Loc, 3657 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3658 Loc); 3659 return false; 3660 } 3661 3662 // Nothing to initialize. 3663 CXXMemberInit = nullptr; 3664 return false; 3665 } 3666 3667 namespace { 3668 struct BaseAndFieldInfo { 3669 Sema &S; 3670 CXXConstructorDecl *Ctor; 3671 bool AnyErrorsInInits; 3672 ImplicitInitializerKind IIK; 3673 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3674 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3675 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3676 3677 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3678 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3679 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3680 if (Generated && Ctor->isCopyConstructor()) 3681 IIK = IIK_Copy; 3682 else if (Generated && Ctor->isMoveConstructor()) 3683 IIK = IIK_Move; 3684 else if (Ctor->getInheritedConstructor()) 3685 IIK = IIK_Inherit; 3686 else 3687 IIK = IIK_Default; 3688 } 3689 3690 bool isImplicitCopyOrMove() const { 3691 switch (IIK) { 3692 case IIK_Copy: 3693 case IIK_Move: 3694 return true; 3695 3696 case IIK_Default: 3697 case IIK_Inherit: 3698 return false; 3699 } 3700 3701 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3702 } 3703 3704 bool addFieldInitializer(CXXCtorInitializer *Init) { 3705 AllToInit.push_back(Init); 3706 3707 // Check whether this initializer makes the field "used". 3708 if (Init->getInit()->HasSideEffects(S.Context)) 3709 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3710 3711 return false; 3712 } 3713 3714 bool isInactiveUnionMember(FieldDecl *Field) { 3715 RecordDecl *Record = Field->getParent(); 3716 if (!Record->isUnion()) 3717 return false; 3718 3719 if (FieldDecl *Active = 3720 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3721 return Active != Field->getCanonicalDecl(); 3722 3723 // In an implicit copy or move constructor, ignore any in-class initializer. 3724 if (isImplicitCopyOrMove()) 3725 return true; 3726 3727 // If there's no explicit initialization, the field is active only if it 3728 // has an in-class initializer... 3729 if (Field->hasInClassInitializer()) 3730 return false; 3731 // ... or it's an anonymous struct or union whose class has an in-class 3732 // initializer. 3733 if (!Field->isAnonymousStructOrUnion()) 3734 return true; 3735 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3736 return !FieldRD->hasInClassInitializer(); 3737 } 3738 3739 /// \brief Determine whether the given field is, or is within, a union member 3740 /// that is inactive (because there was an initializer given for a different 3741 /// member of the union, or because the union was not initialized at all). 3742 bool isWithinInactiveUnionMember(FieldDecl *Field, 3743 IndirectFieldDecl *Indirect) { 3744 if (!Indirect) 3745 return isInactiveUnionMember(Field); 3746 3747 for (auto *C : Indirect->chain()) { 3748 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3749 if (Field && isInactiveUnionMember(Field)) 3750 return true; 3751 } 3752 return false; 3753 } 3754 }; 3755 } 3756 3757 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3758 /// array type. 3759 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3760 if (T->isIncompleteArrayType()) 3761 return true; 3762 3763 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3764 if (!ArrayT->getSize()) 3765 return true; 3766 3767 T = ArrayT->getElementType(); 3768 } 3769 3770 return false; 3771 } 3772 3773 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3774 FieldDecl *Field, 3775 IndirectFieldDecl *Indirect = nullptr) { 3776 if (Field->isInvalidDecl()) 3777 return false; 3778 3779 // Overwhelmingly common case: we have a direct initializer for this field. 3780 if (CXXCtorInitializer *Init = 3781 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3782 return Info.addFieldInitializer(Init); 3783 3784 // C++11 [class.base.init]p8: 3785 // if the entity is a non-static data member that has a 3786 // brace-or-equal-initializer and either 3787 // -- the constructor's class is a union and no other variant member of that 3788 // union is designated by a mem-initializer-id or 3789 // -- the constructor's class is not a union, and, if the entity is a member 3790 // of an anonymous union, no other member of that union is designated by 3791 // a mem-initializer-id, 3792 // the entity is initialized as specified in [dcl.init]. 3793 // 3794 // We also apply the same rules to handle anonymous structs within anonymous 3795 // unions. 3796 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3797 return false; 3798 3799 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3800 ExprResult DIE = 3801 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3802 if (DIE.isInvalid()) 3803 return true; 3804 CXXCtorInitializer *Init; 3805 if (Indirect) 3806 Init = new (SemaRef.Context) 3807 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3808 SourceLocation(), DIE.get(), SourceLocation()); 3809 else 3810 Init = new (SemaRef.Context) 3811 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3812 SourceLocation(), DIE.get(), SourceLocation()); 3813 return Info.addFieldInitializer(Init); 3814 } 3815 3816 // Don't initialize incomplete or zero-length arrays. 3817 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3818 return false; 3819 3820 // Don't try to build an implicit initializer if there were semantic 3821 // errors in any of the initializers (and therefore we might be 3822 // missing some that the user actually wrote). 3823 if (Info.AnyErrorsInInits) 3824 return false; 3825 3826 CXXCtorInitializer *Init = nullptr; 3827 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3828 Indirect, Init)) 3829 return true; 3830 3831 if (!Init) 3832 return false; 3833 3834 return Info.addFieldInitializer(Init); 3835 } 3836 3837 bool 3838 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3839 CXXCtorInitializer *Initializer) { 3840 assert(Initializer->isDelegatingInitializer()); 3841 Constructor->setNumCtorInitializers(1); 3842 CXXCtorInitializer **initializer = 3843 new (Context) CXXCtorInitializer*[1]; 3844 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3845 Constructor->setCtorInitializers(initializer); 3846 3847 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3848 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3849 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3850 } 3851 3852 DelegatingCtorDecls.push_back(Constructor); 3853 3854 DiagnoseUninitializedFields(*this, Constructor); 3855 3856 return false; 3857 } 3858 3859 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3860 ArrayRef<CXXCtorInitializer *> Initializers) { 3861 if (Constructor->isDependentContext()) { 3862 // Just store the initializers as written, they will be checked during 3863 // instantiation. 3864 if (!Initializers.empty()) { 3865 Constructor->setNumCtorInitializers(Initializers.size()); 3866 CXXCtorInitializer **baseOrMemberInitializers = 3867 new (Context) CXXCtorInitializer*[Initializers.size()]; 3868 memcpy(baseOrMemberInitializers, Initializers.data(), 3869 Initializers.size() * sizeof(CXXCtorInitializer*)); 3870 Constructor->setCtorInitializers(baseOrMemberInitializers); 3871 } 3872 3873 // Let template instantiation know whether we had errors. 3874 if (AnyErrors) 3875 Constructor->setInvalidDecl(); 3876 3877 return false; 3878 } 3879 3880 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3881 3882 // We need to build the initializer AST according to order of construction 3883 // and not what user specified in the Initializers list. 3884 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3885 if (!ClassDecl) 3886 return true; 3887 3888 bool HadError = false; 3889 3890 for (unsigned i = 0; i < Initializers.size(); i++) { 3891 CXXCtorInitializer *Member = Initializers[i]; 3892 3893 if (Member->isBaseInitializer()) 3894 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3895 else { 3896 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3897 3898 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3899 for (auto *C : F->chain()) { 3900 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3901 if (FD && FD->getParent()->isUnion()) 3902 Info.ActiveUnionMember.insert(std::make_pair( 3903 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3904 } 3905 } else if (FieldDecl *FD = Member->getMember()) { 3906 if (FD->getParent()->isUnion()) 3907 Info.ActiveUnionMember.insert(std::make_pair( 3908 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3909 } 3910 } 3911 } 3912 3913 // Keep track of the direct virtual bases. 3914 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3915 for (auto &I : ClassDecl->bases()) { 3916 if (I.isVirtual()) 3917 DirectVBases.insert(&I); 3918 } 3919 3920 // Push virtual bases before others. 3921 for (auto &VBase : ClassDecl->vbases()) { 3922 if (CXXCtorInitializer *Value 3923 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3924 // [class.base.init]p7, per DR257: 3925 // A mem-initializer where the mem-initializer-id names a virtual base 3926 // class is ignored during execution of a constructor of any class that 3927 // is not the most derived class. 3928 if (ClassDecl->isAbstract()) { 3929 // FIXME: Provide a fixit to remove the base specifier. This requires 3930 // tracking the location of the associated comma for a base specifier. 3931 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3932 << VBase.getType() << ClassDecl; 3933 DiagnoseAbstractType(ClassDecl); 3934 } 3935 3936 Info.AllToInit.push_back(Value); 3937 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3938 // [class.base.init]p8, per DR257: 3939 // If a given [...] base class is not named by a mem-initializer-id 3940 // [...] and the entity is not a virtual base class of an abstract 3941 // class, then [...] the entity is default-initialized. 3942 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3943 CXXCtorInitializer *CXXBaseInit; 3944 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3945 &VBase, IsInheritedVirtualBase, 3946 CXXBaseInit)) { 3947 HadError = true; 3948 continue; 3949 } 3950 3951 Info.AllToInit.push_back(CXXBaseInit); 3952 } 3953 } 3954 3955 // Non-virtual bases. 3956 for (auto &Base : ClassDecl->bases()) { 3957 // Virtuals are in the virtual base list and already constructed. 3958 if (Base.isVirtual()) 3959 continue; 3960 3961 if (CXXCtorInitializer *Value 3962 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3963 Info.AllToInit.push_back(Value); 3964 } else if (!AnyErrors) { 3965 CXXCtorInitializer *CXXBaseInit; 3966 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3967 &Base, /*IsInheritedVirtualBase=*/false, 3968 CXXBaseInit)) { 3969 HadError = true; 3970 continue; 3971 } 3972 3973 Info.AllToInit.push_back(CXXBaseInit); 3974 } 3975 } 3976 3977 // Fields. 3978 for (auto *Mem : ClassDecl->decls()) { 3979 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3980 // C++ [class.bit]p2: 3981 // A declaration for a bit-field that omits the identifier declares an 3982 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3983 // initialized. 3984 if (F->isUnnamedBitfield()) 3985 continue; 3986 3987 // If we're not generating the implicit copy/move constructor, then we'll 3988 // handle anonymous struct/union fields based on their individual 3989 // indirect fields. 3990 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3991 continue; 3992 3993 if (CollectFieldInitializer(*this, Info, F)) 3994 HadError = true; 3995 continue; 3996 } 3997 3998 // Beyond this point, we only consider default initialization. 3999 if (Info.isImplicitCopyOrMove()) 4000 continue; 4001 4002 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4003 if (F->getType()->isIncompleteArrayType()) { 4004 assert(ClassDecl->hasFlexibleArrayMember() && 4005 "Incomplete array type is not valid"); 4006 continue; 4007 } 4008 4009 // Initialize each field of an anonymous struct individually. 4010 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4011 HadError = true; 4012 4013 continue; 4014 } 4015 } 4016 4017 unsigned NumInitializers = Info.AllToInit.size(); 4018 if (NumInitializers > 0) { 4019 Constructor->setNumCtorInitializers(NumInitializers); 4020 CXXCtorInitializer **baseOrMemberInitializers = 4021 new (Context) CXXCtorInitializer*[NumInitializers]; 4022 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4023 NumInitializers * sizeof(CXXCtorInitializer*)); 4024 Constructor->setCtorInitializers(baseOrMemberInitializers); 4025 4026 // Constructors implicitly reference the base and member 4027 // destructors. 4028 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4029 Constructor->getParent()); 4030 } 4031 4032 return HadError; 4033 } 4034 4035 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4036 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4037 const RecordDecl *RD = RT->getDecl(); 4038 if (RD->isAnonymousStructOrUnion()) { 4039 for (auto *Field : RD->fields()) 4040 PopulateKeysForFields(Field, IdealInits); 4041 return; 4042 } 4043 } 4044 IdealInits.push_back(Field->getCanonicalDecl()); 4045 } 4046 4047 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4048 return Context.getCanonicalType(BaseType).getTypePtr(); 4049 } 4050 4051 static const void *GetKeyForMember(ASTContext &Context, 4052 CXXCtorInitializer *Member) { 4053 if (!Member->isAnyMemberInitializer()) 4054 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4055 4056 return Member->getAnyMember()->getCanonicalDecl(); 4057 } 4058 4059 static void DiagnoseBaseOrMemInitializerOrder( 4060 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4061 ArrayRef<CXXCtorInitializer *> Inits) { 4062 if (Constructor->getDeclContext()->isDependentContext()) 4063 return; 4064 4065 // Don't check initializers order unless the warning is enabled at the 4066 // location of at least one initializer. 4067 bool ShouldCheckOrder = false; 4068 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4069 CXXCtorInitializer *Init = Inits[InitIndex]; 4070 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4071 Init->getSourceLocation())) { 4072 ShouldCheckOrder = true; 4073 break; 4074 } 4075 } 4076 if (!ShouldCheckOrder) 4077 return; 4078 4079 // Build the list of bases and members in the order that they'll 4080 // actually be initialized. The explicit initializers should be in 4081 // this same order but may be missing things. 4082 SmallVector<const void*, 32> IdealInitKeys; 4083 4084 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4085 4086 // 1. Virtual bases. 4087 for (const auto &VBase : ClassDecl->vbases()) 4088 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4089 4090 // 2. Non-virtual bases. 4091 for (const auto &Base : ClassDecl->bases()) { 4092 if (Base.isVirtual()) 4093 continue; 4094 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4095 } 4096 4097 // 3. Direct fields. 4098 for (auto *Field : ClassDecl->fields()) { 4099 if (Field->isUnnamedBitfield()) 4100 continue; 4101 4102 PopulateKeysForFields(Field, IdealInitKeys); 4103 } 4104 4105 unsigned NumIdealInits = IdealInitKeys.size(); 4106 unsigned IdealIndex = 0; 4107 4108 CXXCtorInitializer *PrevInit = nullptr; 4109 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4110 CXXCtorInitializer *Init = Inits[InitIndex]; 4111 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4112 4113 // Scan forward to try to find this initializer in the idealized 4114 // initializers list. 4115 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4116 if (InitKey == IdealInitKeys[IdealIndex]) 4117 break; 4118 4119 // If we didn't find this initializer, it must be because we 4120 // scanned past it on a previous iteration. That can only 4121 // happen if we're out of order; emit a warning. 4122 if (IdealIndex == NumIdealInits && PrevInit) { 4123 Sema::SemaDiagnosticBuilder D = 4124 SemaRef.Diag(PrevInit->getSourceLocation(), 4125 diag::warn_initializer_out_of_order); 4126 4127 if (PrevInit->isAnyMemberInitializer()) 4128 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4129 else 4130 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4131 4132 if (Init->isAnyMemberInitializer()) 4133 D << 0 << Init->getAnyMember()->getDeclName(); 4134 else 4135 D << 1 << Init->getTypeSourceInfo()->getType(); 4136 4137 // Move back to the initializer's location in the ideal list. 4138 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4139 if (InitKey == IdealInitKeys[IdealIndex]) 4140 break; 4141 4142 assert(IdealIndex < NumIdealInits && 4143 "initializer not found in initializer list"); 4144 } 4145 4146 PrevInit = Init; 4147 } 4148 } 4149 4150 namespace { 4151 bool CheckRedundantInit(Sema &S, 4152 CXXCtorInitializer *Init, 4153 CXXCtorInitializer *&PrevInit) { 4154 if (!PrevInit) { 4155 PrevInit = Init; 4156 return false; 4157 } 4158 4159 if (FieldDecl *Field = Init->getAnyMember()) 4160 S.Diag(Init->getSourceLocation(), 4161 diag::err_multiple_mem_initialization) 4162 << Field->getDeclName() 4163 << Init->getSourceRange(); 4164 else { 4165 const Type *BaseClass = Init->getBaseClass(); 4166 assert(BaseClass && "neither field nor base"); 4167 S.Diag(Init->getSourceLocation(), 4168 diag::err_multiple_base_initialization) 4169 << QualType(BaseClass, 0) 4170 << Init->getSourceRange(); 4171 } 4172 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4173 << 0 << PrevInit->getSourceRange(); 4174 4175 return true; 4176 } 4177 4178 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4179 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4180 4181 bool CheckRedundantUnionInit(Sema &S, 4182 CXXCtorInitializer *Init, 4183 RedundantUnionMap &Unions) { 4184 FieldDecl *Field = Init->getAnyMember(); 4185 RecordDecl *Parent = Field->getParent(); 4186 NamedDecl *Child = Field; 4187 4188 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4189 if (Parent->isUnion()) { 4190 UnionEntry &En = Unions[Parent]; 4191 if (En.first && En.first != Child) { 4192 S.Diag(Init->getSourceLocation(), 4193 diag::err_multiple_mem_union_initialization) 4194 << Field->getDeclName() 4195 << Init->getSourceRange(); 4196 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4197 << 0 << En.second->getSourceRange(); 4198 return true; 4199 } 4200 if (!En.first) { 4201 En.first = Child; 4202 En.second = Init; 4203 } 4204 if (!Parent->isAnonymousStructOrUnion()) 4205 return false; 4206 } 4207 4208 Child = Parent; 4209 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4210 } 4211 4212 return false; 4213 } 4214 } 4215 4216 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4217 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4218 SourceLocation ColonLoc, 4219 ArrayRef<CXXCtorInitializer*> MemInits, 4220 bool AnyErrors) { 4221 if (!ConstructorDecl) 4222 return; 4223 4224 AdjustDeclIfTemplate(ConstructorDecl); 4225 4226 CXXConstructorDecl *Constructor 4227 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4228 4229 if (!Constructor) { 4230 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4231 return; 4232 } 4233 4234 // Mapping for the duplicate initializers check. 4235 // For member initializers, this is keyed with a FieldDecl*. 4236 // For base initializers, this is keyed with a Type*. 4237 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4238 4239 // Mapping for the inconsistent anonymous-union initializers check. 4240 RedundantUnionMap MemberUnions; 4241 4242 bool HadError = false; 4243 for (unsigned i = 0; i < MemInits.size(); i++) { 4244 CXXCtorInitializer *Init = MemInits[i]; 4245 4246 // Set the source order index. 4247 Init->setSourceOrder(i); 4248 4249 if (Init->isAnyMemberInitializer()) { 4250 const void *Key = GetKeyForMember(Context, Init); 4251 if (CheckRedundantInit(*this, Init, Members[Key]) || 4252 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4253 HadError = true; 4254 } else if (Init->isBaseInitializer()) { 4255 const void *Key = GetKeyForMember(Context, Init); 4256 if (CheckRedundantInit(*this, Init, Members[Key])) 4257 HadError = true; 4258 } else { 4259 assert(Init->isDelegatingInitializer()); 4260 // This must be the only initializer 4261 if (MemInits.size() != 1) { 4262 Diag(Init->getSourceLocation(), 4263 diag::err_delegating_initializer_alone) 4264 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4265 // We will treat this as being the only initializer. 4266 } 4267 SetDelegatingInitializer(Constructor, MemInits[i]); 4268 // Return immediately as the initializer is set. 4269 return; 4270 } 4271 } 4272 4273 if (HadError) 4274 return; 4275 4276 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4277 4278 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4279 4280 DiagnoseUninitializedFields(*this, Constructor); 4281 } 4282 4283 void 4284 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4285 CXXRecordDecl *ClassDecl) { 4286 // Ignore dependent contexts. Also ignore unions, since their members never 4287 // have destructors implicitly called. 4288 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4289 return; 4290 4291 // FIXME: all the access-control diagnostics are positioned on the 4292 // field/base declaration. That's probably good; that said, the 4293 // user might reasonably want to know why the destructor is being 4294 // emitted, and we currently don't say. 4295 4296 // Non-static data members. 4297 for (auto *Field : ClassDecl->fields()) { 4298 if (Field->isInvalidDecl()) 4299 continue; 4300 4301 // Don't destroy incomplete or zero-length arrays. 4302 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4303 continue; 4304 4305 QualType FieldType = Context.getBaseElementType(Field->getType()); 4306 4307 const RecordType* RT = FieldType->getAs<RecordType>(); 4308 if (!RT) 4309 continue; 4310 4311 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4312 if (FieldClassDecl->isInvalidDecl()) 4313 continue; 4314 if (FieldClassDecl->hasIrrelevantDestructor()) 4315 continue; 4316 // The destructor for an implicit anonymous union member is never invoked. 4317 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4318 continue; 4319 4320 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4321 assert(Dtor && "No dtor found for FieldClassDecl!"); 4322 CheckDestructorAccess(Field->getLocation(), Dtor, 4323 PDiag(diag::err_access_dtor_field) 4324 << Field->getDeclName() 4325 << FieldType); 4326 4327 MarkFunctionReferenced(Location, Dtor); 4328 DiagnoseUseOfDecl(Dtor, Location); 4329 } 4330 4331 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4332 4333 // Bases. 4334 for (const auto &Base : ClassDecl->bases()) { 4335 // Bases are always records in a well-formed non-dependent class. 4336 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4337 4338 // Remember direct virtual bases. 4339 if (Base.isVirtual()) 4340 DirectVirtualBases.insert(RT); 4341 4342 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4343 // If our base class is invalid, we probably can't get its dtor anyway. 4344 if (BaseClassDecl->isInvalidDecl()) 4345 continue; 4346 if (BaseClassDecl->hasIrrelevantDestructor()) 4347 continue; 4348 4349 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4350 assert(Dtor && "No dtor found for BaseClassDecl!"); 4351 4352 // FIXME: caret should be on the start of the class name 4353 CheckDestructorAccess(Base.getLocStart(), Dtor, 4354 PDiag(diag::err_access_dtor_base) 4355 << Base.getType() 4356 << Base.getSourceRange(), 4357 Context.getTypeDeclType(ClassDecl)); 4358 4359 MarkFunctionReferenced(Location, Dtor); 4360 DiagnoseUseOfDecl(Dtor, Location); 4361 } 4362 4363 // Virtual bases. 4364 for (const auto &VBase : ClassDecl->vbases()) { 4365 // Bases are always records in a well-formed non-dependent class. 4366 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4367 4368 // Ignore direct virtual bases. 4369 if (DirectVirtualBases.count(RT)) 4370 continue; 4371 4372 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4373 // If our base class is invalid, we probably can't get its dtor anyway. 4374 if (BaseClassDecl->isInvalidDecl()) 4375 continue; 4376 if (BaseClassDecl->hasIrrelevantDestructor()) 4377 continue; 4378 4379 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4380 assert(Dtor && "No dtor found for BaseClassDecl!"); 4381 if (CheckDestructorAccess( 4382 ClassDecl->getLocation(), Dtor, 4383 PDiag(diag::err_access_dtor_vbase) 4384 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4385 Context.getTypeDeclType(ClassDecl)) == 4386 AR_accessible) { 4387 CheckDerivedToBaseConversion( 4388 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4389 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4390 SourceRange(), DeclarationName(), nullptr); 4391 } 4392 4393 MarkFunctionReferenced(Location, Dtor); 4394 DiagnoseUseOfDecl(Dtor, Location); 4395 } 4396 } 4397 4398 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4399 if (!CDtorDecl) 4400 return; 4401 4402 if (CXXConstructorDecl *Constructor 4403 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4404 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4405 DiagnoseUninitializedFields(*this, Constructor); 4406 } 4407 } 4408 4409 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4410 unsigned DiagID, AbstractDiagSelID SelID) { 4411 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4412 unsigned DiagID; 4413 AbstractDiagSelID SelID; 4414 4415 public: 4416 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4417 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4418 4419 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4420 if (Suppressed) return; 4421 if (SelID == -1) 4422 S.Diag(Loc, DiagID) << T; 4423 else 4424 S.Diag(Loc, DiagID) << SelID << T; 4425 } 4426 } Diagnoser(DiagID, SelID); 4427 4428 return RequireNonAbstractType(Loc, T, Diagnoser); 4429 } 4430 4431 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4432 TypeDiagnoser &Diagnoser) { 4433 if (!getLangOpts().CPlusPlus) 4434 return false; 4435 4436 if (const ArrayType *AT = Context.getAsArrayType(T)) 4437 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4438 4439 if (const PointerType *PT = T->getAs<PointerType>()) { 4440 // Find the innermost pointer type. 4441 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4442 PT = T; 4443 4444 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4445 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4446 } 4447 4448 const RecordType *RT = T->getAs<RecordType>(); 4449 if (!RT) 4450 return false; 4451 4452 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4453 4454 // We can't answer whether something is abstract until it has a 4455 // definition. If it's currently being defined, we'll walk back 4456 // over all the declarations when we have a full definition. 4457 const CXXRecordDecl *Def = RD->getDefinition(); 4458 if (!Def || Def->isBeingDefined()) 4459 return false; 4460 4461 if (!RD->isAbstract()) 4462 return false; 4463 4464 Diagnoser.diagnose(*this, Loc, T); 4465 DiagnoseAbstractType(RD); 4466 4467 return true; 4468 } 4469 4470 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4471 // Check if we've already emitted the list of pure virtual functions 4472 // for this class. 4473 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4474 return; 4475 4476 // If the diagnostic is suppressed, don't emit the notes. We're only 4477 // going to emit them once, so try to attach them to a diagnostic we're 4478 // actually going to show. 4479 if (Diags.isLastDiagnosticIgnored()) 4480 return; 4481 4482 CXXFinalOverriderMap FinalOverriders; 4483 RD->getFinalOverriders(FinalOverriders); 4484 4485 // Keep a set of seen pure methods so we won't diagnose the same method 4486 // more than once. 4487 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4488 4489 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4490 MEnd = FinalOverriders.end(); 4491 M != MEnd; 4492 ++M) { 4493 for (OverridingMethods::iterator SO = M->second.begin(), 4494 SOEnd = M->second.end(); 4495 SO != SOEnd; ++SO) { 4496 // C++ [class.abstract]p4: 4497 // A class is abstract if it contains or inherits at least one 4498 // pure virtual function for which the final overrider is pure 4499 // virtual. 4500 4501 // 4502 if (SO->second.size() != 1) 4503 continue; 4504 4505 if (!SO->second.front().Method->isPure()) 4506 continue; 4507 4508 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4509 continue; 4510 4511 Diag(SO->second.front().Method->getLocation(), 4512 diag::note_pure_virtual_function) 4513 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4514 } 4515 } 4516 4517 if (!PureVirtualClassDiagSet) 4518 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4519 PureVirtualClassDiagSet->insert(RD); 4520 } 4521 4522 namespace { 4523 struct AbstractUsageInfo { 4524 Sema &S; 4525 CXXRecordDecl *Record; 4526 CanQualType AbstractType; 4527 bool Invalid; 4528 4529 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4530 : S(S), Record(Record), 4531 AbstractType(S.Context.getCanonicalType( 4532 S.Context.getTypeDeclType(Record))), 4533 Invalid(false) {} 4534 4535 void DiagnoseAbstractType() { 4536 if (Invalid) return; 4537 S.DiagnoseAbstractType(Record); 4538 Invalid = true; 4539 } 4540 4541 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4542 }; 4543 4544 struct CheckAbstractUsage { 4545 AbstractUsageInfo &Info; 4546 const NamedDecl *Ctx; 4547 4548 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4549 : Info(Info), Ctx(Ctx) {} 4550 4551 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4552 switch (TL.getTypeLocClass()) { 4553 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4554 #define TYPELOC(CLASS, PARENT) \ 4555 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4556 #include "clang/AST/TypeLocNodes.def" 4557 } 4558 } 4559 4560 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4561 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4562 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4563 if (!TL.getParam(I)) 4564 continue; 4565 4566 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4567 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4568 } 4569 } 4570 4571 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4572 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4573 } 4574 4575 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4576 // Visit the type parameters from a permissive context. 4577 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4578 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4579 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4580 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4581 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4582 // TODO: other template argument types? 4583 } 4584 } 4585 4586 // Visit pointee types from a permissive context. 4587 #define CheckPolymorphic(Type) \ 4588 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4589 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4590 } 4591 CheckPolymorphic(PointerTypeLoc) 4592 CheckPolymorphic(ReferenceTypeLoc) 4593 CheckPolymorphic(MemberPointerTypeLoc) 4594 CheckPolymorphic(BlockPointerTypeLoc) 4595 CheckPolymorphic(AtomicTypeLoc) 4596 4597 /// Handle all the types we haven't given a more specific 4598 /// implementation for above. 4599 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4600 // Every other kind of type that we haven't called out already 4601 // that has an inner type is either (1) sugar or (2) contains that 4602 // inner type in some way as a subobject. 4603 if (TypeLoc Next = TL.getNextTypeLoc()) 4604 return Visit(Next, Sel); 4605 4606 // If there's no inner type and we're in a permissive context, 4607 // don't diagnose. 4608 if (Sel == Sema::AbstractNone) return; 4609 4610 // Check whether the type matches the abstract type. 4611 QualType T = TL.getType(); 4612 if (T->isArrayType()) { 4613 Sel = Sema::AbstractArrayType; 4614 T = Info.S.Context.getBaseElementType(T); 4615 } 4616 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4617 if (CT != Info.AbstractType) return; 4618 4619 // It matched; do some magic. 4620 if (Sel == Sema::AbstractArrayType) { 4621 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4622 << T << TL.getSourceRange(); 4623 } else { 4624 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4625 << Sel << T << TL.getSourceRange(); 4626 } 4627 Info.DiagnoseAbstractType(); 4628 } 4629 }; 4630 4631 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4632 Sema::AbstractDiagSelID Sel) { 4633 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4634 } 4635 4636 } 4637 4638 /// Check for invalid uses of an abstract type in a method declaration. 4639 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4640 CXXMethodDecl *MD) { 4641 // No need to do the check on definitions, which require that 4642 // the return/param types be complete. 4643 if (MD->doesThisDeclarationHaveABody()) 4644 return; 4645 4646 // For safety's sake, just ignore it if we don't have type source 4647 // information. This should never happen for non-implicit methods, 4648 // but... 4649 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4650 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4651 } 4652 4653 /// Check for invalid uses of an abstract type within a class definition. 4654 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4655 CXXRecordDecl *RD) { 4656 for (auto *D : RD->decls()) { 4657 if (D->isImplicit()) continue; 4658 4659 // Methods and method templates. 4660 if (isa<CXXMethodDecl>(D)) { 4661 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4662 } else if (isa<FunctionTemplateDecl>(D)) { 4663 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4664 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4665 4666 // Fields and static variables. 4667 } else if (isa<FieldDecl>(D)) { 4668 FieldDecl *FD = cast<FieldDecl>(D); 4669 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4670 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4671 } else if (isa<VarDecl>(D)) { 4672 VarDecl *VD = cast<VarDecl>(D); 4673 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4674 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4675 4676 // Nested classes and class templates. 4677 } else if (isa<CXXRecordDecl>(D)) { 4678 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4679 } else if (isa<ClassTemplateDecl>(D)) { 4680 CheckAbstractClassUsage(Info, 4681 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4682 } 4683 } 4684 } 4685 4686 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 4687 Attr *ClassAttr = getDLLAttr(Class); 4688 if (!ClassAttr) 4689 return; 4690 4691 assert(ClassAttr->getKind() == attr::DLLExport); 4692 4693 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4694 4695 if (TSK == TSK_ExplicitInstantiationDeclaration) 4696 // Don't go any further if this is just an explicit instantiation 4697 // declaration. 4698 return; 4699 4700 for (Decl *Member : Class->decls()) { 4701 auto *MD = dyn_cast<CXXMethodDecl>(Member); 4702 if (!MD) 4703 continue; 4704 4705 if (Member->getAttr<DLLExportAttr>()) { 4706 if (MD->isUserProvided()) { 4707 // Instantiate non-default class member functions ... 4708 4709 // .. except for certain kinds of template specializations. 4710 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4711 continue; 4712 4713 S.MarkFunctionReferenced(Class->getLocation(), MD); 4714 4715 // The function will be passed to the consumer when its definition is 4716 // encountered. 4717 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4718 MD->isCopyAssignmentOperator() || 4719 MD->isMoveAssignmentOperator()) { 4720 // Synthesize and instantiate non-trivial implicit methods, explicitly 4721 // defaulted methods, and the copy and move assignment operators. The 4722 // latter are exported even if they are trivial, because the address of 4723 // an operator can be taken and should compare equal accross libraries. 4724 DiagnosticErrorTrap Trap(S.Diags); 4725 S.MarkFunctionReferenced(Class->getLocation(), MD); 4726 if (Trap.hasErrorOccurred()) { 4727 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 4728 << Class->getName() << !S.getLangOpts().CPlusPlus11; 4729 break; 4730 } 4731 4732 // There is no later point when we will see the definition of this 4733 // function, so pass it to the consumer now. 4734 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 4735 } 4736 } 4737 } 4738 } 4739 4740 /// \brief Check class-level dllimport/dllexport attribute. 4741 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 4742 Attr *ClassAttr = getDLLAttr(Class); 4743 4744 // MSVC inherits DLL attributes to partial class template specializations. 4745 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4746 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4747 if (Attr *TemplateAttr = 4748 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4749 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 4750 A->setInherited(true); 4751 ClassAttr = A; 4752 } 4753 } 4754 } 4755 4756 if (!ClassAttr) 4757 return; 4758 4759 if (!Class->isExternallyVisible()) { 4760 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4761 << Class << ClassAttr; 4762 return; 4763 } 4764 4765 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 4766 !ClassAttr->isInherited()) { 4767 // Diagnose dll attributes on members of class with dll attribute. 4768 for (Decl *Member : Class->decls()) { 4769 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4770 continue; 4771 InheritableAttr *MemberAttr = getDLLAttr(Member); 4772 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4773 continue; 4774 4775 Diag(MemberAttr->getLocation(), 4776 diag::err_attribute_dll_member_of_dll_class) 4777 << MemberAttr << ClassAttr; 4778 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4779 Member->setInvalidDecl(); 4780 } 4781 } 4782 4783 if (Class->getDescribedClassTemplate()) 4784 // Don't inherit dll attribute until the template is instantiated. 4785 return; 4786 4787 // The class is either imported or exported. 4788 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4789 const bool ClassImported = !ClassExported; 4790 4791 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4792 4793 // Ignore explicit dllexport on explicit class template instantiation declarations. 4794 if (ClassExported && !ClassAttr->isInherited() && 4795 TSK == TSK_ExplicitInstantiationDeclaration) { 4796 Class->dropAttr<DLLExportAttr>(); 4797 return; 4798 } 4799 4800 // Force declaration of implicit members so they can inherit the attribute. 4801 ForceDeclarationOfImplicitMembers(Class); 4802 4803 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4804 // seem to be true in practice? 4805 4806 for (Decl *Member : Class->decls()) { 4807 VarDecl *VD = dyn_cast<VarDecl>(Member); 4808 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4809 4810 // Only methods and static fields inherit the attributes. 4811 if (!VD && !MD) 4812 continue; 4813 4814 if (MD) { 4815 // Don't process deleted methods. 4816 if (MD->isDeleted()) 4817 continue; 4818 4819 if (MD->isInlined()) { 4820 // MinGW does not import or export inline methods. 4821 if (!Context.getTargetInfo().getCXXABI().isMicrosoft()) 4822 continue; 4823 4824 // MSVC versions before 2015 don't export the move assignment operators, 4825 // so don't attempt to import them if we have a definition. 4826 if (ClassImported && MD->isMoveAssignmentOperator() && 4827 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 4828 continue; 4829 } 4830 } 4831 4832 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 4833 continue; 4834 4835 if (!getDLLAttr(Member)) { 4836 auto *NewAttr = 4837 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 4838 NewAttr->setInherited(true); 4839 Member->addAttr(NewAttr); 4840 } 4841 } 4842 4843 if (ClassExported) 4844 DelayedDllExportClasses.push_back(Class); 4845 } 4846 4847 /// \brief Perform propagation of DLL attributes from a derived class to a 4848 /// templated base class for MS compatibility. 4849 void Sema::propagateDLLAttrToBaseClassTemplate( 4850 CXXRecordDecl *Class, Attr *ClassAttr, 4851 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 4852 if (getDLLAttr( 4853 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 4854 // If the base class template has a DLL attribute, don't try to change it. 4855 return; 4856 } 4857 4858 auto TSK = BaseTemplateSpec->getSpecializationKind(); 4859 if (!getDLLAttr(BaseTemplateSpec) && 4860 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 4861 TSK == TSK_ImplicitInstantiation)) { 4862 // The template hasn't been instantiated yet (or it has, but only as an 4863 // explicit instantiation declaration or implicit instantiation, which means 4864 // we haven't codegenned any members yet), so propagate the attribute. 4865 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 4866 NewAttr->setInherited(true); 4867 BaseTemplateSpec->addAttr(NewAttr); 4868 4869 // If the template is already instantiated, checkDLLAttributeRedeclaration() 4870 // needs to be run again to work see the new attribute. Otherwise this will 4871 // get run whenever the template is instantiated. 4872 if (TSK != TSK_Undeclared) 4873 checkClassLevelDLLAttribute(BaseTemplateSpec); 4874 4875 return; 4876 } 4877 4878 if (getDLLAttr(BaseTemplateSpec)) { 4879 // The template has already been specialized or instantiated with an 4880 // attribute, explicitly or through propagation. We should not try to change 4881 // it. 4882 return; 4883 } 4884 4885 // The template was previously instantiated or explicitly specialized without 4886 // a dll attribute, It's too late for us to add an attribute, so warn that 4887 // this is unsupported. 4888 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 4889 << BaseTemplateSpec->isExplicitSpecialization(); 4890 Diag(ClassAttr->getLocation(), diag::note_attribute); 4891 if (BaseTemplateSpec->isExplicitSpecialization()) { 4892 Diag(BaseTemplateSpec->getLocation(), 4893 diag::note_template_class_explicit_specialization_was_here) 4894 << BaseTemplateSpec; 4895 } else { 4896 Diag(BaseTemplateSpec->getPointOfInstantiation(), 4897 diag::note_template_class_instantiation_was_here) 4898 << BaseTemplateSpec; 4899 } 4900 } 4901 4902 /// \brief Perform semantic checks on a class definition that has been 4903 /// completing, introducing implicitly-declared members, checking for 4904 /// abstract types, etc. 4905 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4906 if (!Record) 4907 return; 4908 4909 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4910 AbstractUsageInfo Info(*this, Record); 4911 CheckAbstractClassUsage(Info, Record); 4912 } 4913 4914 // If this is not an aggregate type and has no user-declared constructor, 4915 // complain about any non-static data members of reference or const scalar 4916 // type, since they will never get initializers. 4917 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4918 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4919 !Record->isLambda()) { 4920 bool Complained = false; 4921 for (const auto *F : Record->fields()) { 4922 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4923 continue; 4924 4925 if (F->getType()->isReferenceType() || 4926 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4927 if (!Complained) { 4928 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4929 << Record->getTagKind() << Record; 4930 Complained = true; 4931 } 4932 4933 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4934 << F->getType()->isReferenceType() 4935 << F->getDeclName(); 4936 } 4937 } 4938 } 4939 4940 if (Record->getIdentifier()) { 4941 // C++ [class.mem]p13: 4942 // If T is the name of a class, then each of the following shall have a 4943 // name different from T: 4944 // - every member of every anonymous union that is a member of class T. 4945 // 4946 // C++ [class.mem]p14: 4947 // In addition, if class T has a user-declared constructor (12.1), every 4948 // non-static data member of class T shall have a name different from T. 4949 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4950 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4951 ++I) { 4952 NamedDecl *D = *I; 4953 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4954 isa<IndirectFieldDecl>(D)) { 4955 Diag(D->getLocation(), diag::err_member_name_of_class) 4956 << D->getDeclName(); 4957 break; 4958 } 4959 } 4960 } 4961 4962 // Warn if the class has virtual methods but non-virtual public destructor. 4963 if (Record->isPolymorphic() && !Record->isDependentType()) { 4964 CXXDestructorDecl *dtor = Record->getDestructor(); 4965 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4966 !Record->hasAttr<FinalAttr>()) 4967 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4968 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4969 } 4970 4971 if (Record->isAbstract()) { 4972 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4973 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4974 << FA->isSpelledAsSealed(); 4975 DiagnoseAbstractType(Record); 4976 } 4977 } 4978 4979 bool HasMethodWithOverrideControl = false, 4980 HasOverridingMethodWithoutOverrideControl = false; 4981 if (!Record->isDependentType()) { 4982 for (auto *M : Record->methods()) { 4983 // See if a method overloads virtual methods in a base 4984 // class without overriding any. 4985 if (!M->isStatic()) 4986 DiagnoseHiddenVirtualMethods(M); 4987 if (M->hasAttr<OverrideAttr>()) 4988 HasMethodWithOverrideControl = true; 4989 else if (M->size_overridden_methods() > 0) 4990 HasOverridingMethodWithoutOverrideControl = true; 4991 // Check whether the explicitly-defaulted special members are valid. 4992 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4993 CheckExplicitlyDefaultedSpecialMember(M); 4994 4995 // For an explicitly defaulted or deleted special member, we defer 4996 // determining triviality until the class is complete. That time is now! 4997 if (!M->isImplicit() && !M->isUserProvided()) { 4998 CXXSpecialMember CSM = getSpecialMember(M); 4999 if (CSM != CXXInvalid) { 5000 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5001 5002 // Inform the class that we've finished declaring this member. 5003 Record->finishedDefaultedOrDeletedMember(M); 5004 } 5005 } 5006 } 5007 } 5008 5009 if (HasMethodWithOverrideControl && 5010 HasOverridingMethodWithoutOverrideControl) { 5011 // At least one method has the 'override' control declared. 5012 // Diagnose all other overridden methods which do not have 'override' specified on them. 5013 for (auto *M : Record->methods()) 5014 DiagnoseAbsenceOfOverrideControl(M); 5015 } 5016 5017 // ms_struct is a request to use the same ABI rules as MSVC. Check 5018 // whether this class uses any C++ features that are implemented 5019 // completely differently in MSVC, and if so, emit a diagnostic. 5020 // That diagnostic defaults to an error, but we allow projects to 5021 // map it down to a warning (or ignore it). It's a fairly common 5022 // practice among users of the ms_struct pragma to mass-annotate 5023 // headers, sweeping up a bunch of types that the project doesn't 5024 // really rely on MSVC-compatible layout for. We must therefore 5025 // support "ms_struct except for C++ stuff" as a secondary ABI. 5026 if (Record->isMsStruct(Context) && 5027 (Record->isPolymorphic() || Record->getNumBases())) { 5028 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5029 } 5030 5031 // Declare inheriting constructors. We do this eagerly here because: 5032 // - The standard requires an eager diagnostic for conflicting inheriting 5033 // constructors from different classes. 5034 // - The lazy declaration of the other implicit constructors is so as to not 5035 // waste space and performance on classes that are not meant to be 5036 // instantiated (e.g. meta-functions). This doesn't apply to classes that 5037 // have inheriting constructors. 5038 DeclareInheritingConstructors(Record); 5039 5040 checkClassLevelDLLAttribute(Record); 5041 } 5042 5043 /// Look up the special member function that would be called by a special 5044 /// member function for a subobject of class type. 5045 /// 5046 /// \param Class The class type of the subobject. 5047 /// \param CSM The kind of special member function. 5048 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5049 /// \param ConstRHS True if this is a copy operation with a const object 5050 /// on its RHS, that is, if the argument to the outer special member 5051 /// function is 'const' and this is not a field marked 'mutable'. 5052 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 5053 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5054 unsigned FieldQuals, bool ConstRHS) { 5055 unsigned LHSQuals = 0; 5056 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5057 LHSQuals = FieldQuals; 5058 5059 unsigned RHSQuals = FieldQuals; 5060 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5061 RHSQuals = 0; 5062 else if (ConstRHS) 5063 RHSQuals |= Qualifiers::Const; 5064 5065 return S.LookupSpecialMember(Class, CSM, 5066 RHSQuals & Qualifiers::Const, 5067 RHSQuals & Qualifiers::Volatile, 5068 false, 5069 LHSQuals & Qualifiers::Const, 5070 LHSQuals & Qualifiers::Volatile); 5071 } 5072 5073 /// Is the special member function which would be selected to perform the 5074 /// specified operation on the specified class type a constexpr constructor? 5075 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5076 Sema::CXXSpecialMember CSM, 5077 unsigned Quals, bool ConstRHS) { 5078 Sema::SpecialMemberOverloadResult *SMOR = 5079 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5080 if (!SMOR || !SMOR->getMethod()) 5081 // A constructor we wouldn't select can't be "involved in initializing" 5082 // anything. 5083 return true; 5084 return SMOR->getMethod()->isConstexpr(); 5085 } 5086 5087 /// Determine whether the specified special member function would be constexpr 5088 /// if it were implicitly defined. 5089 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5090 Sema::CXXSpecialMember CSM, 5091 bool ConstArg) { 5092 if (!S.getLangOpts().CPlusPlus11) 5093 return false; 5094 5095 // C++11 [dcl.constexpr]p4: 5096 // In the definition of a constexpr constructor [...] 5097 bool Ctor = true; 5098 switch (CSM) { 5099 case Sema::CXXDefaultConstructor: 5100 // Since default constructor lookup is essentially trivial (and cannot 5101 // involve, for instance, template instantiation), we compute whether a 5102 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5103 // 5104 // This is important for performance; we need to know whether the default 5105 // constructor is constexpr to determine whether the type is a literal type. 5106 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5107 5108 case Sema::CXXCopyConstructor: 5109 case Sema::CXXMoveConstructor: 5110 // For copy or move constructors, we need to perform overload resolution. 5111 break; 5112 5113 case Sema::CXXCopyAssignment: 5114 case Sema::CXXMoveAssignment: 5115 if (!S.getLangOpts().CPlusPlus14) 5116 return false; 5117 // In C++1y, we need to perform overload resolution. 5118 Ctor = false; 5119 break; 5120 5121 case Sema::CXXDestructor: 5122 case Sema::CXXInvalid: 5123 return false; 5124 } 5125 5126 // -- if the class is a non-empty union, or for each non-empty anonymous 5127 // union member of a non-union class, exactly one non-static data member 5128 // shall be initialized; [DR1359] 5129 // 5130 // If we squint, this is guaranteed, since exactly one non-static data member 5131 // will be initialized (if the constructor isn't deleted), we just don't know 5132 // which one. 5133 if (Ctor && ClassDecl->isUnion()) 5134 return true; 5135 5136 // -- the class shall not have any virtual base classes; 5137 if (Ctor && ClassDecl->getNumVBases()) 5138 return false; 5139 5140 // C++1y [class.copy]p26: 5141 // -- [the class] is a literal type, and 5142 if (!Ctor && !ClassDecl->isLiteral()) 5143 return false; 5144 5145 // -- every constructor involved in initializing [...] base class 5146 // sub-objects shall be a constexpr constructor; 5147 // -- the assignment operator selected to copy/move each direct base 5148 // class is a constexpr function, and 5149 for (const auto &B : ClassDecl->bases()) { 5150 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5151 if (!BaseType) continue; 5152 5153 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5154 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5155 return false; 5156 } 5157 5158 // -- every constructor involved in initializing non-static data members 5159 // [...] shall be a constexpr constructor; 5160 // -- every non-static data member and base class sub-object shall be 5161 // initialized 5162 // -- for each non-static data member of X that is of class type (or array 5163 // thereof), the assignment operator selected to copy/move that member is 5164 // a constexpr function 5165 for (const auto *F : ClassDecl->fields()) { 5166 if (F->isInvalidDecl()) 5167 continue; 5168 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5169 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5170 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5171 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5172 BaseType.getCVRQualifiers(), 5173 ConstArg && !F->isMutable())) 5174 return false; 5175 } 5176 } 5177 5178 // All OK, it's constexpr! 5179 return true; 5180 } 5181 5182 static Sema::ImplicitExceptionSpecification 5183 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5184 switch (S.getSpecialMember(MD)) { 5185 case Sema::CXXDefaultConstructor: 5186 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5187 case Sema::CXXCopyConstructor: 5188 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5189 case Sema::CXXCopyAssignment: 5190 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5191 case Sema::CXXMoveConstructor: 5192 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5193 case Sema::CXXMoveAssignment: 5194 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5195 case Sema::CXXDestructor: 5196 return S.ComputeDefaultedDtorExceptionSpec(MD); 5197 case Sema::CXXInvalid: 5198 break; 5199 } 5200 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5201 "only special members have implicit exception specs"); 5202 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5203 } 5204 5205 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5206 CXXMethodDecl *MD) { 5207 FunctionProtoType::ExtProtoInfo EPI; 5208 5209 // Build an exception specification pointing back at this member. 5210 EPI.ExceptionSpec.Type = EST_Unevaluated; 5211 EPI.ExceptionSpec.SourceDecl = MD; 5212 5213 // Set the calling convention to the default for C++ instance methods. 5214 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5215 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5216 /*IsCXXMethod=*/true)); 5217 return EPI; 5218 } 5219 5220 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5221 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5222 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5223 return; 5224 5225 // Evaluate the exception specification. 5226 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5227 5228 // Update the type of the special member to use it. 5229 UpdateExceptionSpec(MD, ESI); 5230 5231 // A user-provided destructor can be defined outside the class. When that 5232 // happens, be sure to update the exception specification on both 5233 // declarations. 5234 const FunctionProtoType *CanonicalFPT = 5235 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5236 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5237 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5238 } 5239 5240 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5241 CXXRecordDecl *RD = MD->getParent(); 5242 CXXSpecialMember CSM = getSpecialMember(MD); 5243 5244 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5245 "not an explicitly-defaulted special member"); 5246 5247 // Whether this was the first-declared instance of the constructor. 5248 // This affects whether we implicitly add an exception spec and constexpr. 5249 bool First = MD == MD->getCanonicalDecl(); 5250 5251 bool HadError = false; 5252 5253 // C++11 [dcl.fct.def.default]p1: 5254 // A function that is explicitly defaulted shall 5255 // -- be a special member function (checked elsewhere), 5256 // -- have the same type (except for ref-qualifiers, and except that a 5257 // copy operation can take a non-const reference) as an implicit 5258 // declaration, and 5259 // -- not have default arguments. 5260 unsigned ExpectedParams = 1; 5261 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5262 ExpectedParams = 0; 5263 if (MD->getNumParams() != ExpectedParams) { 5264 // This also checks for default arguments: a copy or move constructor with a 5265 // default argument is classified as a default constructor, and assignment 5266 // operations and destructors can't have default arguments. 5267 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5268 << CSM << MD->getSourceRange(); 5269 HadError = true; 5270 } else if (MD->isVariadic()) { 5271 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5272 << CSM << MD->getSourceRange(); 5273 HadError = true; 5274 } 5275 5276 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5277 5278 bool CanHaveConstParam = false; 5279 if (CSM == CXXCopyConstructor) 5280 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5281 else if (CSM == CXXCopyAssignment) 5282 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5283 5284 QualType ReturnType = Context.VoidTy; 5285 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5286 // Check for return type matching. 5287 ReturnType = Type->getReturnType(); 5288 QualType ExpectedReturnType = 5289 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5290 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5291 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5292 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5293 HadError = true; 5294 } 5295 5296 // A defaulted special member cannot have cv-qualifiers. 5297 if (Type->getTypeQuals()) { 5298 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5299 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5300 HadError = true; 5301 } 5302 } 5303 5304 // Check for parameter type matching. 5305 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5306 bool HasConstParam = false; 5307 if (ExpectedParams && ArgType->isReferenceType()) { 5308 // Argument must be reference to possibly-const T. 5309 QualType ReferentType = ArgType->getPointeeType(); 5310 HasConstParam = ReferentType.isConstQualified(); 5311 5312 if (ReferentType.isVolatileQualified()) { 5313 Diag(MD->getLocation(), 5314 diag::err_defaulted_special_member_volatile_param) << CSM; 5315 HadError = true; 5316 } 5317 5318 if (HasConstParam && !CanHaveConstParam) { 5319 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5320 Diag(MD->getLocation(), 5321 diag::err_defaulted_special_member_copy_const_param) 5322 << (CSM == CXXCopyAssignment); 5323 // FIXME: Explain why this special member can't be const. 5324 } else { 5325 Diag(MD->getLocation(), 5326 diag::err_defaulted_special_member_move_const_param) 5327 << (CSM == CXXMoveAssignment); 5328 } 5329 HadError = true; 5330 } 5331 } else if (ExpectedParams) { 5332 // A copy assignment operator can take its argument by value, but a 5333 // defaulted one cannot. 5334 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5335 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5336 HadError = true; 5337 } 5338 5339 // C++11 [dcl.fct.def.default]p2: 5340 // An explicitly-defaulted function may be declared constexpr only if it 5341 // would have been implicitly declared as constexpr, 5342 // Do not apply this rule to members of class templates, since core issue 1358 5343 // makes such functions always instantiate to constexpr functions. For 5344 // functions which cannot be constexpr (for non-constructors in C++11 and for 5345 // destructors in C++1y), this is checked elsewhere. 5346 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5347 HasConstParam); 5348 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5349 : isa<CXXConstructorDecl>(MD)) && 5350 MD->isConstexpr() && !Constexpr && 5351 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5352 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5353 // FIXME: Explain why the special member can't be constexpr. 5354 HadError = true; 5355 } 5356 5357 // and may have an explicit exception-specification only if it is compatible 5358 // with the exception-specification on the implicit declaration. 5359 if (Type->hasExceptionSpec()) { 5360 // Delay the check if this is the first declaration of the special member, 5361 // since we may not have parsed some necessary in-class initializers yet. 5362 if (First) { 5363 // If the exception specification needs to be instantiated, do so now, 5364 // before we clobber it with an EST_Unevaluated specification below. 5365 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5366 InstantiateExceptionSpec(MD->getLocStart(), MD); 5367 Type = MD->getType()->getAs<FunctionProtoType>(); 5368 } 5369 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5370 } else 5371 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5372 } 5373 5374 // If a function is explicitly defaulted on its first declaration, 5375 if (First) { 5376 // -- it is implicitly considered to be constexpr if the implicit 5377 // definition would be, 5378 MD->setConstexpr(Constexpr); 5379 5380 // -- it is implicitly considered to have the same exception-specification 5381 // as if it had been implicitly declared, 5382 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5383 EPI.ExceptionSpec.Type = EST_Unevaluated; 5384 EPI.ExceptionSpec.SourceDecl = MD; 5385 MD->setType(Context.getFunctionType(ReturnType, 5386 llvm::makeArrayRef(&ArgType, 5387 ExpectedParams), 5388 EPI)); 5389 } 5390 5391 if (ShouldDeleteSpecialMember(MD, CSM)) { 5392 if (First) { 5393 SetDeclDeleted(MD, MD->getLocation()); 5394 } else { 5395 // C++11 [dcl.fct.def.default]p4: 5396 // [For a] user-provided explicitly-defaulted function [...] if such a 5397 // function is implicitly defined as deleted, the program is ill-formed. 5398 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5399 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5400 HadError = true; 5401 } 5402 } 5403 5404 if (HadError) 5405 MD->setInvalidDecl(); 5406 } 5407 5408 /// Check whether the exception specification provided for an 5409 /// explicitly-defaulted special member matches the exception specification 5410 /// that would have been generated for an implicit special member, per 5411 /// C++11 [dcl.fct.def.default]p2. 5412 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5413 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5414 // If the exception specification was explicitly specified but hadn't been 5415 // parsed when the method was defaulted, grab it now. 5416 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5417 SpecifiedType = 5418 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5419 5420 // Compute the implicit exception specification. 5421 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5422 /*IsCXXMethod=*/true); 5423 FunctionProtoType::ExtProtoInfo EPI(CC); 5424 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5425 .getExceptionSpec(); 5426 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5427 Context.getFunctionType(Context.VoidTy, None, EPI)); 5428 5429 // Ensure that it matches. 5430 CheckEquivalentExceptionSpec( 5431 PDiag(diag::err_incorrect_defaulted_exception_spec) 5432 << getSpecialMember(MD), PDiag(), 5433 ImplicitType, SourceLocation(), 5434 SpecifiedType, MD->getLocation()); 5435 } 5436 5437 void Sema::CheckDelayedMemberExceptionSpecs() { 5438 decltype(DelayedExceptionSpecChecks) Checks; 5439 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 5440 5441 std::swap(Checks, DelayedExceptionSpecChecks); 5442 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5443 5444 // Perform any deferred checking of exception specifications for virtual 5445 // destructors. 5446 for (auto &Check : Checks) 5447 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 5448 5449 // Check that any explicitly-defaulted methods have exception specifications 5450 // compatible with their implicit exception specifications. 5451 for (auto &Spec : Specs) 5452 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 5453 } 5454 5455 namespace { 5456 struct SpecialMemberDeletionInfo { 5457 Sema &S; 5458 CXXMethodDecl *MD; 5459 Sema::CXXSpecialMember CSM; 5460 bool Diagnose; 5461 5462 // Properties of the special member, computed for convenience. 5463 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5464 SourceLocation Loc; 5465 5466 bool AllFieldsAreConst; 5467 5468 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5469 Sema::CXXSpecialMember CSM, bool Diagnose) 5470 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5471 IsConstructor(false), IsAssignment(false), IsMove(false), 5472 ConstArg(false), Loc(MD->getLocation()), 5473 AllFieldsAreConst(true) { 5474 switch (CSM) { 5475 case Sema::CXXDefaultConstructor: 5476 case Sema::CXXCopyConstructor: 5477 IsConstructor = true; 5478 break; 5479 case Sema::CXXMoveConstructor: 5480 IsConstructor = true; 5481 IsMove = true; 5482 break; 5483 case Sema::CXXCopyAssignment: 5484 IsAssignment = true; 5485 break; 5486 case Sema::CXXMoveAssignment: 5487 IsAssignment = true; 5488 IsMove = true; 5489 break; 5490 case Sema::CXXDestructor: 5491 break; 5492 case Sema::CXXInvalid: 5493 llvm_unreachable("invalid special member kind"); 5494 } 5495 5496 if (MD->getNumParams()) { 5497 if (const ReferenceType *RT = 5498 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5499 ConstArg = RT->getPointeeType().isConstQualified(); 5500 } 5501 } 5502 5503 bool inUnion() const { return MD->getParent()->isUnion(); } 5504 5505 /// Look up the corresponding special member in the given class. 5506 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5507 unsigned Quals, bool IsMutable) { 5508 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5509 ConstArg && !IsMutable); 5510 } 5511 5512 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5513 5514 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5515 bool shouldDeleteForField(FieldDecl *FD); 5516 bool shouldDeleteForAllConstMembers(); 5517 5518 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5519 unsigned Quals); 5520 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5521 Sema::SpecialMemberOverloadResult *SMOR, 5522 bool IsDtorCallInCtor); 5523 5524 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5525 }; 5526 } 5527 5528 /// Is the given special member inaccessible when used on the given 5529 /// sub-object. 5530 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5531 CXXMethodDecl *target) { 5532 /// If we're operating on a base class, the object type is the 5533 /// type of this special member. 5534 QualType objectTy; 5535 AccessSpecifier access = target->getAccess(); 5536 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5537 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5538 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5539 5540 // If we're operating on a field, the object type is the type of the field. 5541 } else { 5542 objectTy = S.Context.getTypeDeclType(target->getParent()); 5543 } 5544 5545 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5546 } 5547 5548 /// Check whether we should delete a special member due to the implicit 5549 /// definition containing a call to a special member of a subobject. 5550 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5551 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5552 bool IsDtorCallInCtor) { 5553 CXXMethodDecl *Decl = SMOR->getMethod(); 5554 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5555 5556 int DiagKind = -1; 5557 5558 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5559 DiagKind = !Decl ? 0 : 1; 5560 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5561 DiagKind = 2; 5562 else if (!isAccessible(Subobj, Decl)) 5563 DiagKind = 3; 5564 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5565 !Decl->isTrivial()) { 5566 // A member of a union must have a trivial corresponding special member. 5567 // As a weird special case, a destructor call from a union's constructor 5568 // must be accessible and non-deleted, but need not be trivial. Such a 5569 // destructor is never actually called, but is semantically checked as 5570 // if it were. 5571 DiagKind = 4; 5572 } 5573 5574 if (DiagKind == -1) 5575 return false; 5576 5577 if (Diagnose) { 5578 if (Field) { 5579 S.Diag(Field->getLocation(), 5580 diag::note_deleted_special_member_class_subobject) 5581 << CSM << MD->getParent() << /*IsField*/true 5582 << Field << DiagKind << IsDtorCallInCtor; 5583 } else { 5584 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5585 S.Diag(Base->getLocStart(), 5586 diag::note_deleted_special_member_class_subobject) 5587 << CSM << MD->getParent() << /*IsField*/false 5588 << Base->getType() << DiagKind << IsDtorCallInCtor; 5589 } 5590 5591 if (DiagKind == 1) 5592 S.NoteDeletedFunction(Decl); 5593 // FIXME: Explain inaccessibility if DiagKind == 3. 5594 } 5595 5596 return true; 5597 } 5598 5599 /// Check whether we should delete a special member function due to having a 5600 /// direct or virtual base class or non-static data member of class type M. 5601 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5602 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5603 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5604 bool IsMutable = Field && Field->isMutable(); 5605 5606 // C++11 [class.ctor]p5: 5607 // -- any direct or virtual base class, or non-static data member with no 5608 // brace-or-equal-initializer, has class type M (or array thereof) and 5609 // either M has no default constructor or overload resolution as applied 5610 // to M's default constructor results in an ambiguity or in a function 5611 // that is deleted or inaccessible 5612 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5613 // -- a direct or virtual base class B that cannot be copied/moved because 5614 // overload resolution, as applied to B's corresponding special member, 5615 // results in an ambiguity or a function that is deleted or inaccessible 5616 // from the defaulted special member 5617 // C++11 [class.dtor]p5: 5618 // -- any direct or virtual base class [...] has a type with a destructor 5619 // that is deleted or inaccessible 5620 if (!(CSM == Sema::CXXDefaultConstructor && 5621 Field && Field->hasInClassInitializer()) && 5622 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5623 false)) 5624 return true; 5625 5626 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5627 // -- any direct or virtual base class or non-static data member has a 5628 // type with a destructor that is deleted or inaccessible 5629 if (IsConstructor) { 5630 Sema::SpecialMemberOverloadResult *SMOR = 5631 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5632 false, false, false, false, false); 5633 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5634 return true; 5635 } 5636 5637 return false; 5638 } 5639 5640 /// Check whether we should delete a special member function due to the class 5641 /// having a particular direct or virtual base class. 5642 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5643 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5644 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5645 } 5646 5647 /// Check whether we should delete a special member function due to the class 5648 /// having a particular non-static data member. 5649 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5650 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5651 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5652 5653 if (CSM == Sema::CXXDefaultConstructor) { 5654 // For a default constructor, all references must be initialized in-class 5655 // and, if a union, it must have a non-const member. 5656 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5657 if (Diagnose) 5658 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5659 << MD->getParent() << FD << FieldType << /*Reference*/0; 5660 return true; 5661 } 5662 // C++11 [class.ctor]p5: any non-variant non-static data member of 5663 // const-qualified type (or array thereof) with no 5664 // brace-or-equal-initializer does not have a user-provided default 5665 // constructor. 5666 if (!inUnion() && FieldType.isConstQualified() && 5667 !FD->hasInClassInitializer() && 5668 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5669 if (Diagnose) 5670 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5671 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5672 return true; 5673 } 5674 5675 if (inUnion() && !FieldType.isConstQualified()) 5676 AllFieldsAreConst = false; 5677 } else if (CSM == Sema::CXXCopyConstructor) { 5678 // For a copy constructor, data members must not be of rvalue reference 5679 // type. 5680 if (FieldType->isRValueReferenceType()) { 5681 if (Diagnose) 5682 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5683 << MD->getParent() << FD << FieldType; 5684 return true; 5685 } 5686 } else if (IsAssignment) { 5687 // For an assignment operator, data members must not be of reference type. 5688 if (FieldType->isReferenceType()) { 5689 if (Diagnose) 5690 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5691 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5692 return true; 5693 } 5694 if (!FieldRecord && FieldType.isConstQualified()) { 5695 // C++11 [class.copy]p23: 5696 // -- a non-static data member of const non-class type (or array thereof) 5697 if (Diagnose) 5698 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5699 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5700 return true; 5701 } 5702 } 5703 5704 if (FieldRecord) { 5705 // Some additional restrictions exist on the variant members. 5706 if (!inUnion() && FieldRecord->isUnion() && 5707 FieldRecord->isAnonymousStructOrUnion()) { 5708 bool AllVariantFieldsAreConst = true; 5709 5710 // FIXME: Handle anonymous unions declared within anonymous unions. 5711 for (auto *UI : FieldRecord->fields()) { 5712 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5713 5714 if (!UnionFieldType.isConstQualified()) 5715 AllVariantFieldsAreConst = false; 5716 5717 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5718 if (UnionFieldRecord && 5719 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5720 UnionFieldType.getCVRQualifiers())) 5721 return true; 5722 } 5723 5724 // At least one member in each anonymous union must be non-const 5725 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5726 !FieldRecord->field_empty()) { 5727 if (Diagnose) 5728 S.Diag(FieldRecord->getLocation(), 5729 diag::note_deleted_default_ctor_all_const) 5730 << MD->getParent() << /*anonymous union*/1; 5731 return true; 5732 } 5733 5734 // Don't check the implicit member of the anonymous union type. 5735 // This is technically non-conformant, but sanity demands it. 5736 return false; 5737 } 5738 5739 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5740 FieldType.getCVRQualifiers())) 5741 return true; 5742 } 5743 5744 return false; 5745 } 5746 5747 /// C++11 [class.ctor] p5: 5748 /// A defaulted default constructor for a class X is defined as deleted if 5749 /// X is a union and all of its variant members are of const-qualified type. 5750 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5751 // This is a silly definition, because it gives an empty union a deleted 5752 // default constructor. Don't do that. 5753 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5754 !MD->getParent()->field_empty()) { 5755 if (Diagnose) 5756 S.Diag(MD->getParent()->getLocation(), 5757 diag::note_deleted_default_ctor_all_const) 5758 << MD->getParent() << /*not anonymous union*/0; 5759 return true; 5760 } 5761 return false; 5762 } 5763 5764 /// Determine whether a defaulted special member function should be defined as 5765 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5766 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5767 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5768 bool Diagnose) { 5769 if (MD->isInvalidDecl()) 5770 return false; 5771 CXXRecordDecl *RD = MD->getParent(); 5772 assert(!RD->isDependentType() && "do deletion after instantiation"); 5773 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5774 return false; 5775 5776 // C++11 [expr.lambda.prim]p19: 5777 // The closure type associated with a lambda-expression has a 5778 // deleted (8.4.3) default constructor and a deleted copy 5779 // assignment operator. 5780 if (RD->isLambda() && 5781 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5782 if (Diagnose) 5783 Diag(RD->getLocation(), diag::note_lambda_decl); 5784 return true; 5785 } 5786 5787 // For an anonymous struct or union, the copy and assignment special members 5788 // will never be used, so skip the check. For an anonymous union declared at 5789 // namespace scope, the constructor and destructor are used. 5790 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5791 RD->isAnonymousStructOrUnion()) 5792 return false; 5793 5794 // C++11 [class.copy]p7, p18: 5795 // If the class definition declares a move constructor or move assignment 5796 // operator, an implicitly declared copy constructor or copy assignment 5797 // operator is defined as deleted. 5798 if (MD->isImplicit() && 5799 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5800 CXXMethodDecl *UserDeclaredMove = nullptr; 5801 5802 // In Microsoft mode, a user-declared move only causes the deletion of the 5803 // corresponding copy operation, not both copy operations. 5804 if (RD->hasUserDeclaredMoveConstructor() && 5805 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5806 if (!Diagnose) return true; 5807 5808 // Find any user-declared move constructor. 5809 for (auto *I : RD->ctors()) { 5810 if (I->isMoveConstructor()) { 5811 UserDeclaredMove = I; 5812 break; 5813 } 5814 } 5815 assert(UserDeclaredMove); 5816 } else if (RD->hasUserDeclaredMoveAssignment() && 5817 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5818 if (!Diagnose) return true; 5819 5820 // Find any user-declared move assignment operator. 5821 for (auto *I : RD->methods()) { 5822 if (I->isMoveAssignmentOperator()) { 5823 UserDeclaredMove = I; 5824 break; 5825 } 5826 } 5827 assert(UserDeclaredMove); 5828 } 5829 5830 if (UserDeclaredMove) { 5831 Diag(UserDeclaredMove->getLocation(), 5832 diag::note_deleted_copy_user_declared_move) 5833 << (CSM == CXXCopyAssignment) << RD 5834 << UserDeclaredMove->isMoveAssignmentOperator(); 5835 return true; 5836 } 5837 } 5838 5839 // Do access control from the special member function 5840 ContextRAII MethodContext(*this, MD); 5841 5842 // C++11 [class.dtor]p5: 5843 // -- for a virtual destructor, lookup of the non-array deallocation function 5844 // results in an ambiguity or in a function that is deleted or inaccessible 5845 if (CSM == CXXDestructor && MD->isVirtual()) { 5846 FunctionDecl *OperatorDelete = nullptr; 5847 DeclarationName Name = 5848 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5849 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5850 OperatorDelete, false)) { 5851 if (Diagnose) 5852 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5853 return true; 5854 } 5855 } 5856 5857 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5858 5859 for (auto &BI : RD->bases()) 5860 if (!BI.isVirtual() && 5861 SMI.shouldDeleteForBase(&BI)) 5862 return true; 5863 5864 // Per DR1611, do not consider virtual bases of constructors of abstract 5865 // classes, since we are not going to construct them. 5866 if (!RD->isAbstract() || !SMI.IsConstructor) { 5867 for (auto &BI : RD->vbases()) 5868 if (SMI.shouldDeleteForBase(&BI)) 5869 return true; 5870 } 5871 5872 for (auto *FI : RD->fields()) 5873 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5874 SMI.shouldDeleteForField(FI)) 5875 return true; 5876 5877 if (SMI.shouldDeleteForAllConstMembers()) 5878 return true; 5879 5880 if (getLangOpts().CUDA) { 5881 // We should delete the special member in CUDA mode if target inference 5882 // failed. 5883 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5884 Diagnose); 5885 } 5886 5887 return false; 5888 } 5889 5890 /// Perform lookup for a special member of the specified kind, and determine 5891 /// whether it is trivial. If the triviality can be determined without the 5892 /// lookup, skip it. This is intended for use when determining whether a 5893 /// special member of a containing object is trivial, and thus does not ever 5894 /// perform overload resolution for default constructors. 5895 /// 5896 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5897 /// member that was most likely to be intended to be trivial, if any. 5898 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5899 Sema::CXXSpecialMember CSM, unsigned Quals, 5900 bool ConstRHS, CXXMethodDecl **Selected) { 5901 if (Selected) 5902 *Selected = nullptr; 5903 5904 switch (CSM) { 5905 case Sema::CXXInvalid: 5906 llvm_unreachable("not a special member"); 5907 5908 case Sema::CXXDefaultConstructor: 5909 // C++11 [class.ctor]p5: 5910 // A default constructor is trivial if: 5911 // - all the [direct subobjects] have trivial default constructors 5912 // 5913 // Note, no overload resolution is performed in this case. 5914 if (RD->hasTrivialDefaultConstructor()) 5915 return true; 5916 5917 if (Selected) { 5918 // If there's a default constructor which could have been trivial, dig it 5919 // out. Otherwise, if there's any user-provided default constructor, point 5920 // to that as an example of why there's not a trivial one. 5921 CXXConstructorDecl *DefCtor = nullptr; 5922 if (RD->needsImplicitDefaultConstructor()) 5923 S.DeclareImplicitDefaultConstructor(RD); 5924 for (auto *CI : RD->ctors()) { 5925 if (!CI->isDefaultConstructor()) 5926 continue; 5927 DefCtor = CI; 5928 if (!DefCtor->isUserProvided()) 5929 break; 5930 } 5931 5932 *Selected = DefCtor; 5933 } 5934 5935 return false; 5936 5937 case Sema::CXXDestructor: 5938 // C++11 [class.dtor]p5: 5939 // A destructor is trivial if: 5940 // - all the direct [subobjects] have trivial destructors 5941 if (RD->hasTrivialDestructor()) 5942 return true; 5943 5944 if (Selected) { 5945 if (RD->needsImplicitDestructor()) 5946 S.DeclareImplicitDestructor(RD); 5947 *Selected = RD->getDestructor(); 5948 } 5949 5950 return false; 5951 5952 case Sema::CXXCopyConstructor: 5953 // C++11 [class.copy]p12: 5954 // A copy constructor is trivial if: 5955 // - the constructor selected to copy each direct [subobject] is trivial 5956 if (RD->hasTrivialCopyConstructor()) { 5957 if (Quals == Qualifiers::Const) 5958 // We must either select the trivial copy constructor or reach an 5959 // ambiguity; no need to actually perform overload resolution. 5960 return true; 5961 } else if (!Selected) { 5962 return false; 5963 } 5964 // In C++98, we are not supposed to perform overload resolution here, but we 5965 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5966 // cases like B as having a non-trivial copy constructor: 5967 // struct A { template<typename T> A(T&); }; 5968 // struct B { mutable A a; }; 5969 goto NeedOverloadResolution; 5970 5971 case Sema::CXXCopyAssignment: 5972 // C++11 [class.copy]p25: 5973 // A copy assignment operator is trivial if: 5974 // - the assignment operator selected to copy each direct [subobject] is 5975 // trivial 5976 if (RD->hasTrivialCopyAssignment()) { 5977 if (Quals == Qualifiers::Const) 5978 return true; 5979 } else if (!Selected) { 5980 return false; 5981 } 5982 // In C++98, we are not supposed to perform overload resolution here, but we 5983 // treat that as a language defect. 5984 goto NeedOverloadResolution; 5985 5986 case Sema::CXXMoveConstructor: 5987 case Sema::CXXMoveAssignment: 5988 NeedOverloadResolution: 5989 Sema::SpecialMemberOverloadResult *SMOR = 5990 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5991 5992 // The standard doesn't describe how to behave if the lookup is ambiguous. 5993 // We treat it as not making the member non-trivial, just like the standard 5994 // mandates for the default constructor. This should rarely matter, because 5995 // the member will also be deleted. 5996 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5997 return true; 5998 5999 if (!SMOR->getMethod()) { 6000 assert(SMOR->getKind() == 6001 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 6002 return false; 6003 } 6004 6005 // We deliberately don't check if we found a deleted special member. We're 6006 // not supposed to! 6007 if (Selected) 6008 *Selected = SMOR->getMethod(); 6009 return SMOR->getMethod()->isTrivial(); 6010 } 6011 6012 llvm_unreachable("unknown special method kind"); 6013 } 6014 6015 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 6016 for (auto *CI : RD->ctors()) 6017 if (!CI->isImplicit()) 6018 return CI; 6019 6020 // Look for constructor templates. 6021 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 6022 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 6023 if (CXXConstructorDecl *CD = 6024 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 6025 return CD; 6026 } 6027 6028 return nullptr; 6029 } 6030 6031 /// The kind of subobject we are checking for triviality. The values of this 6032 /// enumeration are used in diagnostics. 6033 enum TrivialSubobjectKind { 6034 /// The subobject is a base class. 6035 TSK_BaseClass, 6036 /// The subobject is a non-static data member. 6037 TSK_Field, 6038 /// The object is actually the complete object. 6039 TSK_CompleteObject 6040 }; 6041 6042 /// Check whether the special member selected for a given type would be trivial. 6043 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 6044 QualType SubType, bool ConstRHS, 6045 Sema::CXXSpecialMember CSM, 6046 TrivialSubobjectKind Kind, 6047 bool Diagnose) { 6048 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 6049 if (!SubRD) 6050 return true; 6051 6052 CXXMethodDecl *Selected; 6053 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 6054 ConstRHS, Diagnose ? &Selected : nullptr)) 6055 return true; 6056 6057 if (Diagnose) { 6058 if (ConstRHS) 6059 SubType.addConst(); 6060 6061 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 6062 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 6063 << Kind << SubType.getUnqualifiedType(); 6064 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6065 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6066 } else if (!Selected) 6067 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6068 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6069 else if (Selected->isUserProvided()) { 6070 if (Kind == TSK_CompleteObject) 6071 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6072 << Kind << SubType.getUnqualifiedType() << CSM; 6073 else { 6074 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6075 << Kind << SubType.getUnqualifiedType() << CSM; 6076 S.Diag(Selected->getLocation(), diag::note_declared_at); 6077 } 6078 } else { 6079 if (Kind != TSK_CompleteObject) 6080 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6081 << Kind << SubType.getUnqualifiedType() << CSM; 6082 6083 // Explain why the defaulted or deleted special member isn't trivial. 6084 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6085 } 6086 } 6087 6088 return false; 6089 } 6090 6091 /// Check whether the members of a class type allow a special member to be 6092 /// trivial. 6093 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 6094 Sema::CXXSpecialMember CSM, 6095 bool ConstArg, bool Diagnose) { 6096 for (const auto *FI : RD->fields()) { 6097 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 6098 continue; 6099 6100 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 6101 6102 // Pretend anonymous struct or union members are members of this class. 6103 if (FI->isAnonymousStructOrUnion()) { 6104 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 6105 CSM, ConstArg, Diagnose)) 6106 return false; 6107 continue; 6108 } 6109 6110 // C++11 [class.ctor]p5: 6111 // A default constructor is trivial if [...] 6112 // -- no non-static data member of its class has a 6113 // brace-or-equal-initializer 6114 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 6115 if (Diagnose) 6116 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 6117 return false; 6118 } 6119 6120 // Objective C ARC 4.3.5: 6121 // [...] nontrivally ownership-qualified types are [...] not trivially 6122 // default constructible, copy constructible, move constructible, copy 6123 // assignable, move assignable, or destructible [...] 6124 if (S.getLangOpts().ObjCAutoRefCount && 6125 FieldType.hasNonTrivialObjCLifetime()) { 6126 if (Diagnose) 6127 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6128 << RD << FieldType.getObjCLifetime(); 6129 return false; 6130 } 6131 6132 bool ConstRHS = ConstArg && !FI->isMutable(); 6133 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6134 CSM, TSK_Field, Diagnose)) 6135 return false; 6136 } 6137 6138 return true; 6139 } 6140 6141 /// Diagnose why the specified class does not have a trivial special member of 6142 /// the given kind. 6143 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6144 QualType Ty = Context.getRecordType(RD); 6145 6146 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6147 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6148 TSK_CompleteObject, /*Diagnose*/true); 6149 } 6150 6151 /// Determine whether a defaulted or deleted special member function is trivial, 6152 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6153 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6154 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6155 bool Diagnose) { 6156 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6157 6158 CXXRecordDecl *RD = MD->getParent(); 6159 6160 bool ConstArg = false; 6161 6162 // C++11 [class.copy]p12, p25: [DR1593] 6163 // A [special member] is trivial if [...] its parameter-type-list is 6164 // equivalent to the parameter-type-list of an implicit declaration [...] 6165 switch (CSM) { 6166 case CXXDefaultConstructor: 6167 case CXXDestructor: 6168 // Trivial default constructors and destructors cannot have parameters. 6169 break; 6170 6171 case CXXCopyConstructor: 6172 case CXXCopyAssignment: { 6173 // Trivial copy operations always have const, non-volatile parameter types. 6174 ConstArg = true; 6175 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6176 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6177 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6178 if (Diagnose) 6179 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6180 << Param0->getSourceRange() << Param0->getType() 6181 << Context.getLValueReferenceType( 6182 Context.getRecordType(RD).withConst()); 6183 return false; 6184 } 6185 break; 6186 } 6187 6188 case CXXMoveConstructor: 6189 case CXXMoveAssignment: { 6190 // Trivial move operations always have non-cv-qualified parameters. 6191 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6192 const RValueReferenceType *RT = 6193 Param0->getType()->getAs<RValueReferenceType>(); 6194 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6195 if (Diagnose) 6196 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6197 << Param0->getSourceRange() << Param0->getType() 6198 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6199 return false; 6200 } 6201 break; 6202 } 6203 6204 case CXXInvalid: 6205 llvm_unreachable("not a special member"); 6206 } 6207 6208 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6209 if (Diagnose) 6210 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6211 diag::note_nontrivial_default_arg) 6212 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6213 return false; 6214 } 6215 if (MD->isVariadic()) { 6216 if (Diagnose) 6217 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6218 return false; 6219 } 6220 6221 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6222 // A copy/move [constructor or assignment operator] is trivial if 6223 // -- the [member] selected to copy/move each direct base class subobject 6224 // is trivial 6225 // 6226 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6227 // A [default constructor or destructor] is trivial if 6228 // -- all the direct base classes have trivial [default constructors or 6229 // destructors] 6230 for (const auto &BI : RD->bases()) 6231 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6232 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6233 return false; 6234 6235 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6236 // A copy/move [constructor or assignment operator] for a class X is 6237 // trivial if 6238 // -- for each non-static data member of X that is of class type (or array 6239 // thereof), the constructor selected to copy/move that member is 6240 // trivial 6241 // 6242 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6243 // A [default constructor or destructor] is trivial if 6244 // -- for all of the non-static data members of its class that are of class 6245 // type (or array thereof), each such class has a trivial [default 6246 // constructor or destructor] 6247 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6248 return false; 6249 6250 // C++11 [class.dtor]p5: 6251 // A destructor is trivial if [...] 6252 // -- the destructor is not virtual 6253 if (CSM == CXXDestructor && MD->isVirtual()) { 6254 if (Diagnose) 6255 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6256 return false; 6257 } 6258 6259 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6260 // A [special member] for class X is trivial if [...] 6261 // -- class X has no virtual functions and no virtual base classes 6262 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6263 if (!Diagnose) 6264 return false; 6265 6266 if (RD->getNumVBases()) { 6267 // Check for virtual bases. We already know that the corresponding 6268 // member in all bases is trivial, so vbases must all be direct. 6269 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6270 assert(BS.isVirtual()); 6271 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6272 return false; 6273 } 6274 6275 // Must have a virtual method. 6276 for (const auto *MI : RD->methods()) { 6277 if (MI->isVirtual()) { 6278 SourceLocation MLoc = MI->getLocStart(); 6279 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6280 return false; 6281 } 6282 } 6283 6284 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6285 } 6286 6287 // Looks like it's trivial! 6288 return true; 6289 } 6290 6291 namespace { 6292 struct FindHiddenVirtualMethod { 6293 Sema *S; 6294 CXXMethodDecl *Method; 6295 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6296 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6297 6298 private: 6299 /// Check whether any most overriden method from MD in Methods 6300 static bool CheckMostOverridenMethods( 6301 const CXXMethodDecl *MD, 6302 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 6303 if (MD->size_overridden_methods() == 0) 6304 return Methods.count(MD->getCanonicalDecl()); 6305 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6306 E = MD->end_overridden_methods(); 6307 I != E; ++I) 6308 if (CheckMostOverridenMethods(*I, Methods)) 6309 return true; 6310 return false; 6311 } 6312 6313 public: 6314 /// Member lookup function that determines whether a given C++ 6315 /// method overloads virtual methods in a base class without overriding any, 6316 /// to be used with CXXRecordDecl::lookupInBases(). 6317 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 6318 RecordDecl *BaseRecord = 6319 Specifier->getType()->getAs<RecordType>()->getDecl(); 6320 6321 DeclarationName Name = Method->getDeclName(); 6322 assert(Name.getNameKind() == DeclarationName::Identifier); 6323 6324 bool foundSameNameMethod = false; 6325 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6326 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 6327 Path.Decls = Path.Decls.slice(1)) { 6328 NamedDecl *D = Path.Decls.front(); 6329 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6330 MD = MD->getCanonicalDecl(); 6331 foundSameNameMethod = true; 6332 // Interested only in hidden virtual methods. 6333 if (!MD->isVirtual()) 6334 continue; 6335 // If the method we are checking overrides a method from its base 6336 // don't warn about the other overloaded methods. Clang deviates from 6337 // GCC by only diagnosing overloads of inherited virtual functions that 6338 // do not override any other virtual functions in the base. GCC's 6339 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6340 // function from a base class. These cases may be better served by a 6341 // warning (not specific to virtual functions) on call sites when the 6342 // call would select a different function from the base class, were it 6343 // visible. 6344 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6345 if (!S->IsOverload(Method, MD, false)) 6346 return true; 6347 // Collect the overload only if its hidden. 6348 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 6349 overloadedMethods.push_back(MD); 6350 } 6351 } 6352 6353 if (foundSameNameMethod) 6354 OverloadedMethods.append(overloadedMethods.begin(), 6355 overloadedMethods.end()); 6356 return foundSameNameMethod; 6357 } 6358 }; 6359 } // end anonymous namespace 6360 6361 /// \brief Add the most overriden methods from MD to Methods 6362 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6363 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6364 if (MD->size_overridden_methods() == 0) 6365 Methods.insert(MD->getCanonicalDecl()); 6366 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6367 E = MD->end_overridden_methods(); 6368 I != E; ++I) 6369 AddMostOverridenMethods(*I, Methods); 6370 } 6371 6372 /// \brief Check if a method overloads virtual methods in a base class without 6373 /// overriding any. 6374 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6375 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6376 if (!MD->getDeclName().isIdentifier()) 6377 return; 6378 6379 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6380 /*bool RecordPaths=*/false, 6381 /*bool DetectVirtual=*/false); 6382 FindHiddenVirtualMethod FHVM; 6383 FHVM.Method = MD; 6384 FHVM.S = this; 6385 6386 // Keep the base methods that were overriden or introduced in the subclass 6387 // by 'using' in a set. A base method not in this set is hidden. 6388 CXXRecordDecl *DC = MD->getParent(); 6389 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6390 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6391 NamedDecl *ND = *I; 6392 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6393 ND = shad->getTargetDecl(); 6394 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6395 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 6396 } 6397 6398 if (DC->lookupInBases(FHVM, Paths)) 6399 OverloadedMethods = FHVM.OverloadedMethods; 6400 } 6401 6402 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6403 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6404 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6405 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6406 PartialDiagnostic PD = PDiag( 6407 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6408 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6409 Diag(overloadedMD->getLocation(), PD); 6410 } 6411 } 6412 6413 /// \brief Diagnose methods which overload virtual methods in a base class 6414 /// without overriding any. 6415 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6416 if (MD->isInvalidDecl()) 6417 return; 6418 6419 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6420 return; 6421 6422 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6423 FindHiddenVirtualMethods(MD, OverloadedMethods); 6424 if (!OverloadedMethods.empty()) { 6425 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6426 << MD << (OverloadedMethods.size() > 1); 6427 6428 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6429 } 6430 } 6431 6432 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6433 Decl *TagDecl, 6434 SourceLocation LBrac, 6435 SourceLocation RBrac, 6436 AttributeList *AttrList) { 6437 if (!TagDecl) 6438 return; 6439 6440 AdjustDeclIfTemplate(TagDecl); 6441 6442 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6443 if (l->getKind() != AttributeList::AT_Visibility) 6444 continue; 6445 l->setInvalid(); 6446 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6447 l->getName(); 6448 } 6449 6450 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6451 // strict aliasing violation! 6452 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6453 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6454 6455 CheckCompletedCXXClass( 6456 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6457 } 6458 6459 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6460 /// special functions, such as the default constructor, copy 6461 /// constructor, or destructor, to the given C++ class (C++ 6462 /// [special]p1). This routine can only be executed just before the 6463 /// definition of the class is complete. 6464 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6465 if (!ClassDecl->hasUserDeclaredConstructor()) 6466 ++ASTContext::NumImplicitDefaultConstructors; 6467 6468 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6469 ++ASTContext::NumImplicitCopyConstructors; 6470 6471 // If the properties or semantics of the copy constructor couldn't be 6472 // determined while the class was being declared, force a declaration 6473 // of it now. 6474 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6475 DeclareImplicitCopyConstructor(ClassDecl); 6476 } 6477 6478 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6479 ++ASTContext::NumImplicitMoveConstructors; 6480 6481 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6482 DeclareImplicitMoveConstructor(ClassDecl); 6483 } 6484 6485 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6486 ++ASTContext::NumImplicitCopyAssignmentOperators; 6487 6488 // If we have a dynamic class, then the copy assignment operator may be 6489 // virtual, so we have to declare it immediately. This ensures that, e.g., 6490 // it shows up in the right place in the vtable and that we diagnose 6491 // problems with the implicit exception specification. 6492 if (ClassDecl->isDynamicClass() || 6493 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6494 DeclareImplicitCopyAssignment(ClassDecl); 6495 } 6496 6497 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6498 ++ASTContext::NumImplicitMoveAssignmentOperators; 6499 6500 // Likewise for the move assignment operator. 6501 if (ClassDecl->isDynamicClass() || 6502 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6503 DeclareImplicitMoveAssignment(ClassDecl); 6504 } 6505 6506 if (!ClassDecl->hasUserDeclaredDestructor()) { 6507 ++ASTContext::NumImplicitDestructors; 6508 6509 // If we have a dynamic class, then the destructor may be virtual, so we 6510 // have to declare the destructor immediately. This ensures that, e.g., it 6511 // shows up in the right place in the vtable and that we diagnose problems 6512 // with the implicit exception specification. 6513 if (ClassDecl->isDynamicClass() || 6514 ClassDecl->needsOverloadResolutionForDestructor()) 6515 DeclareImplicitDestructor(ClassDecl); 6516 } 6517 } 6518 6519 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6520 if (!D) 6521 return 0; 6522 6523 // The order of template parameters is not important here. All names 6524 // get added to the same scope. 6525 SmallVector<TemplateParameterList *, 4> ParameterLists; 6526 6527 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6528 D = TD->getTemplatedDecl(); 6529 6530 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6531 ParameterLists.push_back(PSD->getTemplateParameters()); 6532 6533 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6534 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6535 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6536 6537 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6538 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6539 ParameterLists.push_back(FTD->getTemplateParameters()); 6540 } 6541 } 6542 6543 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6544 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6545 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6546 6547 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6548 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6549 ParameterLists.push_back(CTD->getTemplateParameters()); 6550 } 6551 } 6552 6553 unsigned Count = 0; 6554 for (TemplateParameterList *Params : ParameterLists) { 6555 if (Params->size() > 0) 6556 // Ignore explicit specializations; they don't contribute to the template 6557 // depth. 6558 ++Count; 6559 for (NamedDecl *Param : *Params) { 6560 if (Param->getDeclName()) { 6561 S->AddDecl(Param); 6562 IdResolver.AddDecl(Param); 6563 } 6564 } 6565 } 6566 6567 return Count; 6568 } 6569 6570 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6571 if (!RecordD) return; 6572 AdjustDeclIfTemplate(RecordD); 6573 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6574 PushDeclContext(S, Record); 6575 } 6576 6577 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6578 if (!RecordD) return; 6579 PopDeclContext(); 6580 } 6581 6582 /// This is used to implement the constant expression evaluation part of the 6583 /// attribute enable_if extension. There is nothing in standard C++ which would 6584 /// require reentering parameters. 6585 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6586 if (!Param) 6587 return; 6588 6589 S->AddDecl(Param); 6590 if (Param->getDeclName()) 6591 IdResolver.AddDecl(Param); 6592 } 6593 6594 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6595 /// parsing a top-level (non-nested) C++ class, and we are now 6596 /// parsing those parts of the given Method declaration that could 6597 /// not be parsed earlier (C++ [class.mem]p2), such as default 6598 /// arguments. This action should enter the scope of the given 6599 /// Method declaration as if we had just parsed the qualified method 6600 /// name. However, it should not bring the parameters into scope; 6601 /// that will be performed by ActOnDelayedCXXMethodParameter. 6602 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6603 } 6604 6605 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6606 /// C++ method declaration. We're (re-)introducing the given 6607 /// function parameter into scope for use in parsing later parts of 6608 /// the method declaration. For example, we could see an 6609 /// ActOnParamDefaultArgument event for this parameter. 6610 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6611 if (!ParamD) 6612 return; 6613 6614 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6615 6616 // If this parameter has an unparsed default argument, clear it out 6617 // to make way for the parsed default argument. 6618 if (Param->hasUnparsedDefaultArg()) 6619 Param->setDefaultArg(nullptr); 6620 6621 S->AddDecl(Param); 6622 if (Param->getDeclName()) 6623 IdResolver.AddDecl(Param); 6624 } 6625 6626 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6627 /// processing the delayed method declaration for Method. The method 6628 /// declaration is now considered finished. There may be a separate 6629 /// ActOnStartOfFunctionDef action later (not necessarily 6630 /// immediately!) for this method, if it was also defined inside the 6631 /// class body. 6632 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6633 if (!MethodD) 6634 return; 6635 6636 AdjustDeclIfTemplate(MethodD); 6637 6638 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6639 6640 // Now that we have our default arguments, check the constructor 6641 // again. It could produce additional diagnostics or affect whether 6642 // the class has implicitly-declared destructors, among other 6643 // things. 6644 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6645 CheckConstructor(Constructor); 6646 6647 // Check the default arguments, which we may have added. 6648 if (!Method->isInvalidDecl()) 6649 CheckCXXDefaultArguments(Method); 6650 } 6651 6652 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6653 /// the well-formedness of the constructor declarator @p D with type @p 6654 /// R. If there are any errors in the declarator, this routine will 6655 /// emit diagnostics and set the invalid bit to true. In any case, the type 6656 /// will be updated to reflect a well-formed type for the constructor and 6657 /// returned. 6658 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6659 StorageClass &SC) { 6660 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6661 6662 // C++ [class.ctor]p3: 6663 // A constructor shall not be virtual (10.3) or static (9.4). A 6664 // constructor can be invoked for a const, volatile or const 6665 // volatile object. A constructor shall not be declared const, 6666 // volatile, or const volatile (9.3.2). 6667 if (isVirtual) { 6668 if (!D.isInvalidType()) 6669 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6670 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6671 << SourceRange(D.getIdentifierLoc()); 6672 D.setInvalidType(); 6673 } 6674 if (SC == SC_Static) { 6675 if (!D.isInvalidType()) 6676 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6677 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6678 << SourceRange(D.getIdentifierLoc()); 6679 D.setInvalidType(); 6680 SC = SC_None; 6681 } 6682 6683 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6684 diagnoseIgnoredQualifiers( 6685 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6686 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6687 D.getDeclSpec().getRestrictSpecLoc(), 6688 D.getDeclSpec().getAtomicSpecLoc()); 6689 D.setInvalidType(); 6690 } 6691 6692 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6693 if (FTI.TypeQuals != 0) { 6694 if (FTI.TypeQuals & Qualifiers::Const) 6695 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6696 << "const" << SourceRange(D.getIdentifierLoc()); 6697 if (FTI.TypeQuals & Qualifiers::Volatile) 6698 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6699 << "volatile" << SourceRange(D.getIdentifierLoc()); 6700 if (FTI.TypeQuals & Qualifiers::Restrict) 6701 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6702 << "restrict" << SourceRange(D.getIdentifierLoc()); 6703 D.setInvalidType(); 6704 } 6705 6706 // C++0x [class.ctor]p4: 6707 // A constructor shall not be declared with a ref-qualifier. 6708 if (FTI.hasRefQualifier()) { 6709 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6710 << FTI.RefQualifierIsLValueRef 6711 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6712 D.setInvalidType(); 6713 } 6714 6715 // Rebuild the function type "R" without any type qualifiers (in 6716 // case any of the errors above fired) and with "void" as the 6717 // return type, since constructors don't have return types. 6718 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6719 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6720 return R; 6721 6722 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6723 EPI.TypeQuals = 0; 6724 EPI.RefQualifier = RQ_None; 6725 6726 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6727 } 6728 6729 /// CheckConstructor - Checks a fully-formed constructor for 6730 /// well-formedness, issuing any diagnostics required. Returns true if 6731 /// the constructor declarator is invalid. 6732 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6733 CXXRecordDecl *ClassDecl 6734 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6735 if (!ClassDecl) 6736 return Constructor->setInvalidDecl(); 6737 6738 // C++ [class.copy]p3: 6739 // A declaration of a constructor for a class X is ill-formed if 6740 // its first parameter is of type (optionally cv-qualified) X and 6741 // either there are no other parameters or else all other 6742 // parameters have default arguments. 6743 if (!Constructor->isInvalidDecl() && 6744 ((Constructor->getNumParams() == 1) || 6745 (Constructor->getNumParams() > 1 && 6746 Constructor->getParamDecl(1)->hasDefaultArg())) && 6747 Constructor->getTemplateSpecializationKind() 6748 != TSK_ImplicitInstantiation) { 6749 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6750 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6751 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6752 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6753 const char *ConstRef 6754 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6755 : " const &"; 6756 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6757 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6758 6759 // FIXME: Rather that making the constructor invalid, we should endeavor 6760 // to fix the type. 6761 Constructor->setInvalidDecl(); 6762 } 6763 } 6764 } 6765 6766 /// CheckDestructor - Checks a fully-formed destructor definition for 6767 /// well-formedness, issuing any diagnostics required. Returns true 6768 /// on error. 6769 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6770 CXXRecordDecl *RD = Destructor->getParent(); 6771 6772 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6773 SourceLocation Loc; 6774 6775 if (!Destructor->isImplicit()) 6776 Loc = Destructor->getLocation(); 6777 else 6778 Loc = RD->getLocation(); 6779 6780 // If we have a virtual destructor, look up the deallocation function 6781 FunctionDecl *OperatorDelete = nullptr; 6782 DeclarationName Name = 6783 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6784 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6785 return true; 6786 // If there's no class-specific operator delete, look up the global 6787 // non-array delete. 6788 if (!OperatorDelete) 6789 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6790 6791 MarkFunctionReferenced(Loc, OperatorDelete); 6792 6793 Destructor->setOperatorDelete(OperatorDelete); 6794 } 6795 6796 return false; 6797 } 6798 6799 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6800 /// the well-formednes of the destructor declarator @p D with type @p 6801 /// R. If there are any errors in the declarator, this routine will 6802 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6803 /// will be updated to reflect a well-formed type for the destructor and 6804 /// returned. 6805 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6806 StorageClass& SC) { 6807 // C++ [class.dtor]p1: 6808 // [...] A typedef-name that names a class is a class-name 6809 // (7.1.3); however, a typedef-name that names a class shall not 6810 // be used as the identifier in the declarator for a destructor 6811 // declaration. 6812 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6813 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6814 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6815 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6816 else if (const TemplateSpecializationType *TST = 6817 DeclaratorType->getAs<TemplateSpecializationType>()) 6818 if (TST->isTypeAlias()) 6819 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6820 << DeclaratorType << 1; 6821 6822 // C++ [class.dtor]p2: 6823 // A destructor is used to destroy objects of its class type. A 6824 // destructor takes no parameters, and no return type can be 6825 // specified for it (not even void). The address of a destructor 6826 // shall not be taken. A destructor shall not be static. A 6827 // destructor can be invoked for a const, volatile or const 6828 // volatile object. A destructor shall not be declared const, 6829 // volatile or const volatile (9.3.2). 6830 if (SC == SC_Static) { 6831 if (!D.isInvalidType()) 6832 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6833 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6834 << SourceRange(D.getIdentifierLoc()) 6835 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6836 6837 SC = SC_None; 6838 } 6839 if (!D.isInvalidType()) { 6840 // Destructors don't have return types, but the parser will 6841 // happily parse something like: 6842 // 6843 // class X { 6844 // float ~X(); 6845 // }; 6846 // 6847 // The return type will be eliminated later. 6848 if (D.getDeclSpec().hasTypeSpecifier()) 6849 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6850 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6851 << SourceRange(D.getIdentifierLoc()); 6852 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6853 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6854 SourceLocation(), 6855 D.getDeclSpec().getConstSpecLoc(), 6856 D.getDeclSpec().getVolatileSpecLoc(), 6857 D.getDeclSpec().getRestrictSpecLoc(), 6858 D.getDeclSpec().getAtomicSpecLoc()); 6859 D.setInvalidType(); 6860 } 6861 } 6862 6863 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6864 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6865 if (FTI.TypeQuals & Qualifiers::Const) 6866 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6867 << "const" << SourceRange(D.getIdentifierLoc()); 6868 if (FTI.TypeQuals & Qualifiers::Volatile) 6869 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6870 << "volatile" << SourceRange(D.getIdentifierLoc()); 6871 if (FTI.TypeQuals & Qualifiers::Restrict) 6872 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6873 << "restrict" << SourceRange(D.getIdentifierLoc()); 6874 D.setInvalidType(); 6875 } 6876 6877 // C++0x [class.dtor]p2: 6878 // A destructor shall not be declared with a ref-qualifier. 6879 if (FTI.hasRefQualifier()) { 6880 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6881 << FTI.RefQualifierIsLValueRef 6882 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6883 D.setInvalidType(); 6884 } 6885 6886 // Make sure we don't have any parameters. 6887 if (FTIHasNonVoidParameters(FTI)) { 6888 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6889 6890 // Delete the parameters. 6891 FTI.freeParams(); 6892 D.setInvalidType(); 6893 } 6894 6895 // Make sure the destructor isn't variadic. 6896 if (FTI.isVariadic) { 6897 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6898 D.setInvalidType(); 6899 } 6900 6901 // Rebuild the function type "R" without any type qualifiers or 6902 // parameters (in case any of the errors above fired) and with 6903 // "void" as the return type, since destructors don't have return 6904 // types. 6905 if (!D.isInvalidType()) 6906 return R; 6907 6908 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6909 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6910 EPI.Variadic = false; 6911 EPI.TypeQuals = 0; 6912 EPI.RefQualifier = RQ_None; 6913 return Context.getFunctionType(Context.VoidTy, None, EPI); 6914 } 6915 6916 static void extendLeft(SourceRange &R, SourceRange Before) { 6917 if (Before.isInvalid()) 6918 return; 6919 R.setBegin(Before.getBegin()); 6920 if (R.getEnd().isInvalid()) 6921 R.setEnd(Before.getEnd()); 6922 } 6923 6924 static void extendRight(SourceRange &R, SourceRange After) { 6925 if (After.isInvalid()) 6926 return; 6927 if (R.getBegin().isInvalid()) 6928 R.setBegin(After.getBegin()); 6929 R.setEnd(After.getEnd()); 6930 } 6931 6932 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6933 /// well-formednes of the conversion function declarator @p D with 6934 /// type @p R. If there are any errors in the declarator, this routine 6935 /// will emit diagnostics and return true. Otherwise, it will return 6936 /// false. Either way, the type @p R will be updated to reflect a 6937 /// well-formed type for the conversion operator. 6938 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6939 StorageClass& SC) { 6940 // C++ [class.conv.fct]p1: 6941 // Neither parameter types nor return type can be specified. The 6942 // type of a conversion function (8.3.5) is "function taking no 6943 // parameter returning conversion-type-id." 6944 if (SC == SC_Static) { 6945 if (!D.isInvalidType()) 6946 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6947 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6948 << D.getName().getSourceRange(); 6949 D.setInvalidType(); 6950 SC = SC_None; 6951 } 6952 6953 TypeSourceInfo *ConvTSI = nullptr; 6954 QualType ConvType = 6955 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 6956 6957 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6958 // Conversion functions don't have return types, but the parser will 6959 // happily parse something like: 6960 // 6961 // class X { 6962 // float operator bool(); 6963 // }; 6964 // 6965 // The return type will be changed later anyway. 6966 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6967 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6968 << SourceRange(D.getIdentifierLoc()); 6969 D.setInvalidType(); 6970 } 6971 6972 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6973 6974 // Make sure we don't have any parameters. 6975 if (Proto->getNumParams() > 0) { 6976 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6977 6978 // Delete the parameters. 6979 D.getFunctionTypeInfo().freeParams(); 6980 D.setInvalidType(); 6981 } else if (Proto->isVariadic()) { 6982 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6983 D.setInvalidType(); 6984 } 6985 6986 // Diagnose "&operator bool()" and other such nonsense. This 6987 // is actually a gcc extension which we don't support. 6988 if (Proto->getReturnType() != ConvType) { 6989 bool NeedsTypedef = false; 6990 SourceRange Before, After; 6991 6992 // Walk the chunks and extract information on them for our diagnostic. 6993 bool PastFunctionChunk = false; 6994 for (auto &Chunk : D.type_objects()) { 6995 switch (Chunk.Kind) { 6996 case DeclaratorChunk::Function: 6997 if (!PastFunctionChunk) { 6998 if (Chunk.Fun.HasTrailingReturnType) { 6999 TypeSourceInfo *TRT = nullptr; 7000 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 7001 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 7002 } 7003 PastFunctionChunk = true; 7004 break; 7005 } 7006 // Fall through. 7007 case DeclaratorChunk::Array: 7008 NeedsTypedef = true; 7009 extendRight(After, Chunk.getSourceRange()); 7010 break; 7011 7012 case DeclaratorChunk::Pointer: 7013 case DeclaratorChunk::BlockPointer: 7014 case DeclaratorChunk::Reference: 7015 case DeclaratorChunk::MemberPointer: 7016 extendLeft(Before, Chunk.getSourceRange()); 7017 break; 7018 7019 case DeclaratorChunk::Paren: 7020 extendLeft(Before, Chunk.Loc); 7021 extendRight(After, Chunk.EndLoc); 7022 break; 7023 } 7024 } 7025 7026 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 7027 After.isValid() ? After.getBegin() : 7028 D.getIdentifierLoc(); 7029 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 7030 DB << Before << After; 7031 7032 if (!NeedsTypedef) { 7033 DB << /*don't need a typedef*/0; 7034 7035 // If we can provide a correct fix-it hint, do so. 7036 if (After.isInvalid() && ConvTSI) { 7037 SourceLocation InsertLoc = 7038 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 7039 DB << FixItHint::CreateInsertion(InsertLoc, " ") 7040 << FixItHint::CreateInsertionFromRange( 7041 InsertLoc, CharSourceRange::getTokenRange(Before)) 7042 << FixItHint::CreateRemoval(Before); 7043 } 7044 } else if (!Proto->getReturnType()->isDependentType()) { 7045 DB << /*typedef*/1 << Proto->getReturnType(); 7046 } else if (getLangOpts().CPlusPlus11) { 7047 DB << /*alias template*/2 << Proto->getReturnType(); 7048 } else { 7049 DB << /*might not be fixable*/3; 7050 } 7051 7052 // Recover by incorporating the other type chunks into the result type. 7053 // Note, this does *not* change the name of the function. This is compatible 7054 // with the GCC extension: 7055 // struct S { &operator int(); } s; 7056 // int &r = s.operator int(); // ok in GCC 7057 // S::operator int&() {} // error in GCC, function name is 'operator int'. 7058 ConvType = Proto->getReturnType(); 7059 } 7060 7061 // C++ [class.conv.fct]p4: 7062 // The conversion-type-id shall not represent a function type nor 7063 // an array type. 7064 if (ConvType->isArrayType()) { 7065 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7066 ConvType = Context.getPointerType(ConvType); 7067 D.setInvalidType(); 7068 } else if (ConvType->isFunctionType()) { 7069 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7070 ConvType = Context.getPointerType(ConvType); 7071 D.setInvalidType(); 7072 } 7073 7074 // Rebuild the function type "R" without any parameters (in case any 7075 // of the errors above fired) and with the conversion type as the 7076 // return type. 7077 if (D.isInvalidType()) 7078 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7079 7080 // C++0x explicit conversion operators. 7081 if (D.getDeclSpec().isExplicitSpecified()) 7082 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7083 getLangOpts().CPlusPlus11 ? 7084 diag::warn_cxx98_compat_explicit_conversion_functions : 7085 diag::ext_explicit_conversion_functions) 7086 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 7087 } 7088 7089 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 7090 /// the declaration of the given C++ conversion function. This routine 7091 /// is responsible for recording the conversion function in the C++ 7092 /// class, if possible. 7093 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 7094 assert(Conversion && "Expected to receive a conversion function declaration"); 7095 7096 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 7097 7098 // Make sure we aren't redeclaring the conversion function. 7099 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 7100 7101 // C++ [class.conv.fct]p1: 7102 // [...] A conversion function is never used to convert a 7103 // (possibly cv-qualified) object to the (possibly cv-qualified) 7104 // same object type (or a reference to it), to a (possibly 7105 // cv-qualified) base class of that type (or a reference to it), 7106 // or to (possibly cv-qualified) void. 7107 // FIXME: Suppress this warning if the conversion function ends up being a 7108 // virtual function that overrides a virtual function in a base class. 7109 QualType ClassType 7110 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7111 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 7112 ConvType = ConvTypeRef->getPointeeType(); 7113 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 7114 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 7115 /* Suppress diagnostics for instantiations. */; 7116 else if (ConvType->isRecordType()) { 7117 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 7118 if (ConvType == ClassType) 7119 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 7120 << ClassType; 7121 else if (IsDerivedFrom(ClassType, ConvType)) 7122 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 7123 << ClassType << ConvType; 7124 } else if (ConvType->isVoidType()) { 7125 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 7126 << ClassType << ConvType; 7127 } 7128 7129 if (FunctionTemplateDecl *ConversionTemplate 7130 = Conversion->getDescribedFunctionTemplate()) 7131 return ConversionTemplate; 7132 7133 return Conversion; 7134 } 7135 7136 //===----------------------------------------------------------------------===// 7137 // Namespace Handling 7138 //===----------------------------------------------------------------------===// 7139 7140 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 7141 /// reopened. 7142 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 7143 SourceLocation Loc, 7144 IdentifierInfo *II, bool *IsInline, 7145 NamespaceDecl *PrevNS) { 7146 assert(*IsInline != PrevNS->isInline()); 7147 7148 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 7149 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 7150 // inline namespaces, with the intention of bringing names into namespace std. 7151 // 7152 // We support this just well enough to get that case working; this is not 7153 // sufficient to support reopening namespaces as inline in general. 7154 if (*IsInline && II && II->getName().startswith("__atomic") && 7155 S.getSourceManager().isInSystemHeader(Loc)) { 7156 // Mark all prior declarations of the namespace as inline. 7157 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 7158 NS = NS->getPreviousDecl()) 7159 NS->setInline(*IsInline); 7160 // Patch up the lookup table for the containing namespace. This isn't really 7161 // correct, but it's good enough for this particular case. 7162 for (auto *I : PrevNS->decls()) 7163 if (auto *ND = dyn_cast<NamedDecl>(I)) 7164 PrevNS->getParent()->makeDeclVisibleInContext(ND); 7165 return; 7166 } 7167 7168 if (PrevNS->isInline()) 7169 // The user probably just forgot the 'inline', so suggest that it 7170 // be added back. 7171 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 7172 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 7173 else 7174 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 7175 7176 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 7177 *IsInline = PrevNS->isInline(); 7178 } 7179 7180 /// ActOnStartNamespaceDef - This is called at the start of a namespace 7181 /// definition. 7182 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 7183 SourceLocation InlineLoc, 7184 SourceLocation NamespaceLoc, 7185 SourceLocation IdentLoc, 7186 IdentifierInfo *II, 7187 SourceLocation LBrace, 7188 AttributeList *AttrList) { 7189 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 7190 // For anonymous namespace, take the location of the left brace. 7191 SourceLocation Loc = II ? IdentLoc : LBrace; 7192 bool IsInline = InlineLoc.isValid(); 7193 bool IsInvalid = false; 7194 bool IsStd = false; 7195 bool AddToKnown = false; 7196 Scope *DeclRegionScope = NamespcScope->getParent(); 7197 7198 NamespaceDecl *PrevNS = nullptr; 7199 if (II) { 7200 // C++ [namespace.def]p2: 7201 // The identifier in an original-namespace-definition shall not 7202 // have been previously defined in the declarative region in 7203 // which the original-namespace-definition appears. The 7204 // identifier in an original-namespace-definition is the name of 7205 // the namespace. Subsequently in that declarative region, it is 7206 // treated as an original-namespace-name. 7207 // 7208 // Since namespace names are unique in their scope, and we don't 7209 // look through using directives, just look for any ordinary names 7210 // as if by qualified name lookup. 7211 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration); 7212 LookupQualifiedName(R, CurContext->getRedeclContext()); 7213 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 7214 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7215 7216 if (PrevNS) { 7217 // This is an extended namespace definition. 7218 if (IsInline != PrevNS->isInline()) 7219 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7220 &IsInline, PrevNS); 7221 } else if (PrevDecl) { 7222 // This is an invalid name redefinition. 7223 Diag(Loc, diag::err_redefinition_different_kind) 7224 << II; 7225 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7226 IsInvalid = true; 7227 // Continue on to push Namespc as current DeclContext and return it. 7228 } else if (II->isStr("std") && 7229 CurContext->getRedeclContext()->isTranslationUnit()) { 7230 // This is the first "real" definition of the namespace "std", so update 7231 // our cache of the "std" namespace to point at this definition. 7232 PrevNS = getStdNamespace(); 7233 IsStd = true; 7234 AddToKnown = !IsInline; 7235 } else { 7236 // We've seen this namespace for the first time. 7237 AddToKnown = !IsInline; 7238 } 7239 } else { 7240 // Anonymous namespaces. 7241 7242 // Determine whether the parent already has an anonymous namespace. 7243 DeclContext *Parent = CurContext->getRedeclContext(); 7244 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7245 PrevNS = TU->getAnonymousNamespace(); 7246 } else { 7247 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7248 PrevNS = ND->getAnonymousNamespace(); 7249 } 7250 7251 if (PrevNS && IsInline != PrevNS->isInline()) 7252 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7253 &IsInline, PrevNS); 7254 } 7255 7256 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7257 StartLoc, Loc, II, PrevNS); 7258 if (IsInvalid) 7259 Namespc->setInvalidDecl(); 7260 7261 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7262 7263 // FIXME: Should we be merging attributes? 7264 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7265 PushNamespaceVisibilityAttr(Attr, Loc); 7266 7267 if (IsStd) 7268 StdNamespace = Namespc; 7269 if (AddToKnown) 7270 KnownNamespaces[Namespc] = false; 7271 7272 if (II) { 7273 PushOnScopeChains(Namespc, DeclRegionScope); 7274 } else { 7275 // Link the anonymous namespace into its parent. 7276 DeclContext *Parent = CurContext->getRedeclContext(); 7277 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7278 TU->setAnonymousNamespace(Namespc); 7279 } else { 7280 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7281 } 7282 7283 CurContext->addDecl(Namespc); 7284 7285 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7286 // behaves as if it were replaced by 7287 // namespace unique { /* empty body */ } 7288 // using namespace unique; 7289 // namespace unique { namespace-body } 7290 // where all occurrences of 'unique' in a translation unit are 7291 // replaced by the same identifier and this identifier differs 7292 // from all other identifiers in the entire program. 7293 7294 // We just create the namespace with an empty name and then add an 7295 // implicit using declaration, just like the standard suggests. 7296 // 7297 // CodeGen enforces the "universally unique" aspect by giving all 7298 // declarations semantically contained within an anonymous 7299 // namespace internal linkage. 7300 7301 if (!PrevNS) { 7302 UsingDirectiveDecl* UD 7303 = UsingDirectiveDecl::Create(Context, Parent, 7304 /* 'using' */ LBrace, 7305 /* 'namespace' */ SourceLocation(), 7306 /* qualifier */ NestedNameSpecifierLoc(), 7307 /* identifier */ SourceLocation(), 7308 Namespc, 7309 /* Ancestor */ Parent); 7310 UD->setImplicit(); 7311 Parent->addDecl(UD); 7312 } 7313 } 7314 7315 ActOnDocumentableDecl(Namespc); 7316 7317 // Although we could have an invalid decl (i.e. the namespace name is a 7318 // redefinition), push it as current DeclContext and try to continue parsing. 7319 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7320 // for the namespace has the declarations that showed up in that particular 7321 // namespace definition. 7322 PushDeclContext(NamespcScope, Namespc); 7323 return Namespc; 7324 } 7325 7326 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7327 /// is a namespace alias, returns the namespace it points to. 7328 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7329 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7330 return AD->getNamespace(); 7331 return dyn_cast_or_null<NamespaceDecl>(D); 7332 } 7333 7334 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7335 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7336 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7337 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7338 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7339 Namespc->setRBraceLoc(RBrace); 7340 PopDeclContext(); 7341 if (Namespc->hasAttr<VisibilityAttr>()) 7342 PopPragmaVisibility(true, RBrace); 7343 } 7344 7345 CXXRecordDecl *Sema::getStdBadAlloc() const { 7346 return cast_or_null<CXXRecordDecl>( 7347 StdBadAlloc.get(Context.getExternalSource())); 7348 } 7349 7350 NamespaceDecl *Sema::getStdNamespace() const { 7351 return cast_or_null<NamespaceDecl>( 7352 StdNamespace.get(Context.getExternalSource())); 7353 } 7354 7355 /// \brief Retrieve the special "std" namespace, which may require us to 7356 /// implicitly define the namespace. 7357 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7358 if (!StdNamespace) { 7359 // The "std" namespace has not yet been defined, so build one implicitly. 7360 StdNamespace = NamespaceDecl::Create(Context, 7361 Context.getTranslationUnitDecl(), 7362 /*Inline=*/false, 7363 SourceLocation(), SourceLocation(), 7364 &PP.getIdentifierTable().get("std"), 7365 /*PrevDecl=*/nullptr); 7366 getStdNamespace()->setImplicit(true); 7367 } 7368 7369 return getStdNamespace(); 7370 } 7371 7372 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7373 assert(getLangOpts().CPlusPlus && 7374 "Looking for std::initializer_list outside of C++."); 7375 7376 // We're looking for implicit instantiations of 7377 // template <typename E> class std::initializer_list. 7378 7379 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7380 return false; 7381 7382 ClassTemplateDecl *Template = nullptr; 7383 const TemplateArgument *Arguments = nullptr; 7384 7385 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7386 7387 ClassTemplateSpecializationDecl *Specialization = 7388 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7389 if (!Specialization) 7390 return false; 7391 7392 Template = Specialization->getSpecializedTemplate(); 7393 Arguments = Specialization->getTemplateArgs().data(); 7394 } else if (const TemplateSpecializationType *TST = 7395 Ty->getAs<TemplateSpecializationType>()) { 7396 Template = dyn_cast_or_null<ClassTemplateDecl>( 7397 TST->getTemplateName().getAsTemplateDecl()); 7398 Arguments = TST->getArgs(); 7399 } 7400 if (!Template) 7401 return false; 7402 7403 if (!StdInitializerList) { 7404 // Haven't recognized std::initializer_list yet, maybe this is it. 7405 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7406 if (TemplateClass->getIdentifier() != 7407 &PP.getIdentifierTable().get("initializer_list") || 7408 !getStdNamespace()->InEnclosingNamespaceSetOf( 7409 TemplateClass->getDeclContext())) 7410 return false; 7411 // This is a template called std::initializer_list, but is it the right 7412 // template? 7413 TemplateParameterList *Params = Template->getTemplateParameters(); 7414 if (Params->getMinRequiredArguments() != 1) 7415 return false; 7416 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7417 return false; 7418 7419 // It's the right template. 7420 StdInitializerList = Template; 7421 } 7422 7423 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 7424 return false; 7425 7426 // This is an instance of std::initializer_list. Find the argument type. 7427 if (Element) 7428 *Element = Arguments[0].getAsType(); 7429 return true; 7430 } 7431 7432 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7433 NamespaceDecl *Std = S.getStdNamespace(); 7434 if (!Std) { 7435 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7436 return nullptr; 7437 } 7438 7439 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7440 Loc, Sema::LookupOrdinaryName); 7441 if (!S.LookupQualifiedName(Result, Std)) { 7442 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7443 return nullptr; 7444 } 7445 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7446 if (!Template) { 7447 Result.suppressDiagnostics(); 7448 // We found something weird. Complain about the first thing we found. 7449 NamedDecl *Found = *Result.begin(); 7450 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7451 return nullptr; 7452 } 7453 7454 // We found some template called std::initializer_list. Now verify that it's 7455 // correct. 7456 TemplateParameterList *Params = Template->getTemplateParameters(); 7457 if (Params->getMinRequiredArguments() != 1 || 7458 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7459 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7460 return nullptr; 7461 } 7462 7463 return Template; 7464 } 7465 7466 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7467 if (!StdInitializerList) { 7468 StdInitializerList = LookupStdInitializerList(*this, Loc); 7469 if (!StdInitializerList) 7470 return QualType(); 7471 } 7472 7473 TemplateArgumentListInfo Args(Loc, Loc); 7474 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7475 Context.getTrivialTypeSourceInfo(Element, 7476 Loc))); 7477 return Context.getCanonicalType( 7478 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7479 } 7480 7481 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7482 // C++ [dcl.init.list]p2: 7483 // A constructor is an initializer-list constructor if its first parameter 7484 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7485 // std::initializer_list<E> for some type E, and either there are no other 7486 // parameters or else all other parameters have default arguments. 7487 if (Ctor->getNumParams() < 1 || 7488 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7489 return false; 7490 7491 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7492 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7493 ArgType = RT->getPointeeType().getUnqualifiedType(); 7494 7495 return isStdInitializerList(ArgType, nullptr); 7496 } 7497 7498 /// \brief Determine whether a using statement is in a context where it will be 7499 /// apply in all contexts. 7500 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7501 switch (CurContext->getDeclKind()) { 7502 case Decl::TranslationUnit: 7503 return true; 7504 case Decl::LinkageSpec: 7505 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7506 default: 7507 return false; 7508 } 7509 } 7510 7511 namespace { 7512 7513 // Callback to only accept typo corrections that are namespaces. 7514 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7515 public: 7516 bool ValidateCandidate(const TypoCorrection &candidate) override { 7517 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7518 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7519 return false; 7520 } 7521 }; 7522 7523 } 7524 7525 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7526 CXXScopeSpec &SS, 7527 SourceLocation IdentLoc, 7528 IdentifierInfo *Ident) { 7529 R.clear(); 7530 if (TypoCorrection Corrected = 7531 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7532 llvm::make_unique<NamespaceValidatorCCC>(), 7533 Sema::CTK_ErrorRecovery)) { 7534 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7535 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7536 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7537 Ident->getName().equals(CorrectedStr); 7538 S.diagnoseTypo(Corrected, 7539 S.PDiag(diag::err_using_directive_member_suggest) 7540 << Ident << DC << DroppedSpecifier << SS.getRange(), 7541 S.PDiag(diag::note_namespace_defined_here)); 7542 } else { 7543 S.diagnoseTypo(Corrected, 7544 S.PDiag(diag::err_using_directive_suggest) << Ident, 7545 S.PDiag(diag::note_namespace_defined_here)); 7546 } 7547 R.addDecl(Corrected.getCorrectionDecl()); 7548 return true; 7549 } 7550 return false; 7551 } 7552 7553 Decl *Sema::ActOnUsingDirective(Scope *S, 7554 SourceLocation UsingLoc, 7555 SourceLocation NamespcLoc, 7556 CXXScopeSpec &SS, 7557 SourceLocation IdentLoc, 7558 IdentifierInfo *NamespcName, 7559 AttributeList *AttrList) { 7560 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7561 assert(NamespcName && "Invalid NamespcName."); 7562 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7563 7564 // This can only happen along a recovery path. 7565 while (S->isTemplateParamScope()) 7566 S = S->getParent(); 7567 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7568 7569 UsingDirectiveDecl *UDir = nullptr; 7570 NestedNameSpecifier *Qualifier = nullptr; 7571 if (SS.isSet()) 7572 Qualifier = SS.getScopeRep(); 7573 7574 // Lookup namespace name. 7575 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7576 LookupParsedName(R, S, &SS); 7577 if (R.isAmbiguous()) 7578 return nullptr; 7579 7580 if (R.empty()) { 7581 R.clear(); 7582 // Allow "using namespace std;" or "using namespace ::std;" even if 7583 // "std" hasn't been defined yet, for GCC compatibility. 7584 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7585 NamespcName->isStr("std")) { 7586 Diag(IdentLoc, diag::ext_using_undefined_std); 7587 R.addDecl(getOrCreateStdNamespace()); 7588 R.resolveKind(); 7589 } 7590 // Otherwise, attempt typo correction. 7591 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7592 } 7593 7594 if (!R.empty()) { 7595 NamedDecl *Named = R.getFoundDecl(); 7596 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7597 && "expected namespace decl"); 7598 7599 // The use of a nested name specifier may trigger deprecation warnings. 7600 DiagnoseUseOfDecl(Named, IdentLoc); 7601 7602 // C++ [namespace.udir]p1: 7603 // A using-directive specifies that the names in the nominated 7604 // namespace can be used in the scope in which the 7605 // using-directive appears after the using-directive. During 7606 // unqualified name lookup (3.4.1), the names appear as if they 7607 // were declared in the nearest enclosing namespace which 7608 // contains both the using-directive and the nominated 7609 // namespace. [Note: in this context, "contains" means "contains 7610 // directly or indirectly". ] 7611 7612 // Find enclosing context containing both using-directive and 7613 // nominated namespace. 7614 NamespaceDecl *NS = getNamespaceDecl(Named); 7615 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7616 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7617 CommonAncestor = CommonAncestor->getParent(); 7618 7619 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7620 SS.getWithLocInContext(Context), 7621 IdentLoc, Named, CommonAncestor); 7622 7623 if (IsUsingDirectiveInToplevelContext(CurContext) && 7624 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7625 Diag(IdentLoc, diag::warn_using_directive_in_header); 7626 } 7627 7628 PushUsingDirective(S, UDir); 7629 } else { 7630 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7631 } 7632 7633 if (UDir) 7634 ProcessDeclAttributeList(S, UDir, AttrList); 7635 7636 return UDir; 7637 } 7638 7639 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7640 // If the scope has an associated entity and the using directive is at 7641 // namespace or translation unit scope, add the UsingDirectiveDecl into 7642 // its lookup structure so qualified name lookup can find it. 7643 DeclContext *Ctx = S->getEntity(); 7644 if (Ctx && !Ctx->isFunctionOrMethod()) 7645 Ctx->addDecl(UDir); 7646 else 7647 // Otherwise, it is at block scope. The using-directives will affect lookup 7648 // only to the end of the scope. 7649 S->PushUsingDirective(UDir); 7650 } 7651 7652 7653 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7654 AccessSpecifier AS, 7655 bool HasUsingKeyword, 7656 SourceLocation UsingLoc, 7657 CXXScopeSpec &SS, 7658 UnqualifiedId &Name, 7659 AttributeList *AttrList, 7660 bool HasTypenameKeyword, 7661 SourceLocation TypenameLoc) { 7662 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7663 7664 switch (Name.getKind()) { 7665 case UnqualifiedId::IK_ImplicitSelfParam: 7666 case UnqualifiedId::IK_Identifier: 7667 case UnqualifiedId::IK_OperatorFunctionId: 7668 case UnqualifiedId::IK_LiteralOperatorId: 7669 case UnqualifiedId::IK_ConversionFunctionId: 7670 break; 7671 7672 case UnqualifiedId::IK_ConstructorName: 7673 case UnqualifiedId::IK_ConstructorTemplateId: 7674 // C++11 inheriting constructors. 7675 Diag(Name.getLocStart(), 7676 getLangOpts().CPlusPlus11 ? 7677 diag::warn_cxx98_compat_using_decl_constructor : 7678 diag::err_using_decl_constructor) 7679 << SS.getRange(); 7680 7681 if (getLangOpts().CPlusPlus11) break; 7682 7683 return nullptr; 7684 7685 case UnqualifiedId::IK_DestructorName: 7686 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7687 << SS.getRange(); 7688 return nullptr; 7689 7690 case UnqualifiedId::IK_TemplateId: 7691 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7692 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7693 return nullptr; 7694 } 7695 7696 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7697 DeclarationName TargetName = TargetNameInfo.getName(); 7698 if (!TargetName) 7699 return nullptr; 7700 7701 // Warn about access declarations. 7702 if (!HasUsingKeyword) { 7703 Diag(Name.getLocStart(), 7704 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7705 : diag::warn_access_decl_deprecated) 7706 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7707 } 7708 7709 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7710 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7711 return nullptr; 7712 7713 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7714 TargetNameInfo, AttrList, 7715 /* IsInstantiation */ false, 7716 HasTypenameKeyword, TypenameLoc); 7717 if (UD) 7718 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7719 7720 return UD; 7721 } 7722 7723 /// \brief Determine whether a using declaration considers the given 7724 /// declarations as "equivalent", e.g., if they are redeclarations of 7725 /// the same entity or are both typedefs of the same type. 7726 static bool 7727 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7728 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7729 return true; 7730 7731 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7732 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7733 return Context.hasSameType(TD1->getUnderlyingType(), 7734 TD2->getUnderlyingType()); 7735 7736 return false; 7737 } 7738 7739 7740 /// Determines whether to create a using shadow decl for a particular 7741 /// decl, given the set of decls existing prior to this using lookup. 7742 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7743 const LookupResult &Previous, 7744 UsingShadowDecl *&PrevShadow) { 7745 // Diagnose finding a decl which is not from a base class of the 7746 // current class. We do this now because there are cases where this 7747 // function will silently decide not to build a shadow decl, which 7748 // will pre-empt further diagnostics. 7749 // 7750 // We don't need to do this in C++0x because we do the check once on 7751 // the qualifier. 7752 // 7753 // FIXME: diagnose the following if we care enough: 7754 // struct A { int foo; }; 7755 // struct B : A { using A::foo; }; 7756 // template <class T> struct C : A {}; 7757 // template <class T> struct D : C<T> { using B::foo; } // <--- 7758 // This is invalid (during instantiation) in C++03 because B::foo 7759 // resolves to the using decl in B, which is not a base class of D<T>. 7760 // We can't diagnose it immediately because C<T> is an unknown 7761 // specialization. The UsingShadowDecl in D<T> then points directly 7762 // to A::foo, which will look well-formed when we instantiate. 7763 // The right solution is to not collapse the shadow-decl chain. 7764 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7765 DeclContext *OrigDC = Orig->getDeclContext(); 7766 7767 // Handle enums and anonymous structs. 7768 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7769 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7770 while (OrigRec->isAnonymousStructOrUnion()) 7771 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7772 7773 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7774 if (OrigDC == CurContext) { 7775 Diag(Using->getLocation(), 7776 diag::err_using_decl_nested_name_specifier_is_current_class) 7777 << Using->getQualifierLoc().getSourceRange(); 7778 Diag(Orig->getLocation(), diag::note_using_decl_target); 7779 return true; 7780 } 7781 7782 Diag(Using->getQualifierLoc().getBeginLoc(), 7783 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7784 << Using->getQualifier() 7785 << cast<CXXRecordDecl>(CurContext) 7786 << Using->getQualifierLoc().getSourceRange(); 7787 Diag(Orig->getLocation(), diag::note_using_decl_target); 7788 return true; 7789 } 7790 } 7791 7792 if (Previous.empty()) return false; 7793 7794 NamedDecl *Target = Orig; 7795 if (isa<UsingShadowDecl>(Target)) 7796 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7797 7798 // If the target happens to be one of the previous declarations, we 7799 // don't have a conflict. 7800 // 7801 // FIXME: but we might be increasing its access, in which case we 7802 // should redeclare it. 7803 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7804 bool FoundEquivalentDecl = false; 7805 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7806 I != E; ++I) { 7807 NamedDecl *D = (*I)->getUnderlyingDecl(); 7808 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7809 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7810 PrevShadow = Shadow; 7811 FoundEquivalentDecl = true; 7812 } 7813 7814 if (isVisible(D)) 7815 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7816 } 7817 7818 if (FoundEquivalentDecl) 7819 return false; 7820 7821 if (FunctionDecl *FD = Target->getAsFunction()) { 7822 NamedDecl *OldDecl = nullptr; 7823 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7824 /*IsForUsingDecl*/ true)) { 7825 case Ovl_Overload: 7826 return false; 7827 7828 case Ovl_NonFunction: 7829 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7830 break; 7831 7832 // We found a decl with the exact signature. 7833 case Ovl_Match: 7834 // If we're in a record, we want to hide the target, so we 7835 // return true (without a diagnostic) to tell the caller not to 7836 // build a shadow decl. 7837 if (CurContext->isRecord()) 7838 return true; 7839 7840 // If we're not in a record, this is an error. 7841 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7842 break; 7843 } 7844 7845 Diag(Target->getLocation(), diag::note_using_decl_target); 7846 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7847 return true; 7848 } 7849 7850 // Target is not a function. 7851 7852 if (isa<TagDecl>(Target)) { 7853 // No conflict between a tag and a non-tag. 7854 if (!Tag) return false; 7855 7856 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7857 Diag(Target->getLocation(), diag::note_using_decl_target); 7858 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7859 return true; 7860 } 7861 7862 // No conflict between a tag and a non-tag. 7863 if (!NonTag) return false; 7864 7865 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7866 Diag(Target->getLocation(), diag::note_using_decl_target); 7867 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7868 return true; 7869 } 7870 7871 /// Builds a shadow declaration corresponding to a 'using' declaration. 7872 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7873 UsingDecl *UD, 7874 NamedDecl *Orig, 7875 UsingShadowDecl *PrevDecl) { 7876 7877 // If we resolved to another shadow declaration, just coalesce them. 7878 NamedDecl *Target = Orig; 7879 if (isa<UsingShadowDecl>(Target)) { 7880 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7881 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7882 } 7883 7884 UsingShadowDecl *Shadow 7885 = UsingShadowDecl::Create(Context, CurContext, 7886 UD->getLocation(), UD, Target); 7887 UD->addShadowDecl(Shadow); 7888 7889 Shadow->setAccess(UD->getAccess()); 7890 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7891 Shadow->setInvalidDecl(); 7892 7893 Shadow->setPreviousDecl(PrevDecl); 7894 7895 if (S) 7896 PushOnScopeChains(Shadow, S); 7897 else 7898 CurContext->addDecl(Shadow); 7899 7900 7901 return Shadow; 7902 } 7903 7904 /// Hides a using shadow declaration. This is required by the current 7905 /// using-decl implementation when a resolvable using declaration in a 7906 /// class is followed by a declaration which would hide or override 7907 /// one or more of the using decl's targets; for example: 7908 /// 7909 /// struct Base { void foo(int); }; 7910 /// struct Derived : Base { 7911 /// using Base::foo; 7912 /// void foo(int); 7913 /// }; 7914 /// 7915 /// The governing language is C++03 [namespace.udecl]p12: 7916 /// 7917 /// When a using-declaration brings names from a base class into a 7918 /// derived class scope, member functions in the derived class 7919 /// override and/or hide member functions with the same name and 7920 /// parameter types in a base class (rather than conflicting). 7921 /// 7922 /// There are two ways to implement this: 7923 /// (1) optimistically create shadow decls when they're not hidden 7924 /// by existing declarations, or 7925 /// (2) don't create any shadow decls (or at least don't make them 7926 /// visible) until we've fully parsed/instantiated the class. 7927 /// The problem with (1) is that we might have to retroactively remove 7928 /// a shadow decl, which requires several O(n) operations because the 7929 /// decl structures are (very reasonably) not designed for removal. 7930 /// (2) avoids this but is very fiddly and phase-dependent. 7931 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7932 if (Shadow->getDeclName().getNameKind() == 7933 DeclarationName::CXXConversionFunctionName) 7934 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7935 7936 // Remove it from the DeclContext... 7937 Shadow->getDeclContext()->removeDecl(Shadow); 7938 7939 // ...and the scope, if applicable... 7940 if (S) { 7941 S->RemoveDecl(Shadow); 7942 IdResolver.RemoveDecl(Shadow); 7943 } 7944 7945 // ...and the using decl. 7946 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7947 7948 // TODO: complain somehow if Shadow was used. It shouldn't 7949 // be possible for this to happen, because...? 7950 } 7951 7952 /// Find the base specifier for a base class with the given type. 7953 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7954 QualType DesiredBase, 7955 bool &AnyDependentBases) { 7956 // Check whether the named type is a direct base class. 7957 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7958 for (auto &Base : Derived->bases()) { 7959 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7960 if (CanonicalDesiredBase == BaseType) 7961 return &Base; 7962 if (BaseType->isDependentType()) 7963 AnyDependentBases = true; 7964 } 7965 return nullptr; 7966 } 7967 7968 namespace { 7969 class UsingValidatorCCC : public CorrectionCandidateCallback { 7970 public: 7971 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7972 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7973 : HasTypenameKeyword(HasTypenameKeyword), 7974 IsInstantiation(IsInstantiation), OldNNS(NNS), 7975 RequireMemberOf(RequireMemberOf) {} 7976 7977 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7978 NamedDecl *ND = Candidate.getCorrectionDecl(); 7979 7980 // Keywords are not valid here. 7981 if (!ND || isa<NamespaceDecl>(ND)) 7982 return false; 7983 7984 // Completely unqualified names are invalid for a 'using' declaration. 7985 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7986 return false; 7987 7988 if (RequireMemberOf) { 7989 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7990 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7991 // No-one ever wants a using-declaration to name an injected-class-name 7992 // of a base class, unless they're declaring an inheriting constructor. 7993 ASTContext &Ctx = ND->getASTContext(); 7994 if (!Ctx.getLangOpts().CPlusPlus11) 7995 return false; 7996 QualType FoundType = Ctx.getRecordType(FoundRecord); 7997 7998 // Check that the injected-class-name is named as a member of its own 7999 // type; we don't want to suggest 'using Derived::Base;', since that 8000 // means something else. 8001 NestedNameSpecifier *Specifier = 8002 Candidate.WillReplaceSpecifier() 8003 ? Candidate.getCorrectionSpecifier() 8004 : OldNNS; 8005 if (!Specifier->getAsType() || 8006 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 8007 return false; 8008 8009 // Check that this inheriting constructor declaration actually names a 8010 // direct base class of the current class. 8011 bool AnyDependentBases = false; 8012 if (!findDirectBaseWithType(RequireMemberOf, 8013 Ctx.getRecordType(FoundRecord), 8014 AnyDependentBases) && 8015 !AnyDependentBases) 8016 return false; 8017 } else { 8018 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 8019 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 8020 return false; 8021 8022 // FIXME: Check that the base class member is accessible? 8023 } 8024 } else { 8025 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8026 if (FoundRecord && FoundRecord->isInjectedClassName()) 8027 return false; 8028 } 8029 8030 if (isa<TypeDecl>(ND)) 8031 return HasTypenameKeyword || !IsInstantiation; 8032 8033 return !HasTypenameKeyword; 8034 } 8035 8036 private: 8037 bool HasTypenameKeyword; 8038 bool IsInstantiation; 8039 NestedNameSpecifier *OldNNS; 8040 CXXRecordDecl *RequireMemberOf; 8041 }; 8042 } // end anonymous namespace 8043 8044 /// Builds a using declaration. 8045 /// 8046 /// \param IsInstantiation - Whether this call arises from an 8047 /// instantiation of an unresolved using declaration. We treat 8048 /// the lookup differently for these declarations. 8049 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 8050 SourceLocation UsingLoc, 8051 CXXScopeSpec &SS, 8052 DeclarationNameInfo NameInfo, 8053 AttributeList *AttrList, 8054 bool IsInstantiation, 8055 bool HasTypenameKeyword, 8056 SourceLocation TypenameLoc) { 8057 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8058 SourceLocation IdentLoc = NameInfo.getLoc(); 8059 assert(IdentLoc.isValid() && "Invalid TargetName location."); 8060 8061 // FIXME: We ignore attributes for now. 8062 8063 if (SS.isEmpty()) { 8064 Diag(IdentLoc, diag::err_using_requires_qualname); 8065 return nullptr; 8066 } 8067 8068 // Do the redeclaration lookup in the current scope. 8069 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 8070 ForRedeclaration); 8071 Previous.setHideTags(false); 8072 if (S) { 8073 LookupName(Previous, S); 8074 8075 // It is really dumb that we have to do this. 8076 LookupResult::Filter F = Previous.makeFilter(); 8077 while (F.hasNext()) { 8078 NamedDecl *D = F.next(); 8079 if (!isDeclInScope(D, CurContext, S)) 8080 F.erase(); 8081 // If we found a local extern declaration that's not ordinarily visible, 8082 // and this declaration is being added to a non-block scope, ignore it. 8083 // We're only checking for scope conflicts here, not also for violations 8084 // of the linkage rules. 8085 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 8086 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 8087 F.erase(); 8088 } 8089 F.done(); 8090 } else { 8091 assert(IsInstantiation && "no scope in non-instantiation"); 8092 assert(CurContext->isRecord() && "scope not record in instantiation"); 8093 LookupQualifiedName(Previous, CurContext); 8094 } 8095 8096 // Check for invalid redeclarations. 8097 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 8098 SS, IdentLoc, Previous)) 8099 return nullptr; 8100 8101 // Check for bad qualifiers. 8102 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 8103 return nullptr; 8104 8105 DeclContext *LookupContext = computeDeclContext(SS); 8106 NamedDecl *D; 8107 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 8108 if (!LookupContext) { 8109 if (HasTypenameKeyword) { 8110 // FIXME: not all declaration name kinds are legal here 8111 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 8112 UsingLoc, TypenameLoc, 8113 QualifierLoc, 8114 IdentLoc, NameInfo.getName()); 8115 } else { 8116 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 8117 QualifierLoc, NameInfo); 8118 } 8119 D->setAccess(AS); 8120 CurContext->addDecl(D); 8121 return D; 8122 } 8123 8124 auto Build = [&](bool Invalid) { 8125 UsingDecl *UD = 8126 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 8127 HasTypenameKeyword); 8128 UD->setAccess(AS); 8129 CurContext->addDecl(UD); 8130 UD->setInvalidDecl(Invalid); 8131 return UD; 8132 }; 8133 auto BuildInvalid = [&]{ return Build(true); }; 8134 auto BuildValid = [&]{ return Build(false); }; 8135 8136 if (RequireCompleteDeclContext(SS, LookupContext)) 8137 return BuildInvalid(); 8138 8139 // Look up the target name. 8140 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8141 8142 // Unlike most lookups, we don't always want to hide tag 8143 // declarations: tag names are visible through the using declaration 8144 // even if hidden by ordinary names, *except* in a dependent context 8145 // where it's important for the sanity of two-phase lookup. 8146 if (!IsInstantiation) 8147 R.setHideTags(false); 8148 8149 // For the purposes of this lookup, we have a base object type 8150 // equal to that of the current context. 8151 if (CurContext->isRecord()) { 8152 R.setBaseObjectType( 8153 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 8154 } 8155 8156 LookupQualifiedName(R, LookupContext); 8157 8158 // Try to correct typos if possible. If constructor name lookup finds no 8159 // results, that means the named class has no explicit constructors, and we 8160 // suppressed declaring implicit ones (probably because it's dependent or 8161 // invalid). 8162 if (R.empty() && 8163 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 8164 if (TypoCorrection Corrected = CorrectTypo( 8165 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 8166 llvm::make_unique<UsingValidatorCCC>( 8167 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8168 dyn_cast<CXXRecordDecl>(CurContext)), 8169 CTK_ErrorRecovery)) { 8170 // We reject any correction for which ND would be NULL. 8171 NamedDecl *ND = Corrected.getCorrectionDecl(); 8172 8173 // We reject candidates where DroppedSpecifier == true, hence the 8174 // literal '0' below. 8175 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8176 << NameInfo.getName() << LookupContext << 0 8177 << SS.getRange()); 8178 8179 // If we corrected to an inheriting constructor, handle it as one. 8180 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8181 if (RD && RD->isInjectedClassName()) { 8182 // Fix up the information we'll use to build the using declaration. 8183 if (Corrected.WillReplaceSpecifier()) { 8184 NestedNameSpecifierLocBuilder Builder; 8185 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8186 QualifierLoc.getSourceRange()); 8187 QualifierLoc = Builder.getWithLocInContext(Context); 8188 } 8189 8190 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8191 Context.getCanonicalType(Context.getRecordType(RD)))); 8192 NameInfo.setNamedTypeInfo(nullptr); 8193 for (auto *Ctor : LookupConstructors(RD)) 8194 R.addDecl(Ctor); 8195 } else { 8196 // FIXME: Pick up all the declarations if we found an overloaded function. 8197 R.addDecl(ND); 8198 } 8199 } else { 8200 Diag(IdentLoc, diag::err_no_member) 8201 << NameInfo.getName() << LookupContext << SS.getRange(); 8202 return BuildInvalid(); 8203 } 8204 } 8205 8206 if (R.isAmbiguous()) 8207 return BuildInvalid(); 8208 8209 if (HasTypenameKeyword) { 8210 // If we asked for a typename and got a non-type decl, error out. 8211 if (!R.getAsSingle<TypeDecl>()) { 8212 Diag(IdentLoc, diag::err_using_typename_non_type); 8213 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8214 Diag((*I)->getUnderlyingDecl()->getLocation(), 8215 diag::note_using_decl_target); 8216 return BuildInvalid(); 8217 } 8218 } else { 8219 // If we asked for a non-typename and we got a type, error out, 8220 // but only if this is an instantiation of an unresolved using 8221 // decl. Otherwise just silently find the type name. 8222 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8223 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8224 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8225 return BuildInvalid(); 8226 } 8227 } 8228 8229 // C++0x N2914 [namespace.udecl]p6: 8230 // A using-declaration shall not name a namespace. 8231 if (R.getAsSingle<NamespaceDecl>()) { 8232 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8233 << SS.getRange(); 8234 return BuildInvalid(); 8235 } 8236 8237 UsingDecl *UD = BuildValid(); 8238 8239 // The normal rules do not apply to inheriting constructor declarations. 8240 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 8241 // Suppress access diagnostics; the access check is instead performed at the 8242 // point of use for an inheriting constructor. 8243 R.suppressDiagnostics(); 8244 CheckInheritingConstructorUsingDecl(UD); 8245 return UD; 8246 } 8247 8248 // Otherwise, look up the target name. 8249 8250 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8251 UsingShadowDecl *PrevDecl = nullptr; 8252 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8253 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8254 } 8255 8256 return UD; 8257 } 8258 8259 /// Additional checks for a using declaration referring to a constructor name. 8260 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8261 assert(!UD->hasTypename() && "expecting a constructor name"); 8262 8263 const Type *SourceType = UD->getQualifier()->getAsType(); 8264 assert(SourceType && 8265 "Using decl naming constructor doesn't have type in scope spec."); 8266 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8267 8268 // Check whether the named type is a direct base class. 8269 bool AnyDependentBases = false; 8270 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8271 AnyDependentBases); 8272 if (!Base && !AnyDependentBases) { 8273 Diag(UD->getUsingLoc(), 8274 diag::err_using_decl_constructor_not_in_direct_base) 8275 << UD->getNameInfo().getSourceRange() 8276 << QualType(SourceType, 0) << TargetClass; 8277 UD->setInvalidDecl(); 8278 return true; 8279 } 8280 8281 if (Base) 8282 Base->setInheritConstructors(); 8283 8284 return false; 8285 } 8286 8287 /// Checks that the given using declaration is not an invalid 8288 /// redeclaration. Note that this is checking only for the using decl 8289 /// itself, not for any ill-formedness among the UsingShadowDecls. 8290 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8291 bool HasTypenameKeyword, 8292 const CXXScopeSpec &SS, 8293 SourceLocation NameLoc, 8294 const LookupResult &Prev) { 8295 // C++03 [namespace.udecl]p8: 8296 // C++0x [namespace.udecl]p10: 8297 // A using-declaration is a declaration and can therefore be used 8298 // repeatedly where (and only where) multiple declarations are 8299 // allowed. 8300 // 8301 // That's in non-member contexts. 8302 if (!CurContext->getRedeclContext()->isRecord()) 8303 return false; 8304 8305 NestedNameSpecifier *Qual = SS.getScopeRep(); 8306 8307 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8308 NamedDecl *D = *I; 8309 8310 bool DTypename; 8311 NestedNameSpecifier *DQual; 8312 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8313 DTypename = UD->hasTypename(); 8314 DQual = UD->getQualifier(); 8315 } else if (UnresolvedUsingValueDecl *UD 8316 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8317 DTypename = false; 8318 DQual = UD->getQualifier(); 8319 } else if (UnresolvedUsingTypenameDecl *UD 8320 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8321 DTypename = true; 8322 DQual = UD->getQualifier(); 8323 } else continue; 8324 8325 // using decls differ if one says 'typename' and the other doesn't. 8326 // FIXME: non-dependent using decls? 8327 if (HasTypenameKeyword != DTypename) continue; 8328 8329 // using decls differ if they name different scopes (but note that 8330 // template instantiation can cause this check to trigger when it 8331 // didn't before instantiation). 8332 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8333 Context.getCanonicalNestedNameSpecifier(DQual)) 8334 continue; 8335 8336 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8337 Diag(D->getLocation(), diag::note_using_decl) << 1; 8338 return true; 8339 } 8340 8341 return false; 8342 } 8343 8344 8345 /// Checks that the given nested-name qualifier used in a using decl 8346 /// in the current context is appropriately related to the current 8347 /// scope. If an error is found, diagnoses it and returns true. 8348 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8349 const CXXScopeSpec &SS, 8350 const DeclarationNameInfo &NameInfo, 8351 SourceLocation NameLoc) { 8352 DeclContext *NamedContext = computeDeclContext(SS); 8353 8354 if (!CurContext->isRecord()) { 8355 // C++03 [namespace.udecl]p3: 8356 // C++0x [namespace.udecl]p8: 8357 // A using-declaration for a class member shall be a member-declaration. 8358 8359 // If we weren't able to compute a valid scope, it must be a 8360 // dependent class scope. 8361 if (!NamedContext || NamedContext->isRecord()) { 8362 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext); 8363 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8364 RD = nullptr; 8365 8366 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8367 << SS.getRange(); 8368 8369 // If we have a complete, non-dependent source type, try to suggest a 8370 // way to get the same effect. 8371 if (!RD) 8372 return true; 8373 8374 // Find what this using-declaration was referring to. 8375 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8376 R.setHideTags(false); 8377 R.suppressDiagnostics(); 8378 LookupQualifiedName(R, RD); 8379 8380 if (R.getAsSingle<TypeDecl>()) { 8381 if (getLangOpts().CPlusPlus11) { 8382 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8383 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8384 << 0 // alias declaration 8385 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8386 NameInfo.getName().getAsString() + 8387 " = "); 8388 } else { 8389 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8390 SourceLocation InsertLoc = 8391 getLocForEndOfToken(NameInfo.getLocEnd()); 8392 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8393 << 1 // typedef declaration 8394 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8395 << FixItHint::CreateInsertion( 8396 InsertLoc, " " + NameInfo.getName().getAsString()); 8397 } 8398 } else if (R.getAsSingle<VarDecl>()) { 8399 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8400 // repeating the type of the static data member here. 8401 FixItHint FixIt; 8402 if (getLangOpts().CPlusPlus11) { 8403 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8404 FixIt = FixItHint::CreateReplacement( 8405 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8406 } 8407 8408 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8409 << 2 // reference declaration 8410 << FixIt; 8411 } 8412 return true; 8413 } 8414 8415 // Otherwise, everything is known to be fine. 8416 return false; 8417 } 8418 8419 // The current scope is a record. 8420 8421 // If the named context is dependent, we can't decide much. 8422 if (!NamedContext) { 8423 // FIXME: in C++0x, we can diagnose if we can prove that the 8424 // nested-name-specifier does not refer to a base class, which is 8425 // still possible in some cases. 8426 8427 // Otherwise we have to conservatively report that things might be 8428 // okay. 8429 return false; 8430 } 8431 8432 if (!NamedContext->isRecord()) { 8433 // Ideally this would point at the last name in the specifier, 8434 // but we don't have that level of source info. 8435 Diag(SS.getRange().getBegin(), 8436 diag::err_using_decl_nested_name_specifier_is_not_class) 8437 << SS.getScopeRep() << SS.getRange(); 8438 return true; 8439 } 8440 8441 if (!NamedContext->isDependentContext() && 8442 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8443 return true; 8444 8445 if (getLangOpts().CPlusPlus11) { 8446 // C++0x [namespace.udecl]p3: 8447 // In a using-declaration used as a member-declaration, the 8448 // nested-name-specifier shall name a base class of the class 8449 // being defined. 8450 8451 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8452 cast<CXXRecordDecl>(NamedContext))) { 8453 if (CurContext == NamedContext) { 8454 Diag(NameLoc, 8455 diag::err_using_decl_nested_name_specifier_is_current_class) 8456 << SS.getRange(); 8457 return true; 8458 } 8459 8460 Diag(SS.getRange().getBegin(), 8461 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8462 << SS.getScopeRep() 8463 << cast<CXXRecordDecl>(CurContext) 8464 << SS.getRange(); 8465 return true; 8466 } 8467 8468 return false; 8469 } 8470 8471 // C++03 [namespace.udecl]p4: 8472 // A using-declaration used as a member-declaration shall refer 8473 // to a member of a base class of the class being defined [etc.]. 8474 8475 // Salient point: SS doesn't have to name a base class as long as 8476 // lookup only finds members from base classes. Therefore we can 8477 // diagnose here only if we can prove that that can't happen, 8478 // i.e. if the class hierarchies provably don't intersect. 8479 8480 // TODO: it would be nice if "definitely valid" results were cached 8481 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8482 // need to be repeated. 8483 8484 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 8485 auto Collect = [&Bases](const CXXRecordDecl *Base) { 8486 Bases.insert(Base); 8487 return true; 8488 }; 8489 8490 // Collect all bases. Return false if we find a dependent base. 8491 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 8492 return false; 8493 8494 // Returns true if the base is dependent or is one of the accumulated base 8495 // classes. 8496 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 8497 return !Bases.count(Base); 8498 }; 8499 8500 // Return false if the class has a dependent base or if it or one 8501 // of its bases is present in the base set of the current context. 8502 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 8503 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 8504 return false; 8505 8506 Diag(SS.getRange().getBegin(), 8507 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8508 << SS.getScopeRep() 8509 << cast<CXXRecordDecl>(CurContext) 8510 << SS.getRange(); 8511 8512 return true; 8513 } 8514 8515 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8516 AccessSpecifier AS, 8517 MultiTemplateParamsArg TemplateParamLists, 8518 SourceLocation UsingLoc, 8519 UnqualifiedId &Name, 8520 AttributeList *AttrList, 8521 TypeResult Type, 8522 Decl *DeclFromDeclSpec) { 8523 // Skip up to the relevant declaration scope. 8524 while (S->isTemplateParamScope()) 8525 S = S->getParent(); 8526 assert((S->getFlags() & Scope::DeclScope) && 8527 "got alias-declaration outside of declaration scope"); 8528 8529 if (Type.isInvalid()) 8530 return nullptr; 8531 8532 bool Invalid = false; 8533 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8534 TypeSourceInfo *TInfo = nullptr; 8535 GetTypeFromParser(Type.get(), &TInfo); 8536 8537 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8538 return nullptr; 8539 8540 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8541 UPPC_DeclarationType)) { 8542 Invalid = true; 8543 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8544 TInfo->getTypeLoc().getBeginLoc()); 8545 } 8546 8547 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8548 LookupName(Previous, S); 8549 8550 // Warn about shadowing the name of a template parameter. 8551 if (Previous.isSingleResult() && 8552 Previous.getFoundDecl()->isTemplateParameter()) { 8553 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8554 Previous.clear(); 8555 } 8556 8557 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8558 "name in alias declaration must be an identifier"); 8559 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8560 Name.StartLocation, 8561 Name.Identifier, TInfo); 8562 8563 NewTD->setAccess(AS); 8564 8565 if (Invalid) 8566 NewTD->setInvalidDecl(); 8567 8568 ProcessDeclAttributeList(S, NewTD, AttrList); 8569 8570 CheckTypedefForVariablyModifiedType(S, NewTD); 8571 Invalid |= NewTD->isInvalidDecl(); 8572 8573 bool Redeclaration = false; 8574 8575 NamedDecl *NewND; 8576 if (TemplateParamLists.size()) { 8577 TypeAliasTemplateDecl *OldDecl = nullptr; 8578 TemplateParameterList *OldTemplateParams = nullptr; 8579 8580 if (TemplateParamLists.size() != 1) { 8581 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8582 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8583 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8584 } 8585 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8586 8587 // Only consider previous declarations in the same scope. 8588 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8589 /*ExplicitInstantiationOrSpecialization*/false); 8590 if (!Previous.empty()) { 8591 Redeclaration = true; 8592 8593 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8594 if (!OldDecl && !Invalid) { 8595 Diag(UsingLoc, diag::err_redefinition_different_kind) 8596 << Name.Identifier; 8597 8598 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8599 if (OldD->getLocation().isValid()) 8600 Diag(OldD->getLocation(), diag::note_previous_definition); 8601 8602 Invalid = true; 8603 } 8604 8605 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8606 if (TemplateParameterListsAreEqual(TemplateParams, 8607 OldDecl->getTemplateParameters(), 8608 /*Complain=*/true, 8609 TPL_TemplateMatch)) 8610 OldTemplateParams = OldDecl->getTemplateParameters(); 8611 else 8612 Invalid = true; 8613 8614 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8615 if (!Invalid && 8616 !Context.hasSameType(OldTD->getUnderlyingType(), 8617 NewTD->getUnderlyingType())) { 8618 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8619 // but we can't reasonably accept it. 8620 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8621 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8622 if (OldTD->getLocation().isValid()) 8623 Diag(OldTD->getLocation(), diag::note_previous_definition); 8624 Invalid = true; 8625 } 8626 } 8627 } 8628 8629 // Merge any previous default template arguments into our parameters, 8630 // and check the parameter list. 8631 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8632 TPC_TypeAliasTemplate)) 8633 return nullptr; 8634 8635 TypeAliasTemplateDecl *NewDecl = 8636 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8637 Name.Identifier, TemplateParams, 8638 NewTD); 8639 NewTD->setDescribedAliasTemplate(NewDecl); 8640 8641 NewDecl->setAccess(AS); 8642 8643 if (Invalid) 8644 NewDecl->setInvalidDecl(); 8645 else if (OldDecl) 8646 NewDecl->setPreviousDecl(OldDecl); 8647 8648 NewND = NewDecl; 8649 } else { 8650 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 8651 setTagNameForLinkagePurposes(TD, NewTD); 8652 handleTagNumbering(TD, S); 8653 } 8654 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8655 NewND = NewTD; 8656 } 8657 8658 if (!Redeclaration) 8659 PushOnScopeChains(NewND, S); 8660 8661 ActOnDocumentableDecl(NewND); 8662 return NewND; 8663 } 8664 8665 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8666 SourceLocation AliasLoc, 8667 IdentifierInfo *Alias, CXXScopeSpec &SS, 8668 SourceLocation IdentLoc, 8669 IdentifierInfo *Ident) { 8670 8671 // Lookup the namespace name. 8672 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8673 LookupParsedName(R, S, &SS); 8674 8675 if (R.isAmbiguous()) 8676 return nullptr; 8677 8678 if (R.empty()) { 8679 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8680 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8681 return nullptr; 8682 } 8683 } 8684 assert(!R.isAmbiguous() && !R.empty()); 8685 NamedDecl *ND = R.getFoundDecl(); 8686 8687 // Check if we have a previous declaration with the same name. 8688 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 8689 ForRedeclaration); 8690 LookupName(PrevR, S); 8691 8692 // Check we're not shadowing a template parameter. 8693 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 8694 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 8695 PrevR.clear(); 8696 } 8697 8698 // Filter out any other lookup result from an enclosing scope. 8699 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 8700 /*AllowInlineNamespace*/false); 8701 8702 // Find the previous declaration and check that we can redeclare it. 8703 NamespaceAliasDecl *Prev = nullptr; 8704 if (NamedDecl *PrevDecl = PrevR.getAsSingle<NamedDecl>()) { 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 Prev = AD; 8710 } else if (isVisible(PrevDecl)) { 8711 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8712 << Alias; 8713 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8714 << AD->getNamespace(); 8715 return nullptr; 8716 } 8717 } else if (isVisible(PrevDecl)) { 8718 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8719 ? diag::err_redefinition 8720 : diag::err_redefinition_different_kind; 8721 Diag(AliasLoc, DiagID) << Alias; 8722 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8723 return nullptr; 8724 } 8725 } 8726 8727 // The use of a nested name specifier may trigger deprecation warnings. 8728 DiagnoseUseOfDecl(ND, IdentLoc); 8729 8730 NamespaceAliasDecl *AliasDecl = 8731 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8732 Alias, SS.getWithLocInContext(Context), 8733 IdentLoc, ND); 8734 if (Prev) 8735 AliasDecl->setPreviousDecl(Prev); 8736 8737 PushOnScopeChains(AliasDecl, S); 8738 return AliasDecl; 8739 } 8740 8741 Sema::ImplicitExceptionSpecification 8742 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8743 CXXMethodDecl *MD) { 8744 CXXRecordDecl *ClassDecl = MD->getParent(); 8745 8746 // C++ [except.spec]p14: 8747 // An implicitly declared special member function (Clause 12) shall have an 8748 // exception-specification. [...] 8749 ImplicitExceptionSpecification ExceptSpec(*this); 8750 if (ClassDecl->isInvalidDecl()) 8751 return ExceptSpec; 8752 8753 // Direct base-class constructors. 8754 for (const auto &B : ClassDecl->bases()) { 8755 if (B.isVirtual()) // Handled below. 8756 continue; 8757 8758 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8759 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8760 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8761 // If this is a deleted function, add it anyway. This might be conformant 8762 // with the standard. This might not. I'm not sure. It might not matter. 8763 if (Constructor) 8764 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8765 } 8766 } 8767 8768 // Virtual base-class constructors. 8769 for (const auto &B : ClassDecl->vbases()) { 8770 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8771 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8772 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8773 // If this is a deleted function, add it anyway. This might be conformant 8774 // with the standard. This might not. I'm not sure. It might not matter. 8775 if (Constructor) 8776 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8777 } 8778 } 8779 8780 // Field constructors. 8781 for (const auto *F : ClassDecl->fields()) { 8782 if (F->hasInClassInitializer()) { 8783 if (Expr *E = F->getInClassInitializer()) 8784 ExceptSpec.CalledExpr(E); 8785 } else if (const RecordType *RecordTy 8786 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8787 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8788 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8789 // If this is a deleted function, add it anyway. This might be conformant 8790 // with the standard. This might not. I'm not sure. It might not matter. 8791 // In particular, the problem is that this function never gets called. It 8792 // might just be ill-formed because this function attempts to refer to 8793 // a deleted function here. 8794 if (Constructor) 8795 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8796 } 8797 } 8798 8799 return ExceptSpec; 8800 } 8801 8802 Sema::ImplicitExceptionSpecification 8803 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8804 CXXRecordDecl *ClassDecl = CD->getParent(); 8805 8806 // C++ [except.spec]p14: 8807 // An inheriting constructor [...] shall have an exception-specification. [...] 8808 ImplicitExceptionSpecification ExceptSpec(*this); 8809 if (ClassDecl->isInvalidDecl()) 8810 return ExceptSpec; 8811 8812 // Inherited constructor. 8813 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8814 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8815 // FIXME: Copying or moving the parameters could add extra exceptions to the 8816 // set, as could the default arguments for the inherited constructor. This 8817 // will be addressed when we implement the resolution of core issue 1351. 8818 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8819 8820 // Direct base-class constructors. 8821 for (const auto &B : ClassDecl->bases()) { 8822 if (B.isVirtual()) // Handled below. 8823 continue; 8824 8825 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8826 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8827 if (BaseClassDecl == InheritedDecl) 8828 continue; 8829 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8830 if (Constructor) 8831 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8832 } 8833 } 8834 8835 // Virtual base-class constructors. 8836 for (const auto &B : ClassDecl->vbases()) { 8837 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8838 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8839 if (BaseClassDecl == InheritedDecl) 8840 continue; 8841 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8842 if (Constructor) 8843 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8844 } 8845 } 8846 8847 // Field constructors. 8848 for (const auto *F : ClassDecl->fields()) { 8849 if (F->hasInClassInitializer()) { 8850 if (Expr *E = F->getInClassInitializer()) 8851 ExceptSpec.CalledExpr(E); 8852 } else if (const RecordType *RecordTy 8853 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8854 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8855 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8856 if (Constructor) 8857 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8858 } 8859 } 8860 8861 return ExceptSpec; 8862 } 8863 8864 namespace { 8865 /// RAII object to register a special member as being currently declared. 8866 struct DeclaringSpecialMember { 8867 Sema &S; 8868 Sema::SpecialMemberDecl D; 8869 bool WasAlreadyBeingDeclared; 8870 8871 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8872 : S(S), D(RD, CSM) { 8873 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8874 if (WasAlreadyBeingDeclared) 8875 // This almost never happens, but if it does, ensure that our cache 8876 // doesn't contain a stale result. 8877 S.SpecialMemberCache.clear(); 8878 8879 // FIXME: Register a note to be produced if we encounter an error while 8880 // declaring the special member. 8881 } 8882 ~DeclaringSpecialMember() { 8883 if (!WasAlreadyBeingDeclared) 8884 S.SpecialMembersBeingDeclared.erase(D); 8885 } 8886 8887 /// \brief Are we already trying to declare this special member? 8888 bool isAlreadyBeingDeclared() const { 8889 return WasAlreadyBeingDeclared; 8890 } 8891 }; 8892 } 8893 8894 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8895 CXXRecordDecl *ClassDecl) { 8896 // C++ [class.ctor]p5: 8897 // A default constructor for a class X is a constructor of class X 8898 // that can be called without an argument. If there is no 8899 // user-declared constructor for class X, a default constructor is 8900 // implicitly declared. An implicitly-declared default constructor 8901 // is an inline public member of its class. 8902 assert(ClassDecl->needsImplicitDefaultConstructor() && 8903 "Should not build implicit default constructor!"); 8904 8905 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8906 if (DSM.isAlreadyBeingDeclared()) 8907 return nullptr; 8908 8909 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8910 CXXDefaultConstructor, 8911 false); 8912 8913 // Create the actual constructor declaration. 8914 CanQualType ClassType 8915 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8916 SourceLocation ClassLoc = ClassDecl->getLocation(); 8917 DeclarationName Name 8918 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8919 DeclarationNameInfo NameInfo(Name, ClassLoc); 8920 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8921 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8922 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8923 /*isImplicitlyDeclared=*/true, Constexpr); 8924 DefaultCon->setAccess(AS_public); 8925 DefaultCon->setDefaulted(); 8926 8927 if (getLangOpts().CUDA) { 8928 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8929 DefaultCon, 8930 /* ConstRHS */ false, 8931 /* Diagnose */ false); 8932 } 8933 8934 // Build an exception specification pointing back at this constructor. 8935 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8936 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8937 8938 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8939 // constructors is easy to compute. 8940 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8941 8942 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8943 SetDeclDeleted(DefaultCon, ClassLoc); 8944 8945 // Note that we have declared this constructor. 8946 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8947 8948 if (Scope *S = getScopeForContext(ClassDecl)) 8949 PushOnScopeChains(DefaultCon, S, false); 8950 ClassDecl->addDecl(DefaultCon); 8951 8952 return DefaultCon; 8953 } 8954 8955 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8956 CXXConstructorDecl *Constructor) { 8957 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8958 !Constructor->doesThisDeclarationHaveABody() && 8959 !Constructor->isDeleted()) && 8960 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8961 8962 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8963 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8964 8965 SynthesizedFunctionScope Scope(*this, Constructor); 8966 DiagnosticErrorTrap Trap(Diags); 8967 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8968 Trap.hasErrorOccurred()) { 8969 Diag(CurrentLocation, diag::note_member_synthesized_at) 8970 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8971 Constructor->setInvalidDecl(); 8972 return; 8973 } 8974 8975 // The exception specification is needed because we are defining the 8976 // function. 8977 ResolveExceptionSpec(CurrentLocation, 8978 Constructor->getType()->castAs<FunctionProtoType>()); 8979 8980 SourceLocation Loc = Constructor->getLocEnd().isValid() 8981 ? Constructor->getLocEnd() 8982 : Constructor->getLocation(); 8983 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8984 8985 Constructor->markUsed(Context); 8986 MarkVTableUsed(CurrentLocation, ClassDecl); 8987 8988 if (ASTMutationListener *L = getASTMutationListener()) { 8989 L->CompletedImplicitDefinition(Constructor); 8990 } 8991 8992 DiagnoseUninitializedFields(*this, Constructor); 8993 } 8994 8995 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8996 // Perform any delayed checks on exception specifications. 8997 CheckDelayedMemberExceptionSpecs(); 8998 } 8999 9000 namespace { 9001 /// Information on inheriting constructors to declare. 9002 class InheritingConstructorInfo { 9003 public: 9004 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 9005 : SemaRef(SemaRef), Derived(Derived) { 9006 // Mark the constructors that we already have in the derived class. 9007 // 9008 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 9009 // unless there is a user-declared constructor with the same signature in 9010 // the class where the using-declaration appears. 9011 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 9012 } 9013 9014 void inheritAll(CXXRecordDecl *RD) { 9015 visitAll(RD, &InheritingConstructorInfo::inherit); 9016 } 9017 9018 private: 9019 /// Information about an inheriting constructor. 9020 struct InheritingConstructor { 9021 InheritingConstructor() 9022 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 9023 9024 /// If \c true, a constructor with this signature is already declared 9025 /// in the derived class. 9026 bool DeclaredInDerived; 9027 9028 /// The constructor which is inherited. 9029 const CXXConstructorDecl *BaseCtor; 9030 9031 /// The derived constructor we declared. 9032 CXXConstructorDecl *DerivedCtor; 9033 }; 9034 9035 /// Inheriting constructors with a given canonical type. There can be at 9036 /// most one such non-template constructor, and any number of templated 9037 /// constructors. 9038 struct InheritingConstructorsForType { 9039 InheritingConstructor NonTemplate; 9040 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 9041 Templates; 9042 9043 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 9044 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 9045 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 9046 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 9047 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 9048 false, S.TPL_TemplateMatch)) 9049 return Templates[I].second; 9050 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 9051 return Templates.back().second; 9052 } 9053 9054 return NonTemplate; 9055 } 9056 }; 9057 9058 /// Get or create the inheriting constructor record for a constructor. 9059 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 9060 QualType CtorType) { 9061 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 9062 .getEntry(SemaRef, Ctor); 9063 } 9064 9065 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 9066 9067 /// Process all constructors for a class. 9068 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 9069 for (const auto *Ctor : RD->ctors()) 9070 (this->*Callback)(Ctor); 9071 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9072 I(RD->decls_begin()), E(RD->decls_end()); 9073 I != E; ++I) { 9074 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 9075 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 9076 (this->*Callback)(CD); 9077 } 9078 } 9079 9080 /// Note that a constructor (or constructor template) was declared in Derived. 9081 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 9082 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 9083 } 9084 9085 /// Inherit a single constructor. 9086 void inherit(const CXXConstructorDecl *Ctor) { 9087 const FunctionProtoType *CtorType = 9088 Ctor->getType()->castAs<FunctionProtoType>(); 9089 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 9090 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 9091 9092 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 9093 9094 // Core issue (no number yet): the ellipsis is always discarded. 9095 if (EPI.Variadic) { 9096 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 9097 SemaRef.Diag(Ctor->getLocation(), 9098 diag::note_using_decl_constructor_ellipsis); 9099 EPI.Variadic = false; 9100 } 9101 9102 // Declare a constructor for each number of parameters. 9103 // 9104 // C++11 [class.inhctor]p1: 9105 // The candidate set of inherited constructors from the class X named in 9106 // the using-declaration consists of [... modulo defects ...] for each 9107 // constructor or constructor template of X, the set of constructors or 9108 // constructor templates that results from omitting any ellipsis parameter 9109 // specification and successively omitting parameters with a default 9110 // argument from the end of the parameter-type-list 9111 unsigned MinParams = minParamsToInherit(Ctor); 9112 unsigned Params = Ctor->getNumParams(); 9113 if (Params >= MinParams) { 9114 do 9115 declareCtor(UsingLoc, Ctor, 9116 SemaRef.Context.getFunctionType( 9117 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 9118 while (Params > MinParams && 9119 Ctor->getParamDecl(--Params)->hasDefaultArg()); 9120 } 9121 } 9122 9123 /// Find the using-declaration which specified that we should inherit the 9124 /// constructors of \p Base. 9125 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 9126 // No fancy lookup required; just look for the base constructor name 9127 // directly within the derived class. 9128 ASTContext &Context = SemaRef.Context; 9129 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9130 Context.getCanonicalType(Context.getRecordType(Base))); 9131 DeclContext::lookup_result Decls = Derived->lookup(Name); 9132 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 9133 } 9134 9135 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 9136 // C++11 [class.inhctor]p3: 9137 // [F]or each constructor template in the candidate set of inherited 9138 // constructors, a constructor template is implicitly declared 9139 if (Ctor->getDescribedFunctionTemplate()) 9140 return 0; 9141 9142 // For each non-template constructor in the candidate set of inherited 9143 // constructors other than a constructor having no parameters or a 9144 // copy/move constructor having a single parameter, a constructor is 9145 // implicitly declared [...] 9146 if (Ctor->getNumParams() == 0) 9147 return 1; 9148 if (Ctor->isCopyOrMoveConstructor()) 9149 return 2; 9150 9151 // Per discussion on core reflector, never inherit a constructor which 9152 // would become a default, copy, or move constructor of Derived either. 9153 const ParmVarDecl *PD = Ctor->getParamDecl(0); 9154 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 9155 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 9156 } 9157 9158 /// Declare a single inheriting constructor, inheriting the specified 9159 /// constructor, with the given type. 9160 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 9161 QualType DerivedType) { 9162 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 9163 9164 // C++11 [class.inhctor]p3: 9165 // ... a constructor is implicitly declared with the same constructor 9166 // characteristics unless there is a user-declared constructor with 9167 // the same signature in the class where the using-declaration appears 9168 if (Entry.DeclaredInDerived) 9169 return; 9170 9171 // C++11 [class.inhctor]p7: 9172 // If two using-declarations declare inheriting constructors with the 9173 // same signature, the program is ill-formed 9174 if (Entry.DerivedCtor) { 9175 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 9176 // Only diagnose this once per constructor. 9177 if (Entry.DerivedCtor->isInvalidDecl()) 9178 return; 9179 Entry.DerivedCtor->setInvalidDecl(); 9180 9181 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9182 SemaRef.Diag(BaseCtor->getLocation(), 9183 diag::note_using_decl_constructor_conflict_current_ctor); 9184 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9185 diag::note_using_decl_constructor_conflict_previous_ctor); 9186 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9187 diag::note_using_decl_constructor_conflict_previous_using); 9188 } else { 9189 // Core issue (no number): if the same inheriting constructor is 9190 // produced by multiple base class constructors from the same base 9191 // class, the inheriting constructor is defined as deleted. 9192 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9193 } 9194 9195 return; 9196 } 9197 9198 ASTContext &Context = SemaRef.Context; 9199 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9200 Context.getCanonicalType(Context.getRecordType(Derived))); 9201 DeclarationNameInfo NameInfo(Name, UsingLoc); 9202 9203 TemplateParameterList *TemplateParams = nullptr; 9204 if (const FunctionTemplateDecl *FTD = 9205 BaseCtor->getDescribedFunctionTemplate()) { 9206 TemplateParams = FTD->getTemplateParameters(); 9207 // We're reusing template parameters from a different DeclContext. This 9208 // is questionable at best, but works out because the template depth in 9209 // both places is guaranteed to be 0. 9210 // FIXME: Rebuild the template parameters in the new context, and 9211 // transform the function type to refer to them. 9212 } 9213 9214 // Build type source info pointing at the using-declaration. This is 9215 // required by template instantiation. 9216 TypeSourceInfo *TInfo = 9217 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9218 FunctionProtoTypeLoc ProtoLoc = 9219 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9220 9221 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9222 Context, Derived, UsingLoc, NameInfo, DerivedType, 9223 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9224 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9225 9226 // Build an unevaluated exception specification for this constructor. 9227 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9228 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9229 EPI.ExceptionSpec.Type = EST_Unevaluated; 9230 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9231 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9232 FPT->getParamTypes(), EPI)); 9233 9234 // Build the parameter declarations. 9235 SmallVector<ParmVarDecl *, 16> ParamDecls; 9236 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9237 TypeSourceInfo *TInfo = 9238 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9239 ParmVarDecl *PD = ParmVarDecl::Create( 9240 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9241 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9242 PD->setScopeInfo(0, I); 9243 PD->setImplicit(); 9244 ParamDecls.push_back(PD); 9245 ProtoLoc.setParam(I, PD); 9246 } 9247 9248 // Set up the new constructor. 9249 DerivedCtor->setAccess(BaseCtor->getAccess()); 9250 DerivedCtor->setParams(ParamDecls); 9251 DerivedCtor->setInheritedConstructor(BaseCtor); 9252 if (BaseCtor->isDeleted()) 9253 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9254 9255 // If this is a constructor template, build the template declaration. 9256 if (TemplateParams) { 9257 FunctionTemplateDecl *DerivedTemplate = 9258 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9259 TemplateParams, DerivedCtor); 9260 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9261 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9262 Derived->addDecl(DerivedTemplate); 9263 } else { 9264 Derived->addDecl(DerivedCtor); 9265 } 9266 9267 Entry.BaseCtor = BaseCtor; 9268 Entry.DerivedCtor = DerivedCtor; 9269 } 9270 9271 Sema &SemaRef; 9272 CXXRecordDecl *Derived; 9273 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9274 MapType Map; 9275 }; 9276 } 9277 9278 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9279 // Defer declaring the inheriting constructors until the class is 9280 // instantiated. 9281 if (ClassDecl->isDependentContext()) 9282 return; 9283 9284 // Find base classes from which we might inherit constructors. 9285 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9286 for (const auto &BaseIt : ClassDecl->bases()) 9287 if (BaseIt.getInheritConstructors()) 9288 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9289 9290 // Go no further if we're not inheriting any constructors. 9291 if (InheritedBases.empty()) 9292 return; 9293 9294 // Declare the inherited constructors. 9295 InheritingConstructorInfo ICI(*this, ClassDecl); 9296 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9297 ICI.inheritAll(InheritedBases[I]); 9298 } 9299 9300 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9301 CXXConstructorDecl *Constructor) { 9302 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9303 assert(Constructor->getInheritedConstructor() && 9304 !Constructor->doesThisDeclarationHaveABody() && 9305 !Constructor->isDeleted()); 9306 9307 SynthesizedFunctionScope Scope(*this, Constructor); 9308 DiagnosticErrorTrap Trap(Diags); 9309 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9310 Trap.hasErrorOccurred()) { 9311 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9312 << Context.getTagDeclType(ClassDecl); 9313 Constructor->setInvalidDecl(); 9314 return; 9315 } 9316 9317 SourceLocation Loc = Constructor->getLocation(); 9318 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9319 9320 Constructor->markUsed(Context); 9321 MarkVTableUsed(CurrentLocation, ClassDecl); 9322 9323 if (ASTMutationListener *L = getASTMutationListener()) { 9324 L->CompletedImplicitDefinition(Constructor); 9325 } 9326 } 9327 9328 9329 Sema::ImplicitExceptionSpecification 9330 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9331 CXXRecordDecl *ClassDecl = MD->getParent(); 9332 9333 // C++ [except.spec]p14: 9334 // An implicitly declared special member function (Clause 12) shall have 9335 // an exception-specification. 9336 ImplicitExceptionSpecification ExceptSpec(*this); 9337 if (ClassDecl->isInvalidDecl()) 9338 return ExceptSpec; 9339 9340 // Direct base-class destructors. 9341 for (const auto &B : ClassDecl->bases()) { 9342 if (B.isVirtual()) // Handled below. 9343 continue; 9344 9345 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9346 ExceptSpec.CalledDecl(B.getLocStart(), 9347 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9348 } 9349 9350 // Virtual base-class destructors. 9351 for (const auto &B : ClassDecl->vbases()) { 9352 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9353 ExceptSpec.CalledDecl(B.getLocStart(), 9354 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9355 } 9356 9357 // Field destructors. 9358 for (const auto *F : ClassDecl->fields()) { 9359 if (const RecordType *RecordTy 9360 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9361 ExceptSpec.CalledDecl(F->getLocation(), 9362 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9363 } 9364 9365 return ExceptSpec; 9366 } 9367 9368 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9369 // C++ [class.dtor]p2: 9370 // If a class has no user-declared destructor, a destructor is 9371 // declared implicitly. An implicitly-declared destructor is an 9372 // inline public member of its class. 9373 assert(ClassDecl->needsImplicitDestructor()); 9374 9375 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9376 if (DSM.isAlreadyBeingDeclared()) 9377 return nullptr; 9378 9379 // Create the actual destructor declaration. 9380 CanQualType ClassType 9381 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9382 SourceLocation ClassLoc = ClassDecl->getLocation(); 9383 DeclarationName Name 9384 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9385 DeclarationNameInfo NameInfo(Name, ClassLoc); 9386 CXXDestructorDecl *Destructor 9387 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9388 QualType(), nullptr, /*isInline=*/true, 9389 /*isImplicitlyDeclared=*/true); 9390 Destructor->setAccess(AS_public); 9391 Destructor->setDefaulted(); 9392 9393 if (getLangOpts().CUDA) { 9394 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9395 Destructor, 9396 /* ConstRHS */ false, 9397 /* Diagnose */ false); 9398 } 9399 9400 // Build an exception specification pointing back at this destructor. 9401 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9402 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9403 9404 AddOverriddenMethods(ClassDecl, Destructor); 9405 9406 // We don't need to use SpecialMemberIsTrivial here; triviality for 9407 // destructors is easy to compute. 9408 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9409 9410 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9411 SetDeclDeleted(Destructor, ClassLoc); 9412 9413 // Note that we have declared this destructor. 9414 ++ASTContext::NumImplicitDestructorsDeclared; 9415 9416 // Introduce this destructor into its scope. 9417 if (Scope *S = getScopeForContext(ClassDecl)) 9418 PushOnScopeChains(Destructor, S, false); 9419 ClassDecl->addDecl(Destructor); 9420 9421 return Destructor; 9422 } 9423 9424 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9425 CXXDestructorDecl *Destructor) { 9426 assert((Destructor->isDefaulted() && 9427 !Destructor->doesThisDeclarationHaveABody() && 9428 !Destructor->isDeleted()) && 9429 "DefineImplicitDestructor - call it for implicit default dtor"); 9430 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9431 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9432 9433 if (Destructor->isInvalidDecl()) 9434 return; 9435 9436 SynthesizedFunctionScope Scope(*this, Destructor); 9437 9438 DiagnosticErrorTrap Trap(Diags); 9439 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9440 Destructor->getParent()); 9441 9442 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9443 Diag(CurrentLocation, diag::note_member_synthesized_at) 9444 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9445 9446 Destructor->setInvalidDecl(); 9447 return; 9448 } 9449 9450 // The exception specification is needed because we are defining the 9451 // function. 9452 ResolveExceptionSpec(CurrentLocation, 9453 Destructor->getType()->castAs<FunctionProtoType>()); 9454 9455 SourceLocation Loc = Destructor->getLocEnd().isValid() 9456 ? Destructor->getLocEnd() 9457 : Destructor->getLocation(); 9458 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9459 Destructor->markUsed(Context); 9460 MarkVTableUsed(CurrentLocation, ClassDecl); 9461 9462 if (ASTMutationListener *L = getASTMutationListener()) { 9463 L->CompletedImplicitDefinition(Destructor); 9464 } 9465 } 9466 9467 /// \brief Perform any semantic analysis which needs to be delayed until all 9468 /// pending class member declarations have been parsed. 9469 void Sema::ActOnFinishCXXMemberDecls() { 9470 // If the context is an invalid C++ class, just suppress these checks. 9471 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9472 if (Record->isInvalidDecl()) { 9473 DelayedDefaultedMemberExceptionSpecs.clear(); 9474 DelayedExceptionSpecChecks.clear(); 9475 return; 9476 } 9477 } 9478 } 9479 9480 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) { 9481 // Don't do anything for template patterns. 9482 if (Class->getDescribedClassTemplate()) 9483 return; 9484 9485 for (Decl *Member : Class->decls()) { 9486 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 9487 if (!CD) { 9488 // Recurse on nested classes. 9489 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member)) 9490 getDefaultArgExprsForConstructors(S, NestedRD); 9491 continue; 9492 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) { 9493 continue; 9494 } 9495 9496 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) { 9497 // Skip any default arguments that we've already instantiated. 9498 if (S.Context.getDefaultArgExprForConstructor(CD, I)) 9499 continue; 9500 9501 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD, 9502 CD->getParamDecl(I)).get(); 9503 S.DiscardCleanupsInEvaluationContext(); 9504 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 9505 } 9506 } 9507 } 9508 9509 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 9510 auto *RD = dyn_cast<CXXRecordDecl>(D); 9511 9512 // Default constructors that are annotated with __declspec(dllexport) which 9513 // have default arguments or don't use the standard calling convention are 9514 // wrapped with a thunk called the default constructor closure. 9515 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft()) 9516 getDefaultArgExprsForConstructors(*this, RD); 9517 9518 if (!DelayedDllExportClasses.empty()) { 9519 // Calling ReferenceDllExportedMethods might cause the current function to 9520 // be called again, so use a local copy of DelayedDllExportClasses. 9521 SmallVector<CXXRecordDecl *, 4> WorkList; 9522 std::swap(DelayedDllExportClasses, WorkList); 9523 for (CXXRecordDecl *Class : WorkList) 9524 ReferenceDllExportedMethods(*this, Class); 9525 } 9526 } 9527 9528 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9529 CXXDestructorDecl *Destructor) { 9530 assert(getLangOpts().CPlusPlus11 && 9531 "adjusting dtor exception specs was introduced in c++11"); 9532 9533 // C++11 [class.dtor]p3: 9534 // A declaration of a destructor that does not have an exception- 9535 // specification is implicitly considered to have the same exception- 9536 // specification as an implicit declaration. 9537 const FunctionProtoType *DtorType = Destructor->getType()-> 9538 getAs<FunctionProtoType>(); 9539 if (DtorType->hasExceptionSpec()) 9540 return; 9541 9542 // Replace the destructor's type, building off the existing one. Fortunately, 9543 // the only thing of interest in the destructor type is its extended info. 9544 // The return and arguments are fixed. 9545 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9546 EPI.ExceptionSpec.Type = EST_Unevaluated; 9547 EPI.ExceptionSpec.SourceDecl = Destructor; 9548 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9549 9550 // FIXME: If the destructor has a body that could throw, and the newly created 9551 // spec doesn't allow exceptions, we should emit a warning, because this 9552 // change in behavior can break conforming C++03 programs at runtime. 9553 // However, we don't have a body or an exception specification yet, so it 9554 // needs to be done somewhere else. 9555 } 9556 9557 namespace { 9558 /// \brief An abstract base class for all helper classes used in building the 9559 // copy/move operators. These classes serve as factory functions and help us 9560 // avoid using the same Expr* in the AST twice. 9561 class ExprBuilder { 9562 ExprBuilder(const ExprBuilder&) = delete; 9563 ExprBuilder &operator=(const ExprBuilder&) = delete; 9564 9565 protected: 9566 static Expr *assertNotNull(Expr *E) { 9567 assert(E && "Expression construction must not fail."); 9568 return E; 9569 } 9570 9571 public: 9572 ExprBuilder() {} 9573 virtual ~ExprBuilder() {} 9574 9575 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9576 }; 9577 9578 class RefBuilder: public ExprBuilder { 9579 VarDecl *Var; 9580 QualType VarType; 9581 9582 public: 9583 Expr *build(Sema &S, SourceLocation Loc) const override { 9584 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9585 } 9586 9587 RefBuilder(VarDecl *Var, QualType VarType) 9588 : Var(Var), VarType(VarType) {} 9589 }; 9590 9591 class ThisBuilder: public ExprBuilder { 9592 public: 9593 Expr *build(Sema &S, SourceLocation Loc) const override { 9594 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9595 } 9596 }; 9597 9598 class CastBuilder: public ExprBuilder { 9599 const ExprBuilder &Builder; 9600 QualType Type; 9601 ExprValueKind Kind; 9602 const CXXCastPath &Path; 9603 9604 public: 9605 Expr *build(Sema &S, SourceLocation Loc) const override { 9606 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9607 CK_UncheckedDerivedToBase, Kind, 9608 &Path).get()); 9609 } 9610 9611 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9612 const CXXCastPath &Path) 9613 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9614 }; 9615 9616 class DerefBuilder: public ExprBuilder { 9617 const ExprBuilder &Builder; 9618 9619 public: 9620 Expr *build(Sema &S, SourceLocation Loc) const override { 9621 return assertNotNull( 9622 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9623 } 9624 9625 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9626 }; 9627 9628 class MemberBuilder: public ExprBuilder { 9629 const ExprBuilder &Builder; 9630 QualType Type; 9631 CXXScopeSpec SS; 9632 bool IsArrow; 9633 LookupResult &MemberLookup; 9634 9635 public: 9636 Expr *build(Sema &S, SourceLocation Loc) const override { 9637 return assertNotNull(S.BuildMemberReferenceExpr( 9638 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9639 nullptr, MemberLookup, nullptr, nullptr).get()); 9640 } 9641 9642 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9643 LookupResult &MemberLookup) 9644 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9645 MemberLookup(MemberLookup) {} 9646 }; 9647 9648 class MoveCastBuilder: public ExprBuilder { 9649 const ExprBuilder &Builder; 9650 9651 public: 9652 Expr *build(Sema &S, SourceLocation Loc) const override { 9653 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9654 } 9655 9656 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9657 }; 9658 9659 class LvalueConvBuilder: public ExprBuilder { 9660 const ExprBuilder &Builder; 9661 9662 public: 9663 Expr *build(Sema &S, SourceLocation Loc) const override { 9664 return assertNotNull( 9665 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9666 } 9667 9668 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9669 }; 9670 9671 class SubscriptBuilder: public ExprBuilder { 9672 const ExprBuilder &Base; 9673 const ExprBuilder &Index; 9674 9675 public: 9676 Expr *build(Sema &S, SourceLocation Loc) const override { 9677 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9678 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9679 } 9680 9681 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9682 : Base(Base), Index(Index) {} 9683 }; 9684 9685 } // end anonymous namespace 9686 9687 /// When generating a defaulted copy or move assignment operator, if a field 9688 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9689 /// do so. This optimization only applies for arrays of scalars, and for arrays 9690 /// of class type where the selected copy/move-assignment operator is trivial. 9691 static StmtResult 9692 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9693 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9694 // Compute the size of the memory buffer to be copied. 9695 QualType SizeType = S.Context.getSizeType(); 9696 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9697 S.Context.getTypeSizeInChars(T).getQuantity()); 9698 9699 // Take the address of the field references for "from" and "to". We 9700 // directly construct UnaryOperators here because semantic analysis 9701 // does not permit us to take the address of an xvalue. 9702 Expr *From = FromB.build(S, Loc); 9703 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9704 S.Context.getPointerType(From->getType()), 9705 VK_RValue, OK_Ordinary, Loc); 9706 Expr *To = ToB.build(S, Loc); 9707 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9708 S.Context.getPointerType(To->getType()), 9709 VK_RValue, OK_Ordinary, Loc); 9710 9711 const Type *E = T->getBaseElementTypeUnsafe(); 9712 bool NeedsCollectableMemCpy = 9713 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9714 9715 // Create a reference to the __builtin_objc_memmove_collectable function 9716 StringRef MemCpyName = NeedsCollectableMemCpy ? 9717 "__builtin_objc_memmove_collectable" : 9718 "__builtin_memcpy"; 9719 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9720 Sema::LookupOrdinaryName); 9721 S.LookupName(R, S.TUScope, true); 9722 9723 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9724 if (!MemCpy) 9725 // Something went horribly wrong earlier, and we will have complained 9726 // about it. 9727 return StmtError(); 9728 9729 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9730 VK_RValue, Loc, nullptr); 9731 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9732 9733 Expr *CallArgs[] = { 9734 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9735 }; 9736 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9737 Loc, CallArgs, Loc); 9738 9739 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9740 return Call.getAs<Stmt>(); 9741 } 9742 9743 /// \brief Builds a statement that copies/moves the given entity from \p From to 9744 /// \c To. 9745 /// 9746 /// This routine is used to copy/move the members of a class with an 9747 /// implicitly-declared copy/move assignment operator. When the entities being 9748 /// copied are arrays, this routine builds for loops to copy them. 9749 /// 9750 /// \param S The Sema object used for type-checking. 9751 /// 9752 /// \param Loc The location where the implicit copy/move is being generated. 9753 /// 9754 /// \param T The type of the expressions being copied/moved. Both expressions 9755 /// must have this type. 9756 /// 9757 /// \param To The expression we are copying/moving to. 9758 /// 9759 /// \param From The expression we are copying/moving from. 9760 /// 9761 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9762 /// Otherwise, it's a non-static member subobject. 9763 /// 9764 /// \param Copying Whether we're copying or moving. 9765 /// 9766 /// \param Depth Internal parameter recording the depth of the recursion. 9767 /// 9768 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9769 /// if a memcpy should be used instead. 9770 static StmtResult 9771 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9772 const ExprBuilder &To, const ExprBuilder &From, 9773 bool CopyingBaseSubobject, bool Copying, 9774 unsigned Depth = 0) { 9775 // C++11 [class.copy]p28: 9776 // Each subobject is assigned in the manner appropriate to its type: 9777 // 9778 // - if the subobject is of class type, as if by a call to operator= with 9779 // the subobject as the object expression and the corresponding 9780 // subobject of x as a single function argument (as if by explicit 9781 // qualification; that is, ignoring any possible virtual overriding 9782 // functions in more derived classes); 9783 // 9784 // C++03 [class.copy]p13: 9785 // - if the subobject is of class type, the copy assignment operator for 9786 // the class is used (as if by explicit qualification; that is, 9787 // ignoring any possible virtual overriding functions in more derived 9788 // classes); 9789 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9790 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9791 9792 // Look for operator=. 9793 DeclarationName Name 9794 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9795 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9796 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9797 9798 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9799 // operator. 9800 if (!S.getLangOpts().CPlusPlus11) { 9801 LookupResult::Filter F = OpLookup.makeFilter(); 9802 while (F.hasNext()) { 9803 NamedDecl *D = F.next(); 9804 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9805 if (Method->isCopyAssignmentOperator() || 9806 (!Copying && Method->isMoveAssignmentOperator())) 9807 continue; 9808 9809 F.erase(); 9810 } 9811 F.done(); 9812 } 9813 9814 // Suppress the protected check (C++ [class.protected]) for each of the 9815 // assignment operators we found. This strange dance is required when 9816 // we're assigning via a base classes's copy-assignment operator. To 9817 // ensure that we're getting the right base class subobject (without 9818 // ambiguities), we need to cast "this" to that subobject type; to 9819 // ensure that we don't go through the virtual call mechanism, we need 9820 // to qualify the operator= name with the base class (see below). However, 9821 // this means that if the base class has a protected copy assignment 9822 // operator, the protected member access check will fail. So, we 9823 // rewrite "protected" access to "public" access in this case, since we 9824 // know by construction that we're calling from a derived class. 9825 if (CopyingBaseSubobject) { 9826 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9827 L != LEnd; ++L) { 9828 if (L.getAccess() == AS_protected) 9829 L.setAccess(AS_public); 9830 } 9831 } 9832 9833 // Create the nested-name-specifier that will be used to qualify the 9834 // reference to operator=; this is required to suppress the virtual 9835 // call mechanism. 9836 CXXScopeSpec SS; 9837 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9838 SS.MakeTrivial(S.Context, 9839 NestedNameSpecifier::Create(S.Context, nullptr, false, 9840 CanonicalT), 9841 Loc); 9842 9843 // Create the reference to operator=. 9844 ExprResult OpEqualRef 9845 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9846 SS, /*TemplateKWLoc=*/SourceLocation(), 9847 /*FirstQualifierInScope=*/nullptr, 9848 OpLookup, 9849 /*TemplateArgs=*/nullptr, /*S*/nullptr, 9850 /*SuppressQualifierCheck=*/true); 9851 if (OpEqualRef.isInvalid()) 9852 return StmtError(); 9853 9854 // Build the call to the assignment operator. 9855 9856 Expr *FromInst = From.build(S, Loc); 9857 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9858 OpEqualRef.getAs<Expr>(), 9859 Loc, FromInst, Loc); 9860 if (Call.isInvalid()) 9861 return StmtError(); 9862 9863 // If we built a call to a trivial 'operator=' while copying an array, 9864 // bail out. We'll replace the whole shebang with a memcpy. 9865 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9866 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9867 return StmtResult((Stmt*)nullptr); 9868 9869 // Convert to an expression-statement, and clean up any produced 9870 // temporaries. 9871 return S.ActOnExprStmt(Call); 9872 } 9873 9874 // - if the subobject is of scalar type, the built-in assignment 9875 // operator is used. 9876 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9877 if (!ArrayTy) { 9878 ExprResult Assignment = S.CreateBuiltinBinOp( 9879 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9880 if (Assignment.isInvalid()) 9881 return StmtError(); 9882 return S.ActOnExprStmt(Assignment); 9883 } 9884 9885 // - if the subobject is an array, each element is assigned, in the 9886 // manner appropriate to the element type; 9887 9888 // Construct a loop over the array bounds, e.g., 9889 // 9890 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9891 // 9892 // that will copy each of the array elements. 9893 QualType SizeType = S.Context.getSizeType(); 9894 9895 // Create the iteration variable. 9896 IdentifierInfo *IterationVarName = nullptr; 9897 { 9898 SmallString<8> Str; 9899 llvm::raw_svector_ostream OS(Str); 9900 OS << "__i" << Depth; 9901 IterationVarName = &S.Context.Idents.get(OS.str()); 9902 } 9903 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9904 IterationVarName, SizeType, 9905 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9906 SC_None); 9907 9908 // Initialize the iteration variable to zero. 9909 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9910 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9911 9912 // Creates a reference to the iteration variable. 9913 RefBuilder IterationVarRef(IterationVar, SizeType); 9914 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9915 9916 // Create the DeclStmt that holds the iteration variable. 9917 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9918 9919 // Subscript the "from" and "to" expressions with the iteration variable. 9920 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9921 MoveCastBuilder FromIndexMove(FromIndexCopy); 9922 const ExprBuilder *FromIndex; 9923 if (Copying) 9924 FromIndex = &FromIndexCopy; 9925 else 9926 FromIndex = &FromIndexMove; 9927 9928 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9929 9930 // Build the copy/move for an individual element of the array. 9931 StmtResult Copy = 9932 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9933 ToIndex, *FromIndex, CopyingBaseSubobject, 9934 Copying, Depth + 1); 9935 // Bail out if copying fails or if we determined that we should use memcpy. 9936 if (Copy.isInvalid() || !Copy.get()) 9937 return Copy; 9938 9939 // Create the comparison against the array bound. 9940 llvm::APInt Upper 9941 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9942 Expr *Comparison 9943 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9944 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9945 BO_NE, S.Context.BoolTy, 9946 VK_RValue, OK_Ordinary, Loc, false); 9947 9948 // Create the pre-increment of the iteration variable. 9949 Expr *Increment 9950 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9951 SizeType, VK_LValue, OK_Ordinary, Loc); 9952 9953 // Construct the loop that copies all elements of this array. 9954 return S.ActOnForStmt(Loc, Loc, InitStmt, 9955 S.MakeFullExpr(Comparison), 9956 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9957 Loc, Copy.get()); 9958 } 9959 9960 static StmtResult 9961 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9962 const ExprBuilder &To, const ExprBuilder &From, 9963 bool CopyingBaseSubobject, bool Copying) { 9964 // Maybe we should use a memcpy? 9965 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9966 T.isTriviallyCopyableType(S.Context)) 9967 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9968 9969 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9970 CopyingBaseSubobject, 9971 Copying, 0)); 9972 9973 // If we ended up picking a trivial assignment operator for an array of a 9974 // non-trivially-copyable class type, just emit a memcpy. 9975 if (!Result.isInvalid() && !Result.get()) 9976 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9977 9978 return Result; 9979 } 9980 9981 Sema::ImplicitExceptionSpecification 9982 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9983 CXXRecordDecl *ClassDecl = MD->getParent(); 9984 9985 ImplicitExceptionSpecification ExceptSpec(*this); 9986 if (ClassDecl->isInvalidDecl()) 9987 return ExceptSpec; 9988 9989 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9990 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9991 unsigned ArgQuals = 9992 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9993 9994 // C++ [except.spec]p14: 9995 // An implicitly declared special member function (Clause 12) shall have an 9996 // exception-specification. [...] 9997 9998 // It is unspecified whether or not an implicit copy assignment operator 9999 // attempts to deduplicate calls to assignment operators of virtual bases are 10000 // made. As such, this exception specification is effectively unspecified. 10001 // Based on a similar decision made for constness in C++0x, we're erring on 10002 // the side of assuming such calls to be made regardless of whether they 10003 // actually happen. 10004 for (const auto &Base : ClassDecl->bases()) { 10005 if (Base.isVirtual()) 10006 continue; 10007 10008 CXXRecordDecl *BaseClassDecl 10009 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10010 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10011 ArgQuals, false, 0)) 10012 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10013 } 10014 10015 for (const auto &Base : ClassDecl->vbases()) { 10016 CXXRecordDecl *BaseClassDecl 10017 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10018 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10019 ArgQuals, false, 0)) 10020 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10021 } 10022 10023 for (const auto *Field : ClassDecl->fields()) { 10024 QualType FieldType = Context.getBaseElementType(Field->getType()); 10025 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10026 if (CXXMethodDecl *CopyAssign = 10027 LookupCopyingAssignment(FieldClassDecl, 10028 ArgQuals | FieldType.getCVRQualifiers(), 10029 false, 0)) 10030 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 10031 } 10032 } 10033 10034 return ExceptSpec; 10035 } 10036 10037 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 10038 // Note: The following rules are largely analoguous to the copy 10039 // constructor rules. Note that virtual bases are not taken into account 10040 // for determining the argument type of the operator. Note also that 10041 // operators taking an object instead of a reference are allowed. 10042 assert(ClassDecl->needsImplicitCopyAssignment()); 10043 10044 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 10045 if (DSM.isAlreadyBeingDeclared()) 10046 return nullptr; 10047 10048 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10049 QualType RetType = Context.getLValueReferenceType(ArgType); 10050 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 10051 if (Const) 10052 ArgType = ArgType.withConst(); 10053 ArgType = Context.getLValueReferenceType(ArgType); 10054 10055 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10056 CXXCopyAssignment, 10057 Const); 10058 10059 // An implicitly-declared copy assignment operator is an inline public 10060 // member of its class. 10061 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10062 SourceLocation ClassLoc = ClassDecl->getLocation(); 10063 DeclarationNameInfo NameInfo(Name, ClassLoc); 10064 CXXMethodDecl *CopyAssignment = 10065 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10066 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10067 /*isInline=*/true, Constexpr, SourceLocation()); 10068 CopyAssignment->setAccess(AS_public); 10069 CopyAssignment->setDefaulted(); 10070 CopyAssignment->setImplicit(); 10071 10072 if (getLangOpts().CUDA) { 10073 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 10074 CopyAssignment, 10075 /* ConstRHS */ Const, 10076 /* Diagnose */ false); 10077 } 10078 10079 // Build an exception specification pointing back at this member. 10080 FunctionProtoType::ExtProtoInfo EPI = 10081 getImplicitMethodEPI(*this, CopyAssignment); 10082 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10083 10084 // Add the parameter to the operator. 10085 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 10086 ClassLoc, ClassLoc, 10087 /*Id=*/nullptr, ArgType, 10088 /*TInfo=*/nullptr, SC_None, 10089 nullptr); 10090 CopyAssignment->setParams(FromParam); 10091 10092 AddOverriddenMethods(ClassDecl, CopyAssignment); 10093 10094 CopyAssignment->setTrivial( 10095 ClassDecl->needsOverloadResolutionForCopyAssignment() 10096 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 10097 : ClassDecl->hasTrivialCopyAssignment()); 10098 10099 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 10100 SetDeclDeleted(CopyAssignment, ClassLoc); 10101 10102 // Note that we have added this copy-assignment operator. 10103 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10104 10105 if (Scope *S = getScopeForContext(ClassDecl)) 10106 PushOnScopeChains(CopyAssignment, S, false); 10107 ClassDecl->addDecl(CopyAssignment); 10108 10109 return CopyAssignment; 10110 } 10111 10112 /// Diagnose an implicit copy operation for a class which is odr-used, but 10113 /// which is deprecated because the class has a user-declared copy constructor, 10114 /// copy assignment operator, or destructor. 10115 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 10116 SourceLocation UseLoc) { 10117 assert(CopyOp->isImplicit()); 10118 10119 CXXRecordDecl *RD = CopyOp->getParent(); 10120 CXXMethodDecl *UserDeclaredOperation = nullptr; 10121 10122 // In Microsoft mode, assignment operations don't affect constructors and 10123 // vice versa. 10124 if (RD->hasUserDeclaredDestructor()) { 10125 UserDeclaredOperation = RD->getDestructor(); 10126 } else if (!isa<CXXConstructorDecl>(CopyOp) && 10127 RD->hasUserDeclaredCopyConstructor() && 10128 !S.getLangOpts().MSVCCompat) { 10129 // Find any user-declared copy constructor. 10130 for (auto *I : RD->ctors()) { 10131 if (I->isCopyConstructor()) { 10132 UserDeclaredOperation = I; 10133 break; 10134 } 10135 } 10136 assert(UserDeclaredOperation); 10137 } else if (isa<CXXConstructorDecl>(CopyOp) && 10138 RD->hasUserDeclaredCopyAssignment() && 10139 !S.getLangOpts().MSVCCompat) { 10140 // Find any user-declared move assignment operator. 10141 for (auto *I : RD->methods()) { 10142 if (I->isCopyAssignmentOperator()) { 10143 UserDeclaredOperation = I; 10144 break; 10145 } 10146 } 10147 assert(UserDeclaredOperation); 10148 } 10149 10150 if (UserDeclaredOperation) { 10151 S.Diag(UserDeclaredOperation->getLocation(), 10152 diag::warn_deprecated_copy_operation) 10153 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 10154 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 10155 S.Diag(UseLoc, diag::note_member_synthesized_at) 10156 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 10157 : Sema::CXXCopyAssignment) 10158 << RD; 10159 } 10160 } 10161 10162 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 10163 CXXMethodDecl *CopyAssignOperator) { 10164 assert((CopyAssignOperator->isDefaulted() && 10165 CopyAssignOperator->isOverloadedOperator() && 10166 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 10167 !CopyAssignOperator->doesThisDeclarationHaveABody() && 10168 !CopyAssignOperator->isDeleted()) && 10169 "DefineImplicitCopyAssignment called for wrong function"); 10170 10171 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 10172 10173 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 10174 CopyAssignOperator->setInvalidDecl(); 10175 return; 10176 } 10177 10178 // C++11 [class.copy]p18: 10179 // The [definition of an implicitly declared copy assignment operator] is 10180 // deprecated if the class has a user-declared copy constructor or a 10181 // user-declared destructor. 10182 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 10183 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 10184 10185 CopyAssignOperator->markUsed(Context); 10186 10187 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 10188 DiagnosticErrorTrap Trap(Diags); 10189 10190 // C++0x [class.copy]p30: 10191 // The implicitly-defined or explicitly-defaulted copy assignment operator 10192 // for a non-union class X performs memberwise copy assignment of its 10193 // subobjects. The direct base classes of X are assigned first, in the 10194 // order of their declaration in the base-specifier-list, and then the 10195 // immediate non-static data members of X are assigned, in the order in 10196 // which they were declared in the class definition. 10197 10198 // The statements that form the synthesized function body. 10199 SmallVector<Stmt*, 8> Statements; 10200 10201 // The parameter for the "other" object, which we are copying from. 10202 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 10203 Qualifiers OtherQuals = Other->getType().getQualifiers(); 10204 QualType OtherRefType = Other->getType(); 10205 if (const LValueReferenceType *OtherRef 10206 = OtherRefType->getAs<LValueReferenceType>()) { 10207 OtherRefType = OtherRef->getPointeeType(); 10208 OtherQuals = OtherRefType.getQualifiers(); 10209 } 10210 10211 // Our location for everything implicitly-generated. 10212 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 10213 ? CopyAssignOperator->getLocEnd() 10214 : CopyAssignOperator->getLocation(); 10215 10216 // Builds a DeclRefExpr for the "other" object. 10217 RefBuilder OtherRef(Other, OtherRefType); 10218 10219 // Builds the "this" pointer. 10220 ThisBuilder This; 10221 10222 // Assign base classes. 10223 bool Invalid = false; 10224 for (auto &Base : ClassDecl->bases()) { 10225 // Form the assignment: 10226 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10227 QualType BaseType = Base.getType().getUnqualifiedType(); 10228 if (!BaseType->isRecordType()) { 10229 Invalid = true; 10230 continue; 10231 } 10232 10233 CXXCastPath BasePath; 10234 BasePath.push_back(&Base); 10235 10236 // Construct the "from" expression, which is an implicit cast to the 10237 // appropriately-qualified base type. 10238 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10239 VK_LValue, BasePath); 10240 10241 // Dereference "this". 10242 DerefBuilder DerefThis(This); 10243 CastBuilder To(DerefThis, 10244 Context.getCVRQualifiedType( 10245 BaseType, CopyAssignOperator->getTypeQualifiers()), 10246 VK_LValue, BasePath); 10247 10248 // Build the copy. 10249 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10250 To, From, 10251 /*CopyingBaseSubobject=*/true, 10252 /*Copying=*/true); 10253 if (Copy.isInvalid()) { 10254 Diag(CurrentLocation, diag::note_member_synthesized_at) 10255 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10256 CopyAssignOperator->setInvalidDecl(); 10257 return; 10258 } 10259 10260 // Success! Record the copy. 10261 Statements.push_back(Copy.getAs<Expr>()); 10262 } 10263 10264 // Assign non-static members. 10265 for (auto *Field : ClassDecl->fields()) { 10266 // FIXME: We should form some kind of AST representation for the implied 10267 // memcpy in a union copy operation. 10268 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10269 continue; 10270 10271 if (Field->isInvalidDecl()) { 10272 Invalid = true; 10273 continue; 10274 } 10275 10276 // Check for members of reference type; we can't copy those. 10277 if (Field->getType()->isReferenceType()) { 10278 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10279 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10280 Diag(Field->getLocation(), diag::note_declared_at); 10281 Diag(CurrentLocation, diag::note_member_synthesized_at) 10282 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10283 Invalid = true; 10284 continue; 10285 } 10286 10287 // Check for members of const-qualified, non-class type. 10288 QualType BaseType = Context.getBaseElementType(Field->getType()); 10289 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10290 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10291 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10292 Diag(Field->getLocation(), diag::note_declared_at); 10293 Diag(CurrentLocation, diag::note_member_synthesized_at) 10294 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10295 Invalid = true; 10296 continue; 10297 } 10298 10299 // Suppress assigning zero-width bitfields. 10300 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10301 continue; 10302 10303 QualType FieldType = Field->getType().getNonReferenceType(); 10304 if (FieldType->isIncompleteArrayType()) { 10305 assert(ClassDecl->hasFlexibleArrayMember() && 10306 "Incomplete array type is not valid"); 10307 continue; 10308 } 10309 10310 // Build references to the field in the object we're copying from and to. 10311 CXXScopeSpec SS; // Intentionally empty 10312 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10313 LookupMemberName); 10314 MemberLookup.addDecl(Field); 10315 MemberLookup.resolveKind(); 10316 10317 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10318 10319 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10320 10321 // Build the copy of this field. 10322 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10323 To, From, 10324 /*CopyingBaseSubobject=*/false, 10325 /*Copying=*/true); 10326 if (Copy.isInvalid()) { 10327 Diag(CurrentLocation, diag::note_member_synthesized_at) 10328 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10329 CopyAssignOperator->setInvalidDecl(); 10330 return; 10331 } 10332 10333 // Success! Record the copy. 10334 Statements.push_back(Copy.getAs<Stmt>()); 10335 } 10336 10337 if (!Invalid) { 10338 // Add a "return *this;" 10339 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10340 10341 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10342 if (Return.isInvalid()) 10343 Invalid = true; 10344 else { 10345 Statements.push_back(Return.getAs<Stmt>()); 10346 10347 if (Trap.hasErrorOccurred()) { 10348 Diag(CurrentLocation, diag::note_member_synthesized_at) 10349 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10350 Invalid = true; 10351 } 10352 } 10353 } 10354 10355 // The exception specification is needed because we are defining the 10356 // function. 10357 ResolveExceptionSpec(CurrentLocation, 10358 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10359 10360 if (Invalid) { 10361 CopyAssignOperator->setInvalidDecl(); 10362 return; 10363 } 10364 10365 StmtResult Body; 10366 { 10367 CompoundScopeRAII CompoundScope(*this); 10368 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10369 /*isStmtExpr=*/false); 10370 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10371 } 10372 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10373 10374 if (ASTMutationListener *L = getASTMutationListener()) { 10375 L->CompletedImplicitDefinition(CopyAssignOperator); 10376 } 10377 } 10378 10379 Sema::ImplicitExceptionSpecification 10380 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10381 CXXRecordDecl *ClassDecl = MD->getParent(); 10382 10383 ImplicitExceptionSpecification ExceptSpec(*this); 10384 if (ClassDecl->isInvalidDecl()) 10385 return ExceptSpec; 10386 10387 // C++0x [except.spec]p14: 10388 // An implicitly declared special member function (Clause 12) shall have an 10389 // exception-specification. [...] 10390 10391 // It is unspecified whether or not an implicit move assignment operator 10392 // attempts to deduplicate calls to assignment operators of virtual bases are 10393 // made. As such, this exception specification is effectively unspecified. 10394 // Based on a similar decision made for constness in C++0x, we're erring on 10395 // the side of assuming such calls to be made regardless of whether they 10396 // actually happen. 10397 // Note that a move constructor is not implicitly declared when there are 10398 // virtual bases, but it can still be user-declared and explicitly defaulted. 10399 for (const auto &Base : ClassDecl->bases()) { 10400 if (Base.isVirtual()) 10401 continue; 10402 10403 CXXRecordDecl *BaseClassDecl 10404 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10405 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10406 0, false, 0)) 10407 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10408 } 10409 10410 for (const auto &Base : ClassDecl->vbases()) { 10411 CXXRecordDecl *BaseClassDecl 10412 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10413 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10414 0, false, 0)) 10415 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10416 } 10417 10418 for (const auto *Field : ClassDecl->fields()) { 10419 QualType FieldType = Context.getBaseElementType(Field->getType()); 10420 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10421 if (CXXMethodDecl *MoveAssign = 10422 LookupMovingAssignment(FieldClassDecl, 10423 FieldType.getCVRQualifiers(), 10424 false, 0)) 10425 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10426 } 10427 } 10428 10429 return ExceptSpec; 10430 } 10431 10432 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10433 assert(ClassDecl->needsImplicitMoveAssignment()); 10434 10435 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10436 if (DSM.isAlreadyBeingDeclared()) 10437 return nullptr; 10438 10439 // Note: The following rules are largely analoguous to the move 10440 // constructor rules. 10441 10442 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10443 QualType RetType = Context.getLValueReferenceType(ArgType); 10444 ArgType = Context.getRValueReferenceType(ArgType); 10445 10446 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10447 CXXMoveAssignment, 10448 false); 10449 10450 // An implicitly-declared move assignment operator is an inline public 10451 // member of its class. 10452 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10453 SourceLocation ClassLoc = ClassDecl->getLocation(); 10454 DeclarationNameInfo NameInfo(Name, ClassLoc); 10455 CXXMethodDecl *MoveAssignment = 10456 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10457 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10458 /*isInline=*/true, Constexpr, SourceLocation()); 10459 MoveAssignment->setAccess(AS_public); 10460 MoveAssignment->setDefaulted(); 10461 MoveAssignment->setImplicit(); 10462 10463 if (getLangOpts().CUDA) { 10464 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10465 MoveAssignment, 10466 /* ConstRHS */ false, 10467 /* Diagnose */ false); 10468 } 10469 10470 // Build an exception specification pointing back at this member. 10471 FunctionProtoType::ExtProtoInfo EPI = 10472 getImplicitMethodEPI(*this, MoveAssignment); 10473 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10474 10475 // Add the parameter to the operator. 10476 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10477 ClassLoc, ClassLoc, 10478 /*Id=*/nullptr, ArgType, 10479 /*TInfo=*/nullptr, SC_None, 10480 nullptr); 10481 MoveAssignment->setParams(FromParam); 10482 10483 AddOverriddenMethods(ClassDecl, MoveAssignment); 10484 10485 MoveAssignment->setTrivial( 10486 ClassDecl->needsOverloadResolutionForMoveAssignment() 10487 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10488 : ClassDecl->hasTrivialMoveAssignment()); 10489 10490 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10491 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10492 SetDeclDeleted(MoveAssignment, ClassLoc); 10493 } 10494 10495 // Note that we have added this copy-assignment operator. 10496 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10497 10498 if (Scope *S = getScopeForContext(ClassDecl)) 10499 PushOnScopeChains(MoveAssignment, S, false); 10500 ClassDecl->addDecl(MoveAssignment); 10501 10502 return MoveAssignment; 10503 } 10504 10505 /// Check if we're implicitly defining a move assignment operator for a class 10506 /// with virtual bases. Such a move assignment might move-assign the virtual 10507 /// base multiple times. 10508 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10509 SourceLocation CurrentLocation) { 10510 assert(!Class->isDependentContext() && "should not define dependent move"); 10511 10512 // Only a virtual base could get implicitly move-assigned multiple times. 10513 // Only a non-trivial move assignment can observe this. We only want to 10514 // diagnose if we implicitly define an assignment operator that assigns 10515 // two base classes, both of which move-assign the same virtual base. 10516 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10517 Class->getNumBases() < 2) 10518 return; 10519 10520 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10521 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10522 VBaseMap VBases; 10523 10524 for (auto &BI : Class->bases()) { 10525 Worklist.push_back(&BI); 10526 while (!Worklist.empty()) { 10527 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10528 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10529 10530 // If the base has no non-trivial move assignment operators, 10531 // we don't care about moves from it. 10532 if (!Base->hasNonTrivialMoveAssignment()) 10533 continue; 10534 10535 // If there's nothing virtual here, skip it. 10536 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10537 continue; 10538 10539 // If we're not actually going to call a move assignment for this base, 10540 // or the selected move assignment is trivial, skip it. 10541 Sema::SpecialMemberOverloadResult *SMOR = 10542 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10543 /*ConstArg*/false, /*VolatileArg*/false, 10544 /*RValueThis*/true, /*ConstThis*/false, 10545 /*VolatileThis*/false); 10546 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10547 !SMOR->getMethod()->isMoveAssignmentOperator()) 10548 continue; 10549 10550 if (BaseSpec->isVirtual()) { 10551 // We're going to move-assign this virtual base, and its move 10552 // assignment operator is not trivial. If this can happen for 10553 // multiple distinct direct bases of Class, diagnose it. (If it 10554 // only happens in one base, we'll diagnose it when synthesizing 10555 // that base class's move assignment operator.) 10556 CXXBaseSpecifier *&Existing = 10557 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10558 .first->second; 10559 if (Existing && Existing != &BI) { 10560 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10561 << Class << Base; 10562 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10563 << (Base->getCanonicalDecl() == 10564 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10565 << Base << Existing->getType() << Existing->getSourceRange(); 10566 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10567 << (Base->getCanonicalDecl() == 10568 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10569 << Base << BI.getType() << BaseSpec->getSourceRange(); 10570 10571 // Only diagnose each vbase once. 10572 Existing = nullptr; 10573 } 10574 } else { 10575 // Only walk over bases that have defaulted move assignment operators. 10576 // We assume that any user-provided move assignment operator handles 10577 // the multiple-moves-of-vbase case itself somehow. 10578 if (!SMOR->getMethod()->isDefaulted()) 10579 continue; 10580 10581 // We're going to move the base classes of Base. Add them to the list. 10582 for (auto &BI : Base->bases()) 10583 Worklist.push_back(&BI); 10584 } 10585 } 10586 } 10587 } 10588 10589 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10590 CXXMethodDecl *MoveAssignOperator) { 10591 assert((MoveAssignOperator->isDefaulted() && 10592 MoveAssignOperator->isOverloadedOperator() && 10593 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10594 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10595 !MoveAssignOperator->isDeleted()) && 10596 "DefineImplicitMoveAssignment called for wrong function"); 10597 10598 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10599 10600 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10601 MoveAssignOperator->setInvalidDecl(); 10602 return; 10603 } 10604 10605 MoveAssignOperator->markUsed(Context); 10606 10607 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10608 DiagnosticErrorTrap Trap(Diags); 10609 10610 // C++0x [class.copy]p28: 10611 // The implicitly-defined or move assignment operator for a non-union class 10612 // X performs memberwise move assignment of its subobjects. The direct base 10613 // classes of X are assigned first, in the order of their declaration in the 10614 // base-specifier-list, and then the immediate non-static data members of X 10615 // are assigned, in the order in which they were declared in the class 10616 // definition. 10617 10618 // Issue a warning if our implicit move assignment operator will move 10619 // from a virtual base more than once. 10620 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10621 10622 // The statements that form the synthesized function body. 10623 SmallVector<Stmt*, 8> Statements; 10624 10625 // The parameter for the "other" object, which we are move from. 10626 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10627 QualType OtherRefType = Other->getType()-> 10628 getAs<RValueReferenceType>()->getPointeeType(); 10629 assert(!OtherRefType.getQualifiers() && 10630 "Bad argument type of defaulted move assignment"); 10631 10632 // Our location for everything implicitly-generated. 10633 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10634 ? MoveAssignOperator->getLocEnd() 10635 : MoveAssignOperator->getLocation(); 10636 10637 // Builds a reference to the "other" object. 10638 RefBuilder OtherRef(Other, OtherRefType); 10639 // Cast to rvalue. 10640 MoveCastBuilder MoveOther(OtherRef); 10641 10642 // Builds the "this" pointer. 10643 ThisBuilder This; 10644 10645 // Assign base classes. 10646 bool Invalid = false; 10647 for (auto &Base : ClassDecl->bases()) { 10648 // C++11 [class.copy]p28: 10649 // It is unspecified whether subobjects representing virtual base classes 10650 // are assigned more than once by the implicitly-defined copy assignment 10651 // operator. 10652 // FIXME: Do not assign to a vbase that will be assigned by some other base 10653 // class. For a move-assignment, this can result in the vbase being moved 10654 // multiple times. 10655 10656 // Form the assignment: 10657 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10658 QualType BaseType = Base.getType().getUnqualifiedType(); 10659 if (!BaseType->isRecordType()) { 10660 Invalid = true; 10661 continue; 10662 } 10663 10664 CXXCastPath BasePath; 10665 BasePath.push_back(&Base); 10666 10667 // Construct the "from" expression, which is an implicit cast to the 10668 // appropriately-qualified base type. 10669 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10670 10671 // Dereference "this". 10672 DerefBuilder DerefThis(This); 10673 10674 // Implicitly cast "this" to the appropriately-qualified base type. 10675 CastBuilder To(DerefThis, 10676 Context.getCVRQualifiedType( 10677 BaseType, MoveAssignOperator->getTypeQualifiers()), 10678 VK_LValue, BasePath); 10679 10680 // Build the move. 10681 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10682 To, From, 10683 /*CopyingBaseSubobject=*/true, 10684 /*Copying=*/false); 10685 if (Move.isInvalid()) { 10686 Diag(CurrentLocation, diag::note_member_synthesized_at) 10687 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10688 MoveAssignOperator->setInvalidDecl(); 10689 return; 10690 } 10691 10692 // Success! Record the move. 10693 Statements.push_back(Move.getAs<Expr>()); 10694 } 10695 10696 // Assign non-static members. 10697 for (auto *Field : ClassDecl->fields()) { 10698 // FIXME: We should form some kind of AST representation for the implied 10699 // memcpy in a union copy operation. 10700 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 10701 continue; 10702 10703 if (Field->isInvalidDecl()) { 10704 Invalid = true; 10705 continue; 10706 } 10707 10708 // Check for members of reference type; we can't move those. 10709 if (Field->getType()->isReferenceType()) { 10710 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10711 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10712 Diag(Field->getLocation(), diag::note_declared_at); 10713 Diag(CurrentLocation, diag::note_member_synthesized_at) 10714 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10715 Invalid = true; 10716 continue; 10717 } 10718 10719 // Check for members of const-qualified, non-class type. 10720 QualType BaseType = Context.getBaseElementType(Field->getType()); 10721 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10722 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10723 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10724 Diag(Field->getLocation(), diag::note_declared_at); 10725 Diag(CurrentLocation, diag::note_member_synthesized_at) 10726 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10727 Invalid = true; 10728 continue; 10729 } 10730 10731 // Suppress assigning zero-width bitfields. 10732 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10733 continue; 10734 10735 QualType FieldType = Field->getType().getNonReferenceType(); 10736 if (FieldType->isIncompleteArrayType()) { 10737 assert(ClassDecl->hasFlexibleArrayMember() && 10738 "Incomplete array type is not valid"); 10739 continue; 10740 } 10741 10742 // Build references to the field in the object we're copying from and to. 10743 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10744 LookupMemberName); 10745 MemberLookup.addDecl(Field); 10746 MemberLookup.resolveKind(); 10747 MemberBuilder From(MoveOther, OtherRefType, 10748 /*IsArrow=*/false, MemberLookup); 10749 MemberBuilder To(This, getCurrentThisType(), 10750 /*IsArrow=*/true, MemberLookup); 10751 10752 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10753 "Member reference with rvalue base must be rvalue except for reference " 10754 "members, which aren't allowed for move assignment."); 10755 10756 // Build the move of this field. 10757 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10758 To, From, 10759 /*CopyingBaseSubobject=*/false, 10760 /*Copying=*/false); 10761 if (Move.isInvalid()) { 10762 Diag(CurrentLocation, diag::note_member_synthesized_at) 10763 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10764 MoveAssignOperator->setInvalidDecl(); 10765 return; 10766 } 10767 10768 // Success! Record the copy. 10769 Statements.push_back(Move.getAs<Stmt>()); 10770 } 10771 10772 if (!Invalid) { 10773 // Add a "return *this;" 10774 ExprResult ThisObj = 10775 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10776 10777 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10778 if (Return.isInvalid()) 10779 Invalid = true; 10780 else { 10781 Statements.push_back(Return.getAs<Stmt>()); 10782 10783 if (Trap.hasErrorOccurred()) { 10784 Diag(CurrentLocation, diag::note_member_synthesized_at) 10785 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10786 Invalid = true; 10787 } 10788 } 10789 } 10790 10791 // The exception specification is needed because we are defining the 10792 // function. 10793 ResolveExceptionSpec(CurrentLocation, 10794 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10795 10796 if (Invalid) { 10797 MoveAssignOperator->setInvalidDecl(); 10798 return; 10799 } 10800 10801 StmtResult Body; 10802 { 10803 CompoundScopeRAII CompoundScope(*this); 10804 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10805 /*isStmtExpr=*/false); 10806 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10807 } 10808 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10809 10810 if (ASTMutationListener *L = getASTMutationListener()) { 10811 L->CompletedImplicitDefinition(MoveAssignOperator); 10812 } 10813 } 10814 10815 Sema::ImplicitExceptionSpecification 10816 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10817 CXXRecordDecl *ClassDecl = MD->getParent(); 10818 10819 ImplicitExceptionSpecification ExceptSpec(*this); 10820 if (ClassDecl->isInvalidDecl()) 10821 return ExceptSpec; 10822 10823 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10824 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10825 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10826 10827 // C++ [except.spec]p14: 10828 // An implicitly declared special member function (Clause 12) shall have an 10829 // exception-specification. [...] 10830 for (const auto &Base : ClassDecl->bases()) { 10831 // Virtual bases are handled below. 10832 if (Base.isVirtual()) 10833 continue; 10834 10835 CXXRecordDecl *BaseClassDecl 10836 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10837 if (CXXConstructorDecl *CopyConstructor = 10838 LookupCopyingConstructor(BaseClassDecl, Quals)) 10839 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10840 } 10841 for (const auto &Base : ClassDecl->vbases()) { 10842 CXXRecordDecl *BaseClassDecl 10843 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10844 if (CXXConstructorDecl *CopyConstructor = 10845 LookupCopyingConstructor(BaseClassDecl, Quals)) 10846 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10847 } 10848 for (const auto *Field : ClassDecl->fields()) { 10849 QualType FieldType = Context.getBaseElementType(Field->getType()); 10850 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10851 if (CXXConstructorDecl *CopyConstructor = 10852 LookupCopyingConstructor(FieldClassDecl, 10853 Quals | FieldType.getCVRQualifiers())) 10854 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10855 } 10856 } 10857 10858 return ExceptSpec; 10859 } 10860 10861 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10862 CXXRecordDecl *ClassDecl) { 10863 // C++ [class.copy]p4: 10864 // If the class definition does not explicitly declare a copy 10865 // constructor, one is declared implicitly. 10866 assert(ClassDecl->needsImplicitCopyConstructor()); 10867 10868 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10869 if (DSM.isAlreadyBeingDeclared()) 10870 return nullptr; 10871 10872 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10873 QualType ArgType = ClassType; 10874 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10875 if (Const) 10876 ArgType = ArgType.withConst(); 10877 ArgType = Context.getLValueReferenceType(ArgType); 10878 10879 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10880 CXXCopyConstructor, 10881 Const); 10882 10883 DeclarationName Name 10884 = Context.DeclarationNames.getCXXConstructorName( 10885 Context.getCanonicalType(ClassType)); 10886 SourceLocation ClassLoc = ClassDecl->getLocation(); 10887 DeclarationNameInfo NameInfo(Name, ClassLoc); 10888 10889 // An implicitly-declared copy constructor is an inline public 10890 // member of its class. 10891 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10892 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10893 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10894 Constexpr); 10895 CopyConstructor->setAccess(AS_public); 10896 CopyConstructor->setDefaulted(); 10897 10898 if (getLangOpts().CUDA) { 10899 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10900 CopyConstructor, 10901 /* ConstRHS */ Const, 10902 /* Diagnose */ false); 10903 } 10904 10905 // Build an exception specification pointing back at this member. 10906 FunctionProtoType::ExtProtoInfo EPI = 10907 getImplicitMethodEPI(*this, CopyConstructor); 10908 CopyConstructor->setType( 10909 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10910 10911 // Add the parameter to the constructor. 10912 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10913 ClassLoc, ClassLoc, 10914 /*IdentifierInfo=*/nullptr, 10915 ArgType, /*TInfo=*/nullptr, 10916 SC_None, nullptr); 10917 CopyConstructor->setParams(FromParam); 10918 10919 CopyConstructor->setTrivial( 10920 ClassDecl->needsOverloadResolutionForCopyConstructor() 10921 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10922 : ClassDecl->hasTrivialCopyConstructor()); 10923 10924 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10925 SetDeclDeleted(CopyConstructor, ClassLoc); 10926 10927 // Note that we have declared this constructor. 10928 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10929 10930 if (Scope *S = getScopeForContext(ClassDecl)) 10931 PushOnScopeChains(CopyConstructor, S, false); 10932 ClassDecl->addDecl(CopyConstructor); 10933 10934 return CopyConstructor; 10935 } 10936 10937 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10938 CXXConstructorDecl *CopyConstructor) { 10939 assert((CopyConstructor->isDefaulted() && 10940 CopyConstructor->isCopyConstructor() && 10941 !CopyConstructor->doesThisDeclarationHaveABody() && 10942 !CopyConstructor->isDeleted()) && 10943 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10944 10945 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10946 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10947 10948 // C++11 [class.copy]p7: 10949 // The [definition of an implicitly declared copy constructor] is 10950 // deprecated if the class has a user-declared copy assignment operator 10951 // or a user-declared destructor. 10952 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10953 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10954 10955 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10956 DiagnosticErrorTrap Trap(Diags); 10957 10958 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10959 Trap.hasErrorOccurred()) { 10960 Diag(CurrentLocation, diag::note_member_synthesized_at) 10961 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10962 CopyConstructor->setInvalidDecl(); 10963 } else { 10964 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10965 ? CopyConstructor->getLocEnd() 10966 : CopyConstructor->getLocation(); 10967 Sema::CompoundScopeRAII CompoundScope(*this); 10968 CopyConstructor->setBody( 10969 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10970 } 10971 10972 // The exception specification is needed because we are defining the 10973 // function. 10974 ResolveExceptionSpec(CurrentLocation, 10975 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10976 10977 CopyConstructor->markUsed(Context); 10978 MarkVTableUsed(CurrentLocation, ClassDecl); 10979 10980 if (ASTMutationListener *L = getASTMutationListener()) { 10981 L->CompletedImplicitDefinition(CopyConstructor); 10982 } 10983 } 10984 10985 Sema::ImplicitExceptionSpecification 10986 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10987 CXXRecordDecl *ClassDecl = MD->getParent(); 10988 10989 // C++ [except.spec]p14: 10990 // An implicitly declared special member function (Clause 12) shall have an 10991 // exception-specification. [...] 10992 ImplicitExceptionSpecification ExceptSpec(*this); 10993 if (ClassDecl->isInvalidDecl()) 10994 return ExceptSpec; 10995 10996 // Direct base-class constructors. 10997 for (const auto &B : ClassDecl->bases()) { 10998 if (B.isVirtual()) // Handled below. 10999 continue; 11000 11001 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11002 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11003 CXXConstructorDecl *Constructor = 11004 LookupMovingConstructor(BaseClassDecl, 0); 11005 // If this is a deleted function, add it anyway. This might be conformant 11006 // with the standard. This might not. I'm not sure. It might not matter. 11007 if (Constructor) 11008 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11009 } 11010 } 11011 11012 // Virtual base-class constructors. 11013 for (const auto &B : ClassDecl->vbases()) { 11014 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11015 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11016 CXXConstructorDecl *Constructor = 11017 LookupMovingConstructor(BaseClassDecl, 0); 11018 // If this is a deleted function, add it anyway. This might be conformant 11019 // with the standard. This might not. I'm not sure. It might not matter. 11020 if (Constructor) 11021 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11022 } 11023 } 11024 11025 // Field constructors. 11026 for (const auto *F : ClassDecl->fields()) { 11027 QualType FieldType = Context.getBaseElementType(F->getType()); 11028 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 11029 CXXConstructorDecl *Constructor = 11030 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 11031 // If this is a deleted function, add it anyway. This might be conformant 11032 // with the standard. This might not. I'm not sure. It might not matter. 11033 // In particular, the problem is that this function never gets called. It 11034 // might just be ill-formed because this function attempts to refer to 11035 // a deleted function here. 11036 if (Constructor) 11037 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 11038 } 11039 } 11040 11041 return ExceptSpec; 11042 } 11043 11044 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 11045 CXXRecordDecl *ClassDecl) { 11046 assert(ClassDecl->needsImplicitMoveConstructor()); 11047 11048 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 11049 if (DSM.isAlreadyBeingDeclared()) 11050 return nullptr; 11051 11052 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11053 QualType ArgType = Context.getRValueReferenceType(ClassType); 11054 11055 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11056 CXXMoveConstructor, 11057 false); 11058 11059 DeclarationName Name 11060 = Context.DeclarationNames.getCXXConstructorName( 11061 Context.getCanonicalType(ClassType)); 11062 SourceLocation ClassLoc = ClassDecl->getLocation(); 11063 DeclarationNameInfo NameInfo(Name, ClassLoc); 11064 11065 // C++11 [class.copy]p11: 11066 // An implicitly-declared copy/move constructor is an inline public 11067 // member of its class. 11068 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 11069 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11070 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11071 Constexpr); 11072 MoveConstructor->setAccess(AS_public); 11073 MoveConstructor->setDefaulted(); 11074 11075 if (getLangOpts().CUDA) { 11076 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 11077 MoveConstructor, 11078 /* ConstRHS */ false, 11079 /* Diagnose */ false); 11080 } 11081 11082 // Build an exception specification pointing back at this member. 11083 FunctionProtoType::ExtProtoInfo EPI = 11084 getImplicitMethodEPI(*this, MoveConstructor); 11085 MoveConstructor->setType( 11086 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11087 11088 // Add the parameter to the constructor. 11089 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 11090 ClassLoc, ClassLoc, 11091 /*IdentifierInfo=*/nullptr, 11092 ArgType, /*TInfo=*/nullptr, 11093 SC_None, nullptr); 11094 MoveConstructor->setParams(FromParam); 11095 11096 MoveConstructor->setTrivial( 11097 ClassDecl->needsOverloadResolutionForMoveConstructor() 11098 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 11099 : ClassDecl->hasTrivialMoveConstructor()); 11100 11101 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 11102 ClassDecl->setImplicitMoveConstructorIsDeleted(); 11103 SetDeclDeleted(MoveConstructor, ClassLoc); 11104 } 11105 11106 // Note that we have declared this constructor. 11107 ++ASTContext::NumImplicitMoveConstructorsDeclared; 11108 11109 if (Scope *S = getScopeForContext(ClassDecl)) 11110 PushOnScopeChains(MoveConstructor, S, false); 11111 ClassDecl->addDecl(MoveConstructor); 11112 11113 return MoveConstructor; 11114 } 11115 11116 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 11117 CXXConstructorDecl *MoveConstructor) { 11118 assert((MoveConstructor->isDefaulted() && 11119 MoveConstructor->isMoveConstructor() && 11120 !MoveConstructor->doesThisDeclarationHaveABody() && 11121 !MoveConstructor->isDeleted()) && 11122 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 11123 11124 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 11125 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 11126 11127 SynthesizedFunctionScope Scope(*this, MoveConstructor); 11128 DiagnosticErrorTrap Trap(Diags); 11129 11130 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 11131 Trap.hasErrorOccurred()) { 11132 Diag(CurrentLocation, diag::note_member_synthesized_at) 11133 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 11134 MoveConstructor->setInvalidDecl(); 11135 } else { 11136 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 11137 ? MoveConstructor->getLocEnd() 11138 : MoveConstructor->getLocation(); 11139 Sema::CompoundScopeRAII CompoundScope(*this); 11140 MoveConstructor->setBody(ActOnCompoundStmt( 11141 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 11142 } 11143 11144 // The exception specification is needed because we are defining the 11145 // function. 11146 ResolveExceptionSpec(CurrentLocation, 11147 MoveConstructor->getType()->castAs<FunctionProtoType>()); 11148 11149 MoveConstructor->markUsed(Context); 11150 MarkVTableUsed(CurrentLocation, ClassDecl); 11151 11152 if (ASTMutationListener *L = getASTMutationListener()) { 11153 L->CompletedImplicitDefinition(MoveConstructor); 11154 } 11155 } 11156 11157 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 11158 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 11159 } 11160 11161 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 11162 SourceLocation CurrentLocation, 11163 CXXConversionDecl *Conv) { 11164 CXXRecordDecl *Lambda = Conv->getParent(); 11165 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 11166 // If we are defining a specialization of a conversion to function-ptr 11167 // cache the deduced template arguments for this specialization 11168 // so that we can use them to retrieve the corresponding call-operator 11169 // and static-invoker. 11170 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 11171 11172 // Retrieve the corresponding call-operator specialization. 11173 if (Lambda->isGenericLambda()) { 11174 assert(Conv->isFunctionTemplateSpecialization()); 11175 FunctionTemplateDecl *CallOpTemplate = 11176 CallOp->getDescribedFunctionTemplate(); 11177 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 11178 void *InsertPos = nullptr; 11179 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 11180 DeducedTemplateArgs->asArray(), 11181 InsertPos); 11182 assert(CallOpSpec && 11183 "Conversion operator must have a corresponding call operator"); 11184 CallOp = cast<CXXMethodDecl>(CallOpSpec); 11185 } 11186 // Mark the call operator referenced (and add to pending instantiations 11187 // if necessary). 11188 // For both the conversion and static-invoker template specializations 11189 // we construct their body's in this function, so no need to add them 11190 // to the PendingInstantiations. 11191 MarkFunctionReferenced(CurrentLocation, CallOp); 11192 11193 SynthesizedFunctionScope Scope(*this, Conv); 11194 DiagnosticErrorTrap Trap(Diags); 11195 11196 // Retrieve the static invoker... 11197 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 11198 // ... and get the corresponding specialization for a generic lambda. 11199 if (Lambda->isGenericLambda()) { 11200 assert(DeducedTemplateArgs && 11201 "Must have deduced template arguments from Conversion Operator"); 11202 FunctionTemplateDecl *InvokeTemplate = 11203 Invoker->getDescribedFunctionTemplate(); 11204 void *InsertPos = nullptr; 11205 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 11206 DeducedTemplateArgs->asArray(), 11207 InsertPos); 11208 assert(InvokeSpec && 11209 "Must have a corresponding static invoker specialization"); 11210 Invoker = cast<CXXMethodDecl>(InvokeSpec); 11211 } 11212 // Construct the body of the conversion function { return __invoke; }. 11213 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 11214 VK_LValue, Conv->getLocation()).get(); 11215 assert(FunctionRef && "Can't refer to __invoke function?"); 11216 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 11217 Conv->setBody(new (Context) CompoundStmt(Context, Return, 11218 Conv->getLocation(), 11219 Conv->getLocation())); 11220 11221 Conv->markUsed(Context); 11222 Conv->setReferenced(); 11223 11224 // Fill in the __invoke function with a dummy implementation. IR generation 11225 // will fill in the actual details. 11226 Invoker->markUsed(Context); 11227 Invoker->setReferenced(); 11228 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 11229 11230 if (ASTMutationListener *L = getASTMutationListener()) { 11231 L->CompletedImplicitDefinition(Conv); 11232 L->CompletedImplicitDefinition(Invoker); 11233 } 11234 } 11235 11236 11237 11238 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11239 SourceLocation CurrentLocation, 11240 CXXConversionDecl *Conv) 11241 { 11242 assert(!Conv->getParent()->isGenericLambda()); 11243 11244 Conv->markUsed(Context); 11245 11246 SynthesizedFunctionScope Scope(*this, Conv); 11247 DiagnosticErrorTrap Trap(Diags); 11248 11249 // Copy-initialize the lambda object as needed to capture it. 11250 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11251 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11252 11253 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11254 Conv->getLocation(), 11255 Conv, DerefThis); 11256 11257 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11258 // behavior. Note that only the general conversion function does this 11259 // (since it's unusable otherwise); in the case where we inline the 11260 // block literal, it has block literal lifetime semantics. 11261 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11262 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11263 CK_CopyAndAutoreleaseBlockObject, 11264 BuildBlock.get(), nullptr, VK_RValue); 11265 11266 if (BuildBlock.isInvalid()) { 11267 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11268 Conv->setInvalidDecl(); 11269 return; 11270 } 11271 11272 // Create the return statement that returns the block from the conversion 11273 // function. 11274 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11275 if (Return.isInvalid()) { 11276 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11277 Conv->setInvalidDecl(); 11278 return; 11279 } 11280 11281 // Set the body of the conversion function. 11282 Stmt *ReturnS = Return.get(); 11283 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11284 Conv->getLocation(), 11285 Conv->getLocation())); 11286 11287 // We're done; notify the mutation listener, if any. 11288 if (ASTMutationListener *L = getASTMutationListener()) { 11289 L->CompletedImplicitDefinition(Conv); 11290 } 11291 } 11292 11293 /// \brief Determine whether the given list arguments contains exactly one 11294 /// "real" (non-default) argument. 11295 static bool hasOneRealArgument(MultiExprArg Args) { 11296 switch (Args.size()) { 11297 case 0: 11298 return false; 11299 11300 default: 11301 if (!Args[1]->isDefaultArgument()) 11302 return false; 11303 11304 // fall through 11305 case 1: 11306 return !Args[0]->isDefaultArgument(); 11307 } 11308 11309 return false; 11310 } 11311 11312 ExprResult 11313 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11314 CXXConstructorDecl *Constructor, 11315 MultiExprArg ExprArgs, 11316 bool HadMultipleCandidates, 11317 bool IsListInitialization, 11318 bool IsStdInitListInitialization, 11319 bool RequiresZeroInit, 11320 unsigned ConstructKind, 11321 SourceRange ParenRange) { 11322 bool Elidable = false; 11323 11324 // C++0x [class.copy]p34: 11325 // When certain criteria are met, an implementation is allowed to 11326 // omit the copy/move construction of a class object, even if the 11327 // copy/move constructor and/or destructor for the object have 11328 // side effects. [...] 11329 // - when a temporary class object that has not been bound to a 11330 // reference (12.2) would be copied/moved to a class object 11331 // with the same cv-unqualified type, the copy/move operation 11332 // can be omitted by constructing the temporary object 11333 // directly into the target of the omitted copy/move 11334 if (ConstructKind == CXXConstructExpr::CK_Complete && 11335 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11336 Expr *SubExpr = ExprArgs[0]; 11337 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11338 } 11339 11340 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11341 Elidable, ExprArgs, HadMultipleCandidates, 11342 IsListInitialization, 11343 IsStdInitListInitialization, RequiresZeroInit, 11344 ConstructKind, ParenRange); 11345 } 11346 11347 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11348 /// including handling of its default argument expressions. 11349 ExprResult 11350 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11351 CXXConstructorDecl *Constructor, bool Elidable, 11352 MultiExprArg ExprArgs, 11353 bool HadMultipleCandidates, 11354 bool IsListInitialization, 11355 bool IsStdInitListInitialization, 11356 bool RequiresZeroInit, 11357 unsigned ConstructKind, 11358 SourceRange ParenRange) { 11359 MarkFunctionReferenced(ConstructLoc, Constructor); 11360 return CXXConstructExpr::Create( 11361 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11362 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11363 RequiresZeroInit, 11364 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11365 ParenRange); 11366 } 11367 11368 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11369 assert(Field->hasInClassInitializer()); 11370 11371 // If we already have the in-class initializer nothing needs to be done. 11372 if (Field->getInClassInitializer()) 11373 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11374 11375 // Maybe we haven't instantiated the in-class initializer. Go check the 11376 // pattern FieldDecl to see if it has one. 11377 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11378 11379 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11380 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11381 DeclContext::lookup_result Lookup = 11382 ClassPattern->lookup(Field->getDeclName()); 11383 assert(Lookup.size() == 1); 11384 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11385 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11386 getTemplateInstantiationArgs(Field))) 11387 return ExprError(); 11388 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11389 } 11390 11391 // DR1351: 11392 // If the brace-or-equal-initializer of a non-static data member 11393 // invokes a defaulted default constructor of its class or of an 11394 // enclosing class in a potentially evaluated subexpression, the 11395 // program is ill-formed. 11396 // 11397 // This resolution is unworkable: the exception specification of the 11398 // default constructor can be needed in an unevaluated context, in 11399 // particular, in the operand of a noexcept-expression, and we can be 11400 // unable to compute an exception specification for an enclosed class. 11401 // 11402 // Any attempt to resolve the exception specification of a defaulted default 11403 // constructor before the initializer is lexically complete will ultimately 11404 // come here at which point we can diagnose it. 11405 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11406 if (OutermostClass == ParentRD) { 11407 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11408 << ParentRD << Field; 11409 } else { 11410 Diag(Field->getLocEnd(), 11411 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11412 << ParentRD << OutermostClass << Field; 11413 } 11414 11415 return ExprError(); 11416 } 11417 11418 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11419 if (VD->isInvalidDecl()) return; 11420 11421 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11422 if (ClassDecl->isInvalidDecl()) return; 11423 if (ClassDecl->hasIrrelevantDestructor()) return; 11424 if (ClassDecl->isDependentContext()) return; 11425 11426 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11427 MarkFunctionReferenced(VD->getLocation(), Destructor); 11428 CheckDestructorAccess(VD->getLocation(), Destructor, 11429 PDiag(diag::err_access_dtor_var) 11430 << VD->getDeclName() 11431 << VD->getType()); 11432 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11433 11434 if (Destructor->isTrivial()) return; 11435 if (!VD->hasGlobalStorage()) return; 11436 11437 // Emit warning for non-trivial dtor in global scope (a real global, 11438 // class-static, function-static). 11439 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11440 11441 // TODO: this should be re-enabled for static locals by !CXAAtExit 11442 if (!VD->isStaticLocal()) 11443 Diag(VD->getLocation(), diag::warn_global_destructor); 11444 } 11445 11446 /// \brief Given a constructor and the set of arguments provided for the 11447 /// constructor, convert the arguments and add any required default arguments 11448 /// to form a proper call to this constructor. 11449 /// 11450 /// \returns true if an error occurred, false otherwise. 11451 bool 11452 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11453 MultiExprArg ArgsPtr, 11454 SourceLocation Loc, 11455 SmallVectorImpl<Expr*> &ConvertedArgs, 11456 bool AllowExplicit, 11457 bool IsListInitialization) { 11458 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11459 unsigned NumArgs = ArgsPtr.size(); 11460 Expr **Args = ArgsPtr.data(); 11461 11462 const FunctionProtoType *Proto 11463 = Constructor->getType()->getAs<FunctionProtoType>(); 11464 assert(Proto && "Constructor without a prototype?"); 11465 unsigned NumParams = Proto->getNumParams(); 11466 11467 // If too few arguments are available, we'll fill in the rest with defaults. 11468 if (NumArgs < NumParams) 11469 ConvertedArgs.reserve(NumParams); 11470 else 11471 ConvertedArgs.reserve(NumArgs); 11472 11473 VariadicCallType CallType = 11474 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11475 SmallVector<Expr *, 8> AllArgs; 11476 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11477 Proto, 0, 11478 llvm::makeArrayRef(Args, NumArgs), 11479 AllArgs, 11480 CallType, AllowExplicit, 11481 IsListInitialization); 11482 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11483 11484 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11485 11486 CheckConstructorCall(Constructor, 11487 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11488 Proto, Loc); 11489 11490 return Invalid; 11491 } 11492 11493 static inline bool 11494 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11495 const FunctionDecl *FnDecl) { 11496 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11497 if (isa<NamespaceDecl>(DC)) { 11498 return SemaRef.Diag(FnDecl->getLocation(), 11499 diag::err_operator_new_delete_declared_in_namespace) 11500 << FnDecl->getDeclName(); 11501 } 11502 11503 if (isa<TranslationUnitDecl>(DC) && 11504 FnDecl->getStorageClass() == SC_Static) { 11505 return SemaRef.Diag(FnDecl->getLocation(), 11506 diag::err_operator_new_delete_declared_static) 11507 << FnDecl->getDeclName(); 11508 } 11509 11510 return false; 11511 } 11512 11513 static inline bool 11514 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11515 CanQualType ExpectedResultType, 11516 CanQualType ExpectedFirstParamType, 11517 unsigned DependentParamTypeDiag, 11518 unsigned InvalidParamTypeDiag) { 11519 QualType ResultType = 11520 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11521 11522 // Check that the result type is not dependent. 11523 if (ResultType->isDependentType()) 11524 return SemaRef.Diag(FnDecl->getLocation(), 11525 diag::err_operator_new_delete_dependent_result_type) 11526 << FnDecl->getDeclName() << ExpectedResultType; 11527 11528 // Check that the result type is what we expect. 11529 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11530 return SemaRef.Diag(FnDecl->getLocation(), 11531 diag::err_operator_new_delete_invalid_result_type) 11532 << FnDecl->getDeclName() << ExpectedResultType; 11533 11534 // A function template must have at least 2 parameters. 11535 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11536 return SemaRef.Diag(FnDecl->getLocation(), 11537 diag::err_operator_new_delete_template_too_few_parameters) 11538 << FnDecl->getDeclName(); 11539 11540 // The function decl must have at least 1 parameter. 11541 if (FnDecl->getNumParams() == 0) 11542 return SemaRef.Diag(FnDecl->getLocation(), 11543 diag::err_operator_new_delete_too_few_parameters) 11544 << FnDecl->getDeclName(); 11545 11546 // Check the first parameter type is not dependent. 11547 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11548 if (FirstParamType->isDependentType()) 11549 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11550 << FnDecl->getDeclName() << ExpectedFirstParamType; 11551 11552 // Check that the first parameter type is what we expect. 11553 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11554 ExpectedFirstParamType) 11555 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11556 << FnDecl->getDeclName() << ExpectedFirstParamType; 11557 11558 return false; 11559 } 11560 11561 static bool 11562 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11563 // C++ [basic.stc.dynamic.allocation]p1: 11564 // A program is ill-formed if an allocation function is declared in a 11565 // namespace scope other than global scope or declared static in global 11566 // scope. 11567 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11568 return true; 11569 11570 CanQualType SizeTy = 11571 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11572 11573 // C++ [basic.stc.dynamic.allocation]p1: 11574 // The return type shall be void*. The first parameter shall have type 11575 // std::size_t. 11576 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11577 SizeTy, 11578 diag::err_operator_new_dependent_param_type, 11579 diag::err_operator_new_param_type)) 11580 return true; 11581 11582 // C++ [basic.stc.dynamic.allocation]p1: 11583 // The first parameter shall not have an associated default argument. 11584 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11585 return SemaRef.Diag(FnDecl->getLocation(), 11586 diag::err_operator_new_default_arg) 11587 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11588 11589 return false; 11590 } 11591 11592 static bool 11593 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11594 // C++ [basic.stc.dynamic.deallocation]p1: 11595 // A program is ill-formed if deallocation functions are declared in a 11596 // namespace scope other than global scope or declared static in global 11597 // scope. 11598 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11599 return true; 11600 11601 // C++ [basic.stc.dynamic.deallocation]p2: 11602 // Each deallocation function shall return void and its first parameter 11603 // shall be void*. 11604 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11605 SemaRef.Context.VoidPtrTy, 11606 diag::err_operator_delete_dependent_param_type, 11607 diag::err_operator_delete_param_type)) 11608 return true; 11609 11610 return false; 11611 } 11612 11613 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11614 /// of this overloaded operator is well-formed. If so, returns false; 11615 /// otherwise, emits appropriate diagnostics and returns true. 11616 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11617 assert(FnDecl && FnDecl->isOverloadedOperator() && 11618 "Expected an overloaded operator declaration"); 11619 11620 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11621 11622 // C++ [over.oper]p5: 11623 // The allocation and deallocation functions, operator new, 11624 // operator new[], operator delete and operator delete[], are 11625 // described completely in 3.7.3. The attributes and restrictions 11626 // found in the rest of this subclause do not apply to them unless 11627 // explicitly stated in 3.7.3. 11628 if (Op == OO_Delete || Op == OO_Array_Delete) 11629 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11630 11631 if (Op == OO_New || Op == OO_Array_New) 11632 return CheckOperatorNewDeclaration(*this, FnDecl); 11633 11634 // C++ [over.oper]p6: 11635 // An operator function shall either be a non-static member 11636 // function or be a non-member function and have at least one 11637 // parameter whose type is a class, a reference to a class, an 11638 // enumeration, or a reference to an enumeration. 11639 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11640 if (MethodDecl->isStatic()) 11641 return Diag(FnDecl->getLocation(), 11642 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11643 } else { 11644 bool ClassOrEnumParam = false; 11645 for (auto Param : FnDecl->params()) { 11646 QualType ParamType = Param->getType().getNonReferenceType(); 11647 if (ParamType->isDependentType() || ParamType->isRecordType() || 11648 ParamType->isEnumeralType()) { 11649 ClassOrEnumParam = true; 11650 break; 11651 } 11652 } 11653 11654 if (!ClassOrEnumParam) 11655 return Diag(FnDecl->getLocation(), 11656 diag::err_operator_overload_needs_class_or_enum) 11657 << FnDecl->getDeclName(); 11658 } 11659 11660 // C++ [over.oper]p8: 11661 // An operator function cannot have default arguments (8.3.6), 11662 // except where explicitly stated below. 11663 // 11664 // Only the function-call operator allows default arguments 11665 // (C++ [over.call]p1). 11666 if (Op != OO_Call) { 11667 for (auto Param : FnDecl->params()) { 11668 if (Param->hasDefaultArg()) 11669 return Diag(Param->getLocation(), 11670 diag::err_operator_overload_default_arg) 11671 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11672 } 11673 } 11674 11675 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11676 { false, false, false } 11677 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11678 , { Unary, Binary, MemberOnly } 11679 #include "clang/Basic/OperatorKinds.def" 11680 }; 11681 11682 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11683 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11684 bool MustBeMemberOperator = OperatorUses[Op][2]; 11685 11686 // C++ [over.oper]p8: 11687 // [...] Operator functions cannot have more or fewer parameters 11688 // than the number required for the corresponding operator, as 11689 // described in the rest of this subclause. 11690 unsigned NumParams = FnDecl->getNumParams() 11691 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11692 if (Op != OO_Call && 11693 ((NumParams == 1 && !CanBeUnaryOperator) || 11694 (NumParams == 2 && !CanBeBinaryOperator) || 11695 (NumParams < 1) || (NumParams > 2))) { 11696 // We have the wrong number of parameters. 11697 unsigned ErrorKind; 11698 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11699 ErrorKind = 2; // 2 -> unary or binary. 11700 } else if (CanBeUnaryOperator) { 11701 ErrorKind = 0; // 0 -> unary 11702 } else { 11703 assert(CanBeBinaryOperator && 11704 "All non-call overloaded operators are unary or binary!"); 11705 ErrorKind = 1; // 1 -> binary 11706 } 11707 11708 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11709 << FnDecl->getDeclName() << NumParams << ErrorKind; 11710 } 11711 11712 // Overloaded operators other than operator() cannot be variadic. 11713 if (Op != OO_Call && 11714 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11715 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11716 << FnDecl->getDeclName(); 11717 } 11718 11719 // Some operators must be non-static member functions. 11720 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11721 return Diag(FnDecl->getLocation(), 11722 diag::err_operator_overload_must_be_member) 11723 << FnDecl->getDeclName(); 11724 } 11725 11726 // C++ [over.inc]p1: 11727 // The user-defined function called operator++ implements the 11728 // prefix and postfix ++ operator. If this function is a member 11729 // function with no parameters, or a non-member function with one 11730 // parameter of class or enumeration type, it defines the prefix 11731 // increment operator ++ for objects of that type. If the function 11732 // is a member function with one parameter (which shall be of type 11733 // int) or a non-member function with two parameters (the second 11734 // of which shall be of type int), it defines the postfix 11735 // increment operator ++ for objects of that type. 11736 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11737 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11738 QualType ParamType = LastParam->getType(); 11739 11740 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11741 !ParamType->isDependentType()) 11742 return Diag(LastParam->getLocation(), 11743 diag::err_operator_overload_post_incdec_must_be_int) 11744 << LastParam->getType() << (Op == OO_MinusMinus); 11745 } 11746 11747 return false; 11748 } 11749 11750 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11751 /// of this literal operator function is well-formed. If so, returns 11752 /// false; otherwise, emits appropriate diagnostics and returns true. 11753 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11754 if (isa<CXXMethodDecl>(FnDecl)) { 11755 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11756 << FnDecl->getDeclName(); 11757 return true; 11758 } 11759 11760 if (FnDecl->isExternC()) { 11761 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11762 return true; 11763 } 11764 11765 bool Valid = false; 11766 11767 // This might be the definition of a literal operator template. 11768 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11769 // This might be a specialization of a literal operator template. 11770 if (!TpDecl) 11771 TpDecl = FnDecl->getPrimaryTemplate(); 11772 11773 // template <char...> type operator "" name() and 11774 // template <class T, T...> type operator "" name() are the only valid 11775 // template signatures, and the only valid signatures with no parameters. 11776 if (TpDecl) { 11777 if (FnDecl->param_size() == 0) { 11778 // Must have one or two template parameters 11779 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11780 if (Params->size() == 1) { 11781 NonTypeTemplateParmDecl *PmDecl = 11782 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11783 11784 // The template parameter must be a char parameter pack. 11785 if (PmDecl && PmDecl->isTemplateParameterPack() && 11786 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11787 Valid = true; 11788 } else if (Params->size() == 2) { 11789 TemplateTypeParmDecl *PmType = 11790 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11791 NonTypeTemplateParmDecl *PmArgs = 11792 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11793 11794 // The second template parameter must be a parameter pack with the 11795 // first template parameter as its type. 11796 if (PmType && PmArgs && 11797 !PmType->isTemplateParameterPack() && 11798 PmArgs->isTemplateParameterPack()) { 11799 const TemplateTypeParmType *TArgs = 11800 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11801 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11802 TArgs->getIndex() == PmType->getIndex()) { 11803 Valid = true; 11804 if (ActiveTemplateInstantiations.empty()) 11805 Diag(FnDecl->getLocation(), 11806 diag::ext_string_literal_operator_template); 11807 } 11808 } 11809 } 11810 } 11811 } else if (FnDecl->param_size()) { 11812 // Check the first parameter 11813 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11814 11815 QualType T = (*Param)->getType().getUnqualifiedType(); 11816 11817 // unsigned long long int, long double, and any character type are allowed 11818 // as the only parameters. 11819 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11820 Context.hasSameType(T, Context.LongDoubleTy) || 11821 Context.hasSameType(T, Context.CharTy) || 11822 Context.hasSameType(T, Context.WideCharTy) || 11823 Context.hasSameType(T, Context.Char16Ty) || 11824 Context.hasSameType(T, Context.Char32Ty)) { 11825 if (++Param == FnDecl->param_end()) 11826 Valid = true; 11827 goto FinishedParams; 11828 } 11829 11830 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11831 const PointerType *PT = T->getAs<PointerType>(); 11832 if (!PT) 11833 goto FinishedParams; 11834 T = PT->getPointeeType(); 11835 if (!T.isConstQualified() || T.isVolatileQualified()) 11836 goto FinishedParams; 11837 T = T.getUnqualifiedType(); 11838 11839 // Move on to the second parameter; 11840 ++Param; 11841 11842 // If there is no second parameter, the first must be a const char * 11843 if (Param == FnDecl->param_end()) { 11844 if (Context.hasSameType(T, Context.CharTy)) 11845 Valid = true; 11846 goto FinishedParams; 11847 } 11848 11849 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11850 // are allowed as the first parameter to a two-parameter function 11851 if (!(Context.hasSameType(T, Context.CharTy) || 11852 Context.hasSameType(T, Context.WideCharTy) || 11853 Context.hasSameType(T, Context.Char16Ty) || 11854 Context.hasSameType(T, Context.Char32Ty))) 11855 goto FinishedParams; 11856 11857 // The second and final parameter must be an std::size_t 11858 T = (*Param)->getType().getUnqualifiedType(); 11859 if (Context.hasSameType(T, Context.getSizeType()) && 11860 ++Param == FnDecl->param_end()) 11861 Valid = true; 11862 } 11863 11864 // FIXME: This diagnostic is absolutely terrible. 11865 FinishedParams: 11866 if (!Valid) { 11867 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11868 << FnDecl->getDeclName(); 11869 return true; 11870 } 11871 11872 // A parameter-declaration-clause containing a default argument is not 11873 // equivalent to any of the permitted forms. 11874 for (auto Param : FnDecl->params()) { 11875 if (Param->hasDefaultArg()) { 11876 Diag(Param->getDefaultArgRange().getBegin(), 11877 diag::err_literal_operator_default_argument) 11878 << Param->getDefaultArgRange(); 11879 break; 11880 } 11881 } 11882 11883 StringRef LiteralName 11884 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11885 if (LiteralName[0] != '_') { 11886 // C++11 [usrlit.suffix]p1: 11887 // Literal suffix identifiers that do not start with an underscore 11888 // are reserved for future standardization. 11889 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11890 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11891 } 11892 11893 return false; 11894 } 11895 11896 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11897 /// linkage specification, including the language and (if present) 11898 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11899 /// language string literal. LBraceLoc, if valid, provides the location of 11900 /// the '{' brace. Otherwise, this linkage specification does not 11901 /// have any braces. 11902 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11903 Expr *LangStr, 11904 SourceLocation LBraceLoc) { 11905 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11906 if (!Lit->isAscii()) { 11907 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11908 << LangStr->getSourceRange(); 11909 return nullptr; 11910 } 11911 11912 StringRef Lang = Lit->getString(); 11913 LinkageSpecDecl::LanguageIDs Language; 11914 if (Lang == "C") 11915 Language = LinkageSpecDecl::lang_c; 11916 else if (Lang == "C++") 11917 Language = LinkageSpecDecl::lang_cxx; 11918 else { 11919 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11920 << LangStr->getSourceRange(); 11921 return nullptr; 11922 } 11923 11924 // FIXME: Add all the various semantics of linkage specifications 11925 11926 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11927 LangStr->getExprLoc(), Language, 11928 LBraceLoc.isValid()); 11929 CurContext->addDecl(D); 11930 PushDeclContext(S, D); 11931 return D; 11932 } 11933 11934 /// ActOnFinishLinkageSpecification - Complete the definition of 11935 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11936 /// valid, it's the position of the closing '}' brace in a linkage 11937 /// specification that uses braces. 11938 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11939 Decl *LinkageSpec, 11940 SourceLocation RBraceLoc) { 11941 if (RBraceLoc.isValid()) { 11942 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11943 LSDecl->setRBraceLoc(RBraceLoc); 11944 } 11945 PopDeclContext(); 11946 return LinkageSpec; 11947 } 11948 11949 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11950 AttributeList *AttrList, 11951 SourceLocation SemiLoc) { 11952 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11953 // Attribute declarations appertain to empty declaration so we handle 11954 // them here. 11955 if (AttrList) 11956 ProcessDeclAttributeList(S, ED, AttrList); 11957 11958 CurContext->addDecl(ED); 11959 return ED; 11960 } 11961 11962 /// \brief Perform semantic analysis for the variable declaration that 11963 /// occurs within a C++ catch clause, returning the newly-created 11964 /// variable. 11965 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11966 TypeSourceInfo *TInfo, 11967 SourceLocation StartLoc, 11968 SourceLocation Loc, 11969 IdentifierInfo *Name) { 11970 bool Invalid = false; 11971 QualType ExDeclType = TInfo->getType(); 11972 11973 // Arrays and functions decay. 11974 if (ExDeclType->isArrayType()) 11975 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11976 else if (ExDeclType->isFunctionType()) 11977 ExDeclType = Context.getPointerType(ExDeclType); 11978 11979 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11980 // The exception-declaration shall not denote a pointer or reference to an 11981 // incomplete type, other than [cv] void*. 11982 // N2844 forbids rvalue references. 11983 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11984 Diag(Loc, diag::err_catch_rvalue_ref); 11985 Invalid = true; 11986 } 11987 11988 QualType BaseType = ExDeclType; 11989 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11990 unsigned DK = diag::err_catch_incomplete; 11991 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11992 BaseType = Ptr->getPointeeType(); 11993 Mode = 1; 11994 DK = diag::err_catch_incomplete_ptr; 11995 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11996 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11997 BaseType = Ref->getPointeeType(); 11998 Mode = 2; 11999 DK = diag::err_catch_incomplete_ref; 12000 } 12001 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 12002 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 12003 Invalid = true; 12004 12005 if (!Invalid && !ExDeclType->isDependentType() && 12006 RequireNonAbstractType(Loc, ExDeclType, 12007 diag::err_abstract_type_in_decl, 12008 AbstractVariableType)) 12009 Invalid = true; 12010 12011 // Only the non-fragile NeXT runtime currently supports C++ catches 12012 // of ObjC types, and no runtime supports catching ObjC types by value. 12013 if (!Invalid && getLangOpts().ObjC1) { 12014 QualType T = ExDeclType; 12015 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 12016 T = RT->getPointeeType(); 12017 12018 if (T->isObjCObjectType()) { 12019 Diag(Loc, diag::err_objc_object_catch); 12020 Invalid = true; 12021 } else if (T->isObjCObjectPointerType()) { 12022 // FIXME: should this be a test for macosx-fragile specifically? 12023 if (getLangOpts().ObjCRuntime.isFragile()) 12024 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 12025 } 12026 } 12027 12028 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 12029 ExDeclType, TInfo, SC_None); 12030 ExDecl->setExceptionVariable(true); 12031 12032 // In ARC, infer 'retaining' for variables of retainable type. 12033 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 12034 Invalid = true; 12035 12036 if (!Invalid && !ExDeclType->isDependentType()) { 12037 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 12038 // Insulate this from anything else we might currently be parsing. 12039 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 12040 12041 // C++ [except.handle]p16: 12042 // The object declared in an exception-declaration or, if the 12043 // exception-declaration does not specify a name, a temporary (12.2) is 12044 // copy-initialized (8.5) from the exception object. [...] 12045 // The object is destroyed when the handler exits, after the destruction 12046 // of any automatic objects initialized within the handler. 12047 // 12048 // We just pretend to initialize the object with itself, then make sure 12049 // it can be destroyed later. 12050 QualType initType = Context.getExceptionObjectType(ExDeclType); 12051 12052 InitializedEntity entity = 12053 InitializedEntity::InitializeVariable(ExDecl); 12054 InitializationKind initKind = 12055 InitializationKind::CreateCopy(Loc, SourceLocation()); 12056 12057 Expr *opaqueValue = 12058 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 12059 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 12060 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 12061 if (result.isInvalid()) 12062 Invalid = true; 12063 else { 12064 // If the constructor used was non-trivial, set this as the 12065 // "initializer". 12066 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 12067 if (!construct->getConstructor()->isTrivial()) { 12068 Expr *init = MaybeCreateExprWithCleanups(construct); 12069 ExDecl->setInit(init); 12070 } 12071 12072 // And make sure it's destructable. 12073 FinalizeVarWithDestructor(ExDecl, recordType); 12074 } 12075 } 12076 } 12077 12078 if (Invalid) 12079 ExDecl->setInvalidDecl(); 12080 12081 return ExDecl; 12082 } 12083 12084 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 12085 /// handler. 12086 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 12087 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12088 bool Invalid = D.isInvalidType(); 12089 12090 // Check for unexpanded parameter packs. 12091 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12092 UPPC_ExceptionType)) { 12093 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12094 D.getIdentifierLoc()); 12095 Invalid = true; 12096 } 12097 12098 IdentifierInfo *II = D.getIdentifier(); 12099 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 12100 LookupOrdinaryName, 12101 ForRedeclaration)) { 12102 // The scope should be freshly made just for us. There is just no way 12103 // it contains any previous declaration, except for function parameters in 12104 // a function-try-block's catch statement. 12105 assert(!S->isDeclScope(PrevDecl)); 12106 if (isDeclInScope(PrevDecl, CurContext, S)) { 12107 Diag(D.getIdentifierLoc(), diag::err_redefinition) 12108 << D.getIdentifier(); 12109 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12110 Invalid = true; 12111 } else if (PrevDecl->isTemplateParameter()) 12112 // Maybe we will complain about the shadowed template parameter. 12113 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12114 } 12115 12116 if (D.getCXXScopeSpec().isSet() && !Invalid) { 12117 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 12118 << D.getCXXScopeSpec().getRange(); 12119 Invalid = true; 12120 } 12121 12122 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 12123 D.getLocStart(), 12124 D.getIdentifierLoc(), 12125 D.getIdentifier()); 12126 if (Invalid) 12127 ExDecl->setInvalidDecl(); 12128 12129 // Add the exception declaration into this scope. 12130 if (II) 12131 PushOnScopeChains(ExDecl, S); 12132 else 12133 CurContext->addDecl(ExDecl); 12134 12135 ProcessDeclAttributes(S, ExDecl, D); 12136 return ExDecl; 12137 } 12138 12139 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12140 Expr *AssertExpr, 12141 Expr *AssertMessageExpr, 12142 SourceLocation RParenLoc) { 12143 StringLiteral *AssertMessage = 12144 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 12145 12146 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 12147 return nullptr; 12148 12149 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 12150 AssertMessage, RParenLoc, false); 12151 } 12152 12153 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12154 Expr *AssertExpr, 12155 StringLiteral *AssertMessage, 12156 SourceLocation RParenLoc, 12157 bool Failed) { 12158 assert(AssertExpr != nullptr && "Expected non-null condition"); 12159 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 12160 !Failed) { 12161 // In a static_assert-declaration, the constant-expression shall be a 12162 // constant expression that can be contextually converted to bool. 12163 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 12164 if (Converted.isInvalid()) 12165 Failed = true; 12166 12167 llvm::APSInt Cond; 12168 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 12169 diag::err_static_assert_expression_is_not_constant, 12170 /*AllowFold=*/false).isInvalid()) 12171 Failed = true; 12172 12173 if (!Failed && !Cond) { 12174 SmallString<256> MsgBuffer; 12175 llvm::raw_svector_ostream Msg(MsgBuffer); 12176 if (AssertMessage) 12177 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 12178 Diag(StaticAssertLoc, diag::err_static_assert_failed) 12179 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 12180 Failed = true; 12181 } 12182 } 12183 12184 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 12185 AssertExpr, AssertMessage, RParenLoc, 12186 Failed); 12187 12188 CurContext->addDecl(Decl); 12189 return Decl; 12190 } 12191 12192 /// \brief Perform semantic analysis of the given friend type declaration. 12193 /// 12194 /// \returns A friend declaration that. 12195 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 12196 SourceLocation FriendLoc, 12197 TypeSourceInfo *TSInfo) { 12198 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 12199 12200 QualType T = TSInfo->getType(); 12201 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 12202 12203 // C++03 [class.friend]p2: 12204 // An elaborated-type-specifier shall be used in a friend declaration 12205 // for a class.* 12206 // 12207 // * The class-key of the elaborated-type-specifier is required. 12208 if (!ActiveTemplateInstantiations.empty()) { 12209 // Do not complain about the form of friend template types during 12210 // template instantiation; we will already have complained when the 12211 // template was declared. 12212 } else { 12213 if (!T->isElaboratedTypeSpecifier()) { 12214 // If we evaluated the type to a record type, suggest putting 12215 // a tag in front. 12216 if (const RecordType *RT = T->getAs<RecordType>()) { 12217 RecordDecl *RD = RT->getDecl(); 12218 12219 SmallString<16> InsertionText(" "); 12220 InsertionText += RD->getKindName(); 12221 12222 Diag(TypeRange.getBegin(), 12223 getLangOpts().CPlusPlus11 ? 12224 diag::warn_cxx98_compat_unelaborated_friend_type : 12225 diag::ext_unelaborated_friend_type) 12226 << (unsigned) RD->getTagKind() 12227 << T 12228 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 12229 InsertionText); 12230 } else { 12231 Diag(FriendLoc, 12232 getLangOpts().CPlusPlus11 ? 12233 diag::warn_cxx98_compat_nonclass_type_friend : 12234 diag::ext_nonclass_type_friend) 12235 << T 12236 << TypeRange; 12237 } 12238 } else if (T->getAs<EnumType>()) { 12239 Diag(FriendLoc, 12240 getLangOpts().CPlusPlus11 ? 12241 diag::warn_cxx98_compat_enum_friend : 12242 diag::ext_enum_friend) 12243 << T 12244 << TypeRange; 12245 } 12246 12247 // C++11 [class.friend]p3: 12248 // A friend declaration that does not declare a function shall have one 12249 // of the following forms: 12250 // friend elaborated-type-specifier ; 12251 // friend simple-type-specifier ; 12252 // friend typename-specifier ; 12253 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12254 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12255 } 12256 12257 // If the type specifier in a friend declaration designates a (possibly 12258 // cv-qualified) class type, that class is declared as a friend; otherwise, 12259 // the friend declaration is ignored. 12260 return FriendDecl::Create(Context, CurContext, 12261 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12262 FriendLoc); 12263 } 12264 12265 /// Handle a friend tag declaration where the scope specifier was 12266 /// templated. 12267 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12268 unsigned TagSpec, SourceLocation TagLoc, 12269 CXXScopeSpec &SS, 12270 IdentifierInfo *Name, 12271 SourceLocation NameLoc, 12272 AttributeList *Attr, 12273 MultiTemplateParamsArg TempParamLists) { 12274 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12275 12276 bool isExplicitSpecialization = false; 12277 bool Invalid = false; 12278 12279 if (TemplateParameterList *TemplateParams = 12280 MatchTemplateParametersToScopeSpecifier( 12281 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12282 isExplicitSpecialization, Invalid)) { 12283 if (TemplateParams->size() > 0) { 12284 // This is a declaration of a class template. 12285 if (Invalid) 12286 return nullptr; 12287 12288 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12289 NameLoc, Attr, TemplateParams, AS_public, 12290 /*ModulePrivateLoc=*/SourceLocation(), 12291 FriendLoc, TempParamLists.size() - 1, 12292 TempParamLists.data()).get(); 12293 } else { 12294 // The "template<>" header is extraneous. 12295 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12296 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12297 isExplicitSpecialization = true; 12298 } 12299 } 12300 12301 if (Invalid) return nullptr; 12302 12303 bool isAllExplicitSpecializations = true; 12304 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12305 if (TempParamLists[I]->size()) { 12306 isAllExplicitSpecializations = false; 12307 break; 12308 } 12309 } 12310 12311 // FIXME: don't ignore attributes. 12312 12313 // If it's explicit specializations all the way down, just forget 12314 // about the template header and build an appropriate non-templated 12315 // friend. TODO: for source fidelity, remember the headers. 12316 if (isAllExplicitSpecializations) { 12317 if (SS.isEmpty()) { 12318 bool Owned = false; 12319 bool IsDependent = false; 12320 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12321 Attr, AS_public, 12322 /*ModulePrivateLoc=*/SourceLocation(), 12323 MultiTemplateParamsArg(), Owned, IsDependent, 12324 /*ScopedEnumKWLoc=*/SourceLocation(), 12325 /*ScopedEnumUsesClassTag=*/false, 12326 /*UnderlyingType=*/TypeResult(), 12327 /*IsTypeSpecifier=*/false); 12328 } 12329 12330 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12331 ElaboratedTypeKeyword Keyword 12332 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12333 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12334 *Name, NameLoc); 12335 if (T.isNull()) 12336 return nullptr; 12337 12338 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12339 if (isa<DependentNameType>(T)) { 12340 DependentNameTypeLoc TL = 12341 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12342 TL.setElaboratedKeywordLoc(TagLoc); 12343 TL.setQualifierLoc(QualifierLoc); 12344 TL.setNameLoc(NameLoc); 12345 } else { 12346 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12347 TL.setElaboratedKeywordLoc(TagLoc); 12348 TL.setQualifierLoc(QualifierLoc); 12349 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12350 } 12351 12352 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12353 TSI, FriendLoc, TempParamLists); 12354 Friend->setAccess(AS_public); 12355 CurContext->addDecl(Friend); 12356 return Friend; 12357 } 12358 12359 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12360 12361 12362 12363 // Handle the case of a templated-scope friend class. e.g. 12364 // template <class T> class A<T>::B; 12365 // FIXME: we don't support these right now. 12366 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12367 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12368 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12369 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12370 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12371 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12372 TL.setElaboratedKeywordLoc(TagLoc); 12373 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12374 TL.setNameLoc(NameLoc); 12375 12376 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12377 TSI, FriendLoc, TempParamLists); 12378 Friend->setAccess(AS_public); 12379 Friend->setUnsupportedFriend(true); 12380 CurContext->addDecl(Friend); 12381 return Friend; 12382 } 12383 12384 12385 /// Handle a friend type declaration. This works in tandem with 12386 /// ActOnTag. 12387 /// 12388 /// Notes on friend class templates: 12389 /// 12390 /// We generally treat friend class declarations as if they were 12391 /// declaring a class. So, for example, the elaborated type specifier 12392 /// in a friend declaration is required to obey the restrictions of a 12393 /// class-head (i.e. no typedefs in the scope chain), template 12394 /// parameters are required to match up with simple template-ids, &c. 12395 /// However, unlike when declaring a template specialization, it's 12396 /// okay to refer to a template specialization without an empty 12397 /// template parameter declaration, e.g. 12398 /// friend class A<T>::B<unsigned>; 12399 /// We permit this as a special case; if there are any template 12400 /// parameters present at all, require proper matching, i.e. 12401 /// template <> template \<class T> friend class A<int>::B; 12402 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12403 MultiTemplateParamsArg TempParams) { 12404 SourceLocation Loc = DS.getLocStart(); 12405 12406 assert(DS.isFriendSpecified()); 12407 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12408 12409 // Try to convert the decl specifier to a type. This works for 12410 // friend templates because ActOnTag never produces a ClassTemplateDecl 12411 // for a TUK_Friend. 12412 Declarator TheDeclarator(DS, Declarator::MemberContext); 12413 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12414 QualType T = TSI->getType(); 12415 if (TheDeclarator.isInvalidType()) 12416 return nullptr; 12417 12418 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12419 return nullptr; 12420 12421 // This is definitely an error in C++98. It's probably meant to 12422 // be forbidden in C++0x, too, but the specification is just 12423 // poorly written. 12424 // 12425 // The problem is with declarations like the following: 12426 // template <T> friend A<T>::foo; 12427 // where deciding whether a class C is a friend or not now hinges 12428 // on whether there exists an instantiation of A that causes 12429 // 'foo' to equal C. There are restrictions on class-heads 12430 // (which we declare (by fiat) elaborated friend declarations to 12431 // be) that makes this tractable. 12432 // 12433 // FIXME: handle "template <> friend class A<T>;", which 12434 // is possibly well-formed? Who even knows? 12435 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12436 Diag(Loc, diag::err_tagless_friend_type_template) 12437 << DS.getSourceRange(); 12438 return nullptr; 12439 } 12440 12441 // C++98 [class.friend]p1: A friend of a class is a function 12442 // or class that is not a member of the class . . . 12443 // This is fixed in DR77, which just barely didn't make the C++03 12444 // deadline. It's also a very silly restriction that seriously 12445 // affects inner classes and which nobody else seems to implement; 12446 // thus we never diagnose it, not even in -pedantic. 12447 // 12448 // But note that we could warn about it: it's always useless to 12449 // friend one of your own members (it's not, however, worthless to 12450 // friend a member of an arbitrary specialization of your template). 12451 12452 Decl *D; 12453 if (unsigned NumTempParamLists = TempParams.size()) 12454 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12455 NumTempParamLists, 12456 TempParams.data(), 12457 TSI, 12458 DS.getFriendSpecLoc()); 12459 else 12460 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12461 12462 if (!D) 12463 return nullptr; 12464 12465 D->setAccess(AS_public); 12466 CurContext->addDecl(D); 12467 12468 return D; 12469 } 12470 12471 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12472 MultiTemplateParamsArg TemplateParams) { 12473 const DeclSpec &DS = D.getDeclSpec(); 12474 12475 assert(DS.isFriendSpecified()); 12476 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12477 12478 SourceLocation Loc = D.getIdentifierLoc(); 12479 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12480 12481 // C++ [class.friend]p1 12482 // A friend of a class is a function or class.... 12483 // Note that this sees through typedefs, which is intended. 12484 // It *doesn't* see through dependent types, which is correct 12485 // according to [temp.arg.type]p3: 12486 // If a declaration acquires a function type through a 12487 // type dependent on a template-parameter and this causes 12488 // a declaration that does not use the syntactic form of a 12489 // function declarator to have a function type, the program 12490 // is ill-formed. 12491 if (!TInfo->getType()->isFunctionType()) { 12492 Diag(Loc, diag::err_unexpected_friend); 12493 12494 // It might be worthwhile to try to recover by creating an 12495 // appropriate declaration. 12496 return nullptr; 12497 } 12498 12499 // C++ [namespace.memdef]p3 12500 // - If a friend declaration in a non-local class first declares a 12501 // class or function, the friend class or function is a member 12502 // of the innermost enclosing namespace. 12503 // - The name of the friend is not found by simple name lookup 12504 // until a matching declaration is provided in that namespace 12505 // scope (either before or after the class declaration granting 12506 // friendship). 12507 // - If a friend function is called, its name may be found by the 12508 // name lookup that considers functions from namespaces and 12509 // classes associated with the types of the function arguments. 12510 // - When looking for a prior declaration of a class or a function 12511 // declared as a friend, scopes outside the innermost enclosing 12512 // namespace scope are not considered. 12513 12514 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12515 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12516 DeclarationName Name = NameInfo.getName(); 12517 assert(Name); 12518 12519 // Check for unexpanded parameter packs. 12520 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12521 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12522 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12523 return nullptr; 12524 12525 // The context we found the declaration in, or in which we should 12526 // create the declaration. 12527 DeclContext *DC; 12528 Scope *DCScope = S; 12529 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12530 ForRedeclaration); 12531 12532 // There are five cases here. 12533 // - There's no scope specifier and we're in a local class. Only look 12534 // for functions declared in the immediately-enclosing block scope. 12535 // We recover from invalid scope qualifiers as if they just weren't there. 12536 FunctionDecl *FunctionContainingLocalClass = nullptr; 12537 if ((SS.isInvalid() || !SS.isSet()) && 12538 (FunctionContainingLocalClass = 12539 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12540 // C++11 [class.friend]p11: 12541 // If a friend declaration appears in a local class and the name 12542 // specified is an unqualified name, a prior declaration is 12543 // looked up without considering scopes that are outside the 12544 // innermost enclosing non-class scope. For a friend function 12545 // declaration, if there is no prior declaration, the program is 12546 // ill-formed. 12547 12548 // Find the innermost enclosing non-class scope. This is the block 12549 // scope containing the local class definition (or for a nested class, 12550 // the outer local class). 12551 DCScope = S->getFnParent(); 12552 12553 // Look up the function name in the scope. 12554 Previous.clear(LookupLocalFriendName); 12555 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12556 12557 if (!Previous.empty()) { 12558 // All possible previous declarations must have the same context: 12559 // either they were declared at block scope or they are members of 12560 // one of the enclosing local classes. 12561 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12562 } else { 12563 // This is ill-formed, but provide the context that we would have 12564 // declared the function in, if we were permitted to, for error recovery. 12565 DC = FunctionContainingLocalClass; 12566 } 12567 adjustContextForLocalExternDecl(DC); 12568 12569 // C++ [class.friend]p6: 12570 // A function can be defined in a friend declaration of a class if and 12571 // only if the class is a non-local class (9.8), the function name is 12572 // unqualified, and the function has namespace scope. 12573 if (D.isFunctionDefinition()) { 12574 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12575 } 12576 12577 // - There's no scope specifier, in which case we just go to the 12578 // appropriate scope and look for a function or function template 12579 // there as appropriate. 12580 } else if (SS.isInvalid() || !SS.isSet()) { 12581 // C++11 [namespace.memdef]p3: 12582 // If the name in a friend declaration is neither qualified nor 12583 // a template-id and the declaration is a function or an 12584 // elaborated-type-specifier, the lookup to determine whether 12585 // the entity has been previously declared shall not consider 12586 // any scopes outside the innermost enclosing namespace. 12587 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12588 12589 // Find the appropriate context according to the above. 12590 DC = CurContext; 12591 12592 // Skip class contexts. If someone can cite chapter and verse 12593 // for this behavior, that would be nice --- it's what GCC and 12594 // EDG do, and it seems like a reasonable intent, but the spec 12595 // really only says that checks for unqualified existing 12596 // declarations should stop at the nearest enclosing namespace, 12597 // not that they should only consider the nearest enclosing 12598 // namespace. 12599 while (DC->isRecord()) 12600 DC = DC->getParent(); 12601 12602 DeclContext *LookupDC = DC; 12603 while (LookupDC->isTransparentContext()) 12604 LookupDC = LookupDC->getParent(); 12605 12606 while (true) { 12607 LookupQualifiedName(Previous, LookupDC); 12608 12609 if (!Previous.empty()) { 12610 DC = LookupDC; 12611 break; 12612 } 12613 12614 if (isTemplateId) { 12615 if (isa<TranslationUnitDecl>(LookupDC)) break; 12616 } else { 12617 if (LookupDC->isFileContext()) break; 12618 } 12619 LookupDC = LookupDC->getParent(); 12620 } 12621 12622 DCScope = getScopeForDeclContext(S, DC); 12623 12624 // - There's a non-dependent scope specifier, in which case we 12625 // compute it and do a previous lookup there for a function 12626 // or function template. 12627 } else if (!SS.getScopeRep()->isDependent()) { 12628 DC = computeDeclContext(SS); 12629 if (!DC) return nullptr; 12630 12631 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12632 12633 LookupQualifiedName(Previous, DC); 12634 12635 // Ignore things found implicitly in the wrong scope. 12636 // TODO: better diagnostics for this case. Suggesting the right 12637 // qualified scope would be nice... 12638 LookupResult::Filter F = Previous.makeFilter(); 12639 while (F.hasNext()) { 12640 NamedDecl *D = F.next(); 12641 if (!DC->InEnclosingNamespaceSetOf( 12642 D->getDeclContext()->getRedeclContext())) 12643 F.erase(); 12644 } 12645 F.done(); 12646 12647 if (Previous.empty()) { 12648 D.setInvalidType(); 12649 Diag(Loc, diag::err_qualified_friend_not_found) 12650 << Name << TInfo->getType(); 12651 return nullptr; 12652 } 12653 12654 // C++ [class.friend]p1: A friend of a class is a function or 12655 // class that is not a member of the class . . . 12656 if (DC->Equals(CurContext)) 12657 Diag(DS.getFriendSpecLoc(), 12658 getLangOpts().CPlusPlus11 ? 12659 diag::warn_cxx98_compat_friend_is_member : 12660 diag::err_friend_is_member); 12661 12662 if (D.isFunctionDefinition()) { 12663 // C++ [class.friend]p6: 12664 // A function can be defined in a friend declaration of a class if and 12665 // only if the class is a non-local class (9.8), the function name is 12666 // unqualified, and the function has namespace scope. 12667 SemaDiagnosticBuilder DB 12668 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12669 12670 DB << SS.getScopeRep(); 12671 if (DC->isFileContext()) 12672 DB << FixItHint::CreateRemoval(SS.getRange()); 12673 SS.clear(); 12674 } 12675 12676 // - There's a scope specifier that does not match any template 12677 // parameter lists, in which case we use some arbitrary context, 12678 // create a method or method template, and wait for instantiation. 12679 // - There's a scope specifier that does match some template 12680 // parameter lists, which we don't handle right now. 12681 } else { 12682 if (D.isFunctionDefinition()) { 12683 // C++ [class.friend]p6: 12684 // A function can be defined in a friend declaration of a class if and 12685 // only if the class is a non-local class (9.8), the function name is 12686 // unqualified, and the function has namespace scope. 12687 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12688 << SS.getScopeRep(); 12689 } 12690 12691 DC = CurContext; 12692 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12693 } 12694 12695 if (!DC->isRecord()) { 12696 int DiagArg = -1; 12697 switch (D.getName().getKind()) { 12698 case UnqualifiedId::IK_ConstructorTemplateId: 12699 case UnqualifiedId::IK_ConstructorName: 12700 DiagArg = 0; 12701 break; 12702 case UnqualifiedId::IK_DestructorName: 12703 DiagArg = 1; 12704 break; 12705 case UnqualifiedId::IK_ConversionFunctionId: 12706 DiagArg = 2; 12707 break; 12708 case UnqualifiedId::IK_Identifier: 12709 case UnqualifiedId::IK_ImplicitSelfParam: 12710 case UnqualifiedId::IK_LiteralOperatorId: 12711 case UnqualifiedId::IK_OperatorFunctionId: 12712 case UnqualifiedId::IK_TemplateId: 12713 break; 12714 } 12715 // This implies that it has to be an operator or function. 12716 if (DiagArg >= 0) { 12717 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 12718 return nullptr; 12719 } 12720 } 12721 12722 // FIXME: This is an egregious hack to cope with cases where the scope stack 12723 // does not contain the declaration context, i.e., in an out-of-line 12724 // definition of a class. 12725 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12726 if (!DCScope) { 12727 FakeDCScope.setEntity(DC); 12728 DCScope = &FakeDCScope; 12729 } 12730 12731 bool AddToScope = true; 12732 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12733 TemplateParams, AddToScope); 12734 if (!ND) return nullptr; 12735 12736 assert(ND->getLexicalDeclContext() == CurContext); 12737 12738 // If we performed typo correction, we might have added a scope specifier 12739 // and changed the decl context. 12740 DC = ND->getDeclContext(); 12741 12742 // Add the function declaration to the appropriate lookup tables, 12743 // adjusting the redeclarations list as necessary. We don't 12744 // want to do this yet if the friending class is dependent. 12745 // 12746 // Also update the scope-based lookup if the target context's 12747 // lookup context is in lexical scope. 12748 if (!CurContext->isDependentContext()) { 12749 DC = DC->getRedeclContext(); 12750 DC->makeDeclVisibleInContext(ND); 12751 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12752 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12753 } 12754 12755 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12756 D.getIdentifierLoc(), ND, 12757 DS.getFriendSpecLoc()); 12758 FrD->setAccess(AS_public); 12759 CurContext->addDecl(FrD); 12760 12761 if (ND->isInvalidDecl()) { 12762 FrD->setInvalidDecl(); 12763 } else { 12764 if (DC->isRecord()) CheckFriendAccess(ND); 12765 12766 FunctionDecl *FD; 12767 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12768 FD = FTD->getTemplatedDecl(); 12769 else 12770 FD = cast<FunctionDecl>(ND); 12771 12772 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12773 // default argument expression, that declaration shall be a definition 12774 // and shall be the only declaration of the function or function 12775 // template in the translation unit. 12776 if (functionDeclHasDefaultArgument(FD)) { 12777 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12778 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12779 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12780 } else if (!D.isFunctionDefinition()) 12781 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12782 } 12783 12784 // Mark templated-scope function declarations as unsupported. 12785 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12786 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12787 << SS.getScopeRep() << SS.getRange() 12788 << cast<CXXRecordDecl>(CurContext); 12789 FrD->setUnsupportedFriend(true); 12790 } 12791 } 12792 12793 return ND; 12794 } 12795 12796 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12797 AdjustDeclIfTemplate(Dcl); 12798 12799 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12800 if (!Fn) { 12801 Diag(DelLoc, diag::err_deleted_non_function); 12802 return; 12803 } 12804 12805 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12806 // Don't consider the implicit declaration we generate for explicit 12807 // specializations. FIXME: Do not generate these implicit declarations. 12808 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12809 Prev->getPreviousDecl()) && 12810 !Prev->isDefined()) { 12811 Diag(DelLoc, diag::err_deleted_decl_not_first); 12812 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12813 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12814 : diag::note_previous_declaration); 12815 } 12816 // If the declaration wasn't the first, we delete the function anyway for 12817 // recovery. 12818 Fn = Fn->getCanonicalDecl(); 12819 } 12820 12821 // dllimport/dllexport cannot be deleted. 12822 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12823 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12824 Fn->setInvalidDecl(); 12825 } 12826 12827 if (Fn->isDeleted()) 12828 return; 12829 12830 // See if we're deleting a function which is already known to override a 12831 // non-deleted virtual function. 12832 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12833 bool IssuedDiagnostic = false; 12834 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12835 E = MD->end_overridden_methods(); 12836 I != E; ++I) { 12837 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12838 if (!IssuedDiagnostic) { 12839 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12840 IssuedDiagnostic = true; 12841 } 12842 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12843 } 12844 } 12845 } 12846 12847 // C++11 [basic.start.main]p3: 12848 // A program that defines main as deleted [...] is ill-formed. 12849 if (Fn->isMain()) 12850 Diag(DelLoc, diag::err_deleted_main); 12851 12852 Fn->setDeletedAsWritten(); 12853 } 12854 12855 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12856 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12857 12858 if (MD) { 12859 if (MD->getParent()->isDependentType()) { 12860 MD->setDefaulted(); 12861 MD->setExplicitlyDefaulted(); 12862 return; 12863 } 12864 12865 CXXSpecialMember Member = getSpecialMember(MD); 12866 if (Member == CXXInvalid) { 12867 if (!MD->isInvalidDecl()) 12868 Diag(DefaultLoc, diag::err_default_special_members); 12869 return; 12870 } 12871 12872 MD->setDefaulted(); 12873 MD->setExplicitlyDefaulted(); 12874 12875 // If this definition appears within the record, do the checking when 12876 // the record is complete. 12877 const FunctionDecl *Primary = MD; 12878 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12879 // Find the uninstantiated declaration that actually had the '= default' 12880 // on it. 12881 Pattern->isDefined(Primary); 12882 12883 // If the method was defaulted on its first declaration, we will have 12884 // already performed the checking in CheckCompletedCXXClass. Such a 12885 // declaration doesn't trigger an implicit definition. 12886 if (Primary == Primary->getCanonicalDecl()) 12887 return; 12888 12889 CheckExplicitlyDefaultedSpecialMember(MD); 12890 12891 if (MD->isInvalidDecl()) 12892 return; 12893 12894 switch (Member) { 12895 case CXXDefaultConstructor: 12896 DefineImplicitDefaultConstructor(DefaultLoc, 12897 cast<CXXConstructorDecl>(MD)); 12898 break; 12899 case CXXCopyConstructor: 12900 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12901 break; 12902 case CXXCopyAssignment: 12903 DefineImplicitCopyAssignment(DefaultLoc, MD); 12904 break; 12905 case CXXDestructor: 12906 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12907 break; 12908 case CXXMoveConstructor: 12909 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12910 break; 12911 case CXXMoveAssignment: 12912 DefineImplicitMoveAssignment(DefaultLoc, MD); 12913 break; 12914 case CXXInvalid: 12915 llvm_unreachable("Invalid special member."); 12916 } 12917 } else { 12918 Diag(DefaultLoc, diag::err_default_special_members); 12919 } 12920 } 12921 12922 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12923 for (Stmt *SubStmt : S->children()) { 12924 if (!SubStmt) 12925 continue; 12926 if (isa<ReturnStmt>(SubStmt)) 12927 Self.Diag(SubStmt->getLocStart(), 12928 diag::err_return_in_constructor_handler); 12929 if (!isa<Expr>(SubStmt)) 12930 SearchForReturnInStmt(Self, SubStmt); 12931 } 12932 } 12933 12934 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12935 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12936 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12937 SearchForReturnInStmt(*this, Handler); 12938 } 12939 } 12940 12941 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12942 const CXXMethodDecl *Old) { 12943 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12944 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12945 12946 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12947 12948 // If the calling conventions match, everything is fine 12949 if (NewCC == OldCC) 12950 return false; 12951 12952 // If the calling conventions mismatch because the new function is static, 12953 // suppress the calling convention mismatch error; the error about static 12954 // function override (err_static_overrides_virtual from 12955 // Sema::CheckFunctionDeclaration) is more clear. 12956 if (New->getStorageClass() == SC_Static) 12957 return false; 12958 12959 Diag(New->getLocation(), 12960 diag::err_conflicting_overriding_cc_attributes) 12961 << New->getDeclName() << New->getType() << Old->getType(); 12962 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12963 return true; 12964 } 12965 12966 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12967 const CXXMethodDecl *Old) { 12968 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12969 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12970 12971 if (Context.hasSameType(NewTy, OldTy) || 12972 NewTy->isDependentType() || OldTy->isDependentType()) 12973 return false; 12974 12975 // Check if the return types are covariant 12976 QualType NewClassTy, OldClassTy; 12977 12978 /// Both types must be pointers or references to classes. 12979 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12980 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12981 NewClassTy = NewPT->getPointeeType(); 12982 OldClassTy = OldPT->getPointeeType(); 12983 } 12984 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12985 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12986 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12987 NewClassTy = NewRT->getPointeeType(); 12988 OldClassTy = OldRT->getPointeeType(); 12989 } 12990 } 12991 } 12992 12993 // The return types aren't either both pointers or references to a class type. 12994 if (NewClassTy.isNull()) { 12995 Diag(New->getLocation(), 12996 diag::err_different_return_type_for_overriding_virtual_function) 12997 << New->getDeclName() << NewTy << OldTy 12998 << New->getReturnTypeSourceRange(); 12999 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13000 << Old->getReturnTypeSourceRange(); 13001 13002 return true; 13003 } 13004 13005 // C++ [class.virtual]p6: 13006 // If the return type of D::f differs from the return type of B::f, the 13007 // class type in the return type of D::f shall be complete at the point of 13008 // declaration of D::f or shall be the class type D. 13009 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 13010 if (!RT->isBeingDefined() && 13011 RequireCompleteType(New->getLocation(), NewClassTy, 13012 diag::err_covariant_return_incomplete, 13013 New->getDeclName())) 13014 return true; 13015 } 13016 13017 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 13018 // Check if the new class derives from the old class. 13019 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 13020 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 13021 << New->getDeclName() << NewTy << OldTy 13022 << New->getReturnTypeSourceRange(); 13023 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13024 << Old->getReturnTypeSourceRange(); 13025 return true; 13026 } 13027 13028 // Check if we the conversion from derived to base is valid. 13029 if (CheckDerivedToBaseConversion( 13030 NewClassTy, OldClassTy, 13031 diag::err_covariant_return_inaccessible_base, 13032 diag::err_covariant_return_ambiguous_derived_to_base_conv, 13033 New->getLocation(), New->getReturnTypeSourceRange(), 13034 New->getDeclName(), nullptr)) { 13035 // FIXME: this note won't trigger for delayed access control 13036 // diagnostics, and it's impossible to get an undelayed error 13037 // here from access control during the original parse because 13038 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 13039 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13040 << Old->getReturnTypeSourceRange(); 13041 return true; 13042 } 13043 } 13044 13045 // The qualifiers of the return types must be the same. 13046 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 13047 Diag(New->getLocation(), 13048 diag::err_covariant_return_type_different_qualifications) 13049 << New->getDeclName() << NewTy << OldTy 13050 << New->getReturnTypeSourceRange(); 13051 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13052 << Old->getReturnTypeSourceRange(); 13053 return true; 13054 }; 13055 13056 13057 // The new class type must have the same or less qualifiers as the old type. 13058 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 13059 Diag(New->getLocation(), 13060 diag::err_covariant_return_type_class_type_more_qualified) 13061 << New->getDeclName() << NewTy << OldTy 13062 << New->getReturnTypeSourceRange(); 13063 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13064 << Old->getReturnTypeSourceRange(); 13065 return true; 13066 }; 13067 13068 return false; 13069 } 13070 13071 /// \brief Mark the given method pure. 13072 /// 13073 /// \param Method the method to be marked pure. 13074 /// 13075 /// \param InitRange the source range that covers the "0" initializer. 13076 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 13077 SourceLocation EndLoc = InitRange.getEnd(); 13078 if (EndLoc.isValid()) 13079 Method->setRangeEnd(EndLoc); 13080 13081 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 13082 Method->setPure(); 13083 return false; 13084 } 13085 13086 if (!Method->isInvalidDecl()) 13087 Diag(Method->getLocation(), diag::err_non_virtual_pure) 13088 << Method->getDeclName() << InitRange; 13089 return true; 13090 } 13091 13092 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 13093 if (D->getFriendObjectKind()) 13094 Diag(D->getLocation(), diag::err_pure_friend); 13095 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 13096 CheckPureMethod(M, ZeroLoc); 13097 else 13098 Diag(D->getLocation(), diag::err_illegal_initializer); 13099 } 13100 13101 /// \brief Determine whether the given declaration is a static data member. 13102 static bool isStaticDataMember(const Decl *D) { 13103 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 13104 return Var->isStaticDataMember(); 13105 13106 return false; 13107 } 13108 13109 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 13110 /// an initializer for the out-of-line declaration 'Dcl'. The scope 13111 /// is a fresh scope pushed for just this purpose. 13112 /// 13113 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 13114 /// static data member of class X, names should be looked up in the scope of 13115 /// class X. 13116 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 13117 // If there is no declaration, there was an error parsing it. 13118 if (!D || D->isInvalidDecl()) 13119 return; 13120 13121 // We will always have a nested name specifier here, but this declaration 13122 // might not be out of line if the specifier names the current namespace: 13123 // extern int n; 13124 // int ::n = 0; 13125 if (D->isOutOfLine()) 13126 EnterDeclaratorContext(S, D->getDeclContext()); 13127 13128 // If we are parsing the initializer for a static data member, push a 13129 // new expression evaluation context that is associated with this static 13130 // data member. 13131 if (isStaticDataMember(D)) 13132 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 13133 } 13134 13135 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 13136 /// initializer for the out-of-line declaration 'D'. 13137 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 13138 // If there is no declaration, there was an error parsing it. 13139 if (!D || D->isInvalidDecl()) 13140 return; 13141 13142 if (isStaticDataMember(D)) 13143 PopExpressionEvaluationContext(); 13144 13145 if (D->isOutOfLine()) 13146 ExitDeclaratorContext(S); 13147 } 13148 13149 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 13150 /// C++ if/switch/while/for statement. 13151 /// e.g: "if (int x = f()) {...}" 13152 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 13153 // C++ 6.4p2: 13154 // The declarator shall not specify a function or an array. 13155 // The type-specifier-seq shall not contain typedef and shall not declare a 13156 // new class or enumeration. 13157 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 13158 "Parser allowed 'typedef' as storage class of condition decl."); 13159 13160 Decl *Dcl = ActOnDeclarator(S, D); 13161 if (!Dcl) 13162 return true; 13163 13164 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 13165 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 13166 << D.getSourceRange(); 13167 return true; 13168 } 13169 13170 return Dcl; 13171 } 13172 13173 void Sema::LoadExternalVTableUses() { 13174 if (!ExternalSource) 13175 return; 13176 13177 SmallVector<ExternalVTableUse, 4> VTables; 13178 ExternalSource->ReadUsedVTables(VTables); 13179 SmallVector<VTableUse, 4> NewUses; 13180 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 13181 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 13182 = VTablesUsed.find(VTables[I].Record); 13183 // Even if a definition wasn't required before, it may be required now. 13184 if (Pos != VTablesUsed.end()) { 13185 if (!Pos->second && VTables[I].DefinitionRequired) 13186 Pos->second = true; 13187 continue; 13188 } 13189 13190 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 13191 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 13192 } 13193 13194 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 13195 } 13196 13197 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 13198 bool DefinitionRequired) { 13199 // Ignore any vtable uses in unevaluated operands or for classes that do 13200 // not have a vtable. 13201 if (!Class->isDynamicClass() || Class->isDependentContext() || 13202 CurContext->isDependentContext() || isUnevaluatedContext()) 13203 return; 13204 13205 // Try to insert this class into the map. 13206 LoadExternalVTableUses(); 13207 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13208 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 13209 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 13210 if (!Pos.second) { 13211 // If we already had an entry, check to see if we are promoting this vtable 13212 // to require a definition. If so, we need to reappend to the VTableUses 13213 // list, since we may have already processed the first entry. 13214 if (DefinitionRequired && !Pos.first->second) { 13215 Pos.first->second = true; 13216 } else { 13217 // Otherwise, we can early exit. 13218 return; 13219 } 13220 } else { 13221 // The Microsoft ABI requires that we perform the destructor body 13222 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 13223 // the deleting destructor is emitted with the vtable, not with the 13224 // destructor definition as in the Itanium ABI. 13225 // If it has a definition, we do the check at that point instead. 13226 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13227 Class->hasUserDeclaredDestructor() && 13228 !Class->getDestructor()->isDefined() && 13229 !Class->getDestructor()->isDeleted()) { 13230 CXXDestructorDecl *DD = Class->getDestructor(); 13231 ContextRAII SavedContext(*this, DD); 13232 CheckDestructor(DD); 13233 } 13234 } 13235 13236 // Local classes need to have their virtual members marked 13237 // immediately. For all other classes, we mark their virtual members 13238 // at the end of the translation unit. 13239 if (Class->isLocalClass()) 13240 MarkVirtualMembersReferenced(Loc, Class); 13241 else 13242 VTableUses.push_back(std::make_pair(Class, Loc)); 13243 } 13244 13245 bool Sema::DefineUsedVTables() { 13246 LoadExternalVTableUses(); 13247 if (VTableUses.empty()) 13248 return false; 13249 13250 // Note: The VTableUses vector could grow as a result of marking 13251 // the members of a class as "used", so we check the size each 13252 // time through the loop and prefer indices (which are stable) to 13253 // iterators (which are not). 13254 bool DefinedAnything = false; 13255 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13256 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13257 if (!Class) 13258 continue; 13259 13260 SourceLocation Loc = VTableUses[I].second; 13261 13262 bool DefineVTable = true; 13263 13264 // If this class has a key function, but that key function is 13265 // defined in another translation unit, we don't need to emit the 13266 // vtable even though we're using it. 13267 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13268 if (KeyFunction && !KeyFunction->hasBody()) { 13269 // The key function is in another translation unit. 13270 DefineVTable = false; 13271 TemplateSpecializationKind TSK = 13272 KeyFunction->getTemplateSpecializationKind(); 13273 assert(TSK != TSK_ExplicitInstantiationDefinition && 13274 TSK != TSK_ImplicitInstantiation && 13275 "Instantiations don't have key functions"); 13276 (void)TSK; 13277 } else if (!KeyFunction) { 13278 // If we have a class with no key function that is the subject 13279 // of an explicit instantiation declaration, suppress the 13280 // vtable; it will live with the explicit instantiation 13281 // definition. 13282 bool IsExplicitInstantiationDeclaration 13283 = Class->getTemplateSpecializationKind() 13284 == TSK_ExplicitInstantiationDeclaration; 13285 for (auto R : Class->redecls()) { 13286 TemplateSpecializationKind TSK 13287 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13288 if (TSK == TSK_ExplicitInstantiationDeclaration) 13289 IsExplicitInstantiationDeclaration = true; 13290 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13291 IsExplicitInstantiationDeclaration = false; 13292 break; 13293 } 13294 } 13295 13296 if (IsExplicitInstantiationDeclaration) 13297 DefineVTable = false; 13298 } 13299 13300 // The exception specifications for all virtual members may be needed even 13301 // if we are not providing an authoritative form of the vtable in this TU. 13302 // We may choose to emit it available_externally anyway. 13303 if (!DefineVTable) { 13304 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13305 continue; 13306 } 13307 13308 // Mark all of the virtual members of this class as referenced, so 13309 // that we can build a vtable. Then, tell the AST consumer that a 13310 // vtable for this class is required. 13311 DefinedAnything = true; 13312 MarkVirtualMembersReferenced(Loc, Class); 13313 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13314 if (VTablesUsed[Canonical]) 13315 Consumer.HandleVTable(Class); 13316 13317 // Optionally warn if we're emitting a weak vtable. 13318 if (Class->isExternallyVisible() && 13319 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13320 const FunctionDecl *KeyFunctionDef = nullptr; 13321 if (!KeyFunction || 13322 (KeyFunction->hasBody(KeyFunctionDef) && 13323 KeyFunctionDef->isInlined())) 13324 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13325 TSK_ExplicitInstantiationDefinition 13326 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13327 << Class; 13328 } 13329 } 13330 VTableUses.clear(); 13331 13332 return DefinedAnything; 13333 } 13334 13335 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13336 const CXXRecordDecl *RD) { 13337 for (const auto *I : RD->methods()) 13338 if (I->isVirtual() && !I->isPure()) 13339 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13340 } 13341 13342 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13343 const CXXRecordDecl *RD) { 13344 // Mark all functions which will appear in RD's vtable as used. 13345 CXXFinalOverriderMap FinalOverriders; 13346 RD->getFinalOverriders(FinalOverriders); 13347 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13348 E = FinalOverriders.end(); 13349 I != E; ++I) { 13350 for (OverridingMethods::const_iterator OI = I->second.begin(), 13351 OE = I->second.end(); 13352 OI != OE; ++OI) { 13353 assert(OI->second.size() > 0 && "no final overrider"); 13354 CXXMethodDecl *Overrider = OI->second.front().Method; 13355 13356 // C++ [basic.def.odr]p2: 13357 // [...] A virtual member function is used if it is not pure. [...] 13358 if (!Overrider->isPure()) 13359 MarkFunctionReferenced(Loc, Overrider); 13360 } 13361 } 13362 13363 // Only classes that have virtual bases need a VTT. 13364 if (RD->getNumVBases() == 0) 13365 return; 13366 13367 for (const auto &I : RD->bases()) { 13368 const CXXRecordDecl *Base = 13369 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13370 if (Base->getNumVBases() == 0) 13371 continue; 13372 MarkVirtualMembersReferenced(Loc, Base); 13373 } 13374 } 13375 13376 /// SetIvarInitializers - This routine builds initialization ASTs for the 13377 /// Objective-C implementation whose ivars need be initialized. 13378 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13379 if (!getLangOpts().CPlusPlus) 13380 return; 13381 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13382 SmallVector<ObjCIvarDecl*, 8> ivars; 13383 CollectIvarsToConstructOrDestruct(OID, ivars); 13384 if (ivars.empty()) 13385 return; 13386 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13387 for (unsigned i = 0; i < ivars.size(); i++) { 13388 FieldDecl *Field = ivars[i]; 13389 if (Field->isInvalidDecl()) 13390 continue; 13391 13392 CXXCtorInitializer *Member; 13393 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13394 InitializationKind InitKind = 13395 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13396 13397 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13398 ExprResult MemberInit = 13399 InitSeq.Perform(*this, InitEntity, InitKind, None); 13400 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13401 // Note, MemberInit could actually come back empty if no initialization 13402 // is required (e.g., because it would call a trivial default constructor) 13403 if (!MemberInit.get() || MemberInit.isInvalid()) 13404 continue; 13405 13406 Member = 13407 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13408 SourceLocation(), 13409 MemberInit.getAs<Expr>(), 13410 SourceLocation()); 13411 AllToInit.push_back(Member); 13412 13413 // Be sure that the destructor is accessible and is marked as referenced. 13414 if (const RecordType *RecordTy = 13415 Context.getBaseElementType(Field->getType()) 13416 ->getAs<RecordType>()) { 13417 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13418 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13419 MarkFunctionReferenced(Field->getLocation(), Destructor); 13420 CheckDestructorAccess(Field->getLocation(), Destructor, 13421 PDiag(diag::err_access_dtor_ivar) 13422 << Context.getBaseElementType(Field->getType())); 13423 } 13424 } 13425 } 13426 ObjCImplementation->setIvarInitializers(Context, 13427 AllToInit.data(), AllToInit.size()); 13428 } 13429 } 13430 13431 static 13432 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13433 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13434 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13435 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13436 Sema &S) { 13437 if (Ctor->isInvalidDecl()) 13438 return; 13439 13440 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13441 13442 // Target may not be determinable yet, for instance if this is a dependent 13443 // call in an uninstantiated template. 13444 if (Target) { 13445 const FunctionDecl *FNTarget = nullptr; 13446 (void)Target->hasBody(FNTarget); 13447 Target = const_cast<CXXConstructorDecl*>( 13448 cast_or_null<CXXConstructorDecl>(FNTarget)); 13449 } 13450 13451 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13452 // Avoid dereferencing a null pointer here. 13453 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13454 13455 if (!Current.insert(Canonical).second) 13456 return; 13457 13458 // We know that beyond here, we aren't chaining into a cycle. 13459 if (!Target || !Target->isDelegatingConstructor() || 13460 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13461 Valid.insert(Current.begin(), Current.end()); 13462 Current.clear(); 13463 // We've hit a cycle. 13464 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13465 Current.count(TCanonical)) { 13466 // If we haven't diagnosed this cycle yet, do so now. 13467 if (!Invalid.count(TCanonical)) { 13468 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13469 diag::warn_delegating_ctor_cycle) 13470 << Ctor; 13471 13472 // Don't add a note for a function delegating directly to itself. 13473 if (TCanonical != Canonical) 13474 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13475 13476 CXXConstructorDecl *C = Target; 13477 while (C->getCanonicalDecl() != Canonical) { 13478 const FunctionDecl *FNTarget = nullptr; 13479 (void)C->getTargetConstructor()->hasBody(FNTarget); 13480 assert(FNTarget && "Ctor cycle through bodiless function"); 13481 13482 C = const_cast<CXXConstructorDecl*>( 13483 cast<CXXConstructorDecl>(FNTarget)); 13484 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13485 } 13486 } 13487 13488 Invalid.insert(Current.begin(), Current.end()); 13489 Current.clear(); 13490 } else { 13491 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13492 } 13493 } 13494 13495 13496 void Sema::CheckDelegatingCtorCycles() { 13497 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13498 13499 for (DelegatingCtorDeclsType::iterator 13500 I = DelegatingCtorDecls.begin(ExternalSource), 13501 E = DelegatingCtorDecls.end(); 13502 I != E; ++I) 13503 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13504 13505 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13506 CE = Invalid.end(); 13507 CI != CE; ++CI) 13508 (*CI)->setInvalidDecl(); 13509 } 13510 13511 namespace { 13512 /// \brief AST visitor that finds references to the 'this' expression. 13513 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13514 Sema &S; 13515 13516 public: 13517 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13518 13519 bool VisitCXXThisExpr(CXXThisExpr *E) { 13520 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13521 << E->isImplicit(); 13522 return false; 13523 } 13524 }; 13525 } 13526 13527 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13528 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13529 if (!TSInfo) 13530 return false; 13531 13532 TypeLoc TL = TSInfo->getTypeLoc(); 13533 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13534 if (!ProtoTL) 13535 return false; 13536 13537 // C++11 [expr.prim.general]p3: 13538 // [The expression this] shall not appear before the optional 13539 // cv-qualifier-seq and it shall not appear within the declaration of a 13540 // static member function (although its type and value category are defined 13541 // within a static member function as they are within a non-static member 13542 // function). [ Note: this is because declaration matching does not occur 13543 // until the complete declarator is known. - end note ] 13544 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13545 FindCXXThisExpr Finder(*this); 13546 13547 // If the return type came after the cv-qualifier-seq, check it now. 13548 if (Proto->hasTrailingReturn() && 13549 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13550 return true; 13551 13552 // Check the exception specification. 13553 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13554 return true; 13555 13556 return checkThisInStaticMemberFunctionAttributes(Method); 13557 } 13558 13559 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13560 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13561 if (!TSInfo) 13562 return false; 13563 13564 TypeLoc TL = TSInfo->getTypeLoc(); 13565 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13566 if (!ProtoTL) 13567 return false; 13568 13569 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13570 FindCXXThisExpr Finder(*this); 13571 13572 switch (Proto->getExceptionSpecType()) { 13573 case EST_Unparsed: 13574 case EST_Uninstantiated: 13575 case EST_Unevaluated: 13576 case EST_BasicNoexcept: 13577 case EST_DynamicNone: 13578 case EST_MSAny: 13579 case EST_None: 13580 break; 13581 13582 case EST_ComputedNoexcept: 13583 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13584 return true; 13585 13586 case EST_Dynamic: 13587 for (const auto &E : Proto->exceptions()) { 13588 if (!Finder.TraverseType(E)) 13589 return true; 13590 } 13591 break; 13592 } 13593 13594 return false; 13595 } 13596 13597 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13598 FindCXXThisExpr Finder(*this); 13599 13600 // Check attributes. 13601 for (const auto *A : Method->attrs()) { 13602 // FIXME: This should be emitted by tblgen. 13603 Expr *Arg = nullptr; 13604 ArrayRef<Expr *> Args; 13605 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13606 Arg = G->getArg(); 13607 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13608 Arg = G->getArg(); 13609 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13610 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13611 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13612 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13613 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13614 Arg = ETLF->getSuccessValue(); 13615 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13616 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13617 Arg = STLF->getSuccessValue(); 13618 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13619 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13620 Arg = LR->getArg(); 13621 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13622 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13623 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13624 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13625 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13626 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13627 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13628 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13629 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13630 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13631 13632 if (Arg && !Finder.TraverseStmt(Arg)) 13633 return true; 13634 13635 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13636 if (!Finder.TraverseStmt(Args[I])) 13637 return true; 13638 } 13639 } 13640 13641 return false; 13642 } 13643 13644 void Sema::checkExceptionSpecification( 13645 bool IsTopLevel, ExceptionSpecificationType EST, 13646 ArrayRef<ParsedType> DynamicExceptions, 13647 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13648 SmallVectorImpl<QualType> &Exceptions, 13649 FunctionProtoType::ExceptionSpecInfo &ESI) { 13650 Exceptions.clear(); 13651 ESI.Type = EST; 13652 if (EST == EST_Dynamic) { 13653 Exceptions.reserve(DynamicExceptions.size()); 13654 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13655 // FIXME: Preserve type source info. 13656 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13657 13658 if (IsTopLevel) { 13659 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13660 collectUnexpandedParameterPacks(ET, Unexpanded); 13661 if (!Unexpanded.empty()) { 13662 DiagnoseUnexpandedParameterPacks( 13663 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13664 Unexpanded); 13665 continue; 13666 } 13667 } 13668 13669 // Check that the type is valid for an exception spec, and 13670 // drop it if not. 13671 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13672 Exceptions.push_back(ET); 13673 } 13674 ESI.Exceptions = Exceptions; 13675 return; 13676 } 13677 13678 if (EST == EST_ComputedNoexcept) { 13679 // If an error occurred, there's no expression here. 13680 if (NoexceptExpr) { 13681 assert((NoexceptExpr->isTypeDependent() || 13682 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13683 Context.BoolTy) && 13684 "Parser should have made sure that the expression is boolean"); 13685 if (IsTopLevel && NoexceptExpr && 13686 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13687 ESI.Type = EST_BasicNoexcept; 13688 return; 13689 } 13690 13691 if (!NoexceptExpr->isValueDependent()) 13692 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13693 diag::err_noexcept_needs_constant_expression, 13694 /*AllowFold*/ false).get(); 13695 ESI.NoexceptExpr = NoexceptExpr; 13696 } 13697 return; 13698 } 13699 } 13700 13701 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13702 ExceptionSpecificationType EST, 13703 SourceRange SpecificationRange, 13704 ArrayRef<ParsedType> DynamicExceptions, 13705 ArrayRef<SourceRange> DynamicExceptionRanges, 13706 Expr *NoexceptExpr) { 13707 if (!MethodD) 13708 return; 13709 13710 // Dig out the method we're referring to. 13711 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13712 MethodD = FunTmpl->getTemplatedDecl(); 13713 13714 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13715 if (!Method) 13716 return; 13717 13718 // Check the exception specification. 13719 llvm::SmallVector<QualType, 4> Exceptions; 13720 FunctionProtoType::ExceptionSpecInfo ESI; 13721 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13722 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13723 ESI); 13724 13725 // Update the exception specification on the function type. 13726 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13727 13728 if (Method->isStatic()) 13729 checkThisInStaticMemberFunctionExceptionSpec(Method); 13730 13731 if (Method->isVirtual()) { 13732 // Check overrides, which we previously had to delay. 13733 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13734 OEnd = Method->end_overridden_methods(); 13735 O != OEnd; ++O) 13736 CheckOverridingFunctionExceptionSpec(Method, *O); 13737 } 13738 } 13739 13740 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13741 /// 13742 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13743 SourceLocation DeclStart, 13744 Declarator &D, Expr *BitWidth, 13745 InClassInitStyle InitStyle, 13746 AccessSpecifier AS, 13747 AttributeList *MSPropertyAttr) { 13748 IdentifierInfo *II = D.getIdentifier(); 13749 if (!II) { 13750 Diag(DeclStart, diag::err_anonymous_property); 13751 return nullptr; 13752 } 13753 SourceLocation Loc = D.getIdentifierLoc(); 13754 13755 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13756 QualType T = TInfo->getType(); 13757 if (getLangOpts().CPlusPlus) { 13758 CheckExtraCXXDefaultArguments(D); 13759 13760 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13761 UPPC_DataMemberType)) { 13762 D.setInvalidType(); 13763 T = Context.IntTy; 13764 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13765 } 13766 } 13767 13768 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13769 13770 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13771 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13772 diag::err_invalid_thread) 13773 << DeclSpec::getSpecifierName(TSCS); 13774 13775 // Check to see if this name was declared as a member previously 13776 NamedDecl *PrevDecl = nullptr; 13777 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13778 LookupName(Previous, S); 13779 switch (Previous.getResultKind()) { 13780 case LookupResult::Found: 13781 case LookupResult::FoundUnresolvedValue: 13782 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13783 break; 13784 13785 case LookupResult::FoundOverloaded: 13786 PrevDecl = Previous.getRepresentativeDecl(); 13787 break; 13788 13789 case LookupResult::NotFound: 13790 case LookupResult::NotFoundInCurrentInstantiation: 13791 case LookupResult::Ambiguous: 13792 break; 13793 } 13794 13795 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13796 // Maybe we will complain about the shadowed template parameter. 13797 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13798 // Just pretend that we didn't see the previous declaration. 13799 PrevDecl = nullptr; 13800 } 13801 13802 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13803 PrevDecl = nullptr; 13804 13805 SourceLocation TSSL = D.getLocStart(); 13806 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13807 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13808 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13809 ProcessDeclAttributes(TUScope, NewPD, D); 13810 NewPD->setAccess(AS); 13811 13812 if (NewPD->isInvalidDecl()) 13813 Record->setInvalidDecl(); 13814 13815 if (D.getDeclSpec().isModulePrivateSpecified()) 13816 NewPD->setModulePrivate(); 13817 13818 if (NewPD->isInvalidDecl() && PrevDecl) { 13819 // Don't introduce NewFD into scope; there's already something 13820 // with the same name in the same scope. 13821 } else if (II) { 13822 PushOnScopeChains(NewPD, S); 13823 } else 13824 Record->addDecl(NewPD); 13825 13826 return NewPD; 13827 } 13828