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 continue; 5551 5552 // MSVC versions before 2015 don't export the move assignment operators 5553 // and move constructor, so don't attempt to import/export them if 5554 // we have a definition. 5555 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5556 if ((MD->isMoveAssignmentOperator() || 5557 (Ctor && Ctor->isMoveConstructor())) && 5558 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5559 continue; 5560 5561 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5562 // operator is exported anyway. 5563 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5564 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5565 continue; 5566 } 5567 } 5568 5569 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5570 continue; 5571 5572 if (!getDLLAttr(Member)) { 5573 auto *NewAttr = 5574 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5575 NewAttr->setInherited(true); 5576 Member->addAttr(NewAttr); 5577 } 5578 } 5579 5580 if (ClassExported) 5581 DelayedDllExportClasses.push_back(Class); 5582 } 5583 5584 /// \brief Perform propagation of DLL attributes from a derived class to a 5585 /// templated base class for MS compatibility. 5586 void Sema::propagateDLLAttrToBaseClassTemplate( 5587 CXXRecordDecl *Class, Attr *ClassAttr, 5588 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5589 if (getDLLAttr( 5590 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5591 // If the base class template has a DLL attribute, don't try to change it. 5592 return; 5593 } 5594 5595 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5596 if (!getDLLAttr(BaseTemplateSpec) && 5597 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5598 TSK == TSK_ImplicitInstantiation)) { 5599 // The template hasn't been instantiated yet (or it has, but only as an 5600 // explicit instantiation declaration or implicit instantiation, which means 5601 // we haven't codegenned any members yet), so propagate the attribute. 5602 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5603 NewAttr->setInherited(true); 5604 BaseTemplateSpec->addAttr(NewAttr); 5605 5606 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5607 // needs to be run again to work see the new attribute. Otherwise this will 5608 // get run whenever the template is instantiated. 5609 if (TSK != TSK_Undeclared) 5610 checkClassLevelDLLAttribute(BaseTemplateSpec); 5611 5612 return; 5613 } 5614 5615 if (getDLLAttr(BaseTemplateSpec)) { 5616 // The template has already been specialized or instantiated with an 5617 // attribute, explicitly or through propagation. We should not try to change 5618 // it. 5619 return; 5620 } 5621 5622 // The template was previously instantiated or explicitly specialized without 5623 // a dll attribute, It's too late for us to add an attribute, so warn that 5624 // this is unsupported. 5625 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5626 << BaseTemplateSpec->isExplicitSpecialization(); 5627 Diag(ClassAttr->getLocation(), diag::note_attribute); 5628 if (BaseTemplateSpec->isExplicitSpecialization()) { 5629 Diag(BaseTemplateSpec->getLocation(), 5630 diag::note_template_class_explicit_specialization_was_here) 5631 << BaseTemplateSpec; 5632 } else { 5633 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5634 diag::note_template_class_instantiation_was_here) 5635 << BaseTemplateSpec; 5636 } 5637 } 5638 5639 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5640 SourceLocation DefaultLoc) { 5641 switch (S.getSpecialMember(MD)) { 5642 case Sema::CXXDefaultConstructor: 5643 S.DefineImplicitDefaultConstructor(DefaultLoc, 5644 cast<CXXConstructorDecl>(MD)); 5645 break; 5646 case Sema::CXXCopyConstructor: 5647 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5648 break; 5649 case Sema::CXXCopyAssignment: 5650 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5651 break; 5652 case Sema::CXXDestructor: 5653 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5654 break; 5655 case Sema::CXXMoveConstructor: 5656 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5657 break; 5658 case Sema::CXXMoveAssignment: 5659 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5660 break; 5661 case Sema::CXXInvalid: 5662 llvm_unreachable("Invalid special member."); 5663 } 5664 } 5665 5666 /// \brief Perform semantic checks on a class definition that has been 5667 /// completing, introducing implicitly-declared members, checking for 5668 /// abstract types, etc. 5669 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5670 if (!Record) 5671 return; 5672 5673 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5674 AbstractUsageInfo Info(*this, Record); 5675 CheckAbstractClassUsage(Info, Record); 5676 } 5677 5678 // If this is not an aggregate type and has no user-declared constructor, 5679 // complain about any non-static data members of reference or const scalar 5680 // type, since they will never get initializers. 5681 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5682 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5683 !Record->isLambda()) { 5684 bool Complained = false; 5685 for (const auto *F : Record->fields()) { 5686 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5687 continue; 5688 5689 if (F->getType()->isReferenceType() || 5690 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5691 if (!Complained) { 5692 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5693 << Record->getTagKind() << Record; 5694 Complained = true; 5695 } 5696 5697 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5698 << F->getType()->isReferenceType() 5699 << F->getDeclName(); 5700 } 5701 } 5702 } 5703 5704 if (Record->getIdentifier()) { 5705 // C++ [class.mem]p13: 5706 // If T is the name of a class, then each of the following shall have a 5707 // name different from T: 5708 // - every member of every anonymous union that is a member of class T. 5709 // 5710 // C++ [class.mem]p14: 5711 // In addition, if class T has a user-declared constructor (12.1), every 5712 // non-static data member of class T shall have a name different from T. 5713 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5714 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5715 ++I) { 5716 NamedDecl *D = *I; 5717 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5718 isa<IndirectFieldDecl>(D)) { 5719 Diag(D->getLocation(), diag::err_member_name_of_class) 5720 << D->getDeclName(); 5721 break; 5722 } 5723 } 5724 } 5725 5726 // Warn if the class has virtual methods but non-virtual public destructor. 5727 if (Record->isPolymorphic() && !Record->isDependentType()) { 5728 CXXDestructorDecl *dtor = Record->getDestructor(); 5729 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5730 !Record->hasAttr<FinalAttr>()) 5731 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5732 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5733 } 5734 5735 if (Record->isAbstract()) { 5736 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5737 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5738 << FA->isSpelledAsSealed(); 5739 DiagnoseAbstractType(Record); 5740 } 5741 } 5742 5743 bool HasMethodWithOverrideControl = false, 5744 HasOverridingMethodWithoutOverrideControl = false; 5745 if (!Record->isDependentType()) { 5746 for (auto *M : Record->methods()) { 5747 // See if a method overloads virtual methods in a base 5748 // class without overriding any. 5749 if (!M->isStatic()) 5750 DiagnoseHiddenVirtualMethods(M); 5751 if (M->hasAttr<OverrideAttr>()) 5752 HasMethodWithOverrideControl = true; 5753 else if (M->size_overridden_methods() > 0) 5754 HasOverridingMethodWithoutOverrideControl = true; 5755 // Check whether the explicitly-defaulted special members are valid. 5756 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5757 CheckExplicitlyDefaultedSpecialMember(M); 5758 5759 // For an explicitly defaulted or deleted special member, we defer 5760 // determining triviality until the class is complete. That time is now! 5761 CXXSpecialMember CSM = getSpecialMember(M); 5762 if (!M->isImplicit() && !M->isUserProvided()) { 5763 if (CSM != CXXInvalid) { 5764 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5765 5766 // Inform the class that we've finished declaring this member. 5767 Record->finishedDefaultedOrDeletedMember(M); 5768 } 5769 } 5770 5771 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5772 M->hasAttr<DLLExportAttr>()) { 5773 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5774 M->isTrivial() && 5775 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5776 CSM == CXXDestructor)) 5777 M->dropAttr<DLLExportAttr>(); 5778 5779 if (M->hasAttr<DLLExportAttr>()) { 5780 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5781 ActOnFinishInlineFunctionDef(M); 5782 } 5783 } 5784 } 5785 } 5786 5787 if (HasMethodWithOverrideControl && 5788 HasOverridingMethodWithoutOverrideControl) { 5789 // At least one method has the 'override' control declared. 5790 // Diagnose all other overridden methods which do not have 'override' specified on them. 5791 for (auto *M : Record->methods()) 5792 DiagnoseAbsenceOfOverrideControl(M); 5793 } 5794 5795 // ms_struct is a request to use the same ABI rules as MSVC. Check 5796 // whether this class uses any C++ features that are implemented 5797 // completely differently in MSVC, and if so, emit a diagnostic. 5798 // That diagnostic defaults to an error, but we allow projects to 5799 // map it down to a warning (or ignore it). It's a fairly common 5800 // practice among users of the ms_struct pragma to mass-annotate 5801 // headers, sweeping up a bunch of types that the project doesn't 5802 // really rely on MSVC-compatible layout for. We must therefore 5803 // support "ms_struct except for C++ stuff" as a secondary ABI. 5804 if (Record->isMsStruct(Context) && 5805 (Record->isPolymorphic() || Record->getNumBases())) { 5806 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5807 } 5808 5809 checkClassLevelDLLAttribute(Record); 5810 } 5811 5812 /// Look up the special member function that would be called by a special 5813 /// member function for a subobject of class type. 5814 /// 5815 /// \param Class The class type of the subobject. 5816 /// \param CSM The kind of special member function. 5817 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5818 /// \param ConstRHS True if this is a copy operation with a const object 5819 /// on its RHS, that is, if the argument to the outer special member 5820 /// function is 'const' and this is not a field marked 'mutable'. 5821 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 5822 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5823 unsigned FieldQuals, bool ConstRHS) { 5824 unsigned LHSQuals = 0; 5825 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5826 LHSQuals = FieldQuals; 5827 5828 unsigned RHSQuals = FieldQuals; 5829 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5830 RHSQuals = 0; 5831 else if (ConstRHS) 5832 RHSQuals |= Qualifiers::Const; 5833 5834 return S.LookupSpecialMember(Class, CSM, 5835 RHSQuals & Qualifiers::Const, 5836 RHSQuals & Qualifiers::Volatile, 5837 false, 5838 LHSQuals & Qualifiers::Const, 5839 LHSQuals & Qualifiers::Volatile); 5840 } 5841 5842 class Sema::InheritedConstructorInfo { 5843 Sema &S; 5844 SourceLocation UseLoc; 5845 5846 /// A mapping from the base classes through which the constructor was 5847 /// inherited to the using shadow declaration in that base class (or a null 5848 /// pointer if the constructor was declared in that base class). 5849 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 5850 InheritedFromBases; 5851 5852 public: 5853 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 5854 ConstructorUsingShadowDecl *Shadow) 5855 : S(S), UseLoc(UseLoc) { 5856 bool DiagnosedMultipleConstructedBases = false; 5857 CXXRecordDecl *ConstructedBase = nullptr; 5858 UsingDecl *ConstructedBaseUsing = nullptr; 5859 5860 // Find the set of such base class subobjects and check that there's a 5861 // unique constructed subobject. 5862 for (auto *D : Shadow->redecls()) { 5863 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 5864 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 5865 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 5866 5867 InheritedFromBases.insert( 5868 std::make_pair(DNominatedBase->getCanonicalDecl(), 5869 DShadow->getNominatedBaseClassShadowDecl())); 5870 if (DShadow->constructsVirtualBase()) 5871 InheritedFromBases.insert( 5872 std::make_pair(DConstructedBase->getCanonicalDecl(), 5873 DShadow->getConstructedBaseClassShadowDecl())); 5874 else 5875 assert(DNominatedBase == DConstructedBase); 5876 5877 // [class.inhctor.init]p2: 5878 // If the constructor was inherited from multiple base class subobjects 5879 // of type B, the program is ill-formed. 5880 if (!ConstructedBase) { 5881 ConstructedBase = DConstructedBase; 5882 ConstructedBaseUsing = D->getUsingDecl(); 5883 } else if (ConstructedBase != DConstructedBase && 5884 !Shadow->isInvalidDecl()) { 5885 if (!DiagnosedMultipleConstructedBases) { 5886 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 5887 << Shadow->getTargetDecl(); 5888 S.Diag(ConstructedBaseUsing->getLocation(), 5889 diag::note_ambiguous_inherited_constructor_using) 5890 << ConstructedBase; 5891 DiagnosedMultipleConstructedBases = true; 5892 } 5893 S.Diag(D->getUsingDecl()->getLocation(), 5894 diag::note_ambiguous_inherited_constructor_using) 5895 << DConstructedBase; 5896 } 5897 } 5898 5899 if (DiagnosedMultipleConstructedBases) 5900 Shadow->setInvalidDecl(); 5901 } 5902 5903 /// Find the constructor to use for inherited construction of a base class, 5904 /// and whether that base class constructor inherits the constructor from a 5905 /// virtual base class (in which case it won't actually invoke it). 5906 std::pair<CXXConstructorDecl *, bool> 5907 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 5908 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 5909 if (It == InheritedFromBases.end()) 5910 return std::make_pair(nullptr, false); 5911 5912 // This is an intermediary class. 5913 if (It->second) 5914 return std::make_pair( 5915 S.findInheritingConstructor(UseLoc, Ctor, It->second), 5916 It->second->constructsVirtualBase()); 5917 5918 // This is the base class from which the constructor was inherited. 5919 return std::make_pair(Ctor, false); 5920 } 5921 }; 5922 5923 /// Is the special member function which would be selected to perform the 5924 /// specified operation on the specified class type a constexpr constructor? 5925 static bool 5926 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5927 Sema::CXXSpecialMember CSM, unsigned Quals, 5928 bool ConstRHS, 5929 CXXConstructorDecl *InheritedCtor = nullptr, 5930 Sema::InheritedConstructorInfo *Inherited = nullptr) { 5931 // If we're inheriting a constructor, see if we need to call it for this base 5932 // class. 5933 if (InheritedCtor) { 5934 assert(CSM == Sema::CXXDefaultConstructor); 5935 auto BaseCtor = 5936 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 5937 if (BaseCtor) 5938 return BaseCtor->isConstexpr(); 5939 } 5940 5941 if (CSM == Sema::CXXDefaultConstructor) 5942 return ClassDecl->hasConstexprDefaultConstructor(); 5943 5944 Sema::SpecialMemberOverloadResult *SMOR = 5945 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5946 if (!SMOR || !SMOR->getMethod()) 5947 // A constructor we wouldn't select can't be "involved in initializing" 5948 // anything. 5949 return true; 5950 return SMOR->getMethod()->isConstexpr(); 5951 } 5952 5953 /// Determine whether the specified special member function would be constexpr 5954 /// if it were implicitly defined. 5955 static bool defaultedSpecialMemberIsConstexpr( 5956 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 5957 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 5958 Sema::InheritedConstructorInfo *Inherited = nullptr) { 5959 if (!S.getLangOpts().CPlusPlus11) 5960 return false; 5961 5962 // C++11 [dcl.constexpr]p4: 5963 // In the definition of a constexpr constructor [...] 5964 bool Ctor = true; 5965 switch (CSM) { 5966 case Sema::CXXDefaultConstructor: 5967 if (Inherited) 5968 break; 5969 // Since default constructor lookup is essentially trivial (and cannot 5970 // involve, for instance, template instantiation), we compute whether a 5971 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5972 // 5973 // This is important for performance; we need to know whether the default 5974 // constructor is constexpr to determine whether the type is a literal type. 5975 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5976 5977 case Sema::CXXCopyConstructor: 5978 case Sema::CXXMoveConstructor: 5979 // For copy or move constructors, we need to perform overload resolution. 5980 break; 5981 5982 case Sema::CXXCopyAssignment: 5983 case Sema::CXXMoveAssignment: 5984 if (!S.getLangOpts().CPlusPlus14) 5985 return false; 5986 // In C++1y, we need to perform overload resolution. 5987 Ctor = false; 5988 break; 5989 5990 case Sema::CXXDestructor: 5991 case Sema::CXXInvalid: 5992 return false; 5993 } 5994 5995 // -- if the class is a non-empty union, or for each non-empty anonymous 5996 // union member of a non-union class, exactly one non-static data member 5997 // shall be initialized; [DR1359] 5998 // 5999 // If we squint, this is guaranteed, since exactly one non-static data member 6000 // will be initialized (if the constructor isn't deleted), we just don't know 6001 // which one. 6002 if (Ctor && ClassDecl->isUnion()) 6003 return CSM == Sema::CXXDefaultConstructor 6004 ? ClassDecl->hasInClassInitializer() || 6005 !ClassDecl->hasVariantMembers() 6006 : true; 6007 6008 // -- the class shall not have any virtual base classes; 6009 if (Ctor && ClassDecl->getNumVBases()) 6010 return false; 6011 6012 // C++1y [class.copy]p26: 6013 // -- [the class] is a literal type, and 6014 if (!Ctor && !ClassDecl->isLiteral()) 6015 return false; 6016 6017 // -- every constructor involved in initializing [...] base class 6018 // sub-objects shall be a constexpr constructor; 6019 // -- the assignment operator selected to copy/move each direct base 6020 // class is a constexpr function, and 6021 for (const auto &B : ClassDecl->bases()) { 6022 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6023 if (!BaseType) continue; 6024 6025 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6026 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6027 InheritedCtor, Inherited)) 6028 return false; 6029 } 6030 6031 // -- every constructor involved in initializing non-static data members 6032 // [...] shall be a constexpr constructor; 6033 // -- every non-static data member and base class sub-object shall be 6034 // initialized 6035 // -- for each non-static data member of X that is of class type (or array 6036 // thereof), the assignment operator selected to copy/move that member is 6037 // a constexpr function 6038 for (const auto *F : ClassDecl->fields()) { 6039 if (F->isInvalidDecl()) 6040 continue; 6041 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6042 continue; 6043 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6044 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6045 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6046 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6047 BaseType.getCVRQualifiers(), 6048 ConstArg && !F->isMutable())) 6049 return false; 6050 } else if (CSM == Sema::CXXDefaultConstructor) { 6051 return false; 6052 } 6053 } 6054 6055 // All OK, it's constexpr! 6056 return true; 6057 } 6058 6059 static Sema::ImplicitExceptionSpecification 6060 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6061 switch (S.getSpecialMember(MD)) { 6062 case Sema::CXXDefaultConstructor: 6063 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 6064 case Sema::CXXCopyConstructor: 6065 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 6066 case Sema::CXXCopyAssignment: 6067 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 6068 case Sema::CXXMoveConstructor: 6069 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 6070 case Sema::CXXMoveAssignment: 6071 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 6072 case Sema::CXXDestructor: 6073 return S.ComputeDefaultedDtorExceptionSpec(MD); 6074 case Sema::CXXInvalid: 6075 break; 6076 } 6077 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 6078 "only special members have implicit exception specs"); 6079 return S.ComputeInheritingCtorExceptionSpec(Loc, 6080 cast<CXXConstructorDecl>(MD)); 6081 } 6082 6083 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6084 CXXMethodDecl *MD) { 6085 FunctionProtoType::ExtProtoInfo EPI; 6086 6087 // Build an exception specification pointing back at this member. 6088 EPI.ExceptionSpec.Type = EST_Unevaluated; 6089 EPI.ExceptionSpec.SourceDecl = MD; 6090 6091 // Set the calling convention to the default for C++ instance methods. 6092 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6093 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6094 /*IsCXXMethod=*/true)); 6095 return EPI; 6096 } 6097 6098 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6099 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6100 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6101 return; 6102 6103 // Evaluate the exception specification. 6104 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 6105 6106 // Update the type of the special member to use it. 6107 UpdateExceptionSpec(MD, ESI); 6108 6109 // A user-provided destructor can be defined outside the class. When that 6110 // happens, be sure to update the exception specification on both 6111 // declarations. 6112 const FunctionProtoType *CanonicalFPT = 6113 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6114 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6115 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6116 } 6117 6118 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6119 CXXRecordDecl *RD = MD->getParent(); 6120 CXXSpecialMember CSM = getSpecialMember(MD); 6121 6122 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6123 "not an explicitly-defaulted special member"); 6124 6125 // Whether this was the first-declared instance of the constructor. 6126 // This affects whether we implicitly add an exception spec and constexpr. 6127 bool First = MD == MD->getCanonicalDecl(); 6128 6129 bool HadError = false; 6130 6131 // C++11 [dcl.fct.def.default]p1: 6132 // A function that is explicitly defaulted shall 6133 // -- be a special member function (checked elsewhere), 6134 // -- have the same type (except for ref-qualifiers, and except that a 6135 // copy operation can take a non-const reference) as an implicit 6136 // declaration, and 6137 // -- not have default arguments. 6138 unsigned ExpectedParams = 1; 6139 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6140 ExpectedParams = 0; 6141 if (MD->getNumParams() != ExpectedParams) { 6142 // This also checks for default arguments: a copy or move constructor with a 6143 // default argument is classified as a default constructor, and assignment 6144 // operations and destructors can't have default arguments. 6145 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6146 << CSM << MD->getSourceRange(); 6147 HadError = true; 6148 } else if (MD->isVariadic()) { 6149 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6150 << CSM << MD->getSourceRange(); 6151 HadError = true; 6152 } 6153 6154 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6155 6156 bool CanHaveConstParam = false; 6157 if (CSM == CXXCopyConstructor) 6158 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6159 else if (CSM == CXXCopyAssignment) 6160 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6161 6162 QualType ReturnType = Context.VoidTy; 6163 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6164 // Check for return type matching. 6165 ReturnType = Type->getReturnType(); 6166 QualType ExpectedReturnType = 6167 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6168 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6169 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6170 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6171 HadError = true; 6172 } 6173 6174 // A defaulted special member cannot have cv-qualifiers. 6175 if (Type->getTypeQuals()) { 6176 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6177 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6178 HadError = true; 6179 } 6180 } 6181 6182 // Check for parameter type matching. 6183 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6184 bool HasConstParam = false; 6185 if (ExpectedParams && ArgType->isReferenceType()) { 6186 // Argument must be reference to possibly-const T. 6187 QualType ReferentType = ArgType->getPointeeType(); 6188 HasConstParam = ReferentType.isConstQualified(); 6189 6190 if (ReferentType.isVolatileQualified()) { 6191 Diag(MD->getLocation(), 6192 diag::err_defaulted_special_member_volatile_param) << CSM; 6193 HadError = true; 6194 } 6195 6196 if (HasConstParam && !CanHaveConstParam) { 6197 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6198 Diag(MD->getLocation(), 6199 diag::err_defaulted_special_member_copy_const_param) 6200 << (CSM == CXXCopyAssignment); 6201 // FIXME: Explain why this special member can't be const. 6202 } else { 6203 Diag(MD->getLocation(), 6204 diag::err_defaulted_special_member_move_const_param) 6205 << (CSM == CXXMoveAssignment); 6206 } 6207 HadError = true; 6208 } 6209 } else if (ExpectedParams) { 6210 // A copy assignment operator can take its argument by value, but a 6211 // defaulted one cannot. 6212 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6213 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6214 HadError = true; 6215 } 6216 6217 // C++11 [dcl.fct.def.default]p2: 6218 // An explicitly-defaulted function may be declared constexpr only if it 6219 // would have been implicitly declared as constexpr, 6220 // Do not apply this rule to members of class templates, since core issue 1358 6221 // makes such functions always instantiate to constexpr functions. For 6222 // functions which cannot be constexpr (for non-constructors in C++11 and for 6223 // destructors in C++1y), this is checked elsewhere. 6224 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6225 HasConstParam); 6226 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6227 : isa<CXXConstructorDecl>(MD)) && 6228 MD->isConstexpr() && !Constexpr && 6229 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6230 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6231 // FIXME: Explain why the special member can't be constexpr. 6232 HadError = true; 6233 } 6234 6235 // and may have an explicit exception-specification only if it is compatible 6236 // with the exception-specification on the implicit declaration. 6237 if (Type->hasExceptionSpec()) { 6238 // Delay the check if this is the first declaration of the special member, 6239 // since we may not have parsed some necessary in-class initializers yet. 6240 if (First) { 6241 // If the exception specification needs to be instantiated, do so now, 6242 // before we clobber it with an EST_Unevaluated specification below. 6243 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6244 InstantiateExceptionSpec(MD->getLocStart(), MD); 6245 Type = MD->getType()->getAs<FunctionProtoType>(); 6246 } 6247 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6248 } else 6249 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6250 } 6251 6252 // If a function is explicitly defaulted on its first declaration, 6253 if (First) { 6254 // -- it is implicitly considered to be constexpr if the implicit 6255 // definition would be, 6256 MD->setConstexpr(Constexpr); 6257 6258 // -- it is implicitly considered to have the same exception-specification 6259 // as if it had been implicitly declared, 6260 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6261 EPI.ExceptionSpec.Type = EST_Unevaluated; 6262 EPI.ExceptionSpec.SourceDecl = MD; 6263 MD->setType(Context.getFunctionType(ReturnType, 6264 llvm::makeArrayRef(&ArgType, 6265 ExpectedParams), 6266 EPI)); 6267 } 6268 6269 if (ShouldDeleteSpecialMember(MD, CSM)) { 6270 if (First) { 6271 SetDeclDeleted(MD, MD->getLocation()); 6272 } else { 6273 // C++11 [dcl.fct.def.default]p4: 6274 // [For a] user-provided explicitly-defaulted function [...] if such a 6275 // function is implicitly defined as deleted, the program is ill-formed. 6276 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6277 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6278 HadError = true; 6279 } 6280 } 6281 6282 if (HadError) 6283 MD->setInvalidDecl(); 6284 } 6285 6286 /// Check whether the exception specification provided for an 6287 /// explicitly-defaulted special member matches the exception specification 6288 /// that would have been generated for an implicit special member, per 6289 /// C++11 [dcl.fct.def.default]p2. 6290 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6291 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6292 // If the exception specification was explicitly specified but hadn't been 6293 // parsed when the method was defaulted, grab it now. 6294 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6295 SpecifiedType = 6296 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6297 6298 // Compute the implicit exception specification. 6299 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6300 /*IsCXXMethod=*/true); 6301 FunctionProtoType::ExtProtoInfo EPI(CC); 6302 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 6303 .getExceptionSpec(); 6304 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6305 Context.getFunctionType(Context.VoidTy, None, EPI)); 6306 6307 // Ensure that it matches. 6308 CheckEquivalentExceptionSpec( 6309 PDiag(diag::err_incorrect_defaulted_exception_spec) 6310 << getSpecialMember(MD), PDiag(), 6311 ImplicitType, SourceLocation(), 6312 SpecifiedType, MD->getLocation()); 6313 } 6314 6315 void Sema::CheckDelayedMemberExceptionSpecs() { 6316 decltype(DelayedExceptionSpecChecks) Checks; 6317 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6318 6319 std::swap(Checks, DelayedExceptionSpecChecks); 6320 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6321 6322 // Perform any deferred checking of exception specifications for virtual 6323 // destructors. 6324 for (auto &Check : Checks) 6325 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6326 6327 // Check that any explicitly-defaulted methods have exception specifications 6328 // compatible with their implicit exception specifications. 6329 for (auto &Spec : Specs) 6330 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6331 } 6332 6333 namespace { 6334 struct SpecialMemberDeletionInfo { 6335 Sema &S; 6336 CXXMethodDecl *MD; 6337 Sema::CXXSpecialMember CSM; 6338 Sema::InheritedConstructorInfo *ICI; 6339 bool Diagnose; 6340 6341 // Properties of the special member, computed for convenience. 6342 bool IsConstructor, IsAssignment, IsMove, ConstArg; 6343 SourceLocation Loc; 6344 6345 bool AllFieldsAreConst; 6346 6347 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6348 Sema::CXXSpecialMember CSM, 6349 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6350 : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose), 6351 IsConstructor(false), IsAssignment(false), IsMove(false), 6352 ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) { 6353 switch (CSM) { 6354 case Sema::CXXDefaultConstructor: 6355 case Sema::CXXCopyConstructor: 6356 IsConstructor = true; 6357 break; 6358 case Sema::CXXMoveConstructor: 6359 IsConstructor = true; 6360 IsMove = true; 6361 break; 6362 case Sema::CXXCopyAssignment: 6363 IsAssignment = true; 6364 break; 6365 case Sema::CXXMoveAssignment: 6366 IsAssignment = true; 6367 IsMove = true; 6368 break; 6369 case Sema::CXXDestructor: 6370 break; 6371 case Sema::CXXInvalid: 6372 llvm_unreachable("invalid special member kind"); 6373 } 6374 6375 if (MD->getNumParams()) { 6376 if (const ReferenceType *RT = 6377 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6378 ConstArg = RT->getPointeeType().isConstQualified(); 6379 } 6380 } 6381 6382 bool inUnion() const { return MD->getParent()->isUnion(); } 6383 6384 Sema::CXXSpecialMember getEffectiveCSM() { 6385 return ICI ? Sema::CXXInvalid : CSM; 6386 } 6387 6388 /// Look up the corresponding special member in the given class. 6389 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 6390 unsigned Quals, bool IsMutable) { 6391 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6392 ConstArg && !IsMutable); 6393 } 6394 6395 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6396 6397 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6398 bool shouldDeleteForField(FieldDecl *FD); 6399 bool shouldDeleteForAllConstMembers(); 6400 6401 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6402 unsigned Quals); 6403 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6404 Sema::SpecialMemberOverloadResult *SMOR, 6405 bool IsDtorCallInCtor); 6406 6407 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6408 }; 6409 } 6410 6411 /// Is the given special member inaccessible when used on the given 6412 /// sub-object. 6413 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6414 CXXMethodDecl *target) { 6415 /// If we're operating on a base class, the object type is the 6416 /// type of this special member. 6417 QualType objectTy; 6418 AccessSpecifier access = target->getAccess(); 6419 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6420 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6421 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6422 6423 // If we're operating on a field, the object type is the type of the field. 6424 } else { 6425 objectTy = S.Context.getTypeDeclType(target->getParent()); 6426 } 6427 6428 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6429 } 6430 6431 /// Check whether we should delete a special member due to the implicit 6432 /// definition containing a call to a special member of a subobject. 6433 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6434 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 6435 bool IsDtorCallInCtor) { 6436 CXXMethodDecl *Decl = SMOR->getMethod(); 6437 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6438 6439 int DiagKind = -1; 6440 6441 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6442 DiagKind = !Decl ? 0 : 1; 6443 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6444 DiagKind = 2; 6445 else if (!isAccessible(Subobj, Decl)) 6446 DiagKind = 3; 6447 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6448 !Decl->isTrivial()) { 6449 // A member of a union must have a trivial corresponding special member. 6450 // As a weird special case, a destructor call from a union's constructor 6451 // must be accessible and non-deleted, but need not be trivial. Such a 6452 // destructor is never actually called, but is semantically checked as 6453 // if it were. 6454 DiagKind = 4; 6455 } 6456 6457 if (DiagKind == -1) 6458 return false; 6459 6460 if (Diagnose) { 6461 if (Field) { 6462 S.Diag(Field->getLocation(), 6463 diag::note_deleted_special_member_class_subobject) 6464 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6465 << Field << DiagKind << IsDtorCallInCtor; 6466 } else { 6467 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6468 S.Diag(Base->getLocStart(), 6469 diag::note_deleted_special_member_class_subobject) 6470 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6471 << Base->getType() << DiagKind << IsDtorCallInCtor; 6472 } 6473 6474 if (DiagKind == 1) 6475 S.NoteDeletedFunction(Decl); 6476 // FIXME: Explain inaccessibility if DiagKind == 3. 6477 } 6478 6479 return true; 6480 } 6481 6482 /// Check whether we should delete a special member function due to having a 6483 /// direct or virtual base class or non-static data member of class type M. 6484 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6485 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6486 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6487 bool IsMutable = Field && Field->isMutable(); 6488 6489 // C++11 [class.ctor]p5: 6490 // -- any direct or virtual base class, or non-static data member with no 6491 // brace-or-equal-initializer, has class type M (or array thereof) and 6492 // either M has no default constructor or overload resolution as applied 6493 // to M's default constructor results in an ambiguity or in a function 6494 // that is deleted or inaccessible 6495 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6496 // -- a direct or virtual base class B that cannot be copied/moved because 6497 // overload resolution, as applied to B's corresponding special member, 6498 // results in an ambiguity or a function that is deleted or inaccessible 6499 // from the defaulted special member 6500 // C++11 [class.dtor]p5: 6501 // -- any direct or virtual base class [...] has a type with a destructor 6502 // that is deleted or inaccessible 6503 if (!(CSM == Sema::CXXDefaultConstructor && 6504 Field && Field->hasInClassInitializer()) && 6505 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6506 false)) 6507 return true; 6508 6509 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6510 // -- any direct or virtual base class or non-static data member has a 6511 // type with a destructor that is deleted or inaccessible 6512 if (IsConstructor) { 6513 Sema::SpecialMemberOverloadResult *SMOR = 6514 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6515 false, false, false, false, false); 6516 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6517 return true; 6518 } 6519 6520 return false; 6521 } 6522 6523 /// Check whether we should delete a special member function due to the class 6524 /// having a particular direct or virtual base class. 6525 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6526 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6527 // If program is correct, BaseClass cannot be null, but if it is, the error 6528 // must be reported elsewhere. 6529 if (!BaseClass) 6530 return false; 6531 // If we have an inheriting constructor, check whether we're calling an 6532 // inherited constructor instead of a default constructor. 6533 if (ICI) { 6534 assert(CSM == Sema::CXXDefaultConstructor); 6535 auto *BaseCtor = 6536 ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD) 6537 ->getInheritedConstructor() 6538 .getConstructor()) 6539 .first; 6540 if (BaseCtor) { 6541 if (BaseCtor->isDeleted() && Diagnose) { 6542 S.Diag(Base->getLocStart(), 6543 diag::note_deleted_special_member_class_subobject) 6544 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6545 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6546 S.NoteDeletedFunction(BaseCtor); 6547 } 6548 return BaseCtor->isDeleted(); 6549 } 6550 } 6551 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6552 } 6553 6554 /// Check whether we should delete a special member function due to the class 6555 /// having a particular non-static data member. 6556 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6557 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6558 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6559 6560 if (CSM == Sema::CXXDefaultConstructor) { 6561 // For a default constructor, all references must be initialized in-class 6562 // and, if a union, it must have a non-const member. 6563 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6564 if (Diagnose) 6565 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6566 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6567 return true; 6568 } 6569 // C++11 [class.ctor]p5: any non-variant non-static data member of 6570 // const-qualified type (or array thereof) with no 6571 // brace-or-equal-initializer does not have a user-provided default 6572 // constructor. 6573 if (!inUnion() && FieldType.isConstQualified() && 6574 !FD->hasInClassInitializer() && 6575 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6576 if (Diagnose) 6577 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6578 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6579 return true; 6580 } 6581 6582 if (inUnion() && !FieldType.isConstQualified()) 6583 AllFieldsAreConst = false; 6584 } else if (CSM == Sema::CXXCopyConstructor) { 6585 // For a copy constructor, data members must not be of rvalue reference 6586 // type. 6587 if (FieldType->isRValueReferenceType()) { 6588 if (Diagnose) 6589 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6590 << MD->getParent() << FD << FieldType; 6591 return true; 6592 } 6593 } else if (IsAssignment) { 6594 // For an assignment operator, data members must not be of reference type. 6595 if (FieldType->isReferenceType()) { 6596 if (Diagnose) 6597 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6598 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 6599 return true; 6600 } 6601 if (!FieldRecord && FieldType.isConstQualified()) { 6602 // C++11 [class.copy]p23: 6603 // -- a non-static data member of const non-class type (or array thereof) 6604 if (Diagnose) 6605 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6606 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 6607 return true; 6608 } 6609 } 6610 6611 if (FieldRecord) { 6612 // Some additional restrictions exist on the variant members. 6613 if (!inUnion() && FieldRecord->isUnion() && 6614 FieldRecord->isAnonymousStructOrUnion()) { 6615 bool AllVariantFieldsAreConst = true; 6616 6617 // FIXME: Handle anonymous unions declared within anonymous unions. 6618 for (auto *UI : FieldRecord->fields()) { 6619 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6620 6621 if (!UnionFieldType.isConstQualified()) 6622 AllVariantFieldsAreConst = false; 6623 6624 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6625 if (UnionFieldRecord && 6626 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6627 UnionFieldType.getCVRQualifiers())) 6628 return true; 6629 } 6630 6631 // At least one member in each anonymous union must be non-const 6632 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6633 !FieldRecord->field_empty()) { 6634 if (Diagnose) 6635 S.Diag(FieldRecord->getLocation(), 6636 diag::note_deleted_default_ctor_all_const) 6637 << !!ICI << MD->getParent() << /*anonymous union*/1; 6638 return true; 6639 } 6640 6641 // Don't check the implicit member of the anonymous union type. 6642 // This is technically non-conformant, but sanity demands it. 6643 return false; 6644 } 6645 6646 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6647 FieldType.getCVRQualifiers())) 6648 return true; 6649 } 6650 6651 return false; 6652 } 6653 6654 /// C++11 [class.ctor] p5: 6655 /// A defaulted default constructor for a class X is defined as deleted if 6656 /// X is a union and all of its variant members are of const-qualified type. 6657 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6658 // This is a silly definition, because it gives an empty union a deleted 6659 // default constructor. Don't do that. 6660 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 6661 !MD->getParent()->field_empty()) { 6662 if (Diagnose) 6663 S.Diag(MD->getParent()->getLocation(), 6664 diag::note_deleted_default_ctor_all_const) 6665 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6666 return true; 6667 } 6668 return false; 6669 } 6670 6671 /// Determine whether a defaulted special member function should be defined as 6672 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6673 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6674 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6675 InheritedConstructorInfo *ICI, 6676 bool Diagnose) { 6677 if (MD->isInvalidDecl()) 6678 return false; 6679 CXXRecordDecl *RD = MD->getParent(); 6680 assert(!RD->isDependentType() && "do deletion after instantiation"); 6681 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6682 return false; 6683 6684 // C++11 [expr.lambda.prim]p19: 6685 // The closure type associated with a lambda-expression has a 6686 // deleted (8.4.3) default constructor and a deleted copy 6687 // assignment operator. 6688 if (RD->isLambda() && 6689 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6690 if (Diagnose) 6691 Diag(RD->getLocation(), diag::note_lambda_decl); 6692 return true; 6693 } 6694 6695 // For an anonymous struct or union, the copy and assignment special members 6696 // will never be used, so skip the check. For an anonymous union declared at 6697 // namespace scope, the constructor and destructor are used. 6698 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6699 RD->isAnonymousStructOrUnion()) 6700 return false; 6701 6702 // C++11 [class.copy]p7, p18: 6703 // If the class definition declares a move constructor or move assignment 6704 // operator, an implicitly declared copy constructor or copy assignment 6705 // operator is defined as deleted. 6706 if (MD->isImplicit() && 6707 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6708 CXXMethodDecl *UserDeclaredMove = nullptr; 6709 6710 // In Microsoft mode, a user-declared move only causes the deletion of the 6711 // corresponding copy operation, not both copy operations. 6712 if (RD->hasUserDeclaredMoveConstructor() && 6713 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 6714 if (!Diagnose) return true; 6715 6716 // Find any user-declared move constructor. 6717 for (auto *I : RD->ctors()) { 6718 if (I->isMoveConstructor()) { 6719 UserDeclaredMove = I; 6720 break; 6721 } 6722 } 6723 assert(UserDeclaredMove); 6724 } else if (RD->hasUserDeclaredMoveAssignment() && 6725 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 6726 if (!Diagnose) return true; 6727 6728 // Find any user-declared move assignment operator. 6729 for (auto *I : RD->methods()) { 6730 if (I->isMoveAssignmentOperator()) { 6731 UserDeclaredMove = I; 6732 break; 6733 } 6734 } 6735 assert(UserDeclaredMove); 6736 } 6737 6738 if (UserDeclaredMove) { 6739 Diag(UserDeclaredMove->getLocation(), 6740 diag::note_deleted_copy_user_declared_move) 6741 << (CSM == CXXCopyAssignment) << RD 6742 << UserDeclaredMove->isMoveAssignmentOperator(); 6743 return true; 6744 } 6745 } 6746 6747 // Do access control from the special member function 6748 ContextRAII MethodContext(*this, MD); 6749 6750 // C++11 [class.dtor]p5: 6751 // -- for a virtual destructor, lookup of the non-array deallocation function 6752 // results in an ambiguity or in a function that is deleted or inaccessible 6753 if (CSM == CXXDestructor && MD->isVirtual()) { 6754 FunctionDecl *OperatorDelete = nullptr; 6755 DeclarationName Name = 6756 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6757 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 6758 OperatorDelete, false)) { 6759 if (Diagnose) 6760 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 6761 return true; 6762 } 6763 } 6764 6765 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 6766 6767 for (auto &BI : RD->bases()) 6768 if ((SMI.IsAssignment || !BI.isVirtual()) && 6769 SMI.shouldDeleteForBase(&BI)) 6770 return true; 6771 6772 // Per DR1611, do not consider virtual bases of constructors of abstract 6773 // classes, since we are not going to construct them. For assignment 6774 // operators, we only assign (and thus only consider) direct bases. 6775 if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) { 6776 for (auto &BI : RD->vbases()) 6777 if (SMI.shouldDeleteForBase(&BI)) 6778 return true; 6779 } 6780 6781 for (auto *FI : RD->fields()) 6782 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 6783 SMI.shouldDeleteForField(FI)) 6784 return true; 6785 6786 if (SMI.shouldDeleteForAllConstMembers()) 6787 return true; 6788 6789 if (getLangOpts().CUDA) { 6790 // We should delete the special member in CUDA mode if target inference 6791 // failed. 6792 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 6793 Diagnose); 6794 } 6795 6796 return false; 6797 } 6798 6799 /// Perform lookup for a special member of the specified kind, and determine 6800 /// whether it is trivial. If the triviality can be determined without the 6801 /// lookup, skip it. This is intended for use when determining whether a 6802 /// special member of a containing object is trivial, and thus does not ever 6803 /// perform overload resolution for default constructors. 6804 /// 6805 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 6806 /// member that was most likely to be intended to be trivial, if any. 6807 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 6808 Sema::CXXSpecialMember CSM, unsigned Quals, 6809 bool ConstRHS, CXXMethodDecl **Selected) { 6810 if (Selected) 6811 *Selected = nullptr; 6812 6813 switch (CSM) { 6814 case Sema::CXXInvalid: 6815 llvm_unreachable("not a special member"); 6816 6817 case Sema::CXXDefaultConstructor: 6818 // C++11 [class.ctor]p5: 6819 // A default constructor is trivial if: 6820 // - all the [direct subobjects] have trivial default constructors 6821 // 6822 // Note, no overload resolution is performed in this case. 6823 if (RD->hasTrivialDefaultConstructor()) 6824 return true; 6825 6826 if (Selected) { 6827 // If there's a default constructor which could have been trivial, dig it 6828 // out. Otherwise, if there's any user-provided default constructor, point 6829 // to that as an example of why there's not a trivial one. 6830 CXXConstructorDecl *DefCtor = nullptr; 6831 if (RD->needsImplicitDefaultConstructor()) 6832 S.DeclareImplicitDefaultConstructor(RD); 6833 for (auto *CI : RD->ctors()) { 6834 if (!CI->isDefaultConstructor()) 6835 continue; 6836 DefCtor = CI; 6837 if (!DefCtor->isUserProvided()) 6838 break; 6839 } 6840 6841 *Selected = DefCtor; 6842 } 6843 6844 return false; 6845 6846 case Sema::CXXDestructor: 6847 // C++11 [class.dtor]p5: 6848 // A destructor is trivial if: 6849 // - all the direct [subobjects] have trivial destructors 6850 if (RD->hasTrivialDestructor()) 6851 return true; 6852 6853 if (Selected) { 6854 if (RD->needsImplicitDestructor()) 6855 S.DeclareImplicitDestructor(RD); 6856 *Selected = RD->getDestructor(); 6857 } 6858 6859 return false; 6860 6861 case Sema::CXXCopyConstructor: 6862 // C++11 [class.copy]p12: 6863 // A copy constructor is trivial if: 6864 // - the constructor selected to copy each direct [subobject] is trivial 6865 if (RD->hasTrivialCopyConstructor()) { 6866 if (Quals == Qualifiers::Const) 6867 // We must either select the trivial copy constructor or reach an 6868 // ambiguity; no need to actually perform overload resolution. 6869 return true; 6870 } else if (!Selected) { 6871 return false; 6872 } 6873 // In C++98, we are not supposed to perform overload resolution here, but we 6874 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 6875 // cases like B as having a non-trivial copy constructor: 6876 // struct A { template<typename T> A(T&); }; 6877 // struct B { mutable A a; }; 6878 goto NeedOverloadResolution; 6879 6880 case Sema::CXXCopyAssignment: 6881 // C++11 [class.copy]p25: 6882 // A copy assignment operator is trivial if: 6883 // - the assignment operator selected to copy each direct [subobject] is 6884 // trivial 6885 if (RD->hasTrivialCopyAssignment()) { 6886 if (Quals == Qualifiers::Const) 6887 return true; 6888 } else if (!Selected) { 6889 return false; 6890 } 6891 // In C++98, we are not supposed to perform overload resolution here, but we 6892 // treat that as a language defect. 6893 goto NeedOverloadResolution; 6894 6895 case Sema::CXXMoveConstructor: 6896 case Sema::CXXMoveAssignment: 6897 NeedOverloadResolution: 6898 Sema::SpecialMemberOverloadResult *SMOR = 6899 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 6900 6901 // The standard doesn't describe how to behave if the lookup is ambiguous. 6902 // We treat it as not making the member non-trivial, just like the standard 6903 // mandates for the default constructor. This should rarely matter, because 6904 // the member will also be deleted. 6905 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6906 return true; 6907 6908 if (!SMOR->getMethod()) { 6909 assert(SMOR->getKind() == 6910 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 6911 return false; 6912 } 6913 6914 // We deliberately don't check if we found a deleted special member. We're 6915 // not supposed to! 6916 if (Selected) 6917 *Selected = SMOR->getMethod(); 6918 return SMOR->getMethod()->isTrivial(); 6919 } 6920 6921 llvm_unreachable("unknown special method kind"); 6922 } 6923 6924 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 6925 for (auto *CI : RD->ctors()) 6926 if (!CI->isImplicit()) 6927 return CI; 6928 6929 // Look for constructor templates. 6930 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 6931 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 6932 if (CXXConstructorDecl *CD = 6933 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 6934 return CD; 6935 } 6936 6937 return nullptr; 6938 } 6939 6940 /// The kind of subobject we are checking for triviality. The values of this 6941 /// enumeration are used in diagnostics. 6942 enum TrivialSubobjectKind { 6943 /// The subobject is a base class. 6944 TSK_BaseClass, 6945 /// The subobject is a non-static data member. 6946 TSK_Field, 6947 /// The object is actually the complete object. 6948 TSK_CompleteObject 6949 }; 6950 6951 /// Check whether the special member selected for a given type would be trivial. 6952 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 6953 QualType SubType, bool ConstRHS, 6954 Sema::CXXSpecialMember CSM, 6955 TrivialSubobjectKind Kind, 6956 bool Diagnose) { 6957 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 6958 if (!SubRD) 6959 return true; 6960 6961 CXXMethodDecl *Selected; 6962 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 6963 ConstRHS, Diagnose ? &Selected : nullptr)) 6964 return true; 6965 6966 if (Diagnose) { 6967 if (ConstRHS) 6968 SubType.addConst(); 6969 6970 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 6971 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 6972 << Kind << SubType.getUnqualifiedType(); 6973 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6974 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6975 } else if (!Selected) 6976 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6977 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6978 else if (Selected->isUserProvided()) { 6979 if (Kind == TSK_CompleteObject) 6980 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6981 << Kind << SubType.getUnqualifiedType() << CSM; 6982 else { 6983 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6984 << Kind << SubType.getUnqualifiedType() << CSM; 6985 S.Diag(Selected->getLocation(), diag::note_declared_at); 6986 } 6987 } else { 6988 if (Kind != TSK_CompleteObject) 6989 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6990 << Kind << SubType.getUnqualifiedType() << CSM; 6991 6992 // Explain why the defaulted or deleted special member isn't trivial. 6993 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6994 } 6995 } 6996 6997 return false; 6998 } 6999 7000 /// Check whether the members of a class type allow a special member to be 7001 /// trivial. 7002 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7003 Sema::CXXSpecialMember CSM, 7004 bool ConstArg, bool Diagnose) { 7005 for (const auto *FI : RD->fields()) { 7006 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7007 continue; 7008 7009 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7010 7011 // Pretend anonymous struct or union members are members of this class. 7012 if (FI->isAnonymousStructOrUnion()) { 7013 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7014 CSM, ConstArg, Diagnose)) 7015 return false; 7016 continue; 7017 } 7018 7019 // C++11 [class.ctor]p5: 7020 // A default constructor is trivial if [...] 7021 // -- no non-static data member of its class has a 7022 // brace-or-equal-initializer 7023 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7024 if (Diagnose) 7025 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7026 return false; 7027 } 7028 7029 // Objective C ARC 4.3.5: 7030 // [...] nontrivally ownership-qualified types are [...] not trivially 7031 // default constructible, copy constructible, move constructible, copy 7032 // assignable, move assignable, or destructible [...] 7033 if (S.getLangOpts().ObjCAutoRefCount && 7034 FieldType.hasNonTrivialObjCLifetime()) { 7035 if (Diagnose) 7036 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7037 << RD << FieldType.getObjCLifetime(); 7038 return false; 7039 } 7040 7041 bool ConstRHS = ConstArg && !FI->isMutable(); 7042 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7043 CSM, TSK_Field, Diagnose)) 7044 return false; 7045 } 7046 7047 return true; 7048 } 7049 7050 /// Diagnose why the specified class does not have a trivial special member of 7051 /// the given kind. 7052 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7053 QualType Ty = Context.getRecordType(RD); 7054 7055 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7056 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7057 TSK_CompleteObject, /*Diagnose*/true); 7058 } 7059 7060 /// Determine whether a defaulted or deleted special member function is trivial, 7061 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7062 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7063 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7064 bool Diagnose) { 7065 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7066 7067 CXXRecordDecl *RD = MD->getParent(); 7068 7069 bool ConstArg = false; 7070 7071 // C++11 [class.copy]p12, p25: [DR1593] 7072 // A [special member] is trivial if [...] its parameter-type-list is 7073 // equivalent to the parameter-type-list of an implicit declaration [...] 7074 switch (CSM) { 7075 case CXXDefaultConstructor: 7076 case CXXDestructor: 7077 // Trivial default constructors and destructors cannot have parameters. 7078 break; 7079 7080 case CXXCopyConstructor: 7081 case CXXCopyAssignment: { 7082 // Trivial copy operations always have const, non-volatile parameter types. 7083 ConstArg = true; 7084 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7085 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7086 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7087 if (Diagnose) 7088 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7089 << Param0->getSourceRange() << Param0->getType() 7090 << Context.getLValueReferenceType( 7091 Context.getRecordType(RD).withConst()); 7092 return false; 7093 } 7094 break; 7095 } 7096 7097 case CXXMoveConstructor: 7098 case CXXMoveAssignment: { 7099 // Trivial move operations always have non-cv-qualified parameters. 7100 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7101 const RValueReferenceType *RT = 7102 Param0->getType()->getAs<RValueReferenceType>(); 7103 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7104 if (Diagnose) 7105 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7106 << Param0->getSourceRange() << Param0->getType() 7107 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7108 return false; 7109 } 7110 break; 7111 } 7112 7113 case CXXInvalid: 7114 llvm_unreachable("not a special member"); 7115 } 7116 7117 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7118 if (Diagnose) 7119 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7120 diag::note_nontrivial_default_arg) 7121 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7122 return false; 7123 } 7124 if (MD->isVariadic()) { 7125 if (Diagnose) 7126 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7127 return false; 7128 } 7129 7130 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7131 // A copy/move [constructor or assignment operator] is trivial if 7132 // -- the [member] selected to copy/move each direct base class subobject 7133 // is trivial 7134 // 7135 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7136 // A [default constructor or destructor] is trivial if 7137 // -- all the direct base classes have trivial [default constructors or 7138 // destructors] 7139 for (const auto &BI : RD->bases()) 7140 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7141 ConstArg, CSM, TSK_BaseClass, Diagnose)) 7142 return false; 7143 7144 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7145 // A copy/move [constructor or assignment operator] for a class X is 7146 // trivial if 7147 // -- for each non-static data member of X that is of class type (or array 7148 // thereof), the constructor selected to copy/move that member is 7149 // trivial 7150 // 7151 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7152 // A [default constructor or destructor] is trivial if 7153 // -- for all of the non-static data members of its class that are of class 7154 // type (or array thereof), each such class has a trivial [default 7155 // constructor or destructor] 7156 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 7157 return false; 7158 7159 // C++11 [class.dtor]p5: 7160 // A destructor is trivial if [...] 7161 // -- the destructor is not virtual 7162 if (CSM == CXXDestructor && MD->isVirtual()) { 7163 if (Diagnose) 7164 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7165 return false; 7166 } 7167 7168 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7169 // A [special member] for class X is trivial if [...] 7170 // -- class X has no virtual functions and no virtual base classes 7171 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7172 if (!Diagnose) 7173 return false; 7174 7175 if (RD->getNumVBases()) { 7176 // Check for virtual bases. We already know that the corresponding 7177 // member in all bases is trivial, so vbases must all be direct. 7178 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7179 assert(BS.isVirtual()); 7180 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7181 return false; 7182 } 7183 7184 // Must have a virtual method. 7185 for (const auto *MI : RD->methods()) { 7186 if (MI->isVirtual()) { 7187 SourceLocation MLoc = MI->getLocStart(); 7188 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7189 return false; 7190 } 7191 } 7192 7193 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7194 } 7195 7196 // Looks like it's trivial! 7197 return true; 7198 } 7199 7200 namespace { 7201 struct FindHiddenVirtualMethod { 7202 Sema *S; 7203 CXXMethodDecl *Method; 7204 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7205 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7206 7207 private: 7208 /// Check whether any most overriden method from MD in Methods 7209 static bool CheckMostOverridenMethods( 7210 const CXXMethodDecl *MD, 7211 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7212 if (MD->size_overridden_methods() == 0) 7213 return Methods.count(MD->getCanonicalDecl()); 7214 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7215 E = MD->end_overridden_methods(); 7216 I != E; ++I) 7217 if (CheckMostOverridenMethods(*I, Methods)) 7218 return true; 7219 return false; 7220 } 7221 7222 public: 7223 /// Member lookup function that determines whether a given C++ 7224 /// method overloads virtual methods in a base class without overriding any, 7225 /// to be used with CXXRecordDecl::lookupInBases(). 7226 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7227 RecordDecl *BaseRecord = 7228 Specifier->getType()->getAs<RecordType>()->getDecl(); 7229 7230 DeclarationName Name = Method->getDeclName(); 7231 assert(Name.getNameKind() == DeclarationName::Identifier); 7232 7233 bool foundSameNameMethod = false; 7234 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7235 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7236 Path.Decls = Path.Decls.slice(1)) { 7237 NamedDecl *D = Path.Decls.front(); 7238 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7239 MD = MD->getCanonicalDecl(); 7240 foundSameNameMethod = true; 7241 // Interested only in hidden virtual methods. 7242 if (!MD->isVirtual()) 7243 continue; 7244 // If the method we are checking overrides a method from its base 7245 // don't warn about the other overloaded methods. Clang deviates from 7246 // GCC by only diagnosing overloads of inherited virtual functions that 7247 // do not override any other virtual functions in the base. GCC's 7248 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7249 // function from a base class. These cases may be better served by a 7250 // warning (not specific to virtual functions) on call sites when the 7251 // call would select a different function from the base class, were it 7252 // visible. 7253 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7254 if (!S->IsOverload(Method, MD, false)) 7255 return true; 7256 // Collect the overload only if its hidden. 7257 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7258 overloadedMethods.push_back(MD); 7259 } 7260 } 7261 7262 if (foundSameNameMethod) 7263 OverloadedMethods.append(overloadedMethods.begin(), 7264 overloadedMethods.end()); 7265 return foundSameNameMethod; 7266 } 7267 }; 7268 } // end anonymous namespace 7269 7270 /// \brief Add the most overriden methods from MD to Methods 7271 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7272 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7273 if (MD->size_overridden_methods() == 0) 7274 Methods.insert(MD->getCanonicalDecl()); 7275 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7276 E = MD->end_overridden_methods(); 7277 I != E; ++I) 7278 AddMostOverridenMethods(*I, Methods); 7279 } 7280 7281 /// \brief Check if a method overloads virtual methods in a base class without 7282 /// overriding any. 7283 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7284 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7285 if (!MD->getDeclName().isIdentifier()) 7286 return; 7287 7288 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7289 /*bool RecordPaths=*/false, 7290 /*bool DetectVirtual=*/false); 7291 FindHiddenVirtualMethod FHVM; 7292 FHVM.Method = MD; 7293 FHVM.S = this; 7294 7295 // Keep the base methods that were overriden or introduced in the subclass 7296 // by 'using' in a set. A base method not in this set is hidden. 7297 CXXRecordDecl *DC = MD->getParent(); 7298 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7299 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7300 NamedDecl *ND = *I; 7301 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7302 ND = shad->getTargetDecl(); 7303 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7304 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7305 } 7306 7307 if (DC->lookupInBases(FHVM, Paths)) 7308 OverloadedMethods = FHVM.OverloadedMethods; 7309 } 7310 7311 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7312 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7313 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7314 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7315 PartialDiagnostic PD = PDiag( 7316 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7317 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7318 Diag(overloadedMD->getLocation(), PD); 7319 } 7320 } 7321 7322 /// \brief Diagnose methods which overload virtual methods in a base class 7323 /// without overriding any. 7324 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7325 if (MD->isInvalidDecl()) 7326 return; 7327 7328 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7329 return; 7330 7331 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7332 FindHiddenVirtualMethods(MD, OverloadedMethods); 7333 if (!OverloadedMethods.empty()) { 7334 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7335 << MD << (OverloadedMethods.size() > 1); 7336 7337 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7338 } 7339 } 7340 7341 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7342 Decl *TagDecl, 7343 SourceLocation LBrac, 7344 SourceLocation RBrac, 7345 AttributeList *AttrList) { 7346 if (!TagDecl) 7347 return; 7348 7349 AdjustDeclIfTemplate(TagDecl); 7350 7351 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7352 if (l->getKind() != AttributeList::AT_Visibility) 7353 continue; 7354 l->setInvalid(); 7355 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7356 l->getName(); 7357 } 7358 7359 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7360 // strict aliasing violation! 7361 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7362 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7363 7364 CheckCompletedCXXClass( 7365 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 7366 } 7367 7368 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7369 /// special functions, such as the default constructor, copy 7370 /// constructor, or destructor, to the given C++ class (C++ 7371 /// [special]p1). This routine can only be executed just before the 7372 /// definition of the class is complete. 7373 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7374 if (ClassDecl->needsImplicitDefaultConstructor()) { 7375 ++ASTContext::NumImplicitDefaultConstructors; 7376 7377 if (ClassDecl->hasInheritedConstructor()) 7378 DeclareImplicitDefaultConstructor(ClassDecl); 7379 } 7380 7381 if (ClassDecl->needsImplicitCopyConstructor()) { 7382 ++ASTContext::NumImplicitCopyConstructors; 7383 7384 // If the properties or semantics of the copy constructor couldn't be 7385 // determined while the class was being declared, force a declaration 7386 // of it now. 7387 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7388 ClassDecl->hasInheritedConstructor()) 7389 DeclareImplicitCopyConstructor(ClassDecl); 7390 } 7391 7392 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7393 ++ASTContext::NumImplicitMoveConstructors; 7394 7395 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7396 ClassDecl->hasInheritedConstructor()) 7397 DeclareImplicitMoveConstructor(ClassDecl); 7398 } 7399 7400 if (ClassDecl->needsImplicitCopyAssignment()) { 7401 ++ASTContext::NumImplicitCopyAssignmentOperators; 7402 7403 // If we have a dynamic class, then the copy assignment operator may be 7404 // virtual, so we have to declare it immediately. This ensures that, e.g., 7405 // it shows up in the right place in the vtable and that we diagnose 7406 // problems with the implicit exception specification. 7407 if (ClassDecl->isDynamicClass() || 7408 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7409 ClassDecl->hasInheritedAssignment()) 7410 DeclareImplicitCopyAssignment(ClassDecl); 7411 } 7412 7413 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7414 ++ASTContext::NumImplicitMoveAssignmentOperators; 7415 7416 // Likewise for the move assignment operator. 7417 if (ClassDecl->isDynamicClass() || 7418 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7419 ClassDecl->hasInheritedAssignment()) 7420 DeclareImplicitMoveAssignment(ClassDecl); 7421 } 7422 7423 if (ClassDecl->needsImplicitDestructor()) { 7424 ++ASTContext::NumImplicitDestructors; 7425 7426 // If we have a dynamic class, then the destructor may be virtual, so we 7427 // have to declare the destructor immediately. This ensures that, e.g., it 7428 // shows up in the right place in the vtable and that we diagnose problems 7429 // with the implicit exception specification. 7430 if (ClassDecl->isDynamicClass() || 7431 ClassDecl->needsOverloadResolutionForDestructor()) 7432 DeclareImplicitDestructor(ClassDecl); 7433 } 7434 } 7435 7436 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7437 if (!D) 7438 return 0; 7439 7440 // The order of template parameters is not important here. All names 7441 // get added to the same scope. 7442 SmallVector<TemplateParameterList *, 4> ParameterLists; 7443 7444 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7445 D = TD->getTemplatedDecl(); 7446 7447 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7448 ParameterLists.push_back(PSD->getTemplateParameters()); 7449 7450 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7451 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7452 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7453 7454 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7455 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7456 ParameterLists.push_back(FTD->getTemplateParameters()); 7457 } 7458 } 7459 7460 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7461 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7462 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7463 7464 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7465 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7466 ParameterLists.push_back(CTD->getTemplateParameters()); 7467 } 7468 } 7469 7470 unsigned Count = 0; 7471 for (TemplateParameterList *Params : ParameterLists) { 7472 if (Params->size() > 0) 7473 // Ignore explicit specializations; they don't contribute to the template 7474 // depth. 7475 ++Count; 7476 for (NamedDecl *Param : *Params) { 7477 if (Param->getDeclName()) { 7478 S->AddDecl(Param); 7479 IdResolver.AddDecl(Param); 7480 } 7481 } 7482 } 7483 7484 return Count; 7485 } 7486 7487 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7488 if (!RecordD) return; 7489 AdjustDeclIfTemplate(RecordD); 7490 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7491 PushDeclContext(S, Record); 7492 } 7493 7494 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7495 if (!RecordD) return; 7496 PopDeclContext(); 7497 } 7498 7499 /// This is used to implement the constant expression evaluation part of the 7500 /// attribute enable_if extension. There is nothing in standard C++ which would 7501 /// require reentering parameters. 7502 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7503 if (!Param) 7504 return; 7505 7506 S->AddDecl(Param); 7507 if (Param->getDeclName()) 7508 IdResolver.AddDecl(Param); 7509 } 7510 7511 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7512 /// parsing a top-level (non-nested) C++ class, and we are now 7513 /// parsing those parts of the given Method declaration that could 7514 /// not be parsed earlier (C++ [class.mem]p2), such as default 7515 /// arguments. This action should enter the scope of the given 7516 /// Method declaration as if we had just parsed the qualified method 7517 /// name. However, it should not bring the parameters into scope; 7518 /// that will be performed by ActOnDelayedCXXMethodParameter. 7519 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7520 } 7521 7522 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7523 /// C++ method declaration. We're (re-)introducing the given 7524 /// function parameter into scope for use in parsing later parts of 7525 /// the method declaration. For example, we could see an 7526 /// ActOnParamDefaultArgument event for this parameter. 7527 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7528 if (!ParamD) 7529 return; 7530 7531 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7532 7533 // If this parameter has an unparsed default argument, clear it out 7534 // to make way for the parsed default argument. 7535 if (Param->hasUnparsedDefaultArg()) 7536 Param->setDefaultArg(nullptr); 7537 7538 S->AddDecl(Param); 7539 if (Param->getDeclName()) 7540 IdResolver.AddDecl(Param); 7541 } 7542 7543 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7544 /// processing the delayed method declaration for Method. The method 7545 /// declaration is now considered finished. There may be a separate 7546 /// ActOnStartOfFunctionDef action later (not necessarily 7547 /// immediately!) for this method, if it was also defined inside the 7548 /// class body. 7549 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7550 if (!MethodD) 7551 return; 7552 7553 AdjustDeclIfTemplate(MethodD); 7554 7555 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7556 7557 // Now that we have our default arguments, check the constructor 7558 // again. It could produce additional diagnostics or affect whether 7559 // the class has implicitly-declared destructors, among other 7560 // things. 7561 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7562 CheckConstructor(Constructor); 7563 7564 // Check the default arguments, which we may have added. 7565 if (!Method->isInvalidDecl()) 7566 CheckCXXDefaultArguments(Method); 7567 } 7568 7569 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7570 /// the well-formedness of the constructor declarator @p D with type @p 7571 /// R. If there are any errors in the declarator, this routine will 7572 /// emit diagnostics and set the invalid bit to true. In any case, the type 7573 /// will be updated to reflect a well-formed type for the constructor and 7574 /// returned. 7575 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7576 StorageClass &SC) { 7577 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7578 7579 // C++ [class.ctor]p3: 7580 // A constructor shall not be virtual (10.3) or static (9.4). A 7581 // constructor can be invoked for a const, volatile or const 7582 // volatile object. A constructor shall not be declared const, 7583 // volatile, or const volatile (9.3.2). 7584 if (isVirtual) { 7585 if (!D.isInvalidType()) 7586 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7587 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7588 << SourceRange(D.getIdentifierLoc()); 7589 D.setInvalidType(); 7590 } 7591 if (SC == SC_Static) { 7592 if (!D.isInvalidType()) 7593 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7594 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7595 << SourceRange(D.getIdentifierLoc()); 7596 D.setInvalidType(); 7597 SC = SC_None; 7598 } 7599 7600 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7601 diagnoseIgnoredQualifiers( 7602 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7603 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7604 D.getDeclSpec().getRestrictSpecLoc(), 7605 D.getDeclSpec().getAtomicSpecLoc()); 7606 D.setInvalidType(); 7607 } 7608 7609 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7610 if (FTI.TypeQuals != 0) { 7611 if (FTI.TypeQuals & Qualifiers::Const) 7612 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7613 << "const" << SourceRange(D.getIdentifierLoc()); 7614 if (FTI.TypeQuals & Qualifiers::Volatile) 7615 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7616 << "volatile" << SourceRange(D.getIdentifierLoc()); 7617 if (FTI.TypeQuals & Qualifiers::Restrict) 7618 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7619 << "restrict" << SourceRange(D.getIdentifierLoc()); 7620 D.setInvalidType(); 7621 } 7622 7623 // C++0x [class.ctor]p4: 7624 // A constructor shall not be declared with a ref-qualifier. 7625 if (FTI.hasRefQualifier()) { 7626 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7627 << FTI.RefQualifierIsLValueRef 7628 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7629 D.setInvalidType(); 7630 } 7631 7632 // Rebuild the function type "R" without any type qualifiers (in 7633 // case any of the errors above fired) and with "void" as the 7634 // return type, since constructors don't have return types. 7635 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7636 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7637 return R; 7638 7639 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7640 EPI.TypeQuals = 0; 7641 EPI.RefQualifier = RQ_None; 7642 7643 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7644 } 7645 7646 /// CheckConstructor - Checks a fully-formed constructor for 7647 /// well-formedness, issuing any diagnostics required. Returns true if 7648 /// the constructor declarator is invalid. 7649 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7650 CXXRecordDecl *ClassDecl 7651 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7652 if (!ClassDecl) 7653 return Constructor->setInvalidDecl(); 7654 7655 // C++ [class.copy]p3: 7656 // A declaration of a constructor for a class X is ill-formed if 7657 // its first parameter is of type (optionally cv-qualified) X and 7658 // either there are no other parameters or else all other 7659 // parameters have default arguments. 7660 if (!Constructor->isInvalidDecl() && 7661 ((Constructor->getNumParams() == 1) || 7662 (Constructor->getNumParams() > 1 && 7663 Constructor->getParamDecl(1)->hasDefaultArg())) && 7664 Constructor->getTemplateSpecializationKind() 7665 != TSK_ImplicitInstantiation) { 7666 QualType ParamType = Constructor->getParamDecl(0)->getType(); 7667 QualType ClassTy = Context.getTagDeclType(ClassDecl); 7668 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 7669 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 7670 const char *ConstRef 7671 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 7672 : " const &"; 7673 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 7674 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 7675 7676 // FIXME: Rather that making the constructor invalid, we should endeavor 7677 // to fix the type. 7678 Constructor->setInvalidDecl(); 7679 } 7680 } 7681 } 7682 7683 /// CheckDestructor - Checks a fully-formed destructor definition for 7684 /// well-formedness, issuing any diagnostics required. Returns true 7685 /// on error. 7686 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 7687 CXXRecordDecl *RD = Destructor->getParent(); 7688 7689 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 7690 SourceLocation Loc; 7691 7692 if (!Destructor->isImplicit()) 7693 Loc = Destructor->getLocation(); 7694 else 7695 Loc = RD->getLocation(); 7696 7697 // If we have a virtual destructor, look up the deallocation function 7698 FunctionDecl *OperatorDelete = nullptr; 7699 DeclarationName Name = 7700 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7701 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 7702 return true; 7703 // If there's no class-specific operator delete, look up the global 7704 // non-array delete. 7705 if (!OperatorDelete) 7706 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 7707 7708 MarkFunctionReferenced(Loc, OperatorDelete); 7709 7710 Destructor->setOperatorDelete(OperatorDelete); 7711 } 7712 7713 return false; 7714 } 7715 7716 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 7717 /// the well-formednes of the destructor declarator @p D with type @p 7718 /// R. If there are any errors in the declarator, this routine will 7719 /// emit diagnostics and set the declarator to invalid. Even if this happens, 7720 /// will be updated to reflect a well-formed type for the destructor and 7721 /// returned. 7722 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 7723 StorageClass& SC) { 7724 // C++ [class.dtor]p1: 7725 // [...] A typedef-name that names a class is a class-name 7726 // (7.1.3); however, a typedef-name that names a class shall not 7727 // be used as the identifier in the declarator for a destructor 7728 // declaration. 7729 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 7730 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 7731 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7732 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 7733 else if (const TemplateSpecializationType *TST = 7734 DeclaratorType->getAs<TemplateSpecializationType>()) 7735 if (TST->isTypeAlias()) 7736 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7737 << DeclaratorType << 1; 7738 7739 // C++ [class.dtor]p2: 7740 // A destructor is used to destroy objects of its class type. A 7741 // destructor takes no parameters, and no return type can be 7742 // specified for it (not even void). The address of a destructor 7743 // shall not be taken. A destructor shall not be static. A 7744 // destructor can be invoked for a const, volatile or const 7745 // volatile object. A destructor shall not be declared const, 7746 // volatile or const volatile (9.3.2). 7747 if (SC == SC_Static) { 7748 if (!D.isInvalidType()) 7749 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 7750 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7751 << SourceRange(D.getIdentifierLoc()) 7752 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7753 7754 SC = SC_None; 7755 } 7756 if (!D.isInvalidType()) { 7757 // Destructors don't have return types, but the parser will 7758 // happily parse something like: 7759 // 7760 // class X { 7761 // float ~X(); 7762 // }; 7763 // 7764 // The return type will be eliminated later. 7765 if (D.getDeclSpec().hasTypeSpecifier()) 7766 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 7767 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7768 << SourceRange(D.getIdentifierLoc()); 7769 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7770 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 7771 SourceLocation(), 7772 D.getDeclSpec().getConstSpecLoc(), 7773 D.getDeclSpec().getVolatileSpecLoc(), 7774 D.getDeclSpec().getRestrictSpecLoc(), 7775 D.getDeclSpec().getAtomicSpecLoc()); 7776 D.setInvalidType(); 7777 } 7778 } 7779 7780 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7781 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 7782 if (FTI.TypeQuals & Qualifiers::Const) 7783 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7784 << "const" << SourceRange(D.getIdentifierLoc()); 7785 if (FTI.TypeQuals & Qualifiers::Volatile) 7786 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7787 << "volatile" << SourceRange(D.getIdentifierLoc()); 7788 if (FTI.TypeQuals & Qualifiers::Restrict) 7789 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7790 << "restrict" << SourceRange(D.getIdentifierLoc()); 7791 D.setInvalidType(); 7792 } 7793 7794 // C++0x [class.dtor]p2: 7795 // A destructor shall not be declared with a ref-qualifier. 7796 if (FTI.hasRefQualifier()) { 7797 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 7798 << FTI.RefQualifierIsLValueRef 7799 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7800 D.setInvalidType(); 7801 } 7802 7803 // Make sure we don't have any parameters. 7804 if (FTIHasNonVoidParameters(FTI)) { 7805 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 7806 7807 // Delete the parameters. 7808 FTI.freeParams(); 7809 D.setInvalidType(); 7810 } 7811 7812 // Make sure the destructor isn't variadic. 7813 if (FTI.isVariadic) { 7814 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 7815 D.setInvalidType(); 7816 } 7817 7818 // Rebuild the function type "R" without any type qualifiers or 7819 // parameters (in case any of the errors above fired) and with 7820 // "void" as the return type, since destructors don't have return 7821 // types. 7822 if (!D.isInvalidType()) 7823 return R; 7824 7825 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7826 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7827 EPI.Variadic = false; 7828 EPI.TypeQuals = 0; 7829 EPI.RefQualifier = RQ_None; 7830 return Context.getFunctionType(Context.VoidTy, None, EPI); 7831 } 7832 7833 static void extendLeft(SourceRange &R, SourceRange Before) { 7834 if (Before.isInvalid()) 7835 return; 7836 R.setBegin(Before.getBegin()); 7837 if (R.getEnd().isInvalid()) 7838 R.setEnd(Before.getEnd()); 7839 } 7840 7841 static void extendRight(SourceRange &R, SourceRange After) { 7842 if (After.isInvalid()) 7843 return; 7844 if (R.getBegin().isInvalid()) 7845 R.setBegin(After.getBegin()); 7846 R.setEnd(After.getEnd()); 7847 } 7848 7849 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 7850 /// well-formednes of the conversion function declarator @p D with 7851 /// type @p R. If there are any errors in the declarator, this routine 7852 /// will emit diagnostics and return true. Otherwise, it will return 7853 /// false. Either way, the type @p R will be updated to reflect a 7854 /// well-formed type for the conversion operator. 7855 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 7856 StorageClass& SC) { 7857 // C++ [class.conv.fct]p1: 7858 // Neither parameter types nor return type can be specified. The 7859 // type of a conversion function (8.3.5) is "function taking no 7860 // parameter returning conversion-type-id." 7861 if (SC == SC_Static) { 7862 if (!D.isInvalidType()) 7863 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 7864 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7865 << D.getName().getSourceRange(); 7866 D.setInvalidType(); 7867 SC = SC_None; 7868 } 7869 7870 TypeSourceInfo *ConvTSI = nullptr; 7871 QualType ConvType = 7872 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 7873 7874 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 7875 // Conversion functions don't have return types, but the parser will 7876 // happily parse something like: 7877 // 7878 // class X { 7879 // float operator bool(); 7880 // }; 7881 // 7882 // The return type will be changed later anyway. 7883 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 7884 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7885 << SourceRange(D.getIdentifierLoc()); 7886 D.setInvalidType(); 7887 } 7888 7889 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7890 7891 // Make sure we don't have any parameters. 7892 if (Proto->getNumParams() > 0) { 7893 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 7894 7895 // Delete the parameters. 7896 D.getFunctionTypeInfo().freeParams(); 7897 D.setInvalidType(); 7898 } else if (Proto->isVariadic()) { 7899 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 7900 D.setInvalidType(); 7901 } 7902 7903 // Diagnose "&operator bool()" and other such nonsense. This 7904 // is actually a gcc extension which we don't support. 7905 if (Proto->getReturnType() != ConvType) { 7906 bool NeedsTypedef = false; 7907 SourceRange Before, After; 7908 7909 // Walk the chunks and extract information on them for our diagnostic. 7910 bool PastFunctionChunk = false; 7911 for (auto &Chunk : D.type_objects()) { 7912 switch (Chunk.Kind) { 7913 case DeclaratorChunk::Function: 7914 if (!PastFunctionChunk) { 7915 if (Chunk.Fun.HasTrailingReturnType) { 7916 TypeSourceInfo *TRT = nullptr; 7917 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 7918 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 7919 } 7920 PastFunctionChunk = true; 7921 break; 7922 } 7923 // Fall through. 7924 case DeclaratorChunk::Array: 7925 NeedsTypedef = true; 7926 extendRight(After, Chunk.getSourceRange()); 7927 break; 7928 7929 case DeclaratorChunk::Pointer: 7930 case DeclaratorChunk::BlockPointer: 7931 case DeclaratorChunk::Reference: 7932 case DeclaratorChunk::MemberPointer: 7933 case DeclaratorChunk::Pipe: 7934 extendLeft(Before, Chunk.getSourceRange()); 7935 break; 7936 7937 case DeclaratorChunk::Paren: 7938 extendLeft(Before, Chunk.Loc); 7939 extendRight(After, Chunk.EndLoc); 7940 break; 7941 } 7942 } 7943 7944 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 7945 After.isValid() ? After.getBegin() : 7946 D.getIdentifierLoc(); 7947 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 7948 DB << Before << After; 7949 7950 if (!NeedsTypedef) { 7951 DB << /*don't need a typedef*/0; 7952 7953 // If we can provide a correct fix-it hint, do so. 7954 if (After.isInvalid() && ConvTSI) { 7955 SourceLocation InsertLoc = 7956 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 7957 DB << FixItHint::CreateInsertion(InsertLoc, " ") 7958 << FixItHint::CreateInsertionFromRange( 7959 InsertLoc, CharSourceRange::getTokenRange(Before)) 7960 << FixItHint::CreateRemoval(Before); 7961 } 7962 } else if (!Proto->getReturnType()->isDependentType()) { 7963 DB << /*typedef*/1 << Proto->getReturnType(); 7964 } else if (getLangOpts().CPlusPlus11) { 7965 DB << /*alias template*/2 << Proto->getReturnType(); 7966 } else { 7967 DB << /*might not be fixable*/3; 7968 } 7969 7970 // Recover by incorporating the other type chunks into the result type. 7971 // Note, this does *not* change the name of the function. This is compatible 7972 // with the GCC extension: 7973 // struct S { &operator int(); } s; 7974 // int &r = s.operator int(); // ok in GCC 7975 // S::operator int&() {} // error in GCC, function name is 'operator int'. 7976 ConvType = Proto->getReturnType(); 7977 } 7978 7979 // C++ [class.conv.fct]p4: 7980 // The conversion-type-id shall not represent a function type nor 7981 // an array type. 7982 if (ConvType->isArrayType()) { 7983 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7984 ConvType = Context.getPointerType(ConvType); 7985 D.setInvalidType(); 7986 } else if (ConvType->isFunctionType()) { 7987 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7988 ConvType = Context.getPointerType(ConvType); 7989 D.setInvalidType(); 7990 } 7991 7992 // Rebuild the function type "R" without any parameters (in case any 7993 // of the errors above fired) and with the conversion type as the 7994 // return type. 7995 if (D.isInvalidType()) 7996 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7997 7998 // C++0x explicit conversion operators. 7999 if (D.getDeclSpec().isExplicitSpecified()) 8000 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8001 getLangOpts().CPlusPlus11 ? 8002 diag::warn_cxx98_compat_explicit_conversion_functions : 8003 diag::ext_explicit_conversion_functions) 8004 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 8005 } 8006 8007 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8008 /// the declaration of the given C++ conversion function. This routine 8009 /// is responsible for recording the conversion function in the C++ 8010 /// class, if possible. 8011 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8012 assert(Conversion && "Expected to receive a conversion function declaration"); 8013 8014 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8015 8016 // Make sure we aren't redeclaring the conversion function. 8017 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8018 8019 // C++ [class.conv.fct]p1: 8020 // [...] A conversion function is never used to convert a 8021 // (possibly cv-qualified) object to the (possibly cv-qualified) 8022 // same object type (or a reference to it), to a (possibly 8023 // cv-qualified) base class of that type (or a reference to it), 8024 // or to (possibly cv-qualified) void. 8025 // FIXME: Suppress this warning if the conversion function ends up being a 8026 // virtual function that overrides a virtual function in a base class. 8027 QualType ClassType 8028 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8029 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8030 ConvType = ConvTypeRef->getPointeeType(); 8031 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8032 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8033 /* Suppress diagnostics for instantiations. */; 8034 else if (ConvType->isRecordType()) { 8035 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8036 if (ConvType == ClassType) 8037 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8038 << ClassType; 8039 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8040 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8041 << ClassType << ConvType; 8042 } else if (ConvType->isVoidType()) { 8043 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8044 << ClassType << ConvType; 8045 } 8046 8047 if (FunctionTemplateDecl *ConversionTemplate 8048 = Conversion->getDescribedFunctionTemplate()) 8049 return ConversionTemplate; 8050 8051 return Conversion; 8052 } 8053 8054 //===----------------------------------------------------------------------===// 8055 // Namespace Handling 8056 //===----------------------------------------------------------------------===// 8057 8058 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8059 /// reopened. 8060 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8061 SourceLocation Loc, 8062 IdentifierInfo *II, bool *IsInline, 8063 NamespaceDecl *PrevNS) { 8064 assert(*IsInline != PrevNS->isInline()); 8065 8066 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8067 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8068 // inline namespaces, with the intention of bringing names into namespace std. 8069 // 8070 // We support this just well enough to get that case working; this is not 8071 // sufficient to support reopening namespaces as inline in general. 8072 if (*IsInline && II && II->getName().startswith("__atomic") && 8073 S.getSourceManager().isInSystemHeader(Loc)) { 8074 // Mark all prior declarations of the namespace as inline. 8075 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8076 NS = NS->getPreviousDecl()) 8077 NS->setInline(*IsInline); 8078 // Patch up the lookup table for the containing namespace. This isn't really 8079 // correct, but it's good enough for this particular case. 8080 for (auto *I : PrevNS->decls()) 8081 if (auto *ND = dyn_cast<NamedDecl>(I)) 8082 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8083 return; 8084 } 8085 8086 if (PrevNS->isInline()) 8087 // The user probably just forgot the 'inline', so suggest that it 8088 // be added back. 8089 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8090 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8091 else 8092 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 8093 8094 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8095 *IsInline = PrevNS->isInline(); 8096 } 8097 8098 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8099 /// definition. 8100 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8101 SourceLocation InlineLoc, 8102 SourceLocation NamespaceLoc, 8103 SourceLocation IdentLoc, 8104 IdentifierInfo *II, 8105 SourceLocation LBrace, 8106 AttributeList *AttrList, 8107 UsingDirectiveDecl *&UD) { 8108 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8109 // For anonymous namespace, take the location of the left brace. 8110 SourceLocation Loc = II ? IdentLoc : LBrace; 8111 bool IsInline = InlineLoc.isValid(); 8112 bool IsInvalid = false; 8113 bool IsStd = false; 8114 bool AddToKnown = false; 8115 Scope *DeclRegionScope = NamespcScope->getParent(); 8116 8117 NamespaceDecl *PrevNS = nullptr; 8118 if (II) { 8119 // C++ [namespace.def]p2: 8120 // The identifier in an original-namespace-definition shall not 8121 // have been previously defined in the declarative region in 8122 // which the original-namespace-definition appears. The 8123 // identifier in an original-namespace-definition is the name of 8124 // the namespace. Subsequently in that declarative region, it is 8125 // treated as an original-namespace-name. 8126 // 8127 // Since namespace names are unique in their scope, and we don't 8128 // look through using directives, just look for any ordinary names 8129 // as if by qualified name lookup. 8130 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration); 8131 LookupQualifiedName(R, CurContext->getRedeclContext()); 8132 NamedDecl *PrevDecl = 8133 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8134 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8135 8136 if (PrevNS) { 8137 // This is an extended namespace definition. 8138 if (IsInline != PrevNS->isInline()) 8139 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8140 &IsInline, PrevNS); 8141 } else if (PrevDecl) { 8142 // This is an invalid name redefinition. 8143 Diag(Loc, diag::err_redefinition_different_kind) 8144 << II; 8145 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8146 IsInvalid = true; 8147 // Continue on to push Namespc as current DeclContext and return it. 8148 } else if (II->isStr("std") && 8149 CurContext->getRedeclContext()->isTranslationUnit()) { 8150 // This is the first "real" definition of the namespace "std", so update 8151 // our cache of the "std" namespace to point at this definition. 8152 PrevNS = getStdNamespace(); 8153 IsStd = true; 8154 AddToKnown = !IsInline; 8155 } else { 8156 // We've seen this namespace for the first time. 8157 AddToKnown = !IsInline; 8158 } 8159 } else { 8160 // Anonymous namespaces. 8161 8162 // Determine whether the parent already has an anonymous namespace. 8163 DeclContext *Parent = CurContext->getRedeclContext(); 8164 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8165 PrevNS = TU->getAnonymousNamespace(); 8166 } else { 8167 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8168 PrevNS = ND->getAnonymousNamespace(); 8169 } 8170 8171 if (PrevNS && IsInline != PrevNS->isInline()) 8172 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8173 &IsInline, PrevNS); 8174 } 8175 8176 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8177 StartLoc, Loc, II, PrevNS); 8178 if (IsInvalid) 8179 Namespc->setInvalidDecl(); 8180 8181 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8182 8183 // FIXME: Should we be merging attributes? 8184 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8185 PushNamespaceVisibilityAttr(Attr, Loc); 8186 8187 if (IsStd) 8188 StdNamespace = Namespc; 8189 if (AddToKnown) 8190 KnownNamespaces[Namespc] = false; 8191 8192 if (II) { 8193 PushOnScopeChains(Namespc, DeclRegionScope); 8194 } else { 8195 // Link the anonymous namespace into its parent. 8196 DeclContext *Parent = CurContext->getRedeclContext(); 8197 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8198 TU->setAnonymousNamespace(Namespc); 8199 } else { 8200 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8201 } 8202 8203 CurContext->addDecl(Namespc); 8204 8205 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8206 // behaves as if it were replaced by 8207 // namespace unique { /* empty body */ } 8208 // using namespace unique; 8209 // namespace unique { namespace-body } 8210 // where all occurrences of 'unique' in a translation unit are 8211 // replaced by the same identifier and this identifier differs 8212 // from all other identifiers in the entire program. 8213 8214 // We just create the namespace with an empty name and then add an 8215 // implicit using declaration, just like the standard suggests. 8216 // 8217 // CodeGen enforces the "universally unique" aspect by giving all 8218 // declarations semantically contained within an anonymous 8219 // namespace internal linkage. 8220 8221 if (!PrevNS) { 8222 UD = UsingDirectiveDecl::Create(Context, Parent, 8223 /* 'using' */ LBrace, 8224 /* 'namespace' */ SourceLocation(), 8225 /* qualifier */ NestedNameSpecifierLoc(), 8226 /* identifier */ SourceLocation(), 8227 Namespc, 8228 /* Ancestor */ Parent); 8229 UD->setImplicit(); 8230 Parent->addDecl(UD); 8231 } 8232 } 8233 8234 ActOnDocumentableDecl(Namespc); 8235 8236 // Although we could have an invalid decl (i.e. the namespace name is a 8237 // redefinition), push it as current DeclContext and try to continue parsing. 8238 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8239 // for the namespace has the declarations that showed up in that particular 8240 // namespace definition. 8241 PushDeclContext(NamespcScope, Namespc); 8242 return Namespc; 8243 } 8244 8245 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8246 /// is a namespace alias, returns the namespace it points to. 8247 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8248 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8249 return AD->getNamespace(); 8250 return dyn_cast_or_null<NamespaceDecl>(D); 8251 } 8252 8253 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8254 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8255 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8256 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8257 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8258 Namespc->setRBraceLoc(RBrace); 8259 PopDeclContext(); 8260 if (Namespc->hasAttr<VisibilityAttr>()) 8261 PopPragmaVisibility(true, RBrace); 8262 } 8263 8264 CXXRecordDecl *Sema::getStdBadAlloc() const { 8265 return cast_or_null<CXXRecordDecl>( 8266 StdBadAlloc.get(Context.getExternalSource())); 8267 } 8268 8269 NamespaceDecl *Sema::getStdNamespace() const { 8270 return cast_or_null<NamespaceDecl>( 8271 StdNamespace.get(Context.getExternalSource())); 8272 } 8273 8274 /// \brief Retrieve the special "std" namespace, which may require us to 8275 /// implicitly define the namespace. 8276 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8277 if (!StdNamespace) { 8278 // The "std" namespace has not yet been defined, so build one implicitly. 8279 StdNamespace = NamespaceDecl::Create(Context, 8280 Context.getTranslationUnitDecl(), 8281 /*Inline=*/false, 8282 SourceLocation(), SourceLocation(), 8283 &PP.getIdentifierTable().get("std"), 8284 /*PrevDecl=*/nullptr); 8285 getStdNamespace()->setImplicit(true); 8286 } 8287 8288 return getStdNamespace(); 8289 } 8290 8291 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8292 assert(getLangOpts().CPlusPlus && 8293 "Looking for std::initializer_list outside of C++."); 8294 8295 // We're looking for implicit instantiations of 8296 // template <typename E> class std::initializer_list. 8297 8298 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8299 return false; 8300 8301 ClassTemplateDecl *Template = nullptr; 8302 const TemplateArgument *Arguments = nullptr; 8303 8304 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8305 8306 ClassTemplateSpecializationDecl *Specialization = 8307 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8308 if (!Specialization) 8309 return false; 8310 8311 Template = Specialization->getSpecializedTemplate(); 8312 Arguments = Specialization->getTemplateArgs().data(); 8313 } else if (const TemplateSpecializationType *TST = 8314 Ty->getAs<TemplateSpecializationType>()) { 8315 Template = dyn_cast_or_null<ClassTemplateDecl>( 8316 TST->getTemplateName().getAsTemplateDecl()); 8317 Arguments = TST->getArgs(); 8318 } 8319 if (!Template) 8320 return false; 8321 8322 if (!StdInitializerList) { 8323 // Haven't recognized std::initializer_list yet, maybe this is it. 8324 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8325 if (TemplateClass->getIdentifier() != 8326 &PP.getIdentifierTable().get("initializer_list") || 8327 !getStdNamespace()->InEnclosingNamespaceSetOf( 8328 TemplateClass->getDeclContext())) 8329 return false; 8330 // This is a template called std::initializer_list, but is it the right 8331 // template? 8332 TemplateParameterList *Params = Template->getTemplateParameters(); 8333 if (Params->getMinRequiredArguments() != 1) 8334 return false; 8335 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8336 return false; 8337 8338 // It's the right template. 8339 StdInitializerList = Template; 8340 } 8341 8342 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8343 return false; 8344 8345 // This is an instance of std::initializer_list. Find the argument type. 8346 if (Element) 8347 *Element = Arguments[0].getAsType(); 8348 return true; 8349 } 8350 8351 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8352 NamespaceDecl *Std = S.getStdNamespace(); 8353 if (!Std) { 8354 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8355 return nullptr; 8356 } 8357 8358 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8359 Loc, Sema::LookupOrdinaryName); 8360 if (!S.LookupQualifiedName(Result, Std)) { 8361 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8362 return nullptr; 8363 } 8364 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8365 if (!Template) { 8366 Result.suppressDiagnostics(); 8367 // We found something weird. Complain about the first thing we found. 8368 NamedDecl *Found = *Result.begin(); 8369 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8370 return nullptr; 8371 } 8372 8373 // We found some template called std::initializer_list. Now verify that it's 8374 // correct. 8375 TemplateParameterList *Params = Template->getTemplateParameters(); 8376 if (Params->getMinRequiredArguments() != 1 || 8377 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8378 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8379 return nullptr; 8380 } 8381 8382 return Template; 8383 } 8384 8385 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8386 if (!StdInitializerList) { 8387 StdInitializerList = LookupStdInitializerList(*this, Loc); 8388 if (!StdInitializerList) 8389 return QualType(); 8390 } 8391 8392 TemplateArgumentListInfo Args(Loc, Loc); 8393 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8394 Context.getTrivialTypeSourceInfo(Element, 8395 Loc))); 8396 return Context.getCanonicalType( 8397 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8398 } 8399 8400 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 8401 // C++ [dcl.init.list]p2: 8402 // A constructor is an initializer-list constructor if its first parameter 8403 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8404 // std::initializer_list<E> for some type E, and either there are no other 8405 // parameters or else all other parameters have default arguments. 8406 if (Ctor->getNumParams() < 1 || 8407 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8408 return false; 8409 8410 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8411 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8412 ArgType = RT->getPointeeType().getUnqualifiedType(); 8413 8414 return isStdInitializerList(ArgType, nullptr); 8415 } 8416 8417 /// \brief Determine whether a using statement is in a context where it will be 8418 /// apply in all contexts. 8419 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8420 switch (CurContext->getDeclKind()) { 8421 case Decl::TranslationUnit: 8422 return true; 8423 case Decl::LinkageSpec: 8424 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8425 default: 8426 return false; 8427 } 8428 } 8429 8430 namespace { 8431 8432 // Callback to only accept typo corrections that are namespaces. 8433 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8434 public: 8435 bool ValidateCandidate(const TypoCorrection &candidate) override { 8436 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8437 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8438 return false; 8439 } 8440 }; 8441 8442 } 8443 8444 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8445 CXXScopeSpec &SS, 8446 SourceLocation IdentLoc, 8447 IdentifierInfo *Ident) { 8448 R.clear(); 8449 if (TypoCorrection Corrected = 8450 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8451 llvm::make_unique<NamespaceValidatorCCC>(), 8452 Sema::CTK_ErrorRecovery)) { 8453 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8454 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8455 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8456 Ident->getName().equals(CorrectedStr); 8457 S.diagnoseTypo(Corrected, 8458 S.PDiag(diag::err_using_directive_member_suggest) 8459 << Ident << DC << DroppedSpecifier << SS.getRange(), 8460 S.PDiag(diag::note_namespace_defined_here)); 8461 } else { 8462 S.diagnoseTypo(Corrected, 8463 S.PDiag(diag::err_using_directive_suggest) << Ident, 8464 S.PDiag(diag::note_namespace_defined_here)); 8465 } 8466 R.addDecl(Corrected.getFoundDecl()); 8467 return true; 8468 } 8469 return false; 8470 } 8471 8472 Decl *Sema::ActOnUsingDirective(Scope *S, 8473 SourceLocation UsingLoc, 8474 SourceLocation NamespcLoc, 8475 CXXScopeSpec &SS, 8476 SourceLocation IdentLoc, 8477 IdentifierInfo *NamespcName, 8478 AttributeList *AttrList) { 8479 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8480 assert(NamespcName && "Invalid NamespcName."); 8481 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 8482 8483 // This can only happen along a recovery path. 8484 while (S->isTemplateParamScope()) 8485 S = S->getParent(); 8486 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8487 8488 UsingDirectiveDecl *UDir = nullptr; 8489 NestedNameSpecifier *Qualifier = nullptr; 8490 if (SS.isSet()) 8491 Qualifier = SS.getScopeRep(); 8492 8493 // Lookup namespace name. 8494 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 8495 LookupParsedName(R, S, &SS); 8496 if (R.isAmbiguous()) 8497 return nullptr; 8498 8499 if (R.empty()) { 8500 R.clear(); 8501 // Allow "using namespace std;" or "using namespace ::std;" even if 8502 // "std" hasn't been defined yet, for GCC compatibility. 8503 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 8504 NamespcName->isStr("std")) { 8505 Diag(IdentLoc, diag::ext_using_undefined_std); 8506 R.addDecl(getOrCreateStdNamespace()); 8507 R.resolveKind(); 8508 } 8509 // Otherwise, attempt typo correction. 8510 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 8511 } 8512 8513 if (!R.empty()) { 8514 NamedDecl *Named = R.getRepresentativeDecl(); 8515 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 8516 assert(NS && "expected namespace decl"); 8517 8518 // The use of a nested name specifier may trigger deprecation warnings. 8519 DiagnoseUseOfDecl(Named, IdentLoc); 8520 8521 // C++ [namespace.udir]p1: 8522 // A using-directive specifies that the names in the nominated 8523 // namespace can be used in the scope in which the 8524 // using-directive appears after the using-directive. During 8525 // unqualified name lookup (3.4.1), the names appear as if they 8526 // were declared in the nearest enclosing namespace which 8527 // contains both the using-directive and the nominated 8528 // namespace. [Note: in this context, "contains" means "contains 8529 // directly or indirectly". ] 8530 8531 // Find enclosing context containing both using-directive and 8532 // nominated namespace. 8533 DeclContext *CommonAncestor = cast<DeclContext>(NS); 8534 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 8535 CommonAncestor = CommonAncestor->getParent(); 8536 8537 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 8538 SS.getWithLocInContext(Context), 8539 IdentLoc, Named, CommonAncestor); 8540 8541 if (IsUsingDirectiveInToplevelContext(CurContext) && 8542 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 8543 Diag(IdentLoc, diag::warn_using_directive_in_header); 8544 } 8545 8546 PushUsingDirective(S, UDir); 8547 } else { 8548 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8549 } 8550 8551 if (UDir) 8552 ProcessDeclAttributeList(S, UDir, AttrList); 8553 8554 return UDir; 8555 } 8556 8557 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 8558 // If the scope has an associated entity and the using directive is at 8559 // namespace or translation unit scope, add the UsingDirectiveDecl into 8560 // its lookup structure so qualified name lookup can find it. 8561 DeclContext *Ctx = S->getEntity(); 8562 if (Ctx && !Ctx->isFunctionOrMethod()) 8563 Ctx->addDecl(UDir); 8564 else 8565 // Otherwise, it is at block scope. The using-directives will affect lookup 8566 // only to the end of the scope. 8567 S->PushUsingDirective(UDir); 8568 } 8569 8570 8571 Decl *Sema::ActOnUsingDeclaration(Scope *S, 8572 AccessSpecifier AS, 8573 bool HasUsingKeyword, 8574 SourceLocation UsingLoc, 8575 CXXScopeSpec &SS, 8576 UnqualifiedId &Name, 8577 AttributeList *AttrList, 8578 bool HasTypenameKeyword, 8579 SourceLocation TypenameLoc) { 8580 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8581 8582 switch (Name.getKind()) { 8583 case UnqualifiedId::IK_ImplicitSelfParam: 8584 case UnqualifiedId::IK_Identifier: 8585 case UnqualifiedId::IK_OperatorFunctionId: 8586 case UnqualifiedId::IK_LiteralOperatorId: 8587 case UnqualifiedId::IK_ConversionFunctionId: 8588 break; 8589 8590 case UnqualifiedId::IK_ConstructorName: 8591 case UnqualifiedId::IK_ConstructorTemplateId: 8592 // C++11 inheriting constructors. 8593 Diag(Name.getLocStart(), 8594 getLangOpts().CPlusPlus11 ? 8595 diag::warn_cxx98_compat_using_decl_constructor : 8596 diag::err_using_decl_constructor) 8597 << SS.getRange(); 8598 8599 if (getLangOpts().CPlusPlus11) break; 8600 8601 return nullptr; 8602 8603 case UnqualifiedId::IK_DestructorName: 8604 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 8605 << SS.getRange(); 8606 return nullptr; 8607 8608 case UnqualifiedId::IK_TemplateId: 8609 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 8610 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 8611 return nullptr; 8612 } 8613 8614 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 8615 DeclarationName TargetName = TargetNameInfo.getName(); 8616 if (!TargetName) 8617 return nullptr; 8618 8619 // Warn about access declarations. 8620 if (!HasUsingKeyword) { 8621 Diag(Name.getLocStart(), 8622 getLangOpts().CPlusPlus11 ? diag::err_access_decl 8623 : diag::warn_access_decl_deprecated) 8624 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 8625 } 8626 8627 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 8628 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 8629 return nullptr; 8630 8631 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 8632 TargetNameInfo, AttrList, 8633 /* IsInstantiation */ false, 8634 HasTypenameKeyword, TypenameLoc); 8635 if (UD) 8636 PushOnScopeChains(UD, S, /*AddToContext*/ false); 8637 8638 return UD; 8639 } 8640 8641 /// \brief Determine whether a using declaration considers the given 8642 /// declarations as "equivalent", e.g., if they are redeclarations of 8643 /// the same entity or are both typedefs of the same type. 8644 static bool 8645 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 8646 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 8647 return true; 8648 8649 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 8650 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 8651 return Context.hasSameType(TD1->getUnderlyingType(), 8652 TD2->getUnderlyingType()); 8653 8654 return false; 8655 } 8656 8657 8658 /// Determines whether to create a using shadow decl for a particular 8659 /// decl, given the set of decls existing prior to this using lookup. 8660 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 8661 const LookupResult &Previous, 8662 UsingShadowDecl *&PrevShadow) { 8663 // Diagnose finding a decl which is not from a base class of the 8664 // current class. We do this now because there are cases where this 8665 // function will silently decide not to build a shadow decl, which 8666 // will pre-empt further diagnostics. 8667 // 8668 // We don't need to do this in C++11 because we do the check once on 8669 // the qualifier. 8670 // 8671 // FIXME: diagnose the following if we care enough: 8672 // struct A { int foo; }; 8673 // struct B : A { using A::foo; }; 8674 // template <class T> struct C : A {}; 8675 // template <class T> struct D : C<T> { using B::foo; } // <--- 8676 // This is invalid (during instantiation) in C++03 because B::foo 8677 // resolves to the using decl in B, which is not a base class of D<T>. 8678 // We can't diagnose it immediately because C<T> is an unknown 8679 // specialization. The UsingShadowDecl in D<T> then points directly 8680 // to A::foo, which will look well-formed when we instantiate. 8681 // The right solution is to not collapse the shadow-decl chain. 8682 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 8683 DeclContext *OrigDC = Orig->getDeclContext(); 8684 8685 // Handle enums and anonymous structs. 8686 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 8687 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 8688 while (OrigRec->isAnonymousStructOrUnion()) 8689 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 8690 8691 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 8692 if (OrigDC == CurContext) { 8693 Diag(Using->getLocation(), 8694 diag::err_using_decl_nested_name_specifier_is_current_class) 8695 << Using->getQualifierLoc().getSourceRange(); 8696 Diag(Orig->getLocation(), diag::note_using_decl_target); 8697 return true; 8698 } 8699 8700 Diag(Using->getQualifierLoc().getBeginLoc(), 8701 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8702 << Using->getQualifier() 8703 << cast<CXXRecordDecl>(CurContext) 8704 << Using->getQualifierLoc().getSourceRange(); 8705 Diag(Orig->getLocation(), diag::note_using_decl_target); 8706 return true; 8707 } 8708 } 8709 8710 if (Previous.empty()) return false; 8711 8712 NamedDecl *Target = Orig; 8713 if (isa<UsingShadowDecl>(Target)) 8714 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 8715 8716 // If the target happens to be one of the previous declarations, we 8717 // don't have a conflict. 8718 // 8719 // FIXME: but we might be increasing its access, in which case we 8720 // should redeclare it. 8721 NamedDecl *NonTag = nullptr, *Tag = nullptr; 8722 bool FoundEquivalentDecl = false; 8723 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8724 I != E; ++I) { 8725 NamedDecl *D = (*I)->getUnderlyingDecl(); 8726 // We can have UsingDecls in our Previous results because we use the same 8727 // LookupResult for checking whether the UsingDecl itself is a valid 8728 // redeclaration. 8729 if (isa<UsingDecl>(D)) 8730 continue; 8731 8732 if (IsEquivalentForUsingDecl(Context, D, Target)) { 8733 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 8734 PrevShadow = Shadow; 8735 FoundEquivalentDecl = true; 8736 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 8737 // We don't conflict with an existing using shadow decl of an equivalent 8738 // declaration, but we're not a redeclaration of it. 8739 FoundEquivalentDecl = true; 8740 } 8741 8742 if (isVisible(D)) 8743 (isa<TagDecl>(D) ? Tag : NonTag) = D; 8744 } 8745 8746 if (FoundEquivalentDecl) 8747 return false; 8748 8749 if (FunctionDecl *FD = Target->getAsFunction()) { 8750 NamedDecl *OldDecl = nullptr; 8751 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 8752 /*IsForUsingDecl*/ true)) { 8753 case Ovl_Overload: 8754 return false; 8755 8756 case Ovl_NonFunction: 8757 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8758 break; 8759 8760 // We found a decl with the exact signature. 8761 case Ovl_Match: 8762 // If we're in a record, we want to hide the target, so we 8763 // return true (without a diagnostic) to tell the caller not to 8764 // build a shadow decl. 8765 if (CurContext->isRecord()) 8766 return true; 8767 8768 // If we're not in a record, this is an error. 8769 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8770 break; 8771 } 8772 8773 Diag(Target->getLocation(), diag::note_using_decl_target); 8774 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 8775 return true; 8776 } 8777 8778 // Target is not a function. 8779 8780 if (isa<TagDecl>(Target)) { 8781 // No conflict between a tag and a non-tag. 8782 if (!Tag) return false; 8783 8784 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8785 Diag(Target->getLocation(), diag::note_using_decl_target); 8786 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 8787 return true; 8788 } 8789 8790 // No conflict between a tag and a non-tag. 8791 if (!NonTag) return false; 8792 8793 Diag(Using->getLocation(), diag::err_using_decl_conflict); 8794 Diag(Target->getLocation(), diag::note_using_decl_target); 8795 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 8796 return true; 8797 } 8798 8799 /// Determine whether a direct base class is a virtual base class. 8800 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 8801 if (!Derived->getNumVBases()) 8802 return false; 8803 for (auto &B : Derived->bases()) 8804 if (B.getType()->getAsCXXRecordDecl() == Base) 8805 return B.isVirtual(); 8806 llvm_unreachable("not a direct base class"); 8807 } 8808 8809 /// Builds a shadow declaration corresponding to a 'using' declaration. 8810 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 8811 UsingDecl *UD, 8812 NamedDecl *Orig, 8813 UsingShadowDecl *PrevDecl) { 8814 // If we resolved to another shadow declaration, just coalesce them. 8815 NamedDecl *Target = Orig; 8816 if (isa<UsingShadowDecl>(Target)) { 8817 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 8818 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 8819 } 8820 8821 NamedDecl *NonTemplateTarget = Target; 8822 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 8823 NonTemplateTarget = TargetTD->getTemplatedDecl(); 8824 8825 UsingShadowDecl *Shadow; 8826 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 8827 bool IsVirtualBase = 8828 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 8829 UD->getQualifier()->getAsRecordDecl()); 8830 Shadow = ConstructorUsingShadowDecl::Create( 8831 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 8832 } else { 8833 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 8834 Target); 8835 } 8836 UD->addShadowDecl(Shadow); 8837 8838 Shadow->setAccess(UD->getAccess()); 8839 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 8840 Shadow->setInvalidDecl(); 8841 8842 Shadow->setPreviousDecl(PrevDecl); 8843 8844 if (S) 8845 PushOnScopeChains(Shadow, S); 8846 else 8847 CurContext->addDecl(Shadow); 8848 8849 8850 return Shadow; 8851 } 8852 8853 /// Hides a using shadow declaration. This is required by the current 8854 /// using-decl implementation when a resolvable using declaration in a 8855 /// class is followed by a declaration which would hide or override 8856 /// one or more of the using decl's targets; for example: 8857 /// 8858 /// struct Base { void foo(int); }; 8859 /// struct Derived : Base { 8860 /// using Base::foo; 8861 /// void foo(int); 8862 /// }; 8863 /// 8864 /// The governing language is C++03 [namespace.udecl]p12: 8865 /// 8866 /// When a using-declaration brings names from a base class into a 8867 /// derived class scope, member functions in the derived class 8868 /// override and/or hide member functions with the same name and 8869 /// parameter types in a base class (rather than conflicting). 8870 /// 8871 /// There are two ways to implement this: 8872 /// (1) optimistically create shadow decls when they're not hidden 8873 /// by existing declarations, or 8874 /// (2) don't create any shadow decls (or at least don't make them 8875 /// visible) until we've fully parsed/instantiated the class. 8876 /// The problem with (1) is that we might have to retroactively remove 8877 /// a shadow decl, which requires several O(n) operations because the 8878 /// decl structures are (very reasonably) not designed for removal. 8879 /// (2) avoids this but is very fiddly and phase-dependent. 8880 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 8881 if (Shadow->getDeclName().getNameKind() == 8882 DeclarationName::CXXConversionFunctionName) 8883 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 8884 8885 // Remove it from the DeclContext... 8886 Shadow->getDeclContext()->removeDecl(Shadow); 8887 8888 // ...and the scope, if applicable... 8889 if (S) { 8890 S->RemoveDecl(Shadow); 8891 IdResolver.RemoveDecl(Shadow); 8892 } 8893 8894 // ...and the using decl. 8895 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 8896 8897 // TODO: complain somehow if Shadow was used. It shouldn't 8898 // be possible for this to happen, because...? 8899 } 8900 8901 /// Find the base specifier for a base class with the given type. 8902 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 8903 QualType DesiredBase, 8904 bool &AnyDependentBases) { 8905 // Check whether the named type is a direct base class. 8906 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 8907 for (auto &Base : Derived->bases()) { 8908 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 8909 if (CanonicalDesiredBase == BaseType) 8910 return &Base; 8911 if (BaseType->isDependentType()) 8912 AnyDependentBases = true; 8913 } 8914 return nullptr; 8915 } 8916 8917 namespace { 8918 class UsingValidatorCCC : public CorrectionCandidateCallback { 8919 public: 8920 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 8921 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 8922 : HasTypenameKeyword(HasTypenameKeyword), 8923 IsInstantiation(IsInstantiation), OldNNS(NNS), 8924 RequireMemberOf(RequireMemberOf) {} 8925 8926 bool ValidateCandidate(const TypoCorrection &Candidate) override { 8927 NamedDecl *ND = Candidate.getCorrectionDecl(); 8928 8929 // Keywords are not valid here. 8930 if (!ND || isa<NamespaceDecl>(ND)) 8931 return false; 8932 8933 // Completely unqualified names are invalid for a 'using' declaration. 8934 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 8935 return false; 8936 8937 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 8938 // reject. 8939 8940 if (RequireMemberOf) { 8941 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8942 if (FoundRecord && FoundRecord->isInjectedClassName()) { 8943 // No-one ever wants a using-declaration to name an injected-class-name 8944 // of a base class, unless they're declaring an inheriting constructor. 8945 ASTContext &Ctx = ND->getASTContext(); 8946 if (!Ctx.getLangOpts().CPlusPlus11) 8947 return false; 8948 QualType FoundType = Ctx.getRecordType(FoundRecord); 8949 8950 // Check that the injected-class-name is named as a member of its own 8951 // type; we don't want to suggest 'using Derived::Base;', since that 8952 // means something else. 8953 NestedNameSpecifier *Specifier = 8954 Candidate.WillReplaceSpecifier() 8955 ? Candidate.getCorrectionSpecifier() 8956 : OldNNS; 8957 if (!Specifier->getAsType() || 8958 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 8959 return false; 8960 8961 // Check that this inheriting constructor declaration actually names a 8962 // direct base class of the current class. 8963 bool AnyDependentBases = false; 8964 if (!findDirectBaseWithType(RequireMemberOf, 8965 Ctx.getRecordType(FoundRecord), 8966 AnyDependentBases) && 8967 !AnyDependentBases) 8968 return false; 8969 } else { 8970 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 8971 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 8972 return false; 8973 8974 // FIXME: Check that the base class member is accessible? 8975 } 8976 } else { 8977 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 8978 if (FoundRecord && FoundRecord->isInjectedClassName()) 8979 return false; 8980 } 8981 8982 if (isa<TypeDecl>(ND)) 8983 return HasTypenameKeyword || !IsInstantiation; 8984 8985 return !HasTypenameKeyword; 8986 } 8987 8988 private: 8989 bool HasTypenameKeyword; 8990 bool IsInstantiation; 8991 NestedNameSpecifier *OldNNS; 8992 CXXRecordDecl *RequireMemberOf; 8993 }; 8994 } // end anonymous namespace 8995 8996 /// Builds a using declaration. 8997 /// 8998 /// \param IsInstantiation - Whether this call arises from an 8999 /// instantiation of an unresolved using declaration. We treat 9000 /// the lookup differently for these declarations. 9001 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9002 SourceLocation UsingLoc, 9003 CXXScopeSpec &SS, 9004 DeclarationNameInfo NameInfo, 9005 AttributeList *AttrList, 9006 bool IsInstantiation, 9007 bool HasTypenameKeyword, 9008 SourceLocation TypenameLoc) { 9009 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9010 SourceLocation IdentLoc = NameInfo.getLoc(); 9011 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9012 9013 // FIXME: We ignore attributes for now. 9014 9015 if (SS.isEmpty()) { 9016 Diag(IdentLoc, diag::err_using_requires_qualname); 9017 return nullptr; 9018 } 9019 9020 // For an inheriting constructor declaration, the name of the using 9021 // declaration is the name of a constructor in this class, not in the 9022 // base class. 9023 DeclarationNameInfo UsingName = NameInfo; 9024 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9025 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9026 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9027 Context.getCanonicalType(Context.getRecordType(RD)))); 9028 9029 // Do the redeclaration lookup in the current scope. 9030 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9031 ForRedeclaration); 9032 Previous.setHideTags(false); 9033 if (S) { 9034 LookupName(Previous, S); 9035 9036 // It is really dumb that we have to do this. 9037 LookupResult::Filter F = Previous.makeFilter(); 9038 while (F.hasNext()) { 9039 NamedDecl *D = F.next(); 9040 if (!isDeclInScope(D, CurContext, S)) 9041 F.erase(); 9042 // If we found a local extern declaration that's not ordinarily visible, 9043 // and this declaration is being added to a non-block scope, ignore it. 9044 // We're only checking for scope conflicts here, not also for violations 9045 // of the linkage rules. 9046 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9047 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9048 F.erase(); 9049 } 9050 F.done(); 9051 } else { 9052 assert(IsInstantiation && "no scope in non-instantiation"); 9053 assert(CurContext->isRecord() && "scope not record in instantiation"); 9054 LookupQualifiedName(Previous, CurContext); 9055 } 9056 9057 // Check for invalid redeclarations. 9058 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9059 SS, IdentLoc, Previous)) 9060 return nullptr; 9061 9062 // Check for bad qualifiers. 9063 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 9064 return nullptr; 9065 9066 DeclContext *LookupContext = computeDeclContext(SS); 9067 NamedDecl *D; 9068 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9069 if (!LookupContext) { 9070 if (HasTypenameKeyword) { 9071 // FIXME: not all declaration name kinds are legal here 9072 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9073 UsingLoc, TypenameLoc, 9074 QualifierLoc, 9075 IdentLoc, NameInfo.getName()); 9076 } else { 9077 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9078 QualifierLoc, NameInfo); 9079 } 9080 D->setAccess(AS); 9081 CurContext->addDecl(D); 9082 return D; 9083 } 9084 9085 auto Build = [&](bool Invalid) { 9086 UsingDecl *UD = 9087 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9088 UsingName, HasTypenameKeyword); 9089 UD->setAccess(AS); 9090 CurContext->addDecl(UD); 9091 UD->setInvalidDecl(Invalid); 9092 return UD; 9093 }; 9094 auto BuildInvalid = [&]{ return Build(true); }; 9095 auto BuildValid = [&]{ return Build(false); }; 9096 9097 if (RequireCompleteDeclContext(SS, LookupContext)) 9098 return BuildInvalid(); 9099 9100 // Look up the target name. 9101 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9102 9103 // Unlike most lookups, we don't always want to hide tag 9104 // declarations: tag names are visible through the using declaration 9105 // even if hidden by ordinary names, *except* in a dependent context 9106 // where it's important for the sanity of two-phase lookup. 9107 if (!IsInstantiation) 9108 R.setHideTags(false); 9109 9110 // For the purposes of this lookup, we have a base object type 9111 // equal to that of the current context. 9112 if (CurContext->isRecord()) { 9113 R.setBaseObjectType( 9114 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9115 } 9116 9117 LookupQualifiedName(R, LookupContext); 9118 9119 // Try to correct typos if possible. If constructor name lookup finds no 9120 // results, that means the named class has no explicit constructors, and we 9121 // suppressed declaring implicit ones (probably because it's dependent or 9122 // invalid). 9123 if (R.empty() && 9124 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9125 if (TypoCorrection Corrected = CorrectTypo( 9126 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9127 llvm::make_unique<UsingValidatorCCC>( 9128 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9129 dyn_cast<CXXRecordDecl>(CurContext)), 9130 CTK_ErrorRecovery)) { 9131 // We reject any correction for which ND would be NULL. 9132 NamedDecl *ND = Corrected.getCorrectionDecl(); 9133 9134 // We reject candidates where DroppedSpecifier == true, hence the 9135 // literal '0' below. 9136 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9137 << NameInfo.getName() << LookupContext << 0 9138 << SS.getRange()); 9139 9140 // If we corrected to an inheriting constructor, handle it as one. 9141 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9142 if (RD && RD->isInjectedClassName()) { 9143 // The parent of the injected class name is the class itself. 9144 RD = cast<CXXRecordDecl>(RD->getParent()); 9145 9146 // Fix up the information we'll use to build the using declaration. 9147 if (Corrected.WillReplaceSpecifier()) { 9148 NestedNameSpecifierLocBuilder Builder; 9149 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9150 QualifierLoc.getSourceRange()); 9151 QualifierLoc = Builder.getWithLocInContext(Context); 9152 } 9153 9154 // In this case, the name we introduce is the name of a derived class 9155 // constructor. 9156 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9157 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9158 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9159 UsingName.setNamedTypeInfo(nullptr); 9160 for (auto *Ctor : LookupConstructors(RD)) 9161 R.addDecl(Ctor); 9162 R.resolveKind(); 9163 } else { 9164 // FIXME: Pick up all the declarations if we found an overloaded 9165 // function. 9166 UsingName.setName(ND->getDeclName()); 9167 R.addDecl(ND); 9168 } 9169 } else { 9170 Diag(IdentLoc, diag::err_no_member) 9171 << NameInfo.getName() << LookupContext << SS.getRange(); 9172 return BuildInvalid(); 9173 } 9174 } 9175 9176 if (R.isAmbiguous()) 9177 return BuildInvalid(); 9178 9179 if (HasTypenameKeyword) { 9180 // If we asked for a typename and got a non-type decl, error out. 9181 if (!R.getAsSingle<TypeDecl>()) { 9182 Diag(IdentLoc, diag::err_using_typename_non_type); 9183 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9184 Diag((*I)->getUnderlyingDecl()->getLocation(), 9185 diag::note_using_decl_target); 9186 return BuildInvalid(); 9187 } 9188 } else { 9189 // If we asked for a non-typename and we got a type, error out, 9190 // but only if this is an instantiation of an unresolved using 9191 // decl. Otherwise just silently find the type name. 9192 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9193 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9194 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9195 return BuildInvalid(); 9196 } 9197 } 9198 9199 // C++14 [namespace.udecl]p6: 9200 // A using-declaration shall not name a namespace. 9201 if (R.getAsSingle<NamespaceDecl>()) { 9202 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9203 << SS.getRange(); 9204 return BuildInvalid(); 9205 } 9206 9207 // C++14 [namespace.udecl]p7: 9208 // A using-declaration shall not name a scoped enumerator. 9209 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9210 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9211 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9212 << SS.getRange(); 9213 return BuildInvalid(); 9214 } 9215 } 9216 9217 UsingDecl *UD = BuildValid(); 9218 9219 // Some additional rules apply to inheriting constructors. 9220 if (UsingName.getName().getNameKind() == 9221 DeclarationName::CXXConstructorName) { 9222 // Suppress access diagnostics; the access check is instead performed at the 9223 // point of use for an inheriting constructor. 9224 R.suppressDiagnostics(); 9225 if (CheckInheritingConstructorUsingDecl(UD)) 9226 return UD; 9227 } 9228 9229 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9230 UsingShadowDecl *PrevDecl = nullptr; 9231 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9232 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9233 } 9234 9235 return UD; 9236 } 9237 9238 /// Additional checks for a using declaration referring to a constructor name. 9239 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9240 assert(!UD->hasTypename() && "expecting a constructor name"); 9241 9242 const Type *SourceType = UD->getQualifier()->getAsType(); 9243 assert(SourceType && 9244 "Using decl naming constructor doesn't have type in scope spec."); 9245 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9246 9247 // Check whether the named type is a direct base class. 9248 bool AnyDependentBases = false; 9249 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9250 AnyDependentBases); 9251 if (!Base && !AnyDependentBases) { 9252 Diag(UD->getUsingLoc(), 9253 diag::err_using_decl_constructor_not_in_direct_base) 9254 << UD->getNameInfo().getSourceRange() 9255 << QualType(SourceType, 0) << TargetClass; 9256 UD->setInvalidDecl(); 9257 return true; 9258 } 9259 9260 if (Base) 9261 Base->setInheritConstructors(); 9262 9263 return false; 9264 } 9265 9266 /// Checks that the given using declaration is not an invalid 9267 /// redeclaration. Note that this is checking only for the using decl 9268 /// itself, not for any ill-formedness among the UsingShadowDecls. 9269 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9270 bool HasTypenameKeyword, 9271 const CXXScopeSpec &SS, 9272 SourceLocation NameLoc, 9273 const LookupResult &Prev) { 9274 // C++03 [namespace.udecl]p8: 9275 // C++0x [namespace.udecl]p10: 9276 // A using-declaration is a declaration and can therefore be used 9277 // repeatedly where (and only where) multiple declarations are 9278 // allowed. 9279 // 9280 // That's in non-member contexts. 9281 if (!CurContext->getRedeclContext()->isRecord()) 9282 return false; 9283 9284 NestedNameSpecifier *Qual = SS.getScopeRep(); 9285 9286 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9287 NamedDecl *D = *I; 9288 9289 bool DTypename; 9290 NestedNameSpecifier *DQual; 9291 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9292 DTypename = UD->hasTypename(); 9293 DQual = UD->getQualifier(); 9294 } else if (UnresolvedUsingValueDecl *UD 9295 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9296 DTypename = false; 9297 DQual = UD->getQualifier(); 9298 } else if (UnresolvedUsingTypenameDecl *UD 9299 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9300 DTypename = true; 9301 DQual = UD->getQualifier(); 9302 } else continue; 9303 9304 // using decls differ if one says 'typename' and the other doesn't. 9305 // FIXME: non-dependent using decls? 9306 if (HasTypenameKeyword != DTypename) continue; 9307 9308 // using decls differ if they name different scopes (but note that 9309 // template instantiation can cause this check to trigger when it 9310 // didn't before instantiation). 9311 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9312 Context.getCanonicalNestedNameSpecifier(DQual)) 9313 continue; 9314 9315 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9316 Diag(D->getLocation(), diag::note_using_decl) << 1; 9317 return true; 9318 } 9319 9320 return false; 9321 } 9322 9323 9324 /// Checks that the given nested-name qualifier used in a using decl 9325 /// in the current context is appropriately related to the current 9326 /// scope. If an error is found, diagnoses it and returns true. 9327 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9328 const CXXScopeSpec &SS, 9329 const DeclarationNameInfo &NameInfo, 9330 SourceLocation NameLoc) { 9331 DeclContext *NamedContext = computeDeclContext(SS); 9332 9333 if (!CurContext->isRecord()) { 9334 // C++03 [namespace.udecl]p3: 9335 // C++0x [namespace.udecl]p8: 9336 // A using-declaration for a class member shall be a member-declaration. 9337 9338 // If we weren't able to compute a valid scope, it must be a 9339 // dependent class scope. 9340 if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) { 9341 auto *RD = NamedContext 9342 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9343 : nullptr; 9344 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9345 RD = nullptr; 9346 9347 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9348 << SS.getRange(); 9349 9350 // If we have a complete, non-dependent source type, try to suggest a 9351 // way to get the same effect. 9352 if (!RD) 9353 return true; 9354 9355 // Find what this using-declaration was referring to. 9356 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9357 R.setHideTags(false); 9358 R.suppressDiagnostics(); 9359 LookupQualifiedName(R, RD); 9360 9361 if (R.getAsSingle<TypeDecl>()) { 9362 if (getLangOpts().CPlusPlus11) { 9363 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9364 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9365 << 0 // alias declaration 9366 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9367 NameInfo.getName().getAsString() + 9368 " = "); 9369 } else { 9370 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9371 SourceLocation InsertLoc = 9372 getLocForEndOfToken(NameInfo.getLocEnd()); 9373 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9374 << 1 // typedef declaration 9375 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9376 << FixItHint::CreateInsertion( 9377 InsertLoc, " " + NameInfo.getName().getAsString()); 9378 } 9379 } else if (R.getAsSingle<VarDecl>()) { 9380 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9381 // repeating the type of the static data member here. 9382 FixItHint FixIt; 9383 if (getLangOpts().CPlusPlus11) { 9384 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9385 FixIt = FixItHint::CreateReplacement( 9386 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9387 } 9388 9389 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9390 << 2 // reference declaration 9391 << FixIt; 9392 } else if (R.getAsSingle<EnumConstantDecl>()) { 9393 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9394 // repeating the type of the enumeration here, and we can't do so if 9395 // the type is anonymous. 9396 FixItHint FixIt; 9397 if (getLangOpts().CPlusPlus11) { 9398 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9399 FixIt = FixItHint::CreateReplacement( 9400 UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = "); 9401 } 9402 9403 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9404 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 9405 << FixIt; 9406 } 9407 return true; 9408 } 9409 9410 // Otherwise, everything is known to be fine. 9411 return false; 9412 } 9413 9414 // The current scope is a record. 9415 9416 // If the named context is dependent, we can't decide much. 9417 if (!NamedContext) { 9418 // FIXME: in C++0x, we can diagnose if we can prove that the 9419 // nested-name-specifier does not refer to a base class, which is 9420 // still possible in some cases. 9421 9422 // Otherwise we have to conservatively report that things might be 9423 // okay. 9424 return false; 9425 } 9426 9427 if (!NamedContext->isRecord()) { 9428 // Ideally this would point at the last name in the specifier, 9429 // but we don't have that level of source info. 9430 Diag(SS.getRange().getBegin(), 9431 diag::err_using_decl_nested_name_specifier_is_not_class) 9432 << SS.getScopeRep() << SS.getRange(); 9433 return true; 9434 } 9435 9436 if (!NamedContext->isDependentContext() && 9437 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 9438 return true; 9439 9440 if (getLangOpts().CPlusPlus11) { 9441 // C++11 [namespace.udecl]p3: 9442 // In a using-declaration used as a member-declaration, the 9443 // nested-name-specifier shall name a base class of the class 9444 // being defined. 9445 9446 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 9447 cast<CXXRecordDecl>(NamedContext))) { 9448 if (CurContext == NamedContext) { 9449 Diag(NameLoc, 9450 diag::err_using_decl_nested_name_specifier_is_current_class) 9451 << SS.getRange(); 9452 return true; 9453 } 9454 9455 Diag(SS.getRange().getBegin(), 9456 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9457 << SS.getScopeRep() 9458 << cast<CXXRecordDecl>(CurContext) 9459 << SS.getRange(); 9460 return true; 9461 } 9462 9463 return false; 9464 } 9465 9466 // C++03 [namespace.udecl]p4: 9467 // A using-declaration used as a member-declaration shall refer 9468 // to a member of a base class of the class being defined [etc.]. 9469 9470 // Salient point: SS doesn't have to name a base class as long as 9471 // lookup only finds members from base classes. Therefore we can 9472 // diagnose here only if we can prove that that can't happen, 9473 // i.e. if the class hierarchies provably don't intersect. 9474 9475 // TODO: it would be nice if "definitely valid" results were cached 9476 // in the UsingDecl and UsingShadowDecl so that these checks didn't 9477 // need to be repeated. 9478 9479 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 9480 auto Collect = [&Bases](const CXXRecordDecl *Base) { 9481 Bases.insert(Base); 9482 return true; 9483 }; 9484 9485 // Collect all bases. Return false if we find a dependent base. 9486 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 9487 return false; 9488 9489 // Returns true if the base is dependent or is one of the accumulated base 9490 // classes. 9491 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 9492 return !Bases.count(Base); 9493 }; 9494 9495 // Return false if the class has a dependent base or if it or one 9496 // of its bases is present in the base set of the current context. 9497 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 9498 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 9499 return false; 9500 9501 Diag(SS.getRange().getBegin(), 9502 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9503 << SS.getScopeRep() 9504 << cast<CXXRecordDecl>(CurContext) 9505 << SS.getRange(); 9506 9507 return true; 9508 } 9509 9510 Decl *Sema::ActOnAliasDeclaration(Scope *S, 9511 AccessSpecifier AS, 9512 MultiTemplateParamsArg TemplateParamLists, 9513 SourceLocation UsingLoc, 9514 UnqualifiedId &Name, 9515 AttributeList *AttrList, 9516 TypeResult Type, 9517 Decl *DeclFromDeclSpec) { 9518 // Skip up to the relevant declaration scope. 9519 while (S->isTemplateParamScope()) 9520 S = S->getParent(); 9521 assert((S->getFlags() & Scope::DeclScope) && 9522 "got alias-declaration outside of declaration scope"); 9523 9524 if (Type.isInvalid()) 9525 return nullptr; 9526 9527 bool Invalid = false; 9528 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 9529 TypeSourceInfo *TInfo = nullptr; 9530 GetTypeFromParser(Type.get(), &TInfo); 9531 9532 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 9533 return nullptr; 9534 9535 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 9536 UPPC_DeclarationType)) { 9537 Invalid = true; 9538 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9539 TInfo->getTypeLoc().getBeginLoc()); 9540 } 9541 9542 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 9543 LookupName(Previous, S); 9544 9545 // Warn about shadowing the name of a template parameter. 9546 if (Previous.isSingleResult() && 9547 Previous.getFoundDecl()->isTemplateParameter()) { 9548 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 9549 Previous.clear(); 9550 } 9551 9552 assert(Name.Kind == UnqualifiedId::IK_Identifier && 9553 "name in alias declaration must be an identifier"); 9554 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 9555 Name.StartLocation, 9556 Name.Identifier, TInfo); 9557 9558 NewTD->setAccess(AS); 9559 9560 if (Invalid) 9561 NewTD->setInvalidDecl(); 9562 9563 ProcessDeclAttributeList(S, NewTD, AttrList); 9564 9565 CheckTypedefForVariablyModifiedType(S, NewTD); 9566 Invalid |= NewTD->isInvalidDecl(); 9567 9568 bool Redeclaration = false; 9569 9570 NamedDecl *NewND; 9571 if (TemplateParamLists.size()) { 9572 TypeAliasTemplateDecl *OldDecl = nullptr; 9573 TemplateParameterList *OldTemplateParams = nullptr; 9574 9575 if (TemplateParamLists.size() != 1) { 9576 Diag(UsingLoc, diag::err_alias_template_extra_headers) 9577 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 9578 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 9579 } 9580 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 9581 9582 // Check that we can declare a template here. 9583 if (CheckTemplateDeclScope(S, TemplateParams)) 9584 return nullptr; 9585 9586 // Only consider previous declarations in the same scope. 9587 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 9588 /*ExplicitInstantiationOrSpecialization*/false); 9589 if (!Previous.empty()) { 9590 Redeclaration = true; 9591 9592 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 9593 if (!OldDecl && !Invalid) { 9594 Diag(UsingLoc, diag::err_redefinition_different_kind) 9595 << Name.Identifier; 9596 9597 NamedDecl *OldD = Previous.getRepresentativeDecl(); 9598 if (OldD->getLocation().isValid()) 9599 Diag(OldD->getLocation(), diag::note_previous_definition); 9600 9601 Invalid = true; 9602 } 9603 9604 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 9605 if (TemplateParameterListsAreEqual(TemplateParams, 9606 OldDecl->getTemplateParameters(), 9607 /*Complain=*/true, 9608 TPL_TemplateMatch)) 9609 OldTemplateParams = OldDecl->getTemplateParameters(); 9610 else 9611 Invalid = true; 9612 9613 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 9614 if (!Invalid && 9615 !Context.hasSameType(OldTD->getUnderlyingType(), 9616 NewTD->getUnderlyingType())) { 9617 // FIXME: The C++0x standard does not clearly say this is ill-formed, 9618 // but we can't reasonably accept it. 9619 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 9620 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 9621 if (OldTD->getLocation().isValid()) 9622 Diag(OldTD->getLocation(), diag::note_previous_definition); 9623 Invalid = true; 9624 } 9625 } 9626 } 9627 9628 // Merge any previous default template arguments into our parameters, 9629 // and check the parameter list. 9630 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 9631 TPC_TypeAliasTemplate)) 9632 return nullptr; 9633 9634 TypeAliasTemplateDecl *NewDecl = 9635 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 9636 Name.Identifier, TemplateParams, 9637 NewTD); 9638 NewTD->setDescribedAliasTemplate(NewDecl); 9639 9640 NewDecl->setAccess(AS); 9641 9642 if (Invalid) 9643 NewDecl->setInvalidDecl(); 9644 else if (OldDecl) 9645 NewDecl->setPreviousDecl(OldDecl); 9646 9647 NewND = NewDecl; 9648 } else { 9649 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 9650 setTagNameForLinkagePurposes(TD, NewTD); 9651 handleTagNumbering(TD, S); 9652 } 9653 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 9654 NewND = NewTD; 9655 } 9656 9657 PushOnScopeChains(NewND, S); 9658 ActOnDocumentableDecl(NewND); 9659 return NewND; 9660 } 9661 9662 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 9663 SourceLocation AliasLoc, 9664 IdentifierInfo *Alias, CXXScopeSpec &SS, 9665 SourceLocation IdentLoc, 9666 IdentifierInfo *Ident) { 9667 9668 // Lookup the namespace name. 9669 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 9670 LookupParsedName(R, S, &SS); 9671 9672 if (R.isAmbiguous()) 9673 return nullptr; 9674 9675 if (R.empty()) { 9676 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 9677 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9678 return nullptr; 9679 } 9680 } 9681 assert(!R.isAmbiguous() && !R.empty()); 9682 NamedDecl *ND = R.getRepresentativeDecl(); 9683 9684 // Check if we have a previous declaration with the same name. 9685 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 9686 ForRedeclaration); 9687 LookupName(PrevR, S); 9688 9689 // Check we're not shadowing a template parameter. 9690 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 9691 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 9692 PrevR.clear(); 9693 } 9694 9695 // Filter out any other lookup result from an enclosing scope. 9696 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 9697 /*AllowInlineNamespace*/false); 9698 9699 // Find the previous declaration and check that we can redeclare it. 9700 NamespaceAliasDecl *Prev = nullptr; 9701 if (PrevR.isSingleResult()) { 9702 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 9703 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 9704 // We already have an alias with the same name that points to the same 9705 // namespace; check that it matches. 9706 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 9707 Prev = AD; 9708 } else if (isVisible(PrevDecl)) { 9709 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 9710 << Alias; 9711 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 9712 << AD->getNamespace(); 9713 return nullptr; 9714 } 9715 } else if (isVisible(PrevDecl)) { 9716 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 9717 ? diag::err_redefinition 9718 : diag::err_redefinition_different_kind; 9719 Diag(AliasLoc, DiagID) << Alias; 9720 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9721 return nullptr; 9722 } 9723 } 9724 9725 // The use of a nested name specifier may trigger deprecation warnings. 9726 DiagnoseUseOfDecl(ND, IdentLoc); 9727 9728 NamespaceAliasDecl *AliasDecl = 9729 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 9730 Alias, SS.getWithLocInContext(Context), 9731 IdentLoc, ND); 9732 if (Prev) 9733 AliasDecl->setPreviousDecl(Prev); 9734 9735 PushOnScopeChains(AliasDecl, S); 9736 return AliasDecl; 9737 } 9738 9739 Sema::ImplicitExceptionSpecification 9740 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 9741 CXXMethodDecl *MD) { 9742 CXXRecordDecl *ClassDecl = MD->getParent(); 9743 9744 // C++ [except.spec]p14: 9745 // An implicitly declared special member function (Clause 12) shall have an 9746 // exception-specification. [...] 9747 ImplicitExceptionSpecification ExceptSpec(*this); 9748 if (ClassDecl->isInvalidDecl()) 9749 return ExceptSpec; 9750 9751 // Direct base-class constructors. 9752 for (const auto &B : ClassDecl->bases()) { 9753 if (B.isVirtual()) // Handled below. 9754 continue; 9755 9756 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 9757 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9758 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 9759 // If this is a deleted function, add it anyway. This might be conformant 9760 // with the standard. This might not. I'm not sure. It might not matter. 9761 if (Constructor) 9762 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 9763 } 9764 } 9765 9766 // Virtual base-class constructors. 9767 for (const auto &B : ClassDecl->vbases()) { 9768 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 9769 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9770 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 9771 // If this is a deleted function, add it anyway. This might be conformant 9772 // with the standard. This might not. I'm not sure. It might not matter. 9773 if (Constructor) 9774 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 9775 } 9776 } 9777 9778 // Field constructors. 9779 for (const auto *F : ClassDecl->fields()) { 9780 if (F->hasInClassInitializer()) { 9781 if (Expr *E = F->getInClassInitializer()) 9782 ExceptSpec.CalledExpr(E); 9783 } else if (const RecordType *RecordTy 9784 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 9785 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9786 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 9787 // If this is a deleted function, add it anyway. This might be conformant 9788 // with the standard. This might not. I'm not sure. It might not matter. 9789 // In particular, the problem is that this function never gets called. It 9790 // might just be ill-formed because this function attempts to refer to 9791 // a deleted function here. 9792 if (Constructor) 9793 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9794 } 9795 } 9796 9797 return ExceptSpec; 9798 } 9799 9800 Sema::ImplicitExceptionSpecification 9801 Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc, 9802 CXXConstructorDecl *CD) { 9803 CXXRecordDecl *ClassDecl = CD->getParent(); 9804 9805 // C++ [except.spec]p14: 9806 // An inheriting constructor [...] shall have an exception-specification. [...] 9807 ImplicitExceptionSpecification ExceptSpec(*this); 9808 if (ClassDecl->isInvalidDecl()) 9809 return ExceptSpec; 9810 9811 auto Inherited = CD->getInheritedConstructor(); 9812 InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl()); 9813 9814 // Direct and virtual base-class constructors. 9815 for (bool VBase : {false, true}) { 9816 for (CXXBaseSpecifier &B : 9817 VBase ? ClassDecl->vbases() : ClassDecl->bases()) { 9818 // Don't visit direct vbases twice. 9819 if (B.isVirtual() != VBase) 9820 continue; 9821 9822 CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl(); 9823 if (!BaseClass) 9824 continue; 9825 9826 CXXConstructorDecl *Constructor = 9827 ICI.findConstructorForBase(BaseClass, Inherited.getConstructor()) 9828 .first; 9829 if (!Constructor) 9830 Constructor = LookupDefaultConstructor(BaseClass); 9831 if (Constructor) 9832 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 9833 } 9834 } 9835 9836 // Field constructors. 9837 for (const auto *F : ClassDecl->fields()) { 9838 if (F->hasInClassInitializer()) { 9839 if (Expr *E = F->getInClassInitializer()) 9840 ExceptSpec.CalledExpr(E); 9841 } else if (const RecordType *RecordTy 9842 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 9843 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9844 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 9845 if (Constructor) 9846 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9847 } 9848 } 9849 9850 return ExceptSpec; 9851 } 9852 9853 namespace { 9854 /// RAII object to register a special member as being currently declared. 9855 struct DeclaringSpecialMember { 9856 Sema &S; 9857 Sema::SpecialMemberDecl D; 9858 Sema::ContextRAII SavedContext; 9859 bool WasAlreadyBeingDeclared; 9860 9861 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 9862 : S(S), D(RD, CSM), SavedContext(S, RD) { 9863 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 9864 if (WasAlreadyBeingDeclared) 9865 // This almost never happens, but if it does, ensure that our cache 9866 // doesn't contain a stale result. 9867 S.SpecialMemberCache.clear(); 9868 9869 // FIXME: Register a note to be produced if we encounter an error while 9870 // declaring the special member. 9871 } 9872 ~DeclaringSpecialMember() { 9873 if (!WasAlreadyBeingDeclared) 9874 S.SpecialMembersBeingDeclared.erase(D); 9875 } 9876 9877 /// \brief Are we already trying to declare this special member? 9878 bool isAlreadyBeingDeclared() const { 9879 return WasAlreadyBeingDeclared; 9880 } 9881 }; 9882 } 9883 9884 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 9885 // Look up any existing declarations, but don't trigger declaration of all 9886 // implicit special members with this name. 9887 DeclarationName Name = FD->getDeclName(); 9888 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 9889 ForRedeclaration); 9890 for (auto *D : FD->getParent()->lookup(Name)) 9891 if (auto *Acceptable = R.getAcceptableDecl(D)) 9892 R.addDecl(Acceptable); 9893 R.resolveKind(); 9894 R.suppressDiagnostics(); 9895 9896 CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false); 9897 } 9898 9899 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 9900 CXXRecordDecl *ClassDecl) { 9901 // C++ [class.ctor]p5: 9902 // A default constructor for a class X is a constructor of class X 9903 // that can be called without an argument. If there is no 9904 // user-declared constructor for class X, a default constructor is 9905 // implicitly declared. An implicitly-declared default constructor 9906 // is an inline public member of its class. 9907 assert(ClassDecl->needsImplicitDefaultConstructor() && 9908 "Should not build implicit default constructor!"); 9909 9910 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 9911 if (DSM.isAlreadyBeingDeclared()) 9912 return nullptr; 9913 9914 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9915 CXXDefaultConstructor, 9916 false); 9917 9918 // Create the actual constructor declaration. 9919 CanQualType ClassType 9920 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9921 SourceLocation ClassLoc = ClassDecl->getLocation(); 9922 DeclarationName Name 9923 = Context.DeclarationNames.getCXXConstructorName(ClassType); 9924 DeclarationNameInfo NameInfo(Name, ClassLoc); 9925 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 9926 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 9927 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 9928 /*isImplicitlyDeclared=*/true, Constexpr); 9929 DefaultCon->setAccess(AS_public); 9930 DefaultCon->setDefaulted(); 9931 9932 if (getLangOpts().CUDA) { 9933 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 9934 DefaultCon, 9935 /* ConstRHS */ false, 9936 /* Diagnose */ false); 9937 } 9938 9939 // Build an exception specification pointing back at this constructor. 9940 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 9941 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9942 9943 // We don't need to use SpecialMemberIsTrivial here; triviality for default 9944 // constructors is easy to compute. 9945 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 9946 9947 // Note that we have declared this constructor. 9948 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 9949 9950 Scope *S = getScopeForContext(ClassDecl); 9951 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 9952 9953 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 9954 SetDeclDeleted(DefaultCon, ClassLoc); 9955 9956 if (S) 9957 PushOnScopeChains(DefaultCon, S, false); 9958 ClassDecl->addDecl(DefaultCon); 9959 9960 return DefaultCon; 9961 } 9962 9963 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 9964 CXXConstructorDecl *Constructor) { 9965 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 9966 !Constructor->doesThisDeclarationHaveABody() && 9967 !Constructor->isDeleted()) && 9968 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 9969 9970 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9971 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 9972 9973 SynthesizedFunctionScope Scope(*this, Constructor); 9974 DiagnosticErrorTrap Trap(Diags); 9975 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9976 Trap.hasErrorOccurred()) { 9977 Diag(CurrentLocation, diag::note_member_synthesized_at) 9978 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 9979 Constructor->setInvalidDecl(); 9980 return; 9981 } 9982 9983 // The exception specification is needed because we are defining the 9984 // function. 9985 ResolveExceptionSpec(CurrentLocation, 9986 Constructor->getType()->castAs<FunctionProtoType>()); 9987 9988 SourceLocation Loc = Constructor->getLocEnd().isValid() 9989 ? Constructor->getLocEnd() 9990 : Constructor->getLocation(); 9991 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9992 9993 Constructor->markUsed(Context); 9994 MarkVTableUsed(CurrentLocation, ClassDecl); 9995 9996 if (ASTMutationListener *L = getASTMutationListener()) { 9997 L->CompletedImplicitDefinition(Constructor); 9998 } 9999 10000 DiagnoseUninitializedFields(*this, Constructor); 10001 } 10002 10003 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10004 // Perform any delayed checks on exception specifications. 10005 CheckDelayedMemberExceptionSpecs(); 10006 } 10007 10008 /// Find or create the fake constructor we synthesize to model constructing an 10009 /// object of a derived class via a constructor of a base class. 10010 CXXConstructorDecl * 10011 Sema::findInheritingConstructor(SourceLocation Loc, 10012 CXXConstructorDecl *BaseCtor, 10013 ConstructorUsingShadowDecl *Shadow) { 10014 CXXRecordDecl *Derived = Shadow->getParent(); 10015 SourceLocation UsingLoc = Shadow->getLocation(); 10016 10017 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10018 // For now we use the name of the base class constructor as a member of the 10019 // derived class to indicate a (fake) inherited constructor name. 10020 DeclarationName Name = BaseCtor->getDeclName(); 10021 10022 // Check to see if we already have a fake constructor for this inherited 10023 // constructor call. 10024 for (NamedDecl *Ctor : Derived->lookup(Name)) 10025 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10026 ->getInheritedConstructor() 10027 .getConstructor(), 10028 BaseCtor)) 10029 return cast<CXXConstructorDecl>(Ctor); 10030 10031 DeclarationNameInfo NameInfo(Name, UsingLoc); 10032 TypeSourceInfo *TInfo = 10033 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10034 FunctionProtoTypeLoc ProtoLoc = 10035 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10036 10037 // Check the inherited constructor is valid and find the list of base classes 10038 // from which it was inherited. 10039 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10040 10041 bool Constexpr = 10042 BaseCtor->isConstexpr() && 10043 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10044 false, BaseCtor, &ICI); 10045 10046 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10047 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10048 BaseCtor->isExplicit(), /*Inline=*/true, 10049 /*ImplicitlyDeclared=*/true, Constexpr, 10050 InheritedConstructor(Shadow, BaseCtor)); 10051 if (Shadow->isInvalidDecl()) 10052 DerivedCtor->setInvalidDecl(); 10053 10054 // Build an unevaluated exception specification for this fake constructor. 10055 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10056 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10057 EPI.ExceptionSpec.Type = EST_Unevaluated; 10058 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10059 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10060 FPT->getParamTypes(), EPI)); 10061 10062 // Build the parameter declarations. 10063 SmallVector<ParmVarDecl *, 16> ParamDecls; 10064 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10065 TypeSourceInfo *TInfo = 10066 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10067 ParmVarDecl *PD = ParmVarDecl::Create( 10068 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10069 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10070 PD->setScopeInfo(0, I); 10071 PD->setImplicit(); 10072 // Ensure attributes are propagated onto parameters (this matters for 10073 // format, pass_object_size, ...). 10074 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10075 ParamDecls.push_back(PD); 10076 ProtoLoc.setParam(I, PD); 10077 } 10078 10079 // Set up the new constructor. 10080 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10081 DerivedCtor->setAccess(BaseCtor->getAccess()); 10082 DerivedCtor->setParams(ParamDecls); 10083 Derived->addDecl(DerivedCtor); 10084 10085 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10086 SetDeclDeleted(DerivedCtor, UsingLoc); 10087 10088 return DerivedCtor; 10089 } 10090 10091 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10092 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10093 Ctor->getInheritedConstructor().getShadowDecl()); 10094 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10095 /*Diagnose*/true); 10096 } 10097 10098 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10099 CXXConstructorDecl *Constructor) { 10100 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10101 assert(Constructor->getInheritedConstructor() && 10102 !Constructor->doesThisDeclarationHaveABody() && 10103 !Constructor->isDeleted()); 10104 if (Constructor->isInvalidDecl()) 10105 return; 10106 10107 ConstructorUsingShadowDecl *Shadow = 10108 Constructor->getInheritedConstructor().getShadowDecl(); 10109 CXXConstructorDecl *InheritedCtor = 10110 Constructor->getInheritedConstructor().getConstructor(); 10111 10112 // [class.inhctor.init]p1: 10113 // initialization proceeds as if a defaulted default constructor is used to 10114 // initialize the D object and each base class subobject from which the 10115 // constructor was inherited 10116 10117 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10118 CXXRecordDecl *RD = Shadow->getParent(); 10119 SourceLocation InitLoc = Shadow->getLocation(); 10120 10121 // Initializations are performed "as if by a defaulted default constructor", 10122 // so enter the appropriate scope. 10123 SynthesizedFunctionScope Scope(*this, Constructor); 10124 DiagnosticErrorTrap Trap(Diags); 10125 10126 // Build explicit initializers for all base classes from which the 10127 // constructor was inherited. 10128 SmallVector<CXXCtorInitializer*, 8> Inits; 10129 for (bool VBase : {false, true}) { 10130 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10131 if (B.isVirtual() != VBase) 10132 continue; 10133 10134 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10135 if (!BaseRD) 10136 continue; 10137 10138 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10139 if (!BaseCtor.first) 10140 continue; 10141 10142 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10143 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10144 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10145 10146 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10147 Inits.push_back(new (Context) CXXCtorInitializer( 10148 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10149 SourceLocation())); 10150 } 10151 } 10152 10153 // We now proceed as if for a defaulted default constructor, with the relevant 10154 // initializers replaced. 10155 10156 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits); 10157 if (HadError || Trap.hasErrorOccurred()) { 10158 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD; 10159 Constructor->setInvalidDecl(); 10160 return; 10161 } 10162 10163 // The exception specification is needed because we are defining the 10164 // function. 10165 ResolveExceptionSpec(CurrentLocation, 10166 Constructor->getType()->castAs<FunctionProtoType>()); 10167 10168 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10169 10170 Constructor->markUsed(Context); 10171 MarkVTableUsed(CurrentLocation, ClassDecl); 10172 10173 if (ASTMutationListener *L = getASTMutationListener()) { 10174 L->CompletedImplicitDefinition(Constructor); 10175 } 10176 10177 DiagnoseUninitializedFields(*this, Constructor); 10178 } 10179 10180 Sema::ImplicitExceptionSpecification 10181 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 10182 CXXRecordDecl *ClassDecl = MD->getParent(); 10183 10184 // C++ [except.spec]p14: 10185 // An implicitly declared special member function (Clause 12) shall have 10186 // an exception-specification. 10187 ImplicitExceptionSpecification ExceptSpec(*this); 10188 if (ClassDecl->isInvalidDecl()) 10189 return ExceptSpec; 10190 10191 // Direct base-class destructors. 10192 for (const auto &B : ClassDecl->bases()) { 10193 if (B.isVirtual()) // Handled below. 10194 continue; 10195 10196 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 10197 ExceptSpec.CalledDecl(B.getLocStart(), 10198 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 10199 } 10200 10201 // Virtual base-class destructors. 10202 for (const auto &B : ClassDecl->vbases()) { 10203 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 10204 ExceptSpec.CalledDecl(B.getLocStart(), 10205 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 10206 } 10207 10208 // Field destructors. 10209 for (const auto *F : ClassDecl->fields()) { 10210 if (const RecordType *RecordTy 10211 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 10212 ExceptSpec.CalledDecl(F->getLocation(), 10213 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 10214 } 10215 10216 return ExceptSpec; 10217 } 10218 10219 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10220 // C++ [class.dtor]p2: 10221 // If a class has no user-declared destructor, a destructor is 10222 // declared implicitly. An implicitly-declared destructor is an 10223 // inline public member of its class. 10224 assert(ClassDecl->needsImplicitDestructor()); 10225 10226 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10227 if (DSM.isAlreadyBeingDeclared()) 10228 return nullptr; 10229 10230 // Create the actual destructor declaration. 10231 CanQualType ClassType 10232 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10233 SourceLocation ClassLoc = ClassDecl->getLocation(); 10234 DeclarationName Name 10235 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10236 DeclarationNameInfo NameInfo(Name, ClassLoc); 10237 CXXDestructorDecl *Destructor 10238 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10239 QualType(), nullptr, /*isInline=*/true, 10240 /*isImplicitlyDeclared=*/true); 10241 Destructor->setAccess(AS_public); 10242 Destructor->setDefaulted(); 10243 10244 if (getLangOpts().CUDA) { 10245 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10246 Destructor, 10247 /* ConstRHS */ false, 10248 /* Diagnose */ false); 10249 } 10250 10251 // Build an exception specification pointing back at this destructor. 10252 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10253 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10254 10255 // We don't need to use SpecialMemberIsTrivial here; triviality for 10256 // destructors is easy to compute. 10257 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10258 10259 // Note that we have declared this destructor. 10260 ++ASTContext::NumImplicitDestructorsDeclared; 10261 10262 Scope *S = getScopeForContext(ClassDecl); 10263 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10264 10265 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10266 SetDeclDeleted(Destructor, ClassLoc); 10267 10268 // Introduce this destructor into its scope. 10269 if (S) 10270 PushOnScopeChains(Destructor, S, false); 10271 ClassDecl->addDecl(Destructor); 10272 10273 return Destructor; 10274 } 10275 10276 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10277 CXXDestructorDecl *Destructor) { 10278 assert((Destructor->isDefaulted() && 10279 !Destructor->doesThisDeclarationHaveABody() && 10280 !Destructor->isDeleted()) && 10281 "DefineImplicitDestructor - call it for implicit default dtor"); 10282 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10283 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10284 10285 if (Destructor->isInvalidDecl()) 10286 return; 10287 10288 SynthesizedFunctionScope Scope(*this, Destructor); 10289 10290 DiagnosticErrorTrap Trap(Diags); 10291 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10292 Destructor->getParent()); 10293 10294 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 10295 Diag(CurrentLocation, diag::note_member_synthesized_at) 10296 << CXXDestructor << Context.getTagDeclType(ClassDecl); 10297 10298 Destructor->setInvalidDecl(); 10299 return; 10300 } 10301 10302 // The exception specification is needed because we are defining the 10303 // function. 10304 ResolveExceptionSpec(CurrentLocation, 10305 Destructor->getType()->castAs<FunctionProtoType>()); 10306 10307 SourceLocation Loc = Destructor->getLocEnd().isValid() 10308 ? Destructor->getLocEnd() 10309 : Destructor->getLocation(); 10310 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10311 Destructor->markUsed(Context); 10312 MarkVTableUsed(CurrentLocation, ClassDecl); 10313 10314 if (ASTMutationListener *L = getASTMutationListener()) { 10315 L->CompletedImplicitDefinition(Destructor); 10316 } 10317 } 10318 10319 /// \brief Perform any semantic analysis which needs to be delayed until all 10320 /// pending class member declarations have been parsed. 10321 void Sema::ActOnFinishCXXMemberDecls() { 10322 // If the context is an invalid C++ class, just suppress these checks. 10323 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10324 if (Record->isInvalidDecl()) { 10325 DelayedDefaultedMemberExceptionSpecs.clear(); 10326 DelayedExceptionSpecChecks.clear(); 10327 return; 10328 } 10329 } 10330 } 10331 10332 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) { 10333 // Don't do anything for template patterns. 10334 if (Class->getDescribedClassTemplate()) 10335 return; 10336 10337 CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention( 10338 /*IsVariadic=*/false, /*IsCXXMethod=*/true); 10339 10340 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 10341 for (Decl *Member : Class->decls()) { 10342 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 10343 if (!CD) { 10344 // Recurse on nested classes. 10345 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member)) 10346 getDefaultArgExprsForConstructors(S, NestedRD); 10347 continue; 10348 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) { 10349 continue; 10350 } 10351 10352 CallingConv ActualCallingConv = 10353 CD->getType()->getAs<FunctionProtoType>()->getCallConv(); 10354 10355 // Skip default constructors with typical calling conventions and no default 10356 // arguments. 10357 unsigned NumParams = CD->getNumParams(); 10358 if (ExpectedCallingConv == ActualCallingConv && NumParams == 0) 10359 continue; 10360 10361 if (LastExportedDefaultCtor) { 10362 S.Diag(LastExportedDefaultCtor->getLocation(), 10363 diag::err_attribute_dll_ambiguous_default_ctor) << Class; 10364 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 10365 << CD->getDeclName(); 10366 return; 10367 } 10368 LastExportedDefaultCtor = CD; 10369 10370 for (unsigned I = 0; I != NumParams; ++I) { 10371 // Skip any default arguments that we've already instantiated. 10372 if (S.Context.getDefaultArgExprForConstructor(CD, I)) 10373 continue; 10374 10375 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD, 10376 CD->getParamDecl(I)).get(); 10377 S.DiscardCleanupsInEvaluationContext(); 10378 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg); 10379 } 10380 } 10381 } 10382 10383 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10384 auto *RD = dyn_cast<CXXRecordDecl>(D); 10385 10386 // Default constructors that are annotated with __declspec(dllexport) which 10387 // have default arguments or don't use the standard calling convention are 10388 // wrapped with a thunk called the default constructor closure. 10389 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft()) 10390 getDefaultArgExprsForConstructors(*this, RD); 10391 10392 referenceDLLExportedClassMethods(); 10393 } 10394 10395 void Sema::referenceDLLExportedClassMethods() { 10396 if (!DelayedDllExportClasses.empty()) { 10397 // Calling ReferenceDllExportedMethods might cause the current function to 10398 // be called again, so use a local copy of DelayedDllExportClasses. 10399 SmallVector<CXXRecordDecl *, 4> WorkList; 10400 std::swap(DelayedDllExportClasses, WorkList); 10401 for (CXXRecordDecl *Class : WorkList) 10402 ReferenceDllExportedMethods(*this, Class); 10403 } 10404 } 10405 10406 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10407 CXXDestructorDecl *Destructor) { 10408 assert(getLangOpts().CPlusPlus11 && 10409 "adjusting dtor exception specs was introduced in c++11"); 10410 10411 // C++11 [class.dtor]p3: 10412 // A declaration of a destructor that does not have an exception- 10413 // specification is implicitly considered to have the same exception- 10414 // specification as an implicit declaration. 10415 const FunctionProtoType *DtorType = Destructor->getType()-> 10416 getAs<FunctionProtoType>(); 10417 if (DtorType->hasExceptionSpec()) 10418 return; 10419 10420 // Replace the destructor's type, building off the existing one. Fortunately, 10421 // the only thing of interest in the destructor type is its extended info. 10422 // The return and arguments are fixed. 10423 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10424 EPI.ExceptionSpec.Type = EST_Unevaluated; 10425 EPI.ExceptionSpec.SourceDecl = Destructor; 10426 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10427 10428 // FIXME: If the destructor has a body that could throw, and the newly created 10429 // spec doesn't allow exceptions, we should emit a warning, because this 10430 // change in behavior can break conforming C++03 programs at runtime. 10431 // However, we don't have a body or an exception specification yet, so it 10432 // needs to be done somewhere else. 10433 } 10434 10435 namespace { 10436 /// \brief An abstract base class for all helper classes used in building the 10437 // copy/move operators. These classes serve as factory functions and help us 10438 // avoid using the same Expr* in the AST twice. 10439 class ExprBuilder { 10440 ExprBuilder(const ExprBuilder&) = delete; 10441 ExprBuilder &operator=(const ExprBuilder&) = delete; 10442 10443 protected: 10444 static Expr *assertNotNull(Expr *E) { 10445 assert(E && "Expression construction must not fail."); 10446 return E; 10447 } 10448 10449 public: 10450 ExprBuilder() {} 10451 virtual ~ExprBuilder() {} 10452 10453 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10454 }; 10455 10456 class RefBuilder: public ExprBuilder { 10457 VarDecl *Var; 10458 QualType VarType; 10459 10460 public: 10461 Expr *build(Sema &S, SourceLocation Loc) const override { 10462 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10463 } 10464 10465 RefBuilder(VarDecl *Var, QualType VarType) 10466 : Var(Var), VarType(VarType) {} 10467 }; 10468 10469 class ThisBuilder: public ExprBuilder { 10470 public: 10471 Expr *build(Sema &S, SourceLocation Loc) const override { 10472 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 10473 } 10474 }; 10475 10476 class CastBuilder: public ExprBuilder { 10477 const ExprBuilder &Builder; 10478 QualType Type; 10479 ExprValueKind Kind; 10480 const CXXCastPath &Path; 10481 10482 public: 10483 Expr *build(Sema &S, SourceLocation Loc) const override { 10484 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 10485 CK_UncheckedDerivedToBase, Kind, 10486 &Path).get()); 10487 } 10488 10489 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 10490 const CXXCastPath &Path) 10491 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 10492 }; 10493 10494 class DerefBuilder: public ExprBuilder { 10495 const ExprBuilder &Builder; 10496 10497 public: 10498 Expr *build(Sema &S, SourceLocation Loc) const override { 10499 return assertNotNull( 10500 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 10501 } 10502 10503 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10504 }; 10505 10506 class MemberBuilder: public ExprBuilder { 10507 const ExprBuilder &Builder; 10508 QualType Type; 10509 CXXScopeSpec SS; 10510 bool IsArrow; 10511 LookupResult &MemberLookup; 10512 10513 public: 10514 Expr *build(Sema &S, SourceLocation Loc) const override { 10515 return assertNotNull(S.BuildMemberReferenceExpr( 10516 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 10517 nullptr, MemberLookup, nullptr, nullptr).get()); 10518 } 10519 10520 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 10521 LookupResult &MemberLookup) 10522 : Builder(Builder), Type(Type), IsArrow(IsArrow), 10523 MemberLookup(MemberLookup) {} 10524 }; 10525 10526 class MoveCastBuilder: public ExprBuilder { 10527 const ExprBuilder &Builder; 10528 10529 public: 10530 Expr *build(Sema &S, SourceLocation Loc) const override { 10531 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 10532 } 10533 10534 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10535 }; 10536 10537 class LvalueConvBuilder: public ExprBuilder { 10538 const ExprBuilder &Builder; 10539 10540 public: 10541 Expr *build(Sema &S, SourceLocation Loc) const override { 10542 return assertNotNull( 10543 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 10544 } 10545 10546 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10547 }; 10548 10549 class SubscriptBuilder: public ExprBuilder { 10550 const ExprBuilder &Base; 10551 const ExprBuilder &Index; 10552 10553 public: 10554 Expr *build(Sema &S, SourceLocation Loc) const override { 10555 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 10556 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 10557 } 10558 10559 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 10560 : Base(Base), Index(Index) {} 10561 }; 10562 10563 } // end anonymous namespace 10564 10565 /// When generating a defaulted copy or move assignment operator, if a field 10566 /// should be copied with __builtin_memcpy rather than via explicit assignments, 10567 /// do so. This optimization only applies for arrays of scalars, and for arrays 10568 /// of class type where the selected copy/move-assignment operator is trivial. 10569 static StmtResult 10570 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 10571 const ExprBuilder &ToB, const ExprBuilder &FromB) { 10572 // Compute the size of the memory buffer to be copied. 10573 QualType SizeType = S.Context.getSizeType(); 10574 llvm::APInt Size(S.Context.getTypeSize(SizeType), 10575 S.Context.getTypeSizeInChars(T).getQuantity()); 10576 10577 // Take the address of the field references for "from" and "to". We 10578 // directly construct UnaryOperators here because semantic analysis 10579 // does not permit us to take the address of an xvalue. 10580 Expr *From = FromB.build(S, Loc); 10581 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 10582 S.Context.getPointerType(From->getType()), 10583 VK_RValue, OK_Ordinary, Loc); 10584 Expr *To = ToB.build(S, Loc); 10585 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 10586 S.Context.getPointerType(To->getType()), 10587 VK_RValue, OK_Ordinary, Loc); 10588 10589 const Type *E = T->getBaseElementTypeUnsafe(); 10590 bool NeedsCollectableMemCpy = 10591 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 10592 10593 // Create a reference to the __builtin_objc_memmove_collectable function 10594 StringRef MemCpyName = NeedsCollectableMemCpy ? 10595 "__builtin_objc_memmove_collectable" : 10596 "__builtin_memcpy"; 10597 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 10598 Sema::LookupOrdinaryName); 10599 S.LookupName(R, S.TUScope, true); 10600 10601 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 10602 if (!MemCpy) 10603 // Something went horribly wrong earlier, and we will have complained 10604 // about it. 10605 return StmtError(); 10606 10607 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 10608 VK_RValue, Loc, nullptr); 10609 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 10610 10611 Expr *CallArgs[] = { 10612 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 10613 }; 10614 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 10615 Loc, CallArgs, Loc); 10616 10617 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 10618 return Call.getAs<Stmt>(); 10619 } 10620 10621 /// \brief Builds a statement that copies/moves the given entity from \p From to 10622 /// \c To. 10623 /// 10624 /// This routine is used to copy/move the members of a class with an 10625 /// implicitly-declared copy/move assignment operator. When the entities being 10626 /// copied are arrays, this routine builds for loops to copy them. 10627 /// 10628 /// \param S The Sema object used for type-checking. 10629 /// 10630 /// \param Loc The location where the implicit copy/move is being generated. 10631 /// 10632 /// \param T The type of the expressions being copied/moved. Both expressions 10633 /// must have this type. 10634 /// 10635 /// \param To The expression we are copying/moving to. 10636 /// 10637 /// \param From The expression we are copying/moving from. 10638 /// 10639 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 10640 /// Otherwise, it's a non-static member subobject. 10641 /// 10642 /// \param Copying Whether we're copying or moving. 10643 /// 10644 /// \param Depth Internal parameter recording the depth of the recursion. 10645 /// 10646 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 10647 /// if a memcpy should be used instead. 10648 static StmtResult 10649 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 10650 const ExprBuilder &To, const ExprBuilder &From, 10651 bool CopyingBaseSubobject, bool Copying, 10652 unsigned Depth = 0) { 10653 // C++11 [class.copy]p28: 10654 // Each subobject is assigned in the manner appropriate to its type: 10655 // 10656 // - if the subobject is of class type, as if by a call to operator= with 10657 // the subobject as the object expression and the corresponding 10658 // subobject of x as a single function argument (as if by explicit 10659 // qualification; that is, ignoring any possible virtual overriding 10660 // functions in more derived classes); 10661 // 10662 // C++03 [class.copy]p13: 10663 // - if the subobject is of class type, the copy assignment operator for 10664 // the class is used (as if by explicit qualification; that is, 10665 // ignoring any possible virtual overriding functions in more derived 10666 // classes); 10667 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 10668 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 10669 10670 // Look for operator=. 10671 DeclarationName Name 10672 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10673 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 10674 S.LookupQualifiedName(OpLookup, ClassDecl, false); 10675 10676 // Prior to C++11, filter out any result that isn't a copy/move-assignment 10677 // operator. 10678 if (!S.getLangOpts().CPlusPlus11) { 10679 LookupResult::Filter F = OpLookup.makeFilter(); 10680 while (F.hasNext()) { 10681 NamedDecl *D = F.next(); 10682 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 10683 if (Method->isCopyAssignmentOperator() || 10684 (!Copying && Method->isMoveAssignmentOperator())) 10685 continue; 10686 10687 F.erase(); 10688 } 10689 F.done(); 10690 } 10691 10692 // Suppress the protected check (C++ [class.protected]) for each of the 10693 // assignment operators we found. This strange dance is required when 10694 // we're assigning via a base classes's copy-assignment operator. To 10695 // ensure that we're getting the right base class subobject (without 10696 // ambiguities), we need to cast "this" to that subobject type; to 10697 // ensure that we don't go through the virtual call mechanism, we need 10698 // to qualify the operator= name with the base class (see below). However, 10699 // this means that if the base class has a protected copy assignment 10700 // operator, the protected member access check will fail. So, we 10701 // rewrite "protected" access to "public" access in this case, since we 10702 // know by construction that we're calling from a derived class. 10703 if (CopyingBaseSubobject) { 10704 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 10705 L != LEnd; ++L) { 10706 if (L.getAccess() == AS_protected) 10707 L.setAccess(AS_public); 10708 } 10709 } 10710 10711 // Create the nested-name-specifier that will be used to qualify the 10712 // reference to operator=; this is required to suppress the virtual 10713 // call mechanism. 10714 CXXScopeSpec SS; 10715 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 10716 SS.MakeTrivial(S.Context, 10717 NestedNameSpecifier::Create(S.Context, nullptr, false, 10718 CanonicalT), 10719 Loc); 10720 10721 // Create the reference to operator=. 10722 ExprResult OpEqualRef 10723 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 10724 SS, /*TemplateKWLoc=*/SourceLocation(), 10725 /*FirstQualifierInScope=*/nullptr, 10726 OpLookup, 10727 /*TemplateArgs=*/nullptr, /*S*/nullptr, 10728 /*SuppressQualifierCheck=*/true); 10729 if (OpEqualRef.isInvalid()) 10730 return StmtError(); 10731 10732 // Build the call to the assignment operator. 10733 10734 Expr *FromInst = From.build(S, Loc); 10735 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 10736 OpEqualRef.getAs<Expr>(), 10737 Loc, FromInst, Loc); 10738 if (Call.isInvalid()) 10739 return StmtError(); 10740 10741 // If we built a call to a trivial 'operator=' while copying an array, 10742 // bail out. We'll replace the whole shebang with a memcpy. 10743 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 10744 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 10745 return StmtResult((Stmt*)nullptr); 10746 10747 // Convert to an expression-statement, and clean up any produced 10748 // temporaries. 10749 return S.ActOnExprStmt(Call); 10750 } 10751 10752 // - if the subobject is of scalar type, the built-in assignment 10753 // operator is used. 10754 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 10755 if (!ArrayTy) { 10756 ExprResult Assignment = S.CreateBuiltinBinOp( 10757 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 10758 if (Assignment.isInvalid()) 10759 return StmtError(); 10760 return S.ActOnExprStmt(Assignment); 10761 } 10762 10763 // - if the subobject is an array, each element is assigned, in the 10764 // manner appropriate to the element type; 10765 10766 // Construct a loop over the array bounds, e.g., 10767 // 10768 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 10769 // 10770 // that will copy each of the array elements. 10771 QualType SizeType = S.Context.getSizeType(); 10772 10773 // Create the iteration variable. 10774 IdentifierInfo *IterationVarName = nullptr; 10775 { 10776 SmallString<8> Str; 10777 llvm::raw_svector_ostream OS(Str); 10778 OS << "__i" << Depth; 10779 IterationVarName = &S.Context.Idents.get(OS.str()); 10780 } 10781 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 10782 IterationVarName, SizeType, 10783 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 10784 SC_None); 10785 10786 // Initialize the iteration variable to zero. 10787 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 10788 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 10789 10790 // Creates a reference to the iteration variable. 10791 RefBuilder IterationVarRef(IterationVar, SizeType); 10792 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 10793 10794 // Create the DeclStmt that holds the iteration variable. 10795 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 10796 10797 // Subscript the "from" and "to" expressions with the iteration variable. 10798 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 10799 MoveCastBuilder FromIndexMove(FromIndexCopy); 10800 const ExprBuilder *FromIndex; 10801 if (Copying) 10802 FromIndex = &FromIndexCopy; 10803 else 10804 FromIndex = &FromIndexMove; 10805 10806 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 10807 10808 // Build the copy/move for an individual element of the array. 10809 StmtResult Copy = 10810 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 10811 ToIndex, *FromIndex, CopyingBaseSubobject, 10812 Copying, Depth + 1); 10813 // Bail out if copying fails or if we determined that we should use memcpy. 10814 if (Copy.isInvalid() || !Copy.get()) 10815 return Copy; 10816 10817 // Create the comparison against the array bound. 10818 llvm::APInt Upper 10819 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 10820 Expr *Comparison 10821 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 10822 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 10823 BO_NE, S.Context.BoolTy, 10824 VK_RValue, OK_Ordinary, Loc, false); 10825 10826 // Create the pre-increment of the iteration variable. 10827 Expr *Increment 10828 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 10829 SizeType, VK_LValue, OK_Ordinary, Loc); 10830 10831 // Construct the loop that copies all elements of this array. 10832 return S.ActOnForStmt( 10833 Loc, Loc, InitStmt, 10834 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 10835 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 10836 } 10837 10838 static StmtResult 10839 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 10840 const ExprBuilder &To, const ExprBuilder &From, 10841 bool CopyingBaseSubobject, bool Copying) { 10842 // Maybe we should use a memcpy? 10843 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 10844 T.isTriviallyCopyableType(S.Context)) 10845 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 10846 10847 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 10848 CopyingBaseSubobject, 10849 Copying, 0)); 10850 10851 // If we ended up picking a trivial assignment operator for an array of a 10852 // non-trivially-copyable class type, just emit a memcpy. 10853 if (!Result.isInvalid() && !Result.get()) 10854 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 10855 10856 return Result; 10857 } 10858 10859 Sema::ImplicitExceptionSpecification 10860 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 10861 CXXRecordDecl *ClassDecl = MD->getParent(); 10862 10863 ImplicitExceptionSpecification ExceptSpec(*this); 10864 if (ClassDecl->isInvalidDecl()) 10865 return ExceptSpec; 10866 10867 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10868 assert(T->getNumParams() == 1 && "not a copy assignment op"); 10869 unsigned ArgQuals = 10870 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10871 10872 // C++ [except.spec]p14: 10873 // An implicitly declared special member function (Clause 12) shall have an 10874 // exception-specification. [...] 10875 10876 // It is unspecified whether or not an implicit copy assignment operator 10877 // attempts to deduplicate calls to assignment operators of virtual bases are 10878 // made. As such, this exception specification is effectively unspecified. 10879 // Based on a similar decision made for constness in C++0x, we're erring on 10880 // the side of assuming such calls to be made regardless of whether they 10881 // actually happen. 10882 for (const auto &Base : ClassDecl->bases()) { 10883 if (Base.isVirtual()) 10884 continue; 10885 10886 CXXRecordDecl *BaseClassDecl 10887 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10888 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10889 ArgQuals, false, 0)) 10890 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10891 } 10892 10893 for (const auto &Base : ClassDecl->vbases()) { 10894 CXXRecordDecl *BaseClassDecl 10895 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10896 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 10897 ArgQuals, false, 0)) 10898 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 10899 } 10900 10901 for (const auto *Field : ClassDecl->fields()) { 10902 QualType FieldType = Context.getBaseElementType(Field->getType()); 10903 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10904 if (CXXMethodDecl *CopyAssign = 10905 LookupCopyingAssignment(FieldClassDecl, 10906 ArgQuals | FieldType.getCVRQualifiers(), 10907 false, 0)) 10908 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 10909 } 10910 } 10911 10912 return ExceptSpec; 10913 } 10914 10915 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 10916 // Note: The following rules are largely analoguous to the copy 10917 // constructor rules. Note that virtual bases are not taken into account 10918 // for determining the argument type of the operator. Note also that 10919 // operators taking an object instead of a reference are allowed. 10920 assert(ClassDecl->needsImplicitCopyAssignment()); 10921 10922 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 10923 if (DSM.isAlreadyBeingDeclared()) 10924 return nullptr; 10925 10926 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10927 QualType RetType = Context.getLValueReferenceType(ArgType); 10928 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 10929 if (Const) 10930 ArgType = ArgType.withConst(); 10931 ArgType = Context.getLValueReferenceType(ArgType); 10932 10933 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10934 CXXCopyAssignment, 10935 Const); 10936 10937 // An implicitly-declared copy assignment operator is an inline public 10938 // member of its class. 10939 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10940 SourceLocation ClassLoc = ClassDecl->getLocation(); 10941 DeclarationNameInfo NameInfo(Name, ClassLoc); 10942 CXXMethodDecl *CopyAssignment = 10943 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10944 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10945 /*isInline=*/true, Constexpr, SourceLocation()); 10946 CopyAssignment->setAccess(AS_public); 10947 CopyAssignment->setDefaulted(); 10948 CopyAssignment->setImplicit(); 10949 10950 if (getLangOpts().CUDA) { 10951 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 10952 CopyAssignment, 10953 /* ConstRHS */ Const, 10954 /* Diagnose */ false); 10955 } 10956 10957 // Build an exception specification pointing back at this member. 10958 FunctionProtoType::ExtProtoInfo EPI = 10959 getImplicitMethodEPI(*this, CopyAssignment); 10960 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10961 10962 // Add the parameter to the operator. 10963 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 10964 ClassLoc, ClassLoc, 10965 /*Id=*/nullptr, ArgType, 10966 /*TInfo=*/nullptr, SC_None, 10967 nullptr); 10968 CopyAssignment->setParams(FromParam); 10969 10970 CopyAssignment->setTrivial( 10971 ClassDecl->needsOverloadResolutionForCopyAssignment() 10972 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 10973 : ClassDecl->hasTrivialCopyAssignment()); 10974 10975 // Note that we have added this copy-assignment operator. 10976 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10977 10978 Scope *S = getScopeForContext(ClassDecl); 10979 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 10980 10981 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 10982 SetDeclDeleted(CopyAssignment, ClassLoc); 10983 10984 if (S) 10985 PushOnScopeChains(CopyAssignment, S, false); 10986 ClassDecl->addDecl(CopyAssignment); 10987 10988 return CopyAssignment; 10989 } 10990 10991 /// Diagnose an implicit copy operation for a class which is odr-used, but 10992 /// which is deprecated because the class has a user-declared copy constructor, 10993 /// copy assignment operator, or destructor. 10994 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 10995 SourceLocation UseLoc) { 10996 assert(CopyOp->isImplicit()); 10997 10998 CXXRecordDecl *RD = CopyOp->getParent(); 10999 CXXMethodDecl *UserDeclaredOperation = nullptr; 11000 11001 // In Microsoft mode, assignment operations don't affect constructors and 11002 // vice versa. 11003 if (RD->hasUserDeclaredDestructor()) { 11004 UserDeclaredOperation = RD->getDestructor(); 11005 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11006 RD->hasUserDeclaredCopyConstructor() && 11007 !S.getLangOpts().MSVCCompat) { 11008 // Find any user-declared copy constructor. 11009 for (auto *I : RD->ctors()) { 11010 if (I->isCopyConstructor()) { 11011 UserDeclaredOperation = I; 11012 break; 11013 } 11014 } 11015 assert(UserDeclaredOperation); 11016 } else if (isa<CXXConstructorDecl>(CopyOp) && 11017 RD->hasUserDeclaredCopyAssignment() && 11018 !S.getLangOpts().MSVCCompat) { 11019 // Find any user-declared move assignment operator. 11020 for (auto *I : RD->methods()) { 11021 if (I->isCopyAssignmentOperator()) { 11022 UserDeclaredOperation = I; 11023 break; 11024 } 11025 } 11026 assert(UserDeclaredOperation); 11027 } 11028 11029 if (UserDeclaredOperation) { 11030 S.Diag(UserDeclaredOperation->getLocation(), 11031 diag::warn_deprecated_copy_operation) 11032 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11033 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11034 S.Diag(UseLoc, diag::note_member_synthesized_at) 11035 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 11036 : Sema::CXXCopyAssignment) 11037 << RD; 11038 } 11039 } 11040 11041 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11042 CXXMethodDecl *CopyAssignOperator) { 11043 assert((CopyAssignOperator->isDefaulted() && 11044 CopyAssignOperator->isOverloadedOperator() && 11045 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11046 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11047 !CopyAssignOperator->isDeleted()) && 11048 "DefineImplicitCopyAssignment called for wrong function"); 11049 11050 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11051 11052 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 11053 CopyAssignOperator->setInvalidDecl(); 11054 return; 11055 } 11056 11057 // C++11 [class.copy]p18: 11058 // The [definition of an implicitly declared copy assignment operator] is 11059 // deprecated if the class has a user-declared copy constructor or a 11060 // user-declared destructor. 11061 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11062 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 11063 11064 CopyAssignOperator->markUsed(Context); 11065 11066 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11067 DiagnosticErrorTrap Trap(Diags); 11068 11069 // C++0x [class.copy]p30: 11070 // The implicitly-defined or explicitly-defaulted copy assignment operator 11071 // for a non-union class X performs memberwise copy assignment of its 11072 // subobjects. The direct base classes of X are assigned first, in the 11073 // order of their declaration in the base-specifier-list, and then the 11074 // immediate non-static data members of X are assigned, in the order in 11075 // which they were declared in the class definition. 11076 11077 // The statements that form the synthesized function body. 11078 SmallVector<Stmt*, 8> Statements; 11079 11080 // The parameter for the "other" object, which we are copying from. 11081 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11082 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11083 QualType OtherRefType = Other->getType(); 11084 if (const LValueReferenceType *OtherRef 11085 = OtherRefType->getAs<LValueReferenceType>()) { 11086 OtherRefType = OtherRef->getPointeeType(); 11087 OtherQuals = OtherRefType.getQualifiers(); 11088 } 11089 11090 // Our location for everything implicitly-generated. 11091 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11092 ? CopyAssignOperator->getLocEnd() 11093 : CopyAssignOperator->getLocation(); 11094 11095 // Builds a DeclRefExpr for the "other" object. 11096 RefBuilder OtherRef(Other, OtherRefType); 11097 11098 // Builds the "this" pointer. 11099 ThisBuilder This; 11100 11101 // Assign base classes. 11102 bool Invalid = false; 11103 for (auto &Base : ClassDecl->bases()) { 11104 // Form the assignment: 11105 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11106 QualType BaseType = Base.getType().getUnqualifiedType(); 11107 if (!BaseType->isRecordType()) { 11108 Invalid = true; 11109 continue; 11110 } 11111 11112 CXXCastPath BasePath; 11113 BasePath.push_back(&Base); 11114 11115 // Construct the "from" expression, which is an implicit cast to the 11116 // appropriately-qualified base type. 11117 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11118 VK_LValue, BasePath); 11119 11120 // Dereference "this". 11121 DerefBuilder DerefThis(This); 11122 CastBuilder To(DerefThis, 11123 Context.getCVRQualifiedType( 11124 BaseType, CopyAssignOperator->getTypeQualifiers()), 11125 VK_LValue, BasePath); 11126 11127 // Build the copy. 11128 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11129 To, From, 11130 /*CopyingBaseSubobject=*/true, 11131 /*Copying=*/true); 11132 if (Copy.isInvalid()) { 11133 Diag(CurrentLocation, diag::note_member_synthesized_at) 11134 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11135 CopyAssignOperator->setInvalidDecl(); 11136 return; 11137 } 11138 11139 // Success! Record the copy. 11140 Statements.push_back(Copy.getAs<Expr>()); 11141 } 11142 11143 // Assign non-static members. 11144 for (auto *Field : ClassDecl->fields()) { 11145 // FIXME: We should form some kind of AST representation for the implied 11146 // memcpy in a union copy operation. 11147 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11148 continue; 11149 11150 if (Field->isInvalidDecl()) { 11151 Invalid = true; 11152 continue; 11153 } 11154 11155 // Check for members of reference type; we can't copy those. 11156 if (Field->getType()->isReferenceType()) { 11157 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11158 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11159 Diag(Field->getLocation(), diag::note_declared_at); 11160 Diag(CurrentLocation, diag::note_member_synthesized_at) 11161 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11162 Invalid = true; 11163 continue; 11164 } 11165 11166 // Check for members of const-qualified, non-class type. 11167 QualType BaseType = Context.getBaseElementType(Field->getType()); 11168 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11169 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11170 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11171 Diag(Field->getLocation(), diag::note_declared_at); 11172 Diag(CurrentLocation, diag::note_member_synthesized_at) 11173 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11174 Invalid = true; 11175 continue; 11176 } 11177 11178 // Suppress assigning zero-width bitfields. 11179 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11180 continue; 11181 11182 QualType FieldType = Field->getType().getNonReferenceType(); 11183 if (FieldType->isIncompleteArrayType()) { 11184 assert(ClassDecl->hasFlexibleArrayMember() && 11185 "Incomplete array type is not valid"); 11186 continue; 11187 } 11188 11189 // Build references to the field in the object we're copying from and to. 11190 CXXScopeSpec SS; // Intentionally empty 11191 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11192 LookupMemberName); 11193 MemberLookup.addDecl(Field); 11194 MemberLookup.resolveKind(); 11195 11196 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11197 11198 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11199 11200 // Build the copy of this field. 11201 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11202 To, From, 11203 /*CopyingBaseSubobject=*/false, 11204 /*Copying=*/true); 11205 if (Copy.isInvalid()) { 11206 Diag(CurrentLocation, diag::note_member_synthesized_at) 11207 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11208 CopyAssignOperator->setInvalidDecl(); 11209 return; 11210 } 11211 11212 // Success! Record the copy. 11213 Statements.push_back(Copy.getAs<Stmt>()); 11214 } 11215 11216 if (!Invalid) { 11217 // Add a "return *this;" 11218 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11219 11220 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11221 if (Return.isInvalid()) 11222 Invalid = true; 11223 else { 11224 Statements.push_back(Return.getAs<Stmt>()); 11225 11226 if (Trap.hasErrorOccurred()) { 11227 Diag(CurrentLocation, diag::note_member_synthesized_at) 11228 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 11229 Invalid = true; 11230 } 11231 } 11232 } 11233 11234 // The exception specification is needed because we are defining the 11235 // function. 11236 ResolveExceptionSpec(CurrentLocation, 11237 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11238 11239 if (Invalid) { 11240 CopyAssignOperator->setInvalidDecl(); 11241 return; 11242 } 11243 11244 StmtResult Body; 11245 { 11246 CompoundScopeRAII CompoundScope(*this); 11247 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11248 /*isStmtExpr=*/false); 11249 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11250 } 11251 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11252 11253 if (ASTMutationListener *L = getASTMutationListener()) { 11254 L->CompletedImplicitDefinition(CopyAssignOperator); 11255 } 11256 } 11257 11258 Sema::ImplicitExceptionSpecification 11259 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 11260 CXXRecordDecl *ClassDecl = MD->getParent(); 11261 11262 ImplicitExceptionSpecification ExceptSpec(*this); 11263 if (ClassDecl->isInvalidDecl()) 11264 return ExceptSpec; 11265 11266 // C++0x [except.spec]p14: 11267 // An implicitly declared special member function (Clause 12) shall have an 11268 // exception-specification. [...] 11269 11270 // It is unspecified whether or not an implicit move assignment operator 11271 // attempts to deduplicate calls to assignment operators of virtual bases are 11272 // made. As such, this exception specification is effectively unspecified. 11273 // Based on a similar decision made for constness in C++0x, we're erring on 11274 // the side of assuming such calls to be made regardless of whether they 11275 // actually happen. 11276 // Note that a move constructor is not implicitly declared when there are 11277 // virtual bases, but it can still be user-declared and explicitly defaulted. 11278 for (const auto &Base : ClassDecl->bases()) { 11279 if (Base.isVirtual()) 11280 continue; 11281 11282 CXXRecordDecl *BaseClassDecl 11283 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11284 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 11285 0, false, 0)) 11286 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 11287 } 11288 11289 for (const auto &Base : ClassDecl->vbases()) { 11290 CXXRecordDecl *BaseClassDecl 11291 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11292 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 11293 0, false, 0)) 11294 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 11295 } 11296 11297 for (const auto *Field : ClassDecl->fields()) { 11298 QualType FieldType = Context.getBaseElementType(Field->getType()); 11299 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 11300 if (CXXMethodDecl *MoveAssign = 11301 LookupMovingAssignment(FieldClassDecl, 11302 FieldType.getCVRQualifiers(), 11303 false, 0)) 11304 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 11305 } 11306 } 11307 11308 return ExceptSpec; 11309 } 11310 11311 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11312 assert(ClassDecl->needsImplicitMoveAssignment()); 11313 11314 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11315 if (DSM.isAlreadyBeingDeclared()) 11316 return nullptr; 11317 11318 // Note: The following rules are largely analoguous to the move 11319 // constructor rules. 11320 11321 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11322 QualType RetType = Context.getLValueReferenceType(ArgType); 11323 ArgType = Context.getRValueReferenceType(ArgType); 11324 11325 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11326 CXXMoveAssignment, 11327 false); 11328 11329 // An implicitly-declared move assignment operator is an inline public 11330 // member of its class. 11331 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11332 SourceLocation ClassLoc = ClassDecl->getLocation(); 11333 DeclarationNameInfo NameInfo(Name, ClassLoc); 11334 CXXMethodDecl *MoveAssignment = 11335 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11336 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11337 /*isInline=*/true, Constexpr, SourceLocation()); 11338 MoveAssignment->setAccess(AS_public); 11339 MoveAssignment->setDefaulted(); 11340 MoveAssignment->setImplicit(); 11341 11342 if (getLangOpts().CUDA) { 11343 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11344 MoveAssignment, 11345 /* ConstRHS */ false, 11346 /* Diagnose */ false); 11347 } 11348 11349 // Build an exception specification pointing back at this member. 11350 FunctionProtoType::ExtProtoInfo EPI = 11351 getImplicitMethodEPI(*this, MoveAssignment); 11352 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11353 11354 // Add the parameter to the operator. 11355 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11356 ClassLoc, ClassLoc, 11357 /*Id=*/nullptr, ArgType, 11358 /*TInfo=*/nullptr, SC_None, 11359 nullptr); 11360 MoveAssignment->setParams(FromParam); 11361 11362 MoveAssignment->setTrivial( 11363 ClassDecl->needsOverloadResolutionForMoveAssignment() 11364 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11365 : ClassDecl->hasTrivialMoveAssignment()); 11366 11367 // Note that we have added this copy-assignment operator. 11368 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11369 11370 Scope *S = getScopeForContext(ClassDecl); 11371 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11372 11373 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11374 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11375 SetDeclDeleted(MoveAssignment, ClassLoc); 11376 } 11377 11378 if (S) 11379 PushOnScopeChains(MoveAssignment, S, false); 11380 ClassDecl->addDecl(MoveAssignment); 11381 11382 return MoveAssignment; 11383 } 11384 11385 /// Check if we're implicitly defining a move assignment operator for a class 11386 /// with virtual bases. Such a move assignment might move-assign the virtual 11387 /// base multiple times. 11388 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11389 SourceLocation CurrentLocation) { 11390 assert(!Class->isDependentContext() && "should not define dependent move"); 11391 11392 // Only a virtual base could get implicitly move-assigned multiple times. 11393 // Only a non-trivial move assignment can observe this. We only want to 11394 // diagnose if we implicitly define an assignment operator that assigns 11395 // two base classes, both of which move-assign the same virtual base. 11396 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11397 Class->getNumBases() < 2) 11398 return; 11399 11400 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11401 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11402 VBaseMap VBases; 11403 11404 for (auto &BI : Class->bases()) { 11405 Worklist.push_back(&BI); 11406 while (!Worklist.empty()) { 11407 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11408 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11409 11410 // If the base has no non-trivial move assignment operators, 11411 // we don't care about moves from it. 11412 if (!Base->hasNonTrivialMoveAssignment()) 11413 continue; 11414 11415 // If there's nothing virtual here, skip it. 11416 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11417 continue; 11418 11419 // If we're not actually going to call a move assignment for this base, 11420 // or the selected move assignment is trivial, skip it. 11421 Sema::SpecialMemberOverloadResult *SMOR = 11422 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11423 /*ConstArg*/false, /*VolatileArg*/false, 11424 /*RValueThis*/true, /*ConstThis*/false, 11425 /*VolatileThis*/false); 11426 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 11427 !SMOR->getMethod()->isMoveAssignmentOperator()) 11428 continue; 11429 11430 if (BaseSpec->isVirtual()) { 11431 // We're going to move-assign this virtual base, and its move 11432 // assignment operator is not trivial. If this can happen for 11433 // multiple distinct direct bases of Class, diagnose it. (If it 11434 // only happens in one base, we'll diagnose it when synthesizing 11435 // that base class's move assignment operator.) 11436 CXXBaseSpecifier *&Existing = 11437 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11438 .first->second; 11439 if (Existing && Existing != &BI) { 11440 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11441 << Class << Base; 11442 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11443 << (Base->getCanonicalDecl() == 11444 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11445 << Base << Existing->getType() << Existing->getSourceRange(); 11446 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11447 << (Base->getCanonicalDecl() == 11448 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11449 << Base << BI.getType() << BaseSpec->getSourceRange(); 11450 11451 // Only diagnose each vbase once. 11452 Existing = nullptr; 11453 } 11454 } else { 11455 // Only walk over bases that have defaulted move assignment operators. 11456 // We assume that any user-provided move assignment operator handles 11457 // the multiple-moves-of-vbase case itself somehow. 11458 if (!SMOR->getMethod()->isDefaulted()) 11459 continue; 11460 11461 // We're going to move the base classes of Base. Add them to the list. 11462 for (auto &BI : Base->bases()) 11463 Worklist.push_back(&BI); 11464 } 11465 } 11466 } 11467 } 11468 11469 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11470 CXXMethodDecl *MoveAssignOperator) { 11471 assert((MoveAssignOperator->isDefaulted() && 11472 MoveAssignOperator->isOverloadedOperator() && 11473 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11474 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11475 !MoveAssignOperator->isDeleted()) && 11476 "DefineImplicitMoveAssignment called for wrong function"); 11477 11478 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11479 11480 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 11481 MoveAssignOperator->setInvalidDecl(); 11482 return; 11483 } 11484 11485 MoveAssignOperator->markUsed(Context); 11486 11487 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11488 DiagnosticErrorTrap Trap(Diags); 11489 11490 // C++0x [class.copy]p28: 11491 // The implicitly-defined or move assignment operator for a non-union class 11492 // X performs memberwise move assignment of its subobjects. The direct base 11493 // classes of X are assigned first, in the order of their declaration in the 11494 // base-specifier-list, and then the immediate non-static data members of X 11495 // are assigned, in the order in which they were declared in the class 11496 // definition. 11497 11498 // Issue a warning if our implicit move assignment operator will move 11499 // from a virtual base more than once. 11500 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11501 11502 // The statements that form the synthesized function body. 11503 SmallVector<Stmt*, 8> Statements; 11504 11505 // The parameter for the "other" object, which we are move from. 11506 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11507 QualType OtherRefType = Other->getType()-> 11508 getAs<RValueReferenceType>()->getPointeeType(); 11509 assert(!OtherRefType.getQualifiers() && 11510 "Bad argument type of defaulted move assignment"); 11511 11512 // Our location for everything implicitly-generated. 11513 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11514 ? MoveAssignOperator->getLocEnd() 11515 : MoveAssignOperator->getLocation(); 11516 11517 // Builds a reference to the "other" object. 11518 RefBuilder OtherRef(Other, OtherRefType); 11519 // Cast to rvalue. 11520 MoveCastBuilder MoveOther(OtherRef); 11521 11522 // Builds the "this" pointer. 11523 ThisBuilder This; 11524 11525 // Assign base classes. 11526 bool Invalid = false; 11527 for (auto &Base : ClassDecl->bases()) { 11528 // C++11 [class.copy]p28: 11529 // It is unspecified whether subobjects representing virtual base classes 11530 // are assigned more than once by the implicitly-defined copy assignment 11531 // operator. 11532 // FIXME: Do not assign to a vbase that will be assigned by some other base 11533 // class. For a move-assignment, this can result in the vbase being moved 11534 // multiple times. 11535 11536 // Form the assignment: 11537 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11538 QualType BaseType = Base.getType().getUnqualifiedType(); 11539 if (!BaseType->isRecordType()) { 11540 Invalid = true; 11541 continue; 11542 } 11543 11544 CXXCastPath BasePath; 11545 BasePath.push_back(&Base); 11546 11547 // Construct the "from" expression, which is an implicit cast to the 11548 // appropriately-qualified base type. 11549 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11550 11551 // Dereference "this". 11552 DerefBuilder DerefThis(This); 11553 11554 // Implicitly cast "this" to the appropriately-qualified base type. 11555 CastBuilder To(DerefThis, 11556 Context.getCVRQualifiedType( 11557 BaseType, MoveAssignOperator->getTypeQualifiers()), 11558 VK_LValue, BasePath); 11559 11560 // Build the move. 11561 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11562 To, From, 11563 /*CopyingBaseSubobject=*/true, 11564 /*Copying=*/false); 11565 if (Move.isInvalid()) { 11566 Diag(CurrentLocation, diag::note_member_synthesized_at) 11567 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11568 MoveAssignOperator->setInvalidDecl(); 11569 return; 11570 } 11571 11572 // Success! Record the move. 11573 Statements.push_back(Move.getAs<Expr>()); 11574 } 11575 11576 // Assign non-static members. 11577 for (auto *Field : ClassDecl->fields()) { 11578 // FIXME: We should form some kind of AST representation for the implied 11579 // memcpy in a union copy operation. 11580 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11581 continue; 11582 11583 if (Field->isInvalidDecl()) { 11584 Invalid = true; 11585 continue; 11586 } 11587 11588 // Check for members of reference type; we can't move those. 11589 if (Field->getType()->isReferenceType()) { 11590 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11591 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11592 Diag(Field->getLocation(), diag::note_declared_at); 11593 Diag(CurrentLocation, diag::note_member_synthesized_at) 11594 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11595 Invalid = true; 11596 continue; 11597 } 11598 11599 // Check for members of const-qualified, non-class type. 11600 QualType BaseType = Context.getBaseElementType(Field->getType()); 11601 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11602 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11603 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11604 Diag(Field->getLocation(), diag::note_declared_at); 11605 Diag(CurrentLocation, diag::note_member_synthesized_at) 11606 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11607 Invalid = true; 11608 continue; 11609 } 11610 11611 // Suppress assigning zero-width bitfields. 11612 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11613 continue; 11614 11615 QualType FieldType = Field->getType().getNonReferenceType(); 11616 if (FieldType->isIncompleteArrayType()) { 11617 assert(ClassDecl->hasFlexibleArrayMember() && 11618 "Incomplete array type is not valid"); 11619 continue; 11620 } 11621 11622 // Build references to the field in the object we're copying from and to. 11623 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11624 LookupMemberName); 11625 MemberLookup.addDecl(Field); 11626 MemberLookup.resolveKind(); 11627 MemberBuilder From(MoveOther, OtherRefType, 11628 /*IsArrow=*/false, MemberLookup); 11629 MemberBuilder To(This, getCurrentThisType(), 11630 /*IsArrow=*/true, MemberLookup); 11631 11632 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 11633 "Member reference with rvalue base must be rvalue except for reference " 11634 "members, which aren't allowed for move assignment."); 11635 11636 // Build the move of this field. 11637 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 11638 To, From, 11639 /*CopyingBaseSubobject=*/false, 11640 /*Copying=*/false); 11641 if (Move.isInvalid()) { 11642 Diag(CurrentLocation, diag::note_member_synthesized_at) 11643 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11644 MoveAssignOperator->setInvalidDecl(); 11645 return; 11646 } 11647 11648 // Success! Record the copy. 11649 Statements.push_back(Move.getAs<Stmt>()); 11650 } 11651 11652 if (!Invalid) { 11653 // Add a "return *this;" 11654 ExprResult ThisObj = 11655 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11656 11657 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11658 if (Return.isInvalid()) 11659 Invalid = true; 11660 else { 11661 Statements.push_back(Return.getAs<Stmt>()); 11662 11663 if (Trap.hasErrorOccurred()) { 11664 Diag(CurrentLocation, diag::note_member_synthesized_at) 11665 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 11666 Invalid = true; 11667 } 11668 } 11669 } 11670 11671 // The exception specification is needed because we are defining the 11672 // function. 11673 ResolveExceptionSpec(CurrentLocation, 11674 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11675 11676 if (Invalid) { 11677 MoveAssignOperator->setInvalidDecl(); 11678 return; 11679 } 11680 11681 StmtResult Body; 11682 { 11683 CompoundScopeRAII CompoundScope(*this); 11684 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11685 /*isStmtExpr=*/false); 11686 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11687 } 11688 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 11689 11690 if (ASTMutationListener *L = getASTMutationListener()) { 11691 L->CompletedImplicitDefinition(MoveAssignOperator); 11692 } 11693 } 11694 11695 Sema::ImplicitExceptionSpecification 11696 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 11697 CXXRecordDecl *ClassDecl = MD->getParent(); 11698 11699 ImplicitExceptionSpecification ExceptSpec(*this); 11700 if (ClassDecl->isInvalidDecl()) 11701 return ExceptSpec; 11702 11703 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 11704 assert(T->getNumParams() >= 1 && "not a copy ctor"); 11705 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 11706 11707 // C++ [except.spec]p14: 11708 // An implicitly declared special member function (Clause 12) shall have an 11709 // exception-specification. [...] 11710 for (const auto &Base : ClassDecl->bases()) { 11711 // Virtual bases are handled below. 11712 if (Base.isVirtual()) 11713 continue; 11714 11715 CXXRecordDecl *BaseClassDecl 11716 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11717 if (CXXConstructorDecl *CopyConstructor = 11718 LookupCopyingConstructor(BaseClassDecl, Quals)) 11719 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 11720 } 11721 for (const auto &Base : ClassDecl->vbases()) { 11722 CXXRecordDecl *BaseClassDecl 11723 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 11724 if (CXXConstructorDecl *CopyConstructor = 11725 LookupCopyingConstructor(BaseClassDecl, Quals)) 11726 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 11727 } 11728 for (const auto *Field : ClassDecl->fields()) { 11729 QualType FieldType = Context.getBaseElementType(Field->getType()); 11730 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 11731 if (CXXConstructorDecl *CopyConstructor = 11732 LookupCopyingConstructor(FieldClassDecl, 11733 Quals | FieldType.getCVRQualifiers())) 11734 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 11735 } 11736 } 11737 11738 return ExceptSpec; 11739 } 11740 11741 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 11742 CXXRecordDecl *ClassDecl) { 11743 // C++ [class.copy]p4: 11744 // If the class definition does not explicitly declare a copy 11745 // constructor, one is declared implicitly. 11746 assert(ClassDecl->needsImplicitCopyConstructor()); 11747 11748 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 11749 if (DSM.isAlreadyBeingDeclared()) 11750 return nullptr; 11751 11752 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11753 QualType ArgType = ClassType; 11754 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 11755 if (Const) 11756 ArgType = ArgType.withConst(); 11757 ArgType = Context.getLValueReferenceType(ArgType); 11758 11759 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11760 CXXCopyConstructor, 11761 Const); 11762 11763 DeclarationName Name 11764 = Context.DeclarationNames.getCXXConstructorName( 11765 Context.getCanonicalType(ClassType)); 11766 SourceLocation ClassLoc = ClassDecl->getLocation(); 11767 DeclarationNameInfo NameInfo(Name, ClassLoc); 11768 11769 // An implicitly-declared copy constructor is an inline public 11770 // member of its class. 11771 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 11772 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11773 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11774 Constexpr); 11775 CopyConstructor->setAccess(AS_public); 11776 CopyConstructor->setDefaulted(); 11777 11778 if (getLangOpts().CUDA) { 11779 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 11780 CopyConstructor, 11781 /* ConstRHS */ Const, 11782 /* Diagnose */ false); 11783 } 11784 11785 // Build an exception specification pointing back at this member. 11786 FunctionProtoType::ExtProtoInfo EPI = 11787 getImplicitMethodEPI(*this, CopyConstructor); 11788 CopyConstructor->setType( 11789 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11790 11791 // Add the parameter to the constructor. 11792 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 11793 ClassLoc, ClassLoc, 11794 /*IdentifierInfo=*/nullptr, 11795 ArgType, /*TInfo=*/nullptr, 11796 SC_None, nullptr); 11797 CopyConstructor->setParams(FromParam); 11798 11799 CopyConstructor->setTrivial( 11800 ClassDecl->needsOverloadResolutionForCopyConstructor() 11801 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 11802 : ClassDecl->hasTrivialCopyConstructor()); 11803 11804 // Note that we have declared this constructor. 11805 ++ASTContext::NumImplicitCopyConstructorsDeclared; 11806 11807 Scope *S = getScopeForContext(ClassDecl); 11808 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 11809 11810 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 11811 SetDeclDeleted(CopyConstructor, ClassLoc); 11812 11813 if (S) 11814 PushOnScopeChains(CopyConstructor, S, false); 11815 ClassDecl->addDecl(CopyConstructor); 11816 11817 return CopyConstructor; 11818 } 11819 11820 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 11821 CXXConstructorDecl *CopyConstructor) { 11822 assert((CopyConstructor->isDefaulted() && 11823 CopyConstructor->isCopyConstructor() && 11824 !CopyConstructor->doesThisDeclarationHaveABody() && 11825 !CopyConstructor->isDeleted()) && 11826 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 11827 11828 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 11829 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 11830 11831 // C++11 [class.copy]p7: 11832 // The [definition of an implicitly declared copy constructor] is 11833 // deprecated if the class has a user-declared copy assignment operator 11834 // or a user-declared destructor. 11835 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 11836 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 11837 11838 SynthesizedFunctionScope Scope(*this, CopyConstructor); 11839 DiagnosticErrorTrap Trap(Diags); 11840 11841 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 11842 Trap.hasErrorOccurred()) { 11843 Diag(CurrentLocation, diag::note_member_synthesized_at) 11844 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 11845 CopyConstructor->setInvalidDecl(); 11846 } else { 11847 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 11848 ? CopyConstructor->getLocEnd() 11849 : CopyConstructor->getLocation(); 11850 Sema::CompoundScopeRAII CompoundScope(*this); 11851 CopyConstructor->setBody( 11852 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 11853 } 11854 11855 // The exception specification is needed because we are defining the 11856 // function. 11857 ResolveExceptionSpec(CurrentLocation, 11858 CopyConstructor->getType()->castAs<FunctionProtoType>()); 11859 11860 CopyConstructor->markUsed(Context); 11861 MarkVTableUsed(CurrentLocation, ClassDecl); 11862 11863 if (ASTMutationListener *L = getASTMutationListener()) { 11864 L->CompletedImplicitDefinition(CopyConstructor); 11865 } 11866 } 11867 11868 Sema::ImplicitExceptionSpecification 11869 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 11870 CXXRecordDecl *ClassDecl = MD->getParent(); 11871 11872 // C++ [except.spec]p14: 11873 // An implicitly declared special member function (Clause 12) shall have an 11874 // exception-specification. [...] 11875 ImplicitExceptionSpecification ExceptSpec(*this); 11876 if (ClassDecl->isInvalidDecl()) 11877 return ExceptSpec; 11878 11879 // Direct base-class constructors. 11880 for (const auto &B : ClassDecl->bases()) { 11881 if (B.isVirtual()) // Handled below. 11882 continue; 11883 11884 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11885 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11886 CXXConstructorDecl *Constructor = 11887 LookupMovingConstructor(BaseClassDecl, 0); 11888 // If this is a deleted function, add it anyway. This might be conformant 11889 // with the standard. This might not. I'm not sure. It might not matter. 11890 if (Constructor) 11891 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11892 } 11893 } 11894 11895 // Virtual base-class constructors. 11896 for (const auto &B : ClassDecl->vbases()) { 11897 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 11898 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 11899 CXXConstructorDecl *Constructor = 11900 LookupMovingConstructor(BaseClassDecl, 0); 11901 // If this is a deleted function, add it anyway. This might be conformant 11902 // with the standard. This might not. I'm not sure. It might not matter. 11903 if (Constructor) 11904 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 11905 } 11906 } 11907 11908 // Field constructors. 11909 for (const auto *F : ClassDecl->fields()) { 11910 QualType FieldType = Context.getBaseElementType(F->getType()); 11911 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 11912 CXXConstructorDecl *Constructor = 11913 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 11914 // If this is a deleted function, add it anyway. This might be conformant 11915 // with the standard. This might not. I'm not sure. It might not matter. 11916 // In particular, the problem is that this function never gets called. It 11917 // might just be ill-formed because this function attempts to refer to 11918 // a deleted function here. 11919 if (Constructor) 11920 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 11921 } 11922 } 11923 11924 return ExceptSpec; 11925 } 11926 11927 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 11928 CXXRecordDecl *ClassDecl) { 11929 assert(ClassDecl->needsImplicitMoveConstructor()); 11930 11931 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 11932 if (DSM.isAlreadyBeingDeclared()) 11933 return nullptr; 11934 11935 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11936 QualType ArgType = Context.getRValueReferenceType(ClassType); 11937 11938 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11939 CXXMoveConstructor, 11940 false); 11941 11942 DeclarationName Name 11943 = Context.DeclarationNames.getCXXConstructorName( 11944 Context.getCanonicalType(ClassType)); 11945 SourceLocation ClassLoc = ClassDecl->getLocation(); 11946 DeclarationNameInfo NameInfo(Name, ClassLoc); 11947 11948 // C++11 [class.copy]p11: 11949 // An implicitly-declared copy/move constructor is an inline public 11950 // member of its class. 11951 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 11952 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11953 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11954 Constexpr); 11955 MoveConstructor->setAccess(AS_public); 11956 MoveConstructor->setDefaulted(); 11957 11958 if (getLangOpts().CUDA) { 11959 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 11960 MoveConstructor, 11961 /* ConstRHS */ false, 11962 /* Diagnose */ false); 11963 } 11964 11965 // Build an exception specification pointing back at this member. 11966 FunctionProtoType::ExtProtoInfo EPI = 11967 getImplicitMethodEPI(*this, MoveConstructor); 11968 MoveConstructor->setType( 11969 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11970 11971 // Add the parameter to the constructor. 11972 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 11973 ClassLoc, ClassLoc, 11974 /*IdentifierInfo=*/nullptr, 11975 ArgType, /*TInfo=*/nullptr, 11976 SC_None, nullptr); 11977 MoveConstructor->setParams(FromParam); 11978 11979 MoveConstructor->setTrivial( 11980 ClassDecl->needsOverloadResolutionForMoveConstructor() 11981 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 11982 : ClassDecl->hasTrivialMoveConstructor()); 11983 11984 // Note that we have declared this constructor. 11985 ++ASTContext::NumImplicitMoveConstructorsDeclared; 11986 11987 Scope *S = getScopeForContext(ClassDecl); 11988 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 11989 11990 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 11991 ClassDecl->setImplicitMoveConstructorIsDeleted(); 11992 SetDeclDeleted(MoveConstructor, ClassLoc); 11993 } 11994 11995 if (S) 11996 PushOnScopeChains(MoveConstructor, S, false); 11997 ClassDecl->addDecl(MoveConstructor); 11998 11999 return MoveConstructor; 12000 } 12001 12002 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12003 CXXConstructorDecl *MoveConstructor) { 12004 assert((MoveConstructor->isDefaulted() && 12005 MoveConstructor->isMoveConstructor() && 12006 !MoveConstructor->doesThisDeclarationHaveABody() && 12007 !MoveConstructor->isDeleted()) && 12008 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12009 12010 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12011 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12012 12013 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12014 DiagnosticErrorTrap Trap(Diags); 12015 12016 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 12017 Trap.hasErrorOccurred()) { 12018 Diag(CurrentLocation, diag::note_member_synthesized_at) 12019 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 12020 MoveConstructor->setInvalidDecl(); 12021 } else { 12022 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12023 ? MoveConstructor->getLocEnd() 12024 : MoveConstructor->getLocation(); 12025 Sema::CompoundScopeRAII CompoundScope(*this); 12026 MoveConstructor->setBody(ActOnCompoundStmt( 12027 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12028 } 12029 12030 // The exception specification is needed because we are defining the 12031 // function. 12032 ResolveExceptionSpec(CurrentLocation, 12033 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12034 12035 MoveConstructor->markUsed(Context); 12036 MarkVTableUsed(CurrentLocation, ClassDecl); 12037 12038 if (ASTMutationListener *L = getASTMutationListener()) { 12039 L->CompletedImplicitDefinition(MoveConstructor); 12040 } 12041 } 12042 12043 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12044 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12045 } 12046 12047 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12048 SourceLocation CurrentLocation, 12049 CXXConversionDecl *Conv) { 12050 CXXRecordDecl *Lambda = Conv->getParent(); 12051 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 12052 // If we are defining a specialization of a conversion to function-ptr 12053 // cache the deduced template arguments for this specialization 12054 // so that we can use them to retrieve the corresponding call-operator 12055 // and static-invoker. 12056 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 12057 12058 // Retrieve the corresponding call-operator specialization. 12059 if (Lambda->isGenericLambda()) { 12060 assert(Conv->isFunctionTemplateSpecialization()); 12061 FunctionTemplateDecl *CallOpTemplate = 12062 CallOp->getDescribedFunctionTemplate(); 12063 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 12064 void *InsertPos = nullptr; 12065 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 12066 DeducedTemplateArgs->asArray(), 12067 InsertPos); 12068 assert(CallOpSpec && 12069 "Conversion operator must have a corresponding call operator"); 12070 CallOp = cast<CXXMethodDecl>(CallOpSpec); 12071 } 12072 // Mark the call operator referenced (and add to pending instantiations 12073 // if necessary). 12074 // For both the conversion and static-invoker template specializations 12075 // we construct their body's in this function, so no need to add them 12076 // to the PendingInstantiations. 12077 MarkFunctionReferenced(CurrentLocation, CallOp); 12078 12079 SynthesizedFunctionScope Scope(*this, Conv); 12080 DiagnosticErrorTrap Trap(Diags); 12081 12082 // Retrieve the static invoker... 12083 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12084 // ... and get the corresponding specialization for a generic lambda. 12085 if (Lambda->isGenericLambda()) { 12086 assert(DeducedTemplateArgs && 12087 "Must have deduced template arguments from Conversion Operator"); 12088 FunctionTemplateDecl *InvokeTemplate = 12089 Invoker->getDescribedFunctionTemplate(); 12090 void *InsertPos = nullptr; 12091 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 12092 DeducedTemplateArgs->asArray(), 12093 InsertPos); 12094 assert(InvokeSpec && 12095 "Must have a corresponding static invoker specialization"); 12096 Invoker = cast<CXXMethodDecl>(InvokeSpec); 12097 } 12098 // Construct the body of the conversion function { return __invoke; }. 12099 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12100 VK_LValue, Conv->getLocation()).get(); 12101 assert(FunctionRef && "Can't refer to __invoke function?"); 12102 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12103 Conv->setBody(new (Context) CompoundStmt(Context, Return, 12104 Conv->getLocation(), 12105 Conv->getLocation())); 12106 12107 Conv->markUsed(Context); 12108 Conv->setReferenced(); 12109 12110 // Fill in the __invoke function with a dummy implementation. IR generation 12111 // will fill in the actual details. 12112 Invoker->markUsed(Context); 12113 Invoker->setReferenced(); 12114 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12115 12116 if (ASTMutationListener *L = getASTMutationListener()) { 12117 L->CompletedImplicitDefinition(Conv); 12118 L->CompletedImplicitDefinition(Invoker); 12119 } 12120 } 12121 12122 12123 12124 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12125 SourceLocation CurrentLocation, 12126 CXXConversionDecl *Conv) 12127 { 12128 assert(!Conv->getParent()->isGenericLambda()); 12129 12130 Conv->markUsed(Context); 12131 12132 SynthesizedFunctionScope Scope(*this, Conv); 12133 DiagnosticErrorTrap Trap(Diags); 12134 12135 // Copy-initialize the lambda object as needed to capture it. 12136 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12137 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12138 12139 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12140 Conv->getLocation(), 12141 Conv, DerefThis); 12142 12143 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12144 // behavior. Note that only the general conversion function does this 12145 // (since it's unusable otherwise); in the case where we inline the 12146 // block literal, it has block literal lifetime semantics. 12147 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12148 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12149 CK_CopyAndAutoreleaseBlockObject, 12150 BuildBlock.get(), nullptr, VK_RValue); 12151 12152 if (BuildBlock.isInvalid()) { 12153 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12154 Conv->setInvalidDecl(); 12155 return; 12156 } 12157 12158 // Create the return statement that returns the block from the conversion 12159 // function. 12160 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12161 if (Return.isInvalid()) { 12162 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12163 Conv->setInvalidDecl(); 12164 return; 12165 } 12166 12167 // Set the body of the conversion function. 12168 Stmt *ReturnS = Return.get(); 12169 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 12170 Conv->getLocation(), 12171 Conv->getLocation())); 12172 12173 // We're done; notify the mutation listener, if any. 12174 if (ASTMutationListener *L = getASTMutationListener()) { 12175 L->CompletedImplicitDefinition(Conv); 12176 } 12177 } 12178 12179 /// \brief Determine whether the given list arguments contains exactly one 12180 /// "real" (non-default) argument. 12181 static bool hasOneRealArgument(MultiExprArg Args) { 12182 switch (Args.size()) { 12183 case 0: 12184 return false; 12185 12186 default: 12187 if (!Args[1]->isDefaultArgument()) 12188 return false; 12189 12190 // fall through 12191 case 1: 12192 return !Args[0]->isDefaultArgument(); 12193 } 12194 12195 return false; 12196 } 12197 12198 ExprResult 12199 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12200 NamedDecl *FoundDecl, 12201 CXXConstructorDecl *Constructor, 12202 MultiExprArg ExprArgs, 12203 bool HadMultipleCandidates, 12204 bool IsListInitialization, 12205 bool IsStdInitListInitialization, 12206 bool RequiresZeroInit, 12207 unsigned ConstructKind, 12208 SourceRange ParenRange) { 12209 bool Elidable = false; 12210 12211 // C++0x [class.copy]p34: 12212 // When certain criteria are met, an implementation is allowed to 12213 // omit the copy/move construction of a class object, even if the 12214 // copy/move constructor and/or destructor for the object have 12215 // side effects. [...] 12216 // - when a temporary class object that has not been bound to a 12217 // reference (12.2) would be copied/moved to a class object 12218 // with the same cv-unqualified type, the copy/move operation 12219 // can be omitted by constructing the temporary object 12220 // directly into the target of the omitted copy/move 12221 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12222 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12223 Expr *SubExpr = ExprArgs[0]; 12224 Elidable = SubExpr->isTemporaryObject( 12225 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12226 } 12227 12228 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12229 FoundDecl, Constructor, 12230 Elidable, ExprArgs, HadMultipleCandidates, 12231 IsListInitialization, 12232 IsStdInitListInitialization, RequiresZeroInit, 12233 ConstructKind, ParenRange); 12234 } 12235 12236 ExprResult 12237 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12238 NamedDecl *FoundDecl, 12239 CXXConstructorDecl *Constructor, 12240 bool Elidable, 12241 MultiExprArg ExprArgs, 12242 bool HadMultipleCandidates, 12243 bool IsListInitialization, 12244 bool IsStdInitListInitialization, 12245 bool RequiresZeroInit, 12246 unsigned ConstructKind, 12247 SourceRange ParenRange) { 12248 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12249 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12250 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12251 return ExprError(); 12252 } 12253 12254 return BuildCXXConstructExpr( 12255 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12256 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12257 RequiresZeroInit, ConstructKind, ParenRange); 12258 } 12259 12260 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12261 /// including handling of its default argument expressions. 12262 ExprResult 12263 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12264 CXXConstructorDecl *Constructor, 12265 bool Elidable, 12266 MultiExprArg ExprArgs, 12267 bool HadMultipleCandidates, 12268 bool IsListInitialization, 12269 bool IsStdInitListInitialization, 12270 bool RequiresZeroInit, 12271 unsigned ConstructKind, 12272 SourceRange ParenRange) { 12273 assert(declaresSameEntity( 12274 Constructor->getParent(), 12275 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12276 "given constructor for wrong type"); 12277 MarkFunctionReferenced(ConstructLoc, Constructor); 12278 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12279 return ExprError(); 12280 12281 return CXXConstructExpr::Create( 12282 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12283 ExprArgs, HadMultipleCandidates, IsListInitialization, 12284 IsStdInitListInitialization, RequiresZeroInit, 12285 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12286 ParenRange); 12287 } 12288 12289 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12290 assert(Field->hasInClassInitializer()); 12291 12292 // If we already have the in-class initializer nothing needs to be done. 12293 if (Field->getInClassInitializer()) 12294 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12295 12296 // Maybe we haven't instantiated the in-class initializer. Go check the 12297 // pattern FieldDecl to see if it has one. 12298 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12299 12300 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12301 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12302 DeclContext::lookup_result Lookup = 12303 ClassPattern->lookup(Field->getDeclName()); 12304 12305 // Lookup can return at most two results: the pattern for the field, or the 12306 // injected class name of the parent record. No other member can have the 12307 // same name as the field. 12308 assert(!Lookup.empty() && Lookup.size() <= 2 && 12309 "more than two lookup results for field name"); 12310 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12311 if (!Pattern) { 12312 assert(isa<CXXRecordDecl>(Lookup[0]) && 12313 "cannot have other non-field member with same name"); 12314 Pattern = cast<FieldDecl>(Lookup[1]); 12315 } 12316 12317 if (InstantiateInClassInitializer(Loc, Field, Pattern, 12318 getTemplateInstantiationArgs(Field))) 12319 return ExprError(); 12320 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12321 } 12322 12323 // DR1351: 12324 // If the brace-or-equal-initializer of a non-static data member 12325 // invokes a defaulted default constructor of its class or of an 12326 // enclosing class in a potentially evaluated subexpression, the 12327 // program is ill-formed. 12328 // 12329 // This resolution is unworkable: the exception specification of the 12330 // default constructor can be needed in an unevaluated context, in 12331 // particular, in the operand of a noexcept-expression, and we can be 12332 // unable to compute an exception specification for an enclosed class. 12333 // 12334 // Any attempt to resolve the exception specification of a defaulted default 12335 // constructor before the initializer is lexically complete will ultimately 12336 // come here at which point we can diagnose it. 12337 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12338 if (OutermostClass == ParentRD) { 12339 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 12340 << ParentRD << Field; 12341 } else { 12342 Diag(Field->getLocEnd(), 12343 diag::err_in_class_initializer_not_yet_parsed_outer_class) 12344 << ParentRD << OutermostClass << Field; 12345 } 12346 12347 return ExprError(); 12348 } 12349 12350 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12351 if (VD->isInvalidDecl()) return; 12352 12353 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12354 if (ClassDecl->isInvalidDecl()) return; 12355 if (ClassDecl->hasIrrelevantDestructor()) return; 12356 if (ClassDecl->isDependentContext()) return; 12357 12358 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12359 MarkFunctionReferenced(VD->getLocation(), Destructor); 12360 CheckDestructorAccess(VD->getLocation(), Destructor, 12361 PDiag(diag::err_access_dtor_var) 12362 << VD->getDeclName() 12363 << VD->getType()); 12364 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12365 12366 if (Destructor->isTrivial()) return; 12367 if (!VD->hasGlobalStorage()) return; 12368 12369 // Emit warning for non-trivial dtor in global scope (a real global, 12370 // class-static, function-static). 12371 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12372 12373 // TODO: this should be re-enabled for static locals by !CXAAtExit 12374 if (!VD->isStaticLocal()) 12375 Diag(VD->getLocation(), diag::warn_global_destructor); 12376 } 12377 12378 /// \brief Given a constructor and the set of arguments provided for the 12379 /// constructor, convert the arguments and add any required default arguments 12380 /// to form a proper call to this constructor. 12381 /// 12382 /// \returns true if an error occurred, false otherwise. 12383 bool 12384 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12385 MultiExprArg ArgsPtr, 12386 SourceLocation Loc, 12387 SmallVectorImpl<Expr*> &ConvertedArgs, 12388 bool AllowExplicit, 12389 bool IsListInitialization) { 12390 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12391 unsigned NumArgs = ArgsPtr.size(); 12392 Expr **Args = ArgsPtr.data(); 12393 12394 const FunctionProtoType *Proto 12395 = Constructor->getType()->getAs<FunctionProtoType>(); 12396 assert(Proto && "Constructor without a prototype?"); 12397 unsigned NumParams = Proto->getNumParams(); 12398 12399 // If too few arguments are available, we'll fill in the rest with defaults. 12400 if (NumArgs < NumParams) 12401 ConvertedArgs.reserve(NumParams); 12402 else 12403 ConvertedArgs.reserve(NumArgs); 12404 12405 VariadicCallType CallType = 12406 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12407 SmallVector<Expr *, 8> AllArgs; 12408 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12409 Proto, 0, 12410 llvm::makeArrayRef(Args, NumArgs), 12411 AllArgs, 12412 CallType, AllowExplicit, 12413 IsListInitialization); 12414 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12415 12416 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12417 12418 CheckConstructorCall(Constructor, 12419 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12420 Proto, Loc); 12421 12422 return Invalid; 12423 } 12424 12425 static inline bool 12426 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12427 const FunctionDecl *FnDecl) { 12428 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12429 if (isa<NamespaceDecl>(DC)) { 12430 return SemaRef.Diag(FnDecl->getLocation(), 12431 diag::err_operator_new_delete_declared_in_namespace) 12432 << FnDecl->getDeclName(); 12433 } 12434 12435 if (isa<TranslationUnitDecl>(DC) && 12436 FnDecl->getStorageClass() == SC_Static) { 12437 return SemaRef.Diag(FnDecl->getLocation(), 12438 diag::err_operator_new_delete_declared_static) 12439 << FnDecl->getDeclName(); 12440 } 12441 12442 return false; 12443 } 12444 12445 static inline bool 12446 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12447 CanQualType ExpectedResultType, 12448 CanQualType ExpectedFirstParamType, 12449 unsigned DependentParamTypeDiag, 12450 unsigned InvalidParamTypeDiag) { 12451 QualType ResultType = 12452 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12453 12454 // Check that the result type is not dependent. 12455 if (ResultType->isDependentType()) 12456 return SemaRef.Diag(FnDecl->getLocation(), 12457 diag::err_operator_new_delete_dependent_result_type) 12458 << FnDecl->getDeclName() << ExpectedResultType; 12459 12460 // Check that the result type is what we expect. 12461 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12462 return SemaRef.Diag(FnDecl->getLocation(), 12463 diag::err_operator_new_delete_invalid_result_type) 12464 << FnDecl->getDeclName() << ExpectedResultType; 12465 12466 // A function template must have at least 2 parameters. 12467 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12468 return SemaRef.Diag(FnDecl->getLocation(), 12469 diag::err_operator_new_delete_template_too_few_parameters) 12470 << FnDecl->getDeclName(); 12471 12472 // The function decl must have at least 1 parameter. 12473 if (FnDecl->getNumParams() == 0) 12474 return SemaRef.Diag(FnDecl->getLocation(), 12475 diag::err_operator_new_delete_too_few_parameters) 12476 << FnDecl->getDeclName(); 12477 12478 // Check the first parameter type is not dependent. 12479 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12480 if (FirstParamType->isDependentType()) 12481 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12482 << FnDecl->getDeclName() << ExpectedFirstParamType; 12483 12484 // Check that the first parameter type is what we expect. 12485 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12486 ExpectedFirstParamType) 12487 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12488 << FnDecl->getDeclName() << ExpectedFirstParamType; 12489 12490 return false; 12491 } 12492 12493 static bool 12494 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12495 // C++ [basic.stc.dynamic.allocation]p1: 12496 // A program is ill-formed if an allocation function is declared in a 12497 // namespace scope other than global scope or declared static in global 12498 // scope. 12499 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12500 return true; 12501 12502 CanQualType SizeTy = 12503 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12504 12505 // C++ [basic.stc.dynamic.allocation]p1: 12506 // The return type shall be void*. The first parameter shall have type 12507 // std::size_t. 12508 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12509 SizeTy, 12510 diag::err_operator_new_dependent_param_type, 12511 diag::err_operator_new_param_type)) 12512 return true; 12513 12514 // C++ [basic.stc.dynamic.allocation]p1: 12515 // The first parameter shall not have an associated default argument. 12516 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12517 return SemaRef.Diag(FnDecl->getLocation(), 12518 diag::err_operator_new_default_arg) 12519 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12520 12521 return false; 12522 } 12523 12524 static bool 12525 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12526 // C++ [basic.stc.dynamic.deallocation]p1: 12527 // A program is ill-formed if deallocation functions are declared in a 12528 // namespace scope other than global scope or declared static in global 12529 // scope. 12530 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12531 return true; 12532 12533 // C++ [basic.stc.dynamic.deallocation]p2: 12534 // Each deallocation function shall return void and its first parameter 12535 // shall be void*. 12536 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 12537 SemaRef.Context.VoidPtrTy, 12538 diag::err_operator_delete_dependent_param_type, 12539 diag::err_operator_delete_param_type)) 12540 return true; 12541 12542 return false; 12543 } 12544 12545 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12546 /// of this overloaded operator is well-formed. If so, returns false; 12547 /// otherwise, emits appropriate diagnostics and returns true. 12548 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12549 assert(FnDecl && FnDecl->isOverloadedOperator() && 12550 "Expected an overloaded operator declaration"); 12551 12552 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12553 12554 // C++ [over.oper]p5: 12555 // The allocation and deallocation functions, operator new, 12556 // operator new[], operator delete and operator delete[], are 12557 // described completely in 3.7.3. The attributes and restrictions 12558 // found in the rest of this subclause do not apply to them unless 12559 // explicitly stated in 3.7.3. 12560 if (Op == OO_Delete || Op == OO_Array_Delete) 12561 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12562 12563 if (Op == OO_New || Op == OO_Array_New) 12564 return CheckOperatorNewDeclaration(*this, FnDecl); 12565 12566 // C++ [over.oper]p6: 12567 // An operator function shall either be a non-static member 12568 // function or be a non-member function and have at least one 12569 // parameter whose type is a class, a reference to a class, an 12570 // enumeration, or a reference to an enumeration. 12571 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12572 if (MethodDecl->isStatic()) 12573 return Diag(FnDecl->getLocation(), 12574 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12575 } else { 12576 bool ClassOrEnumParam = false; 12577 for (auto Param : FnDecl->parameters()) { 12578 QualType ParamType = Param->getType().getNonReferenceType(); 12579 if (ParamType->isDependentType() || ParamType->isRecordType() || 12580 ParamType->isEnumeralType()) { 12581 ClassOrEnumParam = true; 12582 break; 12583 } 12584 } 12585 12586 if (!ClassOrEnumParam) 12587 return Diag(FnDecl->getLocation(), 12588 diag::err_operator_overload_needs_class_or_enum) 12589 << FnDecl->getDeclName(); 12590 } 12591 12592 // C++ [over.oper]p8: 12593 // An operator function cannot have default arguments (8.3.6), 12594 // except where explicitly stated below. 12595 // 12596 // Only the function-call operator allows default arguments 12597 // (C++ [over.call]p1). 12598 if (Op != OO_Call) { 12599 for (auto Param : FnDecl->parameters()) { 12600 if (Param->hasDefaultArg()) 12601 return Diag(Param->getLocation(), 12602 diag::err_operator_overload_default_arg) 12603 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12604 } 12605 } 12606 12607 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12608 { false, false, false } 12609 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12610 , { Unary, Binary, MemberOnly } 12611 #include "clang/Basic/OperatorKinds.def" 12612 }; 12613 12614 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12615 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12616 bool MustBeMemberOperator = OperatorUses[Op][2]; 12617 12618 // C++ [over.oper]p8: 12619 // [...] Operator functions cannot have more or fewer parameters 12620 // than the number required for the corresponding operator, as 12621 // described in the rest of this subclause. 12622 unsigned NumParams = FnDecl->getNumParams() 12623 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12624 if (Op != OO_Call && 12625 ((NumParams == 1 && !CanBeUnaryOperator) || 12626 (NumParams == 2 && !CanBeBinaryOperator) || 12627 (NumParams < 1) || (NumParams > 2))) { 12628 // We have the wrong number of parameters. 12629 unsigned ErrorKind; 12630 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12631 ErrorKind = 2; // 2 -> unary or binary. 12632 } else if (CanBeUnaryOperator) { 12633 ErrorKind = 0; // 0 -> unary 12634 } else { 12635 assert(CanBeBinaryOperator && 12636 "All non-call overloaded operators are unary or binary!"); 12637 ErrorKind = 1; // 1 -> binary 12638 } 12639 12640 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12641 << FnDecl->getDeclName() << NumParams << ErrorKind; 12642 } 12643 12644 // Overloaded operators other than operator() cannot be variadic. 12645 if (Op != OO_Call && 12646 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12647 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12648 << FnDecl->getDeclName(); 12649 } 12650 12651 // Some operators must be non-static member functions. 12652 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12653 return Diag(FnDecl->getLocation(), 12654 diag::err_operator_overload_must_be_member) 12655 << FnDecl->getDeclName(); 12656 } 12657 12658 // C++ [over.inc]p1: 12659 // The user-defined function called operator++ implements the 12660 // prefix and postfix ++ operator. If this function is a member 12661 // function with no parameters, or a non-member function with one 12662 // parameter of class or enumeration type, it defines the prefix 12663 // increment operator ++ for objects of that type. If the function 12664 // is a member function with one parameter (which shall be of type 12665 // int) or a non-member function with two parameters (the second 12666 // of which shall be of type int), it defines the postfix 12667 // increment operator ++ for objects of that type. 12668 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12669 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12670 QualType ParamType = LastParam->getType(); 12671 12672 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12673 !ParamType->isDependentType()) 12674 return Diag(LastParam->getLocation(), 12675 diag::err_operator_overload_post_incdec_must_be_int) 12676 << LastParam->getType() << (Op == OO_MinusMinus); 12677 } 12678 12679 return false; 12680 } 12681 12682 static bool 12683 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 12684 FunctionTemplateDecl *TpDecl) { 12685 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 12686 12687 // Must have one or two template parameters. 12688 if (TemplateParams->size() == 1) { 12689 NonTypeTemplateParmDecl *PmDecl = 12690 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 12691 12692 // The template parameter must be a char parameter pack. 12693 if (PmDecl && PmDecl->isTemplateParameterPack() && 12694 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 12695 return false; 12696 12697 } else if (TemplateParams->size() == 2) { 12698 TemplateTypeParmDecl *PmType = 12699 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 12700 NonTypeTemplateParmDecl *PmArgs = 12701 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 12702 12703 // The second template parameter must be a parameter pack with the 12704 // first template parameter as its type. 12705 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 12706 PmArgs->isTemplateParameterPack()) { 12707 const TemplateTypeParmType *TArgs = 12708 PmArgs->getType()->getAs<TemplateTypeParmType>(); 12709 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 12710 TArgs->getIndex() == PmType->getIndex()) { 12711 if (SemaRef.ActiveTemplateInstantiations.empty()) 12712 SemaRef.Diag(TpDecl->getLocation(), 12713 diag::ext_string_literal_operator_template); 12714 return false; 12715 } 12716 } 12717 } 12718 12719 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 12720 diag::err_literal_operator_template) 12721 << TpDecl->getTemplateParameters()->getSourceRange(); 12722 return true; 12723 } 12724 12725 /// CheckLiteralOperatorDeclaration - Check whether the declaration 12726 /// of this literal operator function is well-formed. If so, returns 12727 /// false; otherwise, emits appropriate diagnostics and returns true. 12728 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 12729 if (isa<CXXMethodDecl>(FnDecl)) { 12730 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 12731 << FnDecl->getDeclName(); 12732 return true; 12733 } 12734 12735 if (FnDecl->isExternC()) { 12736 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 12737 return true; 12738 } 12739 12740 // This might be the definition of a literal operator template. 12741 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 12742 12743 // This might be a specialization of a literal operator template. 12744 if (!TpDecl) 12745 TpDecl = FnDecl->getPrimaryTemplate(); 12746 12747 // template <char...> type operator "" name() and 12748 // template <class T, T...> type operator "" name() are the only valid 12749 // template signatures, and the only valid signatures with no parameters. 12750 if (TpDecl) { 12751 if (FnDecl->param_size() != 0) { 12752 Diag(FnDecl->getLocation(), 12753 diag::err_literal_operator_template_with_params); 12754 return true; 12755 } 12756 12757 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 12758 return true; 12759 12760 } else if (FnDecl->param_size() == 1) { 12761 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 12762 12763 QualType ParamType = Param->getType().getUnqualifiedType(); 12764 12765 // Only unsigned long long int, long double, any character type, and const 12766 // char * are allowed as the only parameters. 12767 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 12768 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 12769 Context.hasSameType(ParamType, Context.CharTy) || 12770 Context.hasSameType(ParamType, Context.WideCharTy) || 12771 Context.hasSameType(ParamType, Context.Char16Ty) || 12772 Context.hasSameType(ParamType, Context.Char32Ty)) { 12773 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 12774 QualType InnerType = Ptr->getPointeeType(); 12775 12776 // Pointer parameter must be a const char *. 12777 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 12778 Context.CharTy) && 12779 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 12780 Diag(Param->getSourceRange().getBegin(), 12781 diag::err_literal_operator_param) 12782 << ParamType << "'const char *'" << Param->getSourceRange(); 12783 return true; 12784 } 12785 12786 } else if (ParamType->isRealFloatingType()) { 12787 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12788 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 12789 return true; 12790 12791 } else if (ParamType->isIntegerType()) { 12792 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12793 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 12794 return true; 12795 12796 } else { 12797 Diag(Param->getSourceRange().getBegin(), 12798 diag::err_literal_operator_invalid_param) 12799 << ParamType << Param->getSourceRange(); 12800 return true; 12801 } 12802 12803 } else if (FnDecl->param_size() == 2) { 12804 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 12805 12806 // First, verify that the first parameter is correct. 12807 12808 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 12809 12810 // Two parameter function must have a pointer to const as a 12811 // first parameter; let's strip those qualifiers. 12812 const PointerType *PT = FirstParamType->getAs<PointerType>(); 12813 12814 if (!PT) { 12815 Diag((*Param)->getSourceRange().getBegin(), 12816 diag::err_literal_operator_param) 12817 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12818 return true; 12819 } 12820 12821 QualType PointeeType = PT->getPointeeType(); 12822 // First parameter must be const 12823 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 12824 Diag((*Param)->getSourceRange().getBegin(), 12825 diag::err_literal_operator_param) 12826 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12827 return true; 12828 } 12829 12830 QualType InnerType = PointeeType.getUnqualifiedType(); 12831 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 12832 // are allowed as the first parameter to a two-parameter function 12833 if (!(Context.hasSameType(InnerType, Context.CharTy) || 12834 Context.hasSameType(InnerType, Context.WideCharTy) || 12835 Context.hasSameType(InnerType, Context.Char16Ty) || 12836 Context.hasSameType(InnerType, Context.Char32Ty))) { 12837 Diag((*Param)->getSourceRange().getBegin(), 12838 diag::err_literal_operator_param) 12839 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12840 return true; 12841 } 12842 12843 // Move on to the second and final parameter. 12844 ++Param; 12845 12846 // The second parameter must be a std::size_t. 12847 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 12848 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 12849 Diag((*Param)->getSourceRange().getBegin(), 12850 diag::err_literal_operator_param) 12851 << SecondParamType << Context.getSizeType() 12852 << (*Param)->getSourceRange(); 12853 return true; 12854 } 12855 } else { 12856 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 12857 return true; 12858 } 12859 12860 // Parameters are good. 12861 12862 // A parameter-declaration-clause containing a default argument is not 12863 // equivalent to any of the permitted forms. 12864 for (auto Param : FnDecl->parameters()) { 12865 if (Param->hasDefaultArg()) { 12866 Diag(Param->getDefaultArgRange().getBegin(), 12867 diag::err_literal_operator_default_argument) 12868 << Param->getDefaultArgRange(); 12869 break; 12870 } 12871 } 12872 12873 StringRef LiteralName 12874 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 12875 if (LiteralName[0] != '_') { 12876 // C++11 [usrlit.suffix]p1: 12877 // Literal suffix identifiers that do not start with an underscore 12878 // are reserved for future standardization. 12879 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 12880 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 12881 } 12882 12883 return false; 12884 } 12885 12886 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 12887 /// linkage specification, including the language and (if present) 12888 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 12889 /// language string literal. LBraceLoc, if valid, provides the location of 12890 /// the '{' brace. Otherwise, this linkage specification does not 12891 /// have any braces. 12892 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 12893 Expr *LangStr, 12894 SourceLocation LBraceLoc) { 12895 StringLiteral *Lit = cast<StringLiteral>(LangStr); 12896 if (!Lit->isAscii()) { 12897 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 12898 << LangStr->getSourceRange(); 12899 return nullptr; 12900 } 12901 12902 StringRef Lang = Lit->getString(); 12903 LinkageSpecDecl::LanguageIDs Language; 12904 if (Lang == "C") 12905 Language = LinkageSpecDecl::lang_c; 12906 else if (Lang == "C++") 12907 Language = LinkageSpecDecl::lang_cxx; 12908 else { 12909 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 12910 << LangStr->getSourceRange(); 12911 return nullptr; 12912 } 12913 12914 // FIXME: Add all the various semantics of linkage specifications 12915 12916 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 12917 LangStr->getExprLoc(), Language, 12918 LBraceLoc.isValid()); 12919 CurContext->addDecl(D); 12920 PushDeclContext(S, D); 12921 return D; 12922 } 12923 12924 /// ActOnFinishLinkageSpecification - Complete the definition of 12925 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 12926 /// valid, it's the position of the closing '}' brace in a linkage 12927 /// specification that uses braces. 12928 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 12929 Decl *LinkageSpec, 12930 SourceLocation RBraceLoc) { 12931 if (RBraceLoc.isValid()) { 12932 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 12933 LSDecl->setRBraceLoc(RBraceLoc); 12934 } 12935 PopDeclContext(); 12936 return LinkageSpec; 12937 } 12938 12939 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 12940 AttributeList *AttrList, 12941 SourceLocation SemiLoc) { 12942 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 12943 // Attribute declarations appertain to empty declaration so we handle 12944 // them here. 12945 if (AttrList) 12946 ProcessDeclAttributeList(S, ED, AttrList); 12947 12948 CurContext->addDecl(ED); 12949 return ED; 12950 } 12951 12952 /// \brief Perform semantic analysis for the variable declaration that 12953 /// occurs within a C++ catch clause, returning the newly-created 12954 /// variable. 12955 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 12956 TypeSourceInfo *TInfo, 12957 SourceLocation StartLoc, 12958 SourceLocation Loc, 12959 IdentifierInfo *Name) { 12960 bool Invalid = false; 12961 QualType ExDeclType = TInfo->getType(); 12962 12963 // Arrays and functions decay. 12964 if (ExDeclType->isArrayType()) 12965 ExDeclType = Context.getArrayDecayedType(ExDeclType); 12966 else if (ExDeclType->isFunctionType()) 12967 ExDeclType = Context.getPointerType(ExDeclType); 12968 12969 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 12970 // The exception-declaration shall not denote a pointer or reference to an 12971 // incomplete type, other than [cv] void*. 12972 // N2844 forbids rvalue references. 12973 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 12974 Diag(Loc, diag::err_catch_rvalue_ref); 12975 Invalid = true; 12976 } 12977 12978 if (ExDeclType->isVariablyModifiedType()) { 12979 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 12980 Invalid = true; 12981 } 12982 12983 QualType BaseType = ExDeclType; 12984 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 12985 unsigned DK = diag::err_catch_incomplete; 12986 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 12987 BaseType = Ptr->getPointeeType(); 12988 Mode = 1; 12989 DK = diag::err_catch_incomplete_ptr; 12990 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 12991 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 12992 BaseType = Ref->getPointeeType(); 12993 Mode = 2; 12994 DK = diag::err_catch_incomplete_ref; 12995 } 12996 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 12997 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 12998 Invalid = true; 12999 13000 if (!Invalid && !ExDeclType->isDependentType() && 13001 RequireNonAbstractType(Loc, ExDeclType, 13002 diag::err_abstract_type_in_decl, 13003 AbstractVariableType)) 13004 Invalid = true; 13005 13006 // Only the non-fragile NeXT runtime currently supports C++ catches 13007 // of ObjC types, and no runtime supports catching ObjC types by value. 13008 if (!Invalid && getLangOpts().ObjC1) { 13009 QualType T = ExDeclType; 13010 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13011 T = RT->getPointeeType(); 13012 13013 if (T->isObjCObjectType()) { 13014 Diag(Loc, diag::err_objc_object_catch); 13015 Invalid = true; 13016 } else if (T->isObjCObjectPointerType()) { 13017 // FIXME: should this be a test for macosx-fragile specifically? 13018 if (getLangOpts().ObjCRuntime.isFragile()) 13019 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13020 } 13021 } 13022 13023 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13024 ExDeclType, TInfo, SC_None); 13025 ExDecl->setExceptionVariable(true); 13026 13027 // In ARC, infer 'retaining' for variables of retainable type. 13028 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13029 Invalid = true; 13030 13031 if (!Invalid && !ExDeclType->isDependentType()) { 13032 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13033 // Insulate this from anything else we might currently be parsing. 13034 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 13035 13036 // C++ [except.handle]p16: 13037 // The object declared in an exception-declaration or, if the 13038 // exception-declaration does not specify a name, a temporary (12.2) is 13039 // copy-initialized (8.5) from the exception object. [...] 13040 // The object is destroyed when the handler exits, after the destruction 13041 // of any automatic objects initialized within the handler. 13042 // 13043 // We just pretend to initialize the object with itself, then make sure 13044 // it can be destroyed later. 13045 QualType initType = Context.getExceptionObjectType(ExDeclType); 13046 13047 InitializedEntity entity = 13048 InitializedEntity::InitializeVariable(ExDecl); 13049 InitializationKind initKind = 13050 InitializationKind::CreateCopy(Loc, SourceLocation()); 13051 13052 Expr *opaqueValue = 13053 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13054 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13055 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13056 if (result.isInvalid()) 13057 Invalid = true; 13058 else { 13059 // If the constructor used was non-trivial, set this as the 13060 // "initializer". 13061 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13062 if (!construct->getConstructor()->isTrivial()) { 13063 Expr *init = MaybeCreateExprWithCleanups(construct); 13064 ExDecl->setInit(init); 13065 } 13066 13067 // And make sure it's destructable. 13068 FinalizeVarWithDestructor(ExDecl, recordType); 13069 } 13070 } 13071 } 13072 13073 if (Invalid) 13074 ExDecl->setInvalidDecl(); 13075 13076 return ExDecl; 13077 } 13078 13079 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13080 /// handler. 13081 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13082 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13083 bool Invalid = D.isInvalidType(); 13084 13085 // Check for unexpanded parameter packs. 13086 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13087 UPPC_ExceptionType)) { 13088 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13089 D.getIdentifierLoc()); 13090 Invalid = true; 13091 } 13092 13093 IdentifierInfo *II = D.getIdentifier(); 13094 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13095 LookupOrdinaryName, 13096 ForRedeclaration)) { 13097 // The scope should be freshly made just for us. There is just no way 13098 // it contains any previous declaration, except for function parameters in 13099 // a function-try-block's catch statement. 13100 assert(!S->isDeclScope(PrevDecl)); 13101 if (isDeclInScope(PrevDecl, CurContext, S)) { 13102 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13103 << D.getIdentifier(); 13104 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13105 Invalid = true; 13106 } else if (PrevDecl->isTemplateParameter()) 13107 // Maybe we will complain about the shadowed template parameter. 13108 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13109 } 13110 13111 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13112 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13113 << D.getCXXScopeSpec().getRange(); 13114 Invalid = true; 13115 } 13116 13117 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13118 D.getLocStart(), 13119 D.getIdentifierLoc(), 13120 D.getIdentifier()); 13121 if (Invalid) 13122 ExDecl->setInvalidDecl(); 13123 13124 // Add the exception declaration into this scope. 13125 if (II) 13126 PushOnScopeChains(ExDecl, S); 13127 else 13128 CurContext->addDecl(ExDecl); 13129 13130 ProcessDeclAttributes(S, ExDecl, D); 13131 return ExDecl; 13132 } 13133 13134 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13135 Expr *AssertExpr, 13136 Expr *AssertMessageExpr, 13137 SourceLocation RParenLoc) { 13138 StringLiteral *AssertMessage = 13139 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13140 13141 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13142 return nullptr; 13143 13144 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13145 AssertMessage, RParenLoc, false); 13146 } 13147 13148 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13149 Expr *AssertExpr, 13150 StringLiteral *AssertMessage, 13151 SourceLocation RParenLoc, 13152 bool Failed) { 13153 assert(AssertExpr != nullptr && "Expected non-null condition"); 13154 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13155 !Failed) { 13156 // In a static_assert-declaration, the constant-expression shall be a 13157 // constant expression that can be contextually converted to bool. 13158 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13159 if (Converted.isInvalid()) 13160 Failed = true; 13161 13162 llvm::APSInt Cond; 13163 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13164 diag::err_static_assert_expression_is_not_constant, 13165 /*AllowFold=*/false).isInvalid()) 13166 Failed = true; 13167 13168 if (!Failed && !Cond) { 13169 SmallString<256> MsgBuffer; 13170 llvm::raw_svector_ostream Msg(MsgBuffer); 13171 if (AssertMessage) 13172 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13173 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13174 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13175 Failed = true; 13176 } 13177 } 13178 13179 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13180 AssertExpr, AssertMessage, RParenLoc, 13181 Failed); 13182 13183 CurContext->addDecl(Decl); 13184 return Decl; 13185 } 13186 13187 /// \brief Perform semantic analysis of the given friend type declaration. 13188 /// 13189 /// \returns A friend declaration that. 13190 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13191 SourceLocation FriendLoc, 13192 TypeSourceInfo *TSInfo) { 13193 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13194 13195 QualType T = TSInfo->getType(); 13196 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13197 13198 // C++03 [class.friend]p2: 13199 // An elaborated-type-specifier shall be used in a friend declaration 13200 // for a class.* 13201 // 13202 // * The class-key of the elaborated-type-specifier is required. 13203 if (!ActiveTemplateInstantiations.empty()) { 13204 // Do not complain about the form of friend template types during 13205 // template instantiation; we will already have complained when the 13206 // template was declared. 13207 } else { 13208 if (!T->isElaboratedTypeSpecifier()) { 13209 // If we evaluated the type to a record type, suggest putting 13210 // a tag in front. 13211 if (const RecordType *RT = T->getAs<RecordType>()) { 13212 RecordDecl *RD = RT->getDecl(); 13213 13214 SmallString<16> InsertionText(" "); 13215 InsertionText += RD->getKindName(); 13216 13217 Diag(TypeRange.getBegin(), 13218 getLangOpts().CPlusPlus11 ? 13219 diag::warn_cxx98_compat_unelaborated_friend_type : 13220 diag::ext_unelaborated_friend_type) 13221 << (unsigned) RD->getTagKind() 13222 << T 13223 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13224 InsertionText); 13225 } else { 13226 Diag(FriendLoc, 13227 getLangOpts().CPlusPlus11 ? 13228 diag::warn_cxx98_compat_nonclass_type_friend : 13229 diag::ext_nonclass_type_friend) 13230 << T 13231 << TypeRange; 13232 } 13233 } else if (T->getAs<EnumType>()) { 13234 Diag(FriendLoc, 13235 getLangOpts().CPlusPlus11 ? 13236 diag::warn_cxx98_compat_enum_friend : 13237 diag::ext_enum_friend) 13238 << T 13239 << TypeRange; 13240 } 13241 13242 // C++11 [class.friend]p3: 13243 // A friend declaration that does not declare a function shall have one 13244 // of the following forms: 13245 // friend elaborated-type-specifier ; 13246 // friend simple-type-specifier ; 13247 // friend typename-specifier ; 13248 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13249 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13250 } 13251 13252 // If the type specifier in a friend declaration designates a (possibly 13253 // cv-qualified) class type, that class is declared as a friend; otherwise, 13254 // the friend declaration is ignored. 13255 return FriendDecl::Create(Context, CurContext, 13256 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13257 FriendLoc); 13258 } 13259 13260 /// Handle a friend tag declaration where the scope specifier was 13261 /// templated. 13262 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13263 unsigned TagSpec, SourceLocation TagLoc, 13264 CXXScopeSpec &SS, 13265 IdentifierInfo *Name, 13266 SourceLocation NameLoc, 13267 AttributeList *Attr, 13268 MultiTemplateParamsArg TempParamLists) { 13269 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13270 13271 bool isExplicitSpecialization = false; 13272 bool Invalid = false; 13273 13274 if (TemplateParameterList *TemplateParams = 13275 MatchTemplateParametersToScopeSpecifier( 13276 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13277 isExplicitSpecialization, Invalid)) { 13278 if (TemplateParams->size() > 0) { 13279 // This is a declaration of a class template. 13280 if (Invalid) 13281 return nullptr; 13282 13283 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13284 NameLoc, Attr, TemplateParams, AS_public, 13285 /*ModulePrivateLoc=*/SourceLocation(), 13286 FriendLoc, TempParamLists.size() - 1, 13287 TempParamLists.data()).get(); 13288 } else { 13289 // The "template<>" header is extraneous. 13290 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13291 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13292 isExplicitSpecialization = true; 13293 } 13294 } 13295 13296 if (Invalid) return nullptr; 13297 13298 bool isAllExplicitSpecializations = true; 13299 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13300 if (TempParamLists[I]->size()) { 13301 isAllExplicitSpecializations = false; 13302 break; 13303 } 13304 } 13305 13306 // FIXME: don't ignore attributes. 13307 13308 // If it's explicit specializations all the way down, just forget 13309 // about the template header and build an appropriate non-templated 13310 // friend. TODO: for source fidelity, remember the headers. 13311 if (isAllExplicitSpecializations) { 13312 if (SS.isEmpty()) { 13313 bool Owned = false; 13314 bool IsDependent = false; 13315 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13316 Attr, AS_public, 13317 /*ModulePrivateLoc=*/SourceLocation(), 13318 MultiTemplateParamsArg(), Owned, IsDependent, 13319 /*ScopedEnumKWLoc=*/SourceLocation(), 13320 /*ScopedEnumUsesClassTag=*/false, 13321 /*UnderlyingType=*/TypeResult(), 13322 /*IsTypeSpecifier=*/false); 13323 } 13324 13325 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13326 ElaboratedTypeKeyword Keyword 13327 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13328 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13329 *Name, NameLoc); 13330 if (T.isNull()) 13331 return nullptr; 13332 13333 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13334 if (isa<DependentNameType>(T)) { 13335 DependentNameTypeLoc TL = 13336 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13337 TL.setElaboratedKeywordLoc(TagLoc); 13338 TL.setQualifierLoc(QualifierLoc); 13339 TL.setNameLoc(NameLoc); 13340 } else { 13341 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13342 TL.setElaboratedKeywordLoc(TagLoc); 13343 TL.setQualifierLoc(QualifierLoc); 13344 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13345 } 13346 13347 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13348 TSI, FriendLoc, TempParamLists); 13349 Friend->setAccess(AS_public); 13350 CurContext->addDecl(Friend); 13351 return Friend; 13352 } 13353 13354 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13355 13356 13357 13358 // Handle the case of a templated-scope friend class. e.g. 13359 // template <class T> class A<T>::B; 13360 // FIXME: we don't support these right now. 13361 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13362 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13363 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13364 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13365 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13366 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13367 TL.setElaboratedKeywordLoc(TagLoc); 13368 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13369 TL.setNameLoc(NameLoc); 13370 13371 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13372 TSI, FriendLoc, TempParamLists); 13373 Friend->setAccess(AS_public); 13374 Friend->setUnsupportedFriend(true); 13375 CurContext->addDecl(Friend); 13376 return Friend; 13377 } 13378 13379 13380 /// Handle a friend type declaration. This works in tandem with 13381 /// ActOnTag. 13382 /// 13383 /// Notes on friend class templates: 13384 /// 13385 /// We generally treat friend class declarations as if they were 13386 /// declaring a class. So, for example, the elaborated type specifier 13387 /// in a friend declaration is required to obey the restrictions of a 13388 /// class-head (i.e. no typedefs in the scope chain), template 13389 /// parameters are required to match up with simple template-ids, &c. 13390 /// However, unlike when declaring a template specialization, it's 13391 /// okay to refer to a template specialization without an empty 13392 /// template parameter declaration, e.g. 13393 /// friend class A<T>::B<unsigned>; 13394 /// We permit this as a special case; if there are any template 13395 /// parameters present at all, require proper matching, i.e. 13396 /// template <> template \<class T> friend class A<int>::B; 13397 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13398 MultiTemplateParamsArg TempParams) { 13399 SourceLocation Loc = DS.getLocStart(); 13400 13401 assert(DS.isFriendSpecified()); 13402 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13403 13404 // Try to convert the decl specifier to a type. This works for 13405 // friend templates because ActOnTag never produces a ClassTemplateDecl 13406 // for a TUK_Friend. 13407 Declarator TheDeclarator(DS, Declarator::MemberContext); 13408 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13409 QualType T = TSI->getType(); 13410 if (TheDeclarator.isInvalidType()) 13411 return nullptr; 13412 13413 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13414 return nullptr; 13415 13416 // This is definitely an error in C++98. It's probably meant to 13417 // be forbidden in C++0x, too, but the specification is just 13418 // poorly written. 13419 // 13420 // The problem is with declarations like the following: 13421 // template <T> friend A<T>::foo; 13422 // where deciding whether a class C is a friend or not now hinges 13423 // on whether there exists an instantiation of A that causes 13424 // 'foo' to equal C. There are restrictions on class-heads 13425 // (which we declare (by fiat) elaborated friend declarations to 13426 // be) that makes this tractable. 13427 // 13428 // FIXME: handle "template <> friend class A<T>;", which 13429 // is possibly well-formed? Who even knows? 13430 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13431 Diag(Loc, diag::err_tagless_friend_type_template) 13432 << DS.getSourceRange(); 13433 return nullptr; 13434 } 13435 13436 // C++98 [class.friend]p1: A friend of a class is a function 13437 // or class that is not a member of the class . . . 13438 // This is fixed in DR77, which just barely didn't make the C++03 13439 // deadline. It's also a very silly restriction that seriously 13440 // affects inner classes and which nobody else seems to implement; 13441 // thus we never diagnose it, not even in -pedantic. 13442 // 13443 // But note that we could warn about it: it's always useless to 13444 // friend one of your own members (it's not, however, worthless to 13445 // friend a member of an arbitrary specialization of your template). 13446 13447 Decl *D; 13448 if (!TempParams.empty()) 13449 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13450 TempParams, 13451 TSI, 13452 DS.getFriendSpecLoc()); 13453 else 13454 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13455 13456 if (!D) 13457 return nullptr; 13458 13459 D->setAccess(AS_public); 13460 CurContext->addDecl(D); 13461 13462 return D; 13463 } 13464 13465 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13466 MultiTemplateParamsArg TemplateParams) { 13467 const DeclSpec &DS = D.getDeclSpec(); 13468 13469 assert(DS.isFriendSpecified()); 13470 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13471 13472 SourceLocation Loc = D.getIdentifierLoc(); 13473 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13474 13475 // C++ [class.friend]p1 13476 // A friend of a class is a function or class.... 13477 // Note that this sees through typedefs, which is intended. 13478 // It *doesn't* see through dependent types, which is correct 13479 // according to [temp.arg.type]p3: 13480 // If a declaration acquires a function type through a 13481 // type dependent on a template-parameter and this causes 13482 // a declaration that does not use the syntactic form of a 13483 // function declarator to have a function type, the program 13484 // is ill-formed. 13485 if (!TInfo->getType()->isFunctionType()) { 13486 Diag(Loc, diag::err_unexpected_friend); 13487 13488 // It might be worthwhile to try to recover by creating an 13489 // appropriate declaration. 13490 return nullptr; 13491 } 13492 13493 // C++ [namespace.memdef]p3 13494 // - If a friend declaration in a non-local class first declares a 13495 // class or function, the friend class or function is a member 13496 // of the innermost enclosing namespace. 13497 // - The name of the friend is not found by simple name lookup 13498 // until a matching declaration is provided in that namespace 13499 // scope (either before or after the class declaration granting 13500 // friendship). 13501 // - If a friend function is called, its name may be found by the 13502 // name lookup that considers functions from namespaces and 13503 // classes associated with the types of the function arguments. 13504 // - When looking for a prior declaration of a class or a function 13505 // declared as a friend, scopes outside the innermost enclosing 13506 // namespace scope are not considered. 13507 13508 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13509 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13510 DeclarationName Name = NameInfo.getName(); 13511 assert(Name); 13512 13513 // Check for unexpanded parameter packs. 13514 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13515 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13516 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13517 return nullptr; 13518 13519 // The context we found the declaration in, or in which we should 13520 // create the declaration. 13521 DeclContext *DC; 13522 Scope *DCScope = S; 13523 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13524 ForRedeclaration); 13525 13526 // There are five cases here. 13527 // - There's no scope specifier and we're in a local class. Only look 13528 // for functions declared in the immediately-enclosing block scope. 13529 // We recover from invalid scope qualifiers as if they just weren't there. 13530 FunctionDecl *FunctionContainingLocalClass = nullptr; 13531 if ((SS.isInvalid() || !SS.isSet()) && 13532 (FunctionContainingLocalClass = 13533 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13534 // C++11 [class.friend]p11: 13535 // If a friend declaration appears in a local class and the name 13536 // specified is an unqualified name, a prior declaration is 13537 // looked up without considering scopes that are outside the 13538 // innermost enclosing non-class scope. For a friend function 13539 // declaration, if there is no prior declaration, the program is 13540 // ill-formed. 13541 13542 // Find the innermost enclosing non-class scope. This is the block 13543 // scope containing the local class definition (or for a nested class, 13544 // the outer local class). 13545 DCScope = S->getFnParent(); 13546 13547 // Look up the function name in the scope. 13548 Previous.clear(LookupLocalFriendName); 13549 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13550 13551 if (!Previous.empty()) { 13552 // All possible previous declarations must have the same context: 13553 // either they were declared at block scope or they are members of 13554 // one of the enclosing local classes. 13555 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13556 } else { 13557 // This is ill-formed, but provide the context that we would have 13558 // declared the function in, if we were permitted to, for error recovery. 13559 DC = FunctionContainingLocalClass; 13560 } 13561 adjustContextForLocalExternDecl(DC); 13562 13563 // C++ [class.friend]p6: 13564 // A function can be defined in a friend declaration of a class if and 13565 // only if the class is a non-local class (9.8), the function name is 13566 // unqualified, and the function has namespace scope. 13567 if (D.isFunctionDefinition()) { 13568 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13569 } 13570 13571 // - There's no scope specifier, in which case we just go to the 13572 // appropriate scope and look for a function or function template 13573 // there as appropriate. 13574 } else if (SS.isInvalid() || !SS.isSet()) { 13575 // C++11 [namespace.memdef]p3: 13576 // If the name in a friend declaration is neither qualified nor 13577 // a template-id and the declaration is a function or an 13578 // elaborated-type-specifier, the lookup to determine whether 13579 // the entity has been previously declared shall not consider 13580 // any scopes outside the innermost enclosing namespace. 13581 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 13582 13583 // Find the appropriate context according to the above. 13584 DC = CurContext; 13585 13586 // Skip class contexts. If someone can cite chapter and verse 13587 // for this behavior, that would be nice --- it's what GCC and 13588 // EDG do, and it seems like a reasonable intent, but the spec 13589 // really only says that checks for unqualified existing 13590 // declarations should stop at the nearest enclosing namespace, 13591 // not that they should only consider the nearest enclosing 13592 // namespace. 13593 while (DC->isRecord()) 13594 DC = DC->getParent(); 13595 13596 DeclContext *LookupDC = DC; 13597 while (LookupDC->isTransparentContext()) 13598 LookupDC = LookupDC->getParent(); 13599 13600 while (true) { 13601 LookupQualifiedName(Previous, LookupDC); 13602 13603 if (!Previous.empty()) { 13604 DC = LookupDC; 13605 break; 13606 } 13607 13608 if (isTemplateId) { 13609 if (isa<TranslationUnitDecl>(LookupDC)) break; 13610 } else { 13611 if (LookupDC->isFileContext()) break; 13612 } 13613 LookupDC = LookupDC->getParent(); 13614 } 13615 13616 DCScope = getScopeForDeclContext(S, DC); 13617 13618 // - There's a non-dependent scope specifier, in which case we 13619 // compute it and do a previous lookup there for a function 13620 // or function template. 13621 } else if (!SS.getScopeRep()->isDependent()) { 13622 DC = computeDeclContext(SS); 13623 if (!DC) return nullptr; 13624 13625 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13626 13627 LookupQualifiedName(Previous, DC); 13628 13629 // Ignore things found implicitly in the wrong scope. 13630 // TODO: better diagnostics for this case. Suggesting the right 13631 // qualified scope would be nice... 13632 LookupResult::Filter F = Previous.makeFilter(); 13633 while (F.hasNext()) { 13634 NamedDecl *D = F.next(); 13635 if (!DC->InEnclosingNamespaceSetOf( 13636 D->getDeclContext()->getRedeclContext())) 13637 F.erase(); 13638 } 13639 F.done(); 13640 13641 if (Previous.empty()) { 13642 D.setInvalidType(); 13643 Diag(Loc, diag::err_qualified_friend_not_found) 13644 << Name << TInfo->getType(); 13645 return nullptr; 13646 } 13647 13648 // C++ [class.friend]p1: A friend of a class is a function or 13649 // class that is not a member of the class . . . 13650 if (DC->Equals(CurContext)) 13651 Diag(DS.getFriendSpecLoc(), 13652 getLangOpts().CPlusPlus11 ? 13653 diag::warn_cxx98_compat_friend_is_member : 13654 diag::err_friend_is_member); 13655 13656 if (D.isFunctionDefinition()) { 13657 // C++ [class.friend]p6: 13658 // A function can be defined in a friend declaration of a class if and 13659 // only if the class is a non-local class (9.8), the function name is 13660 // unqualified, and the function has namespace scope. 13661 SemaDiagnosticBuilder DB 13662 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 13663 13664 DB << SS.getScopeRep(); 13665 if (DC->isFileContext()) 13666 DB << FixItHint::CreateRemoval(SS.getRange()); 13667 SS.clear(); 13668 } 13669 13670 // - There's a scope specifier that does not match any template 13671 // parameter lists, in which case we use some arbitrary context, 13672 // create a method or method template, and wait for instantiation. 13673 // - There's a scope specifier that does match some template 13674 // parameter lists, which we don't handle right now. 13675 } else { 13676 if (D.isFunctionDefinition()) { 13677 // C++ [class.friend]p6: 13678 // A function can be defined in a friend declaration of a class if and 13679 // only if the class is a non-local class (9.8), the function name is 13680 // unqualified, and the function has namespace scope. 13681 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 13682 << SS.getScopeRep(); 13683 } 13684 13685 DC = CurContext; 13686 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 13687 } 13688 13689 if (!DC->isRecord()) { 13690 int DiagArg = -1; 13691 switch (D.getName().getKind()) { 13692 case UnqualifiedId::IK_ConstructorTemplateId: 13693 case UnqualifiedId::IK_ConstructorName: 13694 DiagArg = 0; 13695 break; 13696 case UnqualifiedId::IK_DestructorName: 13697 DiagArg = 1; 13698 break; 13699 case UnqualifiedId::IK_ConversionFunctionId: 13700 DiagArg = 2; 13701 break; 13702 case UnqualifiedId::IK_Identifier: 13703 case UnqualifiedId::IK_ImplicitSelfParam: 13704 case UnqualifiedId::IK_LiteralOperatorId: 13705 case UnqualifiedId::IK_OperatorFunctionId: 13706 case UnqualifiedId::IK_TemplateId: 13707 break; 13708 } 13709 // This implies that it has to be an operator or function. 13710 if (DiagArg >= 0) { 13711 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 13712 return nullptr; 13713 } 13714 } 13715 13716 // FIXME: This is an egregious hack to cope with cases where the scope stack 13717 // does not contain the declaration context, i.e., in an out-of-line 13718 // definition of a class. 13719 Scope FakeDCScope(S, Scope::DeclScope, Diags); 13720 if (!DCScope) { 13721 FakeDCScope.setEntity(DC); 13722 DCScope = &FakeDCScope; 13723 } 13724 13725 bool AddToScope = true; 13726 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 13727 TemplateParams, AddToScope); 13728 if (!ND) return nullptr; 13729 13730 assert(ND->getLexicalDeclContext() == CurContext); 13731 13732 // If we performed typo correction, we might have added a scope specifier 13733 // and changed the decl context. 13734 DC = ND->getDeclContext(); 13735 13736 // Add the function declaration to the appropriate lookup tables, 13737 // adjusting the redeclarations list as necessary. We don't 13738 // want to do this yet if the friending class is dependent. 13739 // 13740 // Also update the scope-based lookup if the target context's 13741 // lookup context is in lexical scope. 13742 if (!CurContext->isDependentContext()) { 13743 DC = DC->getRedeclContext(); 13744 DC->makeDeclVisibleInContext(ND); 13745 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13746 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 13747 } 13748 13749 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 13750 D.getIdentifierLoc(), ND, 13751 DS.getFriendSpecLoc()); 13752 FrD->setAccess(AS_public); 13753 CurContext->addDecl(FrD); 13754 13755 if (ND->isInvalidDecl()) { 13756 FrD->setInvalidDecl(); 13757 } else { 13758 if (DC->isRecord()) CheckFriendAccess(ND); 13759 13760 FunctionDecl *FD; 13761 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 13762 FD = FTD->getTemplatedDecl(); 13763 else 13764 FD = cast<FunctionDecl>(ND); 13765 13766 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 13767 // default argument expression, that declaration shall be a definition 13768 // and shall be the only declaration of the function or function 13769 // template in the translation unit. 13770 if (functionDeclHasDefaultArgument(FD)) { 13771 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 13772 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 13773 Diag(OldFD->getLocation(), diag::note_previous_declaration); 13774 } else if (!D.isFunctionDefinition()) 13775 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 13776 } 13777 13778 // Mark templated-scope function declarations as unsupported. 13779 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 13780 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 13781 << SS.getScopeRep() << SS.getRange() 13782 << cast<CXXRecordDecl>(CurContext); 13783 FrD->setUnsupportedFriend(true); 13784 } 13785 } 13786 13787 return ND; 13788 } 13789 13790 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 13791 AdjustDeclIfTemplate(Dcl); 13792 13793 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 13794 if (!Fn) { 13795 Diag(DelLoc, diag::err_deleted_non_function); 13796 return; 13797 } 13798 13799 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 13800 // Don't consider the implicit declaration we generate for explicit 13801 // specializations. FIXME: Do not generate these implicit declarations. 13802 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 13803 Prev->getPreviousDecl()) && 13804 !Prev->isDefined()) { 13805 Diag(DelLoc, diag::err_deleted_decl_not_first); 13806 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 13807 Prev->isImplicit() ? diag::note_previous_implicit_declaration 13808 : diag::note_previous_declaration); 13809 } 13810 // If the declaration wasn't the first, we delete the function anyway for 13811 // recovery. 13812 Fn = Fn->getCanonicalDecl(); 13813 } 13814 13815 // dllimport/dllexport cannot be deleted. 13816 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 13817 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 13818 Fn->setInvalidDecl(); 13819 } 13820 13821 if (Fn->isDeleted()) 13822 return; 13823 13824 // See if we're deleting a function which is already known to override a 13825 // non-deleted virtual function. 13826 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 13827 bool IssuedDiagnostic = false; 13828 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 13829 E = MD->end_overridden_methods(); 13830 I != E; ++I) { 13831 if (!(*MD->begin_overridden_methods())->isDeleted()) { 13832 if (!IssuedDiagnostic) { 13833 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 13834 IssuedDiagnostic = true; 13835 } 13836 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 13837 } 13838 } 13839 } 13840 13841 // C++11 [basic.start.main]p3: 13842 // A program that defines main as deleted [...] is ill-formed. 13843 if (Fn->isMain()) 13844 Diag(DelLoc, diag::err_deleted_main); 13845 13846 Fn->setDeletedAsWritten(); 13847 } 13848 13849 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 13850 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 13851 13852 if (MD) { 13853 if (MD->getParent()->isDependentType()) { 13854 MD->setDefaulted(); 13855 MD->setExplicitlyDefaulted(); 13856 return; 13857 } 13858 13859 CXXSpecialMember Member = getSpecialMember(MD); 13860 if (Member == CXXInvalid) { 13861 if (!MD->isInvalidDecl()) 13862 Diag(DefaultLoc, diag::err_default_special_members); 13863 return; 13864 } 13865 13866 MD->setDefaulted(); 13867 MD->setExplicitlyDefaulted(); 13868 13869 // If this definition appears within the record, do the checking when 13870 // the record is complete. 13871 const FunctionDecl *Primary = MD; 13872 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 13873 // Ask the template instantiation pattern that actually had the 13874 // '= default' on it. 13875 Primary = Pattern; 13876 13877 // If the method was defaulted on its first declaration, we will have 13878 // already performed the checking in CheckCompletedCXXClass. Such a 13879 // declaration doesn't trigger an implicit definition. 13880 if (Primary->getCanonicalDecl()->isDefaulted()) 13881 return; 13882 13883 CheckExplicitlyDefaultedSpecialMember(MD); 13884 13885 if (!MD->isInvalidDecl()) 13886 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 13887 } else { 13888 Diag(DefaultLoc, diag::err_default_special_members); 13889 } 13890 } 13891 13892 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 13893 for (Stmt *SubStmt : S->children()) { 13894 if (!SubStmt) 13895 continue; 13896 if (isa<ReturnStmt>(SubStmt)) 13897 Self.Diag(SubStmt->getLocStart(), 13898 diag::err_return_in_constructor_handler); 13899 if (!isa<Expr>(SubStmt)) 13900 SearchForReturnInStmt(Self, SubStmt); 13901 } 13902 } 13903 13904 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 13905 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 13906 CXXCatchStmt *Handler = TryBlock->getHandler(I); 13907 SearchForReturnInStmt(*this, Handler); 13908 } 13909 } 13910 13911 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 13912 const CXXMethodDecl *Old) { 13913 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 13914 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 13915 13916 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 13917 13918 // If the calling conventions match, everything is fine 13919 if (NewCC == OldCC) 13920 return false; 13921 13922 // If the calling conventions mismatch because the new function is static, 13923 // suppress the calling convention mismatch error; the error about static 13924 // function override (err_static_overrides_virtual from 13925 // Sema::CheckFunctionDeclaration) is more clear. 13926 if (New->getStorageClass() == SC_Static) 13927 return false; 13928 13929 Diag(New->getLocation(), 13930 diag::err_conflicting_overriding_cc_attributes) 13931 << New->getDeclName() << New->getType() << Old->getType(); 13932 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 13933 return true; 13934 } 13935 13936 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 13937 const CXXMethodDecl *Old) { 13938 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 13939 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 13940 13941 if (Context.hasSameType(NewTy, OldTy) || 13942 NewTy->isDependentType() || OldTy->isDependentType()) 13943 return false; 13944 13945 // Check if the return types are covariant 13946 QualType NewClassTy, OldClassTy; 13947 13948 /// Both types must be pointers or references to classes. 13949 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 13950 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 13951 NewClassTy = NewPT->getPointeeType(); 13952 OldClassTy = OldPT->getPointeeType(); 13953 } 13954 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 13955 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 13956 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 13957 NewClassTy = NewRT->getPointeeType(); 13958 OldClassTy = OldRT->getPointeeType(); 13959 } 13960 } 13961 } 13962 13963 // The return types aren't either both pointers or references to a class type. 13964 if (NewClassTy.isNull()) { 13965 Diag(New->getLocation(), 13966 diag::err_different_return_type_for_overriding_virtual_function) 13967 << New->getDeclName() << NewTy << OldTy 13968 << New->getReturnTypeSourceRange(); 13969 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13970 << Old->getReturnTypeSourceRange(); 13971 13972 return true; 13973 } 13974 13975 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 13976 // C++14 [class.virtual]p8: 13977 // If the class type in the covariant return type of D::f differs from 13978 // that of B::f, the class type in the return type of D::f shall be 13979 // complete at the point of declaration of D::f or shall be the class 13980 // type D. 13981 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 13982 if (!RT->isBeingDefined() && 13983 RequireCompleteType(New->getLocation(), NewClassTy, 13984 diag::err_covariant_return_incomplete, 13985 New->getDeclName())) 13986 return true; 13987 } 13988 13989 // Check if the new class derives from the old class. 13990 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 13991 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 13992 << New->getDeclName() << NewTy << OldTy 13993 << New->getReturnTypeSourceRange(); 13994 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 13995 << Old->getReturnTypeSourceRange(); 13996 return true; 13997 } 13998 13999 // Check if we the conversion from derived to base is valid. 14000 if (CheckDerivedToBaseConversion( 14001 NewClassTy, OldClassTy, 14002 diag::err_covariant_return_inaccessible_base, 14003 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14004 New->getLocation(), New->getReturnTypeSourceRange(), 14005 New->getDeclName(), nullptr)) { 14006 // FIXME: this note won't trigger for delayed access control 14007 // diagnostics, and it's impossible to get an undelayed error 14008 // here from access control during the original parse because 14009 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14010 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14011 << Old->getReturnTypeSourceRange(); 14012 return true; 14013 } 14014 } 14015 14016 // The qualifiers of the return types must be the same. 14017 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14018 Diag(New->getLocation(), 14019 diag::err_covariant_return_type_different_qualifications) 14020 << New->getDeclName() << NewTy << OldTy 14021 << New->getReturnTypeSourceRange(); 14022 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14023 << Old->getReturnTypeSourceRange(); 14024 return true; 14025 } 14026 14027 14028 // The new class type must have the same or less qualifiers as the old type. 14029 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14030 Diag(New->getLocation(), 14031 diag::err_covariant_return_type_class_type_more_qualified) 14032 << New->getDeclName() << NewTy << OldTy 14033 << New->getReturnTypeSourceRange(); 14034 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14035 << Old->getReturnTypeSourceRange(); 14036 return true; 14037 } 14038 14039 return false; 14040 } 14041 14042 /// \brief Mark the given method pure. 14043 /// 14044 /// \param Method the method to be marked pure. 14045 /// 14046 /// \param InitRange the source range that covers the "0" initializer. 14047 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14048 SourceLocation EndLoc = InitRange.getEnd(); 14049 if (EndLoc.isValid()) 14050 Method->setRangeEnd(EndLoc); 14051 14052 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14053 Method->setPure(); 14054 return false; 14055 } 14056 14057 if (!Method->isInvalidDecl()) 14058 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14059 << Method->getDeclName() << InitRange; 14060 return true; 14061 } 14062 14063 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14064 if (D->getFriendObjectKind()) 14065 Diag(D->getLocation(), diag::err_pure_friend); 14066 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14067 CheckPureMethod(M, ZeroLoc); 14068 else 14069 Diag(D->getLocation(), diag::err_illegal_initializer); 14070 } 14071 14072 /// \brief Determine whether the given declaration is a static data member. 14073 static bool isStaticDataMember(const Decl *D) { 14074 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14075 return Var->isStaticDataMember(); 14076 14077 return false; 14078 } 14079 14080 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 14081 /// an initializer for the out-of-line declaration 'Dcl'. The scope 14082 /// is a fresh scope pushed for just this purpose. 14083 /// 14084 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14085 /// static data member of class X, names should be looked up in the scope of 14086 /// class X. 14087 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14088 // If there is no declaration, there was an error parsing it. 14089 if (!D || D->isInvalidDecl()) 14090 return; 14091 14092 // We will always have a nested name specifier here, but this declaration 14093 // might not be out of line if the specifier names the current namespace: 14094 // extern int n; 14095 // int ::n = 0; 14096 if (D->isOutOfLine()) 14097 EnterDeclaratorContext(S, D->getDeclContext()); 14098 14099 // If we are parsing the initializer for a static data member, push a 14100 // new expression evaluation context that is associated with this static 14101 // data member. 14102 if (isStaticDataMember(D)) 14103 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 14104 } 14105 14106 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 14107 /// initializer for the out-of-line declaration 'D'. 14108 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14109 // If there is no declaration, there was an error parsing it. 14110 if (!D || D->isInvalidDecl()) 14111 return; 14112 14113 if (isStaticDataMember(D)) 14114 PopExpressionEvaluationContext(); 14115 14116 if (D->isOutOfLine()) 14117 ExitDeclaratorContext(S); 14118 } 14119 14120 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14121 /// C++ if/switch/while/for statement. 14122 /// e.g: "if (int x = f()) {...}" 14123 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14124 // C++ 6.4p2: 14125 // The declarator shall not specify a function or an array. 14126 // The type-specifier-seq shall not contain typedef and shall not declare a 14127 // new class or enumeration. 14128 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14129 "Parser allowed 'typedef' as storage class of condition decl."); 14130 14131 Decl *Dcl = ActOnDeclarator(S, D); 14132 if (!Dcl) 14133 return true; 14134 14135 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14136 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14137 << D.getSourceRange(); 14138 return true; 14139 } 14140 14141 return Dcl; 14142 } 14143 14144 void Sema::LoadExternalVTableUses() { 14145 if (!ExternalSource) 14146 return; 14147 14148 SmallVector<ExternalVTableUse, 4> VTables; 14149 ExternalSource->ReadUsedVTables(VTables); 14150 SmallVector<VTableUse, 4> NewUses; 14151 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14152 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14153 = VTablesUsed.find(VTables[I].Record); 14154 // Even if a definition wasn't required before, it may be required now. 14155 if (Pos != VTablesUsed.end()) { 14156 if (!Pos->second && VTables[I].DefinitionRequired) 14157 Pos->second = true; 14158 continue; 14159 } 14160 14161 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14162 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14163 } 14164 14165 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14166 } 14167 14168 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14169 bool DefinitionRequired) { 14170 // Ignore any vtable uses in unevaluated operands or for classes that do 14171 // not have a vtable. 14172 if (!Class->isDynamicClass() || Class->isDependentContext() || 14173 CurContext->isDependentContext() || isUnevaluatedContext()) 14174 return; 14175 14176 // Try to insert this class into the map. 14177 LoadExternalVTableUses(); 14178 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14179 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14180 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14181 if (!Pos.second) { 14182 // If we already had an entry, check to see if we are promoting this vtable 14183 // to require a definition. If so, we need to reappend to the VTableUses 14184 // list, since we may have already processed the first entry. 14185 if (DefinitionRequired && !Pos.first->second) { 14186 Pos.first->second = true; 14187 } else { 14188 // Otherwise, we can early exit. 14189 return; 14190 } 14191 } else { 14192 // The Microsoft ABI requires that we perform the destructor body 14193 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14194 // the deleting destructor is emitted with the vtable, not with the 14195 // destructor definition as in the Itanium ABI. 14196 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14197 CXXDestructorDecl *DD = Class->getDestructor(); 14198 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14199 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14200 // If this is an out-of-line declaration, marking it referenced will 14201 // not do anything. Manually call CheckDestructor to look up operator 14202 // delete(). 14203 ContextRAII SavedContext(*this, DD); 14204 CheckDestructor(DD); 14205 } else { 14206 MarkFunctionReferenced(Loc, Class->getDestructor()); 14207 } 14208 } 14209 } 14210 } 14211 14212 // Local classes need to have their virtual members marked 14213 // immediately. For all other classes, we mark their virtual members 14214 // at the end of the translation unit. 14215 if (Class->isLocalClass()) 14216 MarkVirtualMembersReferenced(Loc, Class); 14217 else 14218 VTableUses.push_back(std::make_pair(Class, Loc)); 14219 } 14220 14221 bool Sema::DefineUsedVTables() { 14222 LoadExternalVTableUses(); 14223 if (VTableUses.empty()) 14224 return false; 14225 14226 // Note: The VTableUses vector could grow as a result of marking 14227 // the members of a class as "used", so we check the size each 14228 // time through the loop and prefer indices (which are stable) to 14229 // iterators (which are not). 14230 bool DefinedAnything = false; 14231 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14232 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14233 if (!Class) 14234 continue; 14235 14236 SourceLocation Loc = VTableUses[I].second; 14237 14238 bool DefineVTable = true; 14239 14240 // If this class has a key function, but that key function is 14241 // defined in another translation unit, we don't need to emit the 14242 // vtable even though we're using it. 14243 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14244 if (KeyFunction && !KeyFunction->hasBody()) { 14245 // The key function is in another translation unit. 14246 DefineVTable = false; 14247 TemplateSpecializationKind TSK = 14248 KeyFunction->getTemplateSpecializationKind(); 14249 assert(TSK != TSK_ExplicitInstantiationDefinition && 14250 TSK != TSK_ImplicitInstantiation && 14251 "Instantiations don't have key functions"); 14252 (void)TSK; 14253 } else if (!KeyFunction) { 14254 // If we have a class with no key function that is the subject 14255 // of an explicit instantiation declaration, suppress the 14256 // vtable; it will live with the explicit instantiation 14257 // definition. 14258 bool IsExplicitInstantiationDeclaration 14259 = Class->getTemplateSpecializationKind() 14260 == TSK_ExplicitInstantiationDeclaration; 14261 for (auto R : Class->redecls()) { 14262 TemplateSpecializationKind TSK 14263 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14264 if (TSK == TSK_ExplicitInstantiationDeclaration) 14265 IsExplicitInstantiationDeclaration = true; 14266 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14267 IsExplicitInstantiationDeclaration = false; 14268 break; 14269 } 14270 } 14271 14272 if (IsExplicitInstantiationDeclaration) 14273 DefineVTable = false; 14274 } 14275 14276 // The exception specifications for all virtual members may be needed even 14277 // if we are not providing an authoritative form of the vtable in this TU. 14278 // We may choose to emit it available_externally anyway. 14279 if (!DefineVTable) { 14280 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14281 continue; 14282 } 14283 14284 // Mark all of the virtual members of this class as referenced, so 14285 // that we can build a vtable. Then, tell the AST consumer that a 14286 // vtable for this class is required. 14287 DefinedAnything = true; 14288 MarkVirtualMembersReferenced(Loc, Class); 14289 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14290 if (VTablesUsed[Canonical]) 14291 Consumer.HandleVTable(Class); 14292 14293 // Optionally warn if we're emitting a weak vtable. 14294 if (Class->isExternallyVisible() && 14295 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 14296 const FunctionDecl *KeyFunctionDef = nullptr; 14297 if (!KeyFunction || 14298 (KeyFunction->hasBody(KeyFunctionDef) && 14299 KeyFunctionDef->isInlined())) 14300 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 14301 TSK_ExplicitInstantiationDefinition 14302 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 14303 << Class; 14304 } 14305 } 14306 VTableUses.clear(); 14307 14308 return DefinedAnything; 14309 } 14310 14311 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14312 const CXXRecordDecl *RD) { 14313 for (const auto *I : RD->methods()) 14314 if (I->isVirtual() && !I->isPure()) 14315 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14316 } 14317 14318 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14319 const CXXRecordDecl *RD) { 14320 // Mark all functions which will appear in RD's vtable as used. 14321 CXXFinalOverriderMap FinalOverriders; 14322 RD->getFinalOverriders(FinalOverriders); 14323 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14324 E = FinalOverriders.end(); 14325 I != E; ++I) { 14326 for (OverridingMethods::const_iterator OI = I->second.begin(), 14327 OE = I->second.end(); 14328 OI != OE; ++OI) { 14329 assert(OI->second.size() > 0 && "no final overrider"); 14330 CXXMethodDecl *Overrider = OI->second.front().Method; 14331 14332 // C++ [basic.def.odr]p2: 14333 // [...] A virtual member function is used if it is not pure. [...] 14334 if (!Overrider->isPure()) 14335 MarkFunctionReferenced(Loc, Overrider); 14336 } 14337 } 14338 14339 // Only classes that have virtual bases need a VTT. 14340 if (RD->getNumVBases() == 0) 14341 return; 14342 14343 for (const auto &I : RD->bases()) { 14344 const CXXRecordDecl *Base = 14345 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14346 if (Base->getNumVBases() == 0) 14347 continue; 14348 MarkVirtualMembersReferenced(Loc, Base); 14349 } 14350 } 14351 14352 /// SetIvarInitializers - This routine builds initialization ASTs for the 14353 /// Objective-C implementation whose ivars need be initialized. 14354 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14355 if (!getLangOpts().CPlusPlus) 14356 return; 14357 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14358 SmallVector<ObjCIvarDecl*, 8> ivars; 14359 CollectIvarsToConstructOrDestruct(OID, ivars); 14360 if (ivars.empty()) 14361 return; 14362 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14363 for (unsigned i = 0; i < ivars.size(); i++) { 14364 FieldDecl *Field = ivars[i]; 14365 if (Field->isInvalidDecl()) 14366 continue; 14367 14368 CXXCtorInitializer *Member; 14369 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14370 InitializationKind InitKind = 14371 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14372 14373 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14374 ExprResult MemberInit = 14375 InitSeq.Perform(*this, InitEntity, InitKind, None); 14376 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14377 // Note, MemberInit could actually come back empty if no initialization 14378 // is required (e.g., because it would call a trivial default constructor) 14379 if (!MemberInit.get() || MemberInit.isInvalid()) 14380 continue; 14381 14382 Member = 14383 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14384 SourceLocation(), 14385 MemberInit.getAs<Expr>(), 14386 SourceLocation()); 14387 AllToInit.push_back(Member); 14388 14389 // Be sure that the destructor is accessible and is marked as referenced. 14390 if (const RecordType *RecordTy = 14391 Context.getBaseElementType(Field->getType()) 14392 ->getAs<RecordType>()) { 14393 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14394 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14395 MarkFunctionReferenced(Field->getLocation(), Destructor); 14396 CheckDestructorAccess(Field->getLocation(), Destructor, 14397 PDiag(diag::err_access_dtor_ivar) 14398 << Context.getBaseElementType(Field->getType())); 14399 } 14400 } 14401 } 14402 ObjCImplementation->setIvarInitializers(Context, 14403 AllToInit.data(), AllToInit.size()); 14404 } 14405 } 14406 14407 static 14408 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14409 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14410 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14411 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14412 Sema &S) { 14413 if (Ctor->isInvalidDecl()) 14414 return; 14415 14416 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14417 14418 // Target may not be determinable yet, for instance if this is a dependent 14419 // call in an uninstantiated template. 14420 if (Target) { 14421 const FunctionDecl *FNTarget = nullptr; 14422 (void)Target->hasBody(FNTarget); 14423 Target = const_cast<CXXConstructorDecl*>( 14424 cast_or_null<CXXConstructorDecl>(FNTarget)); 14425 } 14426 14427 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14428 // Avoid dereferencing a null pointer here. 14429 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14430 14431 if (!Current.insert(Canonical).second) 14432 return; 14433 14434 // We know that beyond here, we aren't chaining into a cycle. 14435 if (!Target || !Target->isDelegatingConstructor() || 14436 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14437 Valid.insert(Current.begin(), Current.end()); 14438 Current.clear(); 14439 // We've hit a cycle. 14440 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14441 Current.count(TCanonical)) { 14442 // If we haven't diagnosed this cycle yet, do so now. 14443 if (!Invalid.count(TCanonical)) { 14444 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14445 diag::warn_delegating_ctor_cycle) 14446 << Ctor; 14447 14448 // Don't add a note for a function delegating directly to itself. 14449 if (TCanonical != Canonical) 14450 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14451 14452 CXXConstructorDecl *C = Target; 14453 while (C->getCanonicalDecl() != Canonical) { 14454 const FunctionDecl *FNTarget = nullptr; 14455 (void)C->getTargetConstructor()->hasBody(FNTarget); 14456 assert(FNTarget && "Ctor cycle through bodiless function"); 14457 14458 C = const_cast<CXXConstructorDecl*>( 14459 cast<CXXConstructorDecl>(FNTarget)); 14460 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14461 } 14462 } 14463 14464 Invalid.insert(Current.begin(), Current.end()); 14465 Current.clear(); 14466 } else { 14467 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14468 } 14469 } 14470 14471 14472 void Sema::CheckDelegatingCtorCycles() { 14473 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14474 14475 for (DelegatingCtorDeclsType::iterator 14476 I = DelegatingCtorDecls.begin(ExternalSource), 14477 E = DelegatingCtorDecls.end(); 14478 I != E; ++I) 14479 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14480 14481 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14482 CE = Invalid.end(); 14483 CI != CE; ++CI) 14484 (*CI)->setInvalidDecl(); 14485 } 14486 14487 namespace { 14488 /// \brief AST visitor that finds references to the 'this' expression. 14489 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14490 Sema &S; 14491 14492 public: 14493 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14494 14495 bool VisitCXXThisExpr(CXXThisExpr *E) { 14496 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14497 << E->isImplicit(); 14498 return false; 14499 } 14500 }; 14501 } 14502 14503 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14504 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14505 if (!TSInfo) 14506 return false; 14507 14508 TypeLoc TL = TSInfo->getTypeLoc(); 14509 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14510 if (!ProtoTL) 14511 return false; 14512 14513 // C++11 [expr.prim.general]p3: 14514 // [The expression this] shall not appear before the optional 14515 // cv-qualifier-seq and it shall not appear within the declaration of a 14516 // static member function (although its type and value category are defined 14517 // within a static member function as they are within a non-static member 14518 // function). [ Note: this is because declaration matching does not occur 14519 // until the complete declarator is known. - end note ] 14520 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14521 FindCXXThisExpr Finder(*this); 14522 14523 // If the return type came after the cv-qualifier-seq, check it now. 14524 if (Proto->hasTrailingReturn() && 14525 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14526 return true; 14527 14528 // Check the exception specification. 14529 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14530 return true; 14531 14532 return checkThisInStaticMemberFunctionAttributes(Method); 14533 } 14534 14535 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14536 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14537 if (!TSInfo) 14538 return false; 14539 14540 TypeLoc TL = TSInfo->getTypeLoc(); 14541 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14542 if (!ProtoTL) 14543 return false; 14544 14545 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14546 FindCXXThisExpr Finder(*this); 14547 14548 switch (Proto->getExceptionSpecType()) { 14549 case EST_Unparsed: 14550 case EST_Uninstantiated: 14551 case EST_Unevaluated: 14552 case EST_BasicNoexcept: 14553 case EST_DynamicNone: 14554 case EST_MSAny: 14555 case EST_None: 14556 break; 14557 14558 case EST_ComputedNoexcept: 14559 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14560 return true; 14561 14562 case EST_Dynamic: 14563 for (const auto &E : Proto->exceptions()) { 14564 if (!Finder.TraverseType(E)) 14565 return true; 14566 } 14567 break; 14568 } 14569 14570 return false; 14571 } 14572 14573 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14574 FindCXXThisExpr Finder(*this); 14575 14576 // Check attributes. 14577 for (const auto *A : Method->attrs()) { 14578 // FIXME: This should be emitted by tblgen. 14579 Expr *Arg = nullptr; 14580 ArrayRef<Expr *> Args; 14581 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14582 Arg = G->getArg(); 14583 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14584 Arg = G->getArg(); 14585 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14586 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14587 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14588 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14589 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14590 Arg = ETLF->getSuccessValue(); 14591 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14592 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14593 Arg = STLF->getSuccessValue(); 14594 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14595 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14596 Arg = LR->getArg(); 14597 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14598 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14599 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14600 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14601 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14602 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14603 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14604 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14605 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14606 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14607 14608 if (Arg && !Finder.TraverseStmt(Arg)) 14609 return true; 14610 14611 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14612 if (!Finder.TraverseStmt(Args[I])) 14613 return true; 14614 } 14615 } 14616 14617 return false; 14618 } 14619 14620 void Sema::checkExceptionSpecification( 14621 bool IsTopLevel, ExceptionSpecificationType EST, 14622 ArrayRef<ParsedType> DynamicExceptions, 14623 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 14624 SmallVectorImpl<QualType> &Exceptions, 14625 FunctionProtoType::ExceptionSpecInfo &ESI) { 14626 Exceptions.clear(); 14627 ESI.Type = EST; 14628 if (EST == EST_Dynamic) { 14629 Exceptions.reserve(DynamicExceptions.size()); 14630 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 14631 // FIXME: Preserve type source info. 14632 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 14633 14634 if (IsTopLevel) { 14635 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 14636 collectUnexpandedParameterPacks(ET, Unexpanded); 14637 if (!Unexpanded.empty()) { 14638 DiagnoseUnexpandedParameterPacks( 14639 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 14640 Unexpanded); 14641 continue; 14642 } 14643 } 14644 14645 // Check that the type is valid for an exception spec, and 14646 // drop it if not. 14647 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 14648 Exceptions.push_back(ET); 14649 } 14650 ESI.Exceptions = Exceptions; 14651 return; 14652 } 14653 14654 if (EST == EST_ComputedNoexcept) { 14655 // If an error occurred, there's no expression here. 14656 if (NoexceptExpr) { 14657 assert((NoexceptExpr->isTypeDependent() || 14658 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 14659 Context.BoolTy) && 14660 "Parser should have made sure that the expression is boolean"); 14661 if (IsTopLevel && NoexceptExpr && 14662 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 14663 ESI.Type = EST_BasicNoexcept; 14664 return; 14665 } 14666 14667 if (!NoexceptExpr->isValueDependent()) 14668 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 14669 diag::err_noexcept_needs_constant_expression, 14670 /*AllowFold*/ false).get(); 14671 ESI.NoexceptExpr = NoexceptExpr; 14672 } 14673 return; 14674 } 14675 } 14676 14677 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 14678 ExceptionSpecificationType EST, 14679 SourceRange SpecificationRange, 14680 ArrayRef<ParsedType> DynamicExceptions, 14681 ArrayRef<SourceRange> DynamicExceptionRanges, 14682 Expr *NoexceptExpr) { 14683 if (!MethodD) 14684 return; 14685 14686 // Dig out the method we're referring to. 14687 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 14688 MethodD = FunTmpl->getTemplatedDecl(); 14689 14690 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 14691 if (!Method) 14692 return; 14693 14694 // Check the exception specification. 14695 llvm::SmallVector<QualType, 4> Exceptions; 14696 FunctionProtoType::ExceptionSpecInfo ESI; 14697 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 14698 DynamicExceptionRanges, NoexceptExpr, Exceptions, 14699 ESI); 14700 14701 // Update the exception specification on the function type. 14702 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 14703 14704 if (Method->isStatic()) 14705 checkThisInStaticMemberFunctionExceptionSpec(Method); 14706 14707 if (Method->isVirtual()) { 14708 // Check overrides, which we previously had to delay. 14709 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 14710 OEnd = Method->end_overridden_methods(); 14711 O != OEnd; ++O) 14712 CheckOverridingFunctionExceptionSpec(Method, *O); 14713 } 14714 } 14715 14716 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 14717 /// 14718 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 14719 SourceLocation DeclStart, 14720 Declarator &D, Expr *BitWidth, 14721 InClassInitStyle InitStyle, 14722 AccessSpecifier AS, 14723 AttributeList *MSPropertyAttr) { 14724 IdentifierInfo *II = D.getIdentifier(); 14725 if (!II) { 14726 Diag(DeclStart, diag::err_anonymous_property); 14727 return nullptr; 14728 } 14729 SourceLocation Loc = D.getIdentifierLoc(); 14730 14731 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14732 QualType T = TInfo->getType(); 14733 if (getLangOpts().CPlusPlus) { 14734 CheckExtraCXXDefaultArguments(D); 14735 14736 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14737 UPPC_DataMemberType)) { 14738 D.setInvalidType(); 14739 T = Context.IntTy; 14740 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14741 } 14742 } 14743 14744 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14745 14746 if (D.getDeclSpec().isInlineSpecified()) 14747 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14748 << getLangOpts().CPlusPlus1z; 14749 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14750 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14751 diag::err_invalid_thread) 14752 << DeclSpec::getSpecifierName(TSCS); 14753 14754 // Check to see if this name was declared as a member previously 14755 NamedDecl *PrevDecl = nullptr; 14756 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14757 LookupName(Previous, S); 14758 switch (Previous.getResultKind()) { 14759 case LookupResult::Found: 14760 case LookupResult::FoundUnresolvedValue: 14761 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14762 break; 14763 14764 case LookupResult::FoundOverloaded: 14765 PrevDecl = Previous.getRepresentativeDecl(); 14766 break; 14767 14768 case LookupResult::NotFound: 14769 case LookupResult::NotFoundInCurrentInstantiation: 14770 case LookupResult::Ambiguous: 14771 break; 14772 } 14773 14774 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14775 // Maybe we will complain about the shadowed template parameter. 14776 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14777 // Just pretend that we didn't see the previous declaration. 14778 PrevDecl = nullptr; 14779 } 14780 14781 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14782 PrevDecl = nullptr; 14783 14784 SourceLocation TSSL = D.getLocStart(); 14785 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 14786 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 14787 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 14788 ProcessDeclAttributes(TUScope, NewPD, D); 14789 NewPD->setAccess(AS); 14790 14791 if (NewPD->isInvalidDecl()) 14792 Record->setInvalidDecl(); 14793 14794 if (D.getDeclSpec().isModulePrivateSpecified()) 14795 NewPD->setModulePrivate(); 14796 14797 if (NewPD->isInvalidDecl() && PrevDecl) { 14798 // Don't introduce NewFD into scope; there's already something 14799 // with the same name in the same scope. 14800 } else if (II) { 14801 PushOnScopeChains(NewPD, S); 14802 } else 14803 Record->addDecl(NewPD); 14804 14805 return NewPD; 14806 } 14807