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/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Lex/LiteralSupport.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Sema/CXXFieldCollector.h" 32 #include "clang/Sema/DeclSpec.h" 33 #include "clang/Sema/Initialization.h" 34 #include "clang/Sema/Lookup.h" 35 #include "clang/Sema/ParsedTemplate.h" 36 #include "clang/Sema/Scope.h" 37 #include "clang/Sema/ScopeInfo.h" 38 #include "clang/Sema/SemaInternal.h" 39 #include "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include "llvm/ADT/StringExtras.h" 43 #include <map> 44 #include <set> 45 46 using namespace clang; 47 48 //===----------------------------------------------------------------------===// 49 // CheckDefaultArgumentVisitor 50 //===----------------------------------------------------------------------===// 51 52 namespace { 53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 54 /// the default argument of a parameter to determine whether it 55 /// contains any ill-formed subexpressions. For example, this will 56 /// diagnose the use of local variables or parameters within the 57 /// default argument expression. 58 class CheckDefaultArgumentVisitor 59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 60 Expr *DefaultArg; 61 Sema *S; 62 63 public: 64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 65 : DefaultArg(defarg), S(s) {} 66 67 bool VisitExpr(Expr *Node); 68 bool VisitDeclRefExpr(DeclRefExpr *DRE); 69 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 70 bool VisitLambdaExpr(LambdaExpr *Lambda); 71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 72 }; 73 74 /// VisitExpr - Visit all of the children of this expression. 75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 76 bool IsInvalid = false; 77 for (Stmt *SubStmt : Node->children()) 78 IsInvalid |= Visit(SubStmt); 79 return IsInvalid; 80 } 81 82 /// VisitDeclRefExpr - Visit a reference to a declaration, to 83 /// determine whether this declaration can be used in the default 84 /// argument expression. 85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 86 NamedDecl *Decl = DRE->getDecl(); 87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 88 // C++ [dcl.fct.default]p9 89 // Default arguments are evaluated each time the function is 90 // called. The order of evaluation of function arguments is 91 // unspecified. Consequently, parameters of a function shall not 92 // be used in default argument expressions, even if they are not 93 // evaluated. Parameters of a function declared before a default 94 // argument expression are in scope and can hide namespace and 95 // class member names. 96 return S->Diag(DRE->getLocStart(), 97 diag::err_param_default_argument_references_param) 98 << Param->getDeclName() << DefaultArg->getSourceRange(); 99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 100 // C++ [dcl.fct.default]p7 101 // Local variables shall not be used in default argument 102 // expressions. 103 if (VDecl->isLocalVarDecl()) 104 return S->Diag(DRE->getLocStart(), 105 diag::err_param_default_argument_references_local) 106 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 107 } 108 109 return false; 110 } 111 112 /// VisitCXXThisExpr - Visit a C++ "this" expression. 113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 114 // C++ [dcl.fct.default]p8: 115 // The keyword this shall not be used in a default argument of a 116 // member function. 117 return S->Diag(ThisE->getLocStart(), 118 diag::err_param_default_argument_references_this) 119 << ThisE->getSourceRange(); 120 } 121 122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 123 bool Invalid = false; 124 for (PseudoObjectExpr::semantics_iterator 125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 126 Expr *E = *i; 127 128 // Look through bindings. 129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 130 E = OVE->getSourceExpr(); 131 assert(E && "pseudo-object binding without source expression?"); 132 } 133 134 Invalid |= Visit(E); 135 } 136 return Invalid; 137 } 138 139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 140 // C++11 [expr.lambda.prim]p13: 141 // A lambda-expression appearing in a default argument shall not 142 // implicitly or explicitly capture any entity. 143 if (Lambda->capture_begin() == Lambda->capture_end()) 144 return false; 145 146 return S->Diag(Lambda->getLocStart(), 147 diag::err_lambda_capture_default_arg); 148 } 149 } 150 151 void 152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 153 const CXXMethodDecl *Method) { 154 // If we have an MSAny spec already, don't bother. 155 if (!Method || ComputedEST == EST_MSAny) 156 return; 157 158 const FunctionProtoType *Proto 159 = Method->getType()->getAs<FunctionProtoType>(); 160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 161 if (!Proto) 162 return; 163 164 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 165 166 // If we have a throw-all spec at this point, ignore the function. 167 if (ComputedEST == EST_None) 168 return; 169 170 switch(EST) { 171 // If this function can throw any exceptions, make a note of that. 172 case EST_MSAny: 173 case EST_None: 174 ClearExceptions(); 175 ComputedEST = EST; 176 return; 177 // FIXME: If the call to this decl is using any of its default arguments, we 178 // need to search them for potentially-throwing calls. 179 // If this function has a basic noexcept, it doesn't affect the outcome. 180 case EST_BasicNoexcept: 181 return; 182 // If we're still at noexcept(true) and there's a nothrow() callee, 183 // change to that specification. 184 case EST_DynamicNone: 185 if (ComputedEST == EST_BasicNoexcept) 186 ComputedEST = EST_DynamicNone; 187 return; 188 // Check out noexcept specs. 189 case EST_ComputedNoexcept: 190 { 191 FunctionProtoType::NoexceptResult NR = 192 Proto->getNoexceptSpec(Self->Context); 193 assert(NR != FunctionProtoType::NR_NoNoexcept && 194 "Must have noexcept result for EST_ComputedNoexcept."); 195 assert(NR != FunctionProtoType::NR_Dependent && 196 "Should not generate implicit declarations for dependent cases, " 197 "and don't know how to handle them anyway."); 198 // noexcept(false) -> no spec on the new function 199 if (NR == FunctionProtoType::NR_Throw) { 200 ClearExceptions(); 201 ComputedEST = EST_None; 202 } 203 // noexcept(true) won't change anything either. 204 return; 205 } 206 default: 207 break; 208 } 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // C++11 [dcl.fct.default]p3 321 // A default argument expression [...] shall not be specified for a 322 // parameter pack. 323 if (Param->isParameterPack()) { 324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 325 << DefaultArg->getSourceRange(); 326 return; 327 } 328 329 // Check that the default argument is well-formed 330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 331 if (DefaultArgChecker.Visit(DefaultArg)) { 332 Param->setInvalidDecl(); 333 return; 334 } 335 336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 337 } 338 339 /// ActOnParamUnparsedDefaultArgument - We've seen a default 340 /// argument for a function parameter, but we can't parse it yet 341 /// because we're inside a class definition. Note that this default 342 /// argument will be parsed later. 343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 344 SourceLocation EqualLoc, 345 SourceLocation ArgLoc) { 346 if (!param) 347 return; 348 349 ParmVarDecl *Param = cast<ParmVarDecl>(param); 350 Param->setUnparsedDefaultArg(); 351 UnparsedDefaultArgLocs[Param] = ArgLoc; 352 } 353 354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 355 /// the default argument for the parameter param failed. 356 void Sema::ActOnParamDefaultArgumentError(Decl *param, 357 SourceLocation EqualLoc) { 358 if (!param) 359 return; 360 361 ParmVarDecl *Param = cast<ParmVarDecl>(param); 362 Param->setInvalidDecl(); 363 UnparsedDefaultArgLocs.erase(Param); 364 Param->setDefaultArg(new(Context) 365 OpaqueValueExpr(EqualLoc, 366 Param->getType().getNonReferenceType(), 367 VK_RValue)); 368 } 369 370 /// CheckExtraCXXDefaultArguments - Check for any extra default 371 /// arguments in the declarator, which is not a function declaration 372 /// or definition and therefore is not permitted to have default 373 /// arguments. This routine should be invoked for every declarator 374 /// that is not a function declaration or definition. 375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 376 // C++ [dcl.fct.default]p3 377 // A default argument expression shall be specified only in the 378 // parameter-declaration-clause of a function declaration or in a 379 // template-parameter (14.1). It shall not be specified for a 380 // parameter pack. If it is specified in a 381 // parameter-declaration-clause, it shall not occur within a 382 // declarator or abstract-declarator of a parameter-declaration. 383 bool MightBeFunction = D.isFunctionDeclarationContext(); 384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 385 DeclaratorChunk &chunk = D.getTypeObject(i); 386 if (chunk.Kind == DeclaratorChunk::Function) { 387 if (MightBeFunction) { 388 // This is a function declaration. It can have default arguments, but 389 // keep looking in case its return type is a function type with default 390 // arguments. 391 MightBeFunction = false; 392 continue; 393 } 394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 395 ++argIdx) { 396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 397 if (Param->hasUnparsedDefaultArg()) { 398 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 399 SourceRange SR; 400 if (Toks->size() > 1) 401 SR = SourceRange((*Toks)[1].getLocation(), 402 Toks->back().getLocation()); 403 else 404 SR = UnparsedDefaultArgLocs[Param]; 405 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 406 << SR; 407 delete Toks; 408 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 409 } else if (Param->getDefaultArg()) { 410 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 411 << Param->getDefaultArg()->getSourceRange(); 412 Param->setDefaultArg(nullptr); 413 } 414 } 415 } else if (chunk.Kind != DeclaratorChunk::Paren) { 416 MightBeFunction = false; 417 } 418 } 419 } 420 421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 422 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 423 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 424 if (!PVD->hasDefaultArg()) 425 return false; 426 if (!PVD->hasInheritedDefaultArg()) 427 return true; 428 } 429 return false; 430 } 431 432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 433 /// function, once we already know that they have the same 434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 435 /// error, false otherwise. 436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 437 Scope *S) { 438 bool Invalid = false; 439 440 // The declaration context corresponding to the scope is the semantic 441 // parent, unless this is a local function declaration, in which case 442 // it is that surrounding function. 443 DeclContext *ScopeDC = New->isLocalExternDecl() 444 ? New->getLexicalDeclContext() 445 : New->getDeclContext(); 446 447 // Find the previous declaration for the purpose of default arguments. 448 FunctionDecl *PrevForDefaultArgs = Old; 449 for (/**/; PrevForDefaultArgs; 450 // Don't bother looking back past the latest decl if this is a local 451 // extern declaration; nothing else could work. 452 PrevForDefaultArgs = New->isLocalExternDecl() 453 ? nullptr 454 : PrevForDefaultArgs->getPreviousDecl()) { 455 // Ignore hidden declarations. 456 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 457 continue; 458 459 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 460 !New->isCXXClassMember()) { 461 // Ignore default arguments of old decl if they are not in 462 // the same scope and this is not an out-of-line definition of 463 // a member function. 464 continue; 465 } 466 467 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 468 // If only one of these is a local function declaration, then they are 469 // declared in different scopes, even though isDeclInScope may think 470 // they're in the same scope. (If both are local, the scope check is 471 // sufficent, and if neither is local, then they are in the same scope.) 472 continue; 473 } 474 475 // We found the right previous declaration. 476 break; 477 } 478 479 // C++ [dcl.fct.default]p4: 480 // For non-template functions, default arguments can be added in 481 // later declarations of a function in the same 482 // scope. Declarations in different scopes have completely 483 // distinct sets of default arguments. That is, declarations in 484 // inner scopes do not acquire default arguments from 485 // declarations in outer scopes, and vice versa. In a given 486 // function declaration, all parameters subsequent to a 487 // parameter with a default argument shall have default 488 // arguments supplied in this or previous declarations. A 489 // default argument shall not be redefined by a later 490 // declaration (not even to the same value). 491 // 492 // C++ [dcl.fct.default]p6: 493 // Except for member functions of class templates, the default arguments 494 // in a member function definition that appears outside of the class 495 // definition are added to the set of default arguments provided by the 496 // member function declaration in the class definition. 497 for (unsigned p = 0, NumParams = PrevForDefaultArgs 498 ? PrevForDefaultArgs->getNumParams() 499 : 0; 500 p < NumParams; ++p) { 501 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 502 ParmVarDecl *NewParam = New->getParamDecl(p); 503 504 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 505 bool NewParamHasDfl = NewParam->hasDefaultArg(); 506 507 if (OldParamHasDfl && NewParamHasDfl) { 508 unsigned DiagDefaultParamID = 509 diag::err_param_default_argument_redefinition; 510 511 // MSVC accepts that default parameters be redefined for member functions 512 // of template class. The new default parameter's value is ignored. 513 Invalid = true; 514 if (getLangOpts().MicrosoftExt) { 515 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 516 if (MD && MD->getParent()->getDescribedClassTemplate()) { 517 // Merge the old default argument into the new parameter. 518 NewParam->setHasInheritedDefaultArg(); 519 if (OldParam->hasUninstantiatedDefaultArg()) 520 NewParam->setUninstantiatedDefaultArg( 521 OldParam->getUninstantiatedDefaultArg()); 522 else 523 NewParam->setDefaultArg(OldParam->getInit()); 524 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 525 Invalid = false; 526 } 527 } 528 529 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 530 // hint here. Alternatively, we could walk the type-source information 531 // for NewParam to find the last source location in the type... but it 532 // isn't worth the effort right now. This is the kind of test case that 533 // is hard to get right: 534 // int f(int); 535 // void g(int (*fp)(int) = f); 536 // void g(int (*fp)(int) = &f); 537 Diag(NewParam->getLocation(), DiagDefaultParamID) 538 << NewParam->getDefaultArgRange(); 539 540 // Look for the function declaration where the default argument was 541 // actually written, which may be a declaration prior to Old. 542 for (auto Older = PrevForDefaultArgs; 543 OldParam->hasInheritedDefaultArg(); /**/) { 544 Older = Older->getPreviousDecl(); 545 OldParam = Older->getParamDecl(p); 546 } 547 548 Diag(OldParam->getLocation(), diag::note_previous_definition) 549 << OldParam->getDefaultArgRange(); 550 } else if (OldParamHasDfl) { 551 // Merge the old default argument into the new parameter. 552 // It's important to use getInit() here; getDefaultArg() 553 // strips off any top-level ExprWithCleanups. 554 NewParam->setHasInheritedDefaultArg(); 555 if (OldParam->hasUnparsedDefaultArg()) 556 NewParam->setUnparsedDefaultArg(); 557 else if (OldParam->hasUninstantiatedDefaultArg()) 558 NewParam->setUninstantiatedDefaultArg( 559 OldParam->getUninstantiatedDefaultArg()); 560 else 561 NewParam->setDefaultArg(OldParam->getInit()); 562 } else if (NewParamHasDfl) { 563 if (New->getDescribedFunctionTemplate()) { 564 // Paragraph 4, quoted above, only applies to non-template functions. 565 Diag(NewParam->getLocation(), 566 diag::err_param_default_argument_template_redecl) 567 << NewParam->getDefaultArgRange(); 568 Diag(PrevForDefaultArgs->getLocation(), 569 diag::note_template_prev_declaration) 570 << false; 571 } else if (New->getTemplateSpecializationKind() 572 != TSK_ImplicitInstantiation && 573 New->getTemplateSpecializationKind() != TSK_Undeclared) { 574 // C++ [temp.expr.spec]p21: 575 // Default function arguments shall not be specified in a declaration 576 // or a definition for one of the following explicit specializations: 577 // - the explicit specialization of a function template; 578 // - the explicit specialization of a member function template; 579 // - the explicit specialization of a member function of a class 580 // template where the class template specialization to which the 581 // member function specialization belongs is implicitly 582 // instantiated. 583 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 584 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 585 << New->getDeclName() 586 << NewParam->getDefaultArgRange(); 587 } else if (New->getDeclContext()->isDependentContext()) { 588 // C++ [dcl.fct.default]p6 (DR217): 589 // Default arguments for a member function of a class template shall 590 // be specified on the initial declaration of the member function 591 // within the class template. 592 // 593 // Reading the tea leaves a bit in DR217 and its reference to DR205 594 // leads me to the conclusion that one cannot add default function 595 // arguments for an out-of-line definition of a member function of a 596 // dependent type. 597 int WhichKind = 2; 598 if (CXXRecordDecl *Record 599 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 600 if (Record->getDescribedClassTemplate()) 601 WhichKind = 0; 602 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 603 WhichKind = 1; 604 else 605 WhichKind = 2; 606 } 607 608 Diag(NewParam->getLocation(), 609 diag::err_param_default_argument_member_template_redecl) 610 << WhichKind 611 << NewParam->getDefaultArgRange(); 612 } 613 } 614 } 615 616 // DR1344: If a default argument is added outside a class definition and that 617 // default argument makes the function a special member function, the program 618 // is ill-formed. This can only happen for constructors. 619 if (isa<CXXConstructorDecl>(New) && 620 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 621 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 622 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 623 if (NewSM != OldSM) { 624 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 625 assert(NewParam->hasDefaultArg()); 626 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 627 << NewParam->getDefaultArgRange() << NewSM; 628 Diag(Old->getLocation(), diag::note_previous_declaration); 629 } 630 } 631 632 const FunctionDecl *Def; 633 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 634 // template has a constexpr specifier then all its declarations shall 635 // contain the constexpr specifier. 636 if (New->isConstexpr() != Old->isConstexpr()) { 637 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 638 << New << New->isConstexpr(); 639 Diag(Old->getLocation(), diag::note_previous_declaration); 640 Invalid = true; 641 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 642 Old->isDefined(Def)) { 643 // C++11 [dcl.fcn.spec]p4: 644 // If the definition of a function appears in a translation unit before its 645 // first declaration as inline, the program is ill-formed. 646 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 647 Diag(Def->getLocation(), diag::note_previous_definition); 648 Invalid = true; 649 } 650 651 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 652 // argument expression, that declaration shall be a definition and shall be 653 // the only declaration of the function or function template in the 654 // translation unit. 655 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 656 functionDeclHasDefaultArgument(Old)) { 657 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 658 Diag(Old->getLocation(), diag::note_previous_declaration); 659 Invalid = true; 660 } 661 662 if (CheckEquivalentExceptionSpec(Old, New)) 663 Invalid = true; 664 665 return Invalid; 666 } 667 668 NamedDecl * 669 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 670 MultiTemplateParamsArg TemplateParamLists) { 671 assert(D.isDecompositionDeclarator()); 672 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 673 674 // The syntax only allows a decomposition declarator as a simple-declaration 675 // or a for-range-declaration, but we parse it in more cases than that. 676 if (!D.mayHaveDecompositionDeclarator()) { 677 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 678 << Decomp.getSourceRange(); 679 return nullptr; 680 } 681 682 if (!TemplateParamLists.empty()) { 683 // FIXME: There's no rule against this, but there are also no rules that 684 // would actually make it usable, so we reject it for now. 685 Diag(TemplateParamLists.front()->getTemplateLoc(), 686 diag::err_decomp_decl_template); 687 return nullptr; 688 } 689 690 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z 691 ? diag::warn_cxx14_compat_decomp_decl 692 : diag::ext_decomp_decl) 693 << Decomp.getSourceRange(); 694 695 // The semantic context is always just the current context. 696 DeclContext *const DC = CurContext; 697 698 // C++1z [dcl.dcl]/8: 699 // The decl-specifier-seq shall contain only the type-specifier auto 700 // and cv-qualifiers. 701 auto &DS = D.getDeclSpec(); 702 { 703 SmallVector<StringRef, 8> BadSpecifiers; 704 SmallVector<SourceLocation, 8> BadSpecifierLocs; 705 if (auto SCS = DS.getStorageClassSpec()) { 706 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 707 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 708 } 709 if (auto TSCS = DS.getThreadStorageClassSpec()) { 710 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 711 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 712 } 713 if (DS.isConstexprSpecified()) { 714 BadSpecifiers.push_back("constexpr"); 715 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 716 } 717 if (DS.isInlineSpecified()) { 718 BadSpecifiers.push_back("inline"); 719 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 720 } 721 if (!BadSpecifiers.empty()) { 722 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 723 Err << (int)BadSpecifiers.size() 724 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 725 // Don't add FixItHints to remove the specifiers; we do still respect 726 // them when building the underlying variable. 727 for (auto Loc : BadSpecifierLocs) 728 Err << SourceRange(Loc, Loc); 729 } 730 // We can't recover from it being declared as a typedef. 731 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 732 return nullptr; 733 } 734 735 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 736 QualType R = TInfo->getType(); 737 738 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 739 UPPC_DeclarationType)) 740 D.setInvalidType(); 741 742 // The syntax only allows a single ref-qualifier prior to the decomposition 743 // declarator. No other declarator chunks are permitted. Also check the type 744 // specifier here. 745 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 746 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 747 (D.getNumTypeObjects() == 1 && 748 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 749 Diag(Decomp.getLSquareLoc(), 750 (D.hasGroupingParens() || 751 (D.getNumTypeObjects() && 752 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 753 ? diag::err_decomp_decl_parens 754 : diag::err_decomp_decl_type) 755 << R; 756 757 // In most cases, there's no actual problem with an explicitly-specified 758 // type, but a function type won't work here, and ActOnVariableDeclarator 759 // shouldn't be called for such a type. 760 if (R->isFunctionType()) 761 D.setInvalidType(); 762 } 763 764 // Build the BindingDecls. 765 SmallVector<BindingDecl*, 8> Bindings; 766 767 // Build the BindingDecls. 768 for (auto &B : D.getDecompositionDeclarator().bindings()) { 769 // Check for name conflicts. 770 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 771 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 772 ForRedeclaration); 773 LookupName(Previous, S, 774 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 775 776 // It's not permitted to shadow a template parameter name. 777 if (Previous.isSingleResult() && 778 Previous.getFoundDecl()->isTemplateParameter()) { 779 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 780 Previous.getFoundDecl()); 781 Previous.clear(); 782 } 783 784 bool ConsiderLinkage = DC->isFunctionOrMethod() && 785 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 786 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 787 /*AllowInlineNamespace*/false); 788 if (!Previous.empty()) { 789 auto *Old = Previous.getRepresentativeDecl(); 790 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 791 Diag(Old->getLocation(), diag::note_previous_definition); 792 } 793 794 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 795 PushOnScopeChains(BD, S, true); 796 Bindings.push_back(BD); 797 ParsingInitForAutoVars.insert(BD); 798 } 799 800 // There are no prior lookup results for the variable itself, because it 801 // is unnamed. 802 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 803 Decomp.getLSquareLoc()); 804 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 805 806 // Build the variable that holds the non-decomposed object. 807 bool AddToScope = true; 808 NamedDecl *New = 809 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 810 MultiTemplateParamsArg(), AddToScope, Bindings); 811 CurContext->addHiddenDecl(New); 812 813 if (isInOpenMPDeclareTargetContext()) 814 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 815 816 return New; 817 } 818 819 static bool checkSimpleDecomposition( 820 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 821 QualType DecompType, llvm::APSInt NumElems, QualType ElemType, 822 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 823 if ((int64_t)Bindings.size() != NumElems) { 824 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 825 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 826 << (NumElems < Bindings.size()); 827 return true; 828 } 829 830 unsigned I = 0; 831 for (auto *B : Bindings) { 832 SourceLocation Loc = B->getLocation(); 833 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 834 if (E.isInvalid()) 835 return true; 836 E = GetInit(Loc, E.get(), I++); 837 if (E.isInvalid()) 838 return true; 839 B->setBinding(ElemType, E.get()); 840 } 841 842 return false; 843 } 844 845 static bool checkArrayLikeDecomposition(Sema &S, 846 ArrayRef<BindingDecl *> Bindings, 847 ValueDecl *Src, QualType DecompType, 848 llvm::APSInt NumElems, 849 QualType ElemType) { 850 return checkSimpleDecomposition( 851 S, Bindings, Src, DecompType, NumElems, ElemType, 852 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 853 ExprResult E = S.ActOnIntegerConstant(Loc, I); 854 if (E.isInvalid()) 855 return ExprError(); 856 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 857 }); 858 } 859 860 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 861 ValueDecl *Src, QualType DecompType, 862 const ConstantArrayType *CAT) { 863 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 864 llvm::APSInt(CAT->getSize()), 865 CAT->getElementType()); 866 } 867 868 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 869 ValueDecl *Src, QualType DecompType, 870 const VectorType *VT) { 871 return checkArrayLikeDecomposition( 872 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 873 S.Context.getQualifiedType(VT->getElementType(), 874 DecompType.getQualifiers())); 875 } 876 877 static bool checkComplexDecomposition(Sema &S, 878 ArrayRef<BindingDecl *> Bindings, 879 ValueDecl *Src, QualType DecompType, 880 const ComplexType *CT) { 881 return checkSimpleDecomposition( 882 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 883 S.Context.getQualifiedType(CT->getElementType(), 884 DecompType.getQualifiers()), 885 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 886 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 887 }); 888 } 889 890 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 891 TemplateArgumentListInfo &Args) { 892 SmallString<128> SS; 893 llvm::raw_svector_ostream OS(SS); 894 bool First = true; 895 for (auto &Arg : Args.arguments()) { 896 if (!First) 897 OS << ", "; 898 Arg.getArgument().print(PrintingPolicy, OS); 899 First = false; 900 } 901 return OS.str(); 902 } 903 904 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 905 SourceLocation Loc, StringRef Trait, 906 TemplateArgumentListInfo &Args, 907 unsigned DiagID) { 908 auto DiagnoseMissing = [&] { 909 if (DiagID) 910 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 911 Args); 912 return true; 913 }; 914 915 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 916 NamespaceDecl *Std = S.getStdNamespace(); 917 if (!Std) 918 return DiagnoseMissing(); 919 920 // Look up the trait itself, within namespace std. We can diagnose various 921 // problems with this lookup even if we've been asked to not diagnose a 922 // missing specialization, because this can only fail if the user has been 923 // declaring their own names in namespace std or we don't support the 924 // standard library implementation in use. 925 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 926 Loc, Sema::LookupOrdinaryName); 927 if (!S.LookupQualifiedName(Result, Std)) 928 return DiagnoseMissing(); 929 if (Result.isAmbiguous()) 930 return true; 931 932 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 933 if (!TraitTD) { 934 Result.suppressDiagnostics(); 935 NamedDecl *Found = *Result.begin(); 936 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 937 S.Diag(Found->getLocation(), diag::note_declared_at); 938 return true; 939 } 940 941 // Build the template-id. 942 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 943 if (TraitTy.isNull()) 944 return true; 945 if (!S.isCompleteType(Loc, TraitTy)) { 946 if (DiagID) 947 S.RequireCompleteType( 948 Loc, TraitTy, DiagID, 949 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 950 return true; 951 } 952 953 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 954 assert(RD && "specialization of class template is not a class?"); 955 956 // Look up the member of the trait type. 957 S.LookupQualifiedName(TraitMemberLookup, RD); 958 return TraitMemberLookup.isAmbiguous(); 959 } 960 961 static TemplateArgumentLoc 962 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 963 uint64_t I) { 964 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 965 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 966 } 967 968 static TemplateArgumentLoc 969 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 970 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 971 } 972 973 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 974 975 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 976 llvm::APSInt &Size) { 977 EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated); 978 979 DeclarationName Value = S.PP.getIdentifierInfo("value"); 980 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 981 982 // Form template argument list for tuple_size<T>. 983 TemplateArgumentListInfo Args(Loc, Loc); 984 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 985 986 // If there's no tuple_size specialization, it's not tuple-like. 987 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 988 return IsTupleLike::NotTupleLike; 989 990 // FIXME: According to the standard, we're not supposed to diagnose if any 991 // of the steps below fail (or if lookup for ::value is ambiguous or otherwise 992 // results in an error), but this is subject to a pending CWG issue / NB 993 // comment, which says we do diagnose if tuple_size<T> is complete but 994 // tuple_size<T>::value is not an ICE. 995 996 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 997 LookupResult &R; 998 TemplateArgumentListInfo &Args; 999 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1000 : R(R), Args(Args) {} 1001 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1002 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1003 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1004 } 1005 } Diagnoser(R, Args); 1006 1007 if (R.empty()) { 1008 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1009 return IsTupleLike::Error; 1010 } 1011 1012 ExprResult E = 1013 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1014 if (E.isInvalid()) 1015 return IsTupleLike::Error; 1016 1017 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1018 if (E.isInvalid()) 1019 return IsTupleLike::Error; 1020 1021 return IsTupleLike::TupleLike; 1022 } 1023 1024 /// \return std::tuple_element<I, T>::type. 1025 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1026 unsigned I, QualType T) { 1027 // Form template argument list for tuple_element<I, T>. 1028 TemplateArgumentListInfo Args(Loc, Loc); 1029 Args.addArgument( 1030 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1031 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1032 1033 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1034 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1035 if (lookupStdTypeTraitMember( 1036 S, R, Loc, "tuple_element", Args, 1037 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1038 return QualType(); 1039 1040 auto *TD = R.getAsSingle<TypeDecl>(); 1041 if (!TD) { 1042 R.suppressDiagnostics(); 1043 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1044 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1045 if (!R.empty()) 1046 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1047 return QualType(); 1048 } 1049 1050 return S.Context.getTypeDeclType(TD); 1051 } 1052 1053 namespace { 1054 struct BindingDiagnosticTrap { 1055 Sema &S; 1056 DiagnosticErrorTrap Trap; 1057 BindingDecl *BD; 1058 1059 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1060 : S(S), Trap(S.Diags), BD(BD) {} 1061 ~BindingDiagnosticTrap() { 1062 if (Trap.hasErrorOccurred()) 1063 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1064 } 1065 }; 1066 } 1067 1068 static bool checkTupleLikeDecomposition(Sema &S, 1069 ArrayRef<BindingDecl *> Bindings, 1070 VarDecl *Src, QualType DecompType, 1071 llvm::APSInt TupleSize) { 1072 if ((int64_t)Bindings.size() != TupleSize) { 1073 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1074 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1075 << (TupleSize < Bindings.size()); 1076 return true; 1077 } 1078 1079 if (Bindings.empty()) 1080 return false; 1081 1082 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1083 1084 // [dcl.decomp]p3: 1085 // The unqualified-id get is looked up in the scope of E by class member 1086 // access lookup 1087 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1088 bool UseMemberGet = false; 1089 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1090 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1091 S.LookupQualifiedName(MemberGet, RD); 1092 if (MemberGet.isAmbiguous()) 1093 return true; 1094 UseMemberGet = !MemberGet.empty(); 1095 S.FilterAcceptableTemplateNames(MemberGet); 1096 } 1097 1098 unsigned I = 0; 1099 for (auto *B : Bindings) { 1100 BindingDiagnosticTrap Trap(S, B); 1101 SourceLocation Loc = B->getLocation(); 1102 1103 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1104 if (E.isInvalid()) 1105 return true; 1106 1107 // e is an lvalue if the type of the entity is an lvalue reference and 1108 // an xvalue otherwise 1109 if (!Src->getType()->isLValueReferenceType()) 1110 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1111 E.get(), nullptr, VK_XValue); 1112 1113 TemplateArgumentListInfo Args(Loc, Loc); 1114 Args.addArgument( 1115 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1116 1117 if (UseMemberGet) { 1118 // if [lookup of member get] finds at least one declaration, the 1119 // initializer is e.get<i-1>(). 1120 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1121 CXXScopeSpec(), SourceLocation(), nullptr, 1122 MemberGet, &Args, nullptr); 1123 if (E.isInvalid()) 1124 return true; 1125 1126 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1127 } else { 1128 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1129 // in the associated namespaces. 1130 Expr *Get = UnresolvedLookupExpr::Create( 1131 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1132 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1133 UnresolvedSetIterator(), UnresolvedSetIterator()); 1134 1135 Expr *Arg = E.get(); 1136 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1137 } 1138 if (E.isInvalid()) 1139 return true; 1140 Expr *Init = E.get(); 1141 1142 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1143 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1144 if (T.isNull()) 1145 return true; 1146 1147 // each vi is a variable of type "reference to T" initialized with the 1148 // initializer, where the reference is an lvalue reference if the 1149 // initializer is an lvalue and an rvalue reference otherwise 1150 QualType RefType = 1151 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1152 if (RefType.isNull()) 1153 return true; 1154 auto *RefVD = VarDecl::Create( 1155 S.Context, Src->getDeclContext(), Loc, Loc, 1156 B->getDeclName().getAsIdentifierInfo(), RefType, 1157 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1158 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1159 RefVD->setTSCSpec(Src->getTSCSpec()); 1160 RefVD->setImplicit(); 1161 if (Src->isInlineSpecified()) 1162 RefVD->setInlineSpecified(); 1163 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1164 1165 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1166 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1167 InitializationSequence Seq(S, Entity, Kind, Init); 1168 E = Seq.Perform(S, Entity, Kind, Init); 1169 if (E.isInvalid()) 1170 return true; 1171 E = S.ActOnFinishFullExpr(E.get(), Loc); 1172 if (E.isInvalid()) 1173 return true; 1174 RefVD->setInit(E.get()); 1175 RefVD->checkInitIsICE(); 1176 1177 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1178 DeclarationNameInfo(B->getDeclName(), Loc), 1179 RefVD); 1180 if (E.isInvalid()) 1181 return true; 1182 1183 B->setBinding(T, E.get()); 1184 I++; 1185 } 1186 1187 return false; 1188 } 1189 1190 /// Find the base class to decompose in a built-in decomposition of a class type. 1191 /// This base class search is, unfortunately, not quite like any other that we 1192 /// perform anywhere else in C++. 1193 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1194 SourceLocation Loc, 1195 const CXXRecordDecl *RD, 1196 CXXCastPath &BasePath) { 1197 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1198 CXXBasePath &Path) { 1199 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1200 }; 1201 1202 const CXXRecordDecl *ClassWithFields = nullptr; 1203 if (RD->hasDirectFields()) 1204 // [dcl.decomp]p4: 1205 // Otherwise, all of E's non-static data members shall be public direct 1206 // members of E ... 1207 ClassWithFields = RD; 1208 else { 1209 // ... or of ... 1210 CXXBasePaths Paths; 1211 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1212 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1213 // If no classes have fields, just decompose RD itself. (This will work 1214 // if and only if zero bindings were provided.) 1215 return RD; 1216 } 1217 1218 CXXBasePath *BestPath = nullptr; 1219 for (auto &P : Paths) { 1220 if (!BestPath) 1221 BestPath = &P; 1222 else if (!S.Context.hasSameType(P.back().Base->getType(), 1223 BestPath->back().Base->getType())) { 1224 // ... the same ... 1225 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1226 << false << RD << BestPath->back().Base->getType() 1227 << P.back().Base->getType(); 1228 return nullptr; 1229 } else if (P.Access < BestPath->Access) { 1230 BestPath = &P; 1231 } 1232 } 1233 1234 // ... unambiguous ... 1235 QualType BaseType = BestPath->back().Base->getType(); 1236 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1237 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1238 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1239 return nullptr; 1240 } 1241 1242 // ... public base class of E. 1243 if (BestPath->Access != AS_public) { 1244 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1245 << RD << BaseType; 1246 for (auto &BS : *BestPath) { 1247 if (BS.Base->getAccessSpecifier() != AS_public) { 1248 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1249 << (BS.Base->getAccessSpecifier() == AS_protected) 1250 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1251 break; 1252 } 1253 } 1254 return nullptr; 1255 } 1256 1257 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1258 S.BuildBasePathArray(Paths, BasePath); 1259 } 1260 1261 // The above search did not check whether the selected class itself has base 1262 // classes with fields, so check that now. 1263 CXXBasePaths Paths; 1264 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1265 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1266 << (ClassWithFields == RD) << RD << ClassWithFields 1267 << Paths.front().back().Base->getType(); 1268 return nullptr; 1269 } 1270 1271 return ClassWithFields; 1272 } 1273 1274 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1275 ValueDecl *Src, QualType DecompType, 1276 const CXXRecordDecl *RD) { 1277 CXXCastPath BasePath; 1278 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1279 if (!RD) 1280 return true; 1281 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1282 DecompType.getQualifiers()); 1283 1284 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1285 unsigned NumFields = std::distance(RD->field_begin(), RD->field_end()); 1286 assert(Bindings.size() != NumFields); 1287 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1288 << DecompType << (unsigned)Bindings.size() << NumFields 1289 << (NumFields < Bindings.size()); 1290 return true; 1291 }; 1292 1293 // all of E's non-static data members shall be public [...] members, 1294 // E shall not have an anonymous union member, ... 1295 unsigned I = 0; 1296 for (auto *FD : RD->fields()) { 1297 if (FD->isUnnamedBitfield()) 1298 continue; 1299 1300 if (FD->isAnonymousStructOrUnion()) { 1301 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1302 << DecompType << FD->getType()->isUnionType(); 1303 S.Diag(FD->getLocation(), diag::note_declared_at); 1304 return true; 1305 } 1306 1307 // We have a real field to bind. 1308 if (I >= Bindings.size()) 1309 return DiagnoseBadNumberOfBindings(); 1310 auto *B = Bindings[I++]; 1311 1312 SourceLocation Loc = B->getLocation(); 1313 if (FD->getAccess() != AS_public) { 1314 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1315 1316 // Determine whether the access specifier was explicit. 1317 bool Implicit = true; 1318 for (const auto *D : RD->decls()) { 1319 if (declaresSameEntity(D, FD)) 1320 break; 1321 if (isa<AccessSpecDecl>(D)) { 1322 Implicit = false; 1323 break; 1324 } 1325 } 1326 1327 S.Diag(FD->getLocation(), diag::note_access_natural) 1328 << (FD->getAccess() == AS_protected) << Implicit; 1329 return true; 1330 } 1331 1332 // Initialize the binding to Src.FD. 1333 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1334 if (E.isInvalid()) 1335 return true; 1336 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1337 VK_LValue, &BasePath); 1338 if (E.isInvalid()) 1339 return true; 1340 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1341 CXXScopeSpec(), FD, 1342 DeclAccessPair::make(FD, FD->getAccess()), 1343 DeclarationNameInfo(FD->getDeclName(), Loc)); 1344 if (E.isInvalid()) 1345 return true; 1346 1347 // If the type of the member is T, the referenced type is cv T, where cv is 1348 // the cv-qualification of the decomposition expression. 1349 // 1350 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1351 // 'const' to the type of the field. 1352 Qualifiers Q = DecompType.getQualifiers(); 1353 if (FD->isMutable()) 1354 Q.removeConst(); 1355 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1356 } 1357 1358 if (I != Bindings.size()) 1359 return DiagnoseBadNumberOfBindings(); 1360 1361 return false; 1362 } 1363 1364 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1365 QualType DecompType = DD->getType(); 1366 1367 // If the type of the decomposition is dependent, then so is the type of 1368 // each binding. 1369 if (DecompType->isDependentType()) { 1370 for (auto *B : DD->bindings()) 1371 B->setType(Context.DependentTy); 1372 return; 1373 } 1374 1375 DecompType = DecompType.getNonReferenceType(); 1376 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1377 1378 // C++1z [dcl.decomp]/2: 1379 // If E is an array type [...] 1380 // As an extension, we also support decomposition of built-in complex and 1381 // vector types. 1382 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1383 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1384 DD->setInvalidDecl(); 1385 return; 1386 } 1387 if (auto *VT = DecompType->getAs<VectorType>()) { 1388 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1389 DD->setInvalidDecl(); 1390 return; 1391 } 1392 if (auto *CT = DecompType->getAs<ComplexType>()) { 1393 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1394 DD->setInvalidDecl(); 1395 return; 1396 } 1397 1398 // C++1z [dcl.decomp]/3: 1399 // if the expression std::tuple_size<E>::value is a well-formed integral 1400 // constant expression, [...] 1401 llvm::APSInt TupleSize(32); 1402 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1403 case IsTupleLike::Error: 1404 DD->setInvalidDecl(); 1405 return; 1406 1407 case IsTupleLike::TupleLike: 1408 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1409 DD->setInvalidDecl(); 1410 return; 1411 1412 case IsTupleLike::NotTupleLike: 1413 break; 1414 } 1415 1416 // C++1z [dcl.dcl]/8: 1417 // [E shall be of array or non-union class type] 1418 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1419 if (!RD || RD->isUnion()) { 1420 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1421 << DD << !RD << DecompType; 1422 DD->setInvalidDecl(); 1423 return; 1424 } 1425 1426 // C++1z [dcl.decomp]/4: 1427 // all of E's non-static data members shall be [...] direct members of 1428 // E or of the same unambiguous public base class of E, ... 1429 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1430 DD->setInvalidDecl(); 1431 } 1432 1433 /// \brief Merge the exception specifications of two variable declarations. 1434 /// 1435 /// This is called when there's a redeclaration of a VarDecl. The function 1436 /// checks if the redeclaration might have an exception specification and 1437 /// validates compatibility and merges the specs if necessary. 1438 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1439 // Shortcut if exceptions are disabled. 1440 if (!getLangOpts().CXXExceptions) 1441 return; 1442 1443 assert(Context.hasSameType(New->getType(), Old->getType()) && 1444 "Should only be called if types are otherwise the same."); 1445 1446 QualType NewType = New->getType(); 1447 QualType OldType = Old->getType(); 1448 1449 // We're only interested in pointers and references to functions, as well 1450 // as pointers to member functions. 1451 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1452 NewType = R->getPointeeType(); 1453 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1454 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1455 NewType = P->getPointeeType(); 1456 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1457 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1458 NewType = M->getPointeeType(); 1459 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1460 } 1461 1462 if (!NewType->isFunctionProtoType()) 1463 return; 1464 1465 // There's lots of special cases for functions. For function pointers, system 1466 // libraries are hopefully not as broken so that we don't need these 1467 // workarounds. 1468 if (CheckEquivalentExceptionSpec( 1469 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1470 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1471 New->setInvalidDecl(); 1472 } 1473 } 1474 1475 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1476 /// function declaration are well-formed according to C++ 1477 /// [dcl.fct.default]. 1478 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1479 unsigned NumParams = FD->getNumParams(); 1480 unsigned p; 1481 1482 // Find first parameter with a default argument 1483 for (p = 0; p < NumParams; ++p) { 1484 ParmVarDecl *Param = FD->getParamDecl(p); 1485 if (Param->hasDefaultArg()) 1486 break; 1487 } 1488 1489 // C++11 [dcl.fct.default]p4: 1490 // In a given function declaration, each parameter subsequent to a parameter 1491 // with a default argument shall have a default argument supplied in this or 1492 // a previous declaration or shall be a function parameter pack. A default 1493 // argument shall not be redefined by a later declaration (not even to the 1494 // same value). 1495 unsigned LastMissingDefaultArg = 0; 1496 for (; p < NumParams; ++p) { 1497 ParmVarDecl *Param = FD->getParamDecl(p); 1498 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1499 if (Param->isInvalidDecl()) 1500 /* We already complained about this parameter. */; 1501 else if (Param->getIdentifier()) 1502 Diag(Param->getLocation(), 1503 diag::err_param_default_argument_missing_name) 1504 << Param->getIdentifier(); 1505 else 1506 Diag(Param->getLocation(), 1507 diag::err_param_default_argument_missing); 1508 1509 LastMissingDefaultArg = p; 1510 } 1511 } 1512 1513 if (LastMissingDefaultArg > 0) { 1514 // Some default arguments were missing. Clear out all of the 1515 // default arguments up to (and including) the last missing 1516 // default argument, so that we leave the function parameters 1517 // in a semantically valid state. 1518 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1519 ParmVarDecl *Param = FD->getParamDecl(p); 1520 if (Param->hasDefaultArg()) { 1521 Param->setDefaultArg(nullptr); 1522 } 1523 } 1524 } 1525 } 1526 1527 // CheckConstexprParameterTypes - Check whether a function's parameter types 1528 // are all literal types. If so, return true. If not, produce a suitable 1529 // diagnostic and return false. 1530 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1531 const FunctionDecl *FD) { 1532 unsigned ArgIndex = 0; 1533 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1534 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1535 e = FT->param_type_end(); 1536 i != e; ++i, ++ArgIndex) { 1537 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1538 SourceLocation ParamLoc = PD->getLocation(); 1539 if (!(*i)->isDependentType() && 1540 SemaRef.RequireLiteralType(ParamLoc, *i, 1541 diag::err_constexpr_non_literal_param, 1542 ArgIndex+1, PD->getSourceRange(), 1543 isa<CXXConstructorDecl>(FD))) 1544 return false; 1545 } 1546 return true; 1547 } 1548 1549 /// \brief Get diagnostic %select index for tag kind for 1550 /// record diagnostic message. 1551 /// WARNING: Indexes apply to particular diagnostics only! 1552 /// 1553 /// \returns diagnostic %select index. 1554 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1555 switch (Tag) { 1556 case TTK_Struct: return 0; 1557 case TTK_Interface: return 1; 1558 case TTK_Class: return 2; 1559 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1560 } 1561 } 1562 1563 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1564 // the requirements of a constexpr function definition or a constexpr 1565 // constructor definition. If so, return true. If not, produce appropriate 1566 // diagnostics and return false. 1567 // 1568 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1569 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1570 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1571 if (MD && MD->isInstance()) { 1572 // C++11 [dcl.constexpr]p4: 1573 // The definition of a constexpr constructor shall satisfy the following 1574 // constraints: 1575 // - the class shall not have any virtual base classes; 1576 const CXXRecordDecl *RD = MD->getParent(); 1577 if (RD->getNumVBases()) { 1578 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1579 << isa<CXXConstructorDecl>(NewFD) 1580 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1581 for (const auto &I : RD->vbases()) 1582 Diag(I.getLocStart(), 1583 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1584 return false; 1585 } 1586 } 1587 1588 if (!isa<CXXConstructorDecl>(NewFD)) { 1589 // C++11 [dcl.constexpr]p3: 1590 // The definition of a constexpr function shall satisfy the following 1591 // constraints: 1592 // - it shall not be virtual; 1593 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1594 if (Method && Method->isVirtual()) { 1595 Method = Method->getCanonicalDecl(); 1596 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1597 1598 // If it's not obvious why this function is virtual, find an overridden 1599 // function which uses the 'virtual' keyword. 1600 const CXXMethodDecl *WrittenVirtual = Method; 1601 while (!WrittenVirtual->isVirtualAsWritten()) 1602 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1603 if (WrittenVirtual != Method) 1604 Diag(WrittenVirtual->getLocation(), 1605 diag::note_overridden_virtual_function); 1606 return false; 1607 } 1608 1609 // - its return type shall be a literal type; 1610 QualType RT = NewFD->getReturnType(); 1611 if (!RT->isDependentType() && 1612 RequireLiteralType(NewFD->getLocation(), RT, 1613 diag::err_constexpr_non_literal_return)) 1614 return false; 1615 } 1616 1617 // - each of its parameter types shall be a literal type; 1618 if (!CheckConstexprParameterTypes(*this, NewFD)) 1619 return false; 1620 1621 return true; 1622 } 1623 1624 /// Check the given declaration statement is legal within a constexpr function 1625 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1626 /// 1627 /// \return true if the body is OK (maybe only as an extension), false if we 1628 /// have diagnosed a problem. 1629 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1630 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1631 // C++11 [dcl.constexpr]p3 and p4: 1632 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1633 // contain only 1634 for (const auto *DclIt : DS->decls()) { 1635 switch (DclIt->getKind()) { 1636 case Decl::StaticAssert: 1637 case Decl::Using: 1638 case Decl::UsingShadow: 1639 case Decl::UsingDirective: 1640 case Decl::UnresolvedUsingTypename: 1641 case Decl::UnresolvedUsingValue: 1642 // - static_assert-declarations 1643 // - using-declarations, 1644 // - using-directives, 1645 continue; 1646 1647 case Decl::Typedef: 1648 case Decl::TypeAlias: { 1649 // - typedef declarations and alias-declarations that do not define 1650 // classes or enumerations, 1651 const auto *TN = cast<TypedefNameDecl>(DclIt); 1652 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1653 // Don't allow variably-modified types in constexpr functions. 1654 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1655 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1656 << TL.getSourceRange() << TL.getType() 1657 << isa<CXXConstructorDecl>(Dcl); 1658 return false; 1659 } 1660 continue; 1661 } 1662 1663 case Decl::Enum: 1664 case Decl::CXXRecord: 1665 // C++1y allows types to be defined, not just declared. 1666 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1667 SemaRef.Diag(DS->getLocStart(), 1668 SemaRef.getLangOpts().CPlusPlus14 1669 ? diag::warn_cxx11_compat_constexpr_type_definition 1670 : diag::ext_constexpr_type_definition) 1671 << isa<CXXConstructorDecl>(Dcl); 1672 continue; 1673 1674 case Decl::EnumConstant: 1675 case Decl::IndirectField: 1676 case Decl::ParmVar: 1677 // These can only appear with other declarations which are banned in 1678 // C++11 and permitted in C++1y, so ignore them. 1679 continue; 1680 1681 case Decl::Var: 1682 case Decl::Decomposition: { 1683 // C++1y [dcl.constexpr]p3 allows anything except: 1684 // a definition of a variable of non-literal type or of static or 1685 // thread storage duration or for which no initialization is performed. 1686 const auto *VD = cast<VarDecl>(DclIt); 1687 if (VD->isThisDeclarationADefinition()) { 1688 if (VD->isStaticLocal()) { 1689 SemaRef.Diag(VD->getLocation(), 1690 diag::err_constexpr_local_var_static) 1691 << isa<CXXConstructorDecl>(Dcl) 1692 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1693 return false; 1694 } 1695 if (!VD->getType()->isDependentType() && 1696 SemaRef.RequireLiteralType( 1697 VD->getLocation(), VD->getType(), 1698 diag::err_constexpr_local_var_non_literal_type, 1699 isa<CXXConstructorDecl>(Dcl))) 1700 return false; 1701 if (!VD->getType()->isDependentType() && 1702 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1703 SemaRef.Diag(VD->getLocation(), 1704 diag::err_constexpr_local_var_no_init) 1705 << isa<CXXConstructorDecl>(Dcl); 1706 return false; 1707 } 1708 } 1709 SemaRef.Diag(VD->getLocation(), 1710 SemaRef.getLangOpts().CPlusPlus14 1711 ? diag::warn_cxx11_compat_constexpr_local_var 1712 : diag::ext_constexpr_local_var) 1713 << isa<CXXConstructorDecl>(Dcl); 1714 continue; 1715 } 1716 1717 case Decl::NamespaceAlias: 1718 case Decl::Function: 1719 // These are disallowed in C++11 and permitted in C++1y. Allow them 1720 // everywhere as an extension. 1721 if (!Cxx1yLoc.isValid()) 1722 Cxx1yLoc = DS->getLocStart(); 1723 continue; 1724 1725 default: 1726 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1727 << isa<CXXConstructorDecl>(Dcl); 1728 return false; 1729 } 1730 } 1731 1732 return true; 1733 } 1734 1735 /// Check that the given field is initialized within a constexpr constructor. 1736 /// 1737 /// \param Dcl The constexpr constructor being checked. 1738 /// \param Field The field being checked. This may be a member of an anonymous 1739 /// struct or union nested within the class being checked. 1740 /// \param Inits All declarations, including anonymous struct/union members and 1741 /// indirect members, for which any initialization was provided. 1742 /// \param Diagnosed Set to true if an error is produced. 1743 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1744 const FunctionDecl *Dcl, 1745 FieldDecl *Field, 1746 llvm::SmallSet<Decl*, 16> &Inits, 1747 bool &Diagnosed) { 1748 if (Field->isInvalidDecl()) 1749 return; 1750 1751 if (Field->isUnnamedBitfield()) 1752 return; 1753 1754 // Anonymous unions with no variant members and empty anonymous structs do not 1755 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1756 // indirect fields don't need initializing. 1757 if (Field->isAnonymousStructOrUnion() && 1758 (Field->getType()->isUnionType() 1759 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1760 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1761 return; 1762 1763 if (!Inits.count(Field)) { 1764 if (!Diagnosed) { 1765 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1766 Diagnosed = true; 1767 } 1768 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1769 } else if (Field->isAnonymousStructOrUnion()) { 1770 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1771 for (auto *I : RD->fields()) 1772 // If an anonymous union contains an anonymous struct of which any member 1773 // is initialized, all members must be initialized. 1774 if (!RD->isUnion() || Inits.count(I)) 1775 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1776 } 1777 } 1778 1779 /// Check the provided statement is allowed in a constexpr function 1780 /// definition. 1781 static bool 1782 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1783 SmallVectorImpl<SourceLocation> &ReturnStmts, 1784 SourceLocation &Cxx1yLoc) { 1785 // - its function-body shall be [...] a compound-statement that contains only 1786 switch (S->getStmtClass()) { 1787 case Stmt::NullStmtClass: 1788 // - null statements, 1789 return true; 1790 1791 case Stmt::DeclStmtClass: 1792 // - static_assert-declarations 1793 // - using-declarations, 1794 // - using-directives, 1795 // - typedef declarations and alias-declarations that do not define 1796 // classes or enumerations, 1797 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1798 return false; 1799 return true; 1800 1801 case Stmt::ReturnStmtClass: 1802 // - and exactly one return statement; 1803 if (isa<CXXConstructorDecl>(Dcl)) { 1804 // C++1y allows return statements in constexpr constructors. 1805 if (!Cxx1yLoc.isValid()) 1806 Cxx1yLoc = S->getLocStart(); 1807 return true; 1808 } 1809 1810 ReturnStmts.push_back(S->getLocStart()); 1811 return true; 1812 1813 case Stmt::CompoundStmtClass: { 1814 // C++1y allows compound-statements. 1815 if (!Cxx1yLoc.isValid()) 1816 Cxx1yLoc = S->getLocStart(); 1817 1818 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1819 for (auto *BodyIt : CompStmt->body()) { 1820 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1821 Cxx1yLoc)) 1822 return false; 1823 } 1824 return true; 1825 } 1826 1827 case Stmt::AttributedStmtClass: 1828 if (!Cxx1yLoc.isValid()) 1829 Cxx1yLoc = S->getLocStart(); 1830 return true; 1831 1832 case Stmt::IfStmtClass: { 1833 // C++1y allows if-statements. 1834 if (!Cxx1yLoc.isValid()) 1835 Cxx1yLoc = S->getLocStart(); 1836 1837 IfStmt *If = cast<IfStmt>(S); 1838 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1839 Cxx1yLoc)) 1840 return false; 1841 if (If->getElse() && 1842 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1843 Cxx1yLoc)) 1844 return false; 1845 return true; 1846 } 1847 1848 case Stmt::WhileStmtClass: 1849 case Stmt::DoStmtClass: 1850 case Stmt::ForStmtClass: 1851 case Stmt::CXXForRangeStmtClass: 1852 case Stmt::ContinueStmtClass: 1853 // C++1y allows all of these. We don't allow them as extensions in C++11, 1854 // because they don't make sense without variable mutation. 1855 if (!SemaRef.getLangOpts().CPlusPlus14) 1856 break; 1857 if (!Cxx1yLoc.isValid()) 1858 Cxx1yLoc = S->getLocStart(); 1859 for (Stmt *SubStmt : S->children()) 1860 if (SubStmt && 1861 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1862 Cxx1yLoc)) 1863 return false; 1864 return true; 1865 1866 case Stmt::SwitchStmtClass: 1867 case Stmt::CaseStmtClass: 1868 case Stmt::DefaultStmtClass: 1869 case Stmt::BreakStmtClass: 1870 // C++1y allows switch-statements, and since they don't need variable 1871 // mutation, we can reasonably allow them in C++11 as an extension. 1872 if (!Cxx1yLoc.isValid()) 1873 Cxx1yLoc = S->getLocStart(); 1874 for (Stmt *SubStmt : S->children()) 1875 if (SubStmt && 1876 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1877 Cxx1yLoc)) 1878 return false; 1879 return true; 1880 1881 default: 1882 if (!isa<Expr>(S)) 1883 break; 1884 1885 // C++1y allows expression-statements. 1886 if (!Cxx1yLoc.isValid()) 1887 Cxx1yLoc = S->getLocStart(); 1888 return true; 1889 } 1890 1891 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1892 << isa<CXXConstructorDecl>(Dcl); 1893 return false; 1894 } 1895 1896 /// Check the body for the given constexpr function declaration only contains 1897 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1898 /// 1899 /// \return true if the body is OK, false if we have diagnosed a problem. 1900 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1901 if (isa<CXXTryStmt>(Body)) { 1902 // C++11 [dcl.constexpr]p3: 1903 // The definition of a constexpr function shall satisfy the following 1904 // constraints: [...] 1905 // - its function-body shall be = delete, = default, or a 1906 // compound-statement 1907 // 1908 // C++11 [dcl.constexpr]p4: 1909 // In the definition of a constexpr constructor, [...] 1910 // - its function-body shall not be a function-try-block; 1911 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1912 << isa<CXXConstructorDecl>(Dcl); 1913 return false; 1914 } 1915 1916 SmallVector<SourceLocation, 4> ReturnStmts; 1917 1918 // - its function-body shall be [...] a compound-statement that contains only 1919 // [... list of cases ...] 1920 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1921 SourceLocation Cxx1yLoc; 1922 for (auto *BodyIt : CompBody->body()) { 1923 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1924 return false; 1925 } 1926 1927 if (Cxx1yLoc.isValid()) 1928 Diag(Cxx1yLoc, 1929 getLangOpts().CPlusPlus14 1930 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1931 : diag::ext_constexpr_body_invalid_stmt) 1932 << isa<CXXConstructorDecl>(Dcl); 1933 1934 if (const CXXConstructorDecl *Constructor 1935 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1936 const CXXRecordDecl *RD = Constructor->getParent(); 1937 // DR1359: 1938 // - every non-variant non-static data member and base class sub-object 1939 // shall be initialized; 1940 // DR1460: 1941 // - if the class is a union having variant members, exactly one of them 1942 // shall be initialized; 1943 if (RD->isUnion()) { 1944 if (Constructor->getNumCtorInitializers() == 0 && 1945 RD->hasVariantMembers()) { 1946 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1947 return false; 1948 } 1949 } else if (!Constructor->isDependentContext() && 1950 !Constructor->isDelegatingConstructor()) { 1951 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1952 1953 // Skip detailed checking if we have enough initializers, and we would 1954 // allow at most one initializer per member. 1955 bool AnyAnonStructUnionMembers = false; 1956 unsigned Fields = 0; 1957 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1958 E = RD->field_end(); I != E; ++I, ++Fields) { 1959 if (I->isAnonymousStructOrUnion()) { 1960 AnyAnonStructUnionMembers = true; 1961 break; 1962 } 1963 } 1964 // DR1460: 1965 // - if the class is a union-like class, but is not a union, for each of 1966 // its anonymous union members having variant members, exactly one of 1967 // them shall be initialized; 1968 if (AnyAnonStructUnionMembers || 1969 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1970 // Check initialization of non-static data members. Base classes are 1971 // always initialized so do not need to be checked. Dependent bases 1972 // might not have initializers in the member initializer list. 1973 llvm::SmallSet<Decl*, 16> Inits; 1974 for (const auto *I: Constructor->inits()) { 1975 if (FieldDecl *FD = I->getMember()) 1976 Inits.insert(FD); 1977 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1978 Inits.insert(ID->chain_begin(), ID->chain_end()); 1979 } 1980 1981 bool Diagnosed = false; 1982 for (auto *I : RD->fields()) 1983 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1984 if (Diagnosed) 1985 return false; 1986 } 1987 } 1988 } else { 1989 if (ReturnStmts.empty()) { 1990 // C++1y doesn't require constexpr functions to contain a 'return' 1991 // statement. We still do, unless the return type might be void, because 1992 // otherwise if there's no return statement, the function cannot 1993 // be used in a core constant expression. 1994 bool OK = getLangOpts().CPlusPlus14 && 1995 (Dcl->getReturnType()->isVoidType() || 1996 Dcl->getReturnType()->isDependentType()); 1997 Diag(Dcl->getLocation(), 1998 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1999 : diag::err_constexpr_body_no_return); 2000 if (!OK) 2001 return false; 2002 } else if (ReturnStmts.size() > 1) { 2003 Diag(ReturnStmts.back(), 2004 getLangOpts().CPlusPlus14 2005 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2006 : diag::ext_constexpr_body_multiple_return); 2007 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2008 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2009 } 2010 } 2011 2012 // C++11 [dcl.constexpr]p5: 2013 // if no function argument values exist such that the function invocation 2014 // substitution would produce a constant expression, the program is 2015 // ill-formed; no diagnostic required. 2016 // C++11 [dcl.constexpr]p3: 2017 // - every constructor call and implicit conversion used in initializing the 2018 // return value shall be one of those allowed in a constant expression. 2019 // C++11 [dcl.constexpr]p4: 2020 // - every constructor involved in initializing non-static data members and 2021 // base class sub-objects shall be a constexpr constructor. 2022 SmallVector<PartialDiagnosticAt, 8> Diags; 2023 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2024 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2025 << isa<CXXConstructorDecl>(Dcl); 2026 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2027 Diag(Diags[I].first, Diags[I].second); 2028 // Don't return false here: we allow this for compatibility in 2029 // system headers. 2030 } 2031 2032 return true; 2033 } 2034 2035 /// isCurrentClassName - Determine whether the identifier II is the 2036 /// name of the class type currently being defined. In the case of 2037 /// nested classes, this will only return true if II is the name of 2038 /// the innermost class. 2039 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2040 const CXXScopeSpec *SS) { 2041 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2042 2043 CXXRecordDecl *CurDecl; 2044 if (SS && SS->isSet() && !SS->isInvalid()) { 2045 DeclContext *DC = computeDeclContext(*SS, true); 2046 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2047 } else 2048 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2049 2050 if (CurDecl && CurDecl->getIdentifier()) 2051 return &II == CurDecl->getIdentifier(); 2052 return false; 2053 } 2054 2055 /// \brief Determine whether the identifier II is a typo for the name of 2056 /// the class type currently being defined. If so, update it to the identifier 2057 /// that should have been used. 2058 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2059 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2060 2061 if (!getLangOpts().SpellChecking) 2062 return false; 2063 2064 CXXRecordDecl *CurDecl; 2065 if (SS && SS->isSet() && !SS->isInvalid()) { 2066 DeclContext *DC = computeDeclContext(*SS, true); 2067 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2068 } else 2069 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2070 2071 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2072 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2073 < II->getLength()) { 2074 II = CurDecl->getIdentifier(); 2075 return true; 2076 } 2077 2078 return false; 2079 } 2080 2081 /// \brief Determine whether the given class is a base class of the given 2082 /// class, including looking at dependent bases. 2083 static bool findCircularInheritance(const CXXRecordDecl *Class, 2084 const CXXRecordDecl *Current) { 2085 SmallVector<const CXXRecordDecl*, 8> Queue; 2086 2087 Class = Class->getCanonicalDecl(); 2088 while (true) { 2089 for (const auto &I : Current->bases()) { 2090 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2091 if (!Base) 2092 continue; 2093 2094 Base = Base->getDefinition(); 2095 if (!Base) 2096 continue; 2097 2098 if (Base->getCanonicalDecl() == Class) 2099 return true; 2100 2101 Queue.push_back(Base); 2102 } 2103 2104 if (Queue.empty()) 2105 return false; 2106 2107 Current = Queue.pop_back_val(); 2108 } 2109 2110 return false; 2111 } 2112 2113 /// \brief Check the validity of a C++ base class specifier. 2114 /// 2115 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2116 /// and returns NULL otherwise. 2117 CXXBaseSpecifier * 2118 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2119 SourceRange SpecifierRange, 2120 bool Virtual, AccessSpecifier Access, 2121 TypeSourceInfo *TInfo, 2122 SourceLocation EllipsisLoc) { 2123 QualType BaseType = TInfo->getType(); 2124 2125 // C++ [class.union]p1: 2126 // A union shall not have base classes. 2127 if (Class->isUnion()) { 2128 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2129 << SpecifierRange; 2130 return nullptr; 2131 } 2132 2133 if (EllipsisLoc.isValid() && 2134 !TInfo->getType()->containsUnexpandedParameterPack()) { 2135 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2136 << TInfo->getTypeLoc().getSourceRange(); 2137 EllipsisLoc = SourceLocation(); 2138 } 2139 2140 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2141 2142 if (BaseType->isDependentType()) { 2143 // Make sure that we don't have circular inheritance among our dependent 2144 // bases. For non-dependent bases, the check for completeness below handles 2145 // this. 2146 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2147 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2148 ((BaseDecl = BaseDecl->getDefinition()) && 2149 findCircularInheritance(Class, BaseDecl))) { 2150 Diag(BaseLoc, diag::err_circular_inheritance) 2151 << BaseType << Context.getTypeDeclType(Class); 2152 2153 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2154 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2155 << BaseType; 2156 2157 return nullptr; 2158 } 2159 } 2160 2161 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2162 Class->getTagKind() == TTK_Class, 2163 Access, TInfo, EllipsisLoc); 2164 } 2165 2166 // Base specifiers must be record types. 2167 if (!BaseType->isRecordType()) { 2168 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2169 return nullptr; 2170 } 2171 2172 // C++ [class.union]p1: 2173 // A union shall not be used as a base class. 2174 if (BaseType->isUnionType()) { 2175 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2176 return nullptr; 2177 } 2178 2179 // For the MS ABI, propagate DLL attributes to base class templates. 2180 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2181 if (Attr *ClassAttr = getDLLAttr(Class)) { 2182 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2183 BaseType->getAsCXXRecordDecl())) { 2184 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2185 BaseLoc); 2186 } 2187 } 2188 } 2189 2190 // C++ [class.derived]p2: 2191 // The class-name in a base-specifier shall not be an incompletely 2192 // defined class. 2193 if (RequireCompleteType(BaseLoc, BaseType, 2194 diag::err_incomplete_base_class, SpecifierRange)) { 2195 Class->setInvalidDecl(); 2196 return nullptr; 2197 } 2198 2199 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2200 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2201 assert(BaseDecl && "Record type has no declaration"); 2202 BaseDecl = BaseDecl->getDefinition(); 2203 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2204 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2205 assert(CXXBaseDecl && "Base type is not a C++ type"); 2206 2207 // A class which contains a flexible array member is not suitable for use as a 2208 // base class: 2209 // - If the layout determines that a base comes before another base, 2210 // the flexible array member would index into the subsequent base. 2211 // - If the layout determines that base comes before the derived class, 2212 // the flexible array member would index into the derived class. 2213 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2214 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2215 << CXXBaseDecl->getDeclName(); 2216 return nullptr; 2217 } 2218 2219 // C++ [class]p3: 2220 // If a class is marked final and it appears as a base-type-specifier in 2221 // base-clause, the program is ill-formed. 2222 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2223 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2224 << CXXBaseDecl->getDeclName() 2225 << FA->isSpelledAsSealed(); 2226 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2227 << CXXBaseDecl->getDeclName() << FA->getRange(); 2228 return nullptr; 2229 } 2230 2231 if (BaseDecl->isInvalidDecl()) 2232 Class->setInvalidDecl(); 2233 2234 // Create the base specifier. 2235 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2236 Class->getTagKind() == TTK_Class, 2237 Access, TInfo, EllipsisLoc); 2238 } 2239 2240 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2241 /// one entry in the base class list of a class specifier, for 2242 /// example: 2243 /// class foo : public bar, virtual private baz { 2244 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2245 BaseResult 2246 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2247 ParsedAttributes &Attributes, 2248 bool Virtual, AccessSpecifier Access, 2249 ParsedType basetype, SourceLocation BaseLoc, 2250 SourceLocation EllipsisLoc) { 2251 if (!classdecl) 2252 return true; 2253 2254 AdjustDeclIfTemplate(classdecl); 2255 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2256 if (!Class) 2257 return true; 2258 2259 // We haven't yet attached the base specifiers. 2260 Class->setIsParsingBaseSpecifiers(); 2261 2262 // We do not support any C++11 attributes on base-specifiers yet. 2263 // Diagnose any attributes we see. 2264 if (!Attributes.empty()) { 2265 for (AttributeList *Attr = Attributes.getList(); Attr; 2266 Attr = Attr->getNext()) { 2267 if (Attr->isInvalid() || 2268 Attr->getKind() == AttributeList::IgnoredAttribute) 2269 continue; 2270 Diag(Attr->getLoc(), 2271 Attr->getKind() == AttributeList::UnknownAttribute 2272 ? diag::warn_unknown_attribute_ignored 2273 : diag::err_base_specifier_attribute) 2274 << Attr->getName(); 2275 } 2276 } 2277 2278 TypeSourceInfo *TInfo = nullptr; 2279 GetTypeFromParser(basetype, &TInfo); 2280 2281 if (EllipsisLoc.isInvalid() && 2282 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2283 UPPC_BaseType)) 2284 return true; 2285 2286 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2287 Virtual, Access, TInfo, 2288 EllipsisLoc)) 2289 return BaseSpec; 2290 else 2291 Class->setInvalidDecl(); 2292 2293 return true; 2294 } 2295 2296 /// Use small set to collect indirect bases. As this is only used 2297 /// locally, there's no need to abstract the small size parameter. 2298 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2299 2300 /// \brief Recursively add the bases of Type. Don't add Type itself. 2301 static void 2302 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2303 const QualType &Type) 2304 { 2305 // Even though the incoming type is a base, it might not be 2306 // a class -- it could be a template parm, for instance. 2307 if (auto Rec = Type->getAs<RecordType>()) { 2308 auto Decl = Rec->getAsCXXRecordDecl(); 2309 2310 // Iterate over its bases. 2311 for (const auto &BaseSpec : Decl->bases()) { 2312 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2313 .getUnqualifiedType(); 2314 if (Set.insert(Base).second) 2315 // If we've not already seen it, recurse. 2316 NoteIndirectBases(Context, Set, Base); 2317 } 2318 } 2319 } 2320 2321 /// \brief Performs the actual work of attaching the given base class 2322 /// specifiers to a C++ class. 2323 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2324 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2325 if (Bases.empty()) 2326 return false; 2327 2328 // Used to keep track of which base types we have already seen, so 2329 // that we can properly diagnose redundant direct base types. Note 2330 // that the key is always the unqualified canonical type of the base 2331 // class. 2332 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2333 2334 // Used to track indirect bases so we can see if a direct base is 2335 // ambiguous. 2336 IndirectBaseSet IndirectBaseTypes; 2337 2338 // Copy non-redundant base specifiers into permanent storage. 2339 unsigned NumGoodBases = 0; 2340 bool Invalid = false; 2341 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2342 QualType NewBaseType 2343 = Context.getCanonicalType(Bases[idx]->getType()); 2344 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2345 2346 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2347 if (KnownBase) { 2348 // C++ [class.mi]p3: 2349 // A class shall not be specified as a direct base class of a 2350 // derived class more than once. 2351 Diag(Bases[idx]->getLocStart(), 2352 diag::err_duplicate_base_class) 2353 << KnownBase->getType() 2354 << Bases[idx]->getSourceRange(); 2355 2356 // Delete the duplicate base class specifier; we're going to 2357 // overwrite its pointer later. 2358 Context.Deallocate(Bases[idx]); 2359 2360 Invalid = true; 2361 } else { 2362 // Okay, add this new base class. 2363 KnownBase = Bases[idx]; 2364 Bases[NumGoodBases++] = Bases[idx]; 2365 2366 // Note this base's direct & indirect bases, if there could be ambiguity. 2367 if (Bases.size() > 1) 2368 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2369 2370 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2371 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2372 if (Class->isInterface() && 2373 (!RD->isInterface() || 2374 KnownBase->getAccessSpecifier() != AS_public)) { 2375 // The Microsoft extension __interface does not permit bases that 2376 // are not themselves public interfaces. 2377 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2378 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 2379 << RD->getSourceRange(); 2380 Invalid = true; 2381 } 2382 if (RD->hasAttr<WeakAttr>()) 2383 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2384 } 2385 } 2386 } 2387 2388 // Attach the remaining base class specifiers to the derived class. 2389 Class->setBases(Bases.data(), NumGoodBases); 2390 2391 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2392 // Check whether this direct base is inaccessible due to ambiguity. 2393 QualType BaseType = Bases[idx]->getType(); 2394 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2395 .getUnqualifiedType(); 2396 2397 if (IndirectBaseTypes.count(CanonicalBase)) { 2398 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2399 /*DetectVirtual=*/true); 2400 bool found 2401 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2402 assert(found); 2403 (void)found; 2404 2405 if (Paths.isAmbiguous(CanonicalBase)) 2406 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2407 << BaseType << getAmbiguousPathsDisplayString(Paths) 2408 << Bases[idx]->getSourceRange(); 2409 else 2410 assert(Bases[idx]->isVirtual()); 2411 } 2412 2413 // Delete the base class specifier, since its data has been copied 2414 // into the CXXRecordDecl. 2415 Context.Deallocate(Bases[idx]); 2416 } 2417 2418 return Invalid; 2419 } 2420 2421 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2422 /// class, after checking whether there are any duplicate base 2423 /// classes. 2424 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2425 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2426 if (!ClassDecl || Bases.empty()) 2427 return; 2428 2429 AdjustDeclIfTemplate(ClassDecl); 2430 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2431 } 2432 2433 /// \brief Determine whether the type \p Derived is a C++ class that is 2434 /// derived from the type \p Base. 2435 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2436 if (!getLangOpts().CPlusPlus) 2437 return false; 2438 2439 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2440 if (!DerivedRD) 2441 return false; 2442 2443 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2444 if (!BaseRD) 2445 return false; 2446 2447 // If either the base or the derived type is invalid, don't try to 2448 // check whether one is derived from the other. 2449 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2450 return false; 2451 2452 // FIXME: In a modules build, do we need the entire path to be visible for us 2453 // to be able to use the inheritance relationship? 2454 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2455 return false; 2456 2457 return DerivedRD->isDerivedFrom(BaseRD); 2458 } 2459 2460 /// \brief Determine whether the type \p Derived is a C++ class that is 2461 /// derived from the type \p Base. 2462 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2463 CXXBasePaths &Paths) { 2464 if (!getLangOpts().CPlusPlus) 2465 return false; 2466 2467 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2468 if (!DerivedRD) 2469 return false; 2470 2471 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2472 if (!BaseRD) 2473 return false; 2474 2475 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2476 return false; 2477 2478 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2479 } 2480 2481 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2482 CXXCastPath &BasePathArray) { 2483 assert(BasePathArray.empty() && "Base path array must be empty!"); 2484 assert(Paths.isRecordingPaths() && "Must record paths!"); 2485 2486 const CXXBasePath &Path = Paths.front(); 2487 2488 // We first go backward and check if we have a virtual base. 2489 // FIXME: It would be better if CXXBasePath had the base specifier for 2490 // the nearest virtual base. 2491 unsigned Start = 0; 2492 for (unsigned I = Path.size(); I != 0; --I) { 2493 if (Path[I - 1].Base->isVirtual()) { 2494 Start = I - 1; 2495 break; 2496 } 2497 } 2498 2499 // Now add all bases. 2500 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2501 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2502 } 2503 2504 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2505 /// conversion (where Derived and Base are class types) is 2506 /// well-formed, meaning that the conversion is unambiguous (and 2507 /// that all of the base classes are accessible). Returns true 2508 /// and emits a diagnostic if the code is ill-formed, returns false 2509 /// otherwise. Loc is the location where this routine should point to 2510 /// if there is an error, and Range is the source range to highlight 2511 /// if there is an error. 2512 /// 2513 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2514 /// diagnostic for the respective type of error will be suppressed, but the 2515 /// check for ill-formed code will still be performed. 2516 bool 2517 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2518 unsigned InaccessibleBaseID, 2519 unsigned AmbigiousBaseConvID, 2520 SourceLocation Loc, SourceRange Range, 2521 DeclarationName Name, 2522 CXXCastPath *BasePath, 2523 bool IgnoreAccess) { 2524 // First, determine whether the path from Derived to Base is 2525 // ambiguous. This is slightly more expensive than checking whether 2526 // the Derived to Base conversion exists, because here we need to 2527 // explore multiple paths to determine if there is an ambiguity. 2528 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2529 /*DetectVirtual=*/false); 2530 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2531 assert(DerivationOkay && 2532 "Can only be used with a derived-to-base conversion"); 2533 (void)DerivationOkay; 2534 2535 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 2536 if (!IgnoreAccess) { 2537 // Check that the base class can be accessed. 2538 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 2539 InaccessibleBaseID)) { 2540 case AR_inaccessible: 2541 return true; 2542 case AR_accessible: 2543 case AR_dependent: 2544 case AR_delayed: 2545 break; 2546 } 2547 } 2548 2549 // Build a base path if necessary. 2550 if (BasePath) 2551 BuildBasePathArray(Paths, *BasePath); 2552 return false; 2553 } 2554 2555 if (AmbigiousBaseConvID) { 2556 // We know that the derived-to-base conversion is ambiguous, and 2557 // we're going to produce a diagnostic. Perform the derived-to-base 2558 // search just one more time to compute all of the possible paths so 2559 // that we can print them out. This is more expensive than any of 2560 // the previous derived-to-base checks we've done, but at this point 2561 // performance isn't as much of an issue. 2562 Paths.clear(); 2563 Paths.setRecordingPaths(true); 2564 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2565 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2566 (void)StillOkay; 2567 2568 // Build up a textual representation of the ambiguous paths, e.g., 2569 // D -> B -> A, that will be used to illustrate the ambiguous 2570 // conversions in the diagnostic. We only print one of the paths 2571 // to each base class subobject. 2572 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2573 2574 Diag(Loc, AmbigiousBaseConvID) 2575 << Derived << Base << PathDisplayStr << Range << Name; 2576 } 2577 return true; 2578 } 2579 2580 bool 2581 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2582 SourceLocation Loc, SourceRange Range, 2583 CXXCastPath *BasePath, 2584 bool IgnoreAccess) { 2585 return CheckDerivedToBaseConversion( 2586 Derived, Base, diag::err_upcast_to_inaccessible_base, 2587 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2588 BasePath, IgnoreAccess); 2589 } 2590 2591 2592 /// @brief Builds a string representing ambiguous paths from a 2593 /// specific derived class to different subobjects of the same base 2594 /// class. 2595 /// 2596 /// This function builds a string that can be used in error messages 2597 /// to show the different paths that one can take through the 2598 /// inheritance hierarchy to go from the derived class to different 2599 /// subobjects of a base class. The result looks something like this: 2600 /// @code 2601 /// struct D -> struct B -> struct A 2602 /// struct D -> struct C -> struct A 2603 /// @endcode 2604 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2605 std::string PathDisplayStr; 2606 std::set<unsigned> DisplayedPaths; 2607 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2608 Path != Paths.end(); ++Path) { 2609 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2610 // We haven't displayed a path to this particular base 2611 // class subobject yet. 2612 PathDisplayStr += "\n "; 2613 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2614 for (CXXBasePath::const_iterator Element = Path->begin(); 2615 Element != Path->end(); ++Element) 2616 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2617 } 2618 } 2619 2620 return PathDisplayStr; 2621 } 2622 2623 //===----------------------------------------------------------------------===// 2624 // C++ class member Handling 2625 //===----------------------------------------------------------------------===// 2626 2627 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2628 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2629 SourceLocation ASLoc, 2630 SourceLocation ColonLoc, 2631 AttributeList *Attrs) { 2632 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2633 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2634 ASLoc, ColonLoc); 2635 CurContext->addHiddenDecl(ASDecl); 2636 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2637 } 2638 2639 /// CheckOverrideControl - Check C++11 override control semantics. 2640 void Sema::CheckOverrideControl(NamedDecl *D) { 2641 if (D->isInvalidDecl()) 2642 return; 2643 2644 // We only care about "override" and "final" declarations. 2645 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2646 return; 2647 2648 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2649 2650 // We can't check dependent instance methods. 2651 if (MD && MD->isInstance() && 2652 (MD->getParent()->hasAnyDependentBases() || 2653 MD->getType()->isDependentType())) 2654 return; 2655 2656 if (MD && !MD->isVirtual()) { 2657 // If we have a non-virtual method, check if if hides a virtual method. 2658 // (In that case, it's most likely the method has the wrong type.) 2659 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2660 FindHiddenVirtualMethods(MD, OverloadedMethods); 2661 2662 if (!OverloadedMethods.empty()) { 2663 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2664 Diag(OA->getLocation(), 2665 diag::override_keyword_hides_virtual_member_function) 2666 << "override" << (OverloadedMethods.size() > 1); 2667 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2668 Diag(FA->getLocation(), 2669 diag::override_keyword_hides_virtual_member_function) 2670 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2671 << (OverloadedMethods.size() > 1); 2672 } 2673 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2674 MD->setInvalidDecl(); 2675 return; 2676 } 2677 // Fall through into the general case diagnostic. 2678 // FIXME: We might want to attempt typo correction here. 2679 } 2680 2681 if (!MD || !MD->isVirtual()) { 2682 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2683 Diag(OA->getLocation(), 2684 diag::override_keyword_only_allowed_on_virtual_member_functions) 2685 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2686 D->dropAttr<OverrideAttr>(); 2687 } 2688 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2689 Diag(FA->getLocation(), 2690 diag::override_keyword_only_allowed_on_virtual_member_functions) 2691 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2692 << FixItHint::CreateRemoval(FA->getLocation()); 2693 D->dropAttr<FinalAttr>(); 2694 } 2695 return; 2696 } 2697 2698 // C++11 [class.virtual]p5: 2699 // If a function is marked with the virt-specifier override and 2700 // does not override a member function of a base class, the program is 2701 // ill-formed. 2702 bool HasOverriddenMethods = 2703 MD->begin_overridden_methods() != MD->end_overridden_methods(); 2704 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2705 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2706 << MD->getDeclName(); 2707 } 2708 2709 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2710 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2711 return; 2712 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2713 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 2714 isa<CXXDestructorDecl>(MD)) 2715 return; 2716 2717 SourceLocation Loc = MD->getLocation(); 2718 SourceLocation SpellingLoc = Loc; 2719 if (getSourceManager().isMacroArgExpansion(Loc)) 2720 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 2721 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2722 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2723 return; 2724 2725 if (MD->size_overridden_methods() > 0) { 2726 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 2727 << MD->getDeclName(); 2728 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2729 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2730 } 2731 } 2732 2733 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2734 /// function overrides a virtual member function marked 'final', according to 2735 /// C++11 [class.virtual]p4. 2736 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2737 const CXXMethodDecl *Old) { 2738 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2739 if (!FA) 2740 return false; 2741 2742 Diag(New->getLocation(), diag::err_final_function_overridden) 2743 << New->getDeclName() 2744 << FA->isSpelledAsSealed(); 2745 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2746 return true; 2747 } 2748 2749 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2750 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2751 // FIXME: Destruction of ObjC lifetime types has side-effects. 2752 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2753 return !RD->isCompleteDefinition() || 2754 !RD->hasTrivialDefaultConstructor() || 2755 !RD->hasTrivialDestructor(); 2756 return false; 2757 } 2758 2759 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2760 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2761 if (it->isDeclspecPropertyAttribute()) 2762 return it; 2763 return nullptr; 2764 } 2765 2766 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2767 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2768 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2769 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2770 /// present (but parsing it has been deferred). 2771 NamedDecl * 2772 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2773 MultiTemplateParamsArg TemplateParameterLists, 2774 Expr *BW, const VirtSpecifiers &VS, 2775 InClassInitStyle InitStyle) { 2776 const DeclSpec &DS = D.getDeclSpec(); 2777 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2778 DeclarationName Name = NameInfo.getName(); 2779 SourceLocation Loc = NameInfo.getLoc(); 2780 2781 // For anonymous bitfields, the location should point to the type. 2782 if (Loc.isInvalid()) 2783 Loc = D.getLocStart(); 2784 2785 Expr *BitWidth = static_cast<Expr*>(BW); 2786 2787 assert(isa<CXXRecordDecl>(CurContext)); 2788 assert(!DS.isFriendSpecified()); 2789 2790 bool isFunc = D.isDeclarationOfFunction(); 2791 2792 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2793 // The Microsoft extension __interface only permits public member functions 2794 // and prohibits constructors, destructors, operators, non-public member 2795 // functions, static methods and data members. 2796 unsigned InvalidDecl; 2797 bool ShowDeclName = true; 2798 if (!isFunc) 2799 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2800 else if (AS != AS_public) 2801 InvalidDecl = 2; 2802 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2803 InvalidDecl = 3; 2804 else switch (Name.getNameKind()) { 2805 case DeclarationName::CXXConstructorName: 2806 InvalidDecl = 4; 2807 ShowDeclName = false; 2808 break; 2809 2810 case DeclarationName::CXXDestructorName: 2811 InvalidDecl = 5; 2812 ShowDeclName = false; 2813 break; 2814 2815 case DeclarationName::CXXOperatorName: 2816 case DeclarationName::CXXConversionFunctionName: 2817 InvalidDecl = 6; 2818 break; 2819 2820 default: 2821 InvalidDecl = 0; 2822 break; 2823 } 2824 2825 if (InvalidDecl) { 2826 if (ShowDeclName) 2827 Diag(Loc, diag::err_invalid_member_in_interface) 2828 << (InvalidDecl-1) << Name; 2829 else 2830 Diag(Loc, diag::err_invalid_member_in_interface) 2831 << (InvalidDecl-1) << ""; 2832 return nullptr; 2833 } 2834 } 2835 2836 // C++ 9.2p6: A member shall not be declared to have automatic storage 2837 // duration (auto, register) or with the extern storage-class-specifier. 2838 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2839 // data members and cannot be applied to names declared const or static, 2840 // and cannot be applied to reference members. 2841 switch (DS.getStorageClassSpec()) { 2842 case DeclSpec::SCS_unspecified: 2843 case DeclSpec::SCS_typedef: 2844 case DeclSpec::SCS_static: 2845 break; 2846 case DeclSpec::SCS_mutable: 2847 if (isFunc) { 2848 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2849 2850 // FIXME: It would be nicer if the keyword was ignored only for this 2851 // declarator. Otherwise we could get follow-up errors. 2852 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2853 } 2854 break; 2855 default: 2856 Diag(DS.getStorageClassSpecLoc(), 2857 diag::err_storageclass_invalid_for_member); 2858 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2859 break; 2860 } 2861 2862 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2863 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2864 !isFunc); 2865 2866 if (DS.isConstexprSpecified() && isInstField) { 2867 SemaDiagnosticBuilder B = 2868 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2869 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2870 if (InitStyle == ICIS_NoInit) { 2871 B << 0 << 0; 2872 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2873 B << FixItHint::CreateRemoval(ConstexprLoc); 2874 else { 2875 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2876 D.getMutableDeclSpec().ClearConstexprSpec(); 2877 const char *PrevSpec; 2878 unsigned DiagID; 2879 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2880 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2881 (void)Failed; 2882 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2883 } 2884 } else { 2885 B << 1; 2886 const char *PrevSpec; 2887 unsigned DiagID; 2888 if (D.getMutableDeclSpec().SetStorageClassSpec( 2889 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2890 Context.getPrintingPolicy())) { 2891 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2892 "This is the only DeclSpec that should fail to be applied"); 2893 B << 1; 2894 } else { 2895 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2896 isInstField = false; 2897 } 2898 } 2899 } 2900 2901 NamedDecl *Member; 2902 if (isInstField) { 2903 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2904 2905 // Data members must have identifiers for names. 2906 if (!Name.isIdentifier()) { 2907 Diag(Loc, diag::err_bad_variable_name) 2908 << Name; 2909 return nullptr; 2910 } 2911 2912 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2913 2914 // Member field could not be with "template" keyword. 2915 // So TemplateParameterLists should be empty in this case. 2916 if (TemplateParameterLists.size()) { 2917 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2918 if (TemplateParams->size()) { 2919 // There is no such thing as a member field template. 2920 Diag(D.getIdentifierLoc(), diag::err_template_member) 2921 << II 2922 << SourceRange(TemplateParams->getTemplateLoc(), 2923 TemplateParams->getRAngleLoc()); 2924 } else { 2925 // There is an extraneous 'template<>' for this member. 2926 Diag(TemplateParams->getTemplateLoc(), 2927 diag::err_template_member_noparams) 2928 << II 2929 << SourceRange(TemplateParams->getTemplateLoc(), 2930 TemplateParams->getRAngleLoc()); 2931 } 2932 return nullptr; 2933 } 2934 2935 if (SS.isSet() && !SS.isInvalid()) { 2936 // The user provided a superfluous scope specifier inside a class 2937 // definition: 2938 // 2939 // class X { 2940 // int X::member; 2941 // }; 2942 if (DeclContext *DC = computeDeclContext(SS, false)) 2943 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2944 else 2945 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2946 << Name << SS.getRange(); 2947 2948 SS.clear(); 2949 } 2950 2951 AttributeList *MSPropertyAttr = 2952 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2953 if (MSPropertyAttr) { 2954 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2955 BitWidth, InitStyle, AS, MSPropertyAttr); 2956 if (!Member) 2957 return nullptr; 2958 isInstField = false; 2959 } else { 2960 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2961 BitWidth, InitStyle, AS); 2962 if (!Member) 2963 return nullptr; 2964 } 2965 } else { 2966 Member = HandleDeclarator(S, D, TemplateParameterLists); 2967 if (!Member) 2968 return nullptr; 2969 2970 // Non-instance-fields can't have a bitfield. 2971 if (BitWidth) { 2972 if (Member->isInvalidDecl()) { 2973 // don't emit another diagnostic. 2974 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 2975 // C++ 9.6p3: A bit-field shall not be a static member. 2976 // "static member 'A' cannot be a bit-field" 2977 Diag(Loc, diag::err_static_not_bitfield) 2978 << Name << BitWidth->getSourceRange(); 2979 } else if (isa<TypedefDecl>(Member)) { 2980 // "typedef member 'x' cannot be a bit-field" 2981 Diag(Loc, diag::err_typedef_not_bitfield) 2982 << Name << BitWidth->getSourceRange(); 2983 } else { 2984 // A function typedef ("typedef int f(); f a;"). 2985 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2986 Diag(Loc, diag::err_not_integral_type_bitfield) 2987 << Name << cast<ValueDecl>(Member)->getType() 2988 << BitWidth->getSourceRange(); 2989 } 2990 2991 BitWidth = nullptr; 2992 Member->setInvalidDecl(); 2993 } 2994 2995 Member->setAccess(AS); 2996 2997 // If we have declared a member function template or static data member 2998 // template, set the access of the templated declaration as well. 2999 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3000 FunTmpl->getTemplatedDecl()->setAccess(AS); 3001 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3002 VarTmpl->getTemplatedDecl()->setAccess(AS); 3003 } 3004 3005 if (VS.isOverrideSpecified()) 3006 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3007 if (VS.isFinalSpecified()) 3008 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3009 VS.isFinalSpelledSealed())); 3010 3011 if (VS.getLastLocation().isValid()) { 3012 // Update the end location of a method that has a virt-specifiers. 3013 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3014 MD->setRangeEnd(VS.getLastLocation()); 3015 } 3016 3017 CheckOverrideControl(Member); 3018 3019 assert((Name || isInstField) && "No identifier for non-field ?"); 3020 3021 if (isInstField) { 3022 FieldDecl *FD = cast<FieldDecl>(Member); 3023 FieldCollector->Add(FD); 3024 3025 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3026 // Remember all explicit private FieldDecls that have a name, no side 3027 // effects and are not part of a dependent type declaration. 3028 if (!FD->isImplicit() && FD->getDeclName() && 3029 FD->getAccess() == AS_private && 3030 !FD->hasAttr<UnusedAttr>() && 3031 !FD->getParent()->isDependentContext() && 3032 !InitializationHasSideEffects(*FD)) 3033 UnusedPrivateFields.insert(FD); 3034 } 3035 } 3036 3037 return Member; 3038 } 3039 3040 namespace { 3041 class UninitializedFieldVisitor 3042 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3043 Sema &S; 3044 // List of Decls to generate a warning on. Also remove Decls that become 3045 // initialized. 3046 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3047 // List of base classes of the record. Classes are removed after their 3048 // initializers. 3049 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3050 // Vector of decls to be removed from the Decl set prior to visiting the 3051 // nodes. These Decls may have been initialized in the prior initializer. 3052 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3053 // If non-null, add a note to the warning pointing back to the constructor. 3054 const CXXConstructorDecl *Constructor; 3055 // Variables to hold state when processing an initializer list. When 3056 // InitList is true, special case initialization of FieldDecls matching 3057 // InitListFieldDecl. 3058 bool InitList; 3059 FieldDecl *InitListFieldDecl; 3060 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3061 3062 public: 3063 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3064 UninitializedFieldVisitor(Sema &S, 3065 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3066 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3067 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3068 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3069 3070 // Returns true if the use of ME is not an uninitialized use. 3071 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3072 bool CheckReferenceOnly) { 3073 llvm::SmallVector<FieldDecl*, 4> Fields; 3074 bool ReferenceField = false; 3075 while (ME) { 3076 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3077 if (!FD) 3078 return false; 3079 Fields.push_back(FD); 3080 if (FD->getType()->isReferenceType()) 3081 ReferenceField = true; 3082 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3083 } 3084 3085 // Binding a reference to an unintialized field is not an 3086 // uninitialized use. 3087 if (CheckReferenceOnly && !ReferenceField) 3088 return true; 3089 3090 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3091 // Discard the first field since it is the field decl that is being 3092 // initialized. 3093 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3094 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3095 } 3096 3097 for (auto UsedIter = UsedFieldIndex.begin(), 3098 UsedEnd = UsedFieldIndex.end(), 3099 OrigIter = InitFieldIndex.begin(), 3100 OrigEnd = InitFieldIndex.end(); 3101 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3102 if (*UsedIter < *OrigIter) 3103 return true; 3104 if (*UsedIter > *OrigIter) 3105 break; 3106 } 3107 3108 return false; 3109 } 3110 3111 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3112 bool AddressOf) { 3113 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3114 return; 3115 3116 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3117 // or union. 3118 MemberExpr *FieldME = ME; 3119 3120 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3121 3122 Expr *Base = ME; 3123 while (MemberExpr *SubME = 3124 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3125 3126 if (isa<VarDecl>(SubME->getMemberDecl())) 3127 return; 3128 3129 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3130 if (!FD->isAnonymousStructOrUnion()) 3131 FieldME = SubME; 3132 3133 if (!FieldME->getType().isPODType(S.Context)) 3134 AllPODFields = false; 3135 3136 Base = SubME->getBase(); 3137 } 3138 3139 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3140 return; 3141 3142 if (AddressOf && AllPODFields) 3143 return; 3144 3145 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3146 3147 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3148 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3149 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3150 } 3151 3152 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3153 QualType T = BaseCast->getType(); 3154 if (T->isPointerType() && 3155 BaseClasses.count(T->getPointeeType())) { 3156 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3157 << T->getPointeeType() << FoundVD; 3158 } 3159 } 3160 } 3161 3162 if (!Decls.count(FoundVD)) 3163 return; 3164 3165 const bool IsReference = FoundVD->getType()->isReferenceType(); 3166 3167 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3168 // Special checking for initializer lists. 3169 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3170 return; 3171 } 3172 } else { 3173 // Prevent double warnings on use of unbounded references. 3174 if (CheckReferenceOnly && !IsReference) 3175 return; 3176 } 3177 3178 unsigned diag = IsReference 3179 ? diag::warn_reference_field_is_uninit 3180 : diag::warn_field_is_uninit; 3181 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3182 if (Constructor) 3183 S.Diag(Constructor->getLocation(), 3184 diag::note_uninit_in_this_constructor) 3185 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3186 3187 } 3188 3189 void HandleValue(Expr *E, bool AddressOf) { 3190 E = E->IgnoreParens(); 3191 3192 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3193 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3194 AddressOf /*AddressOf*/); 3195 return; 3196 } 3197 3198 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3199 Visit(CO->getCond()); 3200 HandleValue(CO->getTrueExpr(), AddressOf); 3201 HandleValue(CO->getFalseExpr(), AddressOf); 3202 return; 3203 } 3204 3205 if (BinaryConditionalOperator *BCO = 3206 dyn_cast<BinaryConditionalOperator>(E)) { 3207 Visit(BCO->getCond()); 3208 HandleValue(BCO->getFalseExpr(), AddressOf); 3209 return; 3210 } 3211 3212 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3213 HandleValue(OVE->getSourceExpr(), AddressOf); 3214 return; 3215 } 3216 3217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3218 switch (BO->getOpcode()) { 3219 default: 3220 break; 3221 case(BO_PtrMemD): 3222 case(BO_PtrMemI): 3223 HandleValue(BO->getLHS(), AddressOf); 3224 Visit(BO->getRHS()); 3225 return; 3226 case(BO_Comma): 3227 Visit(BO->getLHS()); 3228 HandleValue(BO->getRHS(), AddressOf); 3229 return; 3230 } 3231 } 3232 3233 Visit(E); 3234 } 3235 3236 void CheckInitListExpr(InitListExpr *ILE) { 3237 InitFieldIndex.push_back(0); 3238 for (auto Child : ILE->children()) { 3239 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3240 CheckInitListExpr(SubList); 3241 } else { 3242 Visit(Child); 3243 } 3244 ++InitFieldIndex.back(); 3245 } 3246 InitFieldIndex.pop_back(); 3247 } 3248 3249 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3250 FieldDecl *Field, const Type *BaseClass) { 3251 // Remove Decls that may have been initialized in the previous 3252 // initializer. 3253 for (ValueDecl* VD : DeclsToRemove) 3254 Decls.erase(VD); 3255 DeclsToRemove.clear(); 3256 3257 Constructor = FieldConstructor; 3258 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3259 3260 if (ILE && Field) { 3261 InitList = true; 3262 InitListFieldDecl = Field; 3263 InitFieldIndex.clear(); 3264 CheckInitListExpr(ILE); 3265 } else { 3266 InitList = false; 3267 Visit(E); 3268 } 3269 3270 if (Field) 3271 Decls.erase(Field); 3272 if (BaseClass) 3273 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3274 } 3275 3276 void VisitMemberExpr(MemberExpr *ME) { 3277 // All uses of unbounded reference fields will warn. 3278 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3279 } 3280 3281 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3282 if (E->getCastKind() == CK_LValueToRValue) { 3283 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3284 return; 3285 } 3286 3287 Inherited::VisitImplicitCastExpr(E); 3288 } 3289 3290 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3291 if (E->getConstructor()->isCopyConstructor()) { 3292 Expr *ArgExpr = E->getArg(0); 3293 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3294 if (ILE->getNumInits() == 1) 3295 ArgExpr = ILE->getInit(0); 3296 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3297 if (ICE->getCastKind() == CK_NoOp) 3298 ArgExpr = ICE->getSubExpr(); 3299 HandleValue(ArgExpr, false /*AddressOf*/); 3300 return; 3301 } 3302 Inherited::VisitCXXConstructExpr(E); 3303 } 3304 3305 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3306 Expr *Callee = E->getCallee(); 3307 if (isa<MemberExpr>(Callee)) { 3308 HandleValue(Callee, false /*AddressOf*/); 3309 for (auto Arg : E->arguments()) 3310 Visit(Arg); 3311 return; 3312 } 3313 3314 Inherited::VisitCXXMemberCallExpr(E); 3315 } 3316 3317 void VisitCallExpr(CallExpr *E) { 3318 // Treat std::move as a use. 3319 if (E->getNumArgs() == 1) { 3320 if (FunctionDecl *FD = E->getDirectCallee()) { 3321 if (FD->isInStdNamespace() && FD->getIdentifier() && 3322 FD->getIdentifier()->isStr("move")) { 3323 HandleValue(E->getArg(0), false /*AddressOf*/); 3324 return; 3325 } 3326 } 3327 } 3328 3329 Inherited::VisitCallExpr(E); 3330 } 3331 3332 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3333 Expr *Callee = E->getCallee(); 3334 3335 if (isa<UnresolvedLookupExpr>(Callee)) 3336 return Inherited::VisitCXXOperatorCallExpr(E); 3337 3338 Visit(Callee); 3339 for (auto Arg : E->arguments()) 3340 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3341 } 3342 3343 void VisitBinaryOperator(BinaryOperator *E) { 3344 // If a field assignment is detected, remove the field from the 3345 // uninitiailized field set. 3346 if (E->getOpcode() == BO_Assign) 3347 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3348 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3349 if (!FD->getType()->isReferenceType()) 3350 DeclsToRemove.push_back(FD); 3351 3352 if (E->isCompoundAssignmentOp()) { 3353 HandleValue(E->getLHS(), false /*AddressOf*/); 3354 Visit(E->getRHS()); 3355 return; 3356 } 3357 3358 Inherited::VisitBinaryOperator(E); 3359 } 3360 3361 void VisitUnaryOperator(UnaryOperator *E) { 3362 if (E->isIncrementDecrementOp()) { 3363 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3364 return; 3365 } 3366 if (E->getOpcode() == UO_AddrOf) { 3367 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3368 HandleValue(ME->getBase(), true /*AddressOf*/); 3369 return; 3370 } 3371 } 3372 3373 Inherited::VisitUnaryOperator(E); 3374 } 3375 }; 3376 3377 // Diagnose value-uses of fields to initialize themselves, e.g. 3378 // foo(foo) 3379 // where foo is not also a parameter to the constructor. 3380 // Also diagnose across field uninitialized use such as 3381 // x(y), y(x) 3382 // TODO: implement -Wuninitialized and fold this into that framework. 3383 static void DiagnoseUninitializedFields( 3384 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3385 3386 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3387 Constructor->getLocation())) { 3388 return; 3389 } 3390 3391 if (Constructor->isInvalidDecl()) 3392 return; 3393 3394 const CXXRecordDecl *RD = Constructor->getParent(); 3395 3396 if (RD->getDescribedClassTemplate()) 3397 return; 3398 3399 // Holds fields that are uninitialized. 3400 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3401 3402 // At the beginning, all fields are uninitialized. 3403 for (auto *I : RD->decls()) { 3404 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3405 UninitializedFields.insert(FD); 3406 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3407 UninitializedFields.insert(IFD->getAnonField()); 3408 } 3409 } 3410 3411 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3412 for (auto I : RD->bases()) 3413 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3414 3415 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3416 return; 3417 3418 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3419 UninitializedFields, 3420 UninitializedBaseClasses); 3421 3422 for (const auto *FieldInit : Constructor->inits()) { 3423 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3424 break; 3425 3426 Expr *InitExpr = FieldInit->getInit(); 3427 if (!InitExpr) 3428 continue; 3429 3430 if (CXXDefaultInitExpr *Default = 3431 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3432 InitExpr = Default->getExpr(); 3433 if (!InitExpr) 3434 continue; 3435 // In class initializers will point to the constructor. 3436 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3437 FieldInit->getAnyMember(), 3438 FieldInit->getBaseClass()); 3439 } else { 3440 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3441 FieldInit->getAnyMember(), 3442 FieldInit->getBaseClass()); 3443 } 3444 } 3445 } 3446 } // namespace 3447 3448 /// \brief Enter a new C++ default initializer scope. After calling this, the 3449 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3450 /// parsing or instantiating the initializer failed. 3451 void Sema::ActOnStartCXXInClassMemberInitializer() { 3452 // Create a synthetic function scope to represent the call to the constructor 3453 // that notionally surrounds a use of this initializer. 3454 PushFunctionScope(); 3455 } 3456 3457 /// \brief This is invoked after parsing an in-class initializer for a 3458 /// non-static C++ class member, and after instantiating an in-class initializer 3459 /// in a class template. Such actions are deferred until the class is complete. 3460 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3461 SourceLocation InitLoc, 3462 Expr *InitExpr) { 3463 // Pop the notional constructor scope we created earlier. 3464 PopFunctionScopeInfo(nullptr, D); 3465 3466 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3467 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3468 "must set init style when field is created"); 3469 3470 if (!InitExpr) { 3471 D->setInvalidDecl(); 3472 if (FD) 3473 FD->removeInClassInitializer(); 3474 return; 3475 } 3476 3477 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3478 FD->setInvalidDecl(); 3479 FD->removeInClassInitializer(); 3480 return; 3481 } 3482 3483 ExprResult Init = InitExpr; 3484 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3485 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3486 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 3487 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 3488 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3489 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3490 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3491 if (Init.isInvalid()) { 3492 FD->setInvalidDecl(); 3493 return; 3494 } 3495 } 3496 3497 // C++11 [class.base.init]p7: 3498 // The initialization of each base and member constitutes a 3499 // full-expression. 3500 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3501 if (Init.isInvalid()) { 3502 FD->setInvalidDecl(); 3503 return; 3504 } 3505 3506 InitExpr = Init.get(); 3507 3508 FD->setInClassInitializer(InitExpr); 3509 } 3510 3511 /// \brief Find the direct and/or virtual base specifiers that 3512 /// correspond to the given base type, for use in base initialization 3513 /// within a constructor. 3514 static bool FindBaseInitializer(Sema &SemaRef, 3515 CXXRecordDecl *ClassDecl, 3516 QualType BaseType, 3517 const CXXBaseSpecifier *&DirectBaseSpec, 3518 const CXXBaseSpecifier *&VirtualBaseSpec) { 3519 // First, check for a direct base class. 3520 DirectBaseSpec = nullptr; 3521 for (const auto &Base : ClassDecl->bases()) { 3522 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3523 // We found a direct base of this type. That's what we're 3524 // initializing. 3525 DirectBaseSpec = &Base; 3526 break; 3527 } 3528 } 3529 3530 // Check for a virtual base class. 3531 // FIXME: We might be able to short-circuit this if we know in advance that 3532 // there are no virtual bases. 3533 VirtualBaseSpec = nullptr; 3534 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3535 // We haven't found a base yet; search the class hierarchy for a 3536 // virtual base class. 3537 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3538 /*DetectVirtual=*/false); 3539 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3540 SemaRef.Context.getTypeDeclType(ClassDecl), 3541 BaseType, Paths)) { 3542 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3543 Path != Paths.end(); ++Path) { 3544 if (Path->back().Base->isVirtual()) { 3545 VirtualBaseSpec = Path->back().Base; 3546 break; 3547 } 3548 } 3549 } 3550 } 3551 3552 return DirectBaseSpec || VirtualBaseSpec; 3553 } 3554 3555 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3556 MemInitResult 3557 Sema::ActOnMemInitializer(Decl *ConstructorD, 3558 Scope *S, 3559 CXXScopeSpec &SS, 3560 IdentifierInfo *MemberOrBase, 3561 ParsedType TemplateTypeTy, 3562 const DeclSpec &DS, 3563 SourceLocation IdLoc, 3564 Expr *InitList, 3565 SourceLocation EllipsisLoc) { 3566 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3567 DS, IdLoc, InitList, 3568 EllipsisLoc); 3569 } 3570 3571 /// \brief Handle a C++ member initializer using parentheses syntax. 3572 MemInitResult 3573 Sema::ActOnMemInitializer(Decl *ConstructorD, 3574 Scope *S, 3575 CXXScopeSpec &SS, 3576 IdentifierInfo *MemberOrBase, 3577 ParsedType TemplateTypeTy, 3578 const DeclSpec &DS, 3579 SourceLocation IdLoc, 3580 SourceLocation LParenLoc, 3581 ArrayRef<Expr *> Args, 3582 SourceLocation RParenLoc, 3583 SourceLocation EllipsisLoc) { 3584 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3585 Args, RParenLoc); 3586 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3587 DS, IdLoc, List, EllipsisLoc); 3588 } 3589 3590 namespace { 3591 3592 // Callback to only accept typo corrections that can be a valid C++ member 3593 // intializer: either a non-static field member or a base class. 3594 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3595 public: 3596 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3597 : ClassDecl(ClassDecl) {} 3598 3599 bool ValidateCandidate(const TypoCorrection &candidate) override { 3600 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3601 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3602 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3603 return isa<TypeDecl>(ND); 3604 } 3605 return false; 3606 } 3607 3608 private: 3609 CXXRecordDecl *ClassDecl; 3610 }; 3611 3612 } 3613 3614 /// \brief Handle a C++ member initializer. 3615 MemInitResult 3616 Sema::BuildMemInitializer(Decl *ConstructorD, 3617 Scope *S, 3618 CXXScopeSpec &SS, 3619 IdentifierInfo *MemberOrBase, 3620 ParsedType TemplateTypeTy, 3621 const DeclSpec &DS, 3622 SourceLocation IdLoc, 3623 Expr *Init, 3624 SourceLocation EllipsisLoc) { 3625 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3626 if (!Res.isUsable()) 3627 return true; 3628 Init = Res.get(); 3629 3630 if (!ConstructorD) 3631 return true; 3632 3633 AdjustDeclIfTemplate(ConstructorD); 3634 3635 CXXConstructorDecl *Constructor 3636 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3637 if (!Constructor) { 3638 // The user wrote a constructor initializer on a function that is 3639 // not a C++ constructor. Ignore the error for now, because we may 3640 // have more member initializers coming; we'll diagnose it just 3641 // once in ActOnMemInitializers. 3642 return true; 3643 } 3644 3645 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3646 3647 // C++ [class.base.init]p2: 3648 // Names in a mem-initializer-id are looked up in the scope of the 3649 // constructor's class and, if not found in that scope, are looked 3650 // up in the scope containing the constructor's definition. 3651 // [Note: if the constructor's class contains a member with the 3652 // same name as a direct or virtual base class of the class, a 3653 // mem-initializer-id naming the member or base class and composed 3654 // of a single identifier refers to the class member. A 3655 // mem-initializer-id for the hidden base class may be specified 3656 // using a qualified name. ] 3657 if (!SS.getScopeRep() && !TemplateTypeTy) { 3658 // Look for a member, first. 3659 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3660 if (!Result.empty()) { 3661 ValueDecl *Member; 3662 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3663 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3664 if (EllipsisLoc.isValid()) 3665 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3666 << MemberOrBase 3667 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3668 3669 return BuildMemberInitializer(Member, Init, IdLoc); 3670 } 3671 } 3672 } 3673 // It didn't name a member, so see if it names a class. 3674 QualType BaseType; 3675 TypeSourceInfo *TInfo = nullptr; 3676 3677 if (TemplateTypeTy) { 3678 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3679 } else if (DS.getTypeSpecType() == TST_decltype) { 3680 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3681 } else { 3682 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3683 LookupParsedName(R, S, &SS); 3684 3685 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3686 if (!TyD) { 3687 if (R.isAmbiguous()) return true; 3688 3689 // We don't want access-control diagnostics here. 3690 R.suppressDiagnostics(); 3691 3692 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3693 bool NotUnknownSpecialization = false; 3694 DeclContext *DC = computeDeclContext(SS, false); 3695 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3696 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3697 3698 if (!NotUnknownSpecialization) { 3699 // When the scope specifier can refer to a member of an unknown 3700 // specialization, we take it as a type name. 3701 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3702 SS.getWithLocInContext(Context), 3703 *MemberOrBase, IdLoc); 3704 if (BaseType.isNull()) 3705 return true; 3706 3707 R.clear(); 3708 R.setLookupName(MemberOrBase); 3709 } 3710 } 3711 3712 // If no results were found, try to correct typos. 3713 TypoCorrection Corr; 3714 if (R.empty() && BaseType.isNull() && 3715 (Corr = CorrectTypo( 3716 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3717 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3718 CTK_ErrorRecovery, ClassDecl))) { 3719 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3720 // We have found a non-static data member with a similar 3721 // name to what was typed; complain and initialize that 3722 // member. 3723 diagnoseTypo(Corr, 3724 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3725 << MemberOrBase << true); 3726 return BuildMemberInitializer(Member, Init, IdLoc); 3727 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3728 const CXXBaseSpecifier *DirectBaseSpec; 3729 const CXXBaseSpecifier *VirtualBaseSpec; 3730 if (FindBaseInitializer(*this, ClassDecl, 3731 Context.getTypeDeclType(Type), 3732 DirectBaseSpec, VirtualBaseSpec)) { 3733 // We have found a direct or virtual base class with a 3734 // similar name to what was typed; complain and initialize 3735 // that base class. 3736 diagnoseTypo(Corr, 3737 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3738 << MemberOrBase << false, 3739 PDiag() /*Suppress note, we provide our own.*/); 3740 3741 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3742 : VirtualBaseSpec; 3743 Diag(BaseSpec->getLocStart(), 3744 diag::note_base_class_specified_here) 3745 << BaseSpec->getType() 3746 << BaseSpec->getSourceRange(); 3747 3748 TyD = Type; 3749 } 3750 } 3751 } 3752 3753 if (!TyD && BaseType.isNull()) { 3754 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3755 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3756 return true; 3757 } 3758 } 3759 3760 if (BaseType.isNull()) { 3761 BaseType = Context.getTypeDeclType(TyD); 3762 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3763 if (SS.isSet()) { 3764 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3765 BaseType); 3766 TInfo = Context.CreateTypeSourceInfo(BaseType); 3767 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3768 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3769 TL.setElaboratedKeywordLoc(SourceLocation()); 3770 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3771 } 3772 } 3773 } 3774 3775 if (!TInfo) 3776 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3777 3778 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3779 } 3780 3781 /// Checks a member initializer expression for cases where reference (or 3782 /// pointer) members are bound to by-value parameters (or their addresses). 3783 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3784 Expr *Init, 3785 SourceLocation IdLoc) { 3786 QualType MemberTy = Member->getType(); 3787 3788 // We only handle pointers and references currently. 3789 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3790 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3791 return; 3792 3793 const bool IsPointer = MemberTy->isPointerType(); 3794 if (IsPointer) { 3795 if (const UnaryOperator *Op 3796 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3797 // The only case we're worried about with pointers requires taking the 3798 // address. 3799 if (Op->getOpcode() != UO_AddrOf) 3800 return; 3801 3802 Init = Op->getSubExpr(); 3803 } else { 3804 // We only handle address-of expression initializers for pointers. 3805 return; 3806 } 3807 } 3808 3809 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3810 // We only warn when referring to a non-reference parameter declaration. 3811 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3812 if (!Parameter || Parameter->getType()->isReferenceType()) 3813 return; 3814 3815 S.Diag(Init->getExprLoc(), 3816 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3817 : diag::warn_bind_ref_member_to_parameter) 3818 << Member << Parameter << Init->getSourceRange(); 3819 } else { 3820 // Other initializers are fine. 3821 return; 3822 } 3823 3824 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3825 << (unsigned)IsPointer; 3826 } 3827 3828 MemInitResult 3829 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3830 SourceLocation IdLoc) { 3831 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3832 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3833 assert((DirectMember || IndirectMember) && 3834 "Member must be a FieldDecl or IndirectFieldDecl"); 3835 3836 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3837 return true; 3838 3839 if (Member->isInvalidDecl()) 3840 return true; 3841 3842 MultiExprArg Args; 3843 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3844 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3845 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3846 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3847 } else { 3848 // Template instantiation doesn't reconstruct ParenListExprs for us. 3849 Args = Init; 3850 } 3851 3852 SourceRange InitRange = Init->getSourceRange(); 3853 3854 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3855 // Can't check initialization for a member of dependent type or when 3856 // any of the arguments are type-dependent expressions. 3857 DiscardCleanupsInEvaluationContext(); 3858 } else { 3859 bool InitList = false; 3860 if (isa<InitListExpr>(Init)) { 3861 InitList = true; 3862 Args = Init; 3863 } 3864 3865 // Initialize the member. 3866 InitializedEntity MemberEntity = 3867 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3868 : InitializedEntity::InitializeMember(IndirectMember, 3869 nullptr); 3870 InitializationKind Kind = 3871 InitList ? InitializationKind::CreateDirectList(IdLoc) 3872 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3873 InitRange.getEnd()); 3874 3875 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3876 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3877 nullptr); 3878 if (MemberInit.isInvalid()) 3879 return true; 3880 3881 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3882 3883 // C++11 [class.base.init]p7: 3884 // The initialization of each base and member constitutes a 3885 // full-expression. 3886 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3887 if (MemberInit.isInvalid()) 3888 return true; 3889 3890 Init = MemberInit.get(); 3891 } 3892 3893 if (DirectMember) { 3894 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3895 InitRange.getBegin(), Init, 3896 InitRange.getEnd()); 3897 } else { 3898 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3899 InitRange.getBegin(), Init, 3900 InitRange.getEnd()); 3901 } 3902 } 3903 3904 MemInitResult 3905 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3906 CXXRecordDecl *ClassDecl) { 3907 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3908 if (!LangOpts.CPlusPlus11) 3909 return Diag(NameLoc, diag::err_delegating_ctor) 3910 << TInfo->getTypeLoc().getLocalSourceRange(); 3911 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3912 3913 bool InitList = true; 3914 MultiExprArg Args = Init; 3915 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3916 InitList = false; 3917 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3918 } 3919 3920 SourceRange InitRange = Init->getSourceRange(); 3921 // Initialize the object. 3922 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3923 QualType(ClassDecl->getTypeForDecl(), 0)); 3924 InitializationKind Kind = 3925 InitList ? InitializationKind::CreateDirectList(NameLoc) 3926 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3927 InitRange.getEnd()); 3928 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3929 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3930 Args, nullptr); 3931 if (DelegationInit.isInvalid()) 3932 return true; 3933 3934 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3935 "Delegating constructor with no target?"); 3936 3937 // C++11 [class.base.init]p7: 3938 // The initialization of each base and member constitutes a 3939 // full-expression. 3940 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3941 InitRange.getBegin()); 3942 if (DelegationInit.isInvalid()) 3943 return true; 3944 3945 // If we are in a dependent context, template instantiation will 3946 // perform this type-checking again. Just save the arguments that we 3947 // received in a ParenListExpr. 3948 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3949 // of the information that we have about the base 3950 // initializer. However, deconstructing the ASTs is a dicey process, 3951 // and this approach is far more likely to get the corner cases right. 3952 if (CurContext->isDependentContext()) 3953 DelegationInit = Init; 3954 3955 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3956 DelegationInit.getAs<Expr>(), 3957 InitRange.getEnd()); 3958 } 3959 3960 MemInitResult 3961 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3962 Expr *Init, CXXRecordDecl *ClassDecl, 3963 SourceLocation EllipsisLoc) { 3964 SourceLocation BaseLoc 3965 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3966 3967 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3968 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3969 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3970 3971 // C++ [class.base.init]p2: 3972 // [...] Unless the mem-initializer-id names a nonstatic data 3973 // member of the constructor's class or a direct or virtual base 3974 // of that class, the mem-initializer is ill-formed. A 3975 // mem-initializer-list can initialize a base class using any 3976 // name that denotes that base class type. 3977 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3978 3979 SourceRange InitRange = Init->getSourceRange(); 3980 if (EllipsisLoc.isValid()) { 3981 // This is a pack expansion. 3982 if (!BaseType->containsUnexpandedParameterPack()) { 3983 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3984 << SourceRange(BaseLoc, InitRange.getEnd()); 3985 3986 EllipsisLoc = SourceLocation(); 3987 } 3988 } else { 3989 // Check for any unexpanded parameter packs. 3990 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3991 return true; 3992 3993 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3994 return true; 3995 } 3996 3997 // Check for direct and virtual base classes. 3998 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3999 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4000 if (!Dependent) { 4001 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4002 BaseType)) 4003 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4004 4005 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4006 VirtualBaseSpec); 4007 4008 // C++ [base.class.init]p2: 4009 // Unless the mem-initializer-id names a nonstatic data member of the 4010 // constructor's class or a direct or virtual base of that class, the 4011 // mem-initializer is ill-formed. 4012 if (!DirectBaseSpec && !VirtualBaseSpec) { 4013 // If the class has any dependent bases, then it's possible that 4014 // one of those types will resolve to the same type as 4015 // BaseType. Therefore, just treat this as a dependent base 4016 // class initialization. FIXME: Should we try to check the 4017 // initialization anyway? It seems odd. 4018 if (ClassDecl->hasAnyDependentBases()) 4019 Dependent = true; 4020 else 4021 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4022 << BaseType << Context.getTypeDeclType(ClassDecl) 4023 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4024 } 4025 } 4026 4027 if (Dependent) { 4028 DiscardCleanupsInEvaluationContext(); 4029 4030 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4031 /*IsVirtual=*/false, 4032 InitRange.getBegin(), Init, 4033 InitRange.getEnd(), EllipsisLoc); 4034 } 4035 4036 // C++ [base.class.init]p2: 4037 // If a mem-initializer-id is ambiguous because it designates both 4038 // a direct non-virtual base class and an inherited virtual base 4039 // class, the mem-initializer is ill-formed. 4040 if (DirectBaseSpec && VirtualBaseSpec) 4041 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4042 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4043 4044 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4045 if (!BaseSpec) 4046 BaseSpec = VirtualBaseSpec; 4047 4048 // Initialize the base. 4049 bool InitList = true; 4050 MultiExprArg Args = Init; 4051 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4052 InitList = false; 4053 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4054 } 4055 4056 InitializedEntity BaseEntity = 4057 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4058 InitializationKind Kind = 4059 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4060 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4061 InitRange.getEnd()); 4062 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4063 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4064 if (BaseInit.isInvalid()) 4065 return true; 4066 4067 // C++11 [class.base.init]p7: 4068 // The initialization of each base and member constitutes a 4069 // full-expression. 4070 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4071 if (BaseInit.isInvalid()) 4072 return true; 4073 4074 // If we are in a dependent context, template instantiation will 4075 // perform this type-checking again. Just save the arguments that we 4076 // received in a ParenListExpr. 4077 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4078 // of the information that we have about the base 4079 // initializer. However, deconstructing the ASTs is a dicey process, 4080 // and this approach is far more likely to get the corner cases right. 4081 if (CurContext->isDependentContext()) 4082 BaseInit = Init; 4083 4084 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4085 BaseSpec->isVirtual(), 4086 InitRange.getBegin(), 4087 BaseInit.getAs<Expr>(), 4088 InitRange.getEnd(), EllipsisLoc); 4089 } 4090 4091 // Create a static_cast\<T&&>(expr). 4092 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4093 if (T.isNull()) T = E->getType(); 4094 QualType TargetType = SemaRef.BuildReferenceType( 4095 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4096 SourceLocation ExprLoc = E->getLocStart(); 4097 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4098 TargetType, ExprLoc); 4099 4100 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4101 SourceRange(ExprLoc, ExprLoc), 4102 E->getSourceRange()).get(); 4103 } 4104 4105 /// ImplicitInitializerKind - How an implicit base or member initializer should 4106 /// initialize its base or member. 4107 enum ImplicitInitializerKind { 4108 IIK_Default, 4109 IIK_Copy, 4110 IIK_Move, 4111 IIK_Inherit 4112 }; 4113 4114 static bool 4115 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4116 ImplicitInitializerKind ImplicitInitKind, 4117 CXXBaseSpecifier *BaseSpec, 4118 bool IsInheritedVirtualBase, 4119 CXXCtorInitializer *&CXXBaseInit) { 4120 InitializedEntity InitEntity 4121 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4122 IsInheritedVirtualBase); 4123 4124 ExprResult BaseInit; 4125 4126 switch (ImplicitInitKind) { 4127 case IIK_Inherit: 4128 case IIK_Default: { 4129 InitializationKind InitKind 4130 = InitializationKind::CreateDefault(Constructor->getLocation()); 4131 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4132 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4133 break; 4134 } 4135 4136 case IIK_Move: 4137 case IIK_Copy: { 4138 bool Moving = ImplicitInitKind == IIK_Move; 4139 ParmVarDecl *Param = Constructor->getParamDecl(0); 4140 QualType ParamType = Param->getType().getNonReferenceType(); 4141 4142 Expr *CopyCtorArg = 4143 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4144 SourceLocation(), Param, false, 4145 Constructor->getLocation(), ParamType, 4146 VK_LValue, nullptr); 4147 4148 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4149 4150 // Cast to the base class to avoid ambiguities. 4151 QualType ArgTy = 4152 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4153 ParamType.getQualifiers()); 4154 4155 if (Moving) { 4156 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4157 } 4158 4159 CXXCastPath BasePath; 4160 BasePath.push_back(BaseSpec); 4161 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4162 CK_UncheckedDerivedToBase, 4163 Moving ? VK_XValue : VK_LValue, 4164 &BasePath).get(); 4165 4166 InitializationKind InitKind 4167 = InitializationKind::CreateDirect(Constructor->getLocation(), 4168 SourceLocation(), SourceLocation()); 4169 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4170 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4171 break; 4172 } 4173 } 4174 4175 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4176 if (BaseInit.isInvalid()) 4177 return true; 4178 4179 CXXBaseInit = 4180 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4181 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4182 SourceLocation()), 4183 BaseSpec->isVirtual(), 4184 SourceLocation(), 4185 BaseInit.getAs<Expr>(), 4186 SourceLocation(), 4187 SourceLocation()); 4188 4189 return false; 4190 } 4191 4192 static bool RefersToRValueRef(Expr *MemRef) { 4193 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4194 return Referenced->getType()->isRValueReferenceType(); 4195 } 4196 4197 static bool 4198 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4199 ImplicitInitializerKind ImplicitInitKind, 4200 FieldDecl *Field, IndirectFieldDecl *Indirect, 4201 CXXCtorInitializer *&CXXMemberInit) { 4202 if (Field->isInvalidDecl()) 4203 return true; 4204 4205 SourceLocation Loc = Constructor->getLocation(); 4206 4207 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4208 bool Moving = ImplicitInitKind == IIK_Move; 4209 ParmVarDecl *Param = Constructor->getParamDecl(0); 4210 QualType ParamType = Param->getType().getNonReferenceType(); 4211 4212 // Suppress copying zero-width bitfields. 4213 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 4214 return false; 4215 4216 Expr *MemberExprBase = 4217 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4218 SourceLocation(), Param, false, 4219 Loc, ParamType, VK_LValue, nullptr); 4220 4221 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4222 4223 if (Moving) { 4224 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4225 } 4226 4227 // Build a reference to this field within the parameter. 4228 CXXScopeSpec SS; 4229 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4230 Sema::LookupMemberName); 4231 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4232 : cast<ValueDecl>(Field), AS_public); 4233 MemberLookup.resolveKind(); 4234 ExprResult CtorArg 4235 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4236 ParamType, Loc, 4237 /*IsArrow=*/false, 4238 SS, 4239 /*TemplateKWLoc=*/SourceLocation(), 4240 /*FirstQualifierInScope=*/nullptr, 4241 MemberLookup, 4242 /*TemplateArgs=*/nullptr, 4243 /*S*/nullptr); 4244 if (CtorArg.isInvalid()) 4245 return true; 4246 4247 // C++11 [class.copy]p15: 4248 // - if a member m has rvalue reference type T&&, it is direct-initialized 4249 // with static_cast<T&&>(x.m); 4250 if (RefersToRValueRef(CtorArg.get())) { 4251 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4252 } 4253 4254 // When the field we are copying is an array, create index variables for 4255 // each dimension of the array. We use these index variables to subscript 4256 // the source array, and other clients (e.g., CodeGen) will perform the 4257 // necessary iteration with these index variables. 4258 SmallVector<VarDecl *, 4> IndexVariables; 4259 QualType BaseType = Field->getType(); 4260 QualType SizeType = SemaRef.Context.getSizeType(); 4261 bool InitializingArray = false; 4262 while (const ConstantArrayType *Array 4263 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 4264 InitializingArray = true; 4265 // Create the iteration variable for this array index. 4266 IdentifierInfo *IterationVarName = nullptr; 4267 { 4268 SmallString<8> Str; 4269 llvm::raw_svector_ostream OS(Str); 4270 OS << "__i" << IndexVariables.size(); 4271 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 4272 } 4273 VarDecl *IterationVar 4274 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 4275 IterationVarName, SizeType, 4276 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 4277 SC_None); 4278 IndexVariables.push_back(IterationVar); 4279 4280 // Create a reference to the iteration variable. 4281 ExprResult IterationVarRef 4282 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 4283 assert(!IterationVarRef.isInvalid() && 4284 "Reference to invented variable cannot fail!"); 4285 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 4286 assert(!IterationVarRef.isInvalid() && 4287 "Conversion of invented variable cannot fail!"); 4288 4289 // Subscript the array with this iteration variable. 4290 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 4291 IterationVarRef.get(), 4292 Loc); 4293 if (CtorArg.isInvalid()) 4294 return true; 4295 4296 BaseType = Array->getElementType(); 4297 } 4298 4299 // The array subscript expression is an lvalue, which is wrong for moving. 4300 if (Moving && InitializingArray) 4301 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4302 4303 // Construct the entity that we will be initializing. For an array, this 4304 // will be first element in the array, which may require several levels 4305 // of array-subscript entities. 4306 SmallVector<InitializedEntity, 4> Entities; 4307 Entities.reserve(1 + IndexVariables.size()); 4308 if (Indirect) 4309 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 4310 else 4311 Entities.push_back(InitializedEntity::InitializeMember(Field)); 4312 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 4313 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 4314 0, 4315 Entities.back())); 4316 4317 // Direct-initialize to use the copy constructor. 4318 InitializationKind InitKind = 4319 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4320 4321 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4322 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 4323 CtorArgE); 4324 4325 ExprResult MemberInit 4326 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 4327 MultiExprArg(&CtorArgE, 1)); 4328 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4329 if (MemberInit.isInvalid()) 4330 return true; 4331 4332 if (Indirect) { 4333 assert(IndexVariables.size() == 0 && 4334 "Indirect field improperly initialized"); 4335 CXXMemberInit 4336 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 4337 Loc, Loc, 4338 MemberInit.getAs<Expr>(), 4339 Loc); 4340 } else 4341 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 4342 Loc, MemberInit.getAs<Expr>(), 4343 Loc, 4344 IndexVariables.data(), 4345 IndexVariables.size()); 4346 return false; 4347 } 4348 4349 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4350 "Unhandled implicit init kind!"); 4351 4352 QualType FieldBaseElementType = 4353 SemaRef.Context.getBaseElementType(Field->getType()); 4354 4355 if (FieldBaseElementType->isRecordType()) { 4356 InitializedEntity InitEntity 4357 = Indirect? InitializedEntity::InitializeMember(Indirect) 4358 : InitializedEntity::InitializeMember(Field); 4359 InitializationKind InitKind = 4360 InitializationKind::CreateDefault(Loc); 4361 4362 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4363 ExprResult MemberInit = 4364 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4365 4366 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4367 if (MemberInit.isInvalid()) 4368 return true; 4369 4370 if (Indirect) 4371 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4372 Indirect, Loc, 4373 Loc, 4374 MemberInit.get(), 4375 Loc); 4376 else 4377 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4378 Field, Loc, Loc, 4379 MemberInit.get(), 4380 Loc); 4381 return false; 4382 } 4383 4384 if (!Field->getParent()->isUnion()) { 4385 if (FieldBaseElementType->isReferenceType()) { 4386 SemaRef.Diag(Constructor->getLocation(), 4387 diag::err_uninitialized_member_in_ctor) 4388 << (int)Constructor->isImplicit() 4389 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4390 << 0 << Field->getDeclName(); 4391 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4392 return true; 4393 } 4394 4395 if (FieldBaseElementType.isConstQualified()) { 4396 SemaRef.Diag(Constructor->getLocation(), 4397 diag::err_uninitialized_member_in_ctor) 4398 << (int)Constructor->isImplicit() 4399 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4400 << 1 << Field->getDeclName(); 4401 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4402 return true; 4403 } 4404 } 4405 4406 if (SemaRef.getLangOpts().ObjCAutoRefCount && 4407 FieldBaseElementType->isObjCRetainableType() && 4408 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 4409 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 4410 // ARC: 4411 // Default-initialize Objective-C pointers to NULL. 4412 CXXMemberInit 4413 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4414 Loc, Loc, 4415 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4416 Loc); 4417 return false; 4418 } 4419 4420 // Nothing to initialize. 4421 CXXMemberInit = nullptr; 4422 return false; 4423 } 4424 4425 namespace { 4426 struct BaseAndFieldInfo { 4427 Sema &S; 4428 CXXConstructorDecl *Ctor; 4429 bool AnyErrorsInInits; 4430 ImplicitInitializerKind IIK; 4431 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4432 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4433 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4434 4435 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4436 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4437 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4438 if (Ctor->getInheritedConstructor()) 4439 IIK = IIK_Inherit; 4440 else if (Generated && Ctor->isCopyConstructor()) 4441 IIK = IIK_Copy; 4442 else if (Generated && Ctor->isMoveConstructor()) 4443 IIK = IIK_Move; 4444 else 4445 IIK = IIK_Default; 4446 } 4447 4448 bool isImplicitCopyOrMove() const { 4449 switch (IIK) { 4450 case IIK_Copy: 4451 case IIK_Move: 4452 return true; 4453 4454 case IIK_Default: 4455 case IIK_Inherit: 4456 return false; 4457 } 4458 4459 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4460 } 4461 4462 bool addFieldInitializer(CXXCtorInitializer *Init) { 4463 AllToInit.push_back(Init); 4464 4465 // Check whether this initializer makes the field "used". 4466 if (Init->getInit()->HasSideEffects(S.Context)) 4467 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4468 4469 return false; 4470 } 4471 4472 bool isInactiveUnionMember(FieldDecl *Field) { 4473 RecordDecl *Record = Field->getParent(); 4474 if (!Record->isUnion()) 4475 return false; 4476 4477 if (FieldDecl *Active = 4478 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4479 return Active != Field->getCanonicalDecl(); 4480 4481 // In an implicit copy or move constructor, ignore any in-class initializer. 4482 if (isImplicitCopyOrMove()) 4483 return true; 4484 4485 // If there's no explicit initialization, the field is active only if it 4486 // has an in-class initializer... 4487 if (Field->hasInClassInitializer()) 4488 return false; 4489 // ... or it's an anonymous struct or union whose class has an in-class 4490 // initializer. 4491 if (!Field->isAnonymousStructOrUnion()) 4492 return true; 4493 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4494 return !FieldRD->hasInClassInitializer(); 4495 } 4496 4497 /// \brief Determine whether the given field is, or is within, a union member 4498 /// that is inactive (because there was an initializer given for a different 4499 /// member of the union, or because the union was not initialized at all). 4500 bool isWithinInactiveUnionMember(FieldDecl *Field, 4501 IndirectFieldDecl *Indirect) { 4502 if (!Indirect) 4503 return isInactiveUnionMember(Field); 4504 4505 for (auto *C : Indirect->chain()) { 4506 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4507 if (Field && isInactiveUnionMember(Field)) 4508 return true; 4509 } 4510 return false; 4511 } 4512 }; 4513 } 4514 4515 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4516 /// array type. 4517 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4518 if (T->isIncompleteArrayType()) 4519 return true; 4520 4521 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4522 if (!ArrayT->getSize()) 4523 return true; 4524 4525 T = ArrayT->getElementType(); 4526 } 4527 4528 return false; 4529 } 4530 4531 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4532 FieldDecl *Field, 4533 IndirectFieldDecl *Indirect = nullptr) { 4534 if (Field->isInvalidDecl()) 4535 return false; 4536 4537 // Overwhelmingly common case: we have a direct initializer for this field. 4538 if (CXXCtorInitializer *Init = 4539 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4540 return Info.addFieldInitializer(Init); 4541 4542 // C++11 [class.base.init]p8: 4543 // if the entity is a non-static data member that has a 4544 // brace-or-equal-initializer and either 4545 // -- the constructor's class is a union and no other variant member of that 4546 // union is designated by a mem-initializer-id or 4547 // -- the constructor's class is not a union, and, if the entity is a member 4548 // of an anonymous union, no other member of that union is designated by 4549 // a mem-initializer-id, 4550 // the entity is initialized as specified in [dcl.init]. 4551 // 4552 // We also apply the same rules to handle anonymous structs within anonymous 4553 // unions. 4554 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4555 return false; 4556 4557 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4558 ExprResult DIE = 4559 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4560 if (DIE.isInvalid()) 4561 return true; 4562 CXXCtorInitializer *Init; 4563 if (Indirect) 4564 Init = new (SemaRef.Context) 4565 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4566 SourceLocation(), DIE.get(), SourceLocation()); 4567 else 4568 Init = new (SemaRef.Context) 4569 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4570 SourceLocation(), DIE.get(), SourceLocation()); 4571 return Info.addFieldInitializer(Init); 4572 } 4573 4574 // Don't initialize incomplete or zero-length arrays. 4575 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4576 return false; 4577 4578 // Don't try to build an implicit initializer if there were semantic 4579 // errors in any of the initializers (and therefore we might be 4580 // missing some that the user actually wrote). 4581 if (Info.AnyErrorsInInits) 4582 return false; 4583 4584 CXXCtorInitializer *Init = nullptr; 4585 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4586 Indirect, Init)) 4587 return true; 4588 4589 if (!Init) 4590 return false; 4591 4592 return Info.addFieldInitializer(Init); 4593 } 4594 4595 bool 4596 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4597 CXXCtorInitializer *Initializer) { 4598 assert(Initializer->isDelegatingInitializer()); 4599 Constructor->setNumCtorInitializers(1); 4600 CXXCtorInitializer **initializer = 4601 new (Context) CXXCtorInitializer*[1]; 4602 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4603 Constructor->setCtorInitializers(initializer); 4604 4605 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4606 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4607 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4608 } 4609 4610 DelegatingCtorDecls.push_back(Constructor); 4611 4612 DiagnoseUninitializedFields(*this, Constructor); 4613 4614 return false; 4615 } 4616 4617 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4618 ArrayRef<CXXCtorInitializer *> Initializers) { 4619 if (Constructor->isDependentContext()) { 4620 // Just store the initializers as written, they will be checked during 4621 // instantiation. 4622 if (!Initializers.empty()) { 4623 Constructor->setNumCtorInitializers(Initializers.size()); 4624 CXXCtorInitializer **baseOrMemberInitializers = 4625 new (Context) CXXCtorInitializer*[Initializers.size()]; 4626 memcpy(baseOrMemberInitializers, Initializers.data(), 4627 Initializers.size() * sizeof(CXXCtorInitializer*)); 4628 Constructor->setCtorInitializers(baseOrMemberInitializers); 4629 } 4630 4631 // Let template instantiation know whether we had errors. 4632 if (AnyErrors) 4633 Constructor->setInvalidDecl(); 4634 4635 return false; 4636 } 4637 4638 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4639 4640 // We need to build the initializer AST according to order of construction 4641 // and not what user specified in the Initializers list. 4642 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4643 if (!ClassDecl) 4644 return true; 4645 4646 bool HadError = false; 4647 4648 for (unsigned i = 0; i < Initializers.size(); i++) { 4649 CXXCtorInitializer *Member = Initializers[i]; 4650 4651 if (Member->isBaseInitializer()) 4652 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4653 else { 4654 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4655 4656 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4657 for (auto *C : F->chain()) { 4658 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4659 if (FD && FD->getParent()->isUnion()) 4660 Info.ActiveUnionMember.insert(std::make_pair( 4661 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4662 } 4663 } else if (FieldDecl *FD = Member->getMember()) { 4664 if (FD->getParent()->isUnion()) 4665 Info.ActiveUnionMember.insert(std::make_pair( 4666 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4667 } 4668 } 4669 } 4670 4671 // Keep track of the direct virtual bases. 4672 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4673 for (auto &I : ClassDecl->bases()) { 4674 if (I.isVirtual()) 4675 DirectVBases.insert(&I); 4676 } 4677 4678 // Push virtual bases before others. 4679 for (auto &VBase : ClassDecl->vbases()) { 4680 if (CXXCtorInitializer *Value 4681 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4682 // [class.base.init]p7, per DR257: 4683 // A mem-initializer where the mem-initializer-id names a virtual base 4684 // class is ignored during execution of a constructor of any class that 4685 // is not the most derived class. 4686 if (ClassDecl->isAbstract()) { 4687 // FIXME: Provide a fixit to remove the base specifier. This requires 4688 // tracking the location of the associated comma for a base specifier. 4689 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4690 << VBase.getType() << ClassDecl; 4691 DiagnoseAbstractType(ClassDecl); 4692 } 4693 4694 Info.AllToInit.push_back(Value); 4695 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4696 // [class.base.init]p8, per DR257: 4697 // If a given [...] base class is not named by a mem-initializer-id 4698 // [...] and the entity is not a virtual base class of an abstract 4699 // class, then [...] the entity is default-initialized. 4700 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4701 CXXCtorInitializer *CXXBaseInit; 4702 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4703 &VBase, IsInheritedVirtualBase, 4704 CXXBaseInit)) { 4705 HadError = true; 4706 continue; 4707 } 4708 4709 Info.AllToInit.push_back(CXXBaseInit); 4710 } 4711 } 4712 4713 // Non-virtual bases. 4714 for (auto &Base : ClassDecl->bases()) { 4715 // Virtuals are in the virtual base list and already constructed. 4716 if (Base.isVirtual()) 4717 continue; 4718 4719 if (CXXCtorInitializer *Value 4720 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4721 Info.AllToInit.push_back(Value); 4722 } else if (!AnyErrors) { 4723 CXXCtorInitializer *CXXBaseInit; 4724 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4725 &Base, /*IsInheritedVirtualBase=*/false, 4726 CXXBaseInit)) { 4727 HadError = true; 4728 continue; 4729 } 4730 4731 Info.AllToInit.push_back(CXXBaseInit); 4732 } 4733 } 4734 4735 // Fields. 4736 for (auto *Mem : ClassDecl->decls()) { 4737 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4738 // C++ [class.bit]p2: 4739 // A declaration for a bit-field that omits the identifier declares an 4740 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4741 // initialized. 4742 if (F->isUnnamedBitfield()) 4743 continue; 4744 4745 // If we're not generating the implicit copy/move constructor, then we'll 4746 // handle anonymous struct/union fields based on their individual 4747 // indirect fields. 4748 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4749 continue; 4750 4751 if (CollectFieldInitializer(*this, Info, F)) 4752 HadError = true; 4753 continue; 4754 } 4755 4756 // Beyond this point, we only consider default initialization. 4757 if (Info.isImplicitCopyOrMove()) 4758 continue; 4759 4760 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4761 if (F->getType()->isIncompleteArrayType()) { 4762 assert(ClassDecl->hasFlexibleArrayMember() && 4763 "Incomplete array type is not valid"); 4764 continue; 4765 } 4766 4767 // Initialize each field of an anonymous struct individually. 4768 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4769 HadError = true; 4770 4771 continue; 4772 } 4773 } 4774 4775 unsigned NumInitializers = Info.AllToInit.size(); 4776 if (NumInitializers > 0) { 4777 Constructor->setNumCtorInitializers(NumInitializers); 4778 CXXCtorInitializer **baseOrMemberInitializers = 4779 new (Context) CXXCtorInitializer*[NumInitializers]; 4780 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4781 NumInitializers * sizeof(CXXCtorInitializer*)); 4782 Constructor->setCtorInitializers(baseOrMemberInitializers); 4783 4784 // Constructors implicitly reference the base and member 4785 // destructors. 4786 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4787 Constructor->getParent()); 4788 } 4789 4790 return HadError; 4791 } 4792 4793 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4794 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4795 const RecordDecl *RD = RT->getDecl(); 4796 if (RD->isAnonymousStructOrUnion()) { 4797 for (auto *Field : RD->fields()) 4798 PopulateKeysForFields(Field, IdealInits); 4799 return; 4800 } 4801 } 4802 IdealInits.push_back(Field->getCanonicalDecl()); 4803 } 4804 4805 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4806 return Context.getCanonicalType(BaseType).getTypePtr(); 4807 } 4808 4809 static const void *GetKeyForMember(ASTContext &Context, 4810 CXXCtorInitializer *Member) { 4811 if (!Member->isAnyMemberInitializer()) 4812 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4813 4814 return Member->getAnyMember()->getCanonicalDecl(); 4815 } 4816 4817 static void DiagnoseBaseOrMemInitializerOrder( 4818 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4819 ArrayRef<CXXCtorInitializer *> Inits) { 4820 if (Constructor->getDeclContext()->isDependentContext()) 4821 return; 4822 4823 // Don't check initializers order unless the warning is enabled at the 4824 // location of at least one initializer. 4825 bool ShouldCheckOrder = false; 4826 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4827 CXXCtorInitializer *Init = Inits[InitIndex]; 4828 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4829 Init->getSourceLocation())) { 4830 ShouldCheckOrder = true; 4831 break; 4832 } 4833 } 4834 if (!ShouldCheckOrder) 4835 return; 4836 4837 // Build the list of bases and members in the order that they'll 4838 // actually be initialized. The explicit initializers should be in 4839 // this same order but may be missing things. 4840 SmallVector<const void*, 32> IdealInitKeys; 4841 4842 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4843 4844 // 1. Virtual bases. 4845 for (const auto &VBase : ClassDecl->vbases()) 4846 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4847 4848 // 2. Non-virtual bases. 4849 for (const auto &Base : ClassDecl->bases()) { 4850 if (Base.isVirtual()) 4851 continue; 4852 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4853 } 4854 4855 // 3. Direct fields. 4856 for (auto *Field : ClassDecl->fields()) { 4857 if (Field->isUnnamedBitfield()) 4858 continue; 4859 4860 PopulateKeysForFields(Field, IdealInitKeys); 4861 } 4862 4863 unsigned NumIdealInits = IdealInitKeys.size(); 4864 unsigned IdealIndex = 0; 4865 4866 CXXCtorInitializer *PrevInit = nullptr; 4867 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4868 CXXCtorInitializer *Init = Inits[InitIndex]; 4869 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4870 4871 // Scan forward to try to find this initializer in the idealized 4872 // initializers list. 4873 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4874 if (InitKey == IdealInitKeys[IdealIndex]) 4875 break; 4876 4877 // If we didn't find this initializer, it must be because we 4878 // scanned past it on a previous iteration. That can only 4879 // happen if we're out of order; emit a warning. 4880 if (IdealIndex == NumIdealInits && PrevInit) { 4881 Sema::SemaDiagnosticBuilder D = 4882 SemaRef.Diag(PrevInit->getSourceLocation(), 4883 diag::warn_initializer_out_of_order); 4884 4885 if (PrevInit->isAnyMemberInitializer()) 4886 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4887 else 4888 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4889 4890 if (Init->isAnyMemberInitializer()) 4891 D << 0 << Init->getAnyMember()->getDeclName(); 4892 else 4893 D << 1 << Init->getTypeSourceInfo()->getType(); 4894 4895 // Move back to the initializer's location in the ideal list. 4896 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4897 if (InitKey == IdealInitKeys[IdealIndex]) 4898 break; 4899 4900 assert(IdealIndex < NumIdealInits && 4901 "initializer not found in initializer list"); 4902 } 4903 4904 PrevInit = Init; 4905 } 4906 } 4907 4908 namespace { 4909 bool CheckRedundantInit(Sema &S, 4910 CXXCtorInitializer *Init, 4911 CXXCtorInitializer *&PrevInit) { 4912 if (!PrevInit) { 4913 PrevInit = Init; 4914 return false; 4915 } 4916 4917 if (FieldDecl *Field = Init->getAnyMember()) 4918 S.Diag(Init->getSourceLocation(), 4919 diag::err_multiple_mem_initialization) 4920 << Field->getDeclName() 4921 << Init->getSourceRange(); 4922 else { 4923 const Type *BaseClass = Init->getBaseClass(); 4924 assert(BaseClass && "neither field nor base"); 4925 S.Diag(Init->getSourceLocation(), 4926 diag::err_multiple_base_initialization) 4927 << QualType(BaseClass, 0) 4928 << Init->getSourceRange(); 4929 } 4930 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4931 << 0 << PrevInit->getSourceRange(); 4932 4933 return true; 4934 } 4935 4936 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4937 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4938 4939 bool CheckRedundantUnionInit(Sema &S, 4940 CXXCtorInitializer *Init, 4941 RedundantUnionMap &Unions) { 4942 FieldDecl *Field = Init->getAnyMember(); 4943 RecordDecl *Parent = Field->getParent(); 4944 NamedDecl *Child = Field; 4945 4946 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4947 if (Parent->isUnion()) { 4948 UnionEntry &En = Unions[Parent]; 4949 if (En.first && En.first != Child) { 4950 S.Diag(Init->getSourceLocation(), 4951 diag::err_multiple_mem_union_initialization) 4952 << Field->getDeclName() 4953 << Init->getSourceRange(); 4954 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4955 << 0 << En.second->getSourceRange(); 4956 return true; 4957 } 4958 if (!En.first) { 4959 En.first = Child; 4960 En.second = Init; 4961 } 4962 if (!Parent->isAnonymousStructOrUnion()) 4963 return false; 4964 } 4965 4966 Child = Parent; 4967 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4968 } 4969 4970 return false; 4971 } 4972 } 4973 4974 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4975 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4976 SourceLocation ColonLoc, 4977 ArrayRef<CXXCtorInitializer*> MemInits, 4978 bool AnyErrors) { 4979 if (!ConstructorDecl) 4980 return; 4981 4982 AdjustDeclIfTemplate(ConstructorDecl); 4983 4984 CXXConstructorDecl *Constructor 4985 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4986 4987 if (!Constructor) { 4988 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4989 return; 4990 } 4991 4992 // Mapping for the duplicate initializers check. 4993 // For member initializers, this is keyed with a FieldDecl*. 4994 // For base initializers, this is keyed with a Type*. 4995 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4996 4997 // Mapping for the inconsistent anonymous-union initializers check. 4998 RedundantUnionMap MemberUnions; 4999 5000 bool HadError = false; 5001 for (unsigned i = 0; i < MemInits.size(); i++) { 5002 CXXCtorInitializer *Init = MemInits[i]; 5003 5004 // Set the source order index. 5005 Init->setSourceOrder(i); 5006 5007 if (Init->isAnyMemberInitializer()) { 5008 const void *Key = GetKeyForMember(Context, Init); 5009 if (CheckRedundantInit(*this, Init, Members[Key]) || 5010 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5011 HadError = true; 5012 } else if (Init->isBaseInitializer()) { 5013 const void *Key = GetKeyForMember(Context, Init); 5014 if (CheckRedundantInit(*this, Init, Members[Key])) 5015 HadError = true; 5016 } else { 5017 assert(Init->isDelegatingInitializer()); 5018 // This must be the only initializer 5019 if (MemInits.size() != 1) { 5020 Diag(Init->getSourceLocation(), 5021 diag::err_delegating_initializer_alone) 5022 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5023 // We will treat this as being the only initializer. 5024 } 5025 SetDelegatingInitializer(Constructor, MemInits[i]); 5026 // Return immediately as the initializer is set. 5027 return; 5028 } 5029 } 5030 5031 if (HadError) 5032 return; 5033 5034 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5035 5036 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5037 5038 DiagnoseUninitializedFields(*this, Constructor); 5039 } 5040 5041 void 5042 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5043 CXXRecordDecl *ClassDecl) { 5044 // Ignore dependent contexts. Also ignore unions, since their members never 5045 // have destructors implicitly called. 5046 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5047 return; 5048 5049 // FIXME: all the access-control diagnostics are positioned on the 5050 // field/base declaration. That's probably good; that said, the 5051 // user might reasonably want to know why the destructor is being 5052 // emitted, and we currently don't say. 5053 5054 // Non-static data members. 5055 for (auto *Field : ClassDecl->fields()) { 5056 if (Field->isInvalidDecl()) 5057 continue; 5058 5059 // Don't destroy incomplete or zero-length arrays. 5060 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5061 continue; 5062 5063 QualType FieldType = Context.getBaseElementType(Field->getType()); 5064 5065 const RecordType* RT = FieldType->getAs<RecordType>(); 5066 if (!RT) 5067 continue; 5068 5069 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5070 if (FieldClassDecl->isInvalidDecl()) 5071 continue; 5072 if (FieldClassDecl->hasIrrelevantDestructor()) 5073 continue; 5074 // The destructor for an implicit anonymous union member is never invoked. 5075 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5076 continue; 5077 5078 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5079 assert(Dtor && "No dtor found for FieldClassDecl!"); 5080 CheckDestructorAccess(Field->getLocation(), Dtor, 5081 PDiag(diag::err_access_dtor_field) 5082 << Field->getDeclName() 5083 << FieldType); 5084 5085 MarkFunctionReferenced(Location, Dtor); 5086 DiagnoseUseOfDecl(Dtor, Location); 5087 } 5088 5089 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5090 5091 // Bases. 5092 for (const auto &Base : ClassDecl->bases()) { 5093 // Bases are always records in a well-formed non-dependent class. 5094 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5095 5096 // Remember direct virtual bases. 5097 if (Base.isVirtual()) 5098 DirectVirtualBases.insert(RT); 5099 5100 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5101 // If our base class is invalid, we probably can't get its dtor anyway. 5102 if (BaseClassDecl->isInvalidDecl()) 5103 continue; 5104 if (BaseClassDecl->hasIrrelevantDestructor()) 5105 continue; 5106 5107 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5108 assert(Dtor && "No dtor found for BaseClassDecl!"); 5109 5110 // FIXME: caret should be on the start of the class name 5111 CheckDestructorAccess(Base.getLocStart(), Dtor, 5112 PDiag(diag::err_access_dtor_base) 5113 << Base.getType() 5114 << Base.getSourceRange(), 5115 Context.getTypeDeclType(ClassDecl)); 5116 5117 MarkFunctionReferenced(Location, Dtor); 5118 DiagnoseUseOfDecl(Dtor, Location); 5119 } 5120 5121 // Virtual bases. 5122 for (const auto &VBase : ClassDecl->vbases()) { 5123 // Bases are always records in a well-formed non-dependent class. 5124 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5125 5126 // Ignore direct virtual bases. 5127 if (DirectVirtualBases.count(RT)) 5128 continue; 5129 5130 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5131 // If our base class is invalid, we probably can't get its dtor anyway. 5132 if (BaseClassDecl->isInvalidDecl()) 5133 continue; 5134 if (BaseClassDecl->hasIrrelevantDestructor()) 5135 continue; 5136 5137 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5138 assert(Dtor && "No dtor found for BaseClassDecl!"); 5139 if (CheckDestructorAccess( 5140 ClassDecl->getLocation(), Dtor, 5141 PDiag(diag::err_access_dtor_vbase) 5142 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5143 Context.getTypeDeclType(ClassDecl)) == 5144 AR_accessible) { 5145 CheckDerivedToBaseConversion( 5146 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5147 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5148 SourceRange(), DeclarationName(), nullptr); 5149 } 5150 5151 MarkFunctionReferenced(Location, Dtor); 5152 DiagnoseUseOfDecl(Dtor, Location); 5153 } 5154 } 5155 5156 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5157 if (!CDtorDecl) 5158 return; 5159 5160 if (CXXConstructorDecl *Constructor 5161 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5162 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5163 DiagnoseUninitializedFields(*this, Constructor); 5164 } 5165 } 5166 5167 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5168 if (!getLangOpts().CPlusPlus) 5169 return false; 5170 5171 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5172 if (!RD) 5173 return false; 5174 5175 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5176 // class template specialization here, but doing so breaks a lot of code. 5177 5178 // We can't answer whether something is abstract until it has a 5179 // definition. If it's currently being defined, we'll walk back 5180 // over all the declarations when we have a full definition. 5181 const CXXRecordDecl *Def = RD->getDefinition(); 5182 if (!Def || Def->isBeingDefined()) 5183 return false; 5184 5185 return RD->isAbstract(); 5186 } 5187 5188 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5189 TypeDiagnoser &Diagnoser) { 5190 if (!isAbstractType(Loc, T)) 5191 return false; 5192 5193 T = Context.getBaseElementType(T); 5194 Diagnoser.diagnose(*this, Loc, T); 5195 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5196 return true; 5197 } 5198 5199 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5200 // Check if we've already emitted the list of pure virtual functions 5201 // for this class. 5202 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5203 return; 5204 5205 // If the diagnostic is suppressed, don't emit the notes. We're only 5206 // going to emit them once, so try to attach them to a diagnostic we're 5207 // actually going to show. 5208 if (Diags.isLastDiagnosticIgnored()) 5209 return; 5210 5211 CXXFinalOverriderMap FinalOverriders; 5212 RD->getFinalOverriders(FinalOverriders); 5213 5214 // Keep a set of seen pure methods so we won't diagnose the same method 5215 // more than once. 5216 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5217 5218 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5219 MEnd = FinalOverriders.end(); 5220 M != MEnd; 5221 ++M) { 5222 for (OverridingMethods::iterator SO = M->second.begin(), 5223 SOEnd = M->second.end(); 5224 SO != SOEnd; ++SO) { 5225 // C++ [class.abstract]p4: 5226 // A class is abstract if it contains or inherits at least one 5227 // pure virtual function for which the final overrider is pure 5228 // virtual. 5229 5230 // 5231 if (SO->second.size() != 1) 5232 continue; 5233 5234 if (!SO->second.front().Method->isPure()) 5235 continue; 5236 5237 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5238 continue; 5239 5240 Diag(SO->second.front().Method->getLocation(), 5241 diag::note_pure_virtual_function) 5242 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5243 } 5244 } 5245 5246 if (!PureVirtualClassDiagSet) 5247 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5248 PureVirtualClassDiagSet->insert(RD); 5249 } 5250 5251 namespace { 5252 struct AbstractUsageInfo { 5253 Sema &S; 5254 CXXRecordDecl *Record; 5255 CanQualType AbstractType; 5256 bool Invalid; 5257 5258 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5259 : S(S), Record(Record), 5260 AbstractType(S.Context.getCanonicalType( 5261 S.Context.getTypeDeclType(Record))), 5262 Invalid(false) {} 5263 5264 void DiagnoseAbstractType() { 5265 if (Invalid) return; 5266 S.DiagnoseAbstractType(Record); 5267 Invalid = true; 5268 } 5269 5270 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5271 }; 5272 5273 struct CheckAbstractUsage { 5274 AbstractUsageInfo &Info; 5275 const NamedDecl *Ctx; 5276 5277 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5278 : Info(Info), Ctx(Ctx) {} 5279 5280 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5281 switch (TL.getTypeLocClass()) { 5282 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5283 #define TYPELOC(CLASS, PARENT) \ 5284 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5285 #include "clang/AST/TypeLocNodes.def" 5286 } 5287 } 5288 5289 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5290 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5291 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5292 if (!TL.getParam(I)) 5293 continue; 5294 5295 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5296 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5297 } 5298 } 5299 5300 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5301 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5302 } 5303 5304 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5305 // Visit the type parameters from a permissive context. 5306 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5307 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5308 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5309 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5310 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5311 // TODO: other template argument types? 5312 } 5313 } 5314 5315 // Visit pointee types from a permissive context. 5316 #define CheckPolymorphic(Type) \ 5317 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5318 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5319 } 5320 CheckPolymorphic(PointerTypeLoc) 5321 CheckPolymorphic(ReferenceTypeLoc) 5322 CheckPolymorphic(MemberPointerTypeLoc) 5323 CheckPolymorphic(BlockPointerTypeLoc) 5324 CheckPolymorphic(AtomicTypeLoc) 5325 5326 /// Handle all the types we haven't given a more specific 5327 /// implementation for above. 5328 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5329 // Every other kind of type that we haven't called out already 5330 // that has an inner type is either (1) sugar or (2) contains that 5331 // inner type in some way as a subobject. 5332 if (TypeLoc Next = TL.getNextTypeLoc()) 5333 return Visit(Next, Sel); 5334 5335 // If there's no inner type and we're in a permissive context, 5336 // don't diagnose. 5337 if (Sel == Sema::AbstractNone) return; 5338 5339 // Check whether the type matches the abstract type. 5340 QualType T = TL.getType(); 5341 if (T->isArrayType()) { 5342 Sel = Sema::AbstractArrayType; 5343 T = Info.S.Context.getBaseElementType(T); 5344 } 5345 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5346 if (CT != Info.AbstractType) return; 5347 5348 // It matched; do some magic. 5349 if (Sel == Sema::AbstractArrayType) { 5350 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5351 << T << TL.getSourceRange(); 5352 } else { 5353 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5354 << Sel << T << TL.getSourceRange(); 5355 } 5356 Info.DiagnoseAbstractType(); 5357 } 5358 }; 5359 5360 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5361 Sema::AbstractDiagSelID Sel) { 5362 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5363 } 5364 5365 } 5366 5367 /// Check for invalid uses of an abstract type in a method declaration. 5368 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5369 CXXMethodDecl *MD) { 5370 // No need to do the check on definitions, which require that 5371 // the return/param types be complete. 5372 if (MD->doesThisDeclarationHaveABody()) 5373 return; 5374 5375 // For safety's sake, just ignore it if we don't have type source 5376 // information. This should never happen for non-implicit methods, 5377 // but... 5378 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5379 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5380 } 5381 5382 /// Check for invalid uses of an abstract type within a class definition. 5383 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5384 CXXRecordDecl *RD) { 5385 for (auto *D : RD->decls()) { 5386 if (D->isImplicit()) continue; 5387 5388 // Methods and method templates. 5389 if (isa<CXXMethodDecl>(D)) { 5390 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5391 } else if (isa<FunctionTemplateDecl>(D)) { 5392 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5393 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5394 5395 // Fields and static variables. 5396 } else if (isa<FieldDecl>(D)) { 5397 FieldDecl *FD = cast<FieldDecl>(D); 5398 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5399 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5400 } else if (isa<VarDecl>(D)) { 5401 VarDecl *VD = cast<VarDecl>(D); 5402 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5403 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5404 5405 // Nested classes and class templates. 5406 } else if (isa<CXXRecordDecl>(D)) { 5407 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5408 } else if (isa<ClassTemplateDecl>(D)) { 5409 CheckAbstractClassUsage(Info, 5410 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5411 } 5412 } 5413 } 5414 5415 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 5416 Attr *ClassAttr = getDLLAttr(Class); 5417 if (!ClassAttr) 5418 return; 5419 5420 assert(ClassAttr->getKind() == attr::DLLExport); 5421 5422 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5423 5424 if (TSK == TSK_ExplicitInstantiationDeclaration) 5425 // Don't go any further if this is just an explicit instantiation 5426 // declaration. 5427 return; 5428 5429 for (Decl *Member : Class->decls()) { 5430 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5431 if (!MD) 5432 continue; 5433 5434 if (Member->getAttr<DLLExportAttr>()) { 5435 if (MD->isUserProvided()) { 5436 // Instantiate non-default class member functions ... 5437 5438 // .. except for certain kinds of template specializations. 5439 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5440 continue; 5441 5442 S.MarkFunctionReferenced(Class->getLocation(), MD); 5443 5444 // The function will be passed to the consumer when its definition is 5445 // encountered. 5446 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5447 MD->isCopyAssignmentOperator() || 5448 MD->isMoveAssignmentOperator()) { 5449 // Synthesize and instantiate non-trivial implicit methods, explicitly 5450 // defaulted methods, and the copy and move assignment operators. The 5451 // latter are exported even if they are trivial, because the address of 5452 // an operator can be taken and should compare equal accross libraries. 5453 DiagnosticErrorTrap Trap(S.Diags); 5454 S.MarkFunctionReferenced(Class->getLocation(), MD); 5455 if (Trap.hasErrorOccurred()) { 5456 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5457 << Class->getName() << !S.getLangOpts().CPlusPlus11; 5458 break; 5459 } 5460 5461 // There is no later point when we will see the definition of this 5462 // function, so pass it to the consumer now. 5463 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5464 } 5465 } 5466 } 5467 } 5468 5469 /// \brief Check class-level dllimport/dllexport attribute. 5470 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5471 Attr *ClassAttr = getDLLAttr(Class); 5472 5473 // MSVC inherits DLL attributes to partial class template specializations. 5474 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5475 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5476 if (Attr *TemplateAttr = 5477 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5478 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5479 A->setInherited(true); 5480 ClassAttr = A; 5481 } 5482 } 5483 } 5484 5485 if (!ClassAttr) 5486 return; 5487 5488 if (!Class->isExternallyVisible()) { 5489 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5490 << Class << ClassAttr; 5491 return; 5492 } 5493 5494 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5495 !ClassAttr->isInherited()) { 5496 // Diagnose dll attributes on members of class with dll attribute. 5497 for (Decl *Member : Class->decls()) { 5498 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5499 continue; 5500 InheritableAttr *MemberAttr = getDLLAttr(Member); 5501 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5502 continue; 5503 5504 Diag(MemberAttr->getLocation(), 5505 diag::err_attribute_dll_member_of_dll_class) 5506 << MemberAttr << ClassAttr; 5507 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5508 Member->setInvalidDecl(); 5509 } 5510 } 5511 5512 if (Class->getDescribedClassTemplate()) 5513 // Don't inherit dll attribute until the template is instantiated. 5514 return; 5515 5516 // The class is either imported or exported. 5517 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5518 5519 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5520 5521 // Ignore explicit dllexport on explicit class template instantiation declarations. 5522 if (ClassExported && !ClassAttr->isInherited() && 5523 TSK == TSK_ExplicitInstantiationDeclaration) { 5524 Class->dropAttr<DLLExportAttr>(); 5525 return; 5526 } 5527 5528 // Force declaration of implicit members so they can inherit the attribute. 5529 ForceDeclarationOfImplicitMembers(Class); 5530 5531 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5532 // seem to be true in practice? 5533 5534 for (Decl *Member : Class->decls()) { 5535 VarDecl *VD = dyn_cast<VarDecl>(Member); 5536 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5537 5538 // Only methods and static fields inherit the attributes. 5539 if (!VD && !MD) 5540 continue; 5541 5542 if (MD) { 5543 // Don't process deleted methods. 5544 if (MD->isDeleted()) 5545 continue; 5546 5547 if (MD->isInlined()) { 5548 // MinGW does not import or export inline methods. 5549 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5550 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5551 continue; 5552 5553 // MSVC versions before 2015 don't export the move assignment operators 5554 // and move constructor, so don't attempt to import/export them if 5555 // we have a definition. 5556 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5557 if ((MD->isMoveAssignmentOperator() || 5558 (Ctor && Ctor->isMoveConstructor())) && 5559 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5560 continue; 5561 5562 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5563 // operator is exported anyway. 5564 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5565 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5566 continue; 5567 } 5568 } 5569 5570 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5571 continue; 5572 5573 if (!getDLLAttr(Member)) { 5574 auto *NewAttr = 5575 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5576 NewAttr->setInherited(true); 5577 Member->addAttr(NewAttr); 5578 } 5579 } 5580 5581 if (ClassExported) 5582 DelayedDllExportClasses.push_back(Class); 5583 } 5584 5585 /// \brief Perform propagation of DLL attributes from a derived class to a 5586 /// templated base class for MS compatibility. 5587 void Sema::propagateDLLAttrToBaseClassTemplate( 5588 CXXRecordDecl *Class, Attr *ClassAttr, 5589 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5590 if (getDLLAttr( 5591 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5592 // If the base class template has a DLL attribute, don't try to change it. 5593 return; 5594 } 5595 5596 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5597 if (!getDLLAttr(BaseTemplateSpec) && 5598 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5599 TSK == TSK_ImplicitInstantiation)) { 5600 // The template hasn't been instantiated yet (or it has, but only as an 5601 // explicit instantiation declaration or implicit instantiation, which means 5602 // we haven't codegenned any members yet), so propagate the attribute. 5603 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5604 NewAttr->setInherited(true); 5605 BaseTemplateSpec->addAttr(NewAttr); 5606 5607 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5608 // needs to be run again to work see the new attribute. Otherwise this will 5609 // get run whenever the template is instantiated. 5610 if (TSK != TSK_Undeclared) 5611 checkClassLevelDLLAttribute(BaseTemplateSpec); 5612 5613 return; 5614 } 5615 5616 if (getDLLAttr(BaseTemplateSpec)) { 5617 // The template has already been specialized or instantiated with an 5618 // attribute, explicitly or through propagation. We should not try to change 5619 // it. 5620 return; 5621 } 5622 5623 // The template was previously instantiated or explicitly specialized without 5624 // a dll attribute, It's too late for us to add an attribute, so warn that 5625 // this is unsupported. 5626 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5627 << BaseTemplateSpec->isExplicitSpecialization(); 5628 Diag(ClassAttr->getLocation(), diag::note_attribute); 5629 if (BaseTemplateSpec->isExplicitSpecialization()) { 5630 Diag(BaseTemplateSpec->getLocation(), 5631 diag::note_template_class_explicit_specialization_was_here) 5632 << BaseTemplateSpec; 5633 } else { 5634 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5635 diag::note_template_class_instantiation_was_here) 5636 << BaseTemplateSpec; 5637 } 5638 } 5639 5640 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5641 SourceLocation DefaultLoc) { 5642 switch (S.getSpecialMember(MD)) { 5643 case Sema::CXXDefaultConstructor: 5644 S.DefineImplicitDefaultConstructor(DefaultLoc, 5645 cast<CXXConstructorDecl>(MD)); 5646 break; 5647 case Sema::CXXCopyConstructor: 5648 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5649 break; 5650 case Sema::CXXCopyAssignment: 5651 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5652 break; 5653 case Sema::CXXDestructor: 5654 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5655 break; 5656 case Sema::CXXMoveConstructor: 5657 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5658 break; 5659 case Sema::CXXMoveAssignment: 5660 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5661 break; 5662 case Sema::CXXInvalid: 5663 llvm_unreachable("Invalid special member."); 5664 } 5665 } 5666 5667 /// \brief Perform semantic checks on a class definition that has been 5668 /// completing, introducing implicitly-declared members, checking for 5669 /// abstract types, etc. 5670 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5671 if (!Record) 5672 return; 5673 5674 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5675 AbstractUsageInfo Info(*this, Record); 5676 CheckAbstractClassUsage(Info, Record); 5677 } 5678 5679 // If this is not an aggregate type and has no user-declared constructor, 5680 // complain about any non-static data members of reference or const scalar 5681 // type, since they will never get initializers. 5682 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5683 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5684 !Record->isLambda()) { 5685 bool Complained = false; 5686 for (const auto *F : Record->fields()) { 5687 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5688 continue; 5689 5690 if (F->getType()->isReferenceType() || 5691 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5692 if (!Complained) { 5693 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5694 << Record->getTagKind() << Record; 5695 Complained = true; 5696 } 5697 5698 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5699 << F->getType()->isReferenceType() 5700 << F->getDeclName(); 5701 } 5702 } 5703 } 5704 5705 if (Record->getIdentifier()) { 5706 // C++ [class.mem]p13: 5707 // If T is the name of a class, then each of the following shall have a 5708 // name different from T: 5709 // - every member of every anonymous union that is a member of class T. 5710 // 5711 // C++ [class.mem]p14: 5712 // In addition, if class T has a user-declared constructor (12.1), every 5713 // non-static data member of class T shall have a name different from T. 5714 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5715 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5716 ++I) { 5717 NamedDecl *D = *I; 5718 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5719 isa<IndirectFieldDecl>(D)) { 5720 Diag(D->getLocation(), diag::err_member_name_of_class) 5721 << D->getDeclName(); 5722 break; 5723 } 5724 } 5725 } 5726 5727 // Warn if the class has virtual methods but non-virtual public destructor. 5728 if (Record->isPolymorphic() && !Record->isDependentType()) { 5729 CXXDestructorDecl *dtor = Record->getDestructor(); 5730 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5731 !Record->hasAttr<FinalAttr>()) 5732 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5733 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5734 } 5735 5736 if (Record->isAbstract()) { 5737 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5738 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5739 << FA->isSpelledAsSealed(); 5740 DiagnoseAbstractType(Record); 5741 } 5742 } 5743 5744 bool HasMethodWithOverrideControl = false, 5745 HasOverridingMethodWithoutOverrideControl = false; 5746 if (!Record->isDependentType()) { 5747 for (auto *M : Record->methods()) { 5748 // See if a method overloads virtual methods in a base 5749 // class without overriding any. 5750 if (!M->isStatic()) 5751 DiagnoseHiddenVirtualMethods(M); 5752 if (M->hasAttr<OverrideAttr>()) 5753 HasMethodWithOverrideControl = true; 5754 else if (M->size_overridden_methods() > 0) 5755 HasOverridingMethodWithoutOverrideControl = true; 5756 // Check whether the explicitly-defaulted special members are valid. 5757 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5758 CheckExplicitlyDefaultedSpecialMember(M); 5759 5760 // For an explicitly defaulted or deleted special member, we defer 5761 // determining triviality until the class is complete. That time is now! 5762 CXXSpecialMember CSM = getSpecialMember(M); 5763 if (!M->isImplicit() && !M->isUserProvided()) { 5764 if (CSM != CXXInvalid) { 5765 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5766 5767 // Inform the class that we've finished declaring this member. 5768 Record->finishedDefaultedOrDeletedMember(M); 5769 } 5770 } 5771 5772 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5773 M->hasAttr<DLLExportAttr>()) { 5774 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5775 M->isTrivial() && 5776 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5777 CSM == CXXDestructor)) 5778 M->dropAttr<DLLExportAttr>(); 5779 5780 if (M->hasAttr<DLLExportAttr>()) { 5781 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5782 ActOnFinishInlineFunctionDef(M); 5783 } 5784 } 5785 } 5786 } 5787 5788 if (HasMethodWithOverrideControl && 5789 HasOverridingMethodWithoutOverrideControl) { 5790 // At least one method has the 'override' control declared. 5791 // Diagnose all other overridden methods which do not have 'override' specified on them. 5792 for (auto *M : Record->methods()) 5793 DiagnoseAbsenceOfOverrideControl(M); 5794 } 5795 5796 // ms_struct is a request to use the same ABI rules as MSVC. Check 5797 // whether this class uses any C++ features that are implemented 5798 // completely differently in MSVC, and if so, emit a diagnostic. 5799 // That diagnostic defaults to an error, but we allow projects to 5800 // map it down to a warning (or ignore it). It's a fairly common 5801 // practice among users of the ms_struct pragma to mass-annotate 5802 // headers, sweeping up a bunch of types that the project doesn't 5803 // really rely on MSVC-compatible layout for. We must therefore 5804 // support "ms_struct except for C++ stuff" as a secondary ABI. 5805 if (Record->isMsStruct(Context) && 5806 (Record->isPolymorphic() || Record->getNumBases())) { 5807 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5808 } 5809 5810 checkClassLevelDLLAttribute(Record); 5811 } 5812 5813 /// Look up the special member function that would be called by a special 5814 /// member function for a subobject of class type. 5815 /// 5816 /// \param Class The class type of the subobject. 5817 /// \param CSM The kind of special member function. 5818 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5819 /// \param ConstRHS True if this is a copy operation with a const object 5820 /// on its RHS, that is, if the argument to the outer special member 5821 /// function is 'const' and this is not a field marked 'mutable'. 5822 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 5823 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5824 unsigned FieldQuals, bool ConstRHS) { 5825 unsigned LHSQuals = 0; 5826 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5827 LHSQuals = FieldQuals; 5828 5829 unsigned RHSQuals = FieldQuals; 5830 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5831 RHSQuals = 0; 5832 else if (ConstRHS) 5833 RHSQuals |= Qualifiers::Const; 5834 5835 return S.LookupSpecialMember(Class, CSM, 5836 RHSQuals & Qualifiers::Const, 5837 RHSQuals & Qualifiers::Volatile, 5838 false, 5839 LHSQuals & Qualifiers::Const, 5840 LHSQuals & Qualifiers::Volatile); 5841 } 5842 5843 class Sema::InheritedConstructorInfo { 5844 Sema &S; 5845 SourceLocation UseLoc; 5846 5847 /// A mapping from the base classes through which the constructor was 5848 /// inherited to the using shadow declaration in that base class (or a null 5849 /// pointer if the constructor was declared in that base class). 5850 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 5851 InheritedFromBases; 5852 5853 public: 5854 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 5855 ConstructorUsingShadowDecl *Shadow) 5856 : S(S), UseLoc(UseLoc) { 5857 bool DiagnosedMultipleConstructedBases = false; 5858 CXXRecordDecl *ConstructedBase = nullptr; 5859 UsingDecl *ConstructedBaseUsing = nullptr; 5860 5861 // Find the set of such base class subobjects and check that there's a 5862 // unique constructed subobject. 5863 for (auto *D : Shadow->redecls()) { 5864 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 5865 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 5866 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 5867 5868 InheritedFromBases.insert( 5869 std::make_pair(DNominatedBase->getCanonicalDecl(), 5870 DShadow->getNominatedBaseClassShadowDecl())); 5871 if (DShadow->constructsVirtualBase()) 5872 InheritedFromBases.insert( 5873 std::make_pair(DConstructedBase->getCanonicalDecl(), 5874 DShadow->getConstructedBaseClassShadowDecl())); 5875 else 5876 assert(DNominatedBase == DConstructedBase); 5877 5878 // [class.inhctor.init]p2: 5879 // If the constructor was inherited from multiple base class subobjects 5880 // of type B, the program is ill-formed. 5881 if (!ConstructedBase) { 5882 ConstructedBase = DConstructedBase; 5883 ConstructedBaseUsing = D->getUsingDecl(); 5884 } else if (ConstructedBase != DConstructedBase && 5885 !Shadow->isInvalidDecl()) { 5886 if (!DiagnosedMultipleConstructedBases) { 5887 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 5888 << Shadow->getTargetDecl(); 5889 S.Diag(ConstructedBaseUsing->getLocation(), 5890 diag::note_ambiguous_inherited_constructor_using) 5891 << ConstructedBase; 5892 DiagnosedMultipleConstructedBases = true; 5893 } 5894 S.Diag(D->getUsingDecl()->getLocation(), 5895 diag::note_ambiguous_inherited_constructor_using) 5896 << DConstructedBase; 5897 } 5898 } 5899 5900 if (DiagnosedMultipleConstructedBases) 5901 Shadow->setInvalidDecl(); 5902 } 5903 5904 /// Find the constructor to use for inherited construction of a base class, 5905 /// and whether that base class constructor inherits the constructor from a 5906 /// virtual base class (in which case it won't actually invoke it). 5907 std::pair<CXXConstructorDecl *, bool> 5908 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 5909 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 5910 if (It == InheritedFromBases.end()) 5911 return std::make_pair(nullptr, false); 5912 5913 // This is an intermediary class. 5914 if (It->second) 5915 return std::make_pair( 5916 S.findInheritingConstructor(UseLoc, Ctor, It->second), 5917 It->second->constructsVirtualBase()); 5918 5919 // This is the base class from which the constructor was inherited. 5920 return std::make_pair(Ctor, false); 5921 } 5922 }; 5923 5924 /// Is the special member function which would be selected to perform the 5925 /// specified operation on the specified class type a constexpr constructor? 5926 static bool 5927 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5928 Sema::CXXSpecialMember CSM, unsigned Quals, 5929 bool ConstRHS, 5930 CXXConstructorDecl *InheritedCtor = nullptr, 5931 Sema::InheritedConstructorInfo *Inherited = nullptr) { 5932 // If we're inheriting a constructor, see if we need to call it for this base 5933 // class. 5934 if (InheritedCtor) { 5935 assert(CSM == Sema::CXXDefaultConstructor); 5936 auto BaseCtor = 5937 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 5938 if (BaseCtor) 5939 return BaseCtor->isConstexpr(); 5940 } 5941 5942 if (CSM == Sema::CXXDefaultConstructor) 5943 return ClassDecl->hasConstexprDefaultConstructor(); 5944 5945 Sema::SpecialMemberOverloadResult *SMOR = 5946 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5947 if (!SMOR || !SMOR->getMethod()) 5948 // A constructor we wouldn't select can't be "involved in initializing" 5949 // anything. 5950 return true; 5951 return SMOR->getMethod()->isConstexpr(); 5952 } 5953 5954 /// Determine whether the specified special member function would be constexpr 5955 /// if it were implicitly defined. 5956 static bool defaultedSpecialMemberIsConstexpr( 5957 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 5958 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 5959 Sema::InheritedConstructorInfo *Inherited = nullptr) { 5960 if (!S.getLangOpts().CPlusPlus11) 5961 return false; 5962 5963 // C++11 [dcl.constexpr]p4: 5964 // In the definition of a constexpr constructor [...] 5965 bool Ctor = true; 5966 switch (CSM) { 5967 case Sema::CXXDefaultConstructor: 5968 if (Inherited) 5969 break; 5970 // Since default constructor lookup is essentially trivial (and cannot 5971 // involve, for instance, template instantiation), we compute whether a 5972 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5973 // 5974 // This is important for performance; we need to know whether the default 5975 // constructor is constexpr to determine whether the type is a literal type. 5976 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5977 5978 case Sema::CXXCopyConstructor: 5979 case Sema::CXXMoveConstructor: 5980 // For copy or move constructors, we need to perform overload resolution. 5981 break; 5982 5983 case Sema::CXXCopyAssignment: 5984 case Sema::CXXMoveAssignment: 5985 if (!S.getLangOpts().CPlusPlus14) 5986 return false; 5987 // In C++1y, we need to perform overload resolution. 5988 Ctor = false; 5989 break; 5990 5991 case Sema::CXXDestructor: 5992 case Sema::CXXInvalid: 5993 return false; 5994 } 5995 5996 // -- if the class is a non-empty union, or for each non-empty anonymous 5997 // union member of a non-union class, exactly one non-static data member 5998 // shall be initialized; [DR1359] 5999 // 6000 // If we squint, this is guaranteed, since exactly one non-static data member 6001 // will be initialized (if the constructor isn't deleted), we just don't know 6002 // which one. 6003 if (Ctor && ClassDecl->isUnion()) 6004 return CSM == Sema::CXXDefaultConstructor 6005 ? ClassDecl->hasInClassInitializer() || 6006 !ClassDecl->hasVariantMembers() 6007 : true; 6008 6009 // -- the class shall not have any virtual base classes; 6010 if (Ctor && ClassDecl->getNumVBases()) 6011 return false; 6012 6013 // C++1y [class.copy]p26: 6014 // -- [the class] is a literal type, and 6015 if (!Ctor && !ClassDecl->isLiteral()) 6016 return false; 6017 6018 // -- every constructor involved in initializing [...] base class 6019 // sub-objects shall be a constexpr constructor; 6020 // -- the assignment operator selected to copy/move each direct base 6021 // class is a constexpr function, and 6022 for (const auto &B : ClassDecl->bases()) { 6023 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6024 if (!BaseType) continue; 6025 6026 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6027 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6028 InheritedCtor, Inherited)) 6029 return false; 6030 } 6031 6032 // -- every constructor involved in initializing non-static data members 6033 // [...] shall be a constexpr constructor; 6034 // -- every non-static data member and base class sub-object shall be 6035 // initialized 6036 // -- for each non-static data member of X that is of class type (or array 6037 // thereof), the assignment operator selected to copy/move that member is 6038 // a constexpr function 6039 for (const auto *F : ClassDecl->fields()) { 6040 if (F->isInvalidDecl()) 6041 continue; 6042 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6043 continue; 6044 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6045 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6046 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6047 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6048 BaseType.getCVRQualifiers(), 6049 ConstArg && !F->isMutable())) 6050 return false; 6051 } else if (CSM == Sema::CXXDefaultConstructor) { 6052 return false; 6053 } 6054 } 6055 6056 // All OK, it's constexpr! 6057 return true; 6058 } 6059 6060 static Sema::ImplicitExceptionSpecification 6061 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6062 switch (S.getSpecialMember(MD)) { 6063 case Sema::CXXDefaultConstructor: 6064 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 6065 case Sema::CXXCopyConstructor: 6066 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 6067 case Sema::CXXCopyAssignment: 6068 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 6069 case Sema::CXXMoveConstructor: 6070 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 6071 case Sema::CXXMoveAssignment: 6072 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 6073 case Sema::CXXDestructor: 6074 return S.ComputeDefaultedDtorExceptionSpec(MD); 6075 case Sema::CXXInvalid: 6076 break; 6077 } 6078 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 6079 "only special members have implicit exception specs"); 6080 return S.ComputeInheritingCtorExceptionSpec(Loc, 6081 cast<CXXConstructorDecl>(MD)); 6082 } 6083 6084 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6085 CXXMethodDecl *MD) { 6086 FunctionProtoType::ExtProtoInfo EPI; 6087 6088 // Build an exception specification pointing back at this member. 6089 EPI.ExceptionSpec.Type = EST_Unevaluated; 6090 EPI.ExceptionSpec.SourceDecl = MD; 6091 6092 // Set the calling convention to the default for C++ instance methods. 6093 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6094 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6095 /*IsCXXMethod=*/true)); 6096 return EPI; 6097 } 6098 6099 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6100 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6101 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6102 return; 6103 6104 // Evaluate the exception specification. 6105 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 6106 6107 // Update the type of the special member to use it. 6108 UpdateExceptionSpec(MD, ESI); 6109 6110 // A user-provided destructor can be defined outside the class. When that 6111 // happens, be sure to update the exception specification on both 6112 // declarations. 6113 const FunctionProtoType *CanonicalFPT = 6114 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6115 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6116 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6117 } 6118 6119 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6120 CXXRecordDecl *RD = MD->getParent(); 6121 CXXSpecialMember CSM = getSpecialMember(MD); 6122 6123 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6124 "not an explicitly-defaulted special member"); 6125 6126 // Whether this was the first-declared instance of the constructor. 6127 // This affects whether we implicitly add an exception spec and constexpr. 6128 bool First = MD == MD->getCanonicalDecl(); 6129 6130 bool HadError = false; 6131 6132 // C++11 [dcl.fct.def.default]p1: 6133 // A function that is explicitly defaulted shall 6134 // -- be a special member function (checked elsewhere), 6135 // -- have the same type (except for ref-qualifiers, and except that a 6136 // copy operation can take a non-const reference) as an implicit 6137 // declaration, and 6138 // -- not have default arguments. 6139 unsigned ExpectedParams = 1; 6140 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6141 ExpectedParams = 0; 6142 if (MD->getNumParams() != ExpectedParams) { 6143 // This also checks for default arguments: a copy or move constructor with a 6144 // default argument is classified as a default constructor, and assignment 6145 // operations and destructors can't have default arguments. 6146 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6147 << CSM << MD->getSourceRange(); 6148 HadError = true; 6149 } else if (MD->isVariadic()) { 6150 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6151 << CSM << MD->getSourceRange(); 6152 HadError = true; 6153 } 6154 6155 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6156 6157 bool CanHaveConstParam = false; 6158 if (CSM == CXXCopyConstructor) 6159 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6160 else if (CSM == CXXCopyAssignment) 6161 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6162 6163 QualType ReturnType = Context.VoidTy; 6164 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6165 // Check for return type matching. 6166 ReturnType = Type->getReturnType(); 6167 QualType ExpectedReturnType = 6168 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6169 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6170 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6171 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6172 HadError = true; 6173 } 6174 6175 // A defaulted special member cannot have cv-qualifiers. 6176 if (Type->getTypeQuals()) { 6177 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6178 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6179 HadError = true; 6180 } 6181 } 6182 6183 // Check for parameter type matching. 6184 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6185 bool HasConstParam = false; 6186 if (ExpectedParams && ArgType->isReferenceType()) { 6187 // Argument must be reference to possibly-const T. 6188 QualType ReferentType = ArgType->getPointeeType(); 6189 HasConstParam = ReferentType.isConstQualified(); 6190 6191 if (ReferentType.isVolatileQualified()) { 6192 Diag(MD->getLocation(), 6193 diag::err_defaulted_special_member_volatile_param) << CSM; 6194 HadError = true; 6195 } 6196 6197 if (HasConstParam && !CanHaveConstParam) { 6198 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6199 Diag(MD->getLocation(), 6200 diag::err_defaulted_special_member_copy_const_param) 6201 << (CSM == CXXCopyAssignment); 6202 // FIXME: Explain why this special member can't be const. 6203 } else { 6204 Diag(MD->getLocation(), 6205 diag::err_defaulted_special_member_move_const_param) 6206 << (CSM == CXXMoveAssignment); 6207 } 6208 HadError = true; 6209 } 6210 } else if (ExpectedParams) { 6211 // A copy assignment operator can take its argument by value, but a 6212 // defaulted one cannot. 6213 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6214 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6215 HadError = true; 6216 } 6217 6218 // C++11 [dcl.fct.def.default]p2: 6219 // An explicitly-defaulted function may be declared constexpr only if it 6220 // would have been implicitly declared as constexpr, 6221 // Do not apply this rule to members of class templates, since core issue 1358 6222 // makes such functions always instantiate to constexpr functions. For 6223 // functions which cannot be constexpr (for non-constructors in C++11 and for 6224 // destructors in C++1y), this is checked elsewhere. 6225 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6226 HasConstParam); 6227 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6228 : isa<CXXConstructorDecl>(MD)) && 6229 MD->isConstexpr() && !Constexpr && 6230 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6231 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6232 // FIXME: Explain why the special member can't be constexpr. 6233 HadError = true; 6234 } 6235 6236 // and may have an explicit exception-specification only if it is compatible 6237 // with the exception-specification on the implicit declaration. 6238 if (Type->hasExceptionSpec()) { 6239 // Delay the check if this is the first declaration of the special member, 6240 // since we may not have parsed some necessary in-class initializers yet. 6241 if (First) { 6242 // If the exception specification needs to be instantiated, do so now, 6243 // before we clobber it with an EST_Unevaluated specification below. 6244 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6245 InstantiateExceptionSpec(MD->getLocStart(), MD); 6246 Type = MD->getType()->getAs<FunctionProtoType>(); 6247 } 6248 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6249 } else 6250 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6251 } 6252 6253 // If a function is explicitly defaulted on its first declaration, 6254 if (First) { 6255 // -- it is implicitly considered to be constexpr if the implicit 6256 // definition would be, 6257 MD->setConstexpr(Constexpr); 6258 6259 // -- it is implicitly considered to have the same exception-specification 6260 // as if it had been implicitly declared, 6261 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6262 EPI.ExceptionSpec.Type = EST_Unevaluated; 6263 EPI.ExceptionSpec.SourceDecl = MD; 6264 MD->setType(Context.getFunctionType(ReturnType, 6265 llvm::makeArrayRef(&ArgType, 6266 ExpectedParams), 6267 EPI)); 6268 } 6269 6270 if (ShouldDeleteSpecialMember(MD, CSM)) { 6271 if (First) { 6272 SetDeclDeleted(MD, MD->getLocation()); 6273 } else { 6274 // C++11 [dcl.fct.def.default]p4: 6275 // [For a] user-provided explicitly-defaulted function [...] if such a 6276 // function is implicitly defined as deleted, the program is ill-formed. 6277 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6278 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6279 HadError = true; 6280 } 6281 } 6282 6283 if (HadError) 6284 MD->setInvalidDecl(); 6285 } 6286 6287 /// Check whether the exception specification provided for an 6288 /// explicitly-defaulted special member matches the exception specification 6289 /// that would have been generated for an implicit special member, per 6290 /// C++11 [dcl.fct.def.default]p2. 6291 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6292 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6293 // If the exception specification was explicitly specified but hadn't been 6294 // parsed when the method was defaulted, grab it now. 6295 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6296 SpecifiedType = 6297 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6298 6299 // Compute the implicit exception specification. 6300 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6301 /*IsCXXMethod=*/true); 6302 FunctionProtoType::ExtProtoInfo EPI(CC); 6303 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 6304 .getExceptionSpec(); 6305 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6306 Context.getFunctionType(Context.VoidTy, None, EPI)); 6307 6308 // Ensure that it matches. 6309 CheckEquivalentExceptionSpec( 6310 PDiag(diag::err_incorrect_defaulted_exception_spec) 6311 << getSpecialMember(MD), PDiag(), 6312 ImplicitType, SourceLocation(), 6313 SpecifiedType, MD->getLocation()); 6314 } 6315 6316 void Sema::CheckDelayedMemberExceptionSpecs() { 6317 decltype(DelayedExceptionSpecChecks) Checks; 6318 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6319 6320 std::swap(Checks, DelayedExceptionSpecChecks); 6321 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6322 6323 // Perform any deferred checking of exception specifications for virtual 6324 // destructors. 6325 for (auto &Check : Checks) 6326 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6327 6328 // Check that any explicitly-defaulted methods have exception specifications 6329 // compatible with their implicit exception specifications. 6330 for (auto &Spec : Specs) 6331 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6332 } 6333 6334 namespace { 6335 struct SpecialMemberDeletionInfo { 6336 Sema &S; 6337 CXXMethodDecl *MD; 6338 Sema::CXXSpecialMember CSM; 6339 Sema::InheritedConstructorInfo *ICI; 6340 bool Diagnose; 6341 6342 // Properties of the special member, computed for convenience. 6343 bool IsConstructor, IsAssignment, IsMove, ConstArg; 6344 SourceLocation Loc; 6345 6346 bool AllFieldsAreConst; 6347 6348 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6349 Sema::CXXSpecialMember CSM, 6350 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6351 : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose), 6352 IsConstructor(false), IsAssignment(false), IsMove(false), 6353 ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) { 6354 switch (CSM) { 6355 case Sema::CXXDefaultConstructor: 6356 case Sema::CXXCopyConstructor: 6357 IsConstructor = true; 6358 break; 6359 case Sema::CXXMoveConstructor: 6360 IsConstructor = true; 6361 IsMove = true; 6362 break; 6363 case Sema::CXXCopyAssignment: 6364 IsAssignment = true; 6365 break; 6366 case Sema::CXXMoveAssignment: 6367 IsAssignment = true; 6368 IsMove = true; 6369 break; 6370 case Sema::CXXDestructor: 6371 break; 6372 case Sema::CXXInvalid: 6373 llvm_unreachable("invalid special member kind"); 6374 } 6375 6376 if (MD->getNumParams()) { 6377 if (const ReferenceType *RT = 6378 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6379 ConstArg = RT->getPointeeType().isConstQualified(); 6380 } 6381 } 6382 6383 bool inUnion() const { return MD->getParent()->isUnion(); } 6384 6385 Sema::CXXSpecialMember getEffectiveCSM() { 6386 return ICI ? Sema::CXXInvalid : CSM; 6387 } 6388 6389 /// Look up the corresponding special member in the given class. 6390 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 6391 unsigned Quals, bool IsMutable) { 6392 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6393 ConstArg && !IsMutable); 6394 } 6395 6396 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6397 6398 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6399 bool shouldDeleteForField(FieldDecl *FD); 6400 bool shouldDeleteForAllConstMembers(); 6401 6402 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6403 unsigned Quals); 6404 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6405 Sema::SpecialMemberOverloadResult *SMOR, 6406 bool IsDtorCallInCtor); 6407 6408 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6409 }; 6410 } 6411 6412 /// Is the given special member inaccessible when used on the given 6413 /// sub-object. 6414 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6415 CXXMethodDecl *target) { 6416 /// If we're operating on a base class, the object type is the 6417 /// type of this special member. 6418 QualType objectTy; 6419 AccessSpecifier access = target->getAccess(); 6420 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6421 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6422 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6423 6424 // If we're operating on a field, the object type is the type of the field. 6425 } else { 6426 objectTy = S.Context.getTypeDeclType(target->getParent()); 6427 } 6428 6429 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6430 } 6431 6432 /// Check whether we should delete a special member due to the implicit 6433 /// definition containing a call to a special member of a subobject. 6434 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6435 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 6436 bool IsDtorCallInCtor) { 6437 CXXMethodDecl *Decl = SMOR->getMethod(); 6438 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6439 6440 int DiagKind = -1; 6441 6442 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6443 DiagKind = !Decl ? 0 : 1; 6444 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6445 DiagKind = 2; 6446 else if (!isAccessible(Subobj, Decl)) 6447 DiagKind = 3; 6448 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6449 !Decl->isTrivial()) { 6450 // A member of a union must have a trivial corresponding special member. 6451 // As a weird special case, a destructor call from a union's constructor 6452 // must be accessible and non-deleted, but need not be trivial. Such a 6453 // destructor is never actually called, but is semantically checked as 6454 // if it were. 6455 DiagKind = 4; 6456 } 6457 6458 if (DiagKind == -1) 6459 return false; 6460 6461 if (Diagnose) { 6462 if (Field) { 6463 S.Diag(Field->getLocation(), 6464 diag::note_deleted_special_member_class_subobject) 6465 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6466 << Field << DiagKind << IsDtorCallInCtor; 6467 } else { 6468 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6469 S.Diag(Base->getLocStart(), 6470 diag::note_deleted_special_member_class_subobject) 6471 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6472 << Base->getType() << DiagKind << IsDtorCallInCtor; 6473 } 6474 6475 if (DiagKind == 1) 6476 S.NoteDeletedFunction(Decl); 6477 // FIXME: Explain inaccessibility if DiagKind == 3. 6478 } 6479 6480 return true; 6481 } 6482 6483 /// Check whether we should delete a special member function due to having a 6484 /// direct or virtual base class or non-static data member of class type M. 6485 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6486 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6487 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6488 bool IsMutable = Field && Field->isMutable(); 6489 6490 // C++11 [class.ctor]p5: 6491 // -- any direct or virtual base class, or non-static data member with no 6492 // brace-or-equal-initializer, has class type M (or array thereof) and 6493 // either M has no default constructor or overload resolution as applied 6494 // to M's default constructor results in an ambiguity or in a function 6495 // that is deleted or inaccessible 6496 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6497 // -- a direct or virtual base class B that cannot be copied/moved because 6498 // overload resolution, as applied to B's corresponding special member, 6499 // results in an ambiguity or a function that is deleted or inaccessible 6500 // from the defaulted special member 6501 // C++11 [class.dtor]p5: 6502 // -- any direct or virtual base class [...] has a type with a destructor 6503 // that is deleted or inaccessible 6504 if (!(CSM == Sema::CXXDefaultConstructor && 6505 Field && Field->hasInClassInitializer()) && 6506 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6507 false)) 6508 return true; 6509 6510 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6511 // -- any direct or virtual base class or non-static data member has a 6512 // type with a destructor that is deleted or inaccessible 6513 if (IsConstructor) { 6514 Sema::SpecialMemberOverloadResult *SMOR = 6515 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6516 false, false, false, false, false); 6517 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6518 return true; 6519 } 6520 6521 return false; 6522 } 6523 6524 /// Check whether we should delete a special member function due to the class 6525 /// having a particular direct or virtual base class. 6526 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6527 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6528 // If program is correct, BaseClass cannot be null, but if it is, the error 6529 // must be reported elsewhere. 6530 if (!BaseClass) 6531 return false; 6532 // If we have an inheriting constructor, check whether we're calling an 6533 // inherited constructor instead of a default constructor. 6534 if (ICI) { 6535 assert(CSM == Sema::CXXDefaultConstructor); 6536 auto *BaseCtor = 6537 ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD) 6538 ->getInheritedConstructor() 6539 .getConstructor()) 6540 .first; 6541 if (BaseCtor) { 6542 if (BaseCtor->isDeleted() && Diagnose) { 6543 S.Diag(Base->getLocStart(), 6544 diag::note_deleted_special_member_class_subobject) 6545 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6546 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6547 S.NoteDeletedFunction(BaseCtor); 6548 } 6549 return BaseCtor->isDeleted(); 6550 } 6551 } 6552 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6553 } 6554 6555 /// Check whether we should delete a special member function due to the class 6556 /// having a particular non-static data member. 6557 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6558 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6559 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6560 6561 if (CSM == Sema::CXXDefaultConstructor) { 6562 // For a default constructor, all references must be initialized in-class 6563 // and, if a union, it must have a non-const member. 6564 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6565 if (Diagnose) 6566 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6567 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6568 return true; 6569 } 6570 // C++11 [class.ctor]p5: any non-variant non-static data member of 6571 // const-qualified type (or array thereof) with no 6572 // brace-or-equal-initializer does not have a user-provided default 6573 // constructor. 6574 if (!inUnion() && FieldType.isConstQualified() && 6575 !FD->hasInClassInitializer() && 6576 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6577 if (Diagnose) 6578 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6579 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6580 return true; 6581 } 6582 6583 if (inUnion() && !FieldType.isConstQualified()) 6584 AllFieldsAreConst = false; 6585 } else if (CSM == Sema::CXXCopyConstructor) { 6586 // For a copy constructor, data members must not be of rvalue reference 6587 // type. 6588 if (FieldType->isRValueReferenceType()) { 6589 if (Diagnose) 6590 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6591 << MD->getParent() << FD << FieldType; 6592 return true; 6593 } 6594 } else if (IsAssignment) { 6595 // For an assignment operator, data members must not be of reference type. 6596 if (FieldType->isReferenceType()) { 6597 if (Diagnose) 6598 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6599 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 6600 return true; 6601 } 6602 if (!FieldRecord && FieldType.isConstQualified()) { 6603 // C++11 [class.copy]p23: 6604 // -- a non-static data member of const non-class type (or array thereof) 6605 if (Diagnose) 6606 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6607 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 6608 return true; 6609 } 6610 } 6611 6612 if (FieldRecord) { 6613 // Some additional restrictions exist on the variant members. 6614 if (!inUnion() && FieldRecord->isUnion() && 6615 FieldRecord->isAnonymousStructOrUnion()) { 6616 bool AllVariantFieldsAreConst = true; 6617 6618 // FIXME: Handle anonymous unions declared within anonymous unions. 6619 for (auto *UI : FieldRecord->fields()) { 6620 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6621 6622 if (!UnionFieldType.isConstQualified()) 6623 AllVariantFieldsAreConst = false; 6624 6625 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6626 if (UnionFieldRecord && 6627 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6628 UnionFieldType.getCVRQualifiers())) 6629 return true; 6630 } 6631 6632 // At least one member in each anonymous union must be non-const 6633 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6634 !FieldRecord->field_empty()) { 6635 if (Diagnose) 6636 S.Diag(FieldRecord->getLocation(), 6637 diag::note_deleted_default_ctor_all_const) 6638 << !!ICI << MD->getParent() << /*anonymous union*/1; 6639 return true; 6640 } 6641 6642 // Don't check the implicit member of the anonymous union type. 6643 // This is technically non-conformant, but sanity demands it. 6644 return false; 6645 } 6646 6647 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6648 FieldType.getCVRQualifiers())) 6649 return true; 6650 } 6651 6652 return false; 6653 } 6654 6655 /// C++11 [class.ctor] p5: 6656 /// A defaulted default constructor for a class X is defined as deleted if 6657 /// X is a union and all of its variant members are of const-qualified type. 6658 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6659 // This is a silly definition, because it gives an empty union a deleted 6660 // default constructor. Don't do that. 6661 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 6662 !MD->getParent()->field_empty()) { 6663 if (Diagnose) 6664 S.Diag(MD->getParent()->getLocation(), 6665 diag::note_deleted_default_ctor_all_const) 6666 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6667 return true; 6668 } 6669 return false; 6670 } 6671 6672 /// Determine whether a defaulted special member function should be defined as 6673 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6674 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6675 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6676 InheritedConstructorInfo *ICI, 6677 bool Diagnose) { 6678 if (MD->isInvalidDecl()) 6679 return false; 6680 CXXRecordDecl *RD = MD->getParent(); 6681 assert(!RD->isDependentType() && "do deletion after instantiation"); 6682 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6683 return false; 6684 6685 // C++11 [expr.lambda.prim]p19: 6686 // The closure type associated with a lambda-expression has a 6687 // deleted (8.4.3) default constructor and a deleted copy 6688 // assignment operator. 6689 if (RD->isLambda() && 6690 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6691 if (Diagnose) 6692 Diag(RD->getLocation(), diag::note_lambda_decl); 6693 return true; 6694 } 6695 6696 // For an anonymous struct or union, the copy and assignment special members 6697 // will never be used, so skip the check. For an anonymous union declared at 6698 // namespace scope, the constructor and destructor are used. 6699 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6700 RD->isAnonymousStructOrUnion()) 6701 return false; 6702 6703 // C++11 [class.copy]p7, p18: 6704 // If the class definition declares a move constructor or move assignment 6705 // operator, an implicitly declared copy constructor or copy assignment 6706 // operator is defined as deleted. 6707 if (MD->isImplicit() && 6708 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6709 CXXMethodDecl *UserDeclaredMove = nullptr; 6710 6711 // In Microsoft mode, a user-declared move only causes the deletion of the 6712 // corresponding copy operation, not both copy operations. 6713 if (RD->hasUserDeclaredMoveConstructor() && 6714 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 6715 if (!Diagnose) return true; 6716 6717 // Find any user-declared move constructor. 6718 for (auto *I : RD->ctors()) { 6719 if (I->isMoveConstructor()) { 6720 UserDeclaredMove = I; 6721 break; 6722 } 6723 } 6724 assert(UserDeclaredMove); 6725 } else if (RD->hasUserDeclaredMoveAssignment() && 6726 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 6727 if (!Diagnose) return true; 6728 6729 // Find any user-declared move assignment operator. 6730 for (auto *I : RD->methods()) { 6731 if (I->isMoveAssignmentOperator()) { 6732 UserDeclaredMove = I; 6733 break; 6734 } 6735 } 6736 assert(UserDeclaredMove); 6737 } 6738 6739 if (UserDeclaredMove) { 6740 Diag(UserDeclaredMove->getLocation(), 6741 diag::note_deleted_copy_user_declared_move) 6742 << (CSM == CXXCopyAssignment) << RD 6743 << UserDeclaredMove->isMoveAssignmentOperator(); 6744 return true; 6745 } 6746 } 6747 6748 // Do access control from the special member function 6749 ContextRAII MethodContext(*this, MD); 6750 6751 // C++11 [class.dtor]p5: 6752 // -- for a virtual destructor, lookup of the non-array deallocation function 6753 // results in an ambiguity or in a function that is deleted or inaccessible 6754 if (CSM == CXXDestructor && MD->isVirtual()) { 6755 FunctionDecl *OperatorDelete = nullptr; 6756 DeclarationName Name = 6757 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6758 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 6759 OperatorDelete, /*Diagnose*/false)) { 6760 if (Diagnose) 6761 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 6762 return true; 6763 } 6764 } 6765 6766 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 6767 6768 for (auto &BI : RD->bases()) 6769 if ((SMI.IsAssignment || !BI.isVirtual()) && 6770 SMI.shouldDeleteForBase(&BI)) 6771 return true; 6772 6773 // Per DR1611, do not consider virtual bases of constructors of abstract 6774 // classes, since we are not going to construct them. For assignment 6775 // operators, we only assign (and thus only consider) direct bases. 6776 if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) { 6777 for (auto &BI : RD->vbases()) 6778 if (SMI.shouldDeleteForBase(&BI)) 6779 return true; 6780 } 6781 6782 for (auto *FI : RD->fields()) 6783 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 6784 SMI.shouldDeleteForField(FI)) 6785 return true; 6786 6787 if (SMI.shouldDeleteForAllConstMembers()) 6788 return true; 6789 6790 if (getLangOpts().CUDA) { 6791 // We should delete the special member in CUDA mode if target inference 6792 // failed. 6793 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 6794 Diagnose); 6795 } 6796 6797 return false; 6798 } 6799 6800 /// Perform lookup for a special member of the specified kind, and determine 6801 /// whether it is trivial. If the triviality can be determined without the 6802 /// lookup, skip it. This is intended for use when determining whether a 6803 /// special member of a containing object is trivial, and thus does not ever 6804 /// perform overload resolution for default constructors. 6805 /// 6806 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 6807 /// member that was most likely to be intended to be trivial, if any. 6808 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 6809 Sema::CXXSpecialMember CSM, unsigned Quals, 6810 bool ConstRHS, CXXMethodDecl **Selected) { 6811 if (Selected) 6812 *Selected = nullptr; 6813 6814 switch (CSM) { 6815 case Sema::CXXInvalid: 6816 llvm_unreachable("not a special member"); 6817 6818 case Sema::CXXDefaultConstructor: 6819 // C++11 [class.ctor]p5: 6820 // A default constructor is trivial if: 6821 // - all the [direct subobjects] have trivial default constructors 6822 // 6823 // Note, no overload resolution is performed in this case. 6824 if (RD->hasTrivialDefaultConstructor()) 6825 return true; 6826 6827 if (Selected) { 6828 // If there's a default constructor which could have been trivial, dig it 6829 // out. Otherwise, if there's any user-provided default constructor, point 6830 // to that as an example of why there's not a trivial one. 6831 CXXConstructorDecl *DefCtor = nullptr; 6832 if (RD->needsImplicitDefaultConstructor()) 6833 S.DeclareImplicitDefaultConstructor(RD); 6834 for (auto *CI : RD->ctors()) { 6835 if (!CI->isDefaultConstructor()) 6836 continue; 6837 DefCtor = CI; 6838 if (!DefCtor->isUserProvided()) 6839 break; 6840 } 6841 6842 *Selected = DefCtor; 6843 } 6844 6845 return false; 6846 6847 case Sema::CXXDestructor: 6848 // C++11 [class.dtor]p5: 6849 // A destructor is trivial if: 6850 // - all the direct [subobjects] have trivial destructors 6851 if (RD->hasTrivialDestructor()) 6852 return true; 6853 6854 if (Selected) { 6855 if (RD->needsImplicitDestructor()) 6856 S.DeclareImplicitDestructor(RD); 6857 *Selected = RD->getDestructor(); 6858 } 6859 6860 return false; 6861 6862 case Sema::CXXCopyConstructor: 6863 // C++11 [class.copy]p12: 6864 // A copy constructor is trivial if: 6865 // - the constructor selected to copy each direct [subobject] is trivial 6866 if (RD->hasTrivialCopyConstructor()) { 6867 if (Quals == Qualifiers::Const) 6868 // We must either select the trivial copy constructor or reach an 6869 // ambiguity; no need to actually perform overload resolution. 6870 return true; 6871 } else if (!Selected) { 6872 return false; 6873 } 6874 // In C++98, we are not supposed to perform overload resolution here, but we 6875 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 6876 // cases like B as having a non-trivial copy constructor: 6877 // struct A { template<typename T> A(T&); }; 6878 // struct B { mutable A a; }; 6879 goto NeedOverloadResolution; 6880 6881 case Sema::CXXCopyAssignment: 6882 // C++11 [class.copy]p25: 6883 // A copy assignment operator is trivial if: 6884 // - the assignment operator selected to copy each direct [subobject] is 6885 // trivial 6886 if (RD->hasTrivialCopyAssignment()) { 6887 if (Quals == Qualifiers::Const) 6888 return true; 6889 } else if (!Selected) { 6890 return false; 6891 } 6892 // In C++98, we are not supposed to perform overload resolution here, but we 6893 // treat that as a language defect. 6894 goto NeedOverloadResolution; 6895 6896 case Sema::CXXMoveConstructor: 6897 case Sema::CXXMoveAssignment: 6898 NeedOverloadResolution: 6899 Sema::SpecialMemberOverloadResult *SMOR = 6900 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 6901 6902 // The standard doesn't describe how to behave if the lookup is ambiguous. 6903 // We treat it as not making the member non-trivial, just like the standard 6904 // mandates for the default constructor. This should rarely matter, because 6905 // the member will also be deleted. 6906 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6907 return true; 6908 6909 if (!SMOR->getMethod()) { 6910 assert(SMOR->getKind() == 6911 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 6912 return false; 6913 } 6914 6915 // We deliberately don't check if we found a deleted special member. We're 6916 // not supposed to! 6917 if (Selected) 6918 *Selected = SMOR->getMethod(); 6919 return SMOR->getMethod()->isTrivial(); 6920 } 6921 6922 llvm_unreachable("unknown special method kind"); 6923 } 6924 6925 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 6926 for (auto *CI : RD->ctors()) 6927 if (!CI->isImplicit()) 6928 return CI; 6929 6930 // Look for constructor templates. 6931 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 6932 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 6933 if (CXXConstructorDecl *CD = 6934 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 6935 return CD; 6936 } 6937 6938 return nullptr; 6939 } 6940 6941 /// The kind of subobject we are checking for triviality. The values of this 6942 /// enumeration are used in diagnostics. 6943 enum TrivialSubobjectKind { 6944 /// The subobject is a base class. 6945 TSK_BaseClass, 6946 /// The subobject is a non-static data member. 6947 TSK_Field, 6948 /// The object is actually the complete object. 6949 TSK_CompleteObject 6950 }; 6951 6952 /// Check whether the special member selected for a given type would be trivial. 6953 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 6954 QualType SubType, bool ConstRHS, 6955 Sema::CXXSpecialMember CSM, 6956 TrivialSubobjectKind Kind, 6957 bool Diagnose) { 6958 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 6959 if (!SubRD) 6960 return true; 6961 6962 CXXMethodDecl *Selected; 6963 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 6964 ConstRHS, Diagnose ? &Selected : nullptr)) 6965 return true; 6966 6967 if (Diagnose) { 6968 if (ConstRHS) 6969 SubType.addConst(); 6970 6971 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 6972 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 6973 << Kind << SubType.getUnqualifiedType(); 6974 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6975 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6976 } else if (!Selected) 6977 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6978 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6979 else if (Selected->isUserProvided()) { 6980 if (Kind == TSK_CompleteObject) 6981 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6982 << Kind << SubType.getUnqualifiedType() << CSM; 6983 else { 6984 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6985 << Kind << SubType.getUnqualifiedType() << CSM; 6986 S.Diag(Selected->getLocation(), diag::note_declared_at); 6987 } 6988 } else { 6989 if (Kind != TSK_CompleteObject) 6990 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6991 << Kind << SubType.getUnqualifiedType() << CSM; 6992 6993 // Explain why the defaulted or deleted special member isn't trivial. 6994 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6995 } 6996 } 6997 6998 return false; 6999 } 7000 7001 /// Check whether the members of a class type allow a special member to be 7002 /// trivial. 7003 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7004 Sema::CXXSpecialMember CSM, 7005 bool ConstArg, bool Diagnose) { 7006 for (const auto *FI : RD->fields()) { 7007 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7008 continue; 7009 7010 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7011 7012 // Pretend anonymous struct or union members are members of this class. 7013 if (FI->isAnonymousStructOrUnion()) { 7014 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7015 CSM, ConstArg, Diagnose)) 7016 return false; 7017 continue; 7018 } 7019 7020 // C++11 [class.ctor]p5: 7021 // A default constructor is trivial if [...] 7022 // -- no non-static data member of its class has a 7023 // brace-or-equal-initializer 7024 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7025 if (Diagnose) 7026 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7027 return false; 7028 } 7029 7030 // Objective C ARC 4.3.5: 7031 // [...] nontrivally ownership-qualified types are [...] not trivially 7032 // default constructible, copy constructible, move constructible, copy 7033 // assignable, move assignable, or destructible [...] 7034 if (S.getLangOpts().ObjCAutoRefCount && 7035 FieldType.hasNonTrivialObjCLifetime()) { 7036 if (Diagnose) 7037 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7038 << RD << FieldType.getObjCLifetime(); 7039 return false; 7040 } 7041 7042 bool ConstRHS = ConstArg && !FI->isMutable(); 7043 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7044 CSM, TSK_Field, Diagnose)) 7045 return false; 7046 } 7047 7048 return true; 7049 } 7050 7051 /// Diagnose why the specified class does not have a trivial special member of 7052 /// the given kind. 7053 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7054 QualType Ty = Context.getRecordType(RD); 7055 7056 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7057 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7058 TSK_CompleteObject, /*Diagnose*/true); 7059 } 7060 7061 /// Determine whether a defaulted or deleted special member function is trivial, 7062 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7063 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7064 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7065 bool Diagnose) { 7066 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7067 7068 CXXRecordDecl *RD = MD->getParent(); 7069 7070 bool ConstArg = false; 7071 7072 // C++11 [class.copy]p12, p25: [DR1593] 7073 // A [special member] is trivial if [...] its parameter-type-list is 7074 // equivalent to the parameter-type-list of an implicit declaration [...] 7075 switch (CSM) { 7076 case CXXDefaultConstructor: 7077 case CXXDestructor: 7078 // Trivial default constructors and destructors cannot have parameters. 7079 break; 7080 7081 case CXXCopyConstructor: 7082 case CXXCopyAssignment: { 7083 // Trivial copy operations always have const, non-volatile parameter types. 7084 ConstArg = true; 7085 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7086 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7087 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7088 if (Diagnose) 7089 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7090 << Param0->getSourceRange() << Param0->getType() 7091 << Context.getLValueReferenceType( 7092 Context.getRecordType(RD).withConst()); 7093 return false; 7094 } 7095 break; 7096 } 7097 7098 case CXXMoveConstructor: 7099 case CXXMoveAssignment: { 7100 // Trivial move operations always have non-cv-qualified parameters. 7101 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7102 const RValueReferenceType *RT = 7103 Param0->getType()->getAs<RValueReferenceType>(); 7104 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7105 if (Diagnose) 7106 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7107 << Param0->getSourceRange() << Param0->getType() 7108 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7109 return false; 7110 } 7111 break; 7112 } 7113 7114 case CXXInvalid: 7115 llvm_unreachable("not a special member"); 7116 } 7117 7118 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7119 if (Diagnose) 7120 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7121 diag::note_nontrivial_default_arg) 7122 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7123 return false; 7124 } 7125 if (MD->isVariadic()) { 7126 if (Diagnose) 7127 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7128 return false; 7129 } 7130 7131 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7132 // A copy/move [constructor or assignment operator] is trivial if 7133 // -- the [member] selected to copy/move each direct base class subobject 7134 // is trivial 7135 // 7136 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7137 // A [default constructor or destructor] is trivial if 7138 // -- all the direct base classes have trivial [default constructors or 7139 // destructors] 7140 for (const auto &BI : RD->bases()) 7141 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7142 ConstArg, CSM, TSK_BaseClass, Diagnose)) 7143 return false; 7144 7145 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7146 // A copy/move [constructor or assignment operator] for a class X is 7147 // trivial if 7148 // -- for each non-static data member of X that is of class type (or array 7149 // thereof), the constructor selected to copy/move that member is 7150 // trivial 7151 // 7152 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7153 // A [default constructor or destructor] is trivial if 7154 // -- for all of the non-static data members of its class that are of class 7155 // type (or array thereof), each such class has a trivial [default 7156 // constructor or destructor] 7157 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 7158 return false; 7159 7160 // C++11 [class.dtor]p5: 7161 // A destructor is trivial if [...] 7162 // -- the destructor is not virtual 7163 if (CSM == CXXDestructor && MD->isVirtual()) { 7164 if (Diagnose) 7165 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7166 return false; 7167 } 7168 7169 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7170 // A [special member] for class X is trivial if [...] 7171 // -- class X has no virtual functions and no virtual base classes 7172 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7173 if (!Diagnose) 7174 return false; 7175 7176 if (RD->getNumVBases()) { 7177 // Check for virtual bases. We already know that the corresponding 7178 // member in all bases is trivial, so vbases must all be direct. 7179 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7180 assert(BS.isVirtual()); 7181 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7182 return false; 7183 } 7184 7185 // Must have a virtual method. 7186 for (const auto *MI : RD->methods()) { 7187 if (MI->isVirtual()) { 7188 SourceLocation MLoc = MI->getLocStart(); 7189 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7190 return false; 7191 } 7192 } 7193 7194 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7195 } 7196 7197 // Looks like it's trivial! 7198 return true; 7199 } 7200 7201 namespace { 7202 struct FindHiddenVirtualMethod { 7203 Sema *S; 7204 CXXMethodDecl *Method; 7205 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7206 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7207 7208 private: 7209 /// Check whether any most overriden method from MD in Methods 7210 static bool CheckMostOverridenMethods( 7211 const CXXMethodDecl *MD, 7212 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7213 if (MD->size_overridden_methods() == 0) 7214 return Methods.count(MD->getCanonicalDecl()); 7215 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7216 E = MD->end_overridden_methods(); 7217 I != E; ++I) 7218 if (CheckMostOverridenMethods(*I, Methods)) 7219 return true; 7220 return false; 7221 } 7222 7223 public: 7224 /// Member lookup function that determines whether a given C++ 7225 /// method overloads virtual methods in a base class without overriding any, 7226 /// to be used with CXXRecordDecl::lookupInBases(). 7227 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7228 RecordDecl *BaseRecord = 7229 Specifier->getType()->getAs<RecordType>()->getDecl(); 7230 7231 DeclarationName Name = Method->getDeclName(); 7232 assert(Name.getNameKind() == DeclarationName::Identifier); 7233 7234 bool foundSameNameMethod = false; 7235 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7236 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7237 Path.Decls = Path.Decls.slice(1)) { 7238 NamedDecl *D = Path.Decls.front(); 7239 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7240 MD = MD->getCanonicalDecl(); 7241 foundSameNameMethod = true; 7242 // Interested only in hidden virtual methods. 7243 if (!MD->isVirtual()) 7244 continue; 7245 // If the method we are checking overrides a method from its base 7246 // don't warn about the other overloaded methods. Clang deviates from 7247 // GCC by only diagnosing overloads of inherited virtual functions that 7248 // do not override any other virtual functions in the base. GCC's 7249 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7250 // function from a base class. These cases may be better served by a 7251 // warning (not specific to virtual functions) on call sites when the 7252 // call would select a different function from the base class, were it 7253 // visible. 7254 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7255 if (!S->IsOverload(Method, MD, false)) 7256 return true; 7257 // Collect the overload only if its hidden. 7258 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7259 overloadedMethods.push_back(MD); 7260 } 7261 } 7262 7263 if (foundSameNameMethod) 7264 OverloadedMethods.append(overloadedMethods.begin(), 7265 overloadedMethods.end()); 7266 return foundSameNameMethod; 7267 } 7268 }; 7269 } // end anonymous namespace 7270 7271 /// \brief Add the most overriden methods from MD to Methods 7272 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7273 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7274 if (MD->size_overridden_methods() == 0) 7275 Methods.insert(MD->getCanonicalDecl()); 7276 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7277 E = MD->end_overridden_methods(); 7278 I != E; ++I) 7279 AddMostOverridenMethods(*I, Methods); 7280 } 7281 7282 /// \brief Check if a method overloads virtual methods in a base class without 7283 /// overriding any. 7284 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7285 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7286 if (!MD->getDeclName().isIdentifier()) 7287 return; 7288 7289 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7290 /*bool RecordPaths=*/false, 7291 /*bool DetectVirtual=*/false); 7292 FindHiddenVirtualMethod FHVM; 7293 FHVM.Method = MD; 7294 FHVM.S = this; 7295 7296 // Keep the base methods that were overriden or introduced in the subclass 7297 // by 'using' in a set. A base method not in this set is hidden. 7298 CXXRecordDecl *DC = MD->getParent(); 7299 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7300 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7301 NamedDecl *ND = *I; 7302 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7303 ND = shad->getTargetDecl(); 7304 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7305 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7306 } 7307 7308 if (DC->lookupInBases(FHVM, Paths)) 7309 OverloadedMethods = FHVM.OverloadedMethods; 7310 } 7311 7312 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7313 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7314 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7315 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7316 PartialDiagnostic PD = PDiag( 7317 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7318 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7319 Diag(overloadedMD->getLocation(), PD); 7320 } 7321 } 7322 7323 /// \brief Diagnose methods which overload virtual methods in a base class 7324 /// without overriding any. 7325 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7326 if (MD->isInvalidDecl()) 7327 return; 7328 7329 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7330 return; 7331 7332 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7333 FindHiddenVirtualMethods(MD, OverloadedMethods); 7334 if (!OverloadedMethods.empty()) { 7335 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7336 << MD << (OverloadedMethods.size() > 1); 7337 7338 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7339 } 7340 } 7341 7342 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7343 Decl *TagDecl, 7344 SourceLocation LBrac, 7345 SourceLocation RBrac, 7346 AttributeList *AttrList) { 7347 if (!TagDecl) 7348 return; 7349 7350 AdjustDeclIfTemplate(TagDecl); 7351 7352 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7353 if (l->getKind() != AttributeList::AT_Visibility) 7354 continue; 7355 l->setInvalid(); 7356 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7357 l->getName(); 7358 } 7359 7360 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7361 // strict aliasing violation! 7362 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7363 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7364 7365 CheckCompletedCXXClass( 7366 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 7367 } 7368 7369 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7370 /// special functions, such as the default constructor, copy 7371 /// constructor, or destructor, to the given C++ class (C++ 7372 /// [special]p1). This routine can only be executed just before the 7373 /// definition of the class is complete. 7374 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7375 if (ClassDecl->needsImplicitDefaultConstructor()) { 7376 ++ASTContext::NumImplicitDefaultConstructors; 7377 7378 if (ClassDecl->hasInheritedConstructor()) 7379 DeclareImplicitDefaultConstructor(ClassDecl); 7380 } 7381 7382 if (ClassDecl->needsImplicitCopyConstructor()) { 7383 ++ASTContext::NumImplicitCopyConstructors; 7384 7385 // If the properties or semantics of the copy constructor couldn't be 7386 // determined while the class was being declared, force a declaration 7387 // of it now. 7388 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7389 ClassDecl->hasInheritedConstructor()) 7390 DeclareImplicitCopyConstructor(ClassDecl); 7391 } 7392 7393 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7394 ++ASTContext::NumImplicitMoveConstructors; 7395 7396 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7397 ClassDecl->hasInheritedConstructor()) 7398 DeclareImplicitMoveConstructor(ClassDecl); 7399 } 7400 7401 if (ClassDecl->needsImplicitCopyAssignment()) { 7402 ++ASTContext::NumImplicitCopyAssignmentOperators; 7403 7404 // If we have a dynamic class, then the copy assignment operator may be 7405 // virtual, so we have to declare it immediately. This ensures that, e.g., 7406 // it shows up in the right place in the vtable and that we diagnose 7407 // problems with the implicit exception specification. 7408 if (ClassDecl->isDynamicClass() || 7409 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7410 ClassDecl->hasInheritedAssignment()) 7411 DeclareImplicitCopyAssignment(ClassDecl); 7412 } 7413 7414 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7415 ++ASTContext::NumImplicitMoveAssignmentOperators; 7416 7417 // Likewise for the move assignment operator. 7418 if (ClassDecl->isDynamicClass() || 7419 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7420 ClassDecl->hasInheritedAssignment()) 7421 DeclareImplicitMoveAssignment(ClassDecl); 7422 } 7423 7424 if (ClassDecl->needsImplicitDestructor()) { 7425 ++ASTContext::NumImplicitDestructors; 7426 7427 // If we have a dynamic class, then the destructor may be virtual, so we 7428 // have to declare the destructor immediately. This ensures that, e.g., it 7429 // shows up in the right place in the vtable and that we diagnose problems 7430 // with the implicit exception specification. 7431 if (ClassDecl->isDynamicClass() || 7432 ClassDecl->needsOverloadResolutionForDestructor()) 7433 DeclareImplicitDestructor(ClassDecl); 7434 } 7435 } 7436 7437 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7438 if (!D) 7439 return 0; 7440 7441 // The order of template parameters is not important here. All names 7442 // get added to the same scope. 7443 SmallVector<TemplateParameterList *, 4> ParameterLists; 7444 7445 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7446 D = TD->getTemplatedDecl(); 7447 7448 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7449 ParameterLists.push_back(PSD->getTemplateParameters()); 7450 7451 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7452 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7453 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7454 7455 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7456 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7457 ParameterLists.push_back(FTD->getTemplateParameters()); 7458 } 7459 } 7460 7461 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7462 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7463 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7464 7465 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7466 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7467 ParameterLists.push_back(CTD->getTemplateParameters()); 7468 } 7469 } 7470 7471 unsigned Count = 0; 7472 for (TemplateParameterList *Params : ParameterLists) { 7473 if (Params->size() > 0) 7474 // Ignore explicit specializations; they don't contribute to the template 7475 // depth. 7476 ++Count; 7477 for (NamedDecl *Param : *Params) { 7478 if (Param->getDeclName()) { 7479 S->AddDecl(Param); 7480 IdResolver.AddDecl(Param); 7481 } 7482 } 7483 } 7484 7485 return Count; 7486 } 7487 7488 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7489 if (!RecordD) return; 7490 AdjustDeclIfTemplate(RecordD); 7491 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7492 PushDeclContext(S, Record); 7493 } 7494 7495 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7496 if (!RecordD) return; 7497 PopDeclContext(); 7498 } 7499 7500 /// This is used to implement the constant expression evaluation part of the 7501 /// attribute enable_if extension. There is nothing in standard C++ which would 7502 /// require reentering parameters. 7503 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7504 if (!Param) 7505 return; 7506 7507 S->AddDecl(Param); 7508 if (Param->getDeclName()) 7509 IdResolver.AddDecl(Param); 7510 } 7511 7512 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7513 /// parsing a top-level (non-nested) C++ class, and we are now 7514 /// parsing those parts of the given Method declaration that could 7515 /// not be parsed earlier (C++ [class.mem]p2), such as default 7516 /// arguments. This action should enter the scope of the given 7517 /// Method declaration as if we had just parsed the qualified method 7518 /// name. However, it should not bring the parameters into scope; 7519 /// that will be performed by ActOnDelayedCXXMethodParameter. 7520 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7521 } 7522 7523 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7524 /// C++ method declaration. We're (re-)introducing the given 7525 /// function parameter into scope for use in parsing later parts of 7526 /// the method declaration. For example, we could see an 7527 /// ActOnParamDefaultArgument event for this parameter. 7528 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7529 if (!ParamD) 7530 return; 7531 7532 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7533 7534 // If this parameter has an unparsed default argument, clear it out 7535 // to make way for the parsed default argument. 7536 if (Param->hasUnparsedDefaultArg()) 7537 Param->setDefaultArg(nullptr); 7538 7539 S->AddDecl(Param); 7540 if (Param->getDeclName()) 7541 IdResolver.AddDecl(Param); 7542 } 7543 7544 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7545 /// processing the delayed method declaration for Method. The method 7546 /// declaration is now considered finished. There may be a separate 7547 /// ActOnStartOfFunctionDef action later (not necessarily 7548 /// immediately!) for this method, if it was also defined inside the 7549 /// class body. 7550 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7551 if (!MethodD) 7552 return; 7553 7554 AdjustDeclIfTemplate(MethodD); 7555 7556 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7557 7558 // Now that we have our default arguments, check the constructor 7559 // again. It could produce additional diagnostics or affect whether 7560 // the class has implicitly-declared destructors, among other 7561 // things. 7562 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7563 CheckConstructor(Constructor); 7564 7565 // Check the default arguments, which we may have added. 7566 if (!Method->isInvalidDecl()) 7567 CheckCXXDefaultArguments(Method); 7568 } 7569 7570 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7571 /// the well-formedness of the constructor declarator @p D with type @p 7572 /// R. If there are any errors in the declarator, this routine will 7573 /// emit diagnostics and set the invalid bit to true. In any case, the type 7574 /// will be updated to reflect a well-formed type for the constructor and 7575 /// returned. 7576 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7577 StorageClass &SC) { 7578 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7579 7580 // C++ [class.ctor]p3: 7581 // A constructor shall not be virtual (10.3) or static (9.4). A 7582 // constructor can be invoked for a const, volatile or const 7583 // volatile object. A constructor shall not be declared const, 7584 // volatile, or const volatile (9.3.2). 7585 if (isVirtual) { 7586 if (!D.isInvalidType()) 7587 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7588 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7589 << SourceRange(D.getIdentifierLoc()); 7590 D.setInvalidType(); 7591 } 7592 if (SC == SC_Static) { 7593 if (!D.isInvalidType()) 7594 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7595 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7596 << SourceRange(D.getIdentifierLoc()); 7597 D.setInvalidType(); 7598 SC = SC_None; 7599 } 7600 7601 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7602 diagnoseIgnoredQualifiers( 7603 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7604 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7605 D.getDeclSpec().getRestrictSpecLoc(), 7606 D.getDeclSpec().getAtomicSpecLoc()); 7607 D.setInvalidType(); 7608 } 7609 7610 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7611 if (FTI.TypeQuals != 0) { 7612 if (FTI.TypeQuals & Qualifiers::Const) 7613 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7614 << "const" << SourceRange(D.getIdentifierLoc()); 7615 if (FTI.TypeQuals & Qualifiers::Volatile) 7616 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7617 << "volatile" << SourceRange(D.getIdentifierLoc()); 7618 if (FTI.TypeQuals & Qualifiers::Restrict) 7619 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7620 << "restrict" << SourceRange(D.getIdentifierLoc()); 7621 D.setInvalidType(); 7622 } 7623 7624 // C++0x [class.ctor]p4: 7625 // A constructor shall not be declared with a ref-qualifier. 7626 if (FTI.hasRefQualifier()) { 7627 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7628 << FTI.RefQualifierIsLValueRef 7629 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7630 D.setInvalidType(); 7631 } 7632 7633 // Rebuild the function type "R" without any type qualifiers (in 7634 // case any of the errors above fired) and with "void" as the 7635 // return type, since constructors don't have return types. 7636 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7637 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7638 return R; 7639 7640 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7641 EPI.TypeQuals = 0; 7642 EPI.RefQualifier = RQ_None; 7643 7644 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7645 } 7646 7647 /// CheckConstructor - Checks a fully-formed constructor for 7648 /// well-formedness, issuing any diagnostics required. Returns true if 7649 /// the constructor declarator is invalid. 7650 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7651 CXXRecordDecl *ClassDecl 7652 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7653 if (!ClassDecl) 7654 return Constructor->setInvalidDecl(); 7655 7656 // C++ [class.copy]p3: 7657 // A declaration of a constructor for a class X is ill-formed if 7658 // its first parameter is of type (optionally cv-qualified) X and 7659 // either there are no other parameters or else all other 7660 // parameters have default arguments. 7661 if (!Constructor->isInvalidDecl() && 7662 ((Constructor->getNumParams() == 1) || 7663 (Constructor->getNumParams() > 1 && 7664 Constructor->getParamDecl(1)->hasDefaultArg())) && 7665 Constructor->getTemplateSpecializationKind() 7666 != TSK_ImplicitInstantiation) { 7667 QualType ParamType = Constructor->getParamDecl(0)->getType(); 7668 QualType ClassTy = Context.getTagDeclType(ClassDecl); 7669 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 7670 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 7671 const char *ConstRef 7672 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 7673 : " const &"; 7674 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 7675 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 7676 7677 // FIXME: Rather that making the constructor invalid, we should endeavor 7678 // to fix the type. 7679 Constructor->setInvalidDecl(); 7680 } 7681 } 7682 } 7683 7684 /// CheckDestructor - Checks a fully-formed destructor definition for 7685 /// well-formedness, issuing any diagnostics required. Returns true 7686 /// on error. 7687 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 7688 CXXRecordDecl *RD = Destructor->getParent(); 7689 7690 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 7691 SourceLocation Loc; 7692 7693 if (!Destructor->isImplicit()) 7694 Loc = Destructor->getLocation(); 7695 else 7696 Loc = RD->getLocation(); 7697 7698 // If we have a virtual destructor, look up the deallocation function 7699 if (FunctionDecl *OperatorDelete = 7700 FindDeallocationFunctionForDestructor(Loc, RD)) { 7701 MarkFunctionReferenced(Loc, OperatorDelete); 7702 Destructor->setOperatorDelete(OperatorDelete); 7703 } 7704 } 7705 7706 return false; 7707 } 7708 7709 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 7710 /// the well-formednes of the destructor declarator @p D with type @p 7711 /// R. If there are any errors in the declarator, this routine will 7712 /// emit diagnostics and set the declarator to invalid. Even if this happens, 7713 /// will be updated to reflect a well-formed type for the destructor and 7714 /// returned. 7715 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 7716 StorageClass& SC) { 7717 // C++ [class.dtor]p1: 7718 // [...] A typedef-name that names a class is a class-name 7719 // (7.1.3); however, a typedef-name that names a class shall not 7720 // be used as the identifier in the declarator for a destructor 7721 // declaration. 7722 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 7723 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 7724 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7725 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 7726 else if (const TemplateSpecializationType *TST = 7727 DeclaratorType->getAs<TemplateSpecializationType>()) 7728 if (TST->isTypeAlias()) 7729 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7730 << DeclaratorType << 1; 7731 7732 // C++ [class.dtor]p2: 7733 // A destructor is used to destroy objects of its class type. A 7734 // destructor takes no parameters, and no return type can be 7735 // specified for it (not even void). The address of a destructor 7736 // shall not be taken. A destructor shall not be static. A 7737 // destructor can be invoked for a const, volatile or const 7738 // volatile object. A destructor shall not be declared const, 7739 // volatile or const volatile (9.3.2). 7740 if (SC == SC_Static) { 7741 if (!D.isInvalidType()) 7742 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 7743 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7744 << SourceRange(D.getIdentifierLoc()) 7745 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7746 7747 SC = SC_None; 7748 } 7749 if (!D.isInvalidType()) { 7750 // Destructors don't have return types, but the parser will 7751 // happily parse something like: 7752 // 7753 // class X { 7754 // float ~X(); 7755 // }; 7756 // 7757 // The return type will be eliminated later. 7758 if (D.getDeclSpec().hasTypeSpecifier()) 7759 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 7760 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7761 << SourceRange(D.getIdentifierLoc()); 7762 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7763 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 7764 SourceLocation(), 7765 D.getDeclSpec().getConstSpecLoc(), 7766 D.getDeclSpec().getVolatileSpecLoc(), 7767 D.getDeclSpec().getRestrictSpecLoc(), 7768 D.getDeclSpec().getAtomicSpecLoc()); 7769 D.setInvalidType(); 7770 } 7771 } 7772 7773 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7774 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 7775 if (FTI.TypeQuals & Qualifiers::Const) 7776 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7777 << "const" << SourceRange(D.getIdentifierLoc()); 7778 if (FTI.TypeQuals & Qualifiers::Volatile) 7779 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7780 << "volatile" << SourceRange(D.getIdentifierLoc()); 7781 if (FTI.TypeQuals & Qualifiers::Restrict) 7782 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7783 << "restrict" << SourceRange(D.getIdentifierLoc()); 7784 D.setInvalidType(); 7785 } 7786 7787 // C++0x [class.dtor]p2: 7788 // A destructor shall not be declared with a ref-qualifier. 7789 if (FTI.hasRefQualifier()) { 7790 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 7791 << FTI.RefQualifierIsLValueRef 7792 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7793 D.setInvalidType(); 7794 } 7795 7796 // Make sure we don't have any parameters. 7797 if (FTIHasNonVoidParameters(FTI)) { 7798 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 7799 7800 // Delete the parameters. 7801 FTI.freeParams(); 7802 D.setInvalidType(); 7803 } 7804 7805 // Make sure the destructor isn't variadic. 7806 if (FTI.isVariadic) { 7807 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 7808 D.setInvalidType(); 7809 } 7810 7811 // Rebuild the function type "R" without any type qualifiers or 7812 // parameters (in case any of the errors above fired) and with 7813 // "void" as the return type, since destructors don't have return 7814 // types. 7815 if (!D.isInvalidType()) 7816 return R; 7817 7818 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7819 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7820 EPI.Variadic = false; 7821 EPI.TypeQuals = 0; 7822 EPI.RefQualifier = RQ_None; 7823 return Context.getFunctionType(Context.VoidTy, None, EPI); 7824 } 7825 7826 static void extendLeft(SourceRange &R, SourceRange Before) { 7827 if (Before.isInvalid()) 7828 return; 7829 R.setBegin(Before.getBegin()); 7830 if (R.getEnd().isInvalid()) 7831 R.setEnd(Before.getEnd()); 7832 } 7833 7834 static void extendRight(SourceRange &R, SourceRange After) { 7835 if (After.isInvalid()) 7836 return; 7837 if (R.getBegin().isInvalid()) 7838 R.setBegin(After.getBegin()); 7839 R.setEnd(After.getEnd()); 7840 } 7841 7842 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 7843 /// well-formednes of the conversion function declarator @p D with 7844 /// type @p R. If there are any errors in the declarator, this routine 7845 /// will emit diagnostics and return true. Otherwise, it will return 7846 /// false. Either way, the type @p R will be updated to reflect a 7847 /// well-formed type for the conversion operator. 7848 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 7849 StorageClass& SC) { 7850 // C++ [class.conv.fct]p1: 7851 // Neither parameter types nor return type can be specified. The 7852 // type of a conversion function (8.3.5) is "function taking no 7853 // parameter returning conversion-type-id." 7854 if (SC == SC_Static) { 7855 if (!D.isInvalidType()) 7856 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 7857 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7858 << D.getName().getSourceRange(); 7859 D.setInvalidType(); 7860 SC = SC_None; 7861 } 7862 7863 TypeSourceInfo *ConvTSI = nullptr; 7864 QualType ConvType = 7865 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 7866 7867 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 7868 // Conversion functions don't have return types, but the parser will 7869 // happily parse something like: 7870 // 7871 // class X { 7872 // float operator bool(); 7873 // }; 7874 // 7875 // The return type will be changed later anyway. 7876 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 7877 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7878 << SourceRange(D.getIdentifierLoc()); 7879 D.setInvalidType(); 7880 } 7881 7882 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7883 7884 // Make sure we don't have any parameters. 7885 if (Proto->getNumParams() > 0) { 7886 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 7887 7888 // Delete the parameters. 7889 D.getFunctionTypeInfo().freeParams(); 7890 D.setInvalidType(); 7891 } else if (Proto->isVariadic()) { 7892 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 7893 D.setInvalidType(); 7894 } 7895 7896 // Diagnose "&operator bool()" and other such nonsense. This 7897 // is actually a gcc extension which we don't support. 7898 if (Proto->getReturnType() != ConvType) { 7899 bool NeedsTypedef = false; 7900 SourceRange Before, After; 7901 7902 // Walk the chunks and extract information on them for our diagnostic. 7903 bool PastFunctionChunk = false; 7904 for (auto &Chunk : D.type_objects()) { 7905 switch (Chunk.Kind) { 7906 case DeclaratorChunk::Function: 7907 if (!PastFunctionChunk) { 7908 if (Chunk.Fun.HasTrailingReturnType) { 7909 TypeSourceInfo *TRT = nullptr; 7910 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 7911 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 7912 } 7913 PastFunctionChunk = true; 7914 break; 7915 } 7916 // Fall through. 7917 case DeclaratorChunk::Array: 7918 NeedsTypedef = true; 7919 extendRight(After, Chunk.getSourceRange()); 7920 break; 7921 7922 case DeclaratorChunk::Pointer: 7923 case DeclaratorChunk::BlockPointer: 7924 case DeclaratorChunk::Reference: 7925 case DeclaratorChunk::MemberPointer: 7926 case DeclaratorChunk::Pipe: 7927 extendLeft(Before, Chunk.getSourceRange()); 7928 break; 7929 7930 case DeclaratorChunk::Paren: 7931 extendLeft(Before, Chunk.Loc); 7932 extendRight(After, Chunk.EndLoc); 7933 break; 7934 } 7935 } 7936 7937 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 7938 After.isValid() ? After.getBegin() : 7939 D.getIdentifierLoc(); 7940 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 7941 DB << Before << After; 7942 7943 if (!NeedsTypedef) { 7944 DB << /*don't need a typedef*/0; 7945 7946 // If we can provide a correct fix-it hint, do so. 7947 if (After.isInvalid() && ConvTSI) { 7948 SourceLocation InsertLoc = 7949 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 7950 DB << FixItHint::CreateInsertion(InsertLoc, " ") 7951 << FixItHint::CreateInsertionFromRange( 7952 InsertLoc, CharSourceRange::getTokenRange(Before)) 7953 << FixItHint::CreateRemoval(Before); 7954 } 7955 } else if (!Proto->getReturnType()->isDependentType()) { 7956 DB << /*typedef*/1 << Proto->getReturnType(); 7957 } else if (getLangOpts().CPlusPlus11) { 7958 DB << /*alias template*/2 << Proto->getReturnType(); 7959 } else { 7960 DB << /*might not be fixable*/3; 7961 } 7962 7963 // Recover by incorporating the other type chunks into the result type. 7964 // Note, this does *not* change the name of the function. This is compatible 7965 // with the GCC extension: 7966 // struct S { &operator int(); } s; 7967 // int &r = s.operator int(); // ok in GCC 7968 // S::operator int&() {} // error in GCC, function name is 'operator int'. 7969 ConvType = Proto->getReturnType(); 7970 } 7971 7972 // C++ [class.conv.fct]p4: 7973 // The conversion-type-id shall not represent a function type nor 7974 // an array type. 7975 if (ConvType->isArrayType()) { 7976 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7977 ConvType = Context.getPointerType(ConvType); 7978 D.setInvalidType(); 7979 } else if (ConvType->isFunctionType()) { 7980 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7981 ConvType = Context.getPointerType(ConvType); 7982 D.setInvalidType(); 7983 } 7984 7985 // Rebuild the function type "R" without any parameters (in case any 7986 // of the errors above fired) and with the conversion type as the 7987 // return type. 7988 if (D.isInvalidType()) 7989 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7990 7991 // C++0x explicit conversion operators. 7992 if (D.getDeclSpec().isExplicitSpecified()) 7993 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7994 getLangOpts().CPlusPlus11 ? 7995 diag::warn_cxx98_compat_explicit_conversion_functions : 7996 diag::ext_explicit_conversion_functions) 7997 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 7998 } 7999 8000 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8001 /// the declaration of the given C++ conversion function. This routine 8002 /// is responsible for recording the conversion function in the C++ 8003 /// class, if possible. 8004 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8005 assert(Conversion && "Expected to receive a conversion function declaration"); 8006 8007 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8008 8009 // Make sure we aren't redeclaring the conversion function. 8010 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8011 8012 // C++ [class.conv.fct]p1: 8013 // [...] A conversion function is never used to convert a 8014 // (possibly cv-qualified) object to the (possibly cv-qualified) 8015 // same object type (or a reference to it), to a (possibly 8016 // cv-qualified) base class of that type (or a reference to it), 8017 // or to (possibly cv-qualified) void. 8018 // FIXME: Suppress this warning if the conversion function ends up being a 8019 // virtual function that overrides a virtual function in a base class. 8020 QualType ClassType 8021 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8022 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8023 ConvType = ConvTypeRef->getPointeeType(); 8024 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8025 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8026 /* Suppress diagnostics for instantiations. */; 8027 else if (ConvType->isRecordType()) { 8028 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8029 if (ConvType == ClassType) 8030 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8031 << ClassType; 8032 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8033 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8034 << ClassType << ConvType; 8035 } else if (ConvType->isVoidType()) { 8036 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8037 << ClassType << ConvType; 8038 } 8039 8040 if (FunctionTemplateDecl *ConversionTemplate 8041 = Conversion->getDescribedFunctionTemplate()) 8042 return ConversionTemplate; 8043 8044 return Conversion; 8045 } 8046 8047 //===----------------------------------------------------------------------===// 8048 // Namespace Handling 8049 //===----------------------------------------------------------------------===// 8050 8051 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8052 /// reopened. 8053 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8054 SourceLocation Loc, 8055 IdentifierInfo *II, bool *IsInline, 8056 NamespaceDecl *PrevNS) { 8057 assert(*IsInline != PrevNS->isInline()); 8058 8059 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8060 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8061 // inline namespaces, with the intention of bringing names into namespace std. 8062 // 8063 // We support this just well enough to get that case working; this is not 8064 // sufficient to support reopening namespaces as inline in general. 8065 if (*IsInline && II && II->getName().startswith("__atomic") && 8066 S.getSourceManager().isInSystemHeader(Loc)) { 8067 // Mark all prior declarations of the namespace as inline. 8068 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8069 NS = NS->getPreviousDecl()) 8070 NS->setInline(*IsInline); 8071 // Patch up the lookup table for the containing namespace. This isn't really 8072 // correct, but it's good enough for this particular case. 8073 for (auto *I : PrevNS->decls()) 8074 if (auto *ND = dyn_cast<NamedDecl>(I)) 8075 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8076 return; 8077 } 8078 8079 if (PrevNS->isInline()) 8080 // The user probably just forgot the 'inline', so suggest that it 8081 // be added back. 8082 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8083 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8084 else 8085 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8086 8087 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8088 *IsInline = PrevNS->isInline(); 8089 } 8090 8091 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8092 /// definition. 8093 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8094 SourceLocation InlineLoc, 8095 SourceLocation NamespaceLoc, 8096 SourceLocation IdentLoc, 8097 IdentifierInfo *II, 8098 SourceLocation LBrace, 8099 AttributeList *AttrList, 8100 UsingDirectiveDecl *&UD) { 8101 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8102 // For anonymous namespace, take the location of the left brace. 8103 SourceLocation Loc = II ? IdentLoc : LBrace; 8104 bool IsInline = InlineLoc.isValid(); 8105 bool IsInvalid = false; 8106 bool IsStd = false; 8107 bool AddToKnown = false; 8108 Scope *DeclRegionScope = NamespcScope->getParent(); 8109 8110 NamespaceDecl *PrevNS = nullptr; 8111 if (II) { 8112 // C++ [namespace.def]p2: 8113 // The identifier in an original-namespace-definition shall not 8114 // have been previously defined in the declarative region in 8115 // which the original-namespace-definition appears. The 8116 // identifier in an original-namespace-definition is the name of 8117 // the namespace. Subsequently in that declarative region, it is 8118 // treated as an original-namespace-name. 8119 // 8120 // Since namespace names are unique in their scope, and we don't 8121 // look through using directives, just look for any ordinary names 8122 // as if by qualified name lookup. 8123 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration); 8124 LookupQualifiedName(R, CurContext->getRedeclContext()); 8125 NamedDecl *PrevDecl = 8126 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8127 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8128 8129 if (PrevNS) { 8130 // This is an extended namespace definition. 8131 if (IsInline != PrevNS->isInline()) 8132 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8133 &IsInline, PrevNS); 8134 } else if (PrevDecl) { 8135 // This is an invalid name redefinition. 8136 Diag(Loc, diag::err_redefinition_different_kind) 8137 << II; 8138 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8139 IsInvalid = true; 8140 // Continue on to push Namespc as current DeclContext and return it. 8141 } else if (II->isStr("std") && 8142 CurContext->getRedeclContext()->isTranslationUnit()) { 8143 // This is the first "real" definition of the namespace "std", so update 8144 // our cache of the "std" namespace to point at this definition. 8145 PrevNS = getStdNamespace(); 8146 IsStd = true; 8147 AddToKnown = !IsInline; 8148 } else { 8149 // We've seen this namespace for the first time. 8150 AddToKnown = !IsInline; 8151 } 8152 } else { 8153 // Anonymous namespaces. 8154 8155 // Determine whether the parent already has an anonymous namespace. 8156 DeclContext *Parent = CurContext->getRedeclContext(); 8157 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8158 PrevNS = TU->getAnonymousNamespace(); 8159 } else { 8160 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8161 PrevNS = ND->getAnonymousNamespace(); 8162 } 8163 8164 if (PrevNS && IsInline != PrevNS->isInline()) 8165 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8166 &IsInline, PrevNS); 8167 } 8168 8169 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8170 StartLoc, Loc, II, PrevNS); 8171 if (IsInvalid) 8172 Namespc->setInvalidDecl(); 8173 8174 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8175 8176 // FIXME: Should we be merging attributes? 8177 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8178 PushNamespaceVisibilityAttr(Attr, Loc); 8179 8180 if (IsStd) 8181 StdNamespace = Namespc; 8182 if (AddToKnown) 8183 KnownNamespaces[Namespc] = false; 8184 8185 if (II) { 8186 PushOnScopeChains(Namespc, DeclRegionScope); 8187 } else { 8188 // Link the anonymous namespace into its parent. 8189 DeclContext *Parent = CurContext->getRedeclContext(); 8190 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8191 TU->setAnonymousNamespace(Namespc); 8192 } else { 8193 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8194 } 8195 8196 CurContext->addDecl(Namespc); 8197 8198 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8199 // behaves as if it were replaced by 8200 // namespace unique { /* empty body */ } 8201 // using namespace unique; 8202 // namespace unique { namespace-body } 8203 // where all occurrences of 'unique' in a translation unit are 8204 // replaced by the same identifier and this identifier differs 8205 // from all other identifiers in the entire program. 8206 8207 // We just create the namespace with an empty name and then add an 8208 // implicit using declaration, just like the standard suggests. 8209 // 8210 // CodeGen enforces the "universally unique" aspect by giving all 8211 // declarations semantically contained within an anonymous 8212 // namespace internal linkage. 8213 8214 if (!PrevNS) { 8215 UD = UsingDirectiveDecl::Create(Context, Parent, 8216 /* 'using' */ LBrace, 8217 /* 'namespace' */ SourceLocation(), 8218 /* qualifier */ NestedNameSpecifierLoc(), 8219 /* identifier */ SourceLocation(), 8220 Namespc, 8221 /* Ancestor */ Parent); 8222 UD->setImplicit(); 8223 Parent->addDecl(UD); 8224 } 8225 } 8226 8227 ActOnDocumentableDecl(Namespc); 8228 8229 // Although we could have an invalid decl (i.e. the namespace name is a 8230 // redefinition), push it as current DeclContext and try to continue parsing. 8231 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8232 // for the namespace has the declarations that showed up in that particular 8233 // namespace definition. 8234 PushDeclContext(NamespcScope, Namespc); 8235 return Namespc; 8236 } 8237 8238 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8239 /// is a namespace alias, returns the namespace it points to. 8240 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8241 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8242 return AD->getNamespace(); 8243 return dyn_cast_or_null<NamespaceDecl>(D); 8244 } 8245 8246 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8247 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8248 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8249 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8250 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8251 Namespc->setRBraceLoc(RBrace); 8252 PopDeclContext(); 8253 if (Namespc->hasAttr<VisibilityAttr>()) 8254 PopPragmaVisibility(true, RBrace); 8255 } 8256 8257 CXXRecordDecl *Sema::getStdBadAlloc() const { 8258 return cast_or_null<CXXRecordDecl>( 8259 StdBadAlloc.get(Context.getExternalSource())); 8260 } 8261 8262 EnumDecl *Sema::getStdAlignValT() const { 8263 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8264 } 8265 8266 NamespaceDecl *Sema::getStdNamespace() const { 8267 return cast_or_null<NamespaceDecl>( 8268 StdNamespace.get(Context.getExternalSource())); 8269 } 8270 8271 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8272 if (!StdExperimentalNamespaceCache) { 8273 if (auto Std = getStdNamespace()) { 8274 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8275 SourceLocation(), LookupNamespaceName); 8276 if (!LookupQualifiedName(Result, Std) || 8277 !(StdExperimentalNamespaceCache = 8278 Result.getAsSingle<NamespaceDecl>())) 8279 Result.suppressDiagnostics(); 8280 } 8281 } 8282 return StdExperimentalNamespaceCache; 8283 } 8284 8285 /// \brief Retrieve the special "std" namespace, which may require us to 8286 /// implicitly define the namespace. 8287 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8288 if (!StdNamespace) { 8289 // The "std" namespace has not yet been defined, so build one implicitly. 8290 StdNamespace = NamespaceDecl::Create(Context, 8291 Context.getTranslationUnitDecl(), 8292 /*Inline=*/false, 8293 SourceLocation(), SourceLocation(), 8294 &PP.getIdentifierTable().get("std"), 8295 /*PrevDecl=*/nullptr); 8296 getStdNamespace()->setImplicit(true); 8297 } 8298 8299 return getStdNamespace(); 8300 } 8301 8302 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8303 assert(getLangOpts().CPlusPlus && 8304 "Looking for std::initializer_list outside of C++."); 8305 8306 // We're looking for implicit instantiations of 8307 // template <typename E> class std::initializer_list. 8308 8309 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8310 return false; 8311 8312 ClassTemplateDecl *Template = nullptr; 8313 const TemplateArgument *Arguments = nullptr; 8314 8315 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8316 8317 ClassTemplateSpecializationDecl *Specialization = 8318 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8319 if (!Specialization) 8320 return false; 8321 8322 Template = Specialization->getSpecializedTemplate(); 8323 Arguments = Specialization->getTemplateArgs().data(); 8324 } else if (const TemplateSpecializationType *TST = 8325 Ty->getAs<TemplateSpecializationType>()) { 8326 Template = dyn_cast_or_null<ClassTemplateDecl>( 8327 TST->getTemplateName().getAsTemplateDecl()); 8328 Arguments = TST->getArgs(); 8329 } 8330 if (!Template) 8331 return false; 8332 8333 if (!StdInitializerList) { 8334 // Haven't recognized std::initializer_list yet, maybe this is it. 8335 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8336 if (TemplateClass->getIdentifier() != 8337 &PP.getIdentifierTable().get("initializer_list") || 8338 !getStdNamespace()->InEnclosingNamespaceSetOf( 8339 TemplateClass->getDeclContext())) 8340 return false; 8341 // This is a template called std::initializer_list, but is it the right 8342 // template? 8343 TemplateParameterList *Params = Template->getTemplateParameters(); 8344 if (Params->getMinRequiredArguments() != 1) 8345 return false; 8346 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8347 return false; 8348 8349 // It's the right template. 8350 StdInitializerList = Template; 8351 } 8352 8353 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8354 return false; 8355 8356 // This is an instance of std::initializer_list. Find the argument type. 8357 if (Element) 8358 *Element = Arguments[0].getAsType(); 8359 return true; 8360 } 8361 8362 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8363 NamespaceDecl *Std = S.getStdNamespace(); 8364 if (!Std) { 8365 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8366 return nullptr; 8367 } 8368 8369 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8370 Loc, Sema::LookupOrdinaryName); 8371 if (!S.LookupQualifiedName(Result, Std)) { 8372 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8373 return nullptr; 8374 } 8375 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8376 if (!Template) { 8377 Result.suppressDiagnostics(); 8378 // We found something weird. Complain about the first thing we found. 8379 NamedDecl *Found = *Result.begin(); 8380 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8381 return nullptr; 8382 } 8383 8384 // We found some template called std::initializer_list. Now verify that it's 8385 // correct. 8386 TemplateParameterList *Params = Template->getTemplateParameters(); 8387 if (Params->getMinRequiredArguments() != 1 || 8388 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8389 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8390 return nullptr; 8391 } 8392 8393 return Template; 8394 } 8395 8396 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8397 if (!StdInitializerList) { 8398 StdInitializerList = LookupStdInitializerList(*this, Loc); 8399 if (!StdInitializerList) 8400 return QualType(); 8401 } 8402 8403 TemplateArgumentListInfo Args(Loc, Loc); 8404 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8405 Context.getTrivialTypeSourceInfo(Element, 8406 Loc))); 8407 return Context.getCanonicalType( 8408 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8409 } 8410 8411 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 8412 // C++ [dcl.init.list]p2: 8413 // A constructor is an initializer-list constructor if its first parameter 8414 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8415 // std::initializer_list<E> for some type E, and either there are no other 8416 // parameters or else all other parameters have default arguments. 8417 if (Ctor->getNumParams() < 1 || 8418 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8419 return false; 8420 8421 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8422 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8423 ArgType = RT->getPointeeType().getUnqualifiedType(); 8424 8425 return isStdInitializerList(ArgType, nullptr); 8426 } 8427 8428 /// \brief Determine whether a using statement is in a context where it will be 8429 /// apply in all contexts. 8430 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8431 switch (CurContext->getDeclKind()) { 8432 case Decl::TranslationUnit: 8433 return true; 8434 case Decl::LinkageSpec: 8435 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8436 default: 8437 return false; 8438 } 8439 } 8440 8441 namespace { 8442 8443 // Callback to only accept typo corrections that are namespaces. 8444 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8445 public: 8446 bool ValidateCandidate(const TypoCorrection &candidate) override { 8447 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8448 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8449 return false; 8450 } 8451 }; 8452 8453 } 8454 8455 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8456 CXXScopeSpec &SS, 8457 SourceLocation IdentLoc, 8458 IdentifierInfo *Ident) { 8459 R.clear(); 8460 if (TypoCorrection Corrected = 8461 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8462 llvm::make_unique<NamespaceValidatorCCC>(), 8463 Sema::CTK_ErrorRecovery)) { 8464 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8465 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8466 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8467 Ident->getName().equals(CorrectedStr); 8468 S.diagnoseTypo(Corrected, 8469 S.PDiag(diag::err_using_directive_member_suggest) 8470 << Ident << DC << DroppedSpecifier << SS.getRange(), 8471 S.PDiag(diag::note_namespace_defined_here)); 8472 } else { 8473 S.diagnoseTypo(Corrected, 8474 S.PDiag(diag::err_using_directive_suggest) << Ident, 8475 S.PDiag(diag::note_namespace_defined_here)); 8476 } 8477 R.addDecl(Corrected.getFoundDecl()); 8478 return true; 8479 } 8480 return false; 8481 } 8482 8483 Decl *Sema::ActOnUsingDirective(Scope *S, 8484 SourceLocation UsingLoc, 8485 SourceLocation NamespcLoc, 8486 CXXScopeSpec &SS, 8487 SourceLocation IdentLoc, 8488 IdentifierInfo *NamespcName, 8489 AttributeList *AttrList) { 8490 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8491 assert(NamespcName && "Invalid NamespcName."); 8492 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 8493 8494 // This can only happen along a recovery path. 8495 while (S->isTemplateParamScope()) 8496 S = S->getParent(); 8497 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8498 8499 UsingDirectiveDecl *UDir = nullptr; 8500 NestedNameSpecifier *Qualifier = nullptr; 8501 if (SS.isSet()) 8502 Qualifier = SS.getScopeRep(); 8503 8504 // Lookup namespace name. 8505 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 8506 LookupParsedName(R, S, &SS); 8507 if (R.isAmbiguous()) 8508 return nullptr; 8509 8510 if (R.empty()) { 8511 R.clear(); 8512 // Allow "using namespace std;" or "using namespace ::std;" even if 8513 // "std" hasn't been defined yet, for GCC compatibility. 8514 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 8515 NamespcName->isStr("std")) { 8516 Diag(IdentLoc, diag::ext_using_undefined_std); 8517 R.addDecl(getOrCreateStdNamespace()); 8518 R.resolveKind(); 8519 } 8520 // Otherwise, attempt typo correction. 8521 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 8522 } 8523 8524 if (!R.empty()) { 8525 NamedDecl *Named = R.getRepresentativeDecl(); 8526 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 8527 assert(NS && "expected namespace decl"); 8528 8529 // The use of a nested name specifier may trigger deprecation warnings. 8530 DiagnoseUseOfDecl(Named, IdentLoc); 8531 8532 // C++ [namespace.udir]p1: 8533 // A using-directive specifies that the names in the nominated 8534 // namespace can be used in the scope in which the 8535 // using-directive appears after the using-directive. During 8536 // unqualified name lookup (3.4.1), the names appear as if they 8537 // were declared in the nearest enclosing namespace which 8538 // contains both the using-directive and the nominated 8539 // namespace. [Note: in this context, "contains" means "contains 8540 // directly or indirectly". ] 8541 8542 // Find enclosing context containing both using-directive and 8543 // nominated namespace. 8544 DeclContext *CommonAncestor = cast<DeclContext>(NS); 8545 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 8546 CommonAncestor = CommonAncestor->getParent(); 8547 8548 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 8549 SS.getWithLocInContext(Context), 8550 IdentLoc, Named, CommonAncestor); 8551 8552 if (IsUsingDirectiveInToplevelContext(CurContext) && 8553 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 8554 Diag(IdentLoc, diag::warn_using_directive_in_header); 8555 } 8556 8557 PushUsingDirective(S, UDir); 8558 } else { 8559 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8560 } 8561 8562 if (UDir) 8563 ProcessDeclAttributeList(S, UDir, AttrList); 8564 8565 return UDir; 8566 } 8567 8568 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 8569 // If the scope has an associated entity and the using directive is at 8570 // namespace or translation unit scope, add the UsingDirectiveDecl into 8571 // its lookup structure so qualified name lookup can find it. 8572 DeclContext *Ctx = S->getEntity(); 8573 if (Ctx && !Ctx->isFunctionOrMethod()) 8574 Ctx->addDecl(UDir); 8575 else 8576 // Otherwise, it is at block scope. The using-directives will affect lookup 8577 // only to the end of the scope. 8578 S->PushUsingDirective(UDir); 8579 } 8580 8581 8582 Decl *Sema::ActOnUsingDeclaration(Scope *S, 8583 AccessSpecifier AS, 8584 bool HasUsingKeyword, 8585 SourceLocation UsingLoc, 8586 CXXScopeSpec &SS, 8587 UnqualifiedId &Name, 8588 AttributeList *AttrList, 8589 bool HasTypenameKeyword, 8590 SourceLocation TypenameLoc) { 8591 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8592 8593 switch (Name.getKind()) { 8594 case UnqualifiedId::IK_ImplicitSelfParam: 8595 case UnqualifiedId::IK_Identifier: 8596 case UnqualifiedId::IK_OperatorFunctionId: 8597 case UnqualifiedId::IK_LiteralOperatorId: 8598 case UnqualifiedId::IK_ConversionFunctionId: 8599 break; 8600 8601 case UnqualifiedId::IK_ConstructorName: 8602 case UnqualifiedId::IK_ConstructorTemplateId: 8603 // C++11 inheriting constructors. 8604 Diag(Name.getLocStart(), 8605 getLangOpts().CPlusPlus11 ? 8606 diag::warn_cxx98_compat_using_decl_constructor : 8607 diag::err_using_decl_constructor) 8608 << SS.getRange(); 8609 8610 if (getLangOpts().CPlusPlus11) break; 8611 8612 return nullptr; 8613 8614 case UnqualifiedId::IK_DestructorName: 8615 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 8616 << SS.getRange(); 8617 return nullptr; 8618 8619 case UnqualifiedId::IK_TemplateId: 8620 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 8621 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 8622 return nullptr; 8623 } 8624 8625 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 8626 DeclarationName TargetName = TargetNameInfo.getName(); 8627 if (!TargetName) 8628 return nullptr; 8629 8630 // Warn about access declarations. 8631 if (!HasUsingKeyword) { 8632 Diag(Name.getLocStart(), 8633 getLangOpts().CPlusPlus11 ? diag::err_access_decl 8634 : diag::warn_access_decl_deprecated) 8635 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 8636 } 8637 8638 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 8639 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 8640 return nullptr; 8641 8642 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 8643 TargetNameInfo, AttrList, 8644 /* IsInstantiation */ false, 8645 HasTypenameKeyword, TypenameLoc); 8646 if (UD) 8647 PushOnScopeChains(UD, S, /*AddToContext*/ false); 8648 8649 return UD; 8650 } 8651 8652 /// \brief Determine whether a using declaration considers the given 8653 /// declarations as "equivalent", e.g., if they are redeclarations of 8654 /// the same entity or are both typedefs of the same type. 8655 static bool 8656 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 8657 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 8658 return true; 8659 8660 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 8661 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 8662 return Context.hasSameType(TD1->getUnderlyingType(), 8663 TD2->getUnderlyingType()); 8664 8665 return false; 8666 } 8667 8668 8669 /// Determines whether to create a using shadow decl for a particular 8670 /// decl, given the set of decls existing prior to this using lookup. 8671 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 8672 const LookupResult &Previous, 8673 UsingShadowDecl *&PrevShadow) { 8674 // Diagnose finding a decl which is not from a base class of the 8675 // current class. We do this now because there are cases where this 8676 // function will silently decide not to build a shadow decl, which 8677 // will pre-empt further diagnostics. 8678 // 8679 // We don't need to do this in C++11 because we do the check once on 8680 // the qualifier. 8681 // 8682 // FIXME: diagnose the following if we care enough: 8683 // struct A { int foo; }; 8684 // struct B : A { using A::foo; }; 8685 // template <class T> struct C : A {}; 8686 // template <class T> struct D : C<T> { using B::foo; } // <--- 8687 // This is invalid (during instantiation) in C++03 because B::foo 8688 // resolves to the using decl in B, which is not a base class of D<T>. 8689 // We can't diagnose it immediately because C<T> is an unknown 8690 // specialization. The UsingShadowDecl in D<T> then points directly 8691 // to A::foo, which will look well-formed when we instantiate. 8692 // The right solution is to not collapse the shadow-decl chain. 8693 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 8694 DeclContext *OrigDC = Orig->getDeclContext(); 8695 8696 // Handle enums and anonymous structs. 8697 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 8698 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 8699 while (OrigRec->isAnonymousStructOrUnion()) 8700 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 8701 8702 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 8703 if (OrigDC == CurContext) { 8704 Diag(Using->getLocation(), 8705 diag::err_using_decl_nested_name_specifier_is_current_class) 8706 << Using->getQualifierLoc().getSourceRange(); 8707 Diag(Orig->getLocation(), diag::note_using_decl_target); 8708 return true; 8709 } 8710 8711 Diag(Using->getQualifierLoc().getBeginLoc(), 8712 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8713 << Using->getQualifier() 8714 << cast<CXXRecordDecl>(CurContext) 8715 << Using->getQualifierLoc().getSourceRange(); 8716 Diag(Orig->getLocation(), diag::note_using_decl_target); 8717 return true; 8718 } 8719 } 8720 8721 if (Previous.empty()) return false; 8722 8723 NamedDecl *Target = Orig; 8724 if (isa<UsingShadowDecl>(Target)) 8725 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 8726 8727 // If the target happens to be one of the previous declarations, we 8728 // don't have a conflict. 8729 // 8730 // FIXME: but we might be increasing its access, in which case we 8731 // should redeclare it. 8732 NamedDecl *NonTag = nullptr, *Tag = nullptr; 8733 bool FoundEquivalentDecl = false; 8734 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8735 I != E; ++I) { 8736 NamedDecl *D = (*I)->getUnderlyingDecl(); 8737 // We can have UsingDecls in our Previous results because we use the same 8738 // LookupResult for checking whether the UsingDecl itself is a valid 8739 // redeclaration. 8740 if (isa<UsingDecl>(D)) 8741 continue; 8742 8743 if (IsEquivalentForUsingDecl(Context, D, Target)) { 8744 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 8745 PrevShadow = Shadow; 8746 FoundEquivalentDecl = true; 8747 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 8748 // We don't conflict with an existing using shadow decl of an equivalent 8749 // declaration, but we're not a redeclaration of it. 8750 FoundEquivalentDecl = true; 8751 } 8752 8753 if (isVisible(D)) 8754 (isa<TagDecl>(D) ? Tag : NonTag) = D; 8755 } 8756 8757 if (FoundEquivalentDecl) 8758 return false; 8759 8760 if (FunctionDecl *FD = Target->getAsFunction()) { 8761 NamedDecl *OldDecl = nullptr; 8762 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 8763 /*IsForUsingDecl*/ true)) { 8764 case Ovl_Overload: 8765 return false; 8766 8767 case Ovl_NonFunction: 8768 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8769 break; 8770 8771 // We found a decl with the exact signature. 8772 case Ovl_Match: 8773 // If we're in a record, we want to hide the target, so we 8774 // return true (without a diagnostic) to tell the caller not to 8775 // build a shadow decl. 8776 if (CurContext->isRecord()) 8777 return true; 8778 8779 // If we're not in a record, this is an error. 8780 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8781 break; 8782 } 8783 8784 Diag(Target->getLocation(), diag::note_using_decl_target); 8785 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 8786 return true; 8787 } 8788 8789 // Target is not a function. 8790 8791 if (isa<TagDecl>(Target)) { 8792 // No conflict between a tag and a non-tag. 8793 if (!Tag) return false; 8794 8795 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8796 Diag(Target->getLocation(), diag::note_using_decl_target); 8797 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 8798 return true; 8799 } 8800 8801 // No conflict between a tag and a non-tag. 8802 if (!NonTag) return false; 8803 8804 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8805 Diag(Target->getLocation(), diag::note_using_decl_target); 8806 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 8807 return true; 8808 } 8809 8810 /// Determine whether a direct base class is a virtual base class. 8811 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 8812 if (!Derived->getNumVBases()) 8813 return false; 8814 for (auto &B : Derived->bases()) 8815 if (B.getType()->getAsCXXRecordDecl() == Base) 8816 return B.isVirtual(); 8817 llvm_unreachable("not a direct base class"); 8818 } 8819 8820 /// Builds a shadow declaration corresponding to a 'using' declaration. 8821 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 8822 UsingDecl *UD, 8823 NamedDecl *Orig, 8824 UsingShadowDecl *PrevDecl) { 8825 // If we resolved to another shadow declaration, just coalesce them. 8826 NamedDecl *Target = Orig; 8827 if (isa<UsingShadowDecl>(Target)) { 8828 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 8829 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 8830 } 8831 8832 NamedDecl *NonTemplateTarget = Target; 8833 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 8834 NonTemplateTarget = TargetTD->getTemplatedDecl(); 8835 8836 UsingShadowDecl *Shadow; 8837 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 8838 bool IsVirtualBase = 8839 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 8840 UD->getQualifier()->getAsRecordDecl()); 8841 Shadow = ConstructorUsingShadowDecl::Create( 8842 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 8843 } else { 8844 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 8845 Target); 8846 } 8847 UD->addShadowDecl(Shadow); 8848 8849 Shadow->setAccess(UD->getAccess()); 8850 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 8851 Shadow->setInvalidDecl(); 8852 8853 Shadow->setPreviousDecl(PrevDecl); 8854 8855 if (S) 8856 PushOnScopeChains(Shadow, S); 8857 else 8858 CurContext->addDecl(Shadow); 8859 8860 8861 return Shadow; 8862 } 8863 8864 /// Hides a using shadow declaration. This is required by the current 8865 /// using-decl implementation when a resolvable using declaration in a 8866 /// class is followed by a declaration which would hide or override 8867 /// one or more of the using decl's targets; for example: 8868 /// 8869 /// struct Base { void foo(int); }; 8870 /// struct Derived : Base { 8871 /// using Base::foo; 8872 /// void foo(int); 8873 /// }; 8874 /// 8875 /// The governing language is C++03 [namespace.udecl]p12: 8876 /// 8877 /// When a using-declaration brings names from a base class into a 8878 /// derived class scope, member functions in the derived class 8879 /// override and/or hide member functions with the same name and 8880 /// parameter types in a base class (rather than conflicting). 8881 /// 8882 /// There are two ways to implement this: 8883 /// (1) optimistically create shadow decls when they're not hidden 8884 /// by existing declarations, or 8885 /// (2) don't create any shadow decls (or at least don't make them 8886 /// visible) until we've fully parsed/instantiated the class. 8887 /// The problem with (1) is that we might have to retroactively remove 8888 /// a shadow decl, which requires several O(n) operations because the 8889 /// decl structures are (very reasonably) not designed for removal. 8890 /// (2) avoids this but is very fiddly and phase-dependent. 8891 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 8892 if (Shadow->getDeclName().getNameKind() == 8893 DeclarationName::CXXConversionFunctionName) 8894 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 8895 8896 // Remove it from the DeclContext... 8897 Shadow->getDeclContext()->removeDecl(Shadow); 8898 8899 // ...and the scope, if applicable... 8900 if (S) { 8901 S->RemoveDecl(Shadow); 8902 IdResolver.RemoveDecl(Shadow); 8903 } 8904 8905 // ...and the using decl. 8906 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 8907 8908 // TODO: complain somehow if Shadow was used. It shouldn't 8909 // be possible for this to happen, because...? 8910 } 8911 8912 /// Find the base specifier for a base class with the given type. 8913 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 8914 QualType DesiredBase, 8915 bool &AnyDependentBases) { 8916 // Check whether the named type is a direct base class. 8917 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 8918 for (auto &Base : Derived->bases()) { 8919 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 8920 if (CanonicalDesiredBase == BaseType) 8921 return &Base; 8922 if (BaseType->isDependentType()) 8923 AnyDependentBases = true; 8924 } 8925 return nullptr; 8926 } 8927 8928 namespace { 8929 class UsingValidatorCCC : public CorrectionCandidateCallback { 8930 public: 8931 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 8932 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 8933 : HasTypenameKeyword(HasTypenameKeyword), 8934 IsInstantiation(IsInstantiation), OldNNS(NNS), 8935 RequireMemberOf(RequireMemberOf) {} 8936 8937 bool ValidateCandidate(const TypoCorrection &Candidate) override { 8938 NamedDecl *ND = Candidate.getCorrectionDecl(); 8939 8940 // Keywords are not valid here. 8941 if (!ND || isa<NamespaceDecl>(ND)) 8942 return false; 8943 8944 // Completely unqualified names are invalid for a 'using' declaration. 8945 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 8946 return false; 8947 8948 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 8949 // reject. 8950 8951 if (RequireMemberOf) { 8952 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8953 if (FoundRecord && FoundRecord->isInjectedClassName()) { 8954 // No-one ever wants a using-declaration to name an injected-class-name 8955 // of a base class, unless they're declaring an inheriting constructor. 8956 ASTContext &Ctx = ND->getASTContext(); 8957 if (!Ctx.getLangOpts().CPlusPlus11) 8958 return false; 8959 QualType FoundType = Ctx.getRecordType(FoundRecord); 8960 8961 // Check that the injected-class-name is named as a member of its own 8962 // type; we don't want to suggest 'using Derived::Base;', since that 8963 // means something else. 8964 NestedNameSpecifier *Specifier = 8965 Candidate.WillReplaceSpecifier() 8966 ? Candidate.getCorrectionSpecifier() 8967 : OldNNS; 8968 if (!Specifier->getAsType() || 8969 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 8970 return false; 8971 8972 // Check that this inheriting constructor declaration actually names a 8973 // direct base class of the current class. 8974 bool AnyDependentBases = false; 8975 if (!findDirectBaseWithType(RequireMemberOf, 8976 Ctx.getRecordType(FoundRecord), 8977 AnyDependentBases) && 8978 !AnyDependentBases) 8979 return false; 8980 } else { 8981 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 8982 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 8983 return false; 8984 8985 // FIXME: Check that the base class member is accessible? 8986 } 8987 } else { 8988 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8989 if (FoundRecord && FoundRecord->isInjectedClassName()) 8990 return false; 8991 } 8992 8993 if (isa<TypeDecl>(ND)) 8994 return HasTypenameKeyword || !IsInstantiation; 8995 8996 return !HasTypenameKeyword; 8997 } 8998 8999 private: 9000 bool HasTypenameKeyword; 9001 bool IsInstantiation; 9002 NestedNameSpecifier *OldNNS; 9003 CXXRecordDecl *RequireMemberOf; 9004 }; 9005 } // end anonymous namespace 9006 9007 /// Builds a using declaration. 9008 /// 9009 /// \param IsInstantiation - Whether this call arises from an 9010 /// instantiation of an unresolved using declaration. We treat 9011 /// the lookup differently for these declarations. 9012 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9013 SourceLocation UsingLoc, 9014 CXXScopeSpec &SS, 9015 DeclarationNameInfo NameInfo, 9016 AttributeList *AttrList, 9017 bool IsInstantiation, 9018 bool HasTypenameKeyword, 9019 SourceLocation TypenameLoc) { 9020 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9021 SourceLocation IdentLoc = NameInfo.getLoc(); 9022 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9023 9024 // FIXME: We ignore attributes for now. 9025 9026 if (SS.isEmpty()) { 9027 Diag(IdentLoc, diag::err_using_requires_qualname); 9028 return nullptr; 9029 } 9030 9031 // For an inheriting constructor declaration, the name of the using 9032 // declaration is the name of a constructor in this class, not in the 9033 // base class. 9034 DeclarationNameInfo UsingName = NameInfo; 9035 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9036 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9037 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9038 Context.getCanonicalType(Context.getRecordType(RD)))); 9039 9040 // Do the redeclaration lookup in the current scope. 9041 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9042 ForRedeclaration); 9043 Previous.setHideTags(false); 9044 if (S) { 9045 LookupName(Previous, S); 9046 9047 // It is really dumb that we have to do this. 9048 LookupResult::Filter F = Previous.makeFilter(); 9049 while (F.hasNext()) { 9050 NamedDecl *D = F.next(); 9051 if (!isDeclInScope(D, CurContext, S)) 9052 F.erase(); 9053 // If we found a local extern declaration that's not ordinarily visible, 9054 // and this declaration is being added to a non-block scope, ignore it. 9055 // We're only checking for scope conflicts here, not also for violations 9056 // of the linkage rules. 9057 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9058 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9059 F.erase(); 9060 } 9061 F.done(); 9062 } else { 9063 assert(IsInstantiation && "no scope in non-instantiation"); 9064 assert(CurContext->isRecord() && "scope not record in instantiation"); 9065 LookupQualifiedName(Previous, CurContext); 9066 } 9067 9068 // Check for invalid redeclarations. 9069 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9070 SS, IdentLoc, Previous)) 9071 return nullptr; 9072 9073 // Check for bad qualifiers. 9074 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 9075 return nullptr; 9076 9077 DeclContext *LookupContext = computeDeclContext(SS); 9078 NamedDecl *D; 9079 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9080 if (!LookupContext) { 9081 if (HasTypenameKeyword) { 9082 // FIXME: not all declaration name kinds are legal here 9083 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9084 UsingLoc, TypenameLoc, 9085 QualifierLoc, 9086 IdentLoc, NameInfo.getName()); 9087 } else { 9088 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9089 QualifierLoc, NameInfo); 9090 } 9091 D->setAccess(AS); 9092 CurContext->addDecl(D); 9093 return D; 9094 } 9095 9096 auto Build = [&](bool Invalid) { 9097 UsingDecl *UD = 9098 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9099 UsingName, HasTypenameKeyword); 9100 UD->setAccess(AS); 9101 CurContext->addDecl(UD); 9102 UD->setInvalidDecl(Invalid); 9103 return UD; 9104 }; 9105 auto BuildInvalid = [&]{ return Build(true); }; 9106 auto BuildValid = [&]{ return Build(false); }; 9107 9108 if (RequireCompleteDeclContext(SS, LookupContext)) 9109 return BuildInvalid(); 9110 9111 // Look up the target name. 9112 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9113 9114 // Unlike most lookups, we don't always want to hide tag 9115 // declarations: tag names are visible through the using declaration 9116 // even if hidden by ordinary names, *except* in a dependent context 9117 // where it's important for the sanity of two-phase lookup. 9118 if (!IsInstantiation) 9119 R.setHideTags(false); 9120 9121 // For the purposes of this lookup, we have a base object type 9122 // equal to that of the current context. 9123 if (CurContext->isRecord()) { 9124 R.setBaseObjectType( 9125 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9126 } 9127 9128 LookupQualifiedName(R, LookupContext); 9129 9130 // Try to correct typos if possible. If constructor name lookup finds no 9131 // results, that means the named class has no explicit constructors, and we 9132 // suppressed declaring implicit ones (probably because it's dependent or 9133 // invalid). 9134 if (R.empty() && 9135 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9136 if (TypoCorrection Corrected = CorrectTypo( 9137 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9138 llvm::make_unique<UsingValidatorCCC>( 9139 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9140 dyn_cast<CXXRecordDecl>(CurContext)), 9141 CTK_ErrorRecovery)) { 9142 // We reject any correction for which ND would be NULL. 9143 NamedDecl *ND = Corrected.getCorrectionDecl(); 9144 9145 // We reject candidates where DroppedSpecifier == true, hence the 9146 // literal '0' below. 9147 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9148 << NameInfo.getName() << LookupContext << 0 9149 << SS.getRange()); 9150 9151 // If we corrected to an inheriting constructor, handle it as one. 9152 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9153 if (RD && RD->isInjectedClassName()) { 9154 // The parent of the injected class name is the class itself. 9155 RD = cast<CXXRecordDecl>(RD->getParent()); 9156 9157 // Fix up the information we'll use to build the using declaration. 9158 if (Corrected.WillReplaceSpecifier()) { 9159 NestedNameSpecifierLocBuilder Builder; 9160 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9161 QualifierLoc.getSourceRange()); 9162 QualifierLoc = Builder.getWithLocInContext(Context); 9163 } 9164 9165 // In this case, the name we introduce is the name of a derived class 9166 // constructor. 9167 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9168 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9169 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9170 UsingName.setNamedTypeInfo(nullptr); 9171 for (auto *Ctor : LookupConstructors(RD)) 9172 R.addDecl(Ctor); 9173 R.resolveKind(); 9174 } else { 9175 // FIXME: Pick up all the declarations if we found an overloaded 9176 // function. 9177 UsingName.setName(ND->getDeclName()); 9178 R.addDecl(ND); 9179 } 9180 } else { 9181 Diag(IdentLoc, diag::err_no_member) 9182 << NameInfo.getName() << LookupContext << SS.getRange(); 9183 return BuildInvalid(); 9184 } 9185 } 9186 9187 if (R.isAmbiguous()) 9188 return BuildInvalid(); 9189 9190 if (HasTypenameKeyword) { 9191 // If we asked for a typename and got a non-type decl, error out. 9192 if (!R.getAsSingle<TypeDecl>()) { 9193 Diag(IdentLoc, diag::err_using_typename_non_type); 9194 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9195 Diag((*I)->getUnderlyingDecl()->getLocation(), 9196 diag::note_using_decl_target); 9197 return BuildInvalid(); 9198 } 9199 } else { 9200 // If we asked for a non-typename and we got a type, error out, 9201 // but only if this is an instantiation of an unresolved using 9202 // decl. Otherwise just silently find the type name. 9203 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9204 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9205 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9206 return BuildInvalid(); 9207 } 9208 } 9209 9210 // C++14 [namespace.udecl]p6: 9211 // A using-declaration shall not name a namespace. 9212 if (R.getAsSingle<NamespaceDecl>()) { 9213 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9214 << SS.getRange(); 9215 return BuildInvalid(); 9216 } 9217 9218 // C++14 [namespace.udecl]p7: 9219 // A using-declaration shall not name a scoped enumerator. 9220 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9221 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9222 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9223 << SS.getRange(); 9224 return BuildInvalid(); 9225 } 9226 } 9227 9228 UsingDecl *UD = BuildValid(); 9229 9230 // Some additional rules apply to inheriting constructors. 9231 if (UsingName.getName().getNameKind() == 9232 DeclarationName::CXXConstructorName) { 9233 // Suppress access diagnostics; the access check is instead performed at the 9234 // point of use for an inheriting constructor. 9235 R.suppressDiagnostics(); 9236 if (CheckInheritingConstructorUsingDecl(UD)) 9237 return UD; 9238 } 9239 9240 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9241 UsingShadowDecl *PrevDecl = nullptr; 9242 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9243 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9244 } 9245 9246 return UD; 9247 } 9248 9249 /// Additional checks for a using declaration referring to a constructor name. 9250 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9251 assert(!UD->hasTypename() && "expecting a constructor name"); 9252 9253 const Type *SourceType = UD->getQualifier()->getAsType(); 9254 assert(SourceType && 9255 "Using decl naming constructor doesn't have type in scope spec."); 9256 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9257 9258 // Check whether the named type is a direct base class. 9259 bool AnyDependentBases = false; 9260 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9261 AnyDependentBases); 9262 if (!Base && !AnyDependentBases) { 9263 Diag(UD->getUsingLoc(), 9264 diag::err_using_decl_constructor_not_in_direct_base) 9265 << UD->getNameInfo().getSourceRange() 9266 << QualType(SourceType, 0) << TargetClass; 9267 UD->setInvalidDecl(); 9268 return true; 9269 } 9270 9271 if (Base) 9272 Base->setInheritConstructors(); 9273 9274 return false; 9275 } 9276 9277 /// Checks that the given using declaration is not an invalid 9278 /// redeclaration. Note that this is checking only for the using decl 9279 /// itself, not for any ill-formedness among the UsingShadowDecls. 9280 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9281 bool HasTypenameKeyword, 9282 const CXXScopeSpec &SS, 9283 SourceLocation NameLoc, 9284 const LookupResult &Prev) { 9285 // C++03 [namespace.udecl]p8: 9286 // C++0x [namespace.udecl]p10: 9287 // A using-declaration is a declaration and can therefore be used 9288 // repeatedly where (and only where) multiple declarations are 9289 // allowed. 9290 // 9291 // That's in non-member contexts. 9292 if (!CurContext->getRedeclContext()->isRecord()) 9293 return false; 9294 9295 NestedNameSpecifier *Qual = SS.getScopeRep(); 9296 9297 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9298 NamedDecl *D = *I; 9299 9300 bool DTypename; 9301 NestedNameSpecifier *DQual; 9302 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9303 DTypename = UD->hasTypename(); 9304 DQual = UD->getQualifier(); 9305 } else if (UnresolvedUsingValueDecl *UD 9306 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9307 DTypename = false; 9308 DQual = UD->getQualifier(); 9309 } else if (UnresolvedUsingTypenameDecl *UD 9310 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9311 DTypename = true; 9312 DQual = UD->getQualifier(); 9313 } else continue; 9314 9315 // using decls differ if one says 'typename' and the other doesn't. 9316 // FIXME: non-dependent using decls? 9317 if (HasTypenameKeyword != DTypename) continue; 9318 9319 // using decls differ if they name different scopes (but note that 9320 // template instantiation can cause this check to trigger when it 9321 // didn't before instantiation). 9322 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9323 Context.getCanonicalNestedNameSpecifier(DQual)) 9324 continue; 9325 9326 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9327 Diag(D->getLocation(), diag::note_using_decl) << 1; 9328 return true; 9329 } 9330 9331 return false; 9332 } 9333 9334 9335 /// Checks that the given nested-name qualifier used in a using decl 9336 /// in the current context is appropriately related to the current 9337 /// scope. If an error is found, diagnoses it and returns true. 9338 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9339 const CXXScopeSpec &SS, 9340 const DeclarationNameInfo &NameInfo, 9341 SourceLocation NameLoc) { 9342 DeclContext *NamedContext = computeDeclContext(SS); 9343 9344 if (!CurContext->isRecord()) { 9345 // C++03 [namespace.udecl]p3: 9346 // C++0x [namespace.udecl]p8: 9347 // A using-declaration for a class member shall be a member-declaration. 9348 9349 // If we weren't able to compute a valid scope, it must be a 9350 // dependent class scope. 9351 if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) { 9352 auto *RD = NamedContext 9353 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9354 : nullptr; 9355 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9356 RD = nullptr; 9357 9358 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9359 << SS.getRange(); 9360 9361 // If we have a complete, non-dependent source type, try to suggest a 9362 // way to get the same effect. 9363 if (!RD) 9364 return true; 9365 9366 // Find what this using-declaration was referring to. 9367 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9368 R.setHideTags(false); 9369 R.suppressDiagnostics(); 9370 LookupQualifiedName(R, RD); 9371 9372 if (R.getAsSingle<TypeDecl>()) { 9373 if (getLangOpts().CPlusPlus11) { 9374 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9375 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9376 << 0 // alias declaration 9377 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9378 NameInfo.getName().getAsString() + 9379 " = "); 9380 } else { 9381 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9382 SourceLocation InsertLoc = 9383 getLocForEndOfToken(NameInfo.getLocEnd()); 9384 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9385 << 1 // typedef declaration 9386 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9387 << FixItHint::CreateInsertion( 9388 InsertLoc, " " + NameInfo.getName().getAsString()); 9389 } 9390 } else if (R.getAsSingle<VarDecl>()) { 9391 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9392 // repeating the type of the static data member here. 9393 FixItHint FixIt; 9394 if (getLangOpts().CPlusPlus11) { 9395 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9396 FixIt = FixItHint::CreateReplacement( 9397 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9398 } 9399 9400 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9401 << 2 // reference declaration 9402 << FixIt; 9403 } else if (R.getAsSingle<EnumConstantDecl>()) { 9404 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9405 // repeating the type of the enumeration here, and we can't do so if 9406 // the type is anonymous. 9407 FixItHint FixIt; 9408 if (getLangOpts().CPlusPlus11) { 9409 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9410 FixIt = FixItHint::CreateReplacement( 9411 UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = "); 9412 } 9413 9414 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9415 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 9416 << FixIt; 9417 } 9418 return true; 9419 } 9420 9421 // Otherwise, everything is known to be fine. 9422 return false; 9423 } 9424 9425 // The current scope is a record. 9426 9427 // If the named context is dependent, we can't decide much. 9428 if (!NamedContext) { 9429 // FIXME: in C++0x, we can diagnose if we can prove that the 9430 // nested-name-specifier does not refer to a base class, which is 9431 // still possible in some cases. 9432 9433 // Otherwise we have to conservatively report that things might be 9434 // okay. 9435 return false; 9436 } 9437 9438 if (!NamedContext->isRecord()) { 9439 // Ideally this would point at the last name in the specifier, 9440 // but we don't have that level of source info. 9441 Diag(SS.getRange().getBegin(), 9442 diag::err_using_decl_nested_name_specifier_is_not_class) 9443 << SS.getScopeRep() << SS.getRange(); 9444 return true; 9445 } 9446 9447 if (!NamedContext->isDependentContext() && 9448 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 9449 return true; 9450 9451 if (getLangOpts().CPlusPlus11) { 9452 // C++11 [namespace.udecl]p3: 9453 // In a using-declaration used as a member-declaration, the 9454 // nested-name-specifier shall name a base class of the class 9455 // being defined. 9456 9457 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 9458 cast<CXXRecordDecl>(NamedContext))) { 9459 if (CurContext == NamedContext) { 9460 Diag(NameLoc, 9461 diag::err_using_decl_nested_name_specifier_is_current_class) 9462 << SS.getRange(); 9463 return true; 9464 } 9465 9466 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 9467 Diag(SS.getRange().getBegin(), 9468 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9469 << SS.getScopeRep() 9470 << cast<CXXRecordDecl>(CurContext) 9471 << SS.getRange(); 9472 } 9473 return true; 9474 } 9475 9476 return false; 9477 } 9478 9479 // C++03 [namespace.udecl]p4: 9480 // A using-declaration used as a member-declaration shall refer 9481 // to a member of a base class of the class being defined [etc.]. 9482 9483 // Salient point: SS doesn't have to name a base class as long as 9484 // lookup only finds members from base classes. Therefore we can 9485 // diagnose here only if we can prove that that can't happen, 9486 // i.e. if the class hierarchies provably don't intersect. 9487 9488 // TODO: it would be nice if "definitely valid" results were cached 9489 // in the UsingDecl and UsingShadowDecl so that these checks didn't 9490 // need to be repeated. 9491 9492 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 9493 auto Collect = [&Bases](const CXXRecordDecl *Base) { 9494 Bases.insert(Base); 9495 return true; 9496 }; 9497 9498 // Collect all bases. Return false if we find a dependent base. 9499 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 9500 return false; 9501 9502 // Returns true if the base is dependent or is one of the accumulated base 9503 // classes. 9504 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 9505 return !Bases.count(Base); 9506 }; 9507 9508 // Return false if the class has a dependent base or if it or one 9509 // of its bases is present in the base set of the current context. 9510 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 9511 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 9512 return false; 9513 9514 Diag(SS.getRange().getBegin(), 9515 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9516 << SS.getScopeRep() 9517 << cast<CXXRecordDecl>(CurContext) 9518 << SS.getRange(); 9519 9520 return true; 9521 } 9522 9523 Decl *Sema::ActOnAliasDeclaration(Scope *S, 9524 AccessSpecifier AS, 9525 MultiTemplateParamsArg TemplateParamLists, 9526 SourceLocation UsingLoc, 9527 UnqualifiedId &Name, 9528 AttributeList *AttrList, 9529 TypeResult Type, 9530 Decl *DeclFromDeclSpec) { 9531 // Skip up to the relevant declaration scope. 9532 while (S->isTemplateParamScope()) 9533 S = S->getParent(); 9534 assert((S->getFlags() & Scope::DeclScope) && 9535 "got alias-declaration outside of declaration scope"); 9536 9537 if (Type.isInvalid()) 9538 return nullptr; 9539 9540 bool Invalid = false; 9541 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 9542 TypeSourceInfo *TInfo = nullptr; 9543 GetTypeFromParser(Type.get(), &TInfo); 9544 9545 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 9546 return nullptr; 9547 9548 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 9549 UPPC_DeclarationType)) { 9550 Invalid = true; 9551 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9552 TInfo->getTypeLoc().getBeginLoc()); 9553 } 9554 9555 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 9556 LookupName(Previous, S); 9557 9558 // Warn about shadowing the name of a template parameter. 9559 if (Previous.isSingleResult() && 9560 Previous.getFoundDecl()->isTemplateParameter()) { 9561 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 9562 Previous.clear(); 9563 } 9564 9565 assert(Name.Kind == UnqualifiedId::IK_Identifier && 9566 "name in alias declaration must be an identifier"); 9567 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 9568 Name.StartLocation, 9569 Name.Identifier, TInfo); 9570 9571 NewTD->setAccess(AS); 9572 9573 if (Invalid) 9574 NewTD->setInvalidDecl(); 9575 9576 ProcessDeclAttributeList(S, NewTD, AttrList); 9577 9578 CheckTypedefForVariablyModifiedType(S, NewTD); 9579 Invalid |= NewTD->isInvalidDecl(); 9580 9581 bool Redeclaration = false; 9582 9583 NamedDecl *NewND; 9584 if (TemplateParamLists.size()) { 9585 TypeAliasTemplateDecl *OldDecl = nullptr; 9586 TemplateParameterList *OldTemplateParams = nullptr; 9587 9588 if (TemplateParamLists.size() != 1) { 9589 Diag(UsingLoc, diag::err_alias_template_extra_headers) 9590 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 9591 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 9592 } 9593 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 9594 9595 // Check that we can declare a template here. 9596 if (CheckTemplateDeclScope(S, TemplateParams)) 9597 return nullptr; 9598 9599 // Only consider previous declarations in the same scope. 9600 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 9601 /*ExplicitInstantiationOrSpecialization*/false); 9602 if (!Previous.empty()) { 9603 Redeclaration = true; 9604 9605 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 9606 if (!OldDecl && !Invalid) { 9607 Diag(UsingLoc, diag::err_redefinition_different_kind) 9608 << Name.Identifier; 9609 9610 NamedDecl *OldD = Previous.getRepresentativeDecl(); 9611 if (OldD->getLocation().isValid()) 9612 Diag(OldD->getLocation(), diag::note_previous_definition); 9613 9614 Invalid = true; 9615 } 9616 9617 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 9618 if (TemplateParameterListsAreEqual(TemplateParams, 9619 OldDecl->getTemplateParameters(), 9620 /*Complain=*/true, 9621 TPL_TemplateMatch)) 9622 OldTemplateParams = OldDecl->getTemplateParameters(); 9623 else 9624 Invalid = true; 9625 9626 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 9627 if (!Invalid && 9628 !Context.hasSameType(OldTD->getUnderlyingType(), 9629 NewTD->getUnderlyingType())) { 9630 // FIXME: The C++0x standard does not clearly say this is ill-formed, 9631 // but we can't reasonably accept it. 9632 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 9633 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 9634 if (OldTD->getLocation().isValid()) 9635 Diag(OldTD->getLocation(), diag::note_previous_definition); 9636 Invalid = true; 9637 } 9638 } 9639 } 9640 9641 // Merge any previous default template arguments into our parameters, 9642 // and check the parameter list. 9643 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 9644 TPC_TypeAliasTemplate)) 9645 return nullptr; 9646 9647 TypeAliasTemplateDecl *NewDecl = 9648 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 9649 Name.Identifier, TemplateParams, 9650 NewTD); 9651 NewTD->setDescribedAliasTemplate(NewDecl); 9652 9653 NewDecl->setAccess(AS); 9654 9655 if (Invalid) 9656 NewDecl->setInvalidDecl(); 9657 else if (OldDecl) 9658 NewDecl->setPreviousDecl(OldDecl); 9659 9660 NewND = NewDecl; 9661 } else { 9662 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 9663 setTagNameForLinkagePurposes(TD, NewTD); 9664 handleTagNumbering(TD, S); 9665 } 9666 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 9667 NewND = NewTD; 9668 } 9669 9670 PushOnScopeChains(NewND, S); 9671 ActOnDocumentableDecl(NewND); 9672 return NewND; 9673 } 9674 9675 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 9676 SourceLocation AliasLoc, 9677 IdentifierInfo *Alias, CXXScopeSpec &SS, 9678 SourceLocation IdentLoc, 9679 IdentifierInfo *Ident) { 9680 9681 // Lookup the namespace name. 9682 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 9683 LookupParsedName(R, S, &SS); 9684 9685 if (R.isAmbiguous()) 9686 return nullptr; 9687 9688 if (R.empty()) { 9689 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 9690 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9691 return nullptr; 9692 } 9693 } 9694 assert(!R.isAmbiguous() && !R.empty()); 9695 NamedDecl *ND = R.getRepresentativeDecl(); 9696 9697 // Check if we have a previous declaration with the same name. 9698 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 9699 ForRedeclaration); 9700 LookupName(PrevR, S); 9701 9702 // Check we're not shadowing a template parameter. 9703 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 9704 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 9705 PrevR.clear(); 9706 } 9707 9708 // Filter out any other lookup result from an enclosing scope. 9709 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 9710 /*AllowInlineNamespace*/false); 9711 9712 // Find the previous declaration and check that we can redeclare it. 9713 NamespaceAliasDecl *Prev = nullptr; 9714 if (PrevR.isSingleResult()) { 9715 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 9716 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 9717 // We already have an alias with the same name that points to the same 9718 // namespace; check that it matches. 9719 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 9720 Prev = AD; 9721 } else if (isVisible(PrevDecl)) { 9722 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 9723 << Alias; 9724 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 9725 << AD->getNamespace(); 9726 return nullptr; 9727 } 9728 } else if (isVisible(PrevDecl)) { 9729 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 9730 ? diag::err_redefinition 9731 : diag::err_redefinition_different_kind; 9732 Diag(AliasLoc, DiagID) << Alias; 9733 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9734 return nullptr; 9735 } 9736 } 9737 9738 // The use of a nested name specifier may trigger deprecation warnings. 9739 DiagnoseUseOfDecl(ND, IdentLoc); 9740 9741 NamespaceAliasDecl *AliasDecl = 9742 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 9743 Alias, SS.getWithLocInContext(Context), 9744 IdentLoc, ND); 9745 if (Prev) 9746 AliasDecl->setPreviousDecl(Prev); 9747 9748 PushOnScopeChains(AliasDecl, S); 9749 return AliasDecl; 9750 } 9751 9752 Sema::ImplicitExceptionSpecification 9753 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 9754 CXXMethodDecl *MD) { 9755 CXXRecordDecl *ClassDecl = MD->getParent(); 9756 9757 // C++ [except.spec]p14: 9758 // An implicitly declared special member function (Clause 12) shall have an 9759 // exception-specification. [...] 9760 ImplicitExceptionSpecification ExceptSpec(*this); 9761 if (ClassDecl->isInvalidDecl()) 9762 return ExceptSpec; 9763 9764 // Direct base-class constructors. 9765 for (const auto &B : ClassDecl->bases()) { 9766 if (B.isVirtual()) // Handled below. 9767 continue; 9768 9769 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 9770 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9771 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 9772 // If this is a deleted function, add it anyway. This might be conformant 9773 // with the standard. This might not. I'm not sure. It might not matter. 9774 if (Constructor) 9775 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 9776 } 9777 } 9778 9779 // Virtual base-class constructors. 9780 for (const auto &B : ClassDecl->vbases()) { 9781 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 9782 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9783 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 9784 // If this is a deleted function, add it anyway. This might be conformant 9785 // with the standard. This might not. I'm not sure. It might not matter. 9786 if (Constructor) 9787 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 9788 } 9789 } 9790 9791 // Field constructors. 9792 for (const auto *F : ClassDecl->fields()) { 9793 if (F->hasInClassInitializer()) { 9794 if (Expr *E = F->getInClassInitializer()) 9795 ExceptSpec.CalledExpr(E); 9796 } else if (const RecordType *RecordTy 9797 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 9798 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9799 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 9800 // If this is a deleted function, add it anyway. This might be conformant 9801 // with the standard. This might not. I'm not sure. It might not matter. 9802 // In particular, the problem is that this function never gets called. It 9803 // might just be ill-formed because this function attempts to refer to 9804 // a deleted function here. 9805 if (Constructor) 9806 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9807 } 9808 } 9809 9810 return ExceptSpec; 9811 } 9812 9813 Sema::ImplicitExceptionSpecification 9814 Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc, 9815 CXXConstructorDecl *CD) { 9816 CXXRecordDecl *ClassDecl = CD->getParent(); 9817 9818 // C++ [except.spec]p14: 9819 // An inheriting constructor [...] shall have an exception-specification. [...] 9820 ImplicitExceptionSpecification ExceptSpec(*this); 9821 if (ClassDecl->isInvalidDecl()) 9822 return ExceptSpec; 9823 9824 auto Inherited = CD->getInheritedConstructor(); 9825 InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl()); 9826 9827 // Direct and virtual base-class constructors. 9828 for (bool VBase : {false, true}) { 9829 for (CXXBaseSpecifier &B : 9830 VBase ? ClassDecl->vbases() : ClassDecl->bases()) { 9831 // Don't visit direct vbases twice. 9832 if (B.isVirtual() != VBase) 9833 continue; 9834 9835 CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl(); 9836 if (!BaseClass) 9837 continue; 9838 9839 CXXConstructorDecl *Constructor = 9840 ICI.findConstructorForBase(BaseClass, Inherited.getConstructor()) 9841 .first; 9842 if (!Constructor) 9843 Constructor = LookupDefaultConstructor(BaseClass); 9844 if (Constructor) 9845 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 9846 } 9847 } 9848 9849 // Field constructors. 9850 for (const auto *F : ClassDecl->fields()) { 9851 if (F->hasInClassInitializer()) { 9852 if (Expr *E = F->getInClassInitializer()) 9853 ExceptSpec.CalledExpr(E); 9854 } else if (const RecordType *RecordTy 9855 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 9856 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9857 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 9858 if (Constructor) 9859 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9860 } 9861 } 9862 9863 return ExceptSpec; 9864 } 9865 9866 namespace { 9867 /// RAII object to register a special member as being currently declared. 9868 struct DeclaringSpecialMember { 9869 Sema &S; 9870 Sema::SpecialMemberDecl D; 9871 Sema::ContextRAII SavedContext; 9872 bool WasAlreadyBeingDeclared; 9873 9874 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 9875 : S(S), D(RD, CSM), SavedContext(S, RD) { 9876 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 9877 if (WasAlreadyBeingDeclared) 9878 // This almost never happens, but if it does, ensure that our cache 9879 // doesn't contain a stale result. 9880 S.SpecialMemberCache.clear(); 9881 9882 // FIXME: Register a note to be produced if we encounter an error while 9883 // declaring the special member. 9884 } 9885 ~DeclaringSpecialMember() { 9886 if (!WasAlreadyBeingDeclared) 9887 S.SpecialMembersBeingDeclared.erase(D); 9888 } 9889 9890 /// \brief Are we already trying to declare this special member? 9891 bool isAlreadyBeingDeclared() const { 9892 return WasAlreadyBeingDeclared; 9893 } 9894 }; 9895 } 9896 9897 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 9898 // Look up any existing declarations, but don't trigger declaration of all 9899 // implicit special members with this name. 9900 DeclarationName Name = FD->getDeclName(); 9901 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 9902 ForRedeclaration); 9903 for (auto *D : FD->getParent()->lookup(Name)) 9904 if (auto *Acceptable = R.getAcceptableDecl(D)) 9905 R.addDecl(Acceptable); 9906 R.resolveKind(); 9907 R.suppressDiagnostics(); 9908 9909 CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false); 9910 } 9911 9912 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 9913 CXXRecordDecl *ClassDecl) { 9914 // C++ [class.ctor]p5: 9915 // A default constructor for a class X is a constructor of class X 9916 // that can be called without an argument. If there is no 9917 // user-declared constructor for class X, a default constructor is 9918 // implicitly declared. An implicitly-declared default constructor 9919 // is an inline public member of its class. 9920 assert(ClassDecl->needsImplicitDefaultConstructor() && 9921 "Should not build implicit default constructor!"); 9922 9923 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 9924 if (DSM.isAlreadyBeingDeclared()) 9925 return nullptr; 9926 9927 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9928 CXXDefaultConstructor, 9929 false); 9930 9931 // Create the actual constructor declaration. 9932 CanQualType ClassType 9933 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9934 SourceLocation ClassLoc = ClassDecl->getLocation(); 9935 DeclarationName Name 9936 = Context.DeclarationNames.getCXXConstructorName(ClassType); 9937 DeclarationNameInfo NameInfo(Name, ClassLoc); 9938 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 9939 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 9940 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 9941 /*isImplicitlyDeclared=*/true, Constexpr); 9942 DefaultCon->setAccess(AS_public); 9943 DefaultCon->setDefaulted(); 9944 9945 if (getLangOpts().CUDA) { 9946 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 9947 DefaultCon, 9948 /* ConstRHS */ false, 9949 /* Diagnose */ false); 9950 } 9951 9952 // Build an exception specification pointing back at this constructor. 9953 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 9954 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9955 9956 // We don't need to use SpecialMemberIsTrivial here; triviality for default 9957 // constructors is easy to compute. 9958 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 9959 9960 // Note that we have declared this constructor. 9961 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 9962 9963 Scope *S = getScopeForContext(ClassDecl); 9964 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 9965 9966 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 9967 SetDeclDeleted(DefaultCon, ClassLoc); 9968 9969 if (S) 9970 PushOnScopeChains(DefaultCon, S, false); 9971 ClassDecl->addDecl(DefaultCon); 9972 9973 return DefaultCon; 9974 } 9975 9976 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 9977 CXXConstructorDecl *Constructor) { 9978 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 9979 !Constructor->doesThisDeclarationHaveABody() && 9980 !Constructor->isDeleted()) && 9981 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 9982 9983 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9984 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 9985 9986 SynthesizedFunctionScope Scope(*this, Constructor); 9987 DiagnosticErrorTrap Trap(Diags); 9988 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9989 Trap.hasErrorOccurred()) { 9990 Diag(CurrentLocation, diag::note_member_synthesized_at) 9991 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 9992 Constructor->setInvalidDecl(); 9993 return; 9994 } 9995 9996 // The exception specification is needed because we are defining the 9997 // function. 9998 ResolveExceptionSpec(CurrentLocation, 9999 Constructor->getType()->castAs<FunctionProtoType>()); 10000 10001 SourceLocation Loc = Constructor->getLocEnd().isValid() 10002 ? Constructor->getLocEnd() 10003 : Constructor->getLocation(); 10004 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10005 10006 Constructor->markUsed(Context); 10007 MarkVTableUsed(CurrentLocation, ClassDecl); 10008 10009 if (ASTMutationListener *L = getASTMutationListener()) { 10010 L->CompletedImplicitDefinition(Constructor); 10011 } 10012 10013 DiagnoseUninitializedFields(*this, Constructor); 10014 } 10015 10016 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10017 // Perform any delayed checks on exception specifications. 10018 CheckDelayedMemberExceptionSpecs(); 10019 } 10020 10021 /// Find or create the fake constructor we synthesize to model constructing an 10022 /// object of a derived class via a constructor of a base class. 10023 CXXConstructorDecl * 10024 Sema::findInheritingConstructor(SourceLocation Loc, 10025 CXXConstructorDecl *BaseCtor, 10026 ConstructorUsingShadowDecl *Shadow) { 10027 CXXRecordDecl *Derived = Shadow->getParent(); 10028 SourceLocation UsingLoc = Shadow->getLocation(); 10029 10030 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10031 // For now we use the name of the base class constructor as a member of the 10032 // derived class to indicate a (fake) inherited constructor name. 10033 DeclarationName Name = BaseCtor->getDeclName(); 10034 10035 // Check to see if we already have a fake constructor for this inherited 10036 // constructor call. 10037 for (NamedDecl *Ctor : Derived->lookup(Name)) 10038 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10039 ->getInheritedConstructor() 10040 .getConstructor(), 10041 BaseCtor)) 10042 return cast<CXXConstructorDecl>(Ctor); 10043 10044 DeclarationNameInfo NameInfo(Name, UsingLoc); 10045 TypeSourceInfo *TInfo = 10046 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10047 FunctionProtoTypeLoc ProtoLoc = 10048 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10049 10050 // Check the inherited constructor is valid and find the list of base classes 10051 // from which it was inherited. 10052 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10053 10054 bool Constexpr = 10055 BaseCtor->isConstexpr() && 10056 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10057 false, BaseCtor, &ICI); 10058 10059 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10060 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10061 BaseCtor->isExplicit(), /*Inline=*/true, 10062 /*ImplicitlyDeclared=*/true, Constexpr, 10063 InheritedConstructor(Shadow, BaseCtor)); 10064 if (Shadow->isInvalidDecl()) 10065 DerivedCtor->setInvalidDecl(); 10066 10067 // Build an unevaluated exception specification for this fake constructor. 10068 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10069 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10070 EPI.ExceptionSpec.Type = EST_Unevaluated; 10071 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10072 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10073 FPT->getParamTypes(), EPI)); 10074 10075 // Build the parameter declarations. 10076 SmallVector<ParmVarDecl *, 16> ParamDecls; 10077 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10078 TypeSourceInfo *TInfo = 10079 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10080 ParmVarDecl *PD = ParmVarDecl::Create( 10081 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10082 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10083 PD->setScopeInfo(0, I); 10084 PD->setImplicit(); 10085 // Ensure attributes are propagated onto parameters (this matters for 10086 // format, pass_object_size, ...). 10087 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10088 ParamDecls.push_back(PD); 10089 ProtoLoc.setParam(I, PD); 10090 } 10091 10092 // Set up the new constructor. 10093 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10094 DerivedCtor->setAccess(BaseCtor->getAccess()); 10095 DerivedCtor->setParams(ParamDecls); 10096 Derived->addDecl(DerivedCtor); 10097 10098 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10099 SetDeclDeleted(DerivedCtor, UsingLoc); 10100 10101 return DerivedCtor; 10102 } 10103 10104 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10105 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10106 Ctor->getInheritedConstructor().getShadowDecl()); 10107 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10108 /*Diagnose*/true); 10109 } 10110 10111 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10112 CXXConstructorDecl *Constructor) { 10113 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10114 assert(Constructor->getInheritedConstructor() && 10115 !Constructor->doesThisDeclarationHaveABody() && 10116 !Constructor->isDeleted()); 10117 if (Constructor->isInvalidDecl()) 10118 return; 10119 10120 ConstructorUsingShadowDecl *Shadow = 10121 Constructor->getInheritedConstructor().getShadowDecl(); 10122 CXXConstructorDecl *InheritedCtor = 10123 Constructor->getInheritedConstructor().getConstructor(); 10124 10125 // [class.inhctor.init]p1: 10126 // initialization proceeds as if a defaulted default constructor is used to 10127 // initialize the D object and each base class subobject from which the 10128 // constructor was inherited 10129 10130 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10131 CXXRecordDecl *RD = Shadow->getParent(); 10132 SourceLocation InitLoc = Shadow->getLocation(); 10133 10134 // Initializations are performed "as if by a defaulted default constructor", 10135 // so enter the appropriate scope. 10136 SynthesizedFunctionScope Scope(*this, Constructor); 10137 DiagnosticErrorTrap Trap(Diags); 10138 10139 // Build explicit initializers for all base classes from which the 10140 // constructor was inherited. 10141 SmallVector<CXXCtorInitializer*, 8> Inits; 10142 for (bool VBase : {false, true}) { 10143 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10144 if (B.isVirtual() != VBase) 10145 continue; 10146 10147 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10148 if (!BaseRD) 10149 continue; 10150 10151 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10152 if (!BaseCtor.first) 10153 continue; 10154 10155 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10156 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10157 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10158 10159 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10160 Inits.push_back(new (Context) CXXCtorInitializer( 10161 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10162 SourceLocation())); 10163 } 10164 } 10165 10166 // We now proceed as if for a defaulted default constructor, with the relevant 10167 // initializers replaced. 10168 10169 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits); 10170 if (HadError || Trap.hasErrorOccurred()) { 10171 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD; 10172 Constructor->setInvalidDecl(); 10173 return; 10174 } 10175 10176 // The exception specification is needed because we are defining the 10177 // function. 10178 ResolveExceptionSpec(CurrentLocation, 10179 Constructor->getType()->castAs<FunctionProtoType>()); 10180 10181 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10182 10183 Constructor->markUsed(Context); 10184 MarkVTableUsed(CurrentLocation, ClassDecl); 10185 10186 if (ASTMutationListener *L = getASTMutationListener()) { 10187 L->CompletedImplicitDefinition(Constructor); 10188 } 10189 10190 DiagnoseUninitializedFields(*this, Constructor); 10191 } 10192 10193 Sema::ImplicitExceptionSpecification 10194 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 10195 CXXRecordDecl *ClassDecl = MD->getParent(); 10196 10197 // C++ [except.spec]p14: 10198 // An implicitly declared special member function (Clause 12) shall have 10199 // an exception-specification. 10200 ImplicitExceptionSpecification ExceptSpec(*this); 10201 if (ClassDecl->isInvalidDecl()) 10202 return ExceptSpec; 10203 10204 // Direct base-class destructors. 10205 for (const auto &B : ClassDecl->bases()) { 10206 if (B.isVirtual()) // Handled below. 10207 continue; 10208 10209 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 10210 ExceptSpec.CalledDecl(B.getLocStart(), 10211 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 10212 } 10213 10214 // Virtual base-class destructors. 10215 for (const auto &B : ClassDecl->vbases()) { 10216 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 10217 ExceptSpec.CalledDecl(B.getLocStart(), 10218 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 10219 } 10220 10221 // Field destructors. 10222 for (const auto *F : ClassDecl->fields()) { 10223 if (const RecordType *RecordTy 10224 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 10225 ExceptSpec.CalledDecl(F->getLocation(), 10226 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 10227 } 10228 10229 return ExceptSpec; 10230 } 10231 10232 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10233 // C++ [class.dtor]p2: 10234 // If a class has no user-declared destructor, a destructor is 10235 // declared implicitly. An implicitly-declared destructor is an 10236 // inline public member of its class. 10237 assert(ClassDecl->needsImplicitDestructor()); 10238 10239 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10240 if (DSM.isAlreadyBeingDeclared()) 10241 return nullptr; 10242 10243 // Create the actual destructor declaration. 10244 CanQualType ClassType 10245 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10246 SourceLocation ClassLoc = ClassDecl->getLocation(); 10247 DeclarationName Name 10248 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10249 DeclarationNameInfo NameInfo(Name, ClassLoc); 10250 CXXDestructorDecl *Destructor 10251 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10252 QualType(), nullptr, /*isInline=*/true, 10253 /*isImplicitlyDeclared=*/true); 10254 Destructor->setAccess(AS_public); 10255 Destructor->setDefaulted(); 10256 10257 if (getLangOpts().CUDA) { 10258 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10259 Destructor, 10260 /* ConstRHS */ false, 10261 /* Diagnose */ false); 10262 } 10263 10264 // Build an exception specification pointing back at this destructor. 10265 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10266 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10267 10268 // We don't need to use SpecialMemberIsTrivial here; triviality for 10269 // destructors is easy to compute. 10270 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10271 10272 // Note that we have declared this destructor. 10273 ++ASTContext::NumImplicitDestructorsDeclared; 10274 10275 Scope *S = getScopeForContext(ClassDecl); 10276 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10277 10278 // We can't check whether an implicit destructor is deleted before we complete 10279 // the definition of the class, because its validity depends on the alignment 10280 // of the class. We'll check this from ActOnFields once the class is complete. 10281 if (ClassDecl->isCompleteDefinition() && 10282 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10283 SetDeclDeleted(Destructor, ClassLoc); 10284 10285 // Introduce this destructor into its scope. 10286 if (S) 10287 PushOnScopeChains(Destructor, S, false); 10288 ClassDecl->addDecl(Destructor); 10289 10290 return Destructor; 10291 } 10292 10293 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10294 CXXDestructorDecl *Destructor) { 10295 assert((Destructor->isDefaulted() && 10296 !Destructor->doesThisDeclarationHaveABody() && 10297 !Destructor->isDeleted()) && 10298 "DefineImplicitDestructor - call it for implicit default dtor"); 10299 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10300 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10301 10302 if (Destructor->isInvalidDecl()) 10303 return; 10304 10305 SynthesizedFunctionScope Scope(*this, Destructor); 10306 10307 DiagnosticErrorTrap Trap(Diags); 10308 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10309 Destructor->getParent()); 10310 10311 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 10312 Diag(CurrentLocation, diag::note_member_synthesized_at) 10313 << CXXDestructor << Context.getTagDeclType(ClassDecl); 10314 10315 Destructor->setInvalidDecl(); 10316 return; 10317 } 10318 10319 // The exception specification is needed because we are defining the 10320 // function. 10321 ResolveExceptionSpec(CurrentLocation, 10322 Destructor->getType()->castAs<FunctionProtoType>()); 10323 10324 SourceLocation Loc = Destructor->getLocEnd().isValid() 10325 ? Destructor->getLocEnd() 10326 : Destructor->getLocation(); 10327 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10328 Destructor->markUsed(Context); 10329 MarkVTableUsed(CurrentLocation, ClassDecl); 10330 10331 if (ASTMutationListener *L = getASTMutationListener()) { 10332 L->CompletedImplicitDefinition(Destructor); 10333 } 10334 } 10335 10336 /// \brief Perform any semantic analysis which needs to be delayed until all 10337 /// pending class member declarations have been parsed. 10338 void Sema::ActOnFinishCXXMemberDecls() { 10339 // If the context is an invalid C++ class, just suppress these checks. 10340 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10341 if (Record->isInvalidDecl()) { 10342 DelayedDefaultedMemberExceptionSpecs.clear(); 10343 DelayedExceptionSpecChecks.clear(); 10344 return; 10345 } 10346 } 10347 } 10348 10349 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) { 10350 // Don't do anything for template patterns. 10351 if (Class->getDescribedClassTemplate()) 10352 return; 10353 10354 CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention( 10355 /*IsVariadic=*/false, /*IsCXXMethod=*/true); 10356 10357 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 10358 for (Decl *Member : Class->decls()) { 10359 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 10360 if (!CD) { 10361 // Recurse on nested classes. 10362 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member)) 10363 getDefaultArgExprsForConstructors(S, NestedRD); 10364 continue; 10365 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) { 10366 continue; 10367 } 10368 10369 CallingConv ActualCallingConv = 10370 CD->getType()->getAs<FunctionProtoType>()->getCallConv(); 10371 10372 // Skip default constructors with typical calling conventions and no default 10373 // arguments. 10374 unsigned NumParams = CD->getNumParams(); 10375 if (ExpectedCallingConv == ActualCallingConv && NumParams == 0) 10376 continue; 10377 10378 if (LastExportedDefaultCtor) { 10379 S.Diag(LastExportedDefaultCtor->getLocation(), 10380 diag::err_attribute_dll_ambiguous_default_ctor) << Class; 10381 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 10382 << CD->getDeclName(); 10383 return; 10384 } 10385 LastExportedDefaultCtor = CD; 10386 10387 for (unsigned I = 0; I != NumParams; ++I) { 10388 // Skip any default arguments that we've already instantiated. 10389 if (S.Context.getDefaultArgExprForConstructor(CD, I)) 10390 continue; 10391 10392 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD, 10393 CD->getParamDecl(I)).get(); 10394 S.DiscardCleanupsInEvaluationContext(); 10395 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 10396 } 10397 } 10398 } 10399 10400 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10401 auto *RD = dyn_cast<CXXRecordDecl>(D); 10402 10403 // Default constructors that are annotated with __declspec(dllexport) which 10404 // have default arguments or don't use the standard calling convention are 10405 // wrapped with a thunk called the default constructor closure. 10406 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft()) 10407 getDefaultArgExprsForConstructors(*this, RD); 10408 10409 referenceDLLExportedClassMethods(); 10410 } 10411 10412 void Sema::referenceDLLExportedClassMethods() { 10413 if (!DelayedDllExportClasses.empty()) { 10414 // Calling ReferenceDllExportedMethods might cause the current function to 10415 // be called again, so use a local copy of DelayedDllExportClasses. 10416 SmallVector<CXXRecordDecl *, 4> WorkList; 10417 std::swap(DelayedDllExportClasses, WorkList); 10418 for (CXXRecordDecl *Class : WorkList) 10419 ReferenceDllExportedMethods(*this, Class); 10420 } 10421 } 10422 10423 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10424 CXXDestructorDecl *Destructor) { 10425 assert(getLangOpts().CPlusPlus11 && 10426 "adjusting dtor exception specs was introduced in c++11"); 10427 10428 // C++11 [class.dtor]p3: 10429 // A declaration of a destructor that does not have an exception- 10430 // specification is implicitly considered to have the same exception- 10431 // specification as an implicit declaration. 10432 const FunctionProtoType *DtorType = Destructor->getType()-> 10433 getAs<FunctionProtoType>(); 10434 if (DtorType->hasExceptionSpec()) 10435 return; 10436 10437 // Replace the destructor's type, building off the existing one. Fortunately, 10438 // the only thing of interest in the destructor type is its extended info. 10439 // The return and arguments are fixed. 10440 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10441 EPI.ExceptionSpec.Type = EST_Unevaluated; 10442 EPI.ExceptionSpec.SourceDecl = Destructor; 10443 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10444 10445 // FIXME: If the destructor has a body that could throw, and the newly created 10446 // spec doesn't allow exceptions, we should emit a warning, because this 10447 // change in behavior can break conforming C++03 programs at runtime. 10448 // However, we don't have a body or an exception specification yet, so it 10449 // needs to be done somewhere else. 10450 } 10451 10452 namespace { 10453 /// \brief An abstract base class for all helper classes used in building the 10454 // copy/move operators. These classes serve as factory functions and help us 10455 // avoid using the same Expr* in the AST twice. 10456 class ExprBuilder { 10457 ExprBuilder(const ExprBuilder&) = delete; 10458 ExprBuilder &operator=(const ExprBuilder&) = delete; 10459 10460 protected: 10461 static Expr *assertNotNull(Expr *E) { 10462 assert(E && "Expression construction must not fail."); 10463 return E; 10464 } 10465 10466 public: 10467 ExprBuilder() {} 10468 virtual ~ExprBuilder() {} 10469 10470 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10471 }; 10472 10473 class RefBuilder: public ExprBuilder { 10474 VarDecl *Var; 10475 QualType VarType; 10476 10477 public: 10478 Expr *build(Sema &S, SourceLocation Loc) const override { 10479 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10480 } 10481 10482 RefBuilder(VarDecl *Var, QualType VarType) 10483 : Var(Var), VarType(VarType) {} 10484 }; 10485 10486 class ThisBuilder: public ExprBuilder { 10487 public: 10488 Expr *build(Sema &S, SourceLocation Loc) const override { 10489 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 10490 } 10491 }; 10492 10493 class CastBuilder: public ExprBuilder { 10494 const ExprBuilder &Builder; 10495 QualType Type; 10496 ExprValueKind Kind; 10497 const CXXCastPath &Path; 10498 10499 public: 10500 Expr *build(Sema &S, SourceLocation Loc) const override { 10501 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 10502 CK_UncheckedDerivedToBase, Kind, 10503 &Path).get()); 10504 } 10505 10506 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 10507 const CXXCastPath &Path) 10508 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 10509 }; 10510 10511 class DerefBuilder: public ExprBuilder { 10512 const ExprBuilder &Builder; 10513 10514 public: 10515 Expr *build(Sema &S, SourceLocation Loc) const override { 10516 return assertNotNull( 10517 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 10518 } 10519 10520 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10521 }; 10522 10523 class MemberBuilder: public ExprBuilder { 10524 const ExprBuilder &Builder; 10525 QualType Type; 10526 CXXScopeSpec SS; 10527 bool IsArrow; 10528 LookupResult &MemberLookup; 10529 10530 public: 10531 Expr *build(Sema &S, SourceLocation Loc) const override { 10532 return assertNotNull(S.BuildMemberReferenceExpr( 10533 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 10534 nullptr, MemberLookup, nullptr, nullptr).get()); 10535 } 10536 10537 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 10538 LookupResult &MemberLookup) 10539 : Builder(Builder), Type(Type), IsArrow(IsArrow), 10540 MemberLookup(MemberLookup) {} 10541 }; 10542 10543 class MoveCastBuilder: public ExprBuilder { 10544 const ExprBuilder &Builder; 10545 10546 public: 10547 Expr *build(Sema &S, SourceLocation Loc) const override { 10548 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 10549 } 10550 10551 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10552 }; 10553 10554 class LvalueConvBuilder: public ExprBuilder { 10555 const ExprBuilder &Builder; 10556 10557 public: 10558 Expr *build(Sema &S, SourceLocation Loc) const override { 10559 return assertNotNull( 10560 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 10561 } 10562 10563 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10564 }; 10565 10566 class SubscriptBuilder: public ExprBuilder { 10567 const ExprBuilder &Base; 10568 const ExprBuilder &Index; 10569 10570 public: 10571 Expr *build(Sema &S, SourceLocation Loc) const override { 10572 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 10573 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 10574 } 10575 10576 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 10577 : Base(Base), Index(Index) {} 10578 }; 10579 10580 } // end anonymous namespace 10581 10582 /// When generating a defaulted copy or move assignment operator, if a field 10583 /// should be copied with __builtin_memcpy rather than via explicit assignments, 10584 /// do so. This optimization only applies for arrays of scalars, and for arrays 10585 /// of class type where the selected copy/move-assignment operator is trivial. 10586 static StmtResult 10587 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 10588 const ExprBuilder &ToB, const ExprBuilder &FromB) { 10589 // Compute the size of the memory buffer to be copied. 10590 QualType SizeType = S.Context.getSizeType(); 10591 llvm::APInt Size(S.Context.getTypeSize(SizeType), 10592 S.Context.getTypeSizeInChars(T).getQuantity()); 10593 10594 // Take the address of the field references for "from" and "to". We 10595 // directly construct UnaryOperators here because semantic analysis 10596 // does not permit us to take the address of an xvalue. 10597 Expr *From = FromB.build(S, Loc); 10598 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 10599 S.Context.getPointerType(From->getType()), 10600 VK_RValue, OK_Ordinary, Loc); 10601 Expr *To = ToB.build(S, Loc); 10602 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 10603 S.Context.getPointerType(To->getType()), 10604 VK_RValue, OK_Ordinary, Loc); 10605 10606 const Type *E = T->getBaseElementTypeUnsafe(); 10607 bool NeedsCollectableMemCpy = 10608 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 10609 10610 // Create a reference to the __builtin_objc_memmove_collectable function 10611 StringRef MemCpyName = NeedsCollectableMemCpy ? 10612 "__builtin_objc_memmove_collectable" : 10613 "__builtin_memcpy"; 10614 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 10615 Sema::LookupOrdinaryName); 10616 S.LookupName(R, S.TUScope, true); 10617 10618 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 10619 if (!MemCpy) 10620 // Something went horribly wrong earlier, and we will have complained 10621 // about it. 10622 return StmtError(); 10623 10624 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 10625 VK_RValue, Loc, nullptr); 10626 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 10627 10628 Expr *CallArgs[] = { 10629 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 10630 }; 10631 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 10632 Loc, CallArgs, Loc); 10633 10634 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 10635 return Call.getAs<Stmt>(); 10636 } 10637 10638 /// \brief Builds a statement that copies/moves the given entity from \p From to 10639 /// \c To. 10640 /// 10641 /// This routine is used to copy/move the members of a class with an 10642 /// implicitly-declared copy/move assignment operator. When the entities being 10643 /// copied are arrays, this routine builds for loops to copy them. 10644 /// 10645 /// \param S The Sema object used for type-checking. 10646 /// 10647 /// \param Loc The location where the implicit copy/move is being generated. 10648 /// 10649 /// \param T The type of the expressions being copied/moved. Both expressions 10650 /// must have this type. 10651 /// 10652 /// \param To The expression we are copying/moving to. 10653 /// 10654 /// \param From The expression we are copying/moving from. 10655 /// 10656 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 10657 /// Otherwise, it's a non-static member subobject. 10658 /// 10659 /// \param Copying Whether we're copying or moving. 10660 /// 10661 /// \param Depth Internal parameter recording the depth of the recursion. 10662 /// 10663 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 10664 /// if a memcpy should be used instead. 10665 static StmtResult 10666 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 10667 const ExprBuilder &To, const ExprBuilder &From, 10668 bool CopyingBaseSubobject, bool Copying, 10669 unsigned Depth = 0) { 10670 // C++11 [class.copy]p28: 10671 // Each subobject is assigned in the manner appropriate to its type: 10672 // 10673 // - if the subobject is of class type, as if by a call to operator= with 10674 // the subobject as the object expression and the corresponding 10675 // subobject of x as a single function argument (as if by explicit 10676 // qualification; that is, ignoring any possible virtual overriding 10677 // functions in more derived classes); 10678 // 10679 // C++03 [class.copy]p13: 10680 // - if the subobject is of class type, the copy assignment operator for 10681 // the class is used (as if by explicit qualification; that is, 10682 // ignoring any possible virtual overriding functions in more derived 10683 // classes); 10684 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 10685 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 10686 10687 // Look for operator=. 10688 DeclarationName Name 10689 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10690 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 10691 S.LookupQualifiedName(OpLookup, ClassDecl, false); 10692 10693 // Prior to C++11, filter out any result that isn't a copy/move-assignment 10694 // operator. 10695 if (!S.getLangOpts().CPlusPlus11) { 10696 LookupResult::Filter F = OpLookup.makeFilter(); 10697 while (F.hasNext()) { 10698 NamedDecl *D = F.next(); 10699 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 10700 if (Method->isCopyAssignmentOperator() || 10701 (!Copying && Method->isMoveAssignmentOperator())) 10702 continue; 10703 10704 F.erase(); 10705 } 10706 F.done(); 10707 } 10708 10709 // Suppress the protected check (C++ [class.protected]) for each of the 10710 // assignment operators we found. This strange dance is required when 10711 // we're assigning via a base classes's copy-assignment operator. To 10712 // ensure that we're getting the right base class subobject (without 10713 // ambiguities), we need to cast "this" to that subobject type; to 10714 // ensure that we don't go through the virtual call mechanism, we need 10715 // to qualify the operator= name with the base class (see below). However, 10716 // this means that if the base class has a protected copy assignment 10717 // operator, the protected member access check will fail. So, we 10718 // rewrite "protected" access to "public" access in this case, since we 10719 // know by construction that we're calling from a derived class. 10720 if (CopyingBaseSubobject) { 10721 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 10722 L != LEnd; ++L) { 10723 if (L.getAccess() == AS_protected) 10724 L.setAccess(AS_public); 10725 } 10726 } 10727 10728 // Create the nested-name-specifier that will be used to qualify the 10729 // reference to operator=; this is required to suppress the virtual 10730 // call mechanism. 10731 CXXScopeSpec SS; 10732 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 10733 SS.MakeTrivial(S.Context, 10734 NestedNameSpecifier::Create(S.Context, nullptr, false, 10735 CanonicalT), 10736 Loc); 10737 10738 // Create the reference to operator=. 10739 ExprResult OpEqualRef 10740 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 10741 SS, /*TemplateKWLoc=*/SourceLocation(), 10742 /*FirstQualifierInScope=*/nullptr, 10743 OpLookup, 10744 /*TemplateArgs=*/nullptr, /*S*/nullptr, 10745 /*SuppressQualifierCheck=*/true); 10746 if (OpEqualRef.isInvalid()) 10747 return StmtError(); 10748 10749 // Build the call to the assignment operator. 10750 10751 Expr *FromInst = From.build(S, Loc); 10752 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 10753 OpEqualRef.getAs<Expr>(), 10754 Loc, FromInst, Loc); 10755 if (Call.isInvalid()) 10756 return StmtError(); 10757 10758 // If we built a call to a trivial 'operator=' while copying an array, 10759 // bail out. We'll replace the whole shebang with a memcpy. 10760 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 10761 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 10762 return StmtResult((Stmt*)nullptr); 10763 10764 // Convert to an expression-statement, and clean up any produced 10765 // temporaries. 10766 return S.ActOnExprStmt(Call); 10767 } 10768 10769 // - if the subobject is of scalar type, the built-in assignment 10770 // operator is used. 10771 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 10772 if (!ArrayTy) { 10773 ExprResult Assignment = S.CreateBuiltinBinOp( 10774 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 10775 if (Assignment.isInvalid()) 10776 return StmtError(); 10777 return S.ActOnExprStmt(Assignment); 10778 } 10779 10780 // - if the subobject is an array, each element is assigned, in the 10781 // manner appropriate to the element type; 10782 10783 // Construct a loop over the array bounds, e.g., 10784 // 10785 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 10786 // 10787 // that will copy each of the array elements. 10788 QualType SizeType = S.Context.getSizeType(); 10789 10790 // Create the iteration variable. 10791 IdentifierInfo *IterationVarName = nullptr; 10792 { 10793 SmallString<8> Str; 10794 llvm::raw_svector_ostream OS(Str); 10795 OS << "__i" << Depth; 10796 IterationVarName = &S.Context.Idents.get(OS.str()); 10797 } 10798 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 10799 IterationVarName, SizeType, 10800 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 10801 SC_None); 10802 10803 // Initialize the iteration variable to zero. 10804 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 10805 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 10806 10807 // Creates a reference to the iteration variable. 10808 RefBuilder IterationVarRef(IterationVar, SizeType); 10809 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 10810 10811 // Create the DeclStmt that holds the iteration variable. 10812 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 10813 10814 // Subscript the "from" and "to" expressions with the iteration variable. 10815 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 10816 MoveCastBuilder FromIndexMove(FromIndexCopy); 10817 const ExprBuilder *FromIndex; 10818 if (Copying) 10819 FromIndex = &FromIndexCopy; 10820 else 10821 FromIndex = &FromIndexMove; 10822 10823 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 10824 10825 // Build the copy/move for an individual element of the array. 10826 StmtResult Copy = 10827 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 10828 ToIndex, *FromIndex, CopyingBaseSubobject, 10829 Copying, Depth + 1); 10830 // Bail out if copying fails or if we determined that we should use memcpy. 10831 if (Copy.isInvalid() || !Copy.get()) 10832 return Copy; 10833 10834 // Create the comparison against the array bound. 10835 llvm::APInt Upper 10836 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 10837 Expr *Comparison 10838 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 10839 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 10840 BO_NE, S.Context.BoolTy, 10841 VK_RValue, OK_Ordinary, Loc, false); 10842 10843 // Create the pre-increment of the iteration variable. 10844 Expr *Increment 10845 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 10846 SizeType, VK_LValue, OK_Ordinary, Loc); 10847 10848 // Construct the loop that copies all elements of this array. 10849 return S.ActOnForStmt( 10850 Loc, Loc, InitStmt, 10851 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 10852 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 10853 } 10854 10855 static StmtResult 10856 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 10857 const ExprBuilder &To, const ExprBuilder &From, 10858 bool CopyingBaseSubobject, bool Copying) { 10859 // Maybe we should use a memcpy? 10860 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 10861 T.isTriviallyCopyableType(S.Context)) 10862 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 10863 10864 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 10865 CopyingBaseSubobject, 10866 Copying, 0)); 10867 10868 // If we ended up picking a trivial assignment operator for an array of a 10869 // non-trivially-copyable class type, just emit a memcpy. 10870 if (!Result.isInvalid() && !Result.get()) 10871 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 10872 10873 return Result; 10874 } 10875 10876 Sema::ImplicitExceptionSpecification 10877 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 10878 CXXRecordDecl *ClassDecl = MD->getParent(); 10879 10880 ImplicitExceptionSpecification ExceptSpec(*this); 10881 if (ClassDecl->isInvalidDecl()) 10882 return ExceptSpec; 10883 10884 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10885 assert(T->getNumParams() == 1 && "not a copy assignment op"); 10886 unsigned ArgQuals = 10887 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10888 10889 // C++ [except.spec]p14: 10890 // An implicitly declared special member function (Clause 12) shall have an 10891 // exception-specification. [...] 10892 10893 // It is unspecified whether or not an implicit copy assignment operator 10894 // attempts to deduplicate calls to assignment operators of virtual bases are 10895 // made. As such, this exception specification is effectively unspecified. 10896 // Based on a similar decision made for constness in C++0x, we're erring on 10897 // the side of assuming such calls to be made regardless of whether they 10898 // actually happen. 10899 for (const auto &Base : ClassDecl->bases()) { 10900 if (Base.isVirtual()) 10901 continue; 10902 10903 CXXRecordDecl *BaseClassDecl 10904 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10905 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10906 ArgQuals, false, 0)) 10907 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10908 } 10909 10910 for (const auto &Base : ClassDecl->vbases()) { 10911 CXXRecordDecl *BaseClassDecl 10912 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10913 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10914 ArgQuals, false, 0)) 10915 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10916 } 10917 10918 for (const auto *Field : ClassDecl->fields()) { 10919 QualType FieldType = Context.getBaseElementType(Field->getType()); 10920 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10921 if (CXXMethodDecl *CopyAssign = 10922 LookupCopyingAssignment(FieldClassDecl, 10923 ArgQuals | FieldType.getCVRQualifiers(), 10924 false, 0)) 10925 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 10926 } 10927 } 10928 10929 return ExceptSpec; 10930 } 10931 10932 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 10933 // Note: The following rules are largely analoguous to the copy 10934 // constructor rules. Note that virtual bases are not taken into account 10935 // for determining the argument type of the operator. Note also that 10936 // operators taking an object instead of a reference are allowed. 10937 assert(ClassDecl->needsImplicitCopyAssignment()); 10938 10939 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 10940 if (DSM.isAlreadyBeingDeclared()) 10941 return nullptr; 10942 10943 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10944 QualType RetType = Context.getLValueReferenceType(ArgType); 10945 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 10946 if (Const) 10947 ArgType = ArgType.withConst(); 10948 ArgType = Context.getLValueReferenceType(ArgType); 10949 10950 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10951 CXXCopyAssignment, 10952 Const); 10953 10954 // An implicitly-declared copy assignment operator is an inline public 10955 // member of its class. 10956 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10957 SourceLocation ClassLoc = ClassDecl->getLocation(); 10958 DeclarationNameInfo NameInfo(Name, ClassLoc); 10959 CXXMethodDecl *CopyAssignment = 10960 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10961 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10962 /*isInline=*/true, Constexpr, SourceLocation()); 10963 CopyAssignment->setAccess(AS_public); 10964 CopyAssignment->setDefaulted(); 10965 CopyAssignment->setImplicit(); 10966 10967 if (getLangOpts().CUDA) { 10968 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 10969 CopyAssignment, 10970 /* ConstRHS */ Const, 10971 /* Diagnose */ false); 10972 } 10973 10974 // Build an exception specification pointing back at this member. 10975 FunctionProtoType::ExtProtoInfo EPI = 10976 getImplicitMethodEPI(*this, CopyAssignment); 10977 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10978 10979 // Add the parameter to the operator. 10980 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 10981 ClassLoc, ClassLoc, 10982 /*Id=*/nullptr, ArgType, 10983 /*TInfo=*/nullptr, SC_None, 10984 nullptr); 10985 CopyAssignment->setParams(FromParam); 10986 10987 CopyAssignment->setTrivial( 10988 ClassDecl->needsOverloadResolutionForCopyAssignment() 10989 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 10990 : ClassDecl->hasTrivialCopyAssignment()); 10991 10992 // Note that we have added this copy-assignment operator. 10993 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10994 10995 Scope *S = getScopeForContext(ClassDecl); 10996 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 10997 10998 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 10999 SetDeclDeleted(CopyAssignment, ClassLoc); 11000 11001 if (S) 11002 PushOnScopeChains(CopyAssignment, S, false); 11003 ClassDecl->addDecl(CopyAssignment); 11004 11005 return CopyAssignment; 11006 } 11007 11008 /// Diagnose an implicit copy operation for a class which is odr-used, but 11009 /// which is deprecated because the class has a user-declared copy constructor, 11010 /// copy assignment operator, or destructor. 11011 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 11012 SourceLocation UseLoc) { 11013 assert(CopyOp->isImplicit()); 11014 11015 CXXRecordDecl *RD = CopyOp->getParent(); 11016 CXXMethodDecl *UserDeclaredOperation = nullptr; 11017 11018 // In Microsoft mode, assignment operations don't affect constructors and 11019 // vice versa. 11020 if (RD->hasUserDeclaredDestructor()) { 11021 UserDeclaredOperation = RD->getDestructor(); 11022 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11023 RD->hasUserDeclaredCopyConstructor() && 11024 !S.getLangOpts().MSVCCompat) { 11025 // Find any user-declared copy constructor. 11026 for (auto *I : RD->ctors()) { 11027 if (I->isCopyConstructor()) { 11028 UserDeclaredOperation = I; 11029 break; 11030 } 11031 } 11032 assert(UserDeclaredOperation); 11033 } else if (isa<CXXConstructorDecl>(CopyOp) && 11034 RD->hasUserDeclaredCopyAssignment() && 11035 !S.getLangOpts().MSVCCompat) { 11036 // Find any user-declared move assignment operator. 11037 for (auto *I : RD->methods()) { 11038 if (I->isCopyAssignmentOperator()) { 11039 UserDeclaredOperation = I; 11040 break; 11041 } 11042 } 11043 assert(UserDeclaredOperation); 11044 } 11045 11046 if (UserDeclaredOperation) { 11047 S.Diag(UserDeclaredOperation->getLocation(), 11048 diag::warn_deprecated_copy_operation) 11049 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11050 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11051 S.Diag(UseLoc, diag::note_member_synthesized_at) 11052 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 11053 : Sema::CXXCopyAssignment) 11054 << RD; 11055 } 11056 } 11057 11058 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11059 CXXMethodDecl *CopyAssignOperator) { 11060 assert((CopyAssignOperator->isDefaulted() && 11061 CopyAssignOperator->isOverloadedOperator() && 11062 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11063 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11064 !CopyAssignOperator->isDeleted()) && 11065 "DefineImplicitCopyAssignment called for wrong function"); 11066 11067 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11068 11069 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 11070 CopyAssignOperator->setInvalidDecl(); 11071 return; 11072 } 11073 11074 // C++11 [class.copy]p18: 11075 // The [definition of an implicitly declared copy assignment operator] is 11076 // deprecated if the class has a user-declared copy constructor or a 11077 // user-declared destructor. 11078 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11079 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 11080 11081 CopyAssignOperator->markUsed(Context); 11082 11083 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11084 DiagnosticErrorTrap Trap(Diags); 11085 11086 // C++0x [class.copy]p30: 11087 // The implicitly-defined or explicitly-defaulted copy assignment operator 11088 // for a non-union class X performs memberwise copy assignment of its 11089 // subobjects. The direct base classes of X are assigned first, in the 11090 // order of their declaration in the base-specifier-list, and then the 11091 // immediate non-static data members of X are assigned, in the order in 11092 // which they were declared in the class definition. 11093 11094 // The statements that form the synthesized function body. 11095 SmallVector<Stmt*, 8> Statements; 11096 11097 // The parameter for the "other" object, which we are copying from. 11098 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11099 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11100 QualType OtherRefType = Other->getType(); 11101 if (const LValueReferenceType *OtherRef 11102 = OtherRefType->getAs<LValueReferenceType>()) { 11103 OtherRefType = OtherRef->getPointeeType(); 11104 OtherQuals = OtherRefType.getQualifiers(); 11105 } 11106 11107 // Our location for everything implicitly-generated. 11108 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11109 ? CopyAssignOperator->getLocEnd() 11110 : CopyAssignOperator->getLocation(); 11111 11112 // Builds a DeclRefExpr for the "other" object. 11113 RefBuilder OtherRef(Other, OtherRefType); 11114 11115 // Builds the "this" pointer. 11116 ThisBuilder This; 11117 11118 // Assign base classes. 11119 bool Invalid = false; 11120 for (auto &Base : ClassDecl->bases()) { 11121 // Form the assignment: 11122 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11123 QualType BaseType = Base.getType().getUnqualifiedType(); 11124 if (!BaseType->isRecordType()) { 11125 Invalid = true; 11126 continue; 11127 } 11128 11129 CXXCastPath BasePath; 11130 BasePath.push_back(&Base); 11131 11132 // Construct the "from" expression, which is an implicit cast to the 11133 // appropriately-qualified base type. 11134 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11135 VK_LValue, BasePath); 11136 11137 // Dereference "this". 11138 DerefBuilder DerefThis(This); 11139 CastBuilder To(DerefThis, 11140 Context.getCVRQualifiedType( 11141 BaseType, CopyAssignOperator->getTypeQualifiers()), 11142 VK_LValue, BasePath); 11143 11144 // Build the copy. 11145 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11146 To, From, 11147 /*CopyingBaseSubobject=*/true, 11148 /*Copying=*/true); 11149 if (Copy.isInvalid()) { 11150 Diag(CurrentLocation, diag::note_member_synthesized_at) 11151 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11152 CopyAssignOperator->setInvalidDecl(); 11153 return; 11154 } 11155 11156 // Success! Record the copy. 11157 Statements.push_back(Copy.getAs<Expr>()); 11158 } 11159 11160 // Assign non-static members. 11161 for (auto *Field : ClassDecl->fields()) { 11162 // FIXME: We should form some kind of AST representation for the implied 11163 // memcpy in a union copy operation. 11164 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11165 continue; 11166 11167 if (Field->isInvalidDecl()) { 11168 Invalid = true; 11169 continue; 11170 } 11171 11172 // Check for members of reference type; we can't copy those. 11173 if (Field->getType()->isReferenceType()) { 11174 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11175 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11176 Diag(Field->getLocation(), diag::note_declared_at); 11177 Diag(CurrentLocation, diag::note_member_synthesized_at) 11178 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11179 Invalid = true; 11180 continue; 11181 } 11182 11183 // Check for members of const-qualified, non-class type. 11184 QualType BaseType = Context.getBaseElementType(Field->getType()); 11185 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11186 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11187 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11188 Diag(Field->getLocation(), diag::note_declared_at); 11189 Diag(CurrentLocation, diag::note_member_synthesized_at) 11190 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11191 Invalid = true; 11192 continue; 11193 } 11194 11195 // Suppress assigning zero-width bitfields. 11196 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11197 continue; 11198 11199 QualType FieldType = Field->getType().getNonReferenceType(); 11200 if (FieldType->isIncompleteArrayType()) { 11201 assert(ClassDecl->hasFlexibleArrayMember() && 11202 "Incomplete array type is not valid"); 11203 continue; 11204 } 11205 11206 // Build references to the field in the object we're copying from and to. 11207 CXXScopeSpec SS; // Intentionally empty 11208 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11209 LookupMemberName); 11210 MemberLookup.addDecl(Field); 11211 MemberLookup.resolveKind(); 11212 11213 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11214 11215 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11216 11217 // Build the copy of this field. 11218 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11219 To, From, 11220 /*CopyingBaseSubobject=*/false, 11221 /*Copying=*/true); 11222 if (Copy.isInvalid()) { 11223 Diag(CurrentLocation, diag::note_member_synthesized_at) 11224 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11225 CopyAssignOperator->setInvalidDecl(); 11226 return; 11227 } 11228 11229 // Success! Record the copy. 11230 Statements.push_back(Copy.getAs<Stmt>()); 11231 } 11232 11233 if (!Invalid) { 11234 // Add a "return *this;" 11235 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11236 11237 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11238 if (Return.isInvalid()) 11239 Invalid = true; 11240 else { 11241 Statements.push_back(Return.getAs<Stmt>()); 11242 11243 if (Trap.hasErrorOccurred()) { 11244 Diag(CurrentLocation, diag::note_member_synthesized_at) 11245 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11246 Invalid = true; 11247 } 11248 } 11249 } 11250 11251 // The exception specification is needed because we are defining the 11252 // function. 11253 ResolveExceptionSpec(CurrentLocation, 11254 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11255 11256 if (Invalid) { 11257 CopyAssignOperator->setInvalidDecl(); 11258 return; 11259 } 11260 11261 StmtResult Body; 11262 { 11263 CompoundScopeRAII CompoundScope(*this); 11264 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11265 /*isStmtExpr=*/false); 11266 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11267 } 11268 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11269 11270 if (ASTMutationListener *L = getASTMutationListener()) { 11271 L->CompletedImplicitDefinition(CopyAssignOperator); 11272 } 11273 } 11274 11275 Sema::ImplicitExceptionSpecification 11276 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 11277 CXXRecordDecl *ClassDecl = MD->getParent(); 11278 11279 ImplicitExceptionSpecification ExceptSpec(*this); 11280 if (ClassDecl->isInvalidDecl()) 11281 return ExceptSpec; 11282 11283 // C++0x [except.spec]p14: 11284 // An implicitly declared special member function (Clause 12) shall have an 11285 // exception-specification. [...] 11286 11287 // It is unspecified whether or not an implicit move assignment operator 11288 // attempts to deduplicate calls to assignment operators of virtual bases are 11289 // made. As such, this exception specification is effectively unspecified. 11290 // Based on a similar decision made for constness in C++0x, we're erring on 11291 // the side of assuming such calls to be made regardless of whether they 11292 // actually happen. 11293 // Note that a move constructor is not implicitly declared when there are 11294 // virtual bases, but it can still be user-declared and explicitly defaulted. 11295 for (const auto &Base : ClassDecl->bases()) { 11296 if (Base.isVirtual()) 11297 continue; 11298 11299 CXXRecordDecl *BaseClassDecl 11300 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11301 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 11302 0, false, 0)) 11303 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 11304 } 11305 11306 for (const auto &Base : ClassDecl->vbases()) { 11307 CXXRecordDecl *BaseClassDecl 11308 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11309 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 11310 0, false, 0)) 11311 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 11312 } 11313 11314 for (const auto *Field : ClassDecl->fields()) { 11315 QualType FieldType = Context.getBaseElementType(Field->getType()); 11316 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 11317 if (CXXMethodDecl *MoveAssign = 11318 LookupMovingAssignment(FieldClassDecl, 11319 FieldType.getCVRQualifiers(), 11320 false, 0)) 11321 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 11322 } 11323 } 11324 11325 return ExceptSpec; 11326 } 11327 11328 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11329 assert(ClassDecl->needsImplicitMoveAssignment()); 11330 11331 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11332 if (DSM.isAlreadyBeingDeclared()) 11333 return nullptr; 11334 11335 // Note: The following rules are largely analoguous to the move 11336 // constructor rules. 11337 11338 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11339 QualType RetType = Context.getLValueReferenceType(ArgType); 11340 ArgType = Context.getRValueReferenceType(ArgType); 11341 11342 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11343 CXXMoveAssignment, 11344 false); 11345 11346 // An implicitly-declared move assignment operator is an inline public 11347 // member of its class. 11348 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11349 SourceLocation ClassLoc = ClassDecl->getLocation(); 11350 DeclarationNameInfo NameInfo(Name, ClassLoc); 11351 CXXMethodDecl *MoveAssignment = 11352 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11353 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11354 /*isInline=*/true, Constexpr, SourceLocation()); 11355 MoveAssignment->setAccess(AS_public); 11356 MoveAssignment->setDefaulted(); 11357 MoveAssignment->setImplicit(); 11358 11359 if (getLangOpts().CUDA) { 11360 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11361 MoveAssignment, 11362 /* ConstRHS */ false, 11363 /* Diagnose */ false); 11364 } 11365 11366 // Build an exception specification pointing back at this member. 11367 FunctionProtoType::ExtProtoInfo EPI = 11368 getImplicitMethodEPI(*this, MoveAssignment); 11369 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11370 11371 // Add the parameter to the operator. 11372 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11373 ClassLoc, ClassLoc, 11374 /*Id=*/nullptr, ArgType, 11375 /*TInfo=*/nullptr, SC_None, 11376 nullptr); 11377 MoveAssignment->setParams(FromParam); 11378 11379 MoveAssignment->setTrivial( 11380 ClassDecl->needsOverloadResolutionForMoveAssignment() 11381 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11382 : ClassDecl->hasTrivialMoveAssignment()); 11383 11384 // Note that we have added this copy-assignment operator. 11385 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11386 11387 Scope *S = getScopeForContext(ClassDecl); 11388 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11389 11390 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11391 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11392 SetDeclDeleted(MoveAssignment, ClassLoc); 11393 } 11394 11395 if (S) 11396 PushOnScopeChains(MoveAssignment, S, false); 11397 ClassDecl->addDecl(MoveAssignment); 11398 11399 return MoveAssignment; 11400 } 11401 11402 /// Check if we're implicitly defining a move assignment operator for a class 11403 /// with virtual bases. Such a move assignment might move-assign the virtual 11404 /// base multiple times. 11405 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11406 SourceLocation CurrentLocation) { 11407 assert(!Class->isDependentContext() && "should not define dependent move"); 11408 11409 // Only a virtual base could get implicitly move-assigned multiple times. 11410 // Only a non-trivial move assignment can observe this. We only want to 11411 // diagnose if we implicitly define an assignment operator that assigns 11412 // two base classes, both of which move-assign the same virtual base. 11413 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11414 Class->getNumBases() < 2) 11415 return; 11416 11417 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11418 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11419 VBaseMap VBases; 11420 11421 for (auto &BI : Class->bases()) { 11422 Worklist.push_back(&BI); 11423 while (!Worklist.empty()) { 11424 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11425 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11426 11427 // If the base has no non-trivial move assignment operators, 11428 // we don't care about moves from it. 11429 if (!Base->hasNonTrivialMoveAssignment()) 11430 continue; 11431 11432 // If there's nothing virtual here, skip it. 11433 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11434 continue; 11435 11436 // If we're not actually going to call a move assignment for this base, 11437 // or the selected move assignment is trivial, skip it. 11438 Sema::SpecialMemberOverloadResult *SMOR = 11439 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11440 /*ConstArg*/false, /*VolatileArg*/false, 11441 /*RValueThis*/true, /*ConstThis*/false, 11442 /*VolatileThis*/false); 11443 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 11444 !SMOR->getMethod()->isMoveAssignmentOperator()) 11445 continue; 11446 11447 if (BaseSpec->isVirtual()) { 11448 // We're going to move-assign this virtual base, and its move 11449 // assignment operator is not trivial. If this can happen for 11450 // multiple distinct direct bases of Class, diagnose it. (If it 11451 // only happens in one base, we'll diagnose it when synthesizing 11452 // that base class's move assignment operator.) 11453 CXXBaseSpecifier *&Existing = 11454 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11455 .first->second; 11456 if (Existing && Existing != &BI) { 11457 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11458 << Class << Base; 11459 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11460 << (Base->getCanonicalDecl() == 11461 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11462 << Base << Existing->getType() << Existing->getSourceRange(); 11463 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11464 << (Base->getCanonicalDecl() == 11465 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11466 << Base << BI.getType() << BaseSpec->getSourceRange(); 11467 11468 // Only diagnose each vbase once. 11469 Existing = nullptr; 11470 } 11471 } else { 11472 // Only walk over bases that have defaulted move assignment operators. 11473 // We assume that any user-provided move assignment operator handles 11474 // the multiple-moves-of-vbase case itself somehow. 11475 if (!SMOR->getMethod()->isDefaulted()) 11476 continue; 11477 11478 // We're going to move the base classes of Base. Add them to the list. 11479 for (auto &BI : Base->bases()) 11480 Worklist.push_back(&BI); 11481 } 11482 } 11483 } 11484 } 11485 11486 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11487 CXXMethodDecl *MoveAssignOperator) { 11488 assert((MoveAssignOperator->isDefaulted() && 11489 MoveAssignOperator->isOverloadedOperator() && 11490 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11491 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11492 !MoveAssignOperator->isDeleted()) && 11493 "DefineImplicitMoveAssignment called for wrong function"); 11494 11495 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11496 11497 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 11498 MoveAssignOperator->setInvalidDecl(); 11499 return; 11500 } 11501 11502 MoveAssignOperator->markUsed(Context); 11503 11504 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11505 DiagnosticErrorTrap Trap(Diags); 11506 11507 // C++0x [class.copy]p28: 11508 // The implicitly-defined or move assignment operator for a non-union class 11509 // X performs memberwise move assignment of its subobjects. The direct base 11510 // classes of X are assigned first, in the order of their declaration in the 11511 // base-specifier-list, and then the immediate non-static data members of X 11512 // are assigned, in the order in which they were declared in the class 11513 // definition. 11514 11515 // Issue a warning if our implicit move assignment operator will move 11516 // from a virtual base more than once. 11517 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11518 11519 // The statements that form the synthesized function body. 11520 SmallVector<Stmt*, 8> Statements; 11521 11522 // The parameter for the "other" object, which we are move from. 11523 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11524 QualType OtherRefType = Other->getType()-> 11525 getAs<RValueReferenceType>()->getPointeeType(); 11526 assert(!OtherRefType.getQualifiers() && 11527 "Bad argument type of defaulted move assignment"); 11528 11529 // Our location for everything implicitly-generated. 11530 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11531 ? MoveAssignOperator->getLocEnd() 11532 : MoveAssignOperator->getLocation(); 11533 11534 // Builds a reference to the "other" object. 11535 RefBuilder OtherRef(Other, OtherRefType); 11536 // Cast to rvalue. 11537 MoveCastBuilder MoveOther(OtherRef); 11538 11539 // Builds the "this" pointer. 11540 ThisBuilder This; 11541 11542 // Assign base classes. 11543 bool Invalid = false; 11544 for (auto &Base : ClassDecl->bases()) { 11545 // C++11 [class.copy]p28: 11546 // It is unspecified whether subobjects representing virtual base classes 11547 // are assigned more than once by the implicitly-defined copy assignment 11548 // operator. 11549 // FIXME: Do not assign to a vbase that will be assigned by some other base 11550 // class. For a move-assignment, this can result in the vbase being moved 11551 // multiple times. 11552 11553 // Form the assignment: 11554 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11555 QualType BaseType = Base.getType().getUnqualifiedType(); 11556 if (!BaseType->isRecordType()) { 11557 Invalid = true; 11558 continue; 11559 } 11560 11561 CXXCastPath BasePath; 11562 BasePath.push_back(&Base); 11563 11564 // Construct the "from" expression, which is an implicit cast to the 11565 // appropriately-qualified base type. 11566 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11567 11568 // Dereference "this". 11569 DerefBuilder DerefThis(This); 11570 11571 // Implicitly cast "this" to the appropriately-qualified base type. 11572 CastBuilder To(DerefThis, 11573 Context.getCVRQualifiedType( 11574 BaseType, MoveAssignOperator->getTypeQualifiers()), 11575 VK_LValue, BasePath); 11576 11577 // Build the move. 11578 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11579 To, From, 11580 /*CopyingBaseSubobject=*/true, 11581 /*Copying=*/false); 11582 if (Move.isInvalid()) { 11583 Diag(CurrentLocation, diag::note_member_synthesized_at) 11584 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11585 MoveAssignOperator->setInvalidDecl(); 11586 return; 11587 } 11588 11589 // Success! Record the move. 11590 Statements.push_back(Move.getAs<Expr>()); 11591 } 11592 11593 // Assign non-static members. 11594 for (auto *Field : ClassDecl->fields()) { 11595 // FIXME: We should form some kind of AST representation for the implied 11596 // memcpy in a union copy operation. 11597 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11598 continue; 11599 11600 if (Field->isInvalidDecl()) { 11601 Invalid = true; 11602 continue; 11603 } 11604 11605 // Check for members of reference type; we can't move those. 11606 if (Field->getType()->isReferenceType()) { 11607 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11608 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11609 Diag(Field->getLocation(), diag::note_declared_at); 11610 Diag(CurrentLocation, diag::note_member_synthesized_at) 11611 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11612 Invalid = true; 11613 continue; 11614 } 11615 11616 // Check for members of const-qualified, non-class type. 11617 QualType BaseType = Context.getBaseElementType(Field->getType()); 11618 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11619 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11620 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11621 Diag(Field->getLocation(), diag::note_declared_at); 11622 Diag(CurrentLocation, diag::note_member_synthesized_at) 11623 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11624 Invalid = true; 11625 continue; 11626 } 11627 11628 // Suppress assigning zero-width bitfields. 11629 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11630 continue; 11631 11632 QualType FieldType = Field->getType().getNonReferenceType(); 11633 if (FieldType->isIncompleteArrayType()) { 11634 assert(ClassDecl->hasFlexibleArrayMember() && 11635 "Incomplete array type is not valid"); 11636 continue; 11637 } 11638 11639 // Build references to the field in the object we're copying from and to. 11640 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11641 LookupMemberName); 11642 MemberLookup.addDecl(Field); 11643 MemberLookup.resolveKind(); 11644 MemberBuilder From(MoveOther, OtherRefType, 11645 /*IsArrow=*/false, MemberLookup); 11646 MemberBuilder To(This, getCurrentThisType(), 11647 /*IsArrow=*/true, MemberLookup); 11648 11649 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 11650 "Member reference with rvalue base must be rvalue except for reference " 11651 "members, which aren't allowed for move assignment."); 11652 11653 // Build the move of this field. 11654 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 11655 To, From, 11656 /*CopyingBaseSubobject=*/false, 11657 /*Copying=*/false); 11658 if (Move.isInvalid()) { 11659 Diag(CurrentLocation, diag::note_member_synthesized_at) 11660 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11661 MoveAssignOperator->setInvalidDecl(); 11662 return; 11663 } 11664 11665 // Success! Record the copy. 11666 Statements.push_back(Move.getAs<Stmt>()); 11667 } 11668 11669 if (!Invalid) { 11670 // Add a "return *this;" 11671 ExprResult ThisObj = 11672 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11673 11674 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11675 if (Return.isInvalid()) 11676 Invalid = true; 11677 else { 11678 Statements.push_back(Return.getAs<Stmt>()); 11679 11680 if (Trap.hasErrorOccurred()) { 11681 Diag(CurrentLocation, diag::note_member_synthesized_at) 11682 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11683 Invalid = true; 11684 } 11685 } 11686 } 11687 11688 // The exception specification is needed because we are defining the 11689 // function. 11690 ResolveExceptionSpec(CurrentLocation, 11691 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11692 11693 if (Invalid) { 11694 MoveAssignOperator->setInvalidDecl(); 11695 return; 11696 } 11697 11698 StmtResult Body; 11699 { 11700 CompoundScopeRAII CompoundScope(*this); 11701 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11702 /*isStmtExpr=*/false); 11703 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11704 } 11705 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 11706 11707 if (ASTMutationListener *L = getASTMutationListener()) { 11708 L->CompletedImplicitDefinition(MoveAssignOperator); 11709 } 11710 } 11711 11712 Sema::ImplicitExceptionSpecification 11713 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 11714 CXXRecordDecl *ClassDecl = MD->getParent(); 11715 11716 ImplicitExceptionSpecification ExceptSpec(*this); 11717 if (ClassDecl->isInvalidDecl()) 11718 return ExceptSpec; 11719 11720 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 11721 assert(T->getNumParams() >= 1 && "not a copy ctor"); 11722 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 11723 11724 // C++ [except.spec]p14: 11725 // An implicitly declared special member function (Clause 12) shall have an 11726 // exception-specification. [...] 11727 for (const auto &Base : ClassDecl->bases()) { 11728 // Virtual bases are handled below. 11729 if (Base.isVirtual()) 11730 continue; 11731 11732 CXXRecordDecl *BaseClassDecl 11733 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11734 if (CXXConstructorDecl *CopyConstructor = 11735 LookupCopyingConstructor(BaseClassDecl, Quals)) 11736 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 11737 } 11738 for (const auto &Base : ClassDecl->vbases()) { 11739 CXXRecordDecl *BaseClassDecl 11740 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11741 if (CXXConstructorDecl *CopyConstructor = 11742 LookupCopyingConstructor(BaseClassDecl, Quals)) 11743 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 11744 } 11745 for (const auto *Field : ClassDecl->fields()) { 11746 QualType FieldType = Context.getBaseElementType(Field->getType()); 11747 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 11748 if (CXXConstructorDecl *CopyConstructor = 11749 LookupCopyingConstructor(FieldClassDecl, 11750 Quals | FieldType.getCVRQualifiers())) 11751 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 11752 } 11753 } 11754 11755 return ExceptSpec; 11756 } 11757 11758 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 11759 CXXRecordDecl *ClassDecl) { 11760 // C++ [class.copy]p4: 11761 // If the class definition does not explicitly declare a copy 11762 // constructor, one is declared implicitly. 11763 assert(ClassDecl->needsImplicitCopyConstructor()); 11764 11765 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 11766 if (DSM.isAlreadyBeingDeclared()) 11767 return nullptr; 11768 11769 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11770 QualType ArgType = ClassType; 11771 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 11772 if (Const) 11773 ArgType = ArgType.withConst(); 11774 ArgType = Context.getLValueReferenceType(ArgType); 11775 11776 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11777 CXXCopyConstructor, 11778 Const); 11779 11780 DeclarationName Name 11781 = Context.DeclarationNames.getCXXConstructorName( 11782 Context.getCanonicalType(ClassType)); 11783 SourceLocation ClassLoc = ClassDecl->getLocation(); 11784 DeclarationNameInfo NameInfo(Name, ClassLoc); 11785 11786 // An implicitly-declared copy constructor is an inline public 11787 // member of its class. 11788 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 11789 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11790 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11791 Constexpr); 11792 CopyConstructor->setAccess(AS_public); 11793 CopyConstructor->setDefaulted(); 11794 11795 if (getLangOpts().CUDA) { 11796 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 11797 CopyConstructor, 11798 /* ConstRHS */ Const, 11799 /* Diagnose */ false); 11800 } 11801 11802 // Build an exception specification pointing back at this member. 11803 FunctionProtoType::ExtProtoInfo EPI = 11804 getImplicitMethodEPI(*this, CopyConstructor); 11805 CopyConstructor->setType( 11806 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11807 11808 // Add the parameter to the constructor. 11809 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 11810 ClassLoc, ClassLoc, 11811 /*IdentifierInfo=*/nullptr, 11812 ArgType, /*TInfo=*/nullptr, 11813 SC_None, nullptr); 11814 CopyConstructor->setParams(FromParam); 11815 11816 CopyConstructor->setTrivial( 11817 ClassDecl->needsOverloadResolutionForCopyConstructor() 11818 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 11819 : ClassDecl->hasTrivialCopyConstructor()); 11820 11821 // Note that we have declared this constructor. 11822 ++ASTContext::NumImplicitCopyConstructorsDeclared; 11823 11824 Scope *S = getScopeForContext(ClassDecl); 11825 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 11826 11827 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 11828 SetDeclDeleted(CopyConstructor, ClassLoc); 11829 11830 if (S) 11831 PushOnScopeChains(CopyConstructor, S, false); 11832 ClassDecl->addDecl(CopyConstructor); 11833 11834 return CopyConstructor; 11835 } 11836 11837 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 11838 CXXConstructorDecl *CopyConstructor) { 11839 assert((CopyConstructor->isDefaulted() && 11840 CopyConstructor->isCopyConstructor() && 11841 !CopyConstructor->doesThisDeclarationHaveABody() && 11842 !CopyConstructor->isDeleted()) && 11843 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 11844 11845 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 11846 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 11847 11848 // C++11 [class.copy]p7: 11849 // The [definition of an implicitly declared copy constructor] is 11850 // deprecated if the class has a user-declared copy assignment operator 11851 // or a user-declared destructor. 11852 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 11853 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 11854 11855 SynthesizedFunctionScope Scope(*this, CopyConstructor); 11856 DiagnosticErrorTrap Trap(Diags); 11857 11858 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 11859 Trap.hasErrorOccurred()) { 11860 Diag(CurrentLocation, diag::note_member_synthesized_at) 11861 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 11862 CopyConstructor->setInvalidDecl(); 11863 } else { 11864 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 11865 ? CopyConstructor->getLocEnd() 11866 : CopyConstructor->getLocation(); 11867 Sema::CompoundScopeRAII CompoundScope(*this); 11868 CopyConstructor->setBody( 11869 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 11870 } 11871 11872 // The exception specification is needed because we are defining the 11873 // function. 11874 ResolveExceptionSpec(CurrentLocation, 11875 CopyConstructor->getType()->castAs<FunctionProtoType>()); 11876 11877 CopyConstructor->markUsed(Context); 11878 MarkVTableUsed(CurrentLocation, ClassDecl); 11879 11880 if (ASTMutationListener *L = getASTMutationListener()) { 11881 L->CompletedImplicitDefinition(CopyConstructor); 11882 } 11883 } 11884 11885 Sema::ImplicitExceptionSpecification 11886 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 11887 CXXRecordDecl *ClassDecl = MD->getParent(); 11888 11889 // C++ [except.spec]p14: 11890 // An implicitly declared special member function (Clause 12) shall have an 11891 // exception-specification. [...] 11892 ImplicitExceptionSpecification ExceptSpec(*this); 11893 if (ClassDecl->isInvalidDecl()) 11894 return ExceptSpec; 11895 11896 // Direct base-class constructors. 11897 for (const auto &B : ClassDecl->bases()) { 11898 if (B.isVirtual()) // Handled below. 11899 continue; 11900 11901 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11902 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11903 CXXConstructorDecl *Constructor = 11904 LookupMovingConstructor(BaseClassDecl, 0); 11905 // If this is a deleted function, add it anyway. This might be conformant 11906 // with the standard. This might not. I'm not sure. It might not matter. 11907 if (Constructor) 11908 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11909 } 11910 } 11911 11912 // Virtual base-class constructors. 11913 for (const auto &B : ClassDecl->vbases()) { 11914 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11915 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11916 CXXConstructorDecl *Constructor = 11917 LookupMovingConstructor(BaseClassDecl, 0); 11918 // If this is a deleted function, add it anyway. This might be conformant 11919 // with the standard. This might not. I'm not sure. It might not matter. 11920 if (Constructor) 11921 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11922 } 11923 } 11924 11925 // Field constructors. 11926 for (const auto *F : ClassDecl->fields()) { 11927 QualType FieldType = Context.getBaseElementType(F->getType()); 11928 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 11929 CXXConstructorDecl *Constructor = 11930 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 11931 // If this is a deleted function, add it anyway. This might be conformant 11932 // with the standard. This might not. I'm not sure. It might not matter. 11933 // In particular, the problem is that this function never gets called. It 11934 // might just be ill-formed because this function attempts to refer to 11935 // a deleted function here. 11936 if (Constructor) 11937 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 11938 } 11939 } 11940 11941 return ExceptSpec; 11942 } 11943 11944 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 11945 CXXRecordDecl *ClassDecl) { 11946 assert(ClassDecl->needsImplicitMoveConstructor()); 11947 11948 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 11949 if (DSM.isAlreadyBeingDeclared()) 11950 return nullptr; 11951 11952 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11953 QualType ArgType = Context.getRValueReferenceType(ClassType); 11954 11955 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11956 CXXMoveConstructor, 11957 false); 11958 11959 DeclarationName Name 11960 = Context.DeclarationNames.getCXXConstructorName( 11961 Context.getCanonicalType(ClassType)); 11962 SourceLocation ClassLoc = ClassDecl->getLocation(); 11963 DeclarationNameInfo NameInfo(Name, ClassLoc); 11964 11965 // C++11 [class.copy]p11: 11966 // An implicitly-declared copy/move constructor is an inline public 11967 // member of its class. 11968 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 11969 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11970 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11971 Constexpr); 11972 MoveConstructor->setAccess(AS_public); 11973 MoveConstructor->setDefaulted(); 11974 11975 if (getLangOpts().CUDA) { 11976 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 11977 MoveConstructor, 11978 /* ConstRHS */ false, 11979 /* Diagnose */ false); 11980 } 11981 11982 // Build an exception specification pointing back at this member. 11983 FunctionProtoType::ExtProtoInfo EPI = 11984 getImplicitMethodEPI(*this, MoveConstructor); 11985 MoveConstructor->setType( 11986 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11987 11988 // Add the parameter to the constructor. 11989 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 11990 ClassLoc, ClassLoc, 11991 /*IdentifierInfo=*/nullptr, 11992 ArgType, /*TInfo=*/nullptr, 11993 SC_None, nullptr); 11994 MoveConstructor->setParams(FromParam); 11995 11996 MoveConstructor->setTrivial( 11997 ClassDecl->needsOverloadResolutionForMoveConstructor() 11998 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 11999 : ClassDecl->hasTrivialMoveConstructor()); 12000 12001 // Note that we have declared this constructor. 12002 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12003 12004 Scope *S = getScopeForContext(ClassDecl); 12005 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12006 12007 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12008 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12009 SetDeclDeleted(MoveConstructor, ClassLoc); 12010 } 12011 12012 if (S) 12013 PushOnScopeChains(MoveConstructor, S, false); 12014 ClassDecl->addDecl(MoveConstructor); 12015 12016 return MoveConstructor; 12017 } 12018 12019 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12020 CXXConstructorDecl *MoveConstructor) { 12021 assert((MoveConstructor->isDefaulted() && 12022 MoveConstructor->isMoveConstructor() && 12023 !MoveConstructor->doesThisDeclarationHaveABody() && 12024 !MoveConstructor->isDeleted()) && 12025 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12026 12027 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12028 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12029 12030 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12031 DiagnosticErrorTrap Trap(Diags); 12032 12033 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 12034 Trap.hasErrorOccurred()) { 12035 Diag(CurrentLocation, diag::note_member_synthesized_at) 12036 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 12037 MoveConstructor->setInvalidDecl(); 12038 } else { 12039 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12040 ? MoveConstructor->getLocEnd() 12041 : MoveConstructor->getLocation(); 12042 Sema::CompoundScopeRAII CompoundScope(*this); 12043 MoveConstructor->setBody(ActOnCompoundStmt( 12044 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12045 } 12046 12047 // The exception specification is needed because we are defining the 12048 // function. 12049 ResolveExceptionSpec(CurrentLocation, 12050 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12051 12052 MoveConstructor->markUsed(Context); 12053 MarkVTableUsed(CurrentLocation, ClassDecl); 12054 12055 if (ASTMutationListener *L = getASTMutationListener()) { 12056 L->CompletedImplicitDefinition(MoveConstructor); 12057 } 12058 } 12059 12060 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12061 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12062 } 12063 12064 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12065 SourceLocation CurrentLocation, 12066 CXXConversionDecl *Conv) { 12067 CXXRecordDecl *Lambda = Conv->getParent(); 12068 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 12069 // If we are defining a specialization of a conversion to function-ptr 12070 // cache the deduced template arguments for this specialization 12071 // so that we can use them to retrieve the corresponding call-operator 12072 // and static-invoker. 12073 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 12074 12075 // Retrieve the corresponding call-operator specialization. 12076 if (Lambda->isGenericLambda()) { 12077 assert(Conv->isFunctionTemplateSpecialization()); 12078 FunctionTemplateDecl *CallOpTemplate = 12079 CallOp->getDescribedFunctionTemplate(); 12080 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 12081 void *InsertPos = nullptr; 12082 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 12083 DeducedTemplateArgs->asArray(), 12084 InsertPos); 12085 assert(CallOpSpec && 12086 "Conversion operator must have a corresponding call operator"); 12087 CallOp = cast<CXXMethodDecl>(CallOpSpec); 12088 } 12089 // Mark the call operator referenced (and add to pending instantiations 12090 // if necessary). 12091 // For both the conversion and static-invoker template specializations 12092 // we construct their body's in this function, so no need to add them 12093 // to the PendingInstantiations. 12094 MarkFunctionReferenced(CurrentLocation, CallOp); 12095 12096 SynthesizedFunctionScope Scope(*this, Conv); 12097 DiagnosticErrorTrap Trap(Diags); 12098 12099 // Retrieve the static invoker... 12100 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12101 // ... and get the corresponding specialization for a generic lambda. 12102 if (Lambda->isGenericLambda()) { 12103 assert(DeducedTemplateArgs && 12104 "Must have deduced template arguments from Conversion Operator"); 12105 FunctionTemplateDecl *InvokeTemplate = 12106 Invoker->getDescribedFunctionTemplate(); 12107 void *InsertPos = nullptr; 12108 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 12109 DeducedTemplateArgs->asArray(), 12110 InsertPos); 12111 assert(InvokeSpec && 12112 "Must have a corresponding static invoker specialization"); 12113 Invoker = cast<CXXMethodDecl>(InvokeSpec); 12114 } 12115 // Construct the body of the conversion function { return __invoke; }. 12116 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12117 VK_LValue, Conv->getLocation()).get(); 12118 assert(FunctionRef && "Can't refer to __invoke function?"); 12119 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12120 Conv->setBody(new (Context) CompoundStmt(Context, Return, 12121 Conv->getLocation(), 12122 Conv->getLocation())); 12123 12124 Conv->markUsed(Context); 12125 Conv->setReferenced(); 12126 12127 // Fill in the __invoke function with a dummy implementation. IR generation 12128 // will fill in the actual details. 12129 Invoker->markUsed(Context); 12130 Invoker->setReferenced(); 12131 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12132 12133 if (ASTMutationListener *L = getASTMutationListener()) { 12134 L->CompletedImplicitDefinition(Conv); 12135 L->CompletedImplicitDefinition(Invoker); 12136 } 12137 } 12138 12139 12140 12141 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12142 SourceLocation CurrentLocation, 12143 CXXConversionDecl *Conv) 12144 { 12145 assert(!Conv->getParent()->isGenericLambda()); 12146 12147 Conv->markUsed(Context); 12148 12149 SynthesizedFunctionScope Scope(*this, Conv); 12150 DiagnosticErrorTrap Trap(Diags); 12151 12152 // Copy-initialize the lambda object as needed to capture it. 12153 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12154 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12155 12156 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12157 Conv->getLocation(), 12158 Conv, DerefThis); 12159 12160 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12161 // behavior. Note that only the general conversion function does this 12162 // (since it's unusable otherwise); in the case where we inline the 12163 // block literal, it has block literal lifetime semantics. 12164 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12165 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12166 CK_CopyAndAutoreleaseBlockObject, 12167 BuildBlock.get(), nullptr, VK_RValue); 12168 12169 if (BuildBlock.isInvalid()) { 12170 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12171 Conv->setInvalidDecl(); 12172 return; 12173 } 12174 12175 // Create the return statement that returns the block from the conversion 12176 // function. 12177 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12178 if (Return.isInvalid()) { 12179 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12180 Conv->setInvalidDecl(); 12181 return; 12182 } 12183 12184 // Set the body of the conversion function. 12185 Stmt *ReturnS = Return.get(); 12186 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 12187 Conv->getLocation(), 12188 Conv->getLocation())); 12189 12190 // We're done; notify the mutation listener, if any. 12191 if (ASTMutationListener *L = getASTMutationListener()) { 12192 L->CompletedImplicitDefinition(Conv); 12193 } 12194 } 12195 12196 /// \brief Determine whether the given list arguments contains exactly one 12197 /// "real" (non-default) argument. 12198 static bool hasOneRealArgument(MultiExprArg Args) { 12199 switch (Args.size()) { 12200 case 0: 12201 return false; 12202 12203 default: 12204 if (!Args[1]->isDefaultArgument()) 12205 return false; 12206 12207 // fall through 12208 case 1: 12209 return !Args[0]->isDefaultArgument(); 12210 } 12211 12212 return false; 12213 } 12214 12215 ExprResult 12216 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12217 NamedDecl *FoundDecl, 12218 CXXConstructorDecl *Constructor, 12219 MultiExprArg ExprArgs, 12220 bool HadMultipleCandidates, 12221 bool IsListInitialization, 12222 bool IsStdInitListInitialization, 12223 bool RequiresZeroInit, 12224 unsigned ConstructKind, 12225 SourceRange ParenRange) { 12226 bool Elidable = false; 12227 12228 // C++0x [class.copy]p34: 12229 // When certain criteria are met, an implementation is allowed to 12230 // omit the copy/move construction of a class object, even if the 12231 // copy/move constructor and/or destructor for the object have 12232 // side effects. [...] 12233 // - when a temporary class object that has not been bound to a 12234 // reference (12.2) would be copied/moved to a class object 12235 // with the same cv-unqualified type, the copy/move operation 12236 // can be omitted by constructing the temporary object 12237 // directly into the target of the omitted copy/move 12238 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12239 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12240 Expr *SubExpr = ExprArgs[0]; 12241 Elidable = SubExpr->isTemporaryObject( 12242 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12243 } 12244 12245 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12246 FoundDecl, Constructor, 12247 Elidable, ExprArgs, HadMultipleCandidates, 12248 IsListInitialization, 12249 IsStdInitListInitialization, RequiresZeroInit, 12250 ConstructKind, ParenRange); 12251 } 12252 12253 ExprResult 12254 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12255 NamedDecl *FoundDecl, 12256 CXXConstructorDecl *Constructor, 12257 bool Elidable, 12258 MultiExprArg ExprArgs, 12259 bool HadMultipleCandidates, 12260 bool IsListInitialization, 12261 bool IsStdInitListInitialization, 12262 bool RequiresZeroInit, 12263 unsigned ConstructKind, 12264 SourceRange ParenRange) { 12265 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12266 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12267 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12268 return ExprError(); 12269 } 12270 12271 return BuildCXXConstructExpr( 12272 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12273 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12274 RequiresZeroInit, ConstructKind, ParenRange); 12275 } 12276 12277 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12278 /// including handling of its default argument expressions. 12279 ExprResult 12280 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12281 CXXConstructorDecl *Constructor, 12282 bool Elidable, 12283 MultiExprArg ExprArgs, 12284 bool HadMultipleCandidates, 12285 bool IsListInitialization, 12286 bool IsStdInitListInitialization, 12287 bool RequiresZeroInit, 12288 unsigned ConstructKind, 12289 SourceRange ParenRange) { 12290 assert(declaresSameEntity( 12291 Constructor->getParent(), 12292 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12293 "given constructor for wrong type"); 12294 MarkFunctionReferenced(ConstructLoc, Constructor); 12295 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12296 return ExprError(); 12297 12298 return CXXConstructExpr::Create( 12299 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12300 ExprArgs, HadMultipleCandidates, IsListInitialization, 12301 IsStdInitListInitialization, RequiresZeroInit, 12302 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12303 ParenRange); 12304 } 12305 12306 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12307 assert(Field->hasInClassInitializer()); 12308 12309 // If we already have the in-class initializer nothing needs to be done. 12310 if (Field->getInClassInitializer()) 12311 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12312 12313 // Maybe we haven't instantiated the in-class initializer. Go check the 12314 // pattern FieldDecl to see if it has one. 12315 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12316 12317 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12318 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12319 DeclContext::lookup_result Lookup = 12320 ClassPattern->lookup(Field->getDeclName()); 12321 12322 // Lookup can return at most two results: the pattern for the field, or the 12323 // injected class name of the parent record. No other member can have the 12324 // same name as the field. 12325 assert(!Lookup.empty() && Lookup.size() <= 2 && 12326 "more than two lookup results for field name"); 12327 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12328 if (!Pattern) { 12329 assert(isa<CXXRecordDecl>(Lookup[0]) && 12330 "cannot have other non-field member with same name"); 12331 Pattern = cast<FieldDecl>(Lookup[1]); 12332 } 12333 12334 if (InstantiateInClassInitializer(Loc, Field, Pattern, 12335 getTemplateInstantiationArgs(Field))) 12336 return ExprError(); 12337 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12338 } 12339 12340 // DR1351: 12341 // If the brace-or-equal-initializer of a non-static data member 12342 // invokes a defaulted default constructor of its class or of an 12343 // enclosing class in a potentially evaluated subexpression, the 12344 // program is ill-formed. 12345 // 12346 // This resolution is unworkable: the exception specification of the 12347 // default constructor can be needed in an unevaluated context, in 12348 // particular, in the operand of a noexcept-expression, and we can be 12349 // unable to compute an exception specification for an enclosed class. 12350 // 12351 // Any attempt to resolve the exception specification of a defaulted default 12352 // constructor before the initializer is lexically complete will ultimately 12353 // come here at which point we can diagnose it. 12354 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12355 if (OutermostClass == ParentRD) { 12356 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 12357 << ParentRD << Field; 12358 } else { 12359 Diag(Field->getLocEnd(), 12360 diag::err_in_class_initializer_not_yet_parsed_outer_class) 12361 << ParentRD << OutermostClass << Field; 12362 } 12363 12364 return ExprError(); 12365 } 12366 12367 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12368 if (VD->isInvalidDecl()) return; 12369 12370 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12371 if (ClassDecl->isInvalidDecl()) return; 12372 if (ClassDecl->hasIrrelevantDestructor()) return; 12373 if (ClassDecl->isDependentContext()) return; 12374 12375 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12376 MarkFunctionReferenced(VD->getLocation(), Destructor); 12377 CheckDestructorAccess(VD->getLocation(), Destructor, 12378 PDiag(diag::err_access_dtor_var) 12379 << VD->getDeclName() 12380 << VD->getType()); 12381 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12382 12383 if (Destructor->isTrivial()) return; 12384 if (!VD->hasGlobalStorage()) return; 12385 12386 // Emit warning for non-trivial dtor in global scope (a real global, 12387 // class-static, function-static). 12388 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12389 12390 // TODO: this should be re-enabled for static locals by !CXAAtExit 12391 if (!VD->isStaticLocal()) 12392 Diag(VD->getLocation(), diag::warn_global_destructor); 12393 } 12394 12395 /// \brief Given a constructor and the set of arguments provided for the 12396 /// constructor, convert the arguments and add any required default arguments 12397 /// to form a proper call to this constructor. 12398 /// 12399 /// \returns true if an error occurred, false otherwise. 12400 bool 12401 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12402 MultiExprArg ArgsPtr, 12403 SourceLocation Loc, 12404 SmallVectorImpl<Expr*> &ConvertedArgs, 12405 bool AllowExplicit, 12406 bool IsListInitialization) { 12407 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12408 unsigned NumArgs = ArgsPtr.size(); 12409 Expr **Args = ArgsPtr.data(); 12410 12411 const FunctionProtoType *Proto 12412 = Constructor->getType()->getAs<FunctionProtoType>(); 12413 assert(Proto && "Constructor without a prototype?"); 12414 unsigned NumParams = Proto->getNumParams(); 12415 12416 // If too few arguments are available, we'll fill in the rest with defaults. 12417 if (NumArgs < NumParams) 12418 ConvertedArgs.reserve(NumParams); 12419 else 12420 ConvertedArgs.reserve(NumArgs); 12421 12422 VariadicCallType CallType = 12423 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12424 SmallVector<Expr *, 8> AllArgs; 12425 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12426 Proto, 0, 12427 llvm::makeArrayRef(Args, NumArgs), 12428 AllArgs, 12429 CallType, AllowExplicit, 12430 IsListInitialization); 12431 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12432 12433 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12434 12435 CheckConstructorCall(Constructor, 12436 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12437 Proto, Loc); 12438 12439 return Invalid; 12440 } 12441 12442 static inline bool 12443 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12444 const FunctionDecl *FnDecl) { 12445 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12446 if (isa<NamespaceDecl>(DC)) { 12447 return SemaRef.Diag(FnDecl->getLocation(), 12448 diag::err_operator_new_delete_declared_in_namespace) 12449 << FnDecl->getDeclName(); 12450 } 12451 12452 if (isa<TranslationUnitDecl>(DC) && 12453 FnDecl->getStorageClass() == SC_Static) { 12454 return SemaRef.Diag(FnDecl->getLocation(), 12455 diag::err_operator_new_delete_declared_static) 12456 << FnDecl->getDeclName(); 12457 } 12458 12459 return false; 12460 } 12461 12462 static inline bool 12463 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12464 CanQualType ExpectedResultType, 12465 CanQualType ExpectedFirstParamType, 12466 unsigned DependentParamTypeDiag, 12467 unsigned InvalidParamTypeDiag) { 12468 QualType ResultType = 12469 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12470 12471 // Check that the result type is not dependent. 12472 if (ResultType->isDependentType()) 12473 return SemaRef.Diag(FnDecl->getLocation(), 12474 diag::err_operator_new_delete_dependent_result_type) 12475 << FnDecl->getDeclName() << ExpectedResultType; 12476 12477 // Check that the result type is what we expect. 12478 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12479 return SemaRef.Diag(FnDecl->getLocation(), 12480 diag::err_operator_new_delete_invalid_result_type) 12481 << FnDecl->getDeclName() << ExpectedResultType; 12482 12483 // A function template must have at least 2 parameters. 12484 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12485 return SemaRef.Diag(FnDecl->getLocation(), 12486 diag::err_operator_new_delete_template_too_few_parameters) 12487 << FnDecl->getDeclName(); 12488 12489 // The function decl must have at least 1 parameter. 12490 if (FnDecl->getNumParams() == 0) 12491 return SemaRef.Diag(FnDecl->getLocation(), 12492 diag::err_operator_new_delete_too_few_parameters) 12493 << FnDecl->getDeclName(); 12494 12495 // Check the first parameter type is not dependent. 12496 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12497 if (FirstParamType->isDependentType()) 12498 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12499 << FnDecl->getDeclName() << ExpectedFirstParamType; 12500 12501 // Check that the first parameter type is what we expect. 12502 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12503 ExpectedFirstParamType) 12504 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12505 << FnDecl->getDeclName() << ExpectedFirstParamType; 12506 12507 return false; 12508 } 12509 12510 static bool 12511 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12512 // C++ [basic.stc.dynamic.allocation]p1: 12513 // A program is ill-formed if an allocation function is declared in a 12514 // namespace scope other than global scope or declared static in global 12515 // scope. 12516 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12517 return true; 12518 12519 CanQualType SizeTy = 12520 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12521 12522 // C++ [basic.stc.dynamic.allocation]p1: 12523 // The return type shall be void*. The first parameter shall have type 12524 // std::size_t. 12525 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12526 SizeTy, 12527 diag::err_operator_new_dependent_param_type, 12528 diag::err_operator_new_param_type)) 12529 return true; 12530 12531 // C++ [basic.stc.dynamic.allocation]p1: 12532 // The first parameter shall not have an associated default argument. 12533 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12534 return SemaRef.Diag(FnDecl->getLocation(), 12535 diag::err_operator_new_default_arg) 12536 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12537 12538 return false; 12539 } 12540 12541 static bool 12542 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12543 // C++ [basic.stc.dynamic.deallocation]p1: 12544 // A program is ill-formed if deallocation functions are declared in a 12545 // namespace scope other than global scope or declared static in global 12546 // scope. 12547 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12548 return true; 12549 12550 // C++ [basic.stc.dynamic.deallocation]p2: 12551 // Each deallocation function shall return void and its first parameter 12552 // shall be void*. 12553 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 12554 SemaRef.Context.VoidPtrTy, 12555 diag::err_operator_delete_dependent_param_type, 12556 diag::err_operator_delete_param_type)) 12557 return true; 12558 12559 return false; 12560 } 12561 12562 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12563 /// of this overloaded operator is well-formed. If so, returns false; 12564 /// otherwise, emits appropriate diagnostics and returns true. 12565 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12566 assert(FnDecl && FnDecl->isOverloadedOperator() && 12567 "Expected an overloaded operator declaration"); 12568 12569 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12570 12571 // C++ [over.oper]p5: 12572 // The allocation and deallocation functions, operator new, 12573 // operator new[], operator delete and operator delete[], are 12574 // described completely in 3.7.3. The attributes and restrictions 12575 // found in the rest of this subclause do not apply to them unless 12576 // explicitly stated in 3.7.3. 12577 if (Op == OO_Delete || Op == OO_Array_Delete) 12578 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12579 12580 if (Op == OO_New || Op == OO_Array_New) 12581 return CheckOperatorNewDeclaration(*this, FnDecl); 12582 12583 // C++ [over.oper]p6: 12584 // An operator function shall either be a non-static member 12585 // function or be a non-member function and have at least one 12586 // parameter whose type is a class, a reference to a class, an 12587 // enumeration, or a reference to an enumeration. 12588 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12589 if (MethodDecl->isStatic()) 12590 return Diag(FnDecl->getLocation(), 12591 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12592 } else { 12593 bool ClassOrEnumParam = false; 12594 for (auto Param : FnDecl->parameters()) { 12595 QualType ParamType = Param->getType().getNonReferenceType(); 12596 if (ParamType->isDependentType() || ParamType->isRecordType() || 12597 ParamType->isEnumeralType()) { 12598 ClassOrEnumParam = true; 12599 break; 12600 } 12601 } 12602 12603 if (!ClassOrEnumParam) 12604 return Diag(FnDecl->getLocation(), 12605 diag::err_operator_overload_needs_class_or_enum) 12606 << FnDecl->getDeclName(); 12607 } 12608 12609 // C++ [over.oper]p8: 12610 // An operator function cannot have default arguments (8.3.6), 12611 // except where explicitly stated below. 12612 // 12613 // Only the function-call operator allows default arguments 12614 // (C++ [over.call]p1). 12615 if (Op != OO_Call) { 12616 for (auto Param : FnDecl->parameters()) { 12617 if (Param->hasDefaultArg()) 12618 return Diag(Param->getLocation(), 12619 diag::err_operator_overload_default_arg) 12620 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12621 } 12622 } 12623 12624 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12625 { false, false, false } 12626 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12627 , { Unary, Binary, MemberOnly } 12628 #include "clang/Basic/OperatorKinds.def" 12629 }; 12630 12631 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12632 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12633 bool MustBeMemberOperator = OperatorUses[Op][2]; 12634 12635 // C++ [over.oper]p8: 12636 // [...] Operator functions cannot have more or fewer parameters 12637 // than the number required for the corresponding operator, as 12638 // described in the rest of this subclause. 12639 unsigned NumParams = FnDecl->getNumParams() 12640 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12641 if (Op != OO_Call && 12642 ((NumParams == 1 && !CanBeUnaryOperator) || 12643 (NumParams == 2 && !CanBeBinaryOperator) || 12644 (NumParams < 1) || (NumParams > 2))) { 12645 // We have the wrong number of parameters. 12646 unsigned ErrorKind; 12647 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12648 ErrorKind = 2; // 2 -> unary or binary. 12649 } else if (CanBeUnaryOperator) { 12650 ErrorKind = 0; // 0 -> unary 12651 } else { 12652 assert(CanBeBinaryOperator && 12653 "All non-call overloaded operators are unary or binary!"); 12654 ErrorKind = 1; // 1 -> binary 12655 } 12656 12657 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12658 << FnDecl->getDeclName() << NumParams << ErrorKind; 12659 } 12660 12661 // Overloaded operators other than operator() cannot be variadic. 12662 if (Op != OO_Call && 12663 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12664 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12665 << FnDecl->getDeclName(); 12666 } 12667 12668 // Some operators must be non-static member functions. 12669 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12670 return Diag(FnDecl->getLocation(), 12671 diag::err_operator_overload_must_be_member) 12672 << FnDecl->getDeclName(); 12673 } 12674 12675 // C++ [over.inc]p1: 12676 // The user-defined function called operator++ implements the 12677 // prefix and postfix ++ operator. If this function is a member 12678 // function with no parameters, or a non-member function with one 12679 // parameter of class or enumeration type, it defines the prefix 12680 // increment operator ++ for objects of that type. If the function 12681 // is a member function with one parameter (which shall be of type 12682 // int) or a non-member function with two parameters (the second 12683 // of which shall be of type int), it defines the postfix 12684 // increment operator ++ for objects of that type. 12685 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12686 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12687 QualType ParamType = LastParam->getType(); 12688 12689 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12690 !ParamType->isDependentType()) 12691 return Diag(LastParam->getLocation(), 12692 diag::err_operator_overload_post_incdec_must_be_int) 12693 << LastParam->getType() << (Op == OO_MinusMinus); 12694 } 12695 12696 return false; 12697 } 12698 12699 static bool 12700 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 12701 FunctionTemplateDecl *TpDecl) { 12702 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 12703 12704 // Must have one or two template parameters. 12705 if (TemplateParams->size() == 1) { 12706 NonTypeTemplateParmDecl *PmDecl = 12707 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 12708 12709 // The template parameter must be a char parameter pack. 12710 if (PmDecl && PmDecl->isTemplateParameterPack() && 12711 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 12712 return false; 12713 12714 } else if (TemplateParams->size() == 2) { 12715 TemplateTypeParmDecl *PmType = 12716 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 12717 NonTypeTemplateParmDecl *PmArgs = 12718 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 12719 12720 // The second template parameter must be a parameter pack with the 12721 // first template parameter as its type. 12722 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 12723 PmArgs->isTemplateParameterPack()) { 12724 const TemplateTypeParmType *TArgs = 12725 PmArgs->getType()->getAs<TemplateTypeParmType>(); 12726 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 12727 TArgs->getIndex() == PmType->getIndex()) { 12728 if (SemaRef.ActiveTemplateInstantiations.empty()) 12729 SemaRef.Diag(TpDecl->getLocation(), 12730 diag::ext_string_literal_operator_template); 12731 return false; 12732 } 12733 } 12734 } 12735 12736 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 12737 diag::err_literal_operator_template) 12738 << TpDecl->getTemplateParameters()->getSourceRange(); 12739 return true; 12740 } 12741 12742 /// CheckLiteralOperatorDeclaration - Check whether the declaration 12743 /// of this literal operator function is well-formed. If so, returns 12744 /// false; otherwise, emits appropriate diagnostics and returns true. 12745 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 12746 if (isa<CXXMethodDecl>(FnDecl)) { 12747 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 12748 << FnDecl->getDeclName(); 12749 return true; 12750 } 12751 12752 if (FnDecl->isExternC()) { 12753 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 12754 return true; 12755 } 12756 12757 // This might be the definition of a literal operator template. 12758 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 12759 12760 // This might be a specialization of a literal operator template. 12761 if (!TpDecl) 12762 TpDecl = FnDecl->getPrimaryTemplate(); 12763 12764 // template <char...> type operator "" name() and 12765 // template <class T, T...> type operator "" name() are the only valid 12766 // template signatures, and the only valid signatures with no parameters. 12767 if (TpDecl) { 12768 if (FnDecl->param_size() != 0) { 12769 Diag(FnDecl->getLocation(), 12770 diag::err_literal_operator_template_with_params); 12771 return true; 12772 } 12773 12774 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 12775 return true; 12776 12777 } else if (FnDecl->param_size() == 1) { 12778 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 12779 12780 QualType ParamType = Param->getType().getUnqualifiedType(); 12781 12782 // Only unsigned long long int, long double, any character type, and const 12783 // char * are allowed as the only parameters. 12784 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 12785 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 12786 Context.hasSameType(ParamType, Context.CharTy) || 12787 Context.hasSameType(ParamType, Context.WideCharTy) || 12788 Context.hasSameType(ParamType, Context.Char16Ty) || 12789 Context.hasSameType(ParamType, Context.Char32Ty)) { 12790 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 12791 QualType InnerType = Ptr->getPointeeType(); 12792 12793 // Pointer parameter must be a const char *. 12794 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 12795 Context.CharTy) && 12796 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 12797 Diag(Param->getSourceRange().getBegin(), 12798 diag::err_literal_operator_param) 12799 << ParamType << "'const char *'" << Param->getSourceRange(); 12800 return true; 12801 } 12802 12803 } else if (ParamType->isRealFloatingType()) { 12804 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12805 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 12806 return true; 12807 12808 } else if (ParamType->isIntegerType()) { 12809 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12810 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 12811 return true; 12812 12813 } else { 12814 Diag(Param->getSourceRange().getBegin(), 12815 diag::err_literal_operator_invalid_param) 12816 << ParamType << Param->getSourceRange(); 12817 return true; 12818 } 12819 12820 } else if (FnDecl->param_size() == 2) { 12821 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 12822 12823 // First, verify that the first parameter is correct. 12824 12825 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 12826 12827 // Two parameter function must have a pointer to const as a 12828 // first parameter; let's strip those qualifiers. 12829 const PointerType *PT = FirstParamType->getAs<PointerType>(); 12830 12831 if (!PT) { 12832 Diag((*Param)->getSourceRange().getBegin(), 12833 diag::err_literal_operator_param) 12834 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12835 return true; 12836 } 12837 12838 QualType PointeeType = PT->getPointeeType(); 12839 // First parameter must be const 12840 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 12841 Diag((*Param)->getSourceRange().getBegin(), 12842 diag::err_literal_operator_param) 12843 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12844 return true; 12845 } 12846 12847 QualType InnerType = PointeeType.getUnqualifiedType(); 12848 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 12849 // are allowed as the first parameter to a two-parameter function 12850 if (!(Context.hasSameType(InnerType, Context.CharTy) || 12851 Context.hasSameType(InnerType, Context.WideCharTy) || 12852 Context.hasSameType(InnerType, Context.Char16Ty) || 12853 Context.hasSameType(InnerType, Context.Char32Ty))) { 12854 Diag((*Param)->getSourceRange().getBegin(), 12855 diag::err_literal_operator_param) 12856 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12857 return true; 12858 } 12859 12860 // Move on to the second and final parameter. 12861 ++Param; 12862 12863 // The second parameter must be a std::size_t. 12864 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 12865 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 12866 Diag((*Param)->getSourceRange().getBegin(), 12867 diag::err_literal_operator_param) 12868 << SecondParamType << Context.getSizeType() 12869 << (*Param)->getSourceRange(); 12870 return true; 12871 } 12872 } else { 12873 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 12874 return true; 12875 } 12876 12877 // Parameters are good. 12878 12879 // A parameter-declaration-clause containing a default argument is not 12880 // equivalent to any of the permitted forms. 12881 for (auto Param : FnDecl->parameters()) { 12882 if (Param->hasDefaultArg()) { 12883 Diag(Param->getDefaultArgRange().getBegin(), 12884 diag::err_literal_operator_default_argument) 12885 << Param->getDefaultArgRange(); 12886 break; 12887 } 12888 } 12889 12890 StringRef LiteralName 12891 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 12892 if (LiteralName[0] != '_') { 12893 // C++11 [usrlit.suffix]p1: 12894 // Literal suffix identifiers that do not start with an underscore 12895 // are reserved for future standardization. 12896 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 12897 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 12898 } 12899 12900 return false; 12901 } 12902 12903 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 12904 /// linkage specification, including the language and (if present) 12905 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 12906 /// language string literal. LBraceLoc, if valid, provides the location of 12907 /// the '{' brace. Otherwise, this linkage specification does not 12908 /// have any braces. 12909 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 12910 Expr *LangStr, 12911 SourceLocation LBraceLoc) { 12912 StringLiteral *Lit = cast<StringLiteral>(LangStr); 12913 if (!Lit->isAscii()) { 12914 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 12915 << LangStr->getSourceRange(); 12916 return nullptr; 12917 } 12918 12919 StringRef Lang = Lit->getString(); 12920 LinkageSpecDecl::LanguageIDs Language; 12921 if (Lang == "C") 12922 Language = LinkageSpecDecl::lang_c; 12923 else if (Lang == "C++") 12924 Language = LinkageSpecDecl::lang_cxx; 12925 else { 12926 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 12927 << LangStr->getSourceRange(); 12928 return nullptr; 12929 } 12930 12931 // FIXME: Add all the various semantics of linkage specifications 12932 12933 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 12934 LangStr->getExprLoc(), Language, 12935 LBraceLoc.isValid()); 12936 CurContext->addDecl(D); 12937 PushDeclContext(S, D); 12938 return D; 12939 } 12940 12941 /// ActOnFinishLinkageSpecification - Complete the definition of 12942 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 12943 /// valid, it's the position of the closing '}' brace in a linkage 12944 /// specification that uses braces. 12945 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 12946 Decl *LinkageSpec, 12947 SourceLocation RBraceLoc) { 12948 if (RBraceLoc.isValid()) { 12949 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 12950 LSDecl->setRBraceLoc(RBraceLoc); 12951 } 12952 PopDeclContext(); 12953 return LinkageSpec; 12954 } 12955 12956 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 12957 AttributeList *AttrList, 12958 SourceLocation SemiLoc) { 12959 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 12960 // Attribute declarations appertain to empty declaration so we handle 12961 // them here. 12962 if (AttrList) 12963 ProcessDeclAttributeList(S, ED, AttrList); 12964 12965 CurContext->addDecl(ED); 12966 return ED; 12967 } 12968 12969 /// \brief Perform semantic analysis for the variable declaration that 12970 /// occurs within a C++ catch clause, returning the newly-created 12971 /// variable. 12972 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 12973 TypeSourceInfo *TInfo, 12974 SourceLocation StartLoc, 12975 SourceLocation Loc, 12976 IdentifierInfo *Name) { 12977 bool Invalid = false; 12978 QualType ExDeclType = TInfo->getType(); 12979 12980 // Arrays and functions decay. 12981 if (ExDeclType->isArrayType()) 12982 ExDeclType = Context.getArrayDecayedType(ExDeclType); 12983 else if (ExDeclType->isFunctionType()) 12984 ExDeclType = Context.getPointerType(ExDeclType); 12985 12986 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 12987 // The exception-declaration shall not denote a pointer or reference to an 12988 // incomplete type, other than [cv] void*. 12989 // N2844 forbids rvalue references. 12990 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 12991 Diag(Loc, diag::err_catch_rvalue_ref); 12992 Invalid = true; 12993 } 12994 12995 if (ExDeclType->isVariablyModifiedType()) { 12996 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 12997 Invalid = true; 12998 } 12999 13000 QualType BaseType = ExDeclType; 13001 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13002 unsigned DK = diag::err_catch_incomplete; 13003 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13004 BaseType = Ptr->getPointeeType(); 13005 Mode = 1; 13006 DK = diag::err_catch_incomplete_ptr; 13007 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13008 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13009 BaseType = Ref->getPointeeType(); 13010 Mode = 2; 13011 DK = diag::err_catch_incomplete_ref; 13012 } 13013 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13014 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13015 Invalid = true; 13016 13017 if (!Invalid && !ExDeclType->isDependentType() && 13018 RequireNonAbstractType(Loc, ExDeclType, 13019 diag::err_abstract_type_in_decl, 13020 AbstractVariableType)) 13021 Invalid = true; 13022 13023 // Only the non-fragile NeXT runtime currently supports C++ catches 13024 // of ObjC types, and no runtime supports catching ObjC types by value. 13025 if (!Invalid && getLangOpts().ObjC1) { 13026 QualType T = ExDeclType; 13027 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13028 T = RT->getPointeeType(); 13029 13030 if (T->isObjCObjectType()) { 13031 Diag(Loc, diag::err_objc_object_catch); 13032 Invalid = true; 13033 } else if (T->isObjCObjectPointerType()) { 13034 // FIXME: should this be a test for macosx-fragile specifically? 13035 if (getLangOpts().ObjCRuntime.isFragile()) 13036 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13037 } 13038 } 13039 13040 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13041 ExDeclType, TInfo, SC_None); 13042 ExDecl->setExceptionVariable(true); 13043 13044 // In ARC, infer 'retaining' for variables of retainable type. 13045 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13046 Invalid = true; 13047 13048 if (!Invalid && !ExDeclType->isDependentType()) { 13049 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13050 // Insulate this from anything else we might currently be parsing. 13051 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 13052 13053 // C++ [except.handle]p16: 13054 // The object declared in an exception-declaration or, if the 13055 // exception-declaration does not specify a name, a temporary (12.2) is 13056 // copy-initialized (8.5) from the exception object. [...] 13057 // The object is destroyed when the handler exits, after the destruction 13058 // of any automatic objects initialized within the handler. 13059 // 13060 // We just pretend to initialize the object with itself, then make sure 13061 // it can be destroyed later. 13062 QualType initType = Context.getExceptionObjectType(ExDeclType); 13063 13064 InitializedEntity entity = 13065 InitializedEntity::InitializeVariable(ExDecl); 13066 InitializationKind initKind = 13067 InitializationKind::CreateCopy(Loc, SourceLocation()); 13068 13069 Expr *opaqueValue = 13070 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13071 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13072 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13073 if (result.isInvalid()) 13074 Invalid = true; 13075 else { 13076 // If the constructor used was non-trivial, set this as the 13077 // "initializer". 13078 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13079 if (!construct->getConstructor()->isTrivial()) { 13080 Expr *init = MaybeCreateExprWithCleanups(construct); 13081 ExDecl->setInit(init); 13082 } 13083 13084 // And make sure it's destructable. 13085 FinalizeVarWithDestructor(ExDecl, recordType); 13086 } 13087 } 13088 } 13089 13090 if (Invalid) 13091 ExDecl->setInvalidDecl(); 13092 13093 return ExDecl; 13094 } 13095 13096 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13097 /// handler. 13098 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13099 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13100 bool Invalid = D.isInvalidType(); 13101 13102 // Check for unexpanded parameter packs. 13103 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13104 UPPC_ExceptionType)) { 13105 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13106 D.getIdentifierLoc()); 13107 Invalid = true; 13108 } 13109 13110 IdentifierInfo *II = D.getIdentifier(); 13111 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13112 LookupOrdinaryName, 13113 ForRedeclaration)) { 13114 // The scope should be freshly made just for us. There is just no way 13115 // it contains any previous declaration, except for function parameters in 13116 // a function-try-block's catch statement. 13117 assert(!S->isDeclScope(PrevDecl)); 13118 if (isDeclInScope(PrevDecl, CurContext, S)) { 13119 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13120 << D.getIdentifier(); 13121 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13122 Invalid = true; 13123 } else if (PrevDecl->isTemplateParameter()) 13124 // Maybe we will complain about the shadowed template parameter. 13125 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13126 } 13127 13128 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13129 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13130 << D.getCXXScopeSpec().getRange(); 13131 Invalid = true; 13132 } 13133 13134 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13135 D.getLocStart(), 13136 D.getIdentifierLoc(), 13137 D.getIdentifier()); 13138 if (Invalid) 13139 ExDecl->setInvalidDecl(); 13140 13141 // Add the exception declaration into this scope. 13142 if (II) 13143 PushOnScopeChains(ExDecl, S); 13144 else 13145 CurContext->addDecl(ExDecl); 13146 13147 ProcessDeclAttributes(S, ExDecl, D); 13148 return ExDecl; 13149 } 13150 13151 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13152 Expr *AssertExpr, 13153 Expr *AssertMessageExpr, 13154 SourceLocation RParenLoc) { 13155 StringLiteral *AssertMessage = 13156 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13157 13158 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13159 return nullptr; 13160 13161 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13162 AssertMessage, RParenLoc, false); 13163 } 13164 13165 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13166 Expr *AssertExpr, 13167 StringLiteral *AssertMessage, 13168 SourceLocation RParenLoc, 13169 bool Failed) { 13170 assert(AssertExpr != nullptr && "Expected non-null condition"); 13171 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13172 !Failed) { 13173 // In a static_assert-declaration, the constant-expression shall be a 13174 // constant expression that can be contextually converted to bool. 13175 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13176 if (Converted.isInvalid()) 13177 Failed = true; 13178 13179 llvm::APSInt Cond; 13180 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13181 diag::err_static_assert_expression_is_not_constant, 13182 /*AllowFold=*/false).isInvalid()) 13183 Failed = true; 13184 13185 if (!Failed && !Cond) { 13186 SmallString<256> MsgBuffer; 13187 llvm::raw_svector_ostream Msg(MsgBuffer); 13188 if (AssertMessage) 13189 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13190 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13191 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13192 Failed = true; 13193 } 13194 } 13195 13196 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13197 AssertExpr, AssertMessage, RParenLoc, 13198 Failed); 13199 13200 CurContext->addDecl(Decl); 13201 return Decl; 13202 } 13203 13204 /// \brief Perform semantic analysis of the given friend type declaration. 13205 /// 13206 /// \returns A friend declaration that. 13207 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13208 SourceLocation FriendLoc, 13209 TypeSourceInfo *TSInfo) { 13210 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13211 13212 QualType T = TSInfo->getType(); 13213 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13214 13215 // C++03 [class.friend]p2: 13216 // An elaborated-type-specifier shall be used in a friend declaration 13217 // for a class.* 13218 // 13219 // * The class-key of the elaborated-type-specifier is required. 13220 if (!ActiveTemplateInstantiations.empty()) { 13221 // Do not complain about the form of friend template types during 13222 // template instantiation; we will already have complained when the 13223 // template was declared. 13224 } else { 13225 if (!T->isElaboratedTypeSpecifier()) { 13226 // If we evaluated the type to a record type, suggest putting 13227 // a tag in front. 13228 if (const RecordType *RT = T->getAs<RecordType>()) { 13229 RecordDecl *RD = RT->getDecl(); 13230 13231 SmallString<16> InsertionText(" "); 13232 InsertionText += RD->getKindName(); 13233 13234 Diag(TypeRange.getBegin(), 13235 getLangOpts().CPlusPlus11 ? 13236 diag::warn_cxx98_compat_unelaborated_friend_type : 13237 diag::ext_unelaborated_friend_type) 13238 << (unsigned) RD->getTagKind() 13239 << T 13240 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13241 InsertionText); 13242 } else { 13243 Diag(FriendLoc, 13244 getLangOpts().CPlusPlus11 ? 13245 diag::warn_cxx98_compat_nonclass_type_friend : 13246 diag::ext_nonclass_type_friend) 13247 << T 13248 << TypeRange; 13249 } 13250 } else if (T->getAs<EnumType>()) { 13251 Diag(FriendLoc, 13252 getLangOpts().CPlusPlus11 ? 13253 diag::warn_cxx98_compat_enum_friend : 13254 diag::ext_enum_friend) 13255 << T 13256 << TypeRange; 13257 } 13258 13259 // C++11 [class.friend]p3: 13260 // A friend declaration that does not declare a function shall have one 13261 // of the following forms: 13262 // friend elaborated-type-specifier ; 13263 // friend simple-type-specifier ; 13264 // friend typename-specifier ; 13265 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13266 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13267 } 13268 13269 // If the type specifier in a friend declaration designates a (possibly 13270 // cv-qualified) class type, that class is declared as a friend; otherwise, 13271 // the friend declaration is ignored. 13272 return FriendDecl::Create(Context, CurContext, 13273 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13274 FriendLoc); 13275 } 13276 13277 /// Handle a friend tag declaration where the scope specifier was 13278 /// templated. 13279 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13280 unsigned TagSpec, SourceLocation TagLoc, 13281 CXXScopeSpec &SS, 13282 IdentifierInfo *Name, 13283 SourceLocation NameLoc, 13284 AttributeList *Attr, 13285 MultiTemplateParamsArg TempParamLists) { 13286 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13287 13288 bool isExplicitSpecialization = false; 13289 bool Invalid = false; 13290 13291 if (TemplateParameterList *TemplateParams = 13292 MatchTemplateParametersToScopeSpecifier( 13293 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13294 isExplicitSpecialization, Invalid)) { 13295 if (TemplateParams->size() > 0) { 13296 // This is a declaration of a class template. 13297 if (Invalid) 13298 return nullptr; 13299 13300 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13301 NameLoc, Attr, TemplateParams, AS_public, 13302 /*ModulePrivateLoc=*/SourceLocation(), 13303 FriendLoc, TempParamLists.size() - 1, 13304 TempParamLists.data()).get(); 13305 } else { 13306 // The "template<>" header is extraneous. 13307 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13308 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13309 isExplicitSpecialization = true; 13310 } 13311 } 13312 13313 if (Invalid) return nullptr; 13314 13315 bool isAllExplicitSpecializations = true; 13316 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13317 if (TempParamLists[I]->size()) { 13318 isAllExplicitSpecializations = false; 13319 break; 13320 } 13321 } 13322 13323 // FIXME: don't ignore attributes. 13324 13325 // If it's explicit specializations all the way down, just forget 13326 // about the template header and build an appropriate non-templated 13327 // friend. TODO: for source fidelity, remember the headers. 13328 if (isAllExplicitSpecializations) { 13329 if (SS.isEmpty()) { 13330 bool Owned = false; 13331 bool IsDependent = false; 13332 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13333 Attr, AS_public, 13334 /*ModulePrivateLoc=*/SourceLocation(), 13335 MultiTemplateParamsArg(), Owned, IsDependent, 13336 /*ScopedEnumKWLoc=*/SourceLocation(), 13337 /*ScopedEnumUsesClassTag=*/false, 13338 /*UnderlyingType=*/TypeResult(), 13339 /*IsTypeSpecifier=*/false); 13340 } 13341 13342 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13343 ElaboratedTypeKeyword Keyword 13344 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13345 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13346 *Name, NameLoc); 13347 if (T.isNull()) 13348 return nullptr; 13349 13350 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13351 if (isa<DependentNameType>(T)) { 13352 DependentNameTypeLoc TL = 13353 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13354 TL.setElaboratedKeywordLoc(TagLoc); 13355 TL.setQualifierLoc(QualifierLoc); 13356 TL.setNameLoc(NameLoc); 13357 } else { 13358 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13359 TL.setElaboratedKeywordLoc(TagLoc); 13360 TL.setQualifierLoc(QualifierLoc); 13361 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13362 } 13363 13364 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13365 TSI, FriendLoc, TempParamLists); 13366 Friend->setAccess(AS_public); 13367 CurContext->addDecl(Friend); 13368 return Friend; 13369 } 13370 13371 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13372 13373 13374 13375 // Handle the case of a templated-scope friend class. e.g. 13376 // template <class T> class A<T>::B; 13377 // FIXME: we don't support these right now. 13378 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13379 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13380 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13381 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13382 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13383 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13384 TL.setElaboratedKeywordLoc(TagLoc); 13385 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13386 TL.setNameLoc(NameLoc); 13387 13388 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13389 TSI, FriendLoc, TempParamLists); 13390 Friend->setAccess(AS_public); 13391 Friend->setUnsupportedFriend(true); 13392 CurContext->addDecl(Friend); 13393 return Friend; 13394 } 13395 13396 13397 /// Handle a friend type declaration. This works in tandem with 13398 /// ActOnTag. 13399 /// 13400 /// Notes on friend class templates: 13401 /// 13402 /// We generally treat friend class declarations as if they were 13403 /// declaring a class. So, for example, the elaborated type specifier 13404 /// in a friend declaration is required to obey the restrictions of a 13405 /// class-head (i.e. no typedefs in the scope chain), template 13406 /// parameters are required to match up with simple template-ids, &c. 13407 /// However, unlike when declaring a template specialization, it's 13408 /// okay to refer to a template specialization without an empty 13409 /// template parameter declaration, e.g. 13410 /// friend class A<T>::B<unsigned>; 13411 /// We permit this as a special case; if there are any template 13412 /// parameters present at all, require proper matching, i.e. 13413 /// template <> template \<class T> friend class A<int>::B; 13414 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13415 MultiTemplateParamsArg TempParams) { 13416 SourceLocation Loc = DS.getLocStart(); 13417 13418 assert(DS.isFriendSpecified()); 13419 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13420 13421 // Try to convert the decl specifier to a type. This works for 13422 // friend templates because ActOnTag never produces a ClassTemplateDecl 13423 // for a TUK_Friend. 13424 Declarator TheDeclarator(DS, Declarator::MemberContext); 13425 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13426 QualType T = TSI->getType(); 13427 if (TheDeclarator.isInvalidType()) 13428 return nullptr; 13429 13430 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13431 return nullptr; 13432 13433 // This is definitely an error in C++98. It's probably meant to 13434 // be forbidden in C++0x, too, but the specification is just 13435 // poorly written. 13436 // 13437 // The problem is with declarations like the following: 13438 // template <T> friend A<T>::foo; 13439 // where deciding whether a class C is a friend or not now hinges 13440 // on whether there exists an instantiation of A that causes 13441 // 'foo' to equal C. There are restrictions on class-heads 13442 // (which we declare (by fiat) elaborated friend declarations to 13443 // be) that makes this tractable. 13444 // 13445 // FIXME: handle "template <> friend class A<T>;", which 13446 // is possibly well-formed? Who even knows? 13447 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13448 Diag(Loc, diag::err_tagless_friend_type_template) 13449 << DS.getSourceRange(); 13450 return nullptr; 13451 } 13452 13453 // C++98 [class.friend]p1: A friend of a class is a function 13454 // or class that is not a member of the class . . . 13455 // This is fixed in DR77, which just barely didn't make the C++03 13456 // deadline. It's also a very silly restriction that seriously 13457 // affects inner classes and which nobody else seems to implement; 13458 // thus we never diagnose it, not even in -pedantic. 13459 // 13460 // But note that we could warn about it: it's always useless to 13461 // friend one of your own members (it's not, however, worthless to 13462 // friend a member of an arbitrary specialization of your template). 13463 13464 Decl *D; 13465 if (!TempParams.empty()) 13466 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13467 TempParams, 13468 TSI, 13469 DS.getFriendSpecLoc()); 13470 else 13471 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13472 13473 if (!D) 13474 return nullptr; 13475 13476 D->setAccess(AS_public); 13477 CurContext->addDecl(D); 13478 13479 return D; 13480 } 13481 13482 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13483 MultiTemplateParamsArg TemplateParams) { 13484 const DeclSpec &DS = D.getDeclSpec(); 13485 13486 assert(DS.isFriendSpecified()); 13487 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13488 13489 SourceLocation Loc = D.getIdentifierLoc(); 13490 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13491 13492 // C++ [class.friend]p1 13493 // A friend of a class is a function or class.... 13494 // Note that this sees through typedefs, which is intended. 13495 // It *doesn't* see through dependent types, which is correct 13496 // according to [temp.arg.type]p3: 13497 // If a declaration acquires a function type through a 13498 // type dependent on a template-parameter and this causes 13499 // a declaration that does not use the syntactic form of a 13500 // function declarator to have a function type, the program 13501 // is ill-formed. 13502 if (!TInfo->getType()->isFunctionType()) { 13503 Diag(Loc, diag::err_unexpected_friend); 13504 13505 // It might be worthwhile to try to recover by creating an 13506 // appropriate declaration. 13507 return nullptr; 13508 } 13509 13510 // C++ [namespace.memdef]p3 13511 // - If a friend declaration in a non-local class first declares a 13512 // class or function, the friend class or function is a member 13513 // of the innermost enclosing namespace. 13514 // - The name of the friend is not found by simple name lookup 13515 // until a matching declaration is provided in that namespace 13516 // scope (either before or after the class declaration granting 13517 // friendship). 13518 // - If a friend function is called, its name may be found by the 13519 // name lookup that considers functions from namespaces and 13520 // classes associated with the types of the function arguments. 13521 // - When looking for a prior declaration of a class or a function 13522 // declared as a friend, scopes outside the innermost enclosing 13523 // namespace scope are not considered. 13524 13525 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13526 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13527 DeclarationName Name = NameInfo.getName(); 13528 assert(Name); 13529 13530 // Check for unexpanded parameter packs. 13531 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13532 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13533 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13534 return nullptr; 13535 13536 // The context we found the declaration in, or in which we should 13537 // create the declaration. 13538 DeclContext *DC; 13539 Scope *DCScope = S; 13540 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13541 ForRedeclaration); 13542 13543 // There are five cases here. 13544 // - There's no scope specifier and we're in a local class. Only look 13545 // for functions declared in the immediately-enclosing block scope. 13546 // We recover from invalid scope qualifiers as if they just weren't there. 13547 FunctionDecl *FunctionContainingLocalClass = nullptr; 13548 if ((SS.isInvalid() || !SS.isSet()) && 13549 (FunctionContainingLocalClass = 13550 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13551 // C++11 [class.friend]p11: 13552 // If a friend declaration appears in a local class and the name 13553 // specified is an unqualified name, a prior declaration is 13554 // looked up without considering scopes that are outside the 13555 // innermost enclosing non-class scope. For a friend function 13556 // declaration, if there is no prior declaration, the program is 13557 // ill-formed. 13558 13559 // Find the innermost enclosing non-class scope. This is the block 13560 // scope containing the local class definition (or for a nested class, 13561 // the outer local class). 13562 DCScope = S->getFnParent(); 13563 13564 // Look up the function name in the scope. 13565 Previous.clear(LookupLocalFriendName); 13566 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13567 13568 if (!Previous.empty()) { 13569 // All possible previous declarations must have the same context: 13570 // either they were declared at block scope or they are members of 13571 // one of the enclosing local classes. 13572 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13573 } else { 13574 // This is ill-formed, but provide the context that we would have 13575 // declared the function in, if we were permitted to, for error recovery. 13576 DC = FunctionContainingLocalClass; 13577 } 13578 adjustContextForLocalExternDecl(DC); 13579 13580 // C++ [class.friend]p6: 13581 // A function can be defined in a friend declaration of a class if and 13582 // only if the class is a non-local class (9.8), the function name is 13583 // unqualified, and the function has namespace scope. 13584 if (D.isFunctionDefinition()) { 13585 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13586 } 13587 13588 // - There's no scope specifier, in which case we just go to the 13589 // appropriate scope and look for a function or function template 13590 // there as appropriate. 13591 } else if (SS.isInvalid() || !SS.isSet()) { 13592 // C++11 [namespace.memdef]p3: 13593 // If the name in a friend declaration is neither qualified nor 13594 // a template-id and the declaration is a function or an 13595 // elaborated-type-specifier, the lookup to determine whether 13596 // the entity has been previously declared shall not consider 13597 // any scopes outside the innermost enclosing namespace. 13598 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 13599 13600 // Find the appropriate context according to the above. 13601 DC = CurContext; 13602 13603 // Skip class contexts. If someone can cite chapter and verse 13604 // for this behavior, that would be nice --- it's what GCC and 13605 // EDG do, and it seems like a reasonable intent, but the spec 13606 // really only says that checks for unqualified existing 13607 // declarations should stop at the nearest enclosing namespace, 13608 // not that they should only consider the nearest enclosing 13609 // namespace. 13610 while (DC->isRecord()) 13611 DC = DC->getParent(); 13612 13613 DeclContext *LookupDC = DC; 13614 while (LookupDC->isTransparentContext()) 13615 LookupDC = LookupDC->getParent(); 13616 13617 while (true) { 13618 LookupQualifiedName(Previous, LookupDC); 13619 13620 if (!Previous.empty()) { 13621 DC = LookupDC; 13622 break; 13623 } 13624 13625 if (isTemplateId) { 13626 if (isa<TranslationUnitDecl>(LookupDC)) break; 13627 } else { 13628 if (LookupDC->isFileContext()) break; 13629 } 13630 LookupDC = LookupDC->getParent(); 13631 } 13632 13633 DCScope = getScopeForDeclContext(S, DC); 13634 13635 // - There's a non-dependent scope specifier, in which case we 13636 // compute it and do a previous lookup there for a function 13637 // or function template. 13638 } else if (!SS.getScopeRep()->isDependent()) { 13639 DC = computeDeclContext(SS); 13640 if (!DC) return nullptr; 13641 13642 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13643 13644 LookupQualifiedName(Previous, DC); 13645 13646 // Ignore things found implicitly in the wrong scope. 13647 // TODO: better diagnostics for this case. Suggesting the right 13648 // qualified scope would be nice... 13649 LookupResult::Filter F = Previous.makeFilter(); 13650 while (F.hasNext()) { 13651 NamedDecl *D = F.next(); 13652 if (!DC->InEnclosingNamespaceSetOf( 13653 D->getDeclContext()->getRedeclContext())) 13654 F.erase(); 13655 } 13656 F.done(); 13657 13658 if (Previous.empty()) { 13659 D.setInvalidType(); 13660 Diag(Loc, diag::err_qualified_friend_not_found) 13661 << Name << TInfo->getType(); 13662 return nullptr; 13663 } 13664 13665 // C++ [class.friend]p1: A friend of a class is a function or 13666 // class that is not a member of the class . . . 13667 if (DC->Equals(CurContext)) 13668 Diag(DS.getFriendSpecLoc(), 13669 getLangOpts().CPlusPlus11 ? 13670 diag::warn_cxx98_compat_friend_is_member : 13671 diag::err_friend_is_member); 13672 13673 if (D.isFunctionDefinition()) { 13674 // C++ [class.friend]p6: 13675 // A function can be defined in a friend declaration of a class if and 13676 // only if the class is a non-local class (9.8), the function name is 13677 // unqualified, and the function has namespace scope. 13678 SemaDiagnosticBuilder DB 13679 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 13680 13681 DB << SS.getScopeRep(); 13682 if (DC->isFileContext()) 13683 DB << FixItHint::CreateRemoval(SS.getRange()); 13684 SS.clear(); 13685 } 13686 13687 // - There's a scope specifier that does not match any template 13688 // parameter lists, in which case we use some arbitrary context, 13689 // create a method or method template, and wait for instantiation. 13690 // - There's a scope specifier that does match some template 13691 // parameter lists, which we don't handle right now. 13692 } else { 13693 if (D.isFunctionDefinition()) { 13694 // C++ [class.friend]p6: 13695 // A function can be defined in a friend declaration of a class if and 13696 // only if the class is a non-local class (9.8), the function name is 13697 // unqualified, and the function has namespace scope. 13698 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 13699 << SS.getScopeRep(); 13700 } 13701 13702 DC = CurContext; 13703 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 13704 } 13705 13706 if (!DC->isRecord()) { 13707 int DiagArg = -1; 13708 switch (D.getName().getKind()) { 13709 case UnqualifiedId::IK_ConstructorTemplateId: 13710 case UnqualifiedId::IK_ConstructorName: 13711 DiagArg = 0; 13712 break; 13713 case UnqualifiedId::IK_DestructorName: 13714 DiagArg = 1; 13715 break; 13716 case UnqualifiedId::IK_ConversionFunctionId: 13717 DiagArg = 2; 13718 break; 13719 case UnqualifiedId::IK_Identifier: 13720 case UnqualifiedId::IK_ImplicitSelfParam: 13721 case UnqualifiedId::IK_LiteralOperatorId: 13722 case UnqualifiedId::IK_OperatorFunctionId: 13723 case UnqualifiedId::IK_TemplateId: 13724 break; 13725 } 13726 // This implies that it has to be an operator or function. 13727 if (DiagArg >= 0) { 13728 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 13729 return nullptr; 13730 } 13731 } 13732 13733 // FIXME: This is an egregious hack to cope with cases where the scope stack 13734 // does not contain the declaration context, i.e., in an out-of-line 13735 // definition of a class. 13736 Scope FakeDCScope(S, Scope::DeclScope, Diags); 13737 if (!DCScope) { 13738 FakeDCScope.setEntity(DC); 13739 DCScope = &FakeDCScope; 13740 } 13741 13742 bool AddToScope = true; 13743 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 13744 TemplateParams, AddToScope); 13745 if (!ND) return nullptr; 13746 13747 assert(ND->getLexicalDeclContext() == CurContext); 13748 13749 // If we performed typo correction, we might have added a scope specifier 13750 // and changed the decl context. 13751 DC = ND->getDeclContext(); 13752 13753 // Add the function declaration to the appropriate lookup tables, 13754 // adjusting the redeclarations list as necessary. We don't 13755 // want to do this yet if the friending class is dependent. 13756 // 13757 // Also update the scope-based lookup if the target context's 13758 // lookup context is in lexical scope. 13759 if (!CurContext->isDependentContext()) { 13760 DC = DC->getRedeclContext(); 13761 DC->makeDeclVisibleInContext(ND); 13762 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13763 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 13764 } 13765 13766 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 13767 D.getIdentifierLoc(), ND, 13768 DS.getFriendSpecLoc()); 13769 FrD->setAccess(AS_public); 13770 CurContext->addDecl(FrD); 13771 13772 if (ND->isInvalidDecl()) { 13773 FrD->setInvalidDecl(); 13774 } else { 13775 if (DC->isRecord()) CheckFriendAccess(ND); 13776 13777 FunctionDecl *FD; 13778 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 13779 FD = FTD->getTemplatedDecl(); 13780 else 13781 FD = cast<FunctionDecl>(ND); 13782 13783 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 13784 // default argument expression, that declaration shall be a definition 13785 // and shall be the only declaration of the function or function 13786 // template in the translation unit. 13787 if (functionDeclHasDefaultArgument(FD)) { 13788 // We can't look at FD->getPreviousDecl() because it may not have been set 13789 // if we're in a dependent context. If we get this far with a non-empty 13790 // Previous set, we must have a valid previous declaration of this 13791 // function. 13792 if (!Previous.empty()) { 13793 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 13794 Diag(Previous.getRepresentativeDecl()->getLocation(), 13795 diag::note_previous_declaration); 13796 } else if (!D.isFunctionDefinition()) 13797 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 13798 } 13799 13800 // Mark templated-scope function declarations as unsupported. 13801 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 13802 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 13803 << SS.getScopeRep() << SS.getRange() 13804 << cast<CXXRecordDecl>(CurContext); 13805 FrD->setUnsupportedFriend(true); 13806 } 13807 } 13808 13809 return ND; 13810 } 13811 13812 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 13813 AdjustDeclIfTemplate(Dcl); 13814 13815 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 13816 if (!Fn) { 13817 Diag(DelLoc, diag::err_deleted_non_function); 13818 return; 13819 } 13820 13821 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 13822 // Don't consider the implicit declaration we generate for explicit 13823 // specializations. FIXME: Do not generate these implicit declarations. 13824 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 13825 Prev->getPreviousDecl()) && 13826 !Prev->isDefined()) { 13827 Diag(DelLoc, diag::err_deleted_decl_not_first); 13828 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 13829 Prev->isImplicit() ? diag::note_previous_implicit_declaration 13830 : diag::note_previous_declaration); 13831 } 13832 // If the declaration wasn't the first, we delete the function anyway for 13833 // recovery. 13834 Fn = Fn->getCanonicalDecl(); 13835 } 13836 13837 // dllimport/dllexport cannot be deleted. 13838 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 13839 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 13840 Fn->setInvalidDecl(); 13841 } 13842 13843 if (Fn->isDeleted()) 13844 return; 13845 13846 // See if we're deleting a function which is already known to override a 13847 // non-deleted virtual function. 13848 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 13849 bool IssuedDiagnostic = false; 13850 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 13851 E = MD->end_overridden_methods(); 13852 I != E; ++I) { 13853 if (!(*MD->begin_overridden_methods())->isDeleted()) { 13854 if (!IssuedDiagnostic) { 13855 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 13856 IssuedDiagnostic = true; 13857 } 13858 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 13859 } 13860 } 13861 } 13862 13863 // C++11 [basic.start.main]p3: 13864 // A program that defines main as deleted [...] is ill-formed. 13865 if (Fn->isMain()) 13866 Diag(DelLoc, diag::err_deleted_main); 13867 13868 Fn->setDeletedAsWritten(); 13869 } 13870 13871 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 13872 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 13873 13874 if (MD) { 13875 if (MD->getParent()->isDependentType()) { 13876 MD->setDefaulted(); 13877 MD->setExplicitlyDefaulted(); 13878 return; 13879 } 13880 13881 CXXSpecialMember Member = getSpecialMember(MD); 13882 if (Member == CXXInvalid) { 13883 if (!MD->isInvalidDecl()) 13884 Diag(DefaultLoc, diag::err_default_special_members); 13885 return; 13886 } 13887 13888 MD->setDefaulted(); 13889 MD->setExplicitlyDefaulted(); 13890 13891 // If this definition appears within the record, do the checking when 13892 // the record is complete. 13893 const FunctionDecl *Primary = MD; 13894 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 13895 // Ask the template instantiation pattern that actually had the 13896 // '= default' on it. 13897 Primary = Pattern; 13898 13899 // If the method was defaulted on its first declaration, we will have 13900 // already performed the checking in CheckCompletedCXXClass. Such a 13901 // declaration doesn't trigger an implicit definition. 13902 if (Primary->getCanonicalDecl()->isDefaulted()) 13903 return; 13904 13905 CheckExplicitlyDefaultedSpecialMember(MD); 13906 13907 if (!MD->isInvalidDecl()) 13908 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 13909 } else { 13910 Diag(DefaultLoc, diag::err_default_special_members); 13911 } 13912 } 13913 13914 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 13915 for (Stmt *SubStmt : S->children()) { 13916 if (!SubStmt) 13917 continue; 13918 if (isa<ReturnStmt>(SubStmt)) 13919 Self.Diag(SubStmt->getLocStart(), 13920 diag::err_return_in_constructor_handler); 13921 if (!isa<Expr>(SubStmt)) 13922 SearchForReturnInStmt(Self, SubStmt); 13923 } 13924 } 13925 13926 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 13927 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 13928 CXXCatchStmt *Handler = TryBlock->getHandler(I); 13929 SearchForReturnInStmt(*this, Handler); 13930 } 13931 } 13932 13933 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 13934 const CXXMethodDecl *Old) { 13935 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 13936 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 13937 13938 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 13939 13940 // If the calling conventions match, everything is fine 13941 if (NewCC == OldCC) 13942 return false; 13943 13944 // If the calling conventions mismatch because the new function is static, 13945 // suppress the calling convention mismatch error; the error about static 13946 // function override (err_static_overrides_virtual from 13947 // Sema::CheckFunctionDeclaration) is more clear. 13948 if (New->getStorageClass() == SC_Static) 13949 return false; 13950 13951 Diag(New->getLocation(), 13952 diag::err_conflicting_overriding_cc_attributes) 13953 << New->getDeclName() << New->getType() << Old->getType(); 13954 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 13955 return true; 13956 } 13957 13958 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 13959 const CXXMethodDecl *Old) { 13960 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 13961 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 13962 13963 if (Context.hasSameType(NewTy, OldTy) || 13964 NewTy->isDependentType() || OldTy->isDependentType()) 13965 return false; 13966 13967 // Check if the return types are covariant 13968 QualType NewClassTy, OldClassTy; 13969 13970 /// Both types must be pointers or references to classes. 13971 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 13972 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 13973 NewClassTy = NewPT->getPointeeType(); 13974 OldClassTy = OldPT->getPointeeType(); 13975 } 13976 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 13977 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 13978 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 13979 NewClassTy = NewRT->getPointeeType(); 13980 OldClassTy = OldRT->getPointeeType(); 13981 } 13982 } 13983 } 13984 13985 // The return types aren't either both pointers or references to a class type. 13986 if (NewClassTy.isNull()) { 13987 Diag(New->getLocation(), 13988 diag::err_different_return_type_for_overriding_virtual_function) 13989 << New->getDeclName() << NewTy << OldTy 13990 << New->getReturnTypeSourceRange(); 13991 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13992 << Old->getReturnTypeSourceRange(); 13993 13994 return true; 13995 } 13996 13997 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 13998 // C++14 [class.virtual]p8: 13999 // If the class type in the covariant return type of D::f differs from 14000 // that of B::f, the class type in the return type of D::f shall be 14001 // complete at the point of declaration of D::f or shall be the class 14002 // type D. 14003 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14004 if (!RT->isBeingDefined() && 14005 RequireCompleteType(New->getLocation(), NewClassTy, 14006 diag::err_covariant_return_incomplete, 14007 New->getDeclName())) 14008 return true; 14009 } 14010 14011 // Check if the new class derives from the old class. 14012 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14013 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14014 << New->getDeclName() << NewTy << OldTy 14015 << New->getReturnTypeSourceRange(); 14016 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14017 << Old->getReturnTypeSourceRange(); 14018 return true; 14019 } 14020 14021 // Check if we the conversion from derived to base is valid. 14022 if (CheckDerivedToBaseConversion( 14023 NewClassTy, OldClassTy, 14024 diag::err_covariant_return_inaccessible_base, 14025 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14026 New->getLocation(), New->getReturnTypeSourceRange(), 14027 New->getDeclName(), nullptr)) { 14028 // FIXME: this note won't trigger for delayed access control 14029 // diagnostics, and it's impossible to get an undelayed error 14030 // here from access control during the original parse because 14031 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14032 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14033 << Old->getReturnTypeSourceRange(); 14034 return true; 14035 } 14036 } 14037 14038 // The qualifiers of the return types must be the same. 14039 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14040 Diag(New->getLocation(), 14041 diag::err_covariant_return_type_different_qualifications) 14042 << New->getDeclName() << NewTy << OldTy 14043 << New->getReturnTypeSourceRange(); 14044 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14045 << Old->getReturnTypeSourceRange(); 14046 return true; 14047 } 14048 14049 14050 // The new class type must have the same or less qualifiers as the old type. 14051 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14052 Diag(New->getLocation(), 14053 diag::err_covariant_return_type_class_type_more_qualified) 14054 << New->getDeclName() << NewTy << OldTy 14055 << New->getReturnTypeSourceRange(); 14056 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14057 << Old->getReturnTypeSourceRange(); 14058 return true; 14059 } 14060 14061 return false; 14062 } 14063 14064 /// \brief Mark the given method pure. 14065 /// 14066 /// \param Method the method to be marked pure. 14067 /// 14068 /// \param InitRange the source range that covers the "0" initializer. 14069 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14070 SourceLocation EndLoc = InitRange.getEnd(); 14071 if (EndLoc.isValid()) 14072 Method->setRangeEnd(EndLoc); 14073 14074 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14075 Method->setPure(); 14076 return false; 14077 } 14078 14079 if (!Method->isInvalidDecl()) 14080 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14081 << Method->getDeclName() << InitRange; 14082 return true; 14083 } 14084 14085 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14086 if (D->getFriendObjectKind()) 14087 Diag(D->getLocation(), diag::err_pure_friend); 14088 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14089 CheckPureMethod(M, ZeroLoc); 14090 else 14091 Diag(D->getLocation(), diag::err_illegal_initializer); 14092 } 14093 14094 /// \brief Determine whether the given declaration is a static data member. 14095 static bool isStaticDataMember(const Decl *D) { 14096 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14097 return Var->isStaticDataMember(); 14098 14099 return false; 14100 } 14101 14102 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 14103 /// an initializer for the out-of-line declaration 'Dcl'. The scope 14104 /// is a fresh scope pushed for just this purpose. 14105 /// 14106 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14107 /// static data member of class X, names should be looked up in the scope of 14108 /// class X. 14109 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14110 // If there is no declaration, there was an error parsing it. 14111 if (!D || D->isInvalidDecl()) 14112 return; 14113 14114 // We will always have a nested name specifier here, but this declaration 14115 // might not be out of line if the specifier names the current namespace: 14116 // extern int n; 14117 // int ::n = 0; 14118 if (D->isOutOfLine()) 14119 EnterDeclaratorContext(S, D->getDeclContext()); 14120 14121 // If we are parsing the initializer for a static data member, push a 14122 // new expression evaluation context that is associated with this static 14123 // data member. 14124 if (isStaticDataMember(D)) 14125 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 14126 } 14127 14128 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 14129 /// initializer for the out-of-line declaration 'D'. 14130 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14131 // If there is no declaration, there was an error parsing it. 14132 if (!D || D->isInvalidDecl()) 14133 return; 14134 14135 if (isStaticDataMember(D)) 14136 PopExpressionEvaluationContext(); 14137 14138 if (D->isOutOfLine()) 14139 ExitDeclaratorContext(S); 14140 } 14141 14142 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14143 /// C++ if/switch/while/for statement. 14144 /// e.g: "if (int x = f()) {...}" 14145 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14146 // C++ 6.4p2: 14147 // The declarator shall not specify a function or an array. 14148 // The type-specifier-seq shall not contain typedef and shall not declare a 14149 // new class or enumeration. 14150 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14151 "Parser allowed 'typedef' as storage class of condition decl."); 14152 14153 Decl *Dcl = ActOnDeclarator(S, D); 14154 if (!Dcl) 14155 return true; 14156 14157 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14158 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14159 << D.getSourceRange(); 14160 return true; 14161 } 14162 14163 return Dcl; 14164 } 14165 14166 void Sema::LoadExternalVTableUses() { 14167 if (!ExternalSource) 14168 return; 14169 14170 SmallVector<ExternalVTableUse, 4> VTables; 14171 ExternalSource->ReadUsedVTables(VTables); 14172 SmallVector<VTableUse, 4> NewUses; 14173 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14174 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14175 = VTablesUsed.find(VTables[I].Record); 14176 // Even if a definition wasn't required before, it may be required now. 14177 if (Pos != VTablesUsed.end()) { 14178 if (!Pos->second && VTables[I].DefinitionRequired) 14179 Pos->second = true; 14180 continue; 14181 } 14182 14183 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14184 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14185 } 14186 14187 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14188 } 14189 14190 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14191 bool DefinitionRequired) { 14192 // Ignore any vtable uses in unevaluated operands or for classes that do 14193 // not have a vtable. 14194 if (!Class->isDynamicClass() || Class->isDependentContext() || 14195 CurContext->isDependentContext() || isUnevaluatedContext()) 14196 return; 14197 14198 // Try to insert this class into the map. 14199 LoadExternalVTableUses(); 14200 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14201 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14202 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14203 if (!Pos.second) { 14204 // If we already had an entry, check to see if we are promoting this vtable 14205 // to require a definition. If so, we need to reappend to the VTableUses 14206 // list, since we may have already processed the first entry. 14207 if (DefinitionRequired && !Pos.first->second) { 14208 Pos.first->second = true; 14209 } else { 14210 // Otherwise, we can early exit. 14211 return; 14212 } 14213 } else { 14214 // The Microsoft ABI requires that we perform the destructor body 14215 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14216 // the deleting destructor is emitted with the vtable, not with the 14217 // destructor definition as in the Itanium ABI. 14218 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14219 CXXDestructorDecl *DD = Class->getDestructor(); 14220 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14221 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14222 // If this is an out-of-line declaration, marking it referenced will 14223 // not do anything. Manually call CheckDestructor to look up operator 14224 // delete(). 14225 ContextRAII SavedContext(*this, DD); 14226 CheckDestructor(DD); 14227 } else { 14228 MarkFunctionReferenced(Loc, Class->getDestructor()); 14229 } 14230 } 14231 } 14232 } 14233 14234 // Local classes need to have their virtual members marked 14235 // immediately. For all other classes, we mark their virtual members 14236 // at the end of the translation unit. 14237 if (Class->isLocalClass()) 14238 MarkVirtualMembersReferenced(Loc, Class); 14239 else 14240 VTableUses.push_back(std::make_pair(Class, Loc)); 14241 } 14242 14243 bool Sema::DefineUsedVTables() { 14244 LoadExternalVTableUses(); 14245 if (VTableUses.empty()) 14246 return false; 14247 14248 // Note: The VTableUses vector could grow as a result of marking 14249 // the members of a class as "used", so we check the size each 14250 // time through the loop and prefer indices (which are stable) to 14251 // iterators (which are not). 14252 bool DefinedAnything = false; 14253 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14254 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14255 if (!Class) 14256 continue; 14257 14258 SourceLocation Loc = VTableUses[I].second; 14259 14260 bool DefineVTable = true; 14261 14262 // If this class has a key function, but that key function is 14263 // defined in another translation unit, we don't need to emit the 14264 // vtable even though we're using it. 14265 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14266 if (KeyFunction && !KeyFunction->hasBody()) { 14267 // The key function is in another translation unit. 14268 DefineVTable = false; 14269 TemplateSpecializationKind TSK = 14270 KeyFunction->getTemplateSpecializationKind(); 14271 assert(TSK != TSK_ExplicitInstantiationDefinition && 14272 TSK != TSK_ImplicitInstantiation && 14273 "Instantiations don't have key functions"); 14274 (void)TSK; 14275 } else if (!KeyFunction) { 14276 // If we have a class with no key function that is the subject 14277 // of an explicit instantiation declaration, suppress the 14278 // vtable; it will live with the explicit instantiation 14279 // definition. 14280 bool IsExplicitInstantiationDeclaration 14281 = Class->getTemplateSpecializationKind() 14282 == TSK_ExplicitInstantiationDeclaration; 14283 for (auto R : Class->redecls()) { 14284 TemplateSpecializationKind TSK 14285 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14286 if (TSK == TSK_ExplicitInstantiationDeclaration) 14287 IsExplicitInstantiationDeclaration = true; 14288 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14289 IsExplicitInstantiationDeclaration = false; 14290 break; 14291 } 14292 } 14293 14294 if (IsExplicitInstantiationDeclaration) 14295 DefineVTable = false; 14296 } 14297 14298 // The exception specifications for all virtual members may be needed even 14299 // if we are not providing an authoritative form of the vtable in this TU. 14300 // We may choose to emit it available_externally anyway. 14301 if (!DefineVTable) { 14302 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14303 continue; 14304 } 14305 14306 // Mark all of the virtual members of this class as referenced, so 14307 // that we can build a vtable. Then, tell the AST consumer that a 14308 // vtable for this class is required. 14309 DefinedAnything = true; 14310 MarkVirtualMembersReferenced(Loc, Class); 14311 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14312 if (VTablesUsed[Canonical]) 14313 Consumer.HandleVTable(Class); 14314 14315 // Optionally warn if we're emitting a weak vtable. 14316 if (Class->isExternallyVisible() && 14317 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 14318 const FunctionDecl *KeyFunctionDef = nullptr; 14319 if (!KeyFunction || 14320 (KeyFunction->hasBody(KeyFunctionDef) && 14321 KeyFunctionDef->isInlined())) 14322 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 14323 TSK_ExplicitInstantiationDefinition 14324 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 14325 << Class; 14326 } 14327 } 14328 VTableUses.clear(); 14329 14330 return DefinedAnything; 14331 } 14332 14333 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14334 const CXXRecordDecl *RD) { 14335 for (const auto *I : RD->methods()) 14336 if (I->isVirtual() && !I->isPure()) 14337 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14338 } 14339 14340 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14341 const CXXRecordDecl *RD) { 14342 // Mark all functions which will appear in RD's vtable as used. 14343 CXXFinalOverriderMap FinalOverriders; 14344 RD->getFinalOverriders(FinalOverriders); 14345 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14346 E = FinalOverriders.end(); 14347 I != E; ++I) { 14348 for (OverridingMethods::const_iterator OI = I->second.begin(), 14349 OE = I->second.end(); 14350 OI != OE; ++OI) { 14351 assert(OI->second.size() > 0 && "no final overrider"); 14352 CXXMethodDecl *Overrider = OI->second.front().Method; 14353 14354 // C++ [basic.def.odr]p2: 14355 // [...] A virtual member function is used if it is not pure. [...] 14356 if (!Overrider->isPure()) 14357 MarkFunctionReferenced(Loc, Overrider); 14358 } 14359 } 14360 14361 // Only classes that have virtual bases need a VTT. 14362 if (RD->getNumVBases() == 0) 14363 return; 14364 14365 for (const auto &I : RD->bases()) { 14366 const CXXRecordDecl *Base = 14367 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14368 if (Base->getNumVBases() == 0) 14369 continue; 14370 MarkVirtualMembersReferenced(Loc, Base); 14371 } 14372 } 14373 14374 /// SetIvarInitializers - This routine builds initialization ASTs for the 14375 /// Objective-C implementation whose ivars need be initialized. 14376 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14377 if (!getLangOpts().CPlusPlus) 14378 return; 14379 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14380 SmallVector<ObjCIvarDecl*, 8> ivars; 14381 CollectIvarsToConstructOrDestruct(OID, ivars); 14382 if (ivars.empty()) 14383 return; 14384 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14385 for (unsigned i = 0; i < ivars.size(); i++) { 14386 FieldDecl *Field = ivars[i]; 14387 if (Field->isInvalidDecl()) 14388 continue; 14389 14390 CXXCtorInitializer *Member; 14391 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14392 InitializationKind InitKind = 14393 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14394 14395 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14396 ExprResult MemberInit = 14397 InitSeq.Perform(*this, InitEntity, InitKind, None); 14398 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14399 // Note, MemberInit could actually come back empty if no initialization 14400 // is required (e.g., because it would call a trivial default constructor) 14401 if (!MemberInit.get() || MemberInit.isInvalid()) 14402 continue; 14403 14404 Member = 14405 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14406 SourceLocation(), 14407 MemberInit.getAs<Expr>(), 14408 SourceLocation()); 14409 AllToInit.push_back(Member); 14410 14411 // Be sure that the destructor is accessible and is marked as referenced. 14412 if (const RecordType *RecordTy = 14413 Context.getBaseElementType(Field->getType()) 14414 ->getAs<RecordType>()) { 14415 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14416 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14417 MarkFunctionReferenced(Field->getLocation(), Destructor); 14418 CheckDestructorAccess(Field->getLocation(), Destructor, 14419 PDiag(diag::err_access_dtor_ivar) 14420 << Context.getBaseElementType(Field->getType())); 14421 } 14422 } 14423 } 14424 ObjCImplementation->setIvarInitializers(Context, 14425 AllToInit.data(), AllToInit.size()); 14426 } 14427 } 14428 14429 static 14430 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14431 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14432 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14433 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14434 Sema &S) { 14435 if (Ctor->isInvalidDecl()) 14436 return; 14437 14438 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14439 14440 // Target may not be determinable yet, for instance if this is a dependent 14441 // call in an uninstantiated template. 14442 if (Target) { 14443 const FunctionDecl *FNTarget = nullptr; 14444 (void)Target->hasBody(FNTarget); 14445 Target = const_cast<CXXConstructorDecl*>( 14446 cast_or_null<CXXConstructorDecl>(FNTarget)); 14447 } 14448 14449 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14450 // Avoid dereferencing a null pointer here. 14451 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14452 14453 if (!Current.insert(Canonical).second) 14454 return; 14455 14456 // We know that beyond here, we aren't chaining into a cycle. 14457 if (!Target || !Target->isDelegatingConstructor() || 14458 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14459 Valid.insert(Current.begin(), Current.end()); 14460 Current.clear(); 14461 // We've hit a cycle. 14462 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14463 Current.count(TCanonical)) { 14464 // If we haven't diagnosed this cycle yet, do so now. 14465 if (!Invalid.count(TCanonical)) { 14466 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14467 diag::warn_delegating_ctor_cycle) 14468 << Ctor; 14469 14470 // Don't add a note for a function delegating directly to itself. 14471 if (TCanonical != Canonical) 14472 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14473 14474 CXXConstructorDecl *C = Target; 14475 while (C->getCanonicalDecl() != Canonical) { 14476 const FunctionDecl *FNTarget = nullptr; 14477 (void)C->getTargetConstructor()->hasBody(FNTarget); 14478 assert(FNTarget && "Ctor cycle through bodiless function"); 14479 14480 C = const_cast<CXXConstructorDecl*>( 14481 cast<CXXConstructorDecl>(FNTarget)); 14482 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14483 } 14484 } 14485 14486 Invalid.insert(Current.begin(), Current.end()); 14487 Current.clear(); 14488 } else { 14489 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14490 } 14491 } 14492 14493 14494 void Sema::CheckDelegatingCtorCycles() { 14495 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14496 14497 for (DelegatingCtorDeclsType::iterator 14498 I = DelegatingCtorDecls.begin(ExternalSource), 14499 E = DelegatingCtorDecls.end(); 14500 I != E; ++I) 14501 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14502 14503 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14504 CE = Invalid.end(); 14505 CI != CE; ++CI) 14506 (*CI)->setInvalidDecl(); 14507 } 14508 14509 namespace { 14510 /// \brief AST visitor that finds references to the 'this' expression. 14511 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14512 Sema &S; 14513 14514 public: 14515 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14516 14517 bool VisitCXXThisExpr(CXXThisExpr *E) { 14518 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14519 << E->isImplicit(); 14520 return false; 14521 } 14522 }; 14523 } 14524 14525 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14526 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14527 if (!TSInfo) 14528 return false; 14529 14530 TypeLoc TL = TSInfo->getTypeLoc(); 14531 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14532 if (!ProtoTL) 14533 return false; 14534 14535 // C++11 [expr.prim.general]p3: 14536 // [The expression this] shall not appear before the optional 14537 // cv-qualifier-seq and it shall not appear within the declaration of a 14538 // static member function (although its type and value category are defined 14539 // within a static member function as they are within a non-static member 14540 // function). [ Note: this is because declaration matching does not occur 14541 // until the complete declarator is known. - end note ] 14542 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14543 FindCXXThisExpr Finder(*this); 14544 14545 // If the return type came after the cv-qualifier-seq, check it now. 14546 if (Proto->hasTrailingReturn() && 14547 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14548 return true; 14549 14550 // Check the exception specification. 14551 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14552 return true; 14553 14554 return checkThisInStaticMemberFunctionAttributes(Method); 14555 } 14556 14557 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14558 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14559 if (!TSInfo) 14560 return false; 14561 14562 TypeLoc TL = TSInfo->getTypeLoc(); 14563 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14564 if (!ProtoTL) 14565 return false; 14566 14567 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14568 FindCXXThisExpr Finder(*this); 14569 14570 switch (Proto->getExceptionSpecType()) { 14571 case EST_Unparsed: 14572 case EST_Uninstantiated: 14573 case EST_Unevaluated: 14574 case EST_BasicNoexcept: 14575 case EST_DynamicNone: 14576 case EST_MSAny: 14577 case EST_None: 14578 break; 14579 14580 case EST_ComputedNoexcept: 14581 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14582 return true; 14583 14584 case EST_Dynamic: 14585 for (const auto &E : Proto->exceptions()) { 14586 if (!Finder.TraverseType(E)) 14587 return true; 14588 } 14589 break; 14590 } 14591 14592 return false; 14593 } 14594 14595 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14596 FindCXXThisExpr Finder(*this); 14597 14598 // Check attributes. 14599 for (const auto *A : Method->attrs()) { 14600 // FIXME: This should be emitted by tblgen. 14601 Expr *Arg = nullptr; 14602 ArrayRef<Expr *> Args; 14603 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14604 Arg = G->getArg(); 14605 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14606 Arg = G->getArg(); 14607 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14608 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14609 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14610 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14611 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14612 Arg = ETLF->getSuccessValue(); 14613 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14614 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14615 Arg = STLF->getSuccessValue(); 14616 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14617 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14618 Arg = LR->getArg(); 14619 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14620 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14621 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14622 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14623 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14624 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14625 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14626 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14627 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14628 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14629 14630 if (Arg && !Finder.TraverseStmt(Arg)) 14631 return true; 14632 14633 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14634 if (!Finder.TraverseStmt(Args[I])) 14635 return true; 14636 } 14637 } 14638 14639 return false; 14640 } 14641 14642 void Sema::checkExceptionSpecification( 14643 bool IsTopLevel, ExceptionSpecificationType EST, 14644 ArrayRef<ParsedType> DynamicExceptions, 14645 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 14646 SmallVectorImpl<QualType> &Exceptions, 14647 FunctionProtoType::ExceptionSpecInfo &ESI) { 14648 Exceptions.clear(); 14649 ESI.Type = EST; 14650 if (EST == EST_Dynamic) { 14651 Exceptions.reserve(DynamicExceptions.size()); 14652 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 14653 // FIXME: Preserve type source info. 14654 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 14655 14656 if (IsTopLevel) { 14657 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 14658 collectUnexpandedParameterPacks(ET, Unexpanded); 14659 if (!Unexpanded.empty()) { 14660 DiagnoseUnexpandedParameterPacks( 14661 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 14662 Unexpanded); 14663 continue; 14664 } 14665 } 14666 14667 // Check that the type is valid for an exception spec, and 14668 // drop it if not. 14669 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 14670 Exceptions.push_back(ET); 14671 } 14672 ESI.Exceptions = Exceptions; 14673 return; 14674 } 14675 14676 if (EST == EST_ComputedNoexcept) { 14677 // If an error occurred, there's no expression here. 14678 if (NoexceptExpr) { 14679 assert((NoexceptExpr->isTypeDependent() || 14680 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 14681 Context.BoolTy) && 14682 "Parser should have made sure that the expression is boolean"); 14683 if (IsTopLevel && NoexceptExpr && 14684 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 14685 ESI.Type = EST_BasicNoexcept; 14686 return; 14687 } 14688 14689 if (!NoexceptExpr->isValueDependent()) 14690 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 14691 diag::err_noexcept_needs_constant_expression, 14692 /*AllowFold*/ false).get(); 14693 ESI.NoexceptExpr = NoexceptExpr; 14694 } 14695 return; 14696 } 14697 } 14698 14699 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 14700 ExceptionSpecificationType EST, 14701 SourceRange SpecificationRange, 14702 ArrayRef<ParsedType> DynamicExceptions, 14703 ArrayRef<SourceRange> DynamicExceptionRanges, 14704 Expr *NoexceptExpr) { 14705 if (!MethodD) 14706 return; 14707 14708 // Dig out the method we're referring to. 14709 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 14710 MethodD = FunTmpl->getTemplatedDecl(); 14711 14712 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 14713 if (!Method) 14714 return; 14715 14716 // Check the exception specification. 14717 llvm::SmallVector<QualType, 4> Exceptions; 14718 FunctionProtoType::ExceptionSpecInfo ESI; 14719 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 14720 DynamicExceptionRanges, NoexceptExpr, Exceptions, 14721 ESI); 14722 14723 // Update the exception specification on the function type. 14724 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 14725 14726 if (Method->isStatic()) 14727 checkThisInStaticMemberFunctionExceptionSpec(Method); 14728 14729 if (Method->isVirtual()) { 14730 // Check overrides, which we previously had to delay. 14731 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 14732 OEnd = Method->end_overridden_methods(); 14733 O != OEnd; ++O) 14734 CheckOverridingFunctionExceptionSpec(Method, *O); 14735 } 14736 } 14737 14738 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 14739 /// 14740 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 14741 SourceLocation DeclStart, 14742 Declarator &D, Expr *BitWidth, 14743 InClassInitStyle InitStyle, 14744 AccessSpecifier AS, 14745 AttributeList *MSPropertyAttr) { 14746 IdentifierInfo *II = D.getIdentifier(); 14747 if (!II) { 14748 Diag(DeclStart, diag::err_anonymous_property); 14749 return nullptr; 14750 } 14751 SourceLocation Loc = D.getIdentifierLoc(); 14752 14753 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14754 QualType T = TInfo->getType(); 14755 if (getLangOpts().CPlusPlus) { 14756 CheckExtraCXXDefaultArguments(D); 14757 14758 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14759 UPPC_DataMemberType)) { 14760 D.setInvalidType(); 14761 T = Context.IntTy; 14762 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14763 } 14764 } 14765 14766 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14767 14768 if (D.getDeclSpec().isInlineSpecified()) 14769 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14770 << getLangOpts().CPlusPlus1z; 14771 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14772 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14773 diag::err_invalid_thread) 14774 << DeclSpec::getSpecifierName(TSCS); 14775 14776 // Check to see if this name was declared as a member previously 14777 NamedDecl *PrevDecl = nullptr; 14778 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14779 LookupName(Previous, S); 14780 switch (Previous.getResultKind()) { 14781 case LookupResult::Found: 14782 case LookupResult::FoundUnresolvedValue: 14783 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14784 break; 14785 14786 case LookupResult::FoundOverloaded: 14787 PrevDecl = Previous.getRepresentativeDecl(); 14788 break; 14789 14790 case LookupResult::NotFound: 14791 case LookupResult::NotFoundInCurrentInstantiation: 14792 case LookupResult::Ambiguous: 14793 break; 14794 } 14795 14796 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14797 // Maybe we will complain about the shadowed template parameter. 14798 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14799 // Just pretend that we didn't see the previous declaration. 14800 PrevDecl = nullptr; 14801 } 14802 14803 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14804 PrevDecl = nullptr; 14805 14806 SourceLocation TSSL = D.getLocStart(); 14807 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 14808 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 14809 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 14810 ProcessDeclAttributes(TUScope, NewPD, D); 14811 NewPD->setAccess(AS); 14812 14813 if (NewPD->isInvalidDecl()) 14814 Record->setInvalidDecl(); 14815 14816 if (D.getDeclSpec().isModulePrivateSpecified()) 14817 NewPD->setModulePrivate(); 14818 14819 if (NewPD->isInvalidDecl() && PrevDecl) { 14820 // Don't introduce NewFD into scope; there's already something 14821 // with the same name in the same scope. 14822 } else if (II) { 14823 PushOnScopeChains(NewPD, S); 14824 } else 14825 Record->addDecl(NewPD); 14826 14827 return NewPD; 14828 } 14829