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