1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for C++ declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "llvm/ADT/STLExtras.h" 40 #include "llvm/ADT/SmallString.h" 41 #include <map> 42 #include <set> 43 44 using namespace clang; 45 46 //===----------------------------------------------------------------------===// 47 // CheckDefaultArgumentVisitor 48 //===----------------------------------------------------------------------===// 49 50 namespace { 51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 52 /// the default argument of a parameter to determine whether it 53 /// contains any ill-formed subexpressions. For example, this will 54 /// diagnose the use of local variables or parameters within the 55 /// default argument expression. 56 class CheckDefaultArgumentVisitor 57 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 58 Expr *DefaultArg; 59 Sema *S; 60 61 public: 62 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 63 : DefaultArg(defarg), S(s) {} 64 65 bool VisitExpr(Expr *Node); 66 bool VisitDeclRefExpr(DeclRefExpr *DRE); 67 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 68 bool VisitLambdaExpr(LambdaExpr *Lambda); 69 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 70 }; 71 72 /// VisitExpr - Visit all of the children of this expression. 73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 74 bool IsInvalid = false; 75 for (Stmt::child_range I = Node->children(); I; ++I) 76 IsInvalid |= Visit(*I); 77 return IsInvalid; 78 } 79 80 /// VisitDeclRefExpr - Visit a reference to a declaration, to 81 /// determine whether this declaration can be used in the default 82 /// argument expression. 83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 84 NamedDecl *Decl = DRE->getDecl(); 85 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 86 // C++ [dcl.fct.default]p9 87 // Default arguments are evaluated each time the function is 88 // called. The order of evaluation of function arguments is 89 // unspecified. Consequently, parameters of a function shall not 90 // be used in default argument expressions, even if they are not 91 // evaluated. Parameters of a function declared before a default 92 // argument expression are in scope and can hide namespace and 93 // class member names. 94 return S->Diag(DRE->getLocStart(), 95 diag::err_param_default_argument_references_param) 96 << Param->getDeclName() << DefaultArg->getSourceRange(); 97 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 98 // C++ [dcl.fct.default]p7 99 // Local variables shall not be used in default argument 100 // expressions. 101 if (VDecl->isLocalVarDecl()) 102 return S->Diag(DRE->getLocStart(), 103 diag::err_param_default_argument_references_local) 104 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 105 } 106 107 return false; 108 } 109 110 /// VisitCXXThisExpr - Visit a C++ "this" expression. 111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 112 // C++ [dcl.fct.default]p8: 113 // The keyword this shall not be used in a default argument of a 114 // member function. 115 return S->Diag(ThisE->getLocStart(), 116 diag::err_param_default_argument_references_this) 117 << ThisE->getSourceRange(); 118 } 119 120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 121 bool Invalid = false; 122 for (PseudoObjectExpr::semantics_iterator 123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 124 Expr *E = *i; 125 126 // Look through bindings. 127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 128 E = OVE->getSourceExpr(); 129 assert(E && "pseudo-object binding without source expression?"); 130 } 131 132 Invalid |= Visit(E); 133 } 134 return Invalid; 135 } 136 137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 138 // C++11 [expr.lambda.prim]p13: 139 // A lambda-expression appearing in a default argument shall not 140 // implicitly or explicitly capture any entity. 141 if (Lambda->capture_begin() == Lambda->capture_end()) 142 return false; 143 144 return S->Diag(Lambda->getLocStart(), 145 diag::err_lambda_capture_default_arg); 146 } 147 } 148 149 void 150 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 151 const CXXMethodDecl *Method) { 152 // If we have an MSAny spec already, don't bother. 153 if (!Method || ComputedEST == EST_MSAny) 154 return; 155 156 const FunctionProtoType *Proto 157 = Method->getType()->getAs<FunctionProtoType>(); 158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 159 if (!Proto) 160 return; 161 162 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 163 164 // If this function can throw any exceptions, make a note of that. 165 if (EST == EST_MSAny || EST == EST_None) { 166 ClearExceptions(); 167 ComputedEST = EST; 168 return; 169 } 170 171 // FIXME: If the call to this decl is using any of its default arguments, we 172 // need to search them for potentially-throwing calls. 173 174 // If this function has a basic noexcept, it doesn't affect the outcome. 175 if (EST == EST_BasicNoexcept) 176 return; 177 178 // If we have a throw-all spec at this point, ignore the function. 179 if (ComputedEST == EST_None) 180 return; 181 182 // If we're still at noexcept(true) and there's a nothrow() callee, 183 // change to that specification. 184 if (EST == EST_DynamicNone) { 185 if (ComputedEST == EST_BasicNoexcept) 186 ComputedEST = EST_DynamicNone; 187 return; 188 } 189 190 // Check out noexcept specs. 191 if (EST == EST_ComputedNoexcept) { 192 FunctionProtoType::NoexceptResult NR = 193 Proto->getNoexceptSpec(Self->Context); 194 assert(NR != FunctionProtoType::NR_NoNoexcept && 195 "Must have noexcept result for EST_ComputedNoexcept."); 196 assert(NR != FunctionProtoType::NR_Dependent && 197 "Should not generate implicit declarations for dependent cases, " 198 "and don't know how to handle them anyway."); 199 200 // noexcept(false) -> no spec on the new function 201 if (NR == FunctionProtoType::NR_Throw) { 202 ClearExceptions(); 203 ComputedEST = EST_None; 204 } 205 // noexcept(true) won't change anything either. 206 return; 207 } 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))) 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 // Check that the default argument is well-formed 321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 322 if (DefaultArgChecker.Visit(DefaultArg)) { 323 Param->setInvalidDecl(); 324 return; 325 } 326 327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 328 } 329 330 /// ActOnParamUnparsedDefaultArgument - We've seen a default 331 /// argument for a function parameter, but we can't parse it yet 332 /// because we're inside a class definition. Note that this default 333 /// argument will be parsed later. 334 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 335 SourceLocation EqualLoc, 336 SourceLocation ArgLoc) { 337 if (!param) 338 return; 339 340 ParmVarDecl *Param = cast<ParmVarDecl>(param); 341 Param->setUnparsedDefaultArg(); 342 UnparsedDefaultArgLocs[Param] = ArgLoc; 343 } 344 345 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 346 /// the default argument for the parameter param failed. 347 void Sema::ActOnParamDefaultArgumentError(Decl *param) { 348 if (!param) 349 return; 350 351 ParmVarDecl *Param = cast<ParmVarDecl>(param); 352 Param->setInvalidDecl(); 353 UnparsedDefaultArgLocs.erase(Param); 354 } 355 356 /// CheckExtraCXXDefaultArguments - Check for any extra default 357 /// arguments in the declarator, which is not a function declaration 358 /// or definition and therefore is not permitted to have default 359 /// arguments. This routine should be invoked for every declarator 360 /// that is not a function declaration or definition. 361 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 362 // C++ [dcl.fct.default]p3 363 // A default argument expression shall be specified only in the 364 // parameter-declaration-clause of a function declaration or in a 365 // template-parameter (14.1). It shall not be specified for a 366 // parameter pack. If it is specified in a 367 // parameter-declaration-clause, it shall not occur within a 368 // declarator or abstract-declarator of a parameter-declaration. 369 bool MightBeFunction = D.isFunctionDeclarationContext(); 370 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 371 DeclaratorChunk &chunk = D.getTypeObject(i); 372 if (chunk.Kind == DeclaratorChunk::Function) { 373 if (MightBeFunction) { 374 // This is a function declaration. It can have default arguments, but 375 // keep looking in case its return type is a function type with default 376 // arguments. 377 MightBeFunction = false; 378 continue; 379 } 380 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 381 ++argIdx) { 382 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 383 if (Param->hasUnparsedDefaultArg()) { 384 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 385 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 386 << SourceRange((*Toks)[1].getLocation(), 387 Toks->back().getLocation()); 388 delete Toks; 389 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 390 } else if (Param->getDefaultArg()) { 391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 392 << Param->getDefaultArg()->getSourceRange(); 393 Param->setDefaultArg(nullptr); 394 } 395 } 396 } else if (chunk.Kind != DeclaratorChunk::Paren) { 397 MightBeFunction = false; 398 } 399 } 400 } 401 402 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 403 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 404 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 405 if (!PVD->hasDefaultArg()) 406 return false; 407 if (!PVD->hasInheritedDefaultArg()) 408 return true; 409 } 410 return false; 411 } 412 413 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 414 /// function, once we already know that they have the same 415 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 416 /// error, false otherwise. 417 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 418 Scope *S) { 419 bool Invalid = false; 420 421 // C++ [dcl.fct.default]p4: 422 // For non-template functions, default arguments can be added in 423 // later declarations of a function in the same 424 // scope. Declarations in different scopes have completely 425 // distinct sets of default arguments. That is, declarations in 426 // inner scopes do not acquire default arguments from 427 // declarations in outer scopes, and vice versa. In a given 428 // function declaration, all parameters subsequent to a 429 // parameter with a default argument shall have default 430 // arguments supplied in this or previous declarations. A 431 // default argument shall not be redefined by a later 432 // declaration (not even to the same value). 433 // 434 // C++ [dcl.fct.default]p6: 435 // Except for member functions of class templates, the default arguments 436 // in a member function definition that appears outside of the class 437 // definition are added to the set of default arguments provided by the 438 // member function declaration in the class definition. 439 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 440 ParmVarDecl *OldParam = Old->getParamDecl(p); 441 ParmVarDecl *NewParam = New->getParamDecl(p); 442 443 bool OldParamHasDfl = OldParam->hasDefaultArg(); 444 bool NewParamHasDfl = NewParam->hasDefaultArg(); 445 446 NamedDecl *ND = Old; 447 448 // The declaration context corresponding to the scope is the semantic 449 // parent, unless this is a local function declaration, in which case 450 // it is that surrounding function. 451 DeclContext *ScopeDC = New->getLexicalDeclContext(); 452 if (!ScopeDC->isFunctionOrMethod()) 453 ScopeDC = New->getDeclContext(); 454 if (S && !isDeclInScope(ND, ScopeDC, S) && 455 !New->getDeclContext()->isRecord()) 456 // Ignore default parameters of old decl if they are not in 457 // the same scope and this is not an out-of-line definition of 458 // a member function. 459 OldParamHasDfl = false; 460 461 if (OldParamHasDfl && NewParamHasDfl) { 462 463 unsigned DiagDefaultParamID = 464 diag::err_param_default_argument_redefinition; 465 466 // MSVC accepts that default parameters be redefined for member functions 467 // of template class. The new default parameter's value is ignored. 468 Invalid = true; 469 if (getLangOpts().MicrosoftExt) { 470 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 471 if (MD && MD->getParent()->getDescribedClassTemplate()) { 472 // Merge the old default argument into the new parameter. 473 NewParam->setHasInheritedDefaultArg(); 474 if (OldParam->hasUninstantiatedDefaultArg()) 475 NewParam->setUninstantiatedDefaultArg( 476 OldParam->getUninstantiatedDefaultArg()); 477 else 478 NewParam->setDefaultArg(OldParam->getInit()); 479 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 480 Invalid = false; 481 } 482 } 483 484 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 485 // hint here. Alternatively, we could walk the type-source information 486 // for NewParam to find the last source location in the type... but it 487 // isn't worth the effort right now. This is the kind of test case that 488 // is hard to get right: 489 // int f(int); 490 // void g(int (*fp)(int) = f); 491 // void g(int (*fp)(int) = &f); 492 Diag(NewParam->getLocation(), DiagDefaultParamID) 493 << NewParam->getDefaultArgRange(); 494 495 // Look for the function declaration where the default argument was 496 // actually written, which may be a declaration prior to Old. 497 for (FunctionDecl *Older = Old->getPreviousDecl(); 498 Older; Older = Older->getPreviousDecl()) { 499 if (!Older->getParamDecl(p)->hasDefaultArg()) 500 break; 501 502 OldParam = Older->getParamDecl(p); 503 } 504 505 Diag(OldParam->getLocation(), diag::note_previous_definition) 506 << OldParam->getDefaultArgRange(); 507 } else if (OldParamHasDfl) { 508 // Merge the old default argument into the new parameter. 509 // It's important to use getInit() here; getDefaultArg() 510 // strips off any top-level ExprWithCleanups. 511 NewParam->setHasInheritedDefaultArg(); 512 if (OldParam->hasUninstantiatedDefaultArg()) 513 NewParam->setUninstantiatedDefaultArg( 514 OldParam->getUninstantiatedDefaultArg()); 515 else 516 NewParam->setDefaultArg(OldParam->getInit()); 517 } else if (NewParamHasDfl) { 518 if (New->getDescribedFunctionTemplate()) { 519 // Paragraph 4, quoted above, only applies to non-template functions. 520 Diag(NewParam->getLocation(), 521 diag::err_param_default_argument_template_redecl) 522 << NewParam->getDefaultArgRange(); 523 Diag(Old->getLocation(), diag::note_template_prev_declaration) 524 << false; 525 } else if (New->getTemplateSpecializationKind() 526 != TSK_ImplicitInstantiation && 527 New->getTemplateSpecializationKind() != TSK_Undeclared) { 528 // C++ [temp.expr.spec]p21: 529 // Default function arguments shall not be specified in a declaration 530 // or a definition for one of the following explicit specializations: 531 // - the explicit specialization of a function template; 532 // - the explicit specialization of a member function template; 533 // - the explicit specialization of a member function of a class 534 // template where the class template specialization to which the 535 // member function specialization belongs is implicitly 536 // instantiated. 537 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 538 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 539 << New->getDeclName() 540 << NewParam->getDefaultArgRange(); 541 } else if (New->getDeclContext()->isDependentContext()) { 542 // C++ [dcl.fct.default]p6 (DR217): 543 // Default arguments for a member function of a class template shall 544 // be specified on the initial declaration of the member function 545 // within the class template. 546 // 547 // Reading the tea leaves a bit in DR217 and its reference to DR205 548 // leads me to the conclusion that one cannot add default function 549 // arguments for an out-of-line definition of a member function of a 550 // dependent type. 551 int WhichKind = 2; 552 if (CXXRecordDecl *Record 553 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 554 if (Record->getDescribedClassTemplate()) 555 WhichKind = 0; 556 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 557 WhichKind = 1; 558 else 559 WhichKind = 2; 560 } 561 562 Diag(NewParam->getLocation(), 563 diag::err_param_default_argument_member_template_redecl) 564 << WhichKind 565 << NewParam->getDefaultArgRange(); 566 } 567 } 568 } 569 570 // DR1344: If a default argument is added outside a class definition and that 571 // default argument makes the function a special member function, the program 572 // is ill-formed. This can only happen for constructors. 573 if (isa<CXXConstructorDecl>(New) && 574 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 575 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 576 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 577 if (NewSM != OldSM) { 578 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 579 assert(NewParam->hasDefaultArg()); 580 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 581 << NewParam->getDefaultArgRange() << NewSM; 582 Diag(Old->getLocation(), diag::note_previous_declaration); 583 } 584 } 585 586 const FunctionDecl *Def; 587 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 588 // template has a constexpr specifier then all its declarations shall 589 // contain the constexpr specifier. 590 if (New->isConstexpr() != Old->isConstexpr()) { 591 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 592 << New << New->isConstexpr(); 593 Diag(Old->getLocation(), diag::note_previous_declaration); 594 Invalid = true; 595 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 596 // C++11 [dcl.fcn.spec]p4: 597 // If the definition of a function appears in a translation unit before its 598 // first declaration as inline, the program is ill-formed. 599 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 600 Diag(Def->getLocation(), diag::note_previous_definition); 601 Invalid = true; 602 } 603 604 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 605 // argument expression, that declaration shall be a definition and shall be 606 // the only declaration of the function or function template in the 607 // translation unit. 608 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 609 functionDeclHasDefaultArgument(Old)) { 610 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 611 Diag(Old->getLocation(), diag::note_previous_declaration); 612 Invalid = true; 613 } 614 615 if (CheckEquivalentExceptionSpec(Old, New)) 616 Invalid = true; 617 618 return Invalid; 619 } 620 621 /// \brief Merge the exception specifications of two variable declarations. 622 /// 623 /// This is called when there's a redeclaration of a VarDecl. The function 624 /// checks if the redeclaration might have an exception specification and 625 /// validates compatibility and merges the specs if necessary. 626 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 627 // Shortcut if exceptions are disabled. 628 if (!getLangOpts().CXXExceptions) 629 return; 630 631 assert(Context.hasSameType(New->getType(), Old->getType()) && 632 "Should only be called if types are otherwise the same."); 633 634 QualType NewType = New->getType(); 635 QualType OldType = Old->getType(); 636 637 // We're only interested in pointers and references to functions, as well 638 // as pointers to member functions. 639 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 640 NewType = R->getPointeeType(); 641 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 642 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 643 NewType = P->getPointeeType(); 644 OldType = OldType->getAs<PointerType>()->getPointeeType(); 645 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 646 NewType = M->getPointeeType(); 647 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 648 } 649 650 if (!NewType->isFunctionProtoType()) 651 return; 652 653 // There's lots of special cases for functions. For function pointers, system 654 // libraries are hopefully not as broken so that we don't need these 655 // workarounds. 656 if (CheckEquivalentExceptionSpec( 657 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 658 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 659 New->setInvalidDecl(); 660 } 661 } 662 663 /// CheckCXXDefaultArguments - Verify that the default arguments for a 664 /// function declaration are well-formed according to C++ 665 /// [dcl.fct.default]. 666 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 667 unsigned NumParams = FD->getNumParams(); 668 unsigned p; 669 670 // Find first parameter with a default argument 671 for (p = 0; p < NumParams; ++p) { 672 ParmVarDecl *Param = FD->getParamDecl(p); 673 if (Param->hasDefaultArg()) 674 break; 675 } 676 677 // C++ [dcl.fct.default]p4: 678 // In a given function declaration, all parameters 679 // subsequent to a parameter with a default argument shall 680 // have default arguments supplied in this or previous 681 // declarations. A default argument shall not be redefined 682 // by a later declaration (not even to the same value). 683 unsigned LastMissingDefaultArg = 0; 684 for (; p < NumParams; ++p) { 685 ParmVarDecl *Param = FD->getParamDecl(p); 686 if (!Param->hasDefaultArg()) { 687 if (Param->isInvalidDecl()) 688 /* We already complained about this parameter. */; 689 else if (Param->getIdentifier()) 690 Diag(Param->getLocation(), 691 diag::err_param_default_argument_missing_name) 692 << Param->getIdentifier(); 693 else 694 Diag(Param->getLocation(), 695 diag::err_param_default_argument_missing); 696 697 LastMissingDefaultArg = p; 698 } 699 } 700 701 if (LastMissingDefaultArg > 0) { 702 // Some default arguments were missing. Clear out all of the 703 // default arguments up to (and including) the last missing 704 // default argument, so that we leave the function parameters 705 // in a semantically valid state. 706 for (p = 0; p <= LastMissingDefaultArg; ++p) { 707 ParmVarDecl *Param = FD->getParamDecl(p); 708 if (Param->hasDefaultArg()) { 709 Param->setDefaultArg(nullptr); 710 } 711 } 712 } 713 } 714 715 // CheckConstexprParameterTypes - Check whether a function's parameter types 716 // are all literal types. If so, return true. If not, produce a suitable 717 // diagnostic and return false. 718 static bool CheckConstexprParameterTypes(Sema &SemaRef, 719 const FunctionDecl *FD) { 720 unsigned ArgIndex = 0; 721 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 722 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 723 e = FT->param_type_end(); 724 i != e; ++i, ++ArgIndex) { 725 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 726 SourceLocation ParamLoc = PD->getLocation(); 727 if (!(*i)->isDependentType() && 728 SemaRef.RequireLiteralType(ParamLoc, *i, 729 diag::err_constexpr_non_literal_param, 730 ArgIndex+1, PD->getSourceRange(), 731 isa<CXXConstructorDecl>(FD))) 732 return false; 733 } 734 return true; 735 } 736 737 /// \brief Get diagnostic %select index for tag kind for 738 /// record diagnostic message. 739 /// WARNING: Indexes apply to particular diagnostics only! 740 /// 741 /// \returns diagnostic %select index. 742 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 743 switch (Tag) { 744 case TTK_Struct: return 0; 745 case TTK_Interface: return 1; 746 case TTK_Class: return 2; 747 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 748 } 749 } 750 751 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 752 // the requirements of a constexpr function definition or a constexpr 753 // constructor definition. If so, return true. If not, produce appropriate 754 // diagnostics and return false. 755 // 756 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 757 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 758 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 759 if (MD && MD->isInstance()) { 760 // C++11 [dcl.constexpr]p4: 761 // The definition of a constexpr constructor shall satisfy the following 762 // constraints: 763 // - the class shall not have any virtual base classes; 764 const CXXRecordDecl *RD = MD->getParent(); 765 if (RD->getNumVBases()) { 766 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 767 << isa<CXXConstructorDecl>(NewFD) 768 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 769 for (const auto &I : RD->vbases()) 770 Diag(I.getLocStart(), 771 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 772 return false; 773 } 774 } 775 776 if (!isa<CXXConstructorDecl>(NewFD)) { 777 // C++11 [dcl.constexpr]p3: 778 // The definition of a constexpr function shall satisfy the following 779 // constraints: 780 // - it shall not be virtual; 781 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 782 if (Method && Method->isVirtual()) { 783 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 784 785 // If it's not obvious why this function is virtual, find an overridden 786 // function which uses the 'virtual' keyword. 787 const CXXMethodDecl *WrittenVirtual = Method; 788 while (!WrittenVirtual->isVirtualAsWritten()) 789 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 790 if (WrittenVirtual != Method) 791 Diag(WrittenVirtual->getLocation(), 792 diag::note_overridden_virtual_function); 793 return false; 794 } 795 796 // - its return type shall be a literal type; 797 QualType RT = NewFD->getReturnType(); 798 if (!RT->isDependentType() && 799 RequireLiteralType(NewFD->getLocation(), RT, 800 diag::err_constexpr_non_literal_return)) 801 return false; 802 } 803 804 // - each of its parameter types shall be a literal type; 805 if (!CheckConstexprParameterTypes(*this, NewFD)) 806 return false; 807 808 return true; 809 } 810 811 /// Check the given declaration statement is legal within a constexpr function 812 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 813 /// 814 /// \return true if the body is OK (maybe only as an extension), false if we 815 /// have diagnosed a problem. 816 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 817 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 818 // C++11 [dcl.constexpr]p3 and p4: 819 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 820 // contain only 821 for (const auto *DclIt : DS->decls()) { 822 switch (DclIt->getKind()) { 823 case Decl::StaticAssert: 824 case Decl::Using: 825 case Decl::UsingShadow: 826 case Decl::UsingDirective: 827 case Decl::UnresolvedUsingTypename: 828 case Decl::UnresolvedUsingValue: 829 // - static_assert-declarations 830 // - using-declarations, 831 // - using-directives, 832 continue; 833 834 case Decl::Typedef: 835 case Decl::TypeAlias: { 836 // - typedef declarations and alias-declarations that do not define 837 // classes or enumerations, 838 const auto *TN = cast<TypedefNameDecl>(DclIt); 839 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 840 // Don't allow variably-modified types in constexpr functions. 841 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 842 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 843 << TL.getSourceRange() << TL.getType() 844 << isa<CXXConstructorDecl>(Dcl); 845 return false; 846 } 847 continue; 848 } 849 850 case Decl::Enum: 851 case Decl::CXXRecord: 852 // C++1y allows types to be defined, not just declared. 853 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 854 SemaRef.Diag(DS->getLocStart(), 855 SemaRef.getLangOpts().CPlusPlus1y 856 ? diag::warn_cxx11_compat_constexpr_type_definition 857 : diag::ext_constexpr_type_definition) 858 << isa<CXXConstructorDecl>(Dcl); 859 continue; 860 861 case Decl::EnumConstant: 862 case Decl::IndirectField: 863 case Decl::ParmVar: 864 // These can only appear with other declarations which are banned in 865 // C++11 and permitted in C++1y, so ignore them. 866 continue; 867 868 case Decl::Var: { 869 // C++1y [dcl.constexpr]p3 allows anything except: 870 // a definition of a variable of non-literal type or of static or 871 // thread storage duration or for which no initialization is performed. 872 const auto *VD = cast<VarDecl>(DclIt); 873 if (VD->isThisDeclarationADefinition()) { 874 if (VD->isStaticLocal()) { 875 SemaRef.Diag(VD->getLocation(), 876 diag::err_constexpr_local_var_static) 877 << isa<CXXConstructorDecl>(Dcl) 878 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 879 return false; 880 } 881 if (!VD->getType()->isDependentType() && 882 SemaRef.RequireLiteralType( 883 VD->getLocation(), VD->getType(), 884 diag::err_constexpr_local_var_non_literal_type, 885 isa<CXXConstructorDecl>(Dcl))) 886 return false; 887 if (!VD->getType()->isDependentType() && 888 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 889 SemaRef.Diag(VD->getLocation(), 890 diag::err_constexpr_local_var_no_init) 891 << isa<CXXConstructorDecl>(Dcl); 892 return false; 893 } 894 } 895 SemaRef.Diag(VD->getLocation(), 896 SemaRef.getLangOpts().CPlusPlus1y 897 ? diag::warn_cxx11_compat_constexpr_local_var 898 : diag::ext_constexpr_local_var) 899 << isa<CXXConstructorDecl>(Dcl); 900 continue; 901 } 902 903 case Decl::NamespaceAlias: 904 case Decl::Function: 905 // These are disallowed in C++11 and permitted in C++1y. Allow them 906 // everywhere as an extension. 907 if (!Cxx1yLoc.isValid()) 908 Cxx1yLoc = DS->getLocStart(); 909 continue; 910 911 default: 912 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 913 << isa<CXXConstructorDecl>(Dcl); 914 return false; 915 } 916 } 917 918 return true; 919 } 920 921 /// Check that the given field is initialized within a constexpr constructor. 922 /// 923 /// \param Dcl The constexpr constructor being checked. 924 /// \param Field The field being checked. This may be a member of an anonymous 925 /// struct or union nested within the class being checked. 926 /// \param Inits All declarations, including anonymous struct/union members and 927 /// indirect members, for which any initialization was provided. 928 /// \param Diagnosed Set to true if an error is produced. 929 static void CheckConstexprCtorInitializer(Sema &SemaRef, 930 const FunctionDecl *Dcl, 931 FieldDecl *Field, 932 llvm::SmallSet<Decl*, 16> &Inits, 933 bool &Diagnosed) { 934 if (Field->isInvalidDecl()) 935 return; 936 937 if (Field->isUnnamedBitfield()) 938 return; 939 940 // Anonymous unions with no variant members and empty anonymous structs do not 941 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 942 // indirect fields don't need initializing. 943 if (Field->isAnonymousStructOrUnion() && 944 (Field->getType()->isUnionType() 945 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 946 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 947 return; 948 949 if (!Inits.count(Field)) { 950 if (!Diagnosed) { 951 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 952 Diagnosed = true; 953 } 954 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 955 } else if (Field->isAnonymousStructOrUnion()) { 956 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 957 for (auto *I : RD->fields()) 958 // If an anonymous union contains an anonymous struct of which any member 959 // is initialized, all members must be initialized. 960 if (!RD->isUnion() || Inits.count(I)) 961 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 962 } 963 } 964 965 /// Check the provided statement is allowed in a constexpr function 966 /// definition. 967 static bool 968 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 969 SmallVectorImpl<SourceLocation> &ReturnStmts, 970 SourceLocation &Cxx1yLoc) { 971 // - its function-body shall be [...] a compound-statement that contains only 972 switch (S->getStmtClass()) { 973 case Stmt::NullStmtClass: 974 // - null statements, 975 return true; 976 977 case Stmt::DeclStmtClass: 978 // - static_assert-declarations 979 // - using-declarations, 980 // - using-directives, 981 // - typedef declarations and alias-declarations that do not define 982 // classes or enumerations, 983 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 984 return false; 985 return true; 986 987 case Stmt::ReturnStmtClass: 988 // - and exactly one return statement; 989 if (isa<CXXConstructorDecl>(Dcl)) { 990 // C++1y allows return statements in constexpr constructors. 991 if (!Cxx1yLoc.isValid()) 992 Cxx1yLoc = S->getLocStart(); 993 return true; 994 } 995 996 ReturnStmts.push_back(S->getLocStart()); 997 return true; 998 999 case Stmt::CompoundStmtClass: { 1000 // C++1y allows compound-statements. 1001 if (!Cxx1yLoc.isValid()) 1002 Cxx1yLoc = S->getLocStart(); 1003 1004 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1005 for (auto *BodyIt : CompStmt->body()) { 1006 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1007 Cxx1yLoc)) 1008 return false; 1009 } 1010 return true; 1011 } 1012 1013 case Stmt::AttributedStmtClass: 1014 if (!Cxx1yLoc.isValid()) 1015 Cxx1yLoc = S->getLocStart(); 1016 return true; 1017 1018 case Stmt::IfStmtClass: { 1019 // C++1y allows if-statements. 1020 if (!Cxx1yLoc.isValid()) 1021 Cxx1yLoc = S->getLocStart(); 1022 1023 IfStmt *If = cast<IfStmt>(S); 1024 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1025 Cxx1yLoc)) 1026 return false; 1027 if (If->getElse() && 1028 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1029 Cxx1yLoc)) 1030 return false; 1031 return true; 1032 } 1033 1034 case Stmt::WhileStmtClass: 1035 case Stmt::DoStmtClass: 1036 case Stmt::ForStmtClass: 1037 case Stmt::CXXForRangeStmtClass: 1038 case Stmt::ContinueStmtClass: 1039 // C++1y allows all of these. We don't allow them as extensions in C++11, 1040 // because they don't make sense without variable mutation. 1041 if (!SemaRef.getLangOpts().CPlusPlus1y) 1042 break; 1043 if (!Cxx1yLoc.isValid()) 1044 Cxx1yLoc = S->getLocStart(); 1045 for (Stmt::child_range Children = S->children(); Children; ++Children) 1046 if (*Children && 1047 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1048 Cxx1yLoc)) 1049 return false; 1050 return true; 1051 1052 case Stmt::SwitchStmtClass: 1053 case Stmt::CaseStmtClass: 1054 case Stmt::DefaultStmtClass: 1055 case Stmt::BreakStmtClass: 1056 // C++1y allows switch-statements, and since they don't need variable 1057 // mutation, we can reasonably allow them in C++11 as an extension. 1058 if (!Cxx1yLoc.isValid()) 1059 Cxx1yLoc = S->getLocStart(); 1060 for (Stmt::child_range Children = S->children(); Children; ++Children) 1061 if (*Children && 1062 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1063 Cxx1yLoc)) 1064 return false; 1065 return true; 1066 1067 default: 1068 if (!isa<Expr>(S)) 1069 break; 1070 1071 // C++1y allows expression-statements. 1072 if (!Cxx1yLoc.isValid()) 1073 Cxx1yLoc = S->getLocStart(); 1074 return true; 1075 } 1076 1077 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1078 << isa<CXXConstructorDecl>(Dcl); 1079 return false; 1080 } 1081 1082 /// Check the body for the given constexpr function declaration only contains 1083 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1084 /// 1085 /// \return true if the body is OK, false if we have diagnosed a problem. 1086 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1087 if (isa<CXXTryStmt>(Body)) { 1088 // C++11 [dcl.constexpr]p3: 1089 // The definition of a constexpr function shall satisfy the following 1090 // constraints: [...] 1091 // - its function-body shall be = delete, = default, or a 1092 // compound-statement 1093 // 1094 // C++11 [dcl.constexpr]p4: 1095 // In the definition of a constexpr constructor, [...] 1096 // - its function-body shall not be a function-try-block; 1097 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1098 << isa<CXXConstructorDecl>(Dcl); 1099 return false; 1100 } 1101 1102 SmallVector<SourceLocation, 4> ReturnStmts; 1103 1104 // - its function-body shall be [...] a compound-statement that contains only 1105 // [... list of cases ...] 1106 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1107 SourceLocation Cxx1yLoc; 1108 for (auto *BodyIt : CompBody->body()) { 1109 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1110 return false; 1111 } 1112 1113 if (Cxx1yLoc.isValid()) 1114 Diag(Cxx1yLoc, 1115 getLangOpts().CPlusPlus1y 1116 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1117 : diag::ext_constexpr_body_invalid_stmt) 1118 << isa<CXXConstructorDecl>(Dcl); 1119 1120 if (const CXXConstructorDecl *Constructor 1121 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1122 const CXXRecordDecl *RD = Constructor->getParent(); 1123 // DR1359: 1124 // - every non-variant non-static data member and base class sub-object 1125 // shall be initialized; 1126 // DR1460: 1127 // - if the class is a union having variant members, exactly one of them 1128 // shall be initialized; 1129 if (RD->isUnion()) { 1130 if (Constructor->getNumCtorInitializers() == 0 && 1131 RD->hasVariantMembers()) { 1132 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1133 return false; 1134 } 1135 } else if (!Constructor->isDependentContext() && 1136 !Constructor->isDelegatingConstructor()) { 1137 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1138 1139 // Skip detailed checking if we have enough initializers, and we would 1140 // allow at most one initializer per member. 1141 bool AnyAnonStructUnionMembers = false; 1142 unsigned Fields = 0; 1143 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1144 E = RD->field_end(); I != E; ++I, ++Fields) { 1145 if (I->isAnonymousStructOrUnion()) { 1146 AnyAnonStructUnionMembers = true; 1147 break; 1148 } 1149 } 1150 // DR1460: 1151 // - if the class is a union-like class, but is not a union, for each of 1152 // its anonymous union members having variant members, exactly one of 1153 // them shall be initialized; 1154 if (AnyAnonStructUnionMembers || 1155 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1156 // Check initialization of non-static data members. Base classes are 1157 // always initialized so do not need to be checked. Dependent bases 1158 // might not have initializers in the member initializer list. 1159 llvm::SmallSet<Decl*, 16> Inits; 1160 for (const auto *I: Constructor->inits()) { 1161 if (FieldDecl *FD = I->getMember()) 1162 Inits.insert(FD); 1163 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1164 Inits.insert(ID->chain_begin(), ID->chain_end()); 1165 } 1166 1167 bool Diagnosed = false; 1168 for (auto *I : RD->fields()) 1169 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1170 if (Diagnosed) 1171 return false; 1172 } 1173 } 1174 } else { 1175 if (ReturnStmts.empty()) { 1176 // C++1y doesn't require constexpr functions to contain a 'return' 1177 // statement. We still do, unless the return type might be void, because 1178 // otherwise if there's no return statement, the function cannot 1179 // be used in a core constant expression. 1180 bool OK = getLangOpts().CPlusPlus1y && 1181 (Dcl->getReturnType()->isVoidType() || 1182 Dcl->getReturnType()->isDependentType()); 1183 Diag(Dcl->getLocation(), 1184 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1185 : diag::err_constexpr_body_no_return); 1186 return OK; 1187 } 1188 if (ReturnStmts.size() > 1) { 1189 Diag(ReturnStmts.back(), 1190 getLangOpts().CPlusPlus1y 1191 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1192 : diag::ext_constexpr_body_multiple_return); 1193 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1194 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1195 } 1196 } 1197 1198 // C++11 [dcl.constexpr]p5: 1199 // if no function argument values exist such that the function invocation 1200 // substitution would produce a constant expression, the program is 1201 // ill-formed; no diagnostic required. 1202 // C++11 [dcl.constexpr]p3: 1203 // - every constructor call and implicit conversion used in initializing the 1204 // return value shall be one of those allowed in a constant expression. 1205 // C++11 [dcl.constexpr]p4: 1206 // - every constructor involved in initializing non-static data members and 1207 // base class sub-objects shall be a constexpr constructor. 1208 SmallVector<PartialDiagnosticAt, 8> Diags; 1209 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1210 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1211 << isa<CXXConstructorDecl>(Dcl); 1212 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1213 Diag(Diags[I].first, Diags[I].second); 1214 // Don't return false here: we allow this for compatibility in 1215 // system headers. 1216 } 1217 1218 return true; 1219 } 1220 1221 /// isCurrentClassName - Determine whether the identifier II is the 1222 /// name of the class type currently being defined. In the case of 1223 /// nested classes, this will only return true if II is the name of 1224 /// the innermost class. 1225 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1226 const CXXScopeSpec *SS) { 1227 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1228 1229 CXXRecordDecl *CurDecl; 1230 if (SS && SS->isSet() && !SS->isInvalid()) { 1231 DeclContext *DC = computeDeclContext(*SS, true); 1232 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1233 } else 1234 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1235 1236 if (CurDecl && CurDecl->getIdentifier()) 1237 return &II == CurDecl->getIdentifier(); 1238 return false; 1239 } 1240 1241 /// \brief Determine whether the identifier II is a typo for the name of 1242 /// the class type currently being defined. If so, update it to the identifier 1243 /// that should have been used. 1244 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1245 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1246 1247 if (!getLangOpts().SpellChecking) 1248 return false; 1249 1250 CXXRecordDecl *CurDecl; 1251 if (SS && SS->isSet() && !SS->isInvalid()) { 1252 DeclContext *DC = computeDeclContext(*SS, true); 1253 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1254 } else 1255 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1256 1257 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1258 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1259 < II->getLength()) { 1260 II = CurDecl->getIdentifier(); 1261 return true; 1262 } 1263 1264 return false; 1265 } 1266 1267 /// \brief Determine whether the given class is a base class of the given 1268 /// class, including looking at dependent bases. 1269 static bool findCircularInheritance(const CXXRecordDecl *Class, 1270 const CXXRecordDecl *Current) { 1271 SmallVector<const CXXRecordDecl*, 8> Queue; 1272 1273 Class = Class->getCanonicalDecl(); 1274 while (true) { 1275 for (const auto &I : Current->bases()) { 1276 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1277 if (!Base) 1278 continue; 1279 1280 Base = Base->getDefinition(); 1281 if (!Base) 1282 continue; 1283 1284 if (Base->getCanonicalDecl() == Class) 1285 return true; 1286 1287 Queue.push_back(Base); 1288 } 1289 1290 if (Queue.empty()) 1291 return false; 1292 1293 Current = Queue.pop_back_val(); 1294 } 1295 1296 return false; 1297 } 1298 1299 /// \brief Perform propagation of DLL attributes from a derived class to a 1300 /// templated base class for MS compatibility. 1301 static void propagateDLLAttrToBaseClassTemplate( 1302 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1303 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1304 if (getDLLAttr( 1305 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1306 // If the base class template has a DLL attribute, don't try to change it. 1307 return; 1308 } 1309 1310 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1311 // If the base class is not already specialized, we can do the propagation. 1312 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1313 NewAttr->setInherited(true); 1314 BaseTemplateSpec->addAttr(NewAttr); 1315 return; 1316 } 1317 1318 bool DifferentAttribute = false; 1319 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1320 if (!SpecializationAttr->isInherited()) { 1321 // The template has previously been specialized or instantiated with an 1322 // explicit attribute. We should not try to change it. 1323 return; 1324 } 1325 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1326 // The specialization already has the right attribute. 1327 return; 1328 } 1329 DifferentAttribute = true; 1330 } 1331 1332 // The template was previously instantiated or explicitly specialized without 1333 // a dll attribute, or the template was previously instantiated with a 1334 // different inherited attribute. It's too late for us to change the 1335 // attribute, so warn that this is unsupported. 1336 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1337 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1338 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1339 if (BaseTemplateSpec->isExplicitSpecialization()) { 1340 S.Diag(BaseTemplateSpec->getLocation(), 1341 diag::note_template_class_explicit_specialization_was_here) 1342 << BaseTemplateSpec; 1343 } else { 1344 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1345 diag::note_template_class_instantiation_was_here) 1346 << BaseTemplateSpec; 1347 } 1348 } 1349 1350 /// \brief Check the validity of a C++ base class specifier. 1351 /// 1352 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1353 /// and returns NULL otherwise. 1354 CXXBaseSpecifier * 1355 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1356 SourceRange SpecifierRange, 1357 bool Virtual, AccessSpecifier Access, 1358 TypeSourceInfo *TInfo, 1359 SourceLocation EllipsisLoc) { 1360 QualType BaseType = TInfo->getType(); 1361 1362 // C++ [class.union]p1: 1363 // A union shall not have base classes. 1364 if (Class->isUnion()) { 1365 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1366 << SpecifierRange; 1367 return nullptr; 1368 } 1369 1370 if (EllipsisLoc.isValid() && 1371 !TInfo->getType()->containsUnexpandedParameterPack()) { 1372 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1373 << TInfo->getTypeLoc().getSourceRange(); 1374 EllipsisLoc = SourceLocation(); 1375 } 1376 1377 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1378 1379 if (BaseType->isDependentType()) { 1380 // Make sure that we don't have circular inheritance among our dependent 1381 // bases. For non-dependent bases, the check for completeness below handles 1382 // this. 1383 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1384 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1385 ((BaseDecl = BaseDecl->getDefinition()) && 1386 findCircularInheritance(Class, BaseDecl))) { 1387 Diag(BaseLoc, diag::err_circular_inheritance) 1388 << BaseType << Context.getTypeDeclType(Class); 1389 1390 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1391 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1392 << BaseType; 1393 1394 return nullptr; 1395 } 1396 } 1397 1398 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1399 Class->getTagKind() == TTK_Class, 1400 Access, TInfo, EllipsisLoc); 1401 } 1402 1403 // Base specifiers must be record types. 1404 if (!BaseType->isRecordType()) { 1405 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1406 return nullptr; 1407 } 1408 1409 // C++ [class.union]p1: 1410 // A union shall not be used as a base class. 1411 if (BaseType->isUnionType()) { 1412 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1413 return nullptr; 1414 } 1415 1416 // For the MS ABI, propagate DLL attributes to base class templates. 1417 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1418 if (Attr *ClassAttr = getDLLAttr(Class)) { 1419 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1420 BaseType->getAsCXXRecordDecl())) { 1421 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1422 BaseTemplate, BaseLoc); 1423 } 1424 } 1425 } 1426 1427 // C++ [class.derived]p2: 1428 // The class-name in a base-specifier shall not be an incompletely 1429 // defined class. 1430 if (RequireCompleteType(BaseLoc, BaseType, 1431 diag::err_incomplete_base_class, SpecifierRange)) { 1432 Class->setInvalidDecl(); 1433 return nullptr; 1434 } 1435 1436 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1437 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1438 assert(BaseDecl && "Record type has no declaration"); 1439 BaseDecl = BaseDecl->getDefinition(); 1440 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1441 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1442 assert(CXXBaseDecl && "Base type is not a C++ type"); 1443 1444 // A class which contains a flexible array member is not suitable for use as a 1445 // base class: 1446 // - If the layout determines that a base comes before another base, 1447 // the flexible array member would index into the subsequent base. 1448 // - If the layout determines that base comes before the derived class, 1449 // the flexible array member would index into the derived class. 1450 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1451 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1452 << CXXBaseDecl->getDeclName(); 1453 return nullptr; 1454 } 1455 1456 // C++ [class]p3: 1457 // If a class is marked final and it appears as a base-type-specifier in 1458 // base-clause, the program is ill-formed. 1459 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1460 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1461 << CXXBaseDecl->getDeclName() 1462 << FA->isSpelledAsSealed(); 1463 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1464 << CXXBaseDecl->getDeclName() << FA->getRange(); 1465 return nullptr; 1466 } 1467 1468 if (BaseDecl->isInvalidDecl()) 1469 Class->setInvalidDecl(); 1470 1471 // Create the base specifier. 1472 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1473 Class->getTagKind() == TTK_Class, 1474 Access, TInfo, EllipsisLoc); 1475 } 1476 1477 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1478 /// one entry in the base class list of a class specifier, for 1479 /// example: 1480 /// class foo : public bar, virtual private baz { 1481 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1482 BaseResult 1483 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1484 ParsedAttributes &Attributes, 1485 bool Virtual, AccessSpecifier Access, 1486 ParsedType basetype, SourceLocation BaseLoc, 1487 SourceLocation EllipsisLoc) { 1488 if (!classdecl) 1489 return true; 1490 1491 AdjustDeclIfTemplate(classdecl); 1492 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1493 if (!Class) 1494 return true; 1495 1496 // We haven't yet attached the base specifiers. 1497 Class->setIsParsingBaseSpecifiers(); 1498 1499 // We do not support any C++11 attributes on base-specifiers yet. 1500 // Diagnose any attributes we see. 1501 if (!Attributes.empty()) { 1502 for (AttributeList *Attr = Attributes.getList(); Attr; 1503 Attr = Attr->getNext()) { 1504 if (Attr->isInvalid() || 1505 Attr->getKind() == AttributeList::IgnoredAttribute) 1506 continue; 1507 Diag(Attr->getLoc(), 1508 Attr->getKind() == AttributeList::UnknownAttribute 1509 ? diag::warn_unknown_attribute_ignored 1510 : diag::err_base_specifier_attribute) 1511 << Attr->getName(); 1512 } 1513 } 1514 1515 TypeSourceInfo *TInfo = nullptr; 1516 GetTypeFromParser(basetype, &TInfo); 1517 1518 if (EllipsisLoc.isInvalid() && 1519 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1520 UPPC_BaseType)) 1521 return true; 1522 1523 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1524 Virtual, Access, TInfo, 1525 EllipsisLoc)) 1526 return BaseSpec; 1527 else 1528 Class->setInvalidDecl(); 1529 1530 return true; 1531 } 1532 1533 /// \brief Performs the actual work of attaching the given base class 1534 /// specifiers to a C++ class. 1535 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1536 unsigned NumBases) { 1537 if (NumBases == 0) 1538 return false; 1539 1540 // Used to keep track of which base types we have already seen, so 1541 // that we can properly diagnose redundant direct base types. Note 1542 // that the key is always the unqualified canonical type of the base 1543 // class. 1544 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1545 1546 // Copy non-redundant base specifiers into permanent storage. 1547 unsigned NumGoodBases = 0; 1548 bool Invalid = false; 1549 for (unsigned idx = 0; idx < NumBases; ++idx) { 1550 QualType NewBaseType 1551 = Context.getCanonicalType(Bases[idx]->getType()); 1552 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1553 1554 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1555 if (KnownBase) { 1556 // C++ [class.mi]p3: 1557 // A class shall not be specified as a direct base class of a 1558 // derived class more than once. 1559 Diag(Bases[idx]->getLocStart(), 1560 diag::err_duplicate_base_class) 1561 << KnownBase->getType() 1562 << Bases[idx]->getSourceRange(); 1563 1564 // Delete the duplicate base class specifier; we're going to 1565 // overwrite its pointer later. 1566 Context.Deallocate(Bases[idx]); 1567 1568 Invalid = true; 1569 } else { 1570 // Okay, add this new base class. 1571 KnownBase = Bases[idx]; 1572 Bases[NumGoodBases++] = Bases[idx]; 1573 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1574 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1575 if (Class->isInterface() && 1576 (!RD->isInterface() || 1577 KnownBase->getAccessSpecifier() != AS_public)) { 1578 // The Microsoft extension __interface does not permit bases that 1579 // are not themselves public interfaces. 1580 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1581 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1582 << RD->getSourceRange(); 1583 Invalid = true; 1584 } 1585 if (RD->hasAttr<WeakAttr>()) 1586 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1587 } 1588 } 1589 } 1590 1591 // Attach the remaining base class specifiers to the derived class. 1592 Class->setBases(Bases, NumGoodBases); 1593 1594 // Delete the remaining (good) base class specifiers, since their 1595 // data has been copied into the CXXRecordDecl. 1596 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1597 Context.Deallocate(Bases[idx]); 1598 1599 return Invalid; 1600 } 1601 1602 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1603 /// class, after checking whether there are any duplicate base 1604 /// classes. 1605 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1606 unsigned NumBases) { 1607 if (!ClassDecl || !Bases || !NumBases) 1608 return; 1609 1610 AdjustDeclIfTemplate(ClassDecl); 1611 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1612 } 1613 1614 /// \brief Determine whether the type \p Derived is a C++ class that is 1615 /// derived from the type \p Base. 1616 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1617 if (!getLangOpts().CPlusPlus) 1618 return false; 1619 1620 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1621 if (!DerivedRD) 1622 return false; 1623 1624 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1625 if (!BaseRD) 1626 return false; 1627 1628 // If either the base or the derived type is invalid, don't try to 1629 // check whether one is derived from the other. 1630 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1631 return false; 1632 1633 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1634 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1635 } 1636 1637 /// \brief Determine whether the type \p Derived is a C++ class that is 1638 /// derived from the type \p Base. 1639 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1640 if (!getLangOpts().CPlusPlus) 1641 return false; 1642 1643 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1644 if (!DerivedRD) 1645 return false; 1646 1647 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1648 if (!BaseRD) 1649 return false; 1650 1651 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1652 } 1653 1654 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1655 CXXCastPath &BasePathArray) { 1656 assert(BasePathArray.empty() && "Base path array must be empty!"); 1657 assert(Paths.isRecordingPaths() && "Must record paths!"); 1658 1659 const CXXBasePath &Path = Paths.front(); 1660 1661 // We first go backward and check if we have a virtual base. 1662 // FIXME: It would be better if CXXBasePath had the base specifier for 1663 // the nearest virtual base. 1664 unsigned Start = 0; 1665 for (unsigned I = Path.size(); I != 0; --I) { 1666 if (Path[I - 1].Base->isVirtual()) { 1667 Start = I - 1; 1668 break; 1669 } 1670 } 1671 1672 // Now add all bases. 1673 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1674 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1675 } 1676 1677 /// \brief Determine whether the given base path includes a virtual 1678 /// base class. 1679 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1680 for (CXXCastPath::const_iterator B = BasePath.begin(), 1681 BEnd = BasePath.end(); 1682 B != BEnd; ++B) 1683 if ((*B)->isVirtual()) 1684 return true; 1685 1686 return false; 1687 } 1688 1689 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1690 /// conversion (where Derived and Base are class types) is 1691 /// well-formed, meaning that the conversion is unambiguous (and 1692 /// that all of the base classes are accessible). Returns true 1693 /// and emits a diagnostic if the code is ill-formed, returns false 1694 /// otherwise. Loc is the location where this routine should point to 1695 /// if there is an error, and Range is the source range to highlight 1696 /// if there is an error. 1697 bool 1698 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1699 unsigned InaccessibleBaseID, 1700 unsigned AmbigiousBaseConvID, 1701 SourceLocation Loc, SourceRange Range, 1702 DeclarationName Name, 1703 CXXCastPath *BasePath) { 1704 // First, determine whether the path from Derived to Base is 1705 // ambiguous. This is slightly more expensive than checking whether 1706 // the Derived to Base conversion exists, because here we need to 1707 // explore multiple paths to determine if there is an ambiguity. 1708 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1709 /*DetectVirtual=*/false); 1710 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1711 assert(DerivationOkay && 1712 "Can only be used with a derived-to-base conversion"); 1713 (void)DerivationOkay; 1714 1715 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1716 if (InaccessibleBaseID) { 1717 // Check that the base class can be accessed. 1718 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1719 InaccessibleBaseID)) { 1720 case AR_inaccessible: 1721 return true; 1722 case AR_accessible: 1723 case AR_dependent: 1724 case AR_delayed: 1725 break; 1726 } 1727 } 1728 1729 // Build a base path if necessary. 1730 if (BasePath) 1731 BuildBasePathArray(Paths, *BasePath); 1732 return false; 1733 } 1734 1735 if (AmbigiousBaseConvID) { 1736 // We know that the derived-to-base conversion is ambiguous, and 1737 // we're going to produce a diagnostic. Perform the derived-to-base 1738 // search just one more time to compute all of the possible paths so 1739 // that we can print them out. This is more expensive than any of 1740 // the previous derived-to-base checks we've done, but at this point 1741 // performance isn't as much of an issue. 1742 Paths.clear(); 1743 Paths.setRecordingPaths(true); 1744 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1745 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1746 (void)StillOkay; 1747 1748 // Build up a textual representation of the ambiguous paths, e.g., 1749 // D -> B -> A, that will be used to illustrate the ambiguous 1750 // conversions in the diagnostic. We only print one of the paths 1751 // to each base class subobject. 1752 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1753 1754 Diag(Loc, AmbigiousBaseConvID) 1755 << Derived << Base << PathDisplayStr << Range << Name; 1756 } 1757 return true; 1758 } 1759 1760 bool 1761 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1762 SourceLocation Loc, SourceRange Range, 1763 CXXCastPath *BasePath, 1764 bool IgnoreAccess) { 1765 return CheckDerivedToBaseConversion(Derived, Base, 1766 IgnoreAccess ? 0 1767 : diag::err_upcast_to_inaccessible_base, 1768 diag::err_ambiguous_derived_to_base_conv, 1769 Loc, Range, DeclarationName(), 1770 BasePath); 1771 } 1772 1773 1774 /// @brief Builds a string representing ambiguous paths from a 1775 /// specific derived class to different subobjects of the same base 1776 /// class. 1777 /// 1778 /// This function builds a string that can be used in error messages 1779 /// to show the different paths that one can take through the 1780 /// inheritance hierarchy to go from the derived class to different 1781 /// subobjects of a base class. The result looks something like this: 1782 /// @code 1783 /// struct D -> struct B -> struct A 1784 /// struct D -> struct C -> struct A 1785 /// @endcode 1786 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1787 std::string PathDisplayStr; 1788 std::set<unsigned> DisplayedPaths; 1789 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1790 Path != Paths.end(); ++Path) { 1791 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1792 // We haven't displayed a path to this particular base 1793 // class subobject yet. 1794 PathDisplayStr += "\n "; 1795 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1796 for (CXXBasePath::const_iterator Element = Path->begin(); 1797 Element != Path->end(); ++Element) 1798 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1799 } 1800 } 1801 1802 return PathDisplayStr; 1803 } 1804 1805 //===----------------------------------------------------------------------===// 1806 // C++ class member Handling 1807 //===----------------------------------------------------------------------===// 1808 1809 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1810 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1811 SourceLocation ASLoc, 1812 SourceLocation ColonLoc, 1813 AttributeList *Attrs) { 1814 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1815 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1816 ASLoc, ColonLoc); 1817 CurContext->addHiddenDecl(ASDecl); 1818 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1819 } 1820 1821 /// CheckOverrideControl - Check C++11 override control semantics. 1822 void Sema::CheckOverrideControl(NamedDecl *D) { 1823 if (D->isInvalidDecl()) 1824 return; 1825 1826 // We only care about "override" and "final" declarations. 1827 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1828 return; 1829 1830 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1831 1832 // We can't check dependent instance methods. 1833 if (MD && MD->isInstance() && 1834 (MD->getParent()->hasAnyDependentBases() || 1835 MD->getType()->isDependentType())) 1836 return; 1837 1838 if (MD && !MD->isVirtual()) { 1839 // If we have a non-virtual method, check if if hides a virtual method. 1840 // (In that case, it's most likely the method has the wrong type.) 1841 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1842 FindHiddenVirtualMethods(MD, OverloadedMethods); 1843 1844 if (!OverloadedMethods.empty()) { 1845 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1846 Diag(OA->getLocation(), 1847 diag::override_keyword_hides_virtual_member_function) 1848 << "override" << (OverloadedMethods.size() > 1); 1849 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1850 Diag(FA->getLocation(), 1851 diag::override_keyword_hides_virtual_member_function) 1852 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1853 << (OverloadedMethods.size() > 1); 1854 } 1855 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1856 MD->setInvalidDecl(); 1857 return; 1858 } 1859 // Fall through into the general case diagnostic. 1860 // FIXME: We might want to attempt typo correction here. 1861 } 1862 1863 if (!MD || !MD->isVirtual()) { 1864 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1865 Diag(OA->getLocation(), 1866 diag::override_keyword_only_allowed_on_virtual_member_functions) 1867 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1868 D->dropAttr<OverrideAttr>(); 1869 } 1870 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1871 Diag(FA->getLocation(), 1872 diag::override_keyword_only_allowed_on_virtual_member_functions) 1873 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1874 << FixItHint::CreateRemoval(FA->getLocation()); 1875 D->dropAttr<FinalAttr>(); 1876 } 1877 return; 1878 } 1879 1880 // C++11 [class.virtual]p5: 1881 // If a virtual function is marked with the virt-specifier override and 1882 // does not override a member function of a base class, the program is 1883 // ill-formed. 1884 bool HasOverriddenMethods = 1885 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1886 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1887 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1888 << MD->getDeclName(); 1889 } 1890 1891 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1892 /// function overrides a virtual member function marked 'final', according to 1893 /// C++11 [class.virtual]p4. 1894 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1895 const CXXMethodDecl *Old) { 1896 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1897 if (!FA) 1898 return false; 1899 1900 Diag(New->getLocation(), diag::err_final_function_overridden) 1901 << New->getDeclName() 1902 << FA->isSpelledAsSealed(); 1903 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1904 return true; 1905 } 1906 1907 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1908 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1909 // FIXME: Destruction of ObjC lifetime types has side-effects. 1910 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1911 return !RD->isCompleteDefinition() || 1912 !RD->hasTrivialDefaultConstructor() || 1913 !RD->hasTrivialDestructor(); 1914 return false; 1915 } 1916 1917 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1918 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1919 if (it->isDeclspecPropertyAttribute()) 1920 return it; 1921 return nullptr; 1922 } 1923 1924 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1925 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1926 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1927 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1928 /// present (but parsing it has been deferred). 1929 NamedDecl * 1930 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1931 MultiTemplateParamsArg TemplateParameterLists, 1932 Expr *BW, const VirtSpecifiers &VS, 1933 InClassInitStyle InitStyle) { 1934 const DeclSpec &DS = D.getDeclSpec(); 1935 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1936 DeclarationName Name = NameInfo.getName(); 1937 SourceLocation Loc = NameInfo.getLoc(); 1938 1939 // For anonymous bitfields, the location should point to the type. 1940 if (Loc.isInvalid()) 1941 Loc = D.getLocStart(); 1942 1943 Expr *BitWidth = static_cast<Expr*>(BW); 1944 1945 assert(isa<CXXRecordDecl>(CurContext)); 1946 assert(!DS.isFriendSpecified()); 1947 1948 bool isFunc = D.isDeclarationOfFunction(); 1949 1950 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1951 // The Microsoft extension __interface only permits public member functions 1952 // and prohibits constructors, destructors, operators, non-public member 1953 // functions, static methods and data members. 1954 unsigned InvalidDecl; 1955 bool ShowDeclName = true; 1956 if (!isFunc) 1957 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1958 else if (AS != AS_public) 1959 InvalidDecl = 2; 1960 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1961 InvalidDecl = 3; 1962 else switch (Name.getNameKind()) { 1963 case DeclarationName::CXXConstructorName: 1964 InvalidDecl = 4; 1965 ShowDeclName = false; 1966 break; 1967 1968 case DeclarationName::CXXDestructorName: 1969 InvalidDecl = 5; 1970 ShowDeclName = false; 1971 break; 1972 1973 case DeclarationName::CXXOperatorName: 1974 case DeclarationName::CXXConversionFunctionName: 1975 InvalidDecl = 6; 1976 break; 1977 1978 default: 1979 InvalidDecl = 0; 1980 break; 1981 } 1982 1983 if (InvalidDecl) { 1984 if (ShowDeclName) 1985 Diag(Loc, diag::err_invalid_member_in_interface) 1986 << (InvalidDecl-1) << Name; 1987 else 1988 Diag(Loc, diag::err_invalid_member_in_interface) 1989 << (InvalidDecl-1) << ""; 1990 return nullptr; 1991 } 1992 } 1993 1994 // C++ 9.2p6: A member shall not be declared to have automatic storage 1995 // duration (auto, register) or with the extern storage-class-specifier. 1996 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1997 // data members and cannot be applied to names declared const or static, 1998 // and cannot be applied to reference members. 1999 switch (DS.getStorageClassSpec()) { 2000 case DeclSpec::SCS_unspecified: 2001 case DeclSpec::SCS_typedef: 2002 case DeclSpec::SCS_static: 2003 break; 2004 case DeclSpec::SCS_mutable: 2005 if (isFunc) { 2006 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2007 2008 // FIXME: It would be nicer if the keyword was ignored only for this 2009 // declarator. Otherwise we could get follow-up errors. 2010 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2011 } 2012 break; 2013 default: 2014 Diag(DS.getStorageClassSpecLoc(), 2015 diag::err_storageclass_invalid_for_member); 2016 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2017 break; 2018 } 2019 2020 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2021 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2022 !isFunc); 2023 2024 if (DS.isConstexprSpecified() && isInstField) { 2025 SemaDiagnosticBuilder B = 2026 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2027 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2028 if (InitStyle == ICIS_NoInit) { 2029 B << 0 << 0; 2030 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2031 B << FixItHint::CreateRemoval(ConstexprLoc); 2032 else { 2033 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2034 D.getMutableDeclSpec().ClearConstexprSpec(); 2035 const char *PrevSpec; 2036 unsigned DiagID; 2037 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2038 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2039 (void)Failed; 2040 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2041 } 2042 } else { 2043 B << 1; 2044 const char *PrevSpec; 2045 unsigned DiagID; 2046 if (D.getMutableDeclSpec().SetStorageClassSpec( 2047 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2048 Context.getPrintingPolicy())) { 2049 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2050 "This is the only DeclSpec that should fail to be applied"); 2051 B << 1; 2052 } else { 2053 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2054 isInstField = false; 2055 } 2056 } 2057 } 2058 2059 NamedDecl *Member; 2060 if (isInstField) { 2061 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2062 2063 // Data members must have identifiers for names. 2064 if (!Name.isIdentifier()) { 2065 Diag(Loc, diag::err_bad_variable_name) 2066 << Name; 2067 return nullptr; 2068 } 2069 2070 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2071 2072 // Member field could not be with "template" keyword. 2073 // So TemplateParameterLists should be empty in this case. 2074 if (TemplateParameterLists.size()) { 2075 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2076 if (TemplateParams->size()) { 2077 // There is no such thing as a member field template. 2078 Diag(D.getIdentifierLoc(), diag::err_template_member) 2079 << II 2080 << SourceRange(TemplateParams->getTemplateLoc(), 2081 TemplateParams->getRAngleLoc()); 2082 } else { 2083 // There is an extraneous 'template<>' for this member. 2084 Diag(TemplateParams->getTemplateLoc(), 2085 diag::err_template_member_noparams) 2086 << II 2087 << SourceRange(TemplateParams->getTemplateLoc(), 2088 TemplateParams->getRAngleLoc()); 2089 } 2090 return nullptr; 2091 } 2092 2093 if (SS.isSet() && !SS.isInvalid()) { 2094 // The user provided a superfluous scope specifier inside a class 2095 // definition: 2096 // 2097 // class X { 2098 // int X::member; 2099 // }; 2100 if (DeclContext *DC = computeDeclContext(SS, false)) 2101 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2102 else 2103 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2104 << Name << SS.getRange(); 2105 2106 SS.clear(); 2107 } 2108 2109 AttributeList *MSPropertyAttr = 2110 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2111 if (MSPropertyAttr) { 2112 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2113 BitWidth, InitStyle, AS, MSPropertyAttr); 2114 if (!Member) 2115 return nullptr; 2116 isInstField = false; 2117 } else { 2118 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2119 BitWidth, InitStyle, AS); 2120 assert(Member && "HandleField never returns null"); 2121 } 2122 } else { 2123 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2124 2125 Member = HandleDeclarator(S, D, TemplateParameterLists); 2126 if (!Member) 2127 return nullptr; 2128 2129 // Non-instance-fields can't have a bitfield. 2130 if (BitWidth) { 2131 if (Member->isInvalidDecl()) { 2132 // don't emit another diagnostic. 2133 } else if (isa<VarDecl>(Member)) { 2134 // C++ 9.6p3: A bit-field shall not be a static member. 2135 // "static member 'A' cannot be a bit-field" 2136 Diag(Loc, diag::err_static_not_bitfield) 2137 << Name << BitWidth->getSourceRange(); 2138 } else if (isa<TypedefDecl>(Member)) { 2139 // "typedef member 'x' cannot be a bit-field" 2140 Diag(Loc, diag::err_typedef_not_bitfield) 2141 << Name << BitWidth->getSourceRange(); 2142 } else { 2143 // A function typedef ("typedef int f(); f a;"). 2144 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2145 Diag(Loc, diag::err_not_integral_type_bitfield) 2146 << Name << cast<ValueDecl>(Member)->getType() 2147 << BitWidth->getSourceRange(); 2148 } 2149 2150 BitWidth = nullptr; 2151 Member->setInvalidDecl(); 2152 } 2153 2154 Member->setAccess(AS); 2155 2156 // If we have declared a member function template or static data member 2157 // template, set the access of the templated declaration as well. 2158 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2159 FunTmpl->getTemplatedDecl()->setAccess(AS); 2160 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2161 VarTmpl->getTemplatedDecl()->setAccess(AS); 2162 } 2163 2164 if (VS.isOverrideSpecified()) 2165 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2166 if (VS.isFinalSpecified()) 2167 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2168 VS.isFinalSpelledSealed())); 2169 2170 if (VS.getLastLocation().isValid()) { 2171 // Update the end location of a method that has a virt-specifiers. 2172 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2173 MD->setRangeEnd(VS.getLastLocation()); 2174 } 2175 2176 CheckOverrideControl(Member); 2177 2178 assert((Name || isInstField) && "No identifier for non-field ?"); 2179 2180 if (isInstField) { 2181 FieldDecl *FD = cast<FieldDecl>(Member); 2182 FieldCollector->Add(FD); 2183 2184 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2185 // Remember all explicit private FieldDecls that have a name, no side 2186 // effects and are not part of a dependent type declaration. 2187 if (!FD->isImplicit() && FD->getDeclName() && 2188 FD->getAccess() == AS_private && 2189 !FD->hasAttr<UnusedAttr>() && 2190 !FD->getParent()->isDependentContext() && 2191 !InitializationHasSideEffects(*FD)) 2192 UnusedPrivateFields.insert(FD); 2193 } 2194 } 2195 2196 return Member; 2197 } 2198 2199 namespace { 2200 class UninitializedFieldVisitor 2201 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2202 Sema &S; 2203 // List of Decls to generate a warning on. Also remove Decls that become 2204 // initialized. 2205 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2206 // If non-null, add a note to the warning pointing back to the constructor. 2207 const CXXConstructorDecl *Constructor; 2208 public: 2209 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2210 UninitializedFieldVisitor(Sema &S, 2211 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2212 const CXXConstructorDecl *Constructor) 2213 : Inherited(S.Context), S(S), Decls(Decls), 2214 Constructor(Constructor) { } 2215 2216 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2217 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2218 return; 2219 2220 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2221 // or union. 2222 MemberExpr *FieldME = ME; 2223 2224 Expr *Base = ME; 2225 while (isa<MemberExpr>(Base)) { 2226 ME = cast<MemberExpr>(Base); 2227 2228 if (isa<VarDecl>(ME->getMemberDecl())) 2229 return; 2230 2231 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2232 if (!FD->isAnonymousStructOrUnion()) 2233 FieldME = ME; 2234 2235 Base = ME->getBase(); 2236 } 2237 2238 if (!isa<CXXThisExpr>(Base)) 2239 return; 2240 2241 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2242 2243 if (!Decls.count(FoundVD)) 2244 return; 2245 2246 const bool IsReference = FoundVD->getType()->isReferenceType(); 2247 2248 // Prevent double warnings on use of unbounded references. 2249 if (IsReference != CheckReferenceOnly) 2250 return; 2251 2252 unsigned diag = IsReference 2253 ? diag::warn_reference_field_is_uninit 2254 : diag::warn_field_is_uninit; 2255 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2256 if (Constructor) 2257 S.Diag(Constructor->getLocation(), 2258 diag::note_uninit_in_this_constructor) 2259 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2260 2261 } 2262 2263 void HandleValue(Expr *E) { 2264 E = E->IgnoreParens(); 2265 2266 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2267 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2268 return; 2269 } 2270 2271 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2272 HandleValue(CO->getTrueExpr()); 2273 HandleValue(CO->getFalseExpr()); 2274 return; 2275 } 2276 2277 if (BinaryConditionalOperator *BCO = 2278 dyn_cast<BinaryConditionalOperator>(E)) { 2279 HandleValue(BCO->getCommon()); 2280 HandleValue(BCO->getFalseExpr()); 2281 return; 2282 } 2283 2284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2285 switch (BO->getOpcode()) { 2286 default: 2287 return; 2288 case(BO_PtrMemD): 2289 case(BO_PtrMemI): 2290 HandleValue(BO->getLHS()); 2291 return; 2292 case(BO_Comma): 2293 HandleValue(BO->getRHS()); 2294 return; 2295 } 2296 } 2297 } 2298 2299 void VisitMemberExpr(MemberExpr *ME) { 2300 // All uses of unbounded reference fields will warn. 2301 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2302 2303 Inherited::VisitMemberExpr(ME); 2304 } 2305 2306 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2307 if (E->getCastKind() == CK_LValueToRValue) 2308 HandleValue(E->getSubExpr()); 2309 2310 Inherited::VisitImplicitCastExpr(E); 2311 } 2312 2313 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2314 if (E->getConstructor()->isCopyConstructor()) 2315 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0))) 2316 if (ICE->getCastKind() == CK_NoOp) 2317 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr())) 2318 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2319 2320 Inherited::VisitCXXConstructExpr(E); 2321 } 2322 2323 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2324 Expr *Callee = E->getCallee(); 2325 if (isa<MemberExpr>(Callee)) 2326 HandleValue(Callee); 2327 2328 Inherited::VisitCXXMemberCallExpr(E); 2329 } 2330 2331 void VisitBinaryOperator(BinaryOperator *E) { 2332 // If a field assignment is detected, remove the field from the 2333 // uninitiailized field set. 2334 if (E->getOpcode() == BO_Assign) 2335 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2336 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2337 if (!FD->getType()->isReferenceType()) 2338 Decls.erase(FD); 2339 2340 Inherited::VisitBinaryOperator(E); 2341 } 2342 }; 2343 static void CheckInitExprContainsUninitializedFields( 2344 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2345 const CXXConstructorDecl *Constructor) { 2346 if (Decls.size() == 0) 2347 return; 2348 2349 if (!E) 2350 return; 2351 2352 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) { 2353 E = Default->getExpr(); 2354 if (!E) 2355 return; 2356 // In class initializers will point to the constructor. 2357 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E); 2358 } else { 2359 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E); 2360 } 2361 } 2362 2363 // Diagnose value-uses of fields to initialize themselves, e.g. 2364 // foo(foo) 2365 // where foo is not also a parameter to the constructor. 2366 // Also diagnose across field uninitialized use such as 2367 // x(y), y(x) 2368 // TODO: implement -Wuninitialized and fold this into that framework. 2369 static void DiagnoseUninitializedFields( 2370 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2371 2372 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2373 Constructor->getLocation())) { 2374 return; 2375 } 2376 2377 if (Constructor->isInvalidDecl()) 2378 return; 2379 2380 const CXXRecordDecl *RD = Constructor->getParent(); 2381 2382 // Holds fields that are uninitialized. 2383 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2384 2385 // At the beginning, all fields are uninitialized. 2386 for (auto *I : RD->decls()) { 2387 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2388 UninitializedFields.insert(FD); 2389 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2390 UninitializedFields.insert(IFD->getAnonField()); 2391 } 2392 } 2393 2394 for (const auto *FieldInit : Constructor->inits()) { 2395 Expr *InitExpr = FieldInit->getInit(); 2396 2397 CheckInitExprContainsUninitializedFields( 2398 SemaRef, InitExpr, UninitializedFields, Constructor); 2399 2400 if (FieldDecl *Field = FieldInit->getAnyMember()) 2401 UninitializedFields.erase(Field); 2402 } 2403 } 2404 } // namespace 2405 2406 /// \brief Enter a new C++ default initializer scope. After calling this, the 2407 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2408 /// parsing or instantiating the initializer failed. 2409 void Sema::ActOnStartCXXInClassMemberInitializer() { 2410 // Create a synthetic function scope to represent the call to the constructor 2411 // that notionally surrounds a use of this initializer. 2412 PushFunctionScope(); 2413 } 2414 2415 /// \brief This is invoked after parsing an in-class initializer for a 2416 /// non-static C++ class member, and after instantiating an in-class initializer 2417 /// in a class template. Such actions are deferred until the class is complete. 2418 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2419 SourceLocation InitLoc, 2420 Expr *InitExpr) { 2421 // Pop the notional constructor scope we created earlier. 2422 PopFunctionScopeInfo(nullptr, D); 2423 2424 FieldDecl *FD = cast<FieldDecl>(D); 2425 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2426 "must set init style when field is created"); 2427 2428 if (!InitExpr) { 2429 FD->setInvalidDecl(); 2430 FD->removeInClassInitializer(); 2431 return; 2432 } 2433 2434 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2435 FD->setInvalidDecl(); 2436 FD->removeInClassInitializer(); 2437 return; 2438 } 2439 2440 ExprResult Init = InitExpr; 2441 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2442 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2443 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2444 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2445 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2446 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2447 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2448 if (Init.isInvalid()) { 2449 FD->setInvalidDecl(); 2450 return; 2451 } 2452 } 2453 2454 // C++11 [class.base.init]p7: 2455 // The initialization of each base and member constitutes a 2456 // full-expression. 2457 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2458 if (Init.isInvalid()) { 2459 FD->setInvalidDecl(); 2460 return; 2461 } 2462 2463 InitExpr = Init.get(); 2464 2465 FD->setInClassInitializer(InitExpr); 2466 } 2467 2468 /// \brief Find the direct and/or virtual base specifiers that 2469 /// correspond to the given base type, for use in base initialization 2470 /// within a constructor. 2471 static bool FindBaseInitializer(Sema &SemaRef, 2472 CXXRecordDecl *ClassDecl, 2473 QualType BaseType, 2474 const CXXBaseSpecifier *&DirectBaseSpec, 2475 const CXXBaseSpecifier *&VirtualBaseSpec) { 2476 // First, check for a direct base class. 2477 DirectBaseSpec = nullptr; 2478 for (const auto &Base : ClassDecl->bases()) { 2479 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2480 // We found a direct base of this type. That's what we're 2481 // initializing. 2482 DirectBaseSpec = &Base; 2483 break; 2484 } 2485 } 2486 2487 // Check for a virtual base class. 2488 // FIXME: We might be able to short-circuit this if we know in advance that 2489 // there are no virtual bases. 2490 VirtualBaseSpec = nullptr; 2491 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2492 // We haven't found a base yet; search the class hierarchy for a 2493 // virtual base class. 2494 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2495 /*DetectVirtual=*/false); 2496 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2497 BaseType, Paths)) { 2498 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2499 Path != Paths.end(); ++Path) { 2500 if (Path->back().Base->isVirtual()) { 2501 VirtualBaseSpec = Path->back().Base; 2502 break; 2503 } 2504 } 2505 } 2506 } 2507 2508 return DirectBaseSpec || VirtualBaseSpec; 2509 } 2510 2511 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2512 MemInitResult 2513 Sema::ActOnMemInitializer(Decl *ConstructorD, 2514 Scope *S, 2515 CXXScopeSpec &SS, 2516 IdentifierInfo *MemberOrBase, 2517 ParsedType TemplateTypeTy, 2518 const DeclSpec &DS, 2519 SourceLocation IdLoc, 2520 Expr *InitList, 2521 SourceLocation EllipsisLoc) { 2522 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2523 DS, IdLoc, InitList, 2524 EllipsisLoc); 2525 } 2526 2527 /// \brief Handle a C++ member initializer using parentheses syntax. 2528 MemInitResult 2529 Sema::ActOnMemInitializer(Decl *ConstructorD, 2530 Scope *S, 2531 CXXScopeSpec &SS, 2532 IdentifierInfo *MemberOrBase, 2533 ParsedType TemplateTypeTy, 2534 const DeclSpec &DS, 2535 SourceLocation IdLoc, 2536 SourceLocation LParenLoc, 2537 ArrayRef<Expr *> Args, 2538 SourceLocation RParenLoc, 2539 SourceLocation EllipsisLoc) { 2540 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2541 Args, RParenLoc); 2542 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2543 DS, IdLoc, List, EllipsisLoc); 2544 } 2545 2546 namespace { 2547 2548 // Callback to only accept typo corrections that can be a valid C++ member 2549 // intializer: either a non-static field member or a base class. 2550 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2551 public: 2552 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2553 : ClassDecl(ClassDecl) {} 2554 2555 bool ValidateCandidate(const TypoCorrection &candidate) override { 2556 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2557 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2558 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2559 return isa<TypeDecl>(ND); 2560 } 2561 return false; 2562 } 2563 2564 private: 2565 CXXRecordDecl *ClassDecl; 2566 }; 2567 2568 } 2569 2570 /// \brief Handle a C++ member initializer. 2571 MemInitResult 2572 Sema::BuildMemInitializer(Decl *ConstructorD, 2573 Scope *S, 2574 CXXScopeSpec &SS, 2575 IdentifierInfo *MemberOrBase, 2576 ParsedType TemplateTypeTy, 2577 const DeclSpec &DS, 2578 SourceLocation IdLoc, 2579 Expr *Init, 2580 SourceLocation EllipsisLoc) { 2581 if (!ConstructorD) 2582 return true; 2583 2584 AdjustDeclIfTemplate(ConstructorD); 2585 2586 CXXConstructorDecl *Constructor 2587 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2588 if (!Constructor) { 2589 // The user wrote a constructor initializer on a function that is 2590 // not a C++ constructor. Ignore the error for now, because we may 2591 // have more member initializers coming; we'll diagnose it just 2592 // once in ActOnMemInitializers. 2593 return true; 2594 } 2595 2596 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2597 2598 // C++ [class.base.init]p2: 2599 // Names in a mem-initializer-id are looked up in the scope of the 2600 // constructor's class and, if not found in that scope, are looked 2601 // up in the scope containing the constructor's definition. 2602 // [Note: if the constructor's class contains a member with the 2603 // same name as a direct or virtual base class of the class, a 2604 // mem-initializer-id naming the member or base class and composed 2605 // of a single identifier refers to the class member. A 2606 // mem-initializer-id for the hidden base class may be specified 2607 // using a qualified name. ] 2608 if (!SS.getScopeRep() && !TemplateTypeTy) { 2609 // Look for a member, first. 2610 DeclContext::lookup_result Result 2611 = ClassDecl->lookup(MemberOrBase); 2612 if (!Result.empty()) { 2613 ValueDecl *Member; 2614 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2615 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2616 if (EllipsisLoc.isValid()) 2617 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2618 << MemberOrBase 2619 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2620 2621 return BuildMemberInitializer(Member, Init, IdLoc); 2622 } 2623 } 2624 } 2625 // It didn't name a member, so see if it names a class. 2626 QualType BaseType; 2627 TypeSourceInfo *TInfo = nullptr; 2628 2629 if (TemplateTypeTy) { 2630 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2631 } else if (DS.getTypeSpecType() == TST_decltype) { 2632 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2633 } else { 2634 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2635 LookupParsedName(R, S, &SS); 2636 2637 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2638 if (!TyD) { 2639 if (R.isAmbiguous()) return true; 2640 2641 // We don't want access-control diagnostics here. 2642 R.suppressDiagnostics(); 2643 2644 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2645 bool NotUnknownSpecialization = false; 2646 DeclContext *DC = computeDeclContext(SS, false); 2647 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2648 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2649 2650 if (!NotUnknownSpecialization) { 2651 // When the scope specifier can refer to a member of an unknown 2652 // specialization, we take it as a type name. 2653 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2654 SS.getWithLocInContext(Context), 2655 *MemberOrBase, IdLoc); 2656 if (BaseType.isNull()) 2657 return true; 2658 2659 R.clear(); 2660 R.setLookupName(MemberOrBase); 2661 } 2662 } 2663 2664 // If no results were found, try to correct typos. 2665 TypoCorrection Corr; 2666 MemInitializerValidatorCCC Validator(ClassDecl); 2667 if (R.empty() && BaseType.isNull() && 2668 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2669 Validator, CTK_ErrorRecovery, ClassDecl))) { 2670 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2671 // We have found a non-static data member with a similar 2672 // name to what was typed; complain and initialize that 2673 // member. 2674 diagnoseTypo(Corr, 2675 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2676 << MemberOrBase << true); 2677 return BuildMemberInitializer(Member, Init, IdLoc); 2678 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2679 const CXXBaseSpecifier *DirectBaseSpec; 2680 const CXXBaseSpecifier *VirtualBaseSpec; 2681 if (FindBaseInitializer(*this, ClassDecl, 2682 Context.getTypeDeclType(Type), 2683 DirectBaseSpec, VirtualBaseSpec)) { 2684 // We have found a direct or virtual base class with a 2685 // similar name to what was typed; complain and initialize 2686 // that base class. 2687 diagnoseTypo(Corr, 2688 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2689 << MemberOrBase << false, 2690 PDiag() /*Suppress note, we provide our own.*/); 2691 2692 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2693 : VirtualBaseSpec; 2694 Diag(BaseSpec->getLocStart(), 2695 diag::note_base_class_specified_here) 2696 << BaseSpec->getType() 2697 << BaseSpec->getSourceRange(); 2698 2699 TyD = Type; 2700 } 2701 } 2702 } 2703 2704 if (!TyD && BaseType.isNull()) { 2705 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2706 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2707 return true; 2708 } 2709 } 2710 2711 if (BaseType.isNull()) { 2712 BaseType = Context.getTypeDeclType(TyD); 2713 if (SS.isSet()) 2714 // FIXME: preserve source range information 2715 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2716 BaseType); 2717 } 2718 } 2719 2720 if (!TInfo) 2721 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2722 2723 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2724 } 2725 2726 /// Checks a member initializer expression for cases where reference (or 2727 /// pointer) members are bound to by-value parameters (or their addresses). 2728 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2729 Expr *Init, 2730 SourceLocation IdLoc) { 2731 QualType MemberTy = Member->getType(); 2732 2733 // We only handle pointers and references currently. 2734 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2735 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2736 return; 2737 2738 const bool IsPointer = MemberTy->isPointerType(); 2739 if (IsPointer) { 2740 if (const UnaryOperator *Op 2741 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2742 // The only case we're worried about with pointers requires taking the 2743 // address. 2744 if (Op->getOpcode() != UO_AddrOf) 2745 return; 2746 2747 Init = Op->getSubExpr(); 2748 } else { 2749 // We only handle address-of expression initializers for pointers. 2750 return; 2751 } 2752 } 2753 2754 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2755 // We only warn when referring to a non-reference parameter declaration. 2756 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2757 if (!Parameter || Parameter->getType()->isReferenceType()) 2758 return; 2759 2760 S.Diag(Init->getExprLoc(), 2761 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2762 : diag::warn_bind_ref_member_to_parameter) 2763 << Member << Parameter << Init->getSourceRange(); 2764 } else { 2765 // Other initializers are fine. 2766 return; 2767 } 2768 2769 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2770 << (unsigned)IsPointer; 2771 } 2772 2773 MemInitResult 2774 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2775 SourceLocation IdLoc) { 2776 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2777 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2778 assert((DirectMember || IndirectMember) && 2779 "Member must be a FieldDecl or IndirectFieldDecl"); 2780 2781 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2782 return true; 2783 2784 if (Member->isInvalidDecl()) 2785 return true; 2786 2787 MultiExprArg Args; 2788 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2789 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2790 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2791 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2792 } else { 2793 // Template instantiation doesn't reconstruct ParenListExprs for us. 2794 Args = Init; 2795 } 2796 2797 SourceRange InitRange = Init->getSourceRange(); 2798 2799 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2800 // Can't check initialization for a member of dependent type or when 2801 // any of the arguments are type-dependent expressions. 2802 DiscardCleanupsInEvaluationContext(); 2803 } else { 2804 bool InitList = false; 2805 if (isa<InitListExpr>(Init)) { 2806 InitList = true; 2807 Args = Init; 2808 } 2809 2810 // Initialize the member. 2811 InitializedEntity MemberEntity = 2812 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 2813 : InitializedEntity::InitializeMember(IndirectMember, 2814 nullptr); 2815 InitializationKind Kind = 2816 InitList ? InitializationKind::CreateDirectList(IdLoc) 2817 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2818 InitRange.getEnd()); 2819 2820 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2821 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 2822 nullptr); 2823 if (MemberInit.isInvalid()) 2824 return true; 2825 2826 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2827 2828 // C++11 [class.base.init]p7: 2829 // The initialization of each base and member constitutes a 2830 // full-expression. 2831 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2832 if (MemberInit.isInvalid()) 2833 return true; 2834 2835 Init = MemberInit.get(); 2836 } 2837 2838 if (DirectMember) { 2839 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2840 InitRange.getBegin(), Init, 2841 InitRange.getEnd()); 2842 } else { 2843 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2844 InitRange.getBegin(), Init, 2845 InitRange.getEnd()); 2846 } 2847 } 2848 2849 MemInitResult 2850 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2851 CXXRecordDecl *ClassDecl) { 2852 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2853 if (!LangOpts.CPlusPlus11) 2854 return Diag(NameLoc, diag::err_delegating_ctor) 2855 << TInfo->getTypeLoc().getLocalSourceRange(); 2856 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2857 2858 bool InitList = true; 2859 MultiExprArg Args = Init; 2860 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2861 InitList = false; 2862 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2863 } 2864 2865 SourceRange InitRange = Init->getSourceRange(); 2866 // Initialize the object. 2867 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2868 QualType(ClassDecl->getTypeForDecl(), 0)); 2869 InitializationKind Kind = 2870 InitList ? InitializationKind::CreateDirectList(NameLoc) 2871 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2872 InitRange.getEnd()); 2873 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2874 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2875 Args, nullptr); 2876 if (DelegationInit.isInvalid()) 2877 return true; 2878 2879 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2880 "Delegating constructor with no target?"); 2881 2882 // C++11 [class.base.init]p7: 2883 // The initialization of each base and member constitutes a 2884 // full-expression. 2885 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2886 InitRange.getBegin()); 2887 if (DelegationInit.isInvalid()) 2888 return true; 2889 2890 // If we are in a dependent context, template instantiation will 2891 // perform this type-checking again. Just save the arguments that we 2892 // received in a ParenListExpr. 2893 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2894 // of the information that we have about the base 2895 // initializer. However, deconstructing the ASTs is a dicey process, 2896 // and this approach is far more likely to get the corner cases right. 2897 if (CurContext->isDependentContext()) 2898 DelegationInit = Init; 2899 2900 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2901 DelegationInit.getAs<Expr>(), 2902 InitRange.getEnd()); 2903 } 2904 2905 MemInitResult 2906 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2907 Expr *Init, CXXRecordDecl *ClassDecl, 2908 SourceLocation EllipsisLoc) { 2909 SourceLocation BaseLoc 2910 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2911 2912 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2913 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2914 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2915 2916 // C++ [class.base.init]p2: 2917 // [...] Unless the mem-initializer-id names a nonstatic data 2918 // member of the constructor's class or a direct or virtual base 2919 // of that class, the mem-initializer is ill-formed. A 2920 // mem-initializer-list can initialize a base class using any 2921 // name that denotes that base class type. 2922 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2923 2924 SourceRange InitRange = Init->getSourceRange(); 2925 if (EllipsisLoc.isValid()) { 2926 // This is a pack expansion. 2927 if (!BaseType->containsUnexpandedParameterPack()) { 2928 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2929 << SourceRange(BaseLoc, InitRange.getEnd()); 2930 2931 EllipsisLoc = SourceLocation(); 2932 } 2933 } else { 2934 // Check for any unexpanded parameter packs. 2935 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2936 return true; 2937 2938 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2939 return true; 2940 } 2941 2942 // Check for direct and virtual base classes. 2943 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 2944 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 2945 if (!Dependent) { 2946 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2947 BaseType)) 2948 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2949 2950 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2951 VirtualBaseSpec); 2952 2953 // C++ [base.class.init]p2: 2954 // Unless the mem-initializer-id names a nonstatic data member of the 2955 // constructor's class or a direct or virtual base of that class, the 2956 // mem-initializer is ill-formed. 2957 if (!DirectBaseSpec && !VirtualBaseSpec) { 2958 // If the class has any dependent bases, then it's possible that 2959 // one of those types will resolve to the same type as 2960 // BaseType. Therefore, just treat this as a dependent base 2961 // class initialization. FIXME: Should we try to check the 2962 // initialization anyway? It seems odd. 2963 if (ClassDecl->hasAnyDependentBases()) 2964 Dependent = true; 2965 else 2966 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2967 << BaseType << Context.getTypeDeclType(ClassDecl) 2968 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2969 } 2970 } 2971 2972 if (Dependent) { 2973 DiscardCleanupsInEvaluationContext(); 2974 2975 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2976 /*IsVirtual=*/false, 2977 InitRange.getBegin(), Init, 2978 InitRange.getEnd(), EllipsisLoc); 2979 } 2980 2981 // C++ [base.class.init]p2: 2982 // If a mem-initializer-id is ambiguous because it designates both 2983 // a direct non-virtual base class and an inherited virtual base 2984 // class, the mem-initializer is ill-formed. 2985 if (DirectBaseSpec && VirtualBaseSpec) 2986 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2987 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2988 2989 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2990 if (!BaseSpec) 2991 BaseSpec = VirtualBaseSpec; 2992 2993 // Initialize the base. 2994 bool InitList = true; 2995 MultiExprArg Args = Init; 2996 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2997 InitList = false; 2998 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2999 } 3000 3001 InitializedEntity BaseEntity = 3002 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3003 InitializationKind Kind = 3004 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3005 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3006 InitRange.getEnd()); 3007 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3008 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3009 if (BaseInit.isInvalid()) 3010 return true; 3011 3012 // C++11 [class.base.init]p7: 3013 // The initialization of each base and member constitutes a 3014 // full-expression. 3015 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3016 if (BaseInit.isInvalid()) 3017 return true; 3018 3019 // If we are in a dependent context, template instantiation will 3020 // perform this type-checking again. Just save the arguments that we 3021 // received in a ParenListExpr. 3022 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3023 // of the information that we have about the base 3024 // initializer. However, deconstructing the ASTs is a dicey process, 3025 // and this approach is far more likely to get the corner cases right. 3026 if (CurContext->isDependentContext()) 3027 BaseInit = Init; 3028 3029 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3030 BaseSpec->isVirtual(), 3031 InitRange.getBegin(), 3032 BaseInit.getAs<Expr>(), 3033 InitRange.getEnd(), EllipsisLoc); 3034 } 3035 3036 // Create a static_cast\<T&&>(expr). 3037 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3038 if (T.isNull()) T = E->getType(); 3039 QualType TargetType = SemaRef.BuildReferenceType( 3040 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3041 SourceLocation ExprLoc = E->getLocStart(); 3042 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3043 TargetType, ExprLoc); 3044 3045 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3046 SourceRange(ExprLoc, ExprLoc), 3047 E->getSourceRange()).get(); 3048 } 3049 3050 /// ImplicitInitializerKind - How an implicit base or member initializer should 3051 /// initialize its base or member. 3052 enum ImplicitInitializerKind { 3053 IIK_Default, 3054 IIK_Copy, 3055 IIK_Move, 3056 IIK_Inherit 3057 }; 3058 3059 static bool 3060 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3061 ImplicitInitializerKind ImplicitInitKind, 3062 CXXBaseSpecifier *BaseSpec, 3063 bool IsInheritedVirtualBase, 3064 CXXCtorInitializer *&CXXBaseInit) { 3065 InitializedEntity InitEntity 3066 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3067 IsInheritedVirtualBase); 3068 3069 ExprResult BaseInit; 3070 3071 switch (ImplicitInitKind) { 3072 case IIK_Inherit: { 3073 const CXXRecordDecl *Inherited = 3074 Constructor->getInheritedConstructor()->getParent(); 3075 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3076 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3077 // C++11 [class.inhctor]p8: 3078 // Each expression in the expression-list is of the form 3079 // static_cast<T&&>(p), where p is the name of the corresponding 3080 // constructor parameter and T is the declared type of p. 3081 SmallVector<Expr*, 16> Args; 3082 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3083 ParmVarDecl *PD = Constructor->getParamDecl(I); 3084 ExprResult ArgExpr = 3085 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3086 VK_LValue, SourceLocation()); 3087 if (ArgExpr.isInvalid()) 3088 return true; 3089 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3090 } 3091 3092 InitializationKind InitKind = InitializationKind::CreateDirect( 3093 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3094 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3095 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3096 break; 3097 } 3098 } 3099 // Fall through. 3100 case IIK_Default: { 3101 InitializationKind InitKind 3102 = InitializationKind::CreateDefault(Constructor->getLocation()); 3103 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3104 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3105 break; 3106 } 3107 3108 case IIK_Move: 3109 case IIK_Copy: { 3110 bool Moving = ImplicitInitKind == IIK_Move; 3111 ParmVarDecl *Param = Constructor->getParamDecl(0); 3112 QualType ParamType = Param->getType().getNonReferenceType(); 3113 3114 Expr *CopyCtorArg = 3115 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3116 SourceLocation(), Param, false, 3117 Constructor->getLocation(), ParamType, 3118 VK_LValue, nullptr); 3119 3120 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3121 3122 // Cast to the base class to avoid ambiguities. 3123 QualType ArgTy = 3124 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3125 ParamType.getQualifiers()); 3126 3127 if (Moving) { 3128 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3129 } 3130 3131 CXXCastPath BasePath; 3132 BasePath.push_back(BaseSpec); 3133 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3134 CK_UncheckedDerivedToBase, 3135 Moving ? VK_XValue : VK_LValue, 3136 &BasePath).get(); 3137 3138 InitializationKind InitKind 3139 = InitializationKind::CreateDirect(Constructor->getLocation(), 3140 SourceLocation(), SourceLocation()); 3141 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3142 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3143 break; 3144 } 3145 } 3146 3147 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3148 if (BaseInit.isInvalid()) 3149 return true; 3150 3151 CXXBaseInit = 3152 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3153 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3154 SourceLocation()), 3155 BaseSpec->isVirtual(), 3156 SourceLocation(), 3157 BaseInit.getAs<Expr>(), 3158 SourceLocation(), 3159 SourceLocation()); 3160 3161 return false; 3162 } 3163 3164 static bool RefersToRValueRef(Expr *MemRef) { 3165 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3166 return Referenced->getType()->isRValueReferenceType(); 3167 } 3168 3169 static bool 3170 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3171 ImplicitInitializerKind ImplicitInitKind, 3172 FieldDecl *Field, IndirectFieldDecl *Indirect, 3173 CXXCtorInitializer *&CXXMemberInit) { 3174 if (Field->isInvalidDecl()) 3175 return true; 3176 3177 SourceLocation Loc = Constructor->getLocation(); 3178 3179 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3180 bool Moving = ImplicitInitKind == IIK_Move; 3181 ParmVarDecl *Param = Constructor->getParamDecl(0); 3182 QualType ParamType = Param->getType().getNonReferenceType(); 3183 3184 // Suppress copying zero-width bitfields. 3185 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3186 return false; 3187 3188 Expr *MemberExprBase = 3189 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3190 SourceLocation(), Param, false, 3191 Loc, ParamType, VK_LValue, nullptr); 3192 3193 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3194 3195 if (Moving) { 3196 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3197 } 3198 3199 // Build a reference to this field within the parameter. 3200 CXXScopeSpec SS; 3201 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3202 Sema::LookupMemberName); 3203 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3204 : cast<ValueDecl>(Field), AS_public); 3205 MemberLookup.resolveKind(); 3206 ExprResult CtorArg 3207 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3208 ParamType, Loc, 3209 /*IsArrow=*/false, 3210 SS, 3211 /*TemplateKWLoc=*/SourceLocation(), 3212 /*FirstQualifierInScope=*/nullptr, 3213 MemberLookup, 3214 /*TemplateArgs=*/nullptr); 3215 if (CtorArg.isInvalid()) 3216 return true; 3217 3218 // C++11 [class.copy]p15: 3219 // - if a member m has rvalue reference type T&&, it is direct-initialized 3220 // with static_cast<T&&>(x.m); 3221 if (RefersToRValueRef(CtorArg.get())) { 3222 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3223 } 3224 3225 // When the field we are copying is an array, create index variables for 3226 // each dimension of the array. We use these index variables to subscript 3227 // the source array, and other clients (e.g., CodeGen) will perform the 3228 // necessary iteration with these index variables. 3229 SmallVector<VarDecl *, 4> IndexVariables; 3230 QualType BaseType = Field->getType(); 3231 QualType SizeType = SemaRef.Context.getSizeType(); 3232 bool InitializingArray = false; 3233 while (const ConstantArrayType *Array 3234 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3235 InitializingArray = true; 3236 // Create the iteration variable for this array index. 3237 IdentifierInfo *IterationVarName = nullptr; 3238 { 3239 SmallString<8> Str; 3240 llvm::raw_svector_ostream OS(Str); 3241 OS << "__i" << IndexVariables.size(); 3242 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3243 } 3244 VarDecl *IterationVar 3245 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3246 IterationVarName, SizeType, 3247 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3248 SC_None); 3249 IndexVariables.push_back(IterationVar); 3250 3251 // Create a reference to the iteration variable. 3252 ExprResult IterationVarRef 3253 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3254 assert(!IterationVarRef.isInvalid() && 3255 "Reference to invented variable cannot fail!"); 3256 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3257 assert(!IterationVarRef.isInvalid() && 3258 "Conversion of invented variable cannot fail!"); 3259 3260 // Subscript the array with this iteration variable. 3261 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3262 IterationVarRef.get(), 3263 Loc); 3264 if (CtorArg.isInvalid()) 3265 return true; 3266 3267 BaseType = Array->getElementType(); 3268 } 3269 3270 // The array subscript expression is an lvalue, which is wrong for moving. 3271 if (Moving && InitializingArray) 3272 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3273 3274 // Construct the entity that we will be initializing. For an array, this 3275 // will be first element in the array, which may require several levels 3276 // of array-subscript entities. 3277 SmallVector<InitializedEntity, 4> Entities; 3278 Entities.reserve(1 + IndexVariables.size()); 3279 if (Indirect) 3280 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3281 else 3282 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3283 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3284 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3285 0, 3286 Entities.back())); 3287 3288 // Direct-initialize to use the copy constructor. 3289 InitializationKind InitKind = 3290 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3291 3292 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3293 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3294 3295 ExprResult MemberInit 3296 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3297 MultiExprArg(&CtorArgE, 1)); 3298 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3299 if (MemberInit.isInvalid()) 3300 return true; 3301 3302 if (Indirect) { 3303 assert(IndexVariables.size() == 0 && 3304 "Indirect field improperly initialized"); 3305 CXXMemberInit 3306 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3307 Loc, Loc, 3308 MemberInit.getAs<Expr>(), 3309 Loc); 3310 } else 3311 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3312 Loc, MemberInit.getAs<Expr>(), 3313 Loc, 3314 IndexVariables.data(), 3315 IndexVariables.size()); 3316 return false; 3317 } 3318 3319 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3320 "Unhandled implicit init kind!"); 3321 3322 QualType FieldBaseElementType = 3323 SemaRef.Context.getBaseElementType(Field->getType()); 3324 3325 if (FieldBaseElementType->isRecordType()) { 3326 InitializedEntity InitEntity 3327 = Indirect? InitializedEntity::InitializeMember(Indirect) 3328 : InitializedEntity::InitializeMember(Field); 3329 InitializationKind InitKind = 3330 InitializationKind::CreateDefault(Loc); 3331 3332 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3333 ExprResult MemberInit = 3334 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3335 3336 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3337 if (MemberInit.isInvalid()) 3338 return true; 3339 3340 if (Indirect) 3341 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3342 Indirect, Loc, 3343 Loc, 3344 MemberInit.get(), 3345 Loc); 3346 else 3347 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3348 Field, Loc, Loc, 3349 MemberInit.get(), 3350 Loc); 3351 return false; 3352 } 3353 3354 if (!Field->getParent()->isUnion()) { 3355 if (FieldBaseElementType->isReferenceType()) { 3356 SemaRef.Diag(Constructor->getLocation(), 3357 diag::err_uninitialized_member_in_ctor) 3358 << (int)Constructor->isImplicit() 3359 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3360 << 0 << Field->getDeclName(); 3361 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3362 return true; 3363 } 3364 3365 if (FieldBaseElementType.isConstQualified()) { 3366 SemaRef.Diag(Constructor->getLocation(), 3367 diag::err_uninitialized_member_in_ctor) 3368 << (int)Constructor->isImplicit() 3369 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3370 << 1 << Field->getDeclName(); 3371 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3372 return true; 3373 } 3374 } 3375 3376 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3377 FieldBaseElementType->isObjCRetainableType() && 3378 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3379 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3380 // ARC: 3381 // Default-initialize Objective-C pointers to NULL. 3382 CXXMemberInit 3383 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3384 Loc, Loc, 3385 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3386 Loc); 3387 return false; 3388 } 3389 3390 // Nothing to initialize. 3391 CXXMemberInit = nullptr; 3392 return false; 3393 } 3394 3395 namespace { 3396 struct BaseAndFieldInfo { 3397 Sema &S; 3398 CXXConstructorDecl *Ctor; 3399 bool AnyErrorsInInits; 3400 ImplicitInitializerKind IIK; 3401 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3402 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3403 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3404 3405 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3406 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3407 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3408 if (Generated && Ctor->isCopyConstructor()) 3409 IIK = IIK_Copy; 3410 else if (Generated && Ctor->isMoveConstructor()) 3411 IIK = IIK_Move; 3412 else if (Ctor->getInheritedConstructor()) 3413 IIK = IIK_Inherit; 3414 else 3415 IIK = IIK_Default; 3416 } 3417 3418 bool isImplicitCopyOrMove() const { 3419 switch (IIK) { 3420 case IIK_Copy: 3421 case IIK_Move: 3422 return true; 3423 3424 case IIK_Default: 3425 case IIK_Inherit: 3426 return false; 3427 } 3428 3429 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3430 } 3431 3432 bool addFieldInitializer(CXXCtorInitializer *Init) { 3433 AllToInit.push_back(Init); 3434 3435 // Check whether this initializer makes the field "used". 3436 if (Init->getInit()->HasSideEffects(S.Context)) 3437 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3438 3439 return false; 3440 } 3441 3442 bool isInactiveUnionMember(FieldDecl *Field) { 3443 RecordDecl *Record = Field->getParent(); 3444 if (!Record->isUnion()) 3445 return false; 3446 3447 if (FieldDecl *Active = 3448 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3449 return Active != Field->getCanonicalDecl(); 3450 3451 // In an implicit copy or move constructor, ignore any in-class initializer. 3452 if (isImplicitCopyOrMove()) 3453 return true; 3454 3455 // If there's no explicit initialization, the field is active only if it 3456 // has an in-class initializer... 3457 if (Field->hasInClassInitializer()) 3458 return false; 3459 // ... or it's an anonymous struct or union whose class has an in-class 3460 // initializer. 3461 if (!Field->isAnonymousStructOrUnion()) 3462 return true; 3463 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3464 return !FieldRD->hasInClassInitializer(); 3465 } 3466 3467 /// \brief Determine whether the given field is, or is within, a union member 3468 /// that is inactive (because there was an initializer given for a different 3469 /// member of the union, or because the union was not initialized at all). 3470 bool isWithinInactiveUnionMember(FieldDecl *Field, 3471 IndirectFieldDecl *Indirect) { 3472 if (!Indirect) 3473 return isInactiveUnionMember(Field); 3474 3475 for (auto *C : Indirect->chain()) { 3476 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3477 if (Field && isInactiveUnionMember(Field)) 3478 return true; 3479 } 3480 return false; 3481 } 3482 }; 3483 } 3484 3485 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3486 /// array type. 3487 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3488 if (T->isIncompleteArrayType()) 3489 return true; 3490 3491 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3492 if (!ArrayT->getSize()) 3493 return true; 3494 3495 T = ArrayT->getElementType(); 3496 } 3497 3498 return false; 3499 } 3500 3501 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3502 FieldDecl *Field, 3503 IndirectFieldDecl *Indirect = nullptr) { 3504 if (Field->isInvalidDecl()) 3505 return false; 3506 3507 // Overwhelmingly common case: we have a direct initializer for this field. 3508 if (CXXCtorInitializer *Init = 3509 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3510 return Info.addFieldInitializer(Init); 3511 3512 // C++11 [class.base.init]p8: 3513 // if the entity is a non-static data member that has a 3514 // brace-or-equal-initializer and either 3515 // -- the constructor's class is a union and no other variant member of that 3516 // union is designated by a mem-initializer-id or 3517 // -- the constructor's class is not a union, and, if the entity is a member 3518 // of an anonymous union, no other member of that union is designated by 3519 // a mem-initializer-id, 3520 // the entity is initialized as specified in [dcl.init]. 3521 // 3522 // We also apply the same rules to handle anonymous structs within anonymous 3523 // unions. 3524 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3525 return false; 3526 3527 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3528 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3529 Info.Ctor->getLocation(), Field); 3530 CXXCtorInitializer *Init; 3531 if (Indirect) 3532 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3533 SourceLocation(), 3534 SourceLocation(), DIE, 3535 SourceLocation()); 3536 else 3537 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3538 SourceLocation(), 3539 SourceLocation(), DIE, 3540 SourceLocation()); 3541 return Info.addFieldInitializer(Init); 3542 } 3543 3544 // Don't initialize incomplete or zero-length arrays. 3545 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3546 return false; 3547 3548 // Don't try to build an implicit initializer if there were semantic 3549 // errors in any of the initializers (and therefore we might be 3550 // missing some that the user actually wrote). 3551 if (Info.AnyErrorsInInits) 3552 return false; 3553 3554 CXXCtorInitializer *Init = nullptr; 3555 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3556 Indirect, Init)) 3557 return true; 3558 3559 if (!Init) 3560 return false; 3561 3562 return Info.addFieldInitializer(Init); 3563 } 3564 3565 bool 3566 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3567 CXXCtorInitializer *Initializer) { 3568 assert(Initializer->isDelegatingInitializer()); 3569 Constructor->setNumCtorInitializers(1); 3570 CXXCtorInitializer **initializer = 3571 new (Context) CXXCtorInitializer*[1]; 3572 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3573 Constructor->setCtorInitializers(initializer); 3574 3575 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3576 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3577 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3578 } 3579 3580 DelegatingCtorDecls.push_back(Constructor); 3581 3582 return false; 3583 } 3584 3585 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3586 ArrayRef<CXXCtorInitializer *> Initializers) { 3587 if (Constructor->isDependentContext()) { 3588 // Just store the initializers as written, they will be checked during 3589 // instantiation. 3590 if (!Initializers.empty()) { 3591 Constructor->setNumCtorInitializers(Initializers.size()); 3592 CXXCtorInitializer **baseOrMemberInitializers = 3593 new (Context) CXXCtorInitializer*[Initializers.size()]; 3594 memcpy(baseOrMemberInitializers, Initializers.data(), 3595 Initializers.size() * sizeof(CXXCtorInitializer*)); 3596 Constructor->setCtorInitializers(baseOrMemberInitializers); 3597 } 3598 3599 // Let template instantiation know whether we had errors. 3600 if (AnyErrors) 3601 Constructor->setInvalidDecl(); 3602 3603 return false; 3604 } 3605 3606 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3607 3608 // We need to build the initializer AST according to order of construction 3609 // and not what user specified in the Initializers list. 3610 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3611 if (!ClassDecl) 3612 return true; 3613 3614 bool HadError = false; 3615 3616 for (unsigned i = 0; i < Initializers.size(); i++) { 3617 CXXCtorInitializer *Member = Initializers[i]; 3618 3619 if (Member->isBaseInitializer()) 3620 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3621 else { 3622 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3623 3624 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3625 for (auto *C : F->chain()) { 3626 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3627 if (FD && FD->getParent()->isUnion()) 3628 Info.ActiveUnionMember.insert(std::make_pair( 3629 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3630 } 3631 } else if (FieldDecl *FD = Member->getMember()) { 3632 if (FD->getParent()->isUnion()) 3633 Info.ActiveUnionMember.insert(std::make_pair( 3634 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3635 } 3636 } 3637 } 3638 3639 // Keep track of the direct virtual bases. 3640 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3641 for (auto &I : ClassDecl->bases()) { 3642 if (I.isVirtual()) 3643 DirectVBases.insert(&I); 3644 } 3645 3646 // Push virtual bases before others. 3647 for (auto &VBase : ClassDecl->vbases()) { 3648 if (CXXCtorInitializer *Value 3649 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3650 // [class.base.init]p7, per DR257: 3651 // A mem-initializer where the mem-initializer-id names a virtual base 3652 // class is ignored during execution of a constructor of any class that 3653 // is not the most derived class. 3654 if (ClassDecl->isAbstract()) { 3655 // FIXME: Provide a fixit to remove the base specifier. This requires 3656 // tracking the location of the associated comma for a base specifier. 3657 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3658 << VBase.getType() << ClassDecl; 3659 DiagnoseAbstractType(ClassDecl); 3660 } 3661 3662 Info.AllToInit.push_back(Value); 3663 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3664 // [class.base.init]p8, per DR257: 3665 // If a given [...] base class is not named by a mem-initializer-id 3666 // [...] and the entity is not a virtual base class of an abstract 3667 // class, then [...] the entity is default-initialized. 3668 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3669 CXXCtorInitializer *CXXBaseInit; 3670 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3671 &VBase, IsInheritedVirtualBase, 3672 CXXBaseInit)) { 3673 HadError = true; 3674 continue; 3675 } 3676 3677 Info.AllToInit.push_back(CXXBaseInit); 3678 } 3679 } 3680 3681 // Non-virtual bases. 3682 for (auto &Base : ClassDecl->bases()) { 3683 // Virtuals are in the virtual base list and already constructed. 3684 if (Base.isVirtual()) 3685 continue; 3686 3687 if (CXXCtorInitializer *Value 3688 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3689 Info.AllToInit.push_back(Value); 3690 } else if (!AnyErrors) { 3691 CXXCtorInitializer *CXXBaseInit; 3692 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3693 &Base, /*IsInheritedVirtualBase=*/false, 3694 CXXBaseInit)) { 3695 HadError = true; 3696 continue; 3697 } 3698 3699 Info.AllToInit.push_back(CXXBaseInit); 3700 } 3701 } 3702 3703 // Fields. 3704 for (auto *Mem : ClassDecl->decls()) { 3705 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3706 // C++ [class.bit]p2: 3707 // A declaration for a bit-field that omits the identifier declares an 3708 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3709 // initialized. 3710 if (F->isUnnamedBitfield()) 3711 continue; 3712 3713 // If we're not generating the implicit copy/move constructor, then we'll 3714 // handle anonymous struct/union fields based on their individual 3715 // indirect fields. 3716 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3717 continue; 3718 3719 if (CollectFieldInitializer(*this, Info, F)) 3720 HadError = true; 3721 continue; 3722 } 3723 3724 // Beyond this point, we only consider default initialization. 3725 if (Info.isImplicitCopyOrMove()) 3726 continue; 3727 3728 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3729 if (F->getType()->isIncompleteArrayType()) { 3730 assert(ClassDecl->hasFlexibleArrayMember() && 3731 "Incomplete array type is not valid"); 3732 continue; 3733 } 3734 3735 // Initialize each field of an anonymous struct individually. 3736 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3737 HadError = true; 3738 3739 continue; 3740 } 3741 } 3742 3743 unsigned NumInitializers = Info.AllToInit.size(); 3744 if (NumInitializers > 0) { 3745 Constructor->setNumCtorInitializers(NumInitializers); 3746 CXXCtorInitializer **baseOrMemberInitializers = 3747 new (Context) CXXCtorInitializer*[NumInitializers]; 3748 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3749 NumInitializers * sizeof(CXXCtorInitializer*)); 3750 Constructor->setCtorInitializers(baseOrMemberInitializers); 3751 3752 // Constructors implicitly reference the base and member 3753 // destructors. 3754 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3755 Constructor->getParent()); 3756 } 3757 3758 return HadError; 3759 } 3760 3761 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3762 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3763 const RecordDecl *RD = RT->getDecl(); 3764 if (RD->isAnonymousStructOrUnion()) { 3765 for (auto *Field : RD->fields()) 3766 PopulateKeysForFields(Field, IdealInits); 3767 return; 3768 } 3769 } 3770 IdealInits.push_back(Field->getCanonicalDecl()); 3771 } 3772 3773 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3774 return Context.getCanonicalType(BaseType).getTypePtr(); 3775 } 3776 3777 static const void *GetKeyForMember(ASTContext &Context, 3778 CXXCtorInitializer *Member) { 3779 if (!Member->isAnyMemberInitializer()) 3780 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3781 3782 return Member->getAnyMember()->getCanonicalDecl(); 3783 } 3784 3785 static void DiagnoseBaseOrMemInitializerOrder( 3786 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3787 ArrayRef<CXXCtorInitializer *> Inits) { 3788 if (Constructor->getDeclContext()->isDependentContext()) 3789 return; 3790 3791 // Don't check initializers order unless the warning is enabled at the 3792 // location of at least one initializer. 3793 bool ShouldCheckOrder = false; 3794 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3795 CXXCtorInitializer *Init = Inits[InitIndex]; 3796 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 3797 Init->getSourceLocation())) { 3798 ShouldCheckOrder = true; 3799 break; 3800 } 3801 } 3802 if (!ShouldCheckOrder) 3803 return; 3804 3805 // Build the list of bases and members in the order that they'll 3806 // actually be initialized. The explicit initializers should be in 3807 // this same order but may be missing things. 3808 SmallVector<const void*, 32> IdealInitKeys; 3809 3810 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3811 3812 // 1. Virtual bases. 3813 for (const auto &VBase : ClassDecl->vbases()) 3814 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 3815 3816 // 2. Non-virtual bases. 3817 for (const auto &Base : ClassDecl->bases()) { 3818 if (Base.isVirtual()) 3819 continue; 3820 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 3821 } 3822 3823 // 3. Direct fields. 3824 for (auto *Field : ClassDecl->fields()) { 3825 if (Field->isUnnamedBitfield()) 3826 continue; 3827 3828 PopulateKeysForFields(Field, IdealInitKeys); 3829 } 3830 3831 unsigned NumIdealInits = IdealInitKeys.size(); 3832 unsigned IdealIndex = 0; 3833 3834 CXXCtorInitializer *PrevInit = nullptr; 3835 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3836 CXXCtorInitializer *Init = Inits[InitIndex]; 3837 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3838 3839 // Scan forward to try to find this initializer in the idealized 3840 // initializers list. 3841 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3842 if (InitKey == IdealInitKeys[IdealIndex]) 3843 break; 3844 3845 // If we didn't find this initializer, it must be because we 3846 // scanned past it on a previous iteration. That can only 3847 // happen if we're out of order; emit a warning. 3848 if (IdealIndex == NumIdealInits && PrevInit) { 3849 Sema::SemaDiagnosticBuilder D = 3850 SemaRef.Diag(PrevInit->getSourceLocation(), 3851 diag::warn_initializer_out_of_order); 3852 3853 if (PrevInit->isAnyMemberInitializer()) 3854 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3855 else 3856 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3857 3858 if (Init->isAnyMemberInitializer()) 3859 D << 0 << Init->getAnyMember()->getDeclName(); 3860 else 3861 D << 1 << Init->getTypeSourceInfo()->getType(); 3862 3863 // Move back to the initializer's location in the ideal list. 3864 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3865 if (InitKey == IdealInitKeys[IdealIndex]) 3866 break; 3867 3868 assert(IdealIndex != NumIdealInits && 3869 "initializer not found in initializer list"); 3870 } 3871 3872 PrevInit = Init; 3873 } 3874 } 3875 3876 namespace { 3877 bool CheckRedundantInit(Sema &S, 3878 CXXCtorInitializer *Init, 3879 CXXCtorInitializer *&PrevInit) { 3880 if (!PrevInit) { 3881 PrevInit = Init; 3882 return false; 3883 } 3884 3885 if (FieldDecl *Field = Init->getAnyMember()) 3886 S.Diag(Init->getSourceLocation(), 3887 diag::err_multiple_mem_initialization) 3888 << Field->getDeclName() 3889 << Init->getSourceRange(); 3890 else { 3891 const Type *BaseClass = Init->getBaseClass(); 3892 assert(BaseClass && "neither field nor base"); 3893 S.Diag(Init->getSourceLocation(), 3894 diag::err_multiple_base_initialization) 3895 << QualType(BaseClass, 0) 3896 << Init->getSourceRange(); 3897 } 3898 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3899 << 0 << PrevInit->getSourceRange(); 3900 3901 return true; 3902 } 3903 3904 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3905 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3906 3907 bool CheckRedundantUnionInit(Sema &S, 3908 CXXCtorInitializer *Init, 3909 RedundantUnionMap &Unions) { 3910 FieldDecl *Field = Init->getAnyMember(); 3911 RecordDecl *Parent = Field->getParent(); 3912 NamedDecl *Child = Field; 3913 3914 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3915 if (Parent->isUnion()) { 3916 UnionEntry &En = Unions[Parent]; 3917 if (En.first && En.first != Child) { 3918 S.Diag(Init->getSourceLocation(), 3919 diag::err_multiple_mem_union_initialization) 3920 << Field->getDeclName() 3921 << Init->getSourceRange(); 3922 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3923 << 0 << En.second->getSourceRange(); 3924 return true; 3925 } 3926 if (!En.first) { 3927 En.first = Child; 3928 En.second = Init; 3929 } 3930 if (!Parent->isAnonymousStructOrUnion()) 3931 return false; 3932 } 3933 3934 Child = Parent; 3935 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3936 } 3937 3938 return false; 3939 } 3940 } 3941 3942 /// ActOnMemInitializers - Handle the member initializers for a constructor. 3943 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3944 SourceLocation ColonLoc, 3945 ArrayRef<CXXCtorInitializer*> MemInits, 3946 bool AnyErrors) { 3947 if (!ConstructorDecl) 3948 return; 3949 3950 AdjustDeclIfTemplate(ConstructorDecl); 3951 3952 CXXConstructorDecl *Constructor 3953 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3954 3955 if (!Constructor) { 3956 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3957 return; 3958 } 3959 3960 // Mapping for the duplicate initializers check. 3961 // For member initializers, this is keyed with a FieldDecl*. 3962 // For base initializers, this is keyed with a Type*. 3963 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3964 3965 // Mapping for the inconsistent anonymous-union initializers check. 3966 RedundantUnionMap MemberUnions; 3967 3968 bool HadError = false; 3969 for (unsigned i = 0; i < MemInits.size(); i++) { 3970 CXXCtorInitializer *Init = MemInits[i]; 3971 3972 // Set the source order index. 3973 Init->setSourceOrder(i); 3974 3975 if (Init->isAnyMemberInitializer()) { 3976 const void *Key = GetKeyForMember(Context, Init); 3977 if (CheckRedundantInit(*this, Init, Members[Key]) || 3978 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3979 HadError = true; 3980 } else if (Init->isBaseInitializer()) { 3981 const void *Key = GetKeyForMember(Context, Init); 3982 if (CheckRedundantInit(*this, Init, Members[Key])) 3983 HadError = true; 3984 } else { 3985 assert(Init->isDelegatingInitializer()); 3986 // This must be the only initializer 3987 if (MemInits.size() != 1) { 3988 Diag(Init->getSourceLocation(), 3989 diag::err_delegating_initializer_alone) 3990 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3991 // We will treat this as being the only initializer. 3992 } 3993 SetDelegatingInitializer(Constructor, MemInits[i]); 3994 // Return immediately as the initializer is set. 3995 return; 3996 } 3997 } 3998 3999 if (HadError) 4000 return; 4001 4002 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4003 4004 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4005 4006 DiagnoseUninitializedFields(*this, Constructor); 4007 } 4008 4009 void 4010 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4011 CXXRecordDecl *ClassDecl) { 4012 // Ignore dependent contexts. Also ignore unions, since their members never 4013 // have destructors implicitly called. 4014 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4015 return; 4016 4017 // FIXME: all the access-control diagnostics are positioned on the 4018 // field/base declaration. That's probably good; that said, the 4019 // user might reasonably want to know why the destructor is being 4020 // emitted, and we currently don't say. 4021 4022 // Non-static data members. 4023 for (auto *Field : ClassDecl->fields()) { 4024 if (Field->isInvalidDecl()) 4025 continue; 4026 4027 // Don't destroy incomplete or zero-length arrays. 4028 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4029 continue; 4030 4031 QualType FieldType = Context.getBaseElementType(Field->getType()); 4032 4033 const RecordType* RT = FieldType->getAs<RecordType>(); 4034 if (!RT) 4035 continue; 4036 4037 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4038 if (FieldClassDecl->isInvalidDecl()) 4039 continue; 4040 if (FieldClassDecl->hasIrrelevantDestructor()) 4041 continue; 4042 // The destructor for an implicit anonymous union member is never invoked. 4043 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4044 continue; 4045 4046 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4047 assert(Dtor && "No dtor found for FieldClassDecl!"); 4048 CheckDestructorAccess(Field->getLocation(), Dtor, 4049 PDiag(diag::err_access_dtor_field) 4050 << Field->getDeclName() 4051 << FieldType); 4052 4053 MarkFunctionReferenced(Location, Dtor); 4054 DiagnoseUseOfDecl(Dtor, Location); 4055 } 4056 4057 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4058 4059 // Bases. 4060 for (const auto &Base : ClassDecl->bases()) { 4061 // Bases are always records in a well-formed non-dependent class. 4062 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4063 4064 // Remember direct virtual bases. 4065 if (Base.isVirtual()) 4066 DirectVirtualBases.insert(RT); 4067 4068 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4069 // If our base class is invalid, we probably can't get its dtor anyway. 4070 if (BaseClassDecl->isInvalidDecl()) 4071 continue; 4072 if (BaseClassDecl->hasIrrelevantDestructor()) 4073 continue; 4074 4075 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4076 assert(Dtor && "No dtor found for BaseClassDecl!"); 4077 4078 // FIXME: caret should be on the start of the class name 4079 CheckDestructorAccess(Base.getLocStart(), Dtor, 4080 PDiag(diag::err_access_dtor_base) 4081 << Base.getType() 4082 << Base.getSourceRange(), 4083 Context.getTypeDeclType(ClassDecl)); 4084 4085 MarkFunctionReferenced(Location, Dtor); 4086 DiagnoseUseOfDecl(Dtor, Location); 4087 } 4088 4089 // Virtual bases. 4090 for (const auto &VBase : ClassDecl->vbases()) { 4091 // Bases are always records in a well-formed non-dependent class. 4092 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4093 4094 // Ignore direct virtual bases. 4095 if (DirectVirtualBases.count(RT)) 4096 continue; 4097 4098 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4099 // If our base class is invalid, we probably can't get its dtor anyway. 4100 if (BaseClassDecl->isInvalidDecl()) 4101 continue; 4102 if (BaseClassDecl->hasIrrelevantDestructor()) 4103 continue; 4104 4105 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4106 assert(Dtor && "No dtor found for BaseClassDecl!"); 4107 if (CheckDestructorAccess( 4108 ClassDecl->getLocation(), Dtor, 4109 PDiag(diag::err_access_dtor_vbase) 4110 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4111 Context.getTypeDeclType(ClassDecl)) == 4112 AR_accessible) { 4113 CheckDerivedToBaseConversion( 4114 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4115 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4116 SourceRange(), DeclarationName(), nullptr); 4117 } 4118 4119 MarkFunctionReferenced(Location, Dtor); 4120 DiagnoseUseOfDecl(Dtor, Location); 4121 } 4122 } 4123 4124 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4125 if (!CDtorDecl) 4126 return; 4127 4128 if (CXXConstructorDecl *Constructor 4129 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4130 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4131 DiagnoseUninitializedFields(*this, Constructor); 4132 } 4133 } 4134 4135 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4136 unsigned DiagID, AbstractDiagSelID SelID) { 4137 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4138 unsigned DiagID; 4139 AbstractDiagSelID SelID; 4140 4141 public: 4142 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4143 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4144 4145 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4146 if (Suppressed) return; 4147 if (SelID == -1) 4148 S.Diag(Loc, DiagID) << T; 4149 else 4150 S.Diag(Loc, DiagID) << SelID << T; 4151 } 4152 } Diagnoser(DiagID, SelID); 4153 4154 return RequireNonAbstractType(Loc, T, Diagnoser); 4155 } 4156 4157 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4158 TypeDiagnoser &Diagnoser) { 4159 if (!getLangOpts().CPlusPlus) 4160 return false; 4161 4162 if (const ArrayType *AT = Context.getAsArrayType(T)) 4163 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4164 4165 if (const PointerType *PT = T->getAs<PointerType>()) { 4166 // Find the innermost pointer type. 4167 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4168 PT = T; 4169 4170 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4171 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4172 } 4173 4174 const RecordType *RT = T->getAs<RecordType>(); 4175 if (!RT) 4176 return false; 4177 4178 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4179 4180 // We can't answer whether something is abstract until it has a 4181 // definition. If it's currently being defined, we'll walk back 4182 // over all the declarations when we have a full definition. 4183 const CXXRecordDecl *Def = RD->getDefinition(); 4184 if (!Def || Def->isBeingDefined()) 4185 return false; 4186 4187 if (!RD->isAbstract()) 4188 return false; 4189 4190 Diagnoser.diagnose(*this, Loc, T); 4191 DiagnoseAbstractType(RD); 4192 4193 return true; 4194 } 4195 4196 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4197 // Check if we've already emitted the list of pure virtual functions 4198 // for this class. 4199 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4200 return; 4201 4202 // If the diagnostic is suppressed, don't emit the notes. We're only 4203 // going to emit them once, so try to attach them to a diagnostic we're 4204 // actually going to show. 4205 if (Diags.isLastDiagnosticIgnored()) 4206 return; 4207 4208 CXXFinalOverriderMap FinalOverriders; 4209 RD->getFinalOverriders(FinalOverriders); 4210 4211 // Keep a set of seen pure methods so we won't diagnose the same method 4212 // more than once. 4213 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4214 4215 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4216 MEnd = FinalOverriders.end(); 4217 M != MEnd; 4218 ++M) { 4219 for (OverridingMethods::iterator SO = M->second.begin(), 4220 SOEnd = M->second.end(); 4221 SO != SOEnd; ++SO) { 4222 // C++ [class.abstract]p4: 4223 // A class is abstract if it contains or inherits at least one 4224 // pure virtual function for which the final overrider is pure 4225 // virtual. 4226 4227 // 4228 if (SO->second.size() != 1) 4229 continue; 4230 4231 if (!SO->second.front().Method->isPure()) 4232 continue; 4233 4234 if (!SeenPureMethods.insert(SO->second.front().Method)) 4235 continue; 4236 4237 Diag(SO->second.front().Method->getLocation(), 4238 diag::note_pure_virtual_function) 4239 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4240 } 4241 } 4242 4243 if (!PureVirtualClassDiagSet) 4244 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4245 PureVirtualClassDiagSet->insert(RD); 4246 } 4247 4248 namespace { 4249 struct AbstractUsageInfo { 4250 Sema &S; 4251 CXXRecordDecl *Record; 4252 CanQualType AbstractType; 4253 bool Invalid; 4254 4255 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4256 : S(S), Record(Record), 4257 AbstractType(S.Context.getCanonicalType( 4258 S.Context.getTypeDeclType(Record))), 4259 Invalid(false) {} 4260 4261 void DiagnoseAbstractType() { 4262 if (Invalid) return; 4263 S.DiagnoseAbstractType(Record); 4264 Invalid = true; 4265 } 4266 4267 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4268 }; 4269 4270 struct CheckAbstractUsage { 4271 AbstractUsageInfo &Info; 4272 const NamedDecl *Ctx; 4273 4274 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4275 : Info(Info), Ctx(Ctx) {} 4276 4277 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4278 switch (TL.getTypeLocClass()) { 4279 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4280 #define TYPELOC(CLASS, PARENT) \ 4281 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4282 #include "clang/AST/TypeLocNodes.def" 4283 } 4284 } 4285 4286 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4287 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4288 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4289 if (!TL.getParam(I)) 4290 continue; 4291 4292 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4293 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4294 } 4295 } 4296 4297 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4298 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4299 } 4300 4301 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4302 // Visit the type parameters from a permissive context. 4303 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4304 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4305 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4306 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4307 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4308 // TODO: other template argument types? 4309 } 4310 } 4311 4312 // Visit pointee types from a permissive context. 4313 #define CheckPolymorphic(Type) \ 4314 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4315 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4316 } 4317 CheckPolymorphic(PointerTypeLoc) 4318 CheckPolymorphic(ReferenceTypeLoc) 4319 CheckPolymorphic(MemberPointerTypeLoc) 4320 CheckPolymorphic(BlockPointerTypeLoc) 4321 CheckPolymorphic(AtomicTypeLoc) 4322 4323 /// Handle all the types we haven't given a more specific 4324 /// implementation for above. 4325 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4326 // Every other kind of type that we haven't called out already 4327 // that has an inner type is either (1) sugar or (2) contains that 4328 // inner type in some way as a subobject. 4329 if (TypeLoc Next = TL.getNextTypeLoc()) 4330 return Visit(Next, Sel); 4331 4332 // If there's no inner type and we're in a permissive context, 4333 // don't diagnose. 4334 if (Sel == Sema::AbstractNone) return; 4335 4336 // Check whether the type matches the abstract type. 4337 QualType T = TL.getType(); 4338 if (T->isArrayType()) { 4339 Sel = Sema::AbstractArrayType; 4340 T = Info.S.Context.getBaseElementType(T); 4341 } 4342 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4343 if (CT != Info.AbstractType) return; 4344 4345 // It matched; do some magic. 4346 if (Sel == Sema::AbstractArrayType) { 4347 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4348 << T << TL.getSourceRange(); 4349 } else { 4350 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4351 << Sel << T << TL.getSourceRange(); 4352 } 4353 Info.DiagnoseAbstractType(); 4354 } 4355 }; 4356 4357 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4358 Sema::AbstractDiagSelID Sel) { 4359 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4360 } 4361 4362 } 4363 4364 /// Check for invalid uses of an abstract type in a method declaration. 4365 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4366 CXXMethodDecl *MD) { 4367 // No need to do the check on definitions, which require that 4368 // the return/param types be complete. 4369 if (MD->doesThisDeclarationHaveABody()) 4370 return; 4371 4372 // For safety's sake, just ignore it if we don't have type source 4373 // information. This should never happen for non-implicit methods, 4374 // but... 4375 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4376 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4377 } 4378 4379 /// Check for invalid uses of an abstract type within a class definition. 4380 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4381 CXXRecordDecl *RD) { 4382 for (auto *D : RD->decls()) { 4383 if (D->isImplicit()) continue; 4384 4385 // Methods and method templates. 4386 if (isa<CXXMethodDecl>(D)) { 4387 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4388 } else if (isa<FunctionTemplateDecl>(D)) { 4389 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4390 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4391 4392 // Fields and static variables. 4393 } else if (isa<FieldDecl>(D)) { 4394 FieldDecl *FD = cast<FieldDecl>(D); 4395 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4396 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4397 } else if (isa<VarDecl>(D)) { 4398 VarDecl *VD = cast<VarDecl>(D); 4399 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4400 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4401 4402 // Nested classes and class templates. 4403 } else if (isa<CXXRecordDecl>(D)) { 4404 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4405 } else if (isa<ClassTemplateDecl>(D)) { 4406 CheckAbstractClassUsage(Info, 4407 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4408 } 4409 } 4410 } 4411 4412 /// \brief Check class-level dllimport/dllexport attribute. 4413 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4414 Attr *ClassAttr = getDLLAttr(Class); 4415 if (!ClassAttr) 4416 return; 4417 4418 bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4419 4420 // Force declaration of implicit members so they can inherit the attribute. 4421 S.ForceDeclarationOfImplicitMembers(Class); 4422 4423 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4424 // seem to be true in practice? 4425 4426 for (Decl *Member : Class->decls()) { 4427 VarDecl *VD = dyn_cast<VarDecl>(Member); 4428 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4429 4430 // Only methods and static fields inherit the attributes. 4431 if (!VD && !MD) 4432 continue; 4433 4434 // Don't process deleted methods. 4435 if (MD && MD->isDeleted()) 4436 continue; 4437 4438 if (MD && MD->isMoveAssignmentOperator() && !ClassExported && 4439 MD->isInlined()) { 4440 // Current MSVC versions don't export the move assignment operators, so 4441 // don't attempt to import them if we have a definition. 4442 continue; 4443 } 4444 4445 if (InheritableAttr *MemberAttr = getDLLAttr(Member)) { 4446 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4447 !MemberAttr->isInherited() && !ClassAttr->isInherited()) { 4448 S.Diag(MemberAttr->getLocation(), 4449 diag::err_attribute_dll_member_of_dll_class) 4450 << MemberAttr << ClassAttr; 4451 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4452 Member->setInvalidDecl(); 4453 continue; 4454 } 4455 } else { 4456 auto *NewAttr = 4457 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4458 NewAttr->setInherited(true); 4459 Member->addAttr(NewAttr); 4460 } 4461 4462 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 4463 if (ClassExported) { 4464 if (MD->isUserProvided()) { 4465 // Instantiate non-default methods. 4466 S.MarkFunctionReferenced(Class->getLocation(), MD); 4467 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4468 MD->isCopyAssignmentOperator() || 4469 MD->isMoveAssignmentOperator()) { 4470 // Instantiate non-trivial or explicitly defaulted methods, and the 4471 // copy assignment / move assignment operators. 4472 S.MarkFunctionReferenced(Class->getLocation(), MD); 4473 // Resolve its exception specification; CodeGen needs it. 4474 auto *FPT = MD->getType()->getAs<FunctionProtoType>(); 4475 S.ResolveExceptionSpec(Class->getLocation(), FPT); 4476 S.ActOnFinishInlineMethodDef(MD); 4477 } 4478 } 4479 } 4480 } 4481 } 4482 4483 /// \brief Perform semantic checks on a class definition that has been 4484 /// completing, introducing implicitly-declared members, checking for 4485 /// abstract types, etc. 4486 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4487 if (!Record) 4488 return; 4489 4490 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4491 AbstractUsageInfo Info(*this, Record); 4492 CheckAbstractClassUsage(Info, Record); 4493 } 4494 4495 // If this is not an aggregate type and has no user-declared constructor, 4496 // complain about any non-static data members of reference or const scalar 4497 // type, since they will never get initializers. 4498 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4499 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4500 !Record->isLambda()) { 4501 bool Complained = false; 4502 for (const auto *F : Record->fields()) { 4503 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4504 continue; 4505 4506 if (F->getType()->isReferenceType() || 4507 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4508 if (!Complained) { 4509 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4510 << Record->getTagKind() << Record; 4511 Complained = true; 4512 } 4513 4514 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4515 << F->getType()->isReferenceType() 4516 << F->getDeclName(); 4517 } 4518 } 4519 } 4520 4521 if (Record->isDynamicClass() && !Record->isDependentType()) 4522 DynamicClasses.push_back(Record); 4523 4524 if (Record->getIdentifier()) { 4525 // C++ [class.mem]p13: 4526 // If T is the name of a class, then each of the following shall have a 4527 // name different from T: 4528 // - every member of every anonymous union that is a member of class T. 4529 // 4530 // C++ [class.mem]p14: 4531 // In addition, if class T has a user-declared constructor (12.1), every 4532 // non-static data member of class T shall have a name different from T. 4533 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4534 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4535 ++I) { 4536 NamedDecl *D = *I; 4537 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4538 isa<IndirectFieldDecl>(D)) { 4539 Diag(D->getLocation(), diag::err_member_name_of_class) 4540 << D->getDeclName(); 4541 break; 4542 } 4543 } 4544 } 4545 4546 // Warn if the class has virtual methods but non-virtual public destructor. 4547 if (Record->isPolymorphic() && !Record->isDependentType()) { 4548 CXXDestructorDecl *dtor = Record->getDestructor(); 4549 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4550 !Record->hasAttr<FinalAttr>()) 4551 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4552 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4553 } 4554 4555 if (Record->isAbstract()) { 4556 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4557 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4558 << FA->isSpelledAsSealed(); 4559 DiagnoseAbstractType(Record); 4560 } 4561 } 4562 4563 if (!Record->isDependentType()) { 4564 for (auto *M : Record->methods()) { 4565 // See if a method overloads virtual methods in a base 4566 // class without overriding any. 4567 if (!M->isStatic()) 4568 DiagnoseHiddenVirtualMethods(M); 4569 4570 // Check whether the explicitly-defaulted special members are valid. 4571 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4572 CheckExplicitlyDefaultedSpecialMember(M); 4573 4574 // For an explicitly defaulted or deleted special member, we defer 4575 // determining triviality until the class is complete. That time is now! 4576 if (!M->isImplicit() && !M->isUserProvided()) { 4577 CXXSpecialMember CSM = getSpecialMember(M); 4578 if (CSM != CXXInvalid) { 4579 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4580 4581 // Inform the class that we've finished declaring this member. 4582 Record->finishedDefaultedOrDeletedMember(M); 4583 } 4584 } 4585 } 4586 } 4587 4588 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4589 // function that is not a constructor declares that member function to be 4590 // const. [...] The class of which that function is a member shall be 4591 // a literal type. 4592 // 4593 // If the class has virtual bases, any constexpr members will already have 4594 // been diagnosed by the checks performed on the member declaration, so 4595 // suppress this (less useful) diagnostic. 4596 // 4597 // We delay this until we know whether an explicitly-defaulted (or deleted) 4598 // destructor for the class is trivial. 4599 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4600 !Record->isLiteral() && !Record->getNumVBases()) { 4601 for (const auto *M : Record->methods()) { 4602 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) { 4603 switch (Record->getTemplateSpecializationKind()) { 4604 case TSK_ImplicitInstantiation: 4605 case TSK_ExplicitInstantiationDeclaration: 4606 case TSK_ExplicitInstantiationDefinition: 4607 // If a template instantiates to a non-literal type, but its members 4608 // instantiate to constexpr functions, the template is technically 4609 // ill-formed, but we allow it for sanity. 4610 continue; 4611 4612 case TSK_Undeclared: 4613 case TSK_ExplicitSpecialization: 4614 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4615 diag::err_constexpr_method_non_literal); 4616 break; 4617 } 4618 4619 // Only produce one error per class. 4620 break; 4621 } 4622 } 4623 } 4624 4625 // ms_struct is a request to use the same ABI rules as MSVC. Check 4626 // whether this class uses any C++ features that are implemented 4627 // completely differently in MSVC, and if so, emit a diagnostic. 4628 // That diagnostic defaults to an error, but we allow projects to 4629 // map it down to a warning (or ignore it). It's a fairly common 4630 // practice among users of the ms_struct pragma to mass-annotate 4631 // headers, sweeping up a bunch of types that the project doesn't 4632 // really rely on MSVC-compatible layout for. We must therefore 4633 // support "ms_struct except for C++ stuff" as a secondary ABI. 4634 if (Record->isMsStruct(Context) && 4635 (Record->isPolymorphic() || Record->getNumBases())) { 4636 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4637 } 4638 4639 // Declare inheriting constructors. We do this eagerly here because: 4640 // - The standard requires an eager diagnostic for conflicting inheriting 4641 // constructors from different classes. 4642 // - The lazy declaration of the other implicit constructors is so as to not 4643 // waste space and performance on classes that are not meant to be 4644 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4645 // have inheriting constructors. 4646 DeclareInheritingConstructors(Record); 4647 4648 checkDLLAttribute(*this, Record); 4649 } 4650 4651 /// Look up the special member function that would be called by a special 4652 /// member function for a subobject of class type. 4653 /// 4654 /// \param Class The class type of the subobject. 4655 /// \param CSM The kind of special member function. 4656 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4657 /// \param ConstRHS True if this is a copy operation with a const object 4658 /// on its RHS, that is, if the argument to the outer special member 4659 /// function is 'const' and this is not a field marked 'mutable'. 4660 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4661 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4662 unsigned FieldQuals, bool ConstRHS) { 4663 unsigned LHSQuals = 0; 4664 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4665 LHSQuals = FieldQuals; 4666 4667 unsigned RHSQuals = FieldQuals; 4668 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4669 RHSQuals = 0; 4670 else if (ConstRHS) 4671 RHSQuals |= Qualifiers::Const; 4672 4673 return S.LookupSpecialMember(Class, CSM, 4674 RHSQuals & Qualifiers::Const, 4675 RHSQuals & Qualifiers::Volatile, 4676 false, 4677 LHSQuals & Qualifiers::Const, 4678 LHSQuals & Qualifiers::Volatile); 4679 } 4680 4681 /// Is the special member function which would be selected to perform the 4682 /// specified operation on the specified class type a constexpr constructor? 4683 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4684 Sema::CXXSpecialMember CSM, 4685 unsigned Quals, bool ConstRHS) { 4686 Sema::SpecialMemberOverloadResult *SMOR = 4687 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4688 if (!SMOR || !SMOR->getMethod()) 4689 // A constructor we wouldn't select can't be "involved in initializing" 4690 // anything. 4691 return true; 4692 return SMOR->getMethod()->isConstexpr(); 4693 } 4694 4695 /// Determine whether the specified special member function would be constexpr 4696 /// if it were implicitly defined. 4697 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4698 Sema::CXXSpecialMember CSM, 4699 bool ConstArg) { 4700 if (!S.getLangOpts().CPlusPlus11) 4701 return false; 4702 4703 // C++11 [dcl.constexpr]p4: 4704 // In the definition of a constexpr constructor [...] 4705 bool Ctor = true; 4706 switch (CSM) { 4707 case Sema::CXXDefaultConstructor: 4708 // Since default constructor lookup is essentially trivial (and cannot 4709 // involve, for instance, template instantiation), we compute whether a 4710 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4711 // 4712 // This is important for performance; we need to know whether the default 4713 // constructor is constexpr to determine whether the type is a literal type. 4714 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4715 4716 case Sema::CXXCopyConstructor: 4717 case Sema::CXXMoveConstructor: 4718 // For copy or move constructors, we need to perform overload resolution. 4719 break; 4720 4721 case Sema::CXXCopyAssignment: 4722 case Sema::CXXMoveAssignment: 4723 if (!S.getLangOpts().CPlusPlus1y) 4724 return false; 4725 // In C++1y, we need to perform overload resolution. 4726 Ctor = false; 4727 break; 4728 4729 case Sema::CXXDestructor: 4730 case Sema::CXXInvalid: 4731 return false; 4732 } 4733 4734 // -- if the class is a non-empty union, or for each non-empty anonymous 4735 // union member of a non-union class, exactly one non-static data member 4736 // shall be initialized; [DR1359] 4737 // 4738 // If we squint, this is guaranteed, since exactly one non-static data member 4739 // will be initialized (if the constructor isn't deleted), we just don't know 4740 // which one. 4741 if (Ctor && ClassDecl->isUnion()) 4742 return true; 4743 4744 // -- the class shall not have any virtual base classes; 4745 if (Ctor && ClassDecl->getNumVBases()) 4746 return false; 4747 4748 // C++1y [class.copy]p26: 4749 // -- [the class] is a literal type, and 4750 if (!Ctor && !ClassDecl->isLiteral()) 4751 return false; 4752 4753 // -- every constructor involved in initializing [...] base class 4754 // sub-objects shall be a constexpr constructor; 4755 // -- the assignment operator selected to copy/move each direct base 4756 // class is a constexpr function, and 4757 for (const auto &B : ClassDecl->bases()) { 4758 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 4759 if (!BaseType) continue; 4760 4761 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4762 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 4763 return false; 4764 } 4765 4766 // -- every constructor involved in initializing non-static data members 4767 // [...] shall be a constexpr constructor; 4768 // -- every non-static data member and base class sub-object shall be 4769 // initialized 4770 // -- for each non-static data member of X that is of class type (or array 4771 // thereof), the assignment operator selected to copy/move that member is 4772 // a constexpr function 4773 for (const auto *F : ClassDecl->fields()) { 4774 if (F->isInvalidDecl()) 4775 continue; 4776 QualType BaseType = S.Context.getBaseElementType(F->getType()); 4777 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 4778 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4779 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 4780 BaseType.getCVRQualifiers(), 4781 ConstArg && !F->isMutable())) 4782 return false; 4783 } 4784 } 4785 4786 // All OK, it's constexpr! 4787 return true; 4788 } 4789 4790 static Sema::ImplicitExceptionSpecification 4791 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4792 switch (S.getSpecialMember(MD)) { 4793 case Sema::CXXDefaultConstructor: 4794 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4795 case Sema::CXXCopyConstructor: 4796 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4797 case Sema::CXXCopyAssignment: 4798 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4799 case Sema::CXXMoveConstructor: 4800 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4801 case Sema::CXXMoveAssignment: 4802 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4803 case Sema::CXXDestructor: 4804 return S.ComputeDefaultedDtorExceptionSpec(MD); 4805 case Sema::CXXInvalid: 4806 break; 4807 } 4808 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4809 "only special members have implicit exception specs"); 4810 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4811 } 4812 4813 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4814 CXXMethodDecl *MD) { 4815 FunctionProtoType::ExtProtoInfo EPI; 4816 4817 // Build an exception specification pointing back at this member. 4818 EPI.ExceptionSpecType = EST_Unevaluated; 4819 EPI.ExceptionSpecDecl = MD; 4820 4821 // Set the calling convention to the default for C++ instance methods. 4822 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4823 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4824 /*IsCXXMethod=*/true)); 4825 return EPI; 4826 } 4827 4828 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4829 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4830 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4831 return; 4832 4833 // Evaluate the exception specification. 4834 ImplicitExceptionSpecification ExceptSpec = 4835 computeImplicitExceptionSpec(*this, Loc, MD); 4836 4837 FunctionProtoType::ExtProtoInfo EPI; 4838 ExceptSpec.getEPI(EPI); 4839 4840 // Update the type of the special member to use it. 4841 UpdateExceptionSpec(MD, EPI); 4842 4843 // A user-provided destructor can be defined outside the class. When that 4844 // happens, be sure to update the exception specification on both 4845 // declarations. 4846 const FunctionProtoType *CanonicalFPT = 4847 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4848 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4849 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI); 4850 } 4851 4852 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4853 CXXRecordDecl *RD = MD->getParent(); 4854 CXXSpecialMember CSM = getSpecialMember(MD); 4855 4856 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4857 "not an explicitly-defaulted special member"); 4858 4859 // Whether this was the first-declared instance of the constructor. 4860 // This affects whether we implicitly add an exception spec and constexpr. 4861 bool First = MD == MD->getCanonicalDecl(); 4862 4863 bool HadError = false; 4864 4865 // C++11 [dcl.fct.def.default]p1: 4866 // A function that is explicitly defaulted shall 4867 // -- be a special member function (checked elsewhere), 4868 // -- have the same type (except for ref-qualifiers, and except that a 4869 // copy operation can take a non-const reference) as an implicit 4870 // declaration, and 4871 // -- not have default arguments. 4872 unsigned ExpectedParams = 1; 4873 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4874 ExpectedParams = 0; 4875 if (MD->getNumParams() != ExpectedParams) { 4876 // This also checks for default arguments: a copy or move constructor with a 4877 // default argument is classified as a default constructor, and assignment 4878 // operations and destructors can't have default arguments. 4879 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4880 << CSM << MD->getSourceRange(); 4881 HadError = true; 4882 } else if (MD->isVariadic()) { 4883 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4884 << CSM << MD->getSourceRange(); 4885 HadError = true; 4886 } 4887 4888 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4889 4890 bool CanHaveConstParam = false; 4891 if (CSM == CXXCopyConstructor) 4892 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4893 else if (CSM == CXXCopyAssignment) 4894 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4895 4896 QualType ReturnType = Context.VoidTy; 4897 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4898 // Check for return type matching. 4899 ReturnType = Type->getReturnType(); 4900 QualType ExpectedReturnType = 4901 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4902 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4903 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4904 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4905 HadError = true; 4906 } 4907 4908 // A defaulted special member cannot have cv-qualifiers. 4909 if (Type->getTypeQuals()) { 4910 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4911 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4912 HadError = true; 4913 } 4914 } 4915 4916 // Check for parameter type matching. 4917 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 4918 bool HasConstParam = false; 4919 if (ExpectedParams && ArgType->isReferenceType()) { 4920 // Argument must be reference to possibly-const T. 4921 QualType ReferentType = ArgType->getPointeeType(); 4922 HasConstParam = ReferentType.isConstQualified(); 4923 4924 if (ReferentType.isVolatileQualified()) { 4925 Diag(MD->getLocation(), 4926 diag::err_defaulted_special_member_volatile_param) << CSM; 4927 HadError = true; 4928 } 4929 4930 if (HasConstParam && !CanHaveConstParam) { 4931 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4932 Diag(MD->getLocation(), 4933 diag::err_defaulted_special_member_copy_const_param) 4934 << (CSM == CXXCopyAssignment); 4935 // FIXME: Explain why this special member can't be const. 4936 } else { 4937 Diag(MD->getLocation(), 4938 diag::err_defaulted_special_member_move_const_param) 4939 << (CSM == CXXMoveAssignment); 4940 } 4941 HadError = true; 4942 } 4943 } else if (ExpectedParams) { 4944 // A copy assignment operator can take its argument by value, but a 4945 // defaulted one cannot. 4946 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4947 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4948 HadError = true; 4949 } 4950 4951 // C++11 [dcl.fct.def.default]p2: 4952 // An explicitly-defaulted function may be declared constexpr only if it 4953 // would have been implicitly declared as constexpr, 4954 // Do not apply this rule to members of class templates, since core issue 1358 4955 // makes such functions always instantiate to constexpr functions. For 4956 // functions which cannot be constexpr (for non-constructors in C++11 and for 4957 // destructors in C++1y), this is checked elsewhere. 4958 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4959 HasConstParam); 4960 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4961 : isa<CXXConstructorDecl>(MD)) && 4962 MD->isConstexpr() && !Constexpr && 4963 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4964 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4965 // FIXME: Explain why the special member can't be constexpr. 4966 HadError = true; 4967 } 4968 4969 // and may have an explicit exception-specification only if it is compatible 4970 // with the exception-specification on the implicit declaration. 4971 if (Type->hasExceptionSpec()) { 4972 // Delay the check if this is the first declaration of the special member, 4973 // since we may not have parsed some necessary in-class initializers yet. 4974 if (First) { 4975 // If the exception specification needs to be instantiated, do so now, 4976 // before we clobber it with an EST_Unevaluated specification below. 4977 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4978 InstantiateExceptionSpec(MD->getLocStart(), MD); 4979 Type = MD->getType()->getAs<FunctionProtoType>(); 4980 } 4981 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4982 } else 4983 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4984 } 4985 4986 // If a function is explicitly defaulted on its first declaration, 4987 if (First) { 4988 // -- it is implicitly considered to be constexpr if the implicit 4989 // definition would be, 4990 MD->setConstexpr(Constexpr); 4991 4992 // -- it is implicitly considered to have the same exception-specification 4993 // as if it had been implicitly declared, 4994 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4995 EPI.ExceptionSpecType = EST_Unevaluated; 4996 EPI.ExceptionSpecDecl = MD; 4997 MD->setType(Context.getFunctionType(ReturnType, 4998 ArrayRef<QualType>(&ArgType, 4999 ExpectedParams), 5000 EPI)); 5001 } 5002 5003 if (ShouldDeleteSpecialMember(MD, CSM)) { 5004 if (First) { 5005 SetDeclDeleted(MD, MD->getLocation()); 5006 } else { 5007 // C++11 [dcl.fct.def.default]p4: 5008 // [For a] user-provided explicitly-defaulted function [...] if such a 5009 // function is implicitly defined as deleted, the program is ill-formed. 5010 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5011 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5012 HadError = true; 5013 } 5014 } 5015 5016 if (HadError) 5017 MD->setInvalidDecl(); 5018 } 5019 5020 /// Check whether the exception specification provided for an 5021 /// explicitly-defaulted special member matches the exception specification 5022 /// that would have been generated for an implicit special member, per 5023 /// C++11 [dcl.fct.def.default]p2. 5024 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5025 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5026 // Compute the implicit exception specification. 5027 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5028 /*IsCXXMethod=*/true); 5029 FunctionProtoType::ExtProtoInfo EPI(CC); 5030 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 5031 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5032 Context.getFunctionType(Context.VoidTy, None, EPI)); 5033 5034 // Ensure that it matches. 5035 CheckEquivalentExceptionSpec( 5036 PDiag(diag::err_incorrect_defaulted_exception_spec) 5037 << getSpecialMember(MD), PDiag(), 5038 ImplicitType, SourceLocation(), 5039 SpecifiedType, MD->getLocation()); 5040 } 5041 5042 void Sema::CheckDelayedMemberExceptionSpecs() { 5043 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 5044 2> Checks; 5045 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 5046 5047 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 5048 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5049 5050 // Perform any deferred checking of exception specifications for virtual 5051 // destructors. 5052 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 5053 const CXXDestructorDecl *Dtor = Checks[i].first; 5054 assert(!Dtor->getParent()->isDependentType() && 5055 "Should not ever add destructors of templates into the list."); 5056 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 5057 } 5058 5059 // Check that any explicitly-defaulted methods have exception specifications 5060 // compatible with their implicit exception specifications. 5061 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 5062 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 5063 Specs[I].second); 5064 } 5065 5066 namespace { 5067 struct SpecialMemberDeletionInfo { 5068 Sema &S; 5069 CXXMethodDecl *MD; 5070 Sema::CXXSpecialMember CSM; 5071 bool Diagnose; 5072 5073 // Properties of the special member, computed for convenience. 5074 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5075 SourceLocation Loc; 5076 5077 bool AllFieldsAreConst; 5078 5079 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5080 Sema::CXXSpecialMember CSM, bool Diagnose) 5081 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5082 IsConstructor(false), IsAssignment(false), IsMove(false), 5083 ConstArg(false), Loc(MD->getLocation()), 5084 AllFieldsAreConst(true) { 5085 switch (CSM) { 5086 case Sema::CXXDefaultConstructor: 5087 case Sema::CXXCopyConstructor: 5088 IsConstructor = true; 5089 break; 5090 case Sema::CXXMoveConstructor: 5091 IsConstructor = true; 5092 IsMove = true; 5093 break; 5094 case Sema::CXXCopyAssignment: 5095 IsAssignment = true; 5096 break; 5097 case Sema::CXXMoveAssignment: 5098 IsAssignment = true; 5099 IsMove = true; 5100 break; 5101 case Sema::CXXDestructor: 5102 break; 5103 case Sema::CXXInvalid: 5104 llvm_unreachable("invalid special member kind"); 5105 } 5106 5107 if (MD->getNumParams()) { 5108 if (const ReferenceType *RT = 5109 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5110 ConstArg = RT->getPointeeType().isConstQualified(); 5111 } 5112 } 5113 5114 bool inUnion() const { return MD->getParent()->isUnion(); } 5115 5116 /// Look up the corresponding special member in the given class. 5117 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5118 unsigned Quals, bool IsMutable) { 5119 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5120 ConstArg && !IsMutable); 5121 } 5122 5123 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5124 5125 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5126 bool shouldDeleteForField(FieldDecl *FD); 5127 bool shouldDeleteForAllConstMembers(); 5128 5129 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5130 unsigned Quals); 5131 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5132 Sema::SpecialMemberOverloadResult *SMOR, 5133 bool IsDtorCallInCtor); 5134 5135 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5136 }; 5137 } 5138 5139 /// Is the given special member inaccessible when used on the given 5140 /// sub-object. 5141 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5142 CXXMethodDecl *target) { 5143 /// If we're operating on a base class, the object type is the 5144 /// type of this special member. 5145 QualType objectTy; 5146 AccessSpecifier access = target->getAccess(); 5147 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5148 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5149 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5150 5151 // If we're operating on a field, the object type is the type of the field. 5152 } else { 5153 objectTy = S.Context.getTypeDeclType(target->getParent()); 5154 } 5155 5156 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5157 } 5158 5159 /// Check whether we should delete a special member due to the implicit 5160 /// definition containing a call to a special member of a subobject. 5161 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5162 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5163 bool IsDtorCallInCtor) { 5164 CXXMethodDecl *Decl = SMOR->getMethod(); 5165 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5166 5167 int DiagKind = -1; 5168 5169 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5170 DiagKind = !Decl ? 0 : 1; 5171 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5172 DiagKind = 2; 5173 else if (!isAccessible(Subobj, Decl)) 5174 DiagKind = 3; 5175 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5176 !Decl->isTrivial()) { 5177 // A member of a union must have a trivial corresponding special member. 5178 // As a weird special case, a destructor call from a union's constructor 5179 // must be accessible and non-deleted, but need not be trivial. Such a 5180 // destructor is never actually called, but is semantically checked as 5181 // if it were. 5182 DiagKind = 4; 5183 } 5184 5185 if (DiagKind == -1) 5186 return false; 5187 5188 if (Diagnose) { 5189 if (Field) { 5190 S.Diag(Field->getLocation(), 5191 diag::note_deleted_special_member_class_subobject) 5192 << CSM << MD->getParent() << /*IsField*/true 5193 << Field << DiagKind << IsDtorCallInCtor; 5194 } else { 5195 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5196 S.Diag(Base->getLocStart(), 5197 diag::note_deleted_special_member_class_subobject) 5198 << CSM << MD->getParent() << /*IsField*/false 5199 << Base->getType() << DiagKind << IsDtorCallInCtor; 5200 } 5201 5202 if (DiagKind == 1) 5203 S.NoteDeletedFunction(Decl); 5204 // FIXME: Explain inaccessibility if DiagKind == 3. 5205 } 5206 5207 return true; 5208 } 5209 5210 /// Check whether we should delete a special member function due to having a 5211 /// direct or virtual base class or non-static data member of class type M. 5212 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5213 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5214 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5215 bool IsMutable = Field && Field->isMutable(); 5216 5217 // C++11 [class.ctor]p5: 5218 // -- any direct or virtual base class, or non-static data member with no 5219 // brace-or-equal-initializer, has class type M (or array thereof) and 5220 // either M has no default constructor or overload resolution as applied 5221 // to M's default constructor results in an ambiguity or in a function 5222 // that is deleted or inaccessible 5223 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5224 // -- a direct or virtual base class B that cannot be copied/moved because 5225 // overload resolution, as applied to B's corresponding special member, 5226 // results in an ambiguity or a function that is deleted or inaccessible 5227 // from the defaulted special member 5228 // C++11 [class.dtor]p5: 5229 // -- any direct or virtual base class [...] has a type with a destructor 5230 // that is deleted or inaccessible 5231 if (!(CSM == Sema::CXXDefaultConstructor && 5232 Field && Field->hasInClassInitializer()) && 5233 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5234 false)) 5235 return true; 5236 5237 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5238 // -- any direct or virtual base class or non-static data member has a 5239 // type with a destructor that is deleted or inaccessible 5240 if (IsConstructor) { 5241 Sema::SpecialMemberOverloadResult *SMOR = 5242 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5243 false, false, false, false, false); 5244 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5245 return true; 5246 } 5247 5248 return false; 5249 } 5250 5251 /// Check whether we should delete a special member function due to the class 5252 /// having a particular direct or virtual base class. 5253 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5254 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5255 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5256 } 5257 5258 /// Check whether we should delete a special member function due to the class 5259 /// having a particular non-static data member. 5260 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5261 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5262 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5263 5264 if (CSM == Sema::CXXDefaultConstructor) { 5265 // For a default constructor, all references must be initialized in-class 5266 // and, if a union, it must have a non-const member. 5267 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5268 if (Diagnose) 5269 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5270 << MD->getParent() << FD << FieldType << /*Reference*/0; 5271 return true; 5272 } 5273 // C++11 [class.ctor]p5: any non-variant non-static data member of 5274 // const-qualified type (or array thereof) with no 5275 // brace-or-equal-initializer does not have a user-provided default 5276 // constructor. 5277 if (!inUnion() && FieldType.isConstQualified() && 5278 !FD->hasInClassInitializer() && 5279 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5280 if (Diagnose) 5281 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5282 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5283 return true; 5284 } 5285 5286 if (inUnion() && !FieldType.isConstQualified()) 5287 AllFieldsAreConst = false; 5288 } else if (CSM == Sema::CXXCopyConstructor) { 5289 // For a copy constructor, data members must not be of rvalue reference 5290 // type. 5291 if (FieldType->isRValueReferenceType()) { 5292 if (Diagnose) 5293 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5294 << MD->getParent() << FD << FieldType; 5295 return true; 5296 } 5297 } else if (IsAssignment) { 5298 // For an assignment operator, data members must not be of reference type. 5299 if (FieldType->isReferenceType()) { 5300 if (Diagnose) 5301 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5302 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5303 return true; 5304 } 5305 if (!FieldRecord && FieldType.isConstQualified()) { 5306 // C++11 [class.copy]p23: 5307 // -- a non-static data member of const non-class type (or array thereof) 5308 if (Diagnose) 5309 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5310 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5311 return true; 5312 } 5313 } 5314 5315 if (FieldRecord) { 5316 // Some additional restrictions exist on the variant members. 5317 if (!inUnion() && FieldRecord->isUnion() && 5318 FieldRecord->isAnonymousStructOrUnion()) { 5319 bool AllVariantFieldsAreConst = true; 5320 5321 // FIXME: Handle anonymous unions declared within anonymous unions. 5322 for (auto *UI : FieldRecord->fields()) { 5323 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5324 5325 if (!UnionFieldType.isConstQualified()) 5326 AllVariantFieldsAreConst = false; 5327 5328 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5329 if (UnionFieldRecord && 5330 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5331 UnionFieldType.getCVRQualifiers())) 5332 return true; 5333 } 5334 5335 // At least one member in each anonymous union must be non-const 5336 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5337 !FieldRecord->field_empty()) { 5338 if (Diagnose) 5339 S.Diag(FieldRecord->getLocation(), 5340 diag::note_deleted_default_ctor_all_const) 5341 << MD->getParent() << /*anonymous union*/1; 5342 return true; 5343 } 5344 5345 // Don't check the implicit member of the anonymous union type. 5346 // This is technically non-conformant, but sanity demands it. 5347 return false; 5348 } 5349 5350 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5351 FieldType.getCVRQualifiers())) 5352 return true; 5353 } 5354 5355 return false; 5356 } 5357 5358 /// C++11 [class.ctor] p5: 5359 /// A defaulted default constructor for a class X is defined as deleted if 5360 /// X is a union and all of its variant members are of const-qualified type. 5361 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5362 // This is a silly definition, because it gives an empty union a deleted 5363 // default constructor. Don't do that. 5364 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5365 !MD->getParent()->field_empty()) { 5366 if (Diagnose) 5367 S.Diag(MD->getParent()->getLocation(), 5368 diag::note_deleted_default_ctor_all_const) 5369 << MD->getParent() << /*not anonymous union*/0; 5370 return true; 5371 } 5372 return false; 5373 } 5374 5375 /// Determine whether a defaulted special member function should be defined as 5376 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5377 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5378 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5379 bool Diagnose) { 5380 if (MD->isInvalidDecl()) 5381 return false; 5382 CXXRecordDecl *RD = MD->getParent(); 5383 assert(!RD->isDependentType() && "do deletion after instantiation"); 5384 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5385 return false; 5386 5387 // C++11 [expr.lambda.prim]p19: 5388 // The closure type associated with a lambda-expression has a 5389 // deleted (8.4.3) default constructor and a deleted copy 5390 // assignment operator. 5391 if (RD->isLambda() && 5392 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5393 if (Diagnose) 5394 Diag(RD->getLocation(), diag::note_lambda_decl); 5395 return true; 5396 } 5397 5398 // For an anonymous struct or union, the copy and assignment special members 5399 // will never be used, so skip the check. For an anonymous union declared at 5400 // namespace scope, the constructor and destructor are used. 5401 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5402 RD->isAnonymousStructOrUnion()) 5403 return false; 5404 5405 // C++11 [class.copy]p7, p18: 5406 // If the class definition declares a move constructor or move assignment 5407 // operator, an implicitly declared copy constructor or copy assignment 5408 // operator is defined as deleted. 5409 if (MD->isImplicit() && 5410 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5411 CXXMethodDecl *UserDeclaredMove = nullptr; 5412 5413 // In Microsoft mode, a user-declared move only causes the deletion of the 5414 // corresponding copy operation, not both copy operations. 5415 if (RD->hasUserDeclaredMoveConstructor() && 5416 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5417 if (!Diagnose) return true; 5418 5419 // Find any user-declared move constructor. 5420 for (auto *I : RD->ctors()) { 5421 if (I->isMoveConstructor()) { 5422 UserDeclaredMove = I; 5423 break; 5424 } 5425 } 5426 assert(UserDeclaredMove); 5427 } else if (RD->hasUserDeclaredMoveAssignment() && 5428 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5429 if (!Diagnose) return true; 5430 5431 // Find any user-declared move assignment operator. 5432 for (auto *I : RD->methods()) { 5433 if (I->isMoveAssignmentOperator()) { 5434 UserDeclaredMove = I; 5435 break; 5436 } 5437 } 5438 assert(UserDeclaredMove); 5439 } 5440 5441 if (UserDeclaredMove) { 5442 Diag(UserDeclaredMove->getLocation(), 5443 diag::note_deleted_copy_user_declared_move) 5444 << (CSM == CXXCopyAssignment) << RD 5445 << UserDeclaredMove->isMoveAssignmentOperator(); 5446 return true; 5447 } 5448 } 5449 5450 // Do access control from the special member function 5451 ContextRAII MethodContext(*this, MD); 5452 5453 // C++11 [class.dtor]p5: 5454 // -- for a virtual destructor, lookup of the non-array deallocation function 5455 // results in an ambiguity or in a function that is deleted or inaccessible 5456 if (CSM == CXXDestructor && MD->isVirtual()) { 5457 FunctionDecl *OperatorDelete = nullptr; 5458 DeclarationName Name = 5459 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5460 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5461 OperatorDelete, false)) { 5462 if (Diagnose) 5463 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5464 return true; 5465 } 5466 } 5467 5468 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5469 5470 for (auto &BI : RD->bases()) 5471 if (!BI.isVirtual() && 5472 SMI.shouldDeleteForBase(&BI)) 5473 return true; 5474 5475 // Per DR1611, do not consider virtual bases of constructors of abstract 5476 // classes, since we are not going to construct them. 5477 if (!RD->isAbstract() || !SMI.IsConstructor) { 5478 for (auto &BI : RD->vbases()) 5479 if (SMI.shouldDeleteForBase(&BI)) 5480 return true; 5481 } 5482 5483 for (auto *FI : RD->fields()) 5484 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5485 SMI.shouldDeleteForField(FI)) 5486 return true; 5487 5488 if (SMI.shouldDeleteForAllConstMembers()) 5489 return true; 5490 5491 return false; 5492 } 5493 5494 /// Perform lookup for a special member of the specified kind, and determine 5495 /// whether it is trivial. If the triviality can be determined without the 5496 /// lookup, skip it. This is intended for use when determining whether a 5497 /// special member of a containing object is trivial, and thus does not ever 5498 /// perform overload resolution for default constructors. 5499 /// 5500 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5501 /// member that was most likely to be intended to be trivial, if any. 5502 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5503 Sema::CXXSpecialMember CSM, unsigned Quals, 5504 bool ConstRHS, CXXMethodDecl **Selected) { 5505 if (Selected) 5506 *Selected = nullptr; 5507 5508 switch (CSM) { 5509 case Sema::CXXInvalid: 5510 llvm_unreachable("not a special member"); 5511 5512 case Sema::CXXDefaultConstructor: 5513 // C++11 [class.ctor]p5: 5514 // A default constructor is trivial if: 5515 // - all the [direct subobjects] have trivial default constructors 5516 // 5517 // Note, no overload resolution is performed in this case. 5518 if (RD->hasTrivialDefaultConstructor()) 5519 return true; 5520 5521 if (Selected) { 5522 // If there's a default constructor which could have been trivial, dig it 5523 // out. Otherwise, if there's any user-provided default constructor, point 5524 // to that as an example of why there's not a trivial one. 5525 CXXConstructorDecl *DefCtor = nullptr; 5526 if (RD->needsImplicitDefaultConstructor()) 5527 S.DeclareImplicitDefaultConstructor(RD); 5528 for (auto *CI : RD->ctors()) { 5529 if (!CI->isDefaultConstructor()) 5530 continue; 5531 DefCtor = CI; 5532 if (!DefCtor->isUserProvided()) 5533 break; 5534 } 5535 5536 *Selected = DefCtor; 5537 } 5538 5539 return false; 5540 5541 case Sema::CXXDestructor: 5542 // C++11 [class.dtor]p5: 5543 // A destructor is trivial if: 5544 // - all the direct [subobjects] have trivial destructors 5545 if (RD->hasTrivialDestructor()) 5546 return true; 5547 5548 if (Selected) { 5549 if (RD->needsImplicitDestructor()) 5550 S.DeclareImplicitDestructor(RD); 5551 *Selected = RD->getDestructor(); 5552 } 5553 5554 return false; 5555 5556 case Sema::CXXCopyConstructor: 5557 // C++11 [class.copy]p12: 5558 // A copy constructor is trivial if: 5559 // - the constructor selected to copy each direct [subobject] is trivial 5560 if (RD->hasTrivialCopyConstructor()) { 5561 if (Quals == Qualifiers::Const) 5562 // We must either select the trivial copy constructor or reach an 5563 // ambiguity; no need to actually perform overload resolution. 5564 return true; 5565 } else if (!Selected) { 5566 return false; 5567 } 5568 // In C++98, we are not supposed to perform overload resolution here, but we 5569 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5570 // cases like B as having a non-trivial copy constructor: 5571 // struct A { template<typename T> A(T&); }; 5572 // struct B { mutable A a; }; 5573 goto NeedOverloadResolution; 5574 5575 case Sema::CXXCopyAssignment: 5576 // C++11 [class.copy]p25: 5577 // A copy assignment operator is trivial if: 5578 // - the assignment operator selected to copy each direct [subobject] is 5579 // trivial 5580 if (RD->hasTrivialCopyAssignment()) { 5581 if (Quals == Qualifiers::Const) 5582 return true; 5583 } else if (!Selected) { 5584 return false; 5585 } 5586 // In C++98, we are not supposed to perform overload resolution here, but we 5587 // treat that as a language defect. 5588 goto NeedOverloadResolution; 5589 5590 case Sema::CXXMoveConstructor: 5591 case Sema::CXXMoveAssignment: 5592 NeedOverloadResolution: 5593 Sema::SpecialMemberOverloadResult *SMOR = 5594 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5595 5596 // The standard doesn't describe how to behave if the lookup is ambiguous. 5597 // We treat it as not making the member non-trivial, just like the standard 5598 // mandates for the default constructor. This should rarely matter, because 5599 // the member will also be deleted. 5600 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5601 return true; 5602 5603 if (!SMOR->getMethod()) { 5604 assert(SMOR->getKind() == 5605 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5606 return false; 5607 } 5608 5609 // We deliberately don't check if we found a deleted special member. We're 5610 // not supposed to! 5611 if (Selected) 5612 *Selected = SMOR->getMethod(); 5613 return SMOR->getMethod()->isTrivial(); 5614 } 5615 5616 llvm_unreachable("unknown special method kind"); 5617 } 5618 5619 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5620 for (auto *CI : RD->ctors()) 5621 if (!CI->isImplicit()) 5622 return CI; 5623 5624 // Look for constructor templates. 5625 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5626 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5627 if (CXXConstructorDecl *CD = 5628 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5629 return CD; 5630 } 5631 5632 return nullptr; 5633 } 5634 5635 /// The kind of subobject we are checking for triviality. The values of this 5636 /// enumeration are used in diagnostics. 5637 enum TrivialSubobjectKind { 5638 /// The subobject is a base class. 5639 TSK_BaseClass, 5640 /// The subobject is a non-static data member. 5641 TSK_Field, 5642 /// The object is actually the complete object. 5643 TSK_CompleteObject 5644 }; 5645 5646 /// Check whether the special member selected for a given type would be trivial. 5647 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5648 QualType SubType, bool ConstRHS, 5649 Sema::CXXSpecialMember CSM, 5650 TrivialSubobjectKind Kind, 5651 bool Diagnose) { 5652 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5653 if (!SubRD) 5654 return true; 5655 5656 CXXMethodDecl *Selected; 5657 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5658 ConstRHS, Diagnose ? &Selected : nullptr)) 5659 return true; 5660 5661 if (Diagnose) { 5662 if (ConstRHS) 5663 SubType.addConst(); 5664 5665 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5666 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5667 << Kind << SubType.getUnqualifiedType(); 5668 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5669 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5670 } else if (!Selected) 5671 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5672 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5673 else if (Selected->isUserProvided()) { 5674 if (Kind == TSK_CompleteObject) 5675 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5676 << Kind << SubType.getUnqualifiedType() << CSM; 5677 else { 5678 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5679 << Kind << SubType.getUnqualifiedType() << CSM; 5680 S.Diag(Selected->getLocation(), diag::note_declared_at); 5681 } 5682 } else { 5683 if (Kind != TSK_CompleteObject) 5684 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5685 << Kind << SubType.getUnqualifiedType() << CSM; 5686 5687 // Explain why the defaulted or deleted special member isn't trivial. 5688 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5689 } 5690 } 5691 5692 return false; 5693 } 5694 5695 /// Check whether the members of a class type allow a special member to be 5696 /// trivial. 5697 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5698 Sema::CXXSpecialMember CSM, 5699 bool ConstArg, bool Diagnose) { 5700 for (const auto *FI : RD->fields()) { 5701 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5702 continue; 5703 5704 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5705 5706 // Pretend anonymous struct or union members are members of this class. 5707 if (FI->isAnonymousStructOrUnion()) { 5708 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5709 CSM, ConstArg, Diagnose)) 5710 return false; 5711 continue; 5712 } 5713 5714 // C++11 [class.ctor]p5: 5715 // A default constructor is trivial if [...] 5716 // -- no non-static data member of its class has a 5717 // brace-or-equal-initializer 5718 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5719 if (Diagnose) 5720 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5721 return false; 5722 } 5723 5724 // Objective C ARC 4.3.5: 5725 // [...] nontrivally ownership-qualified types are [...] not trivially 5726 // default constructible, copy constructible, move constructible, copy 5727 // assignable, move assignable, or destructible [...] 5728 if (S.getLangOpts().ObjCAutoRefCount && 5729 FieldType.hasNonTrivialObjCLifetime()) { 5730 if (Diagnose) 5731 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5732 << RD << FieldType.getObjCLifetime(); 5733 return false; 5734 } 5735 5736 bool ConstRHS = ConstArg && !FI->isMutable(); 5737 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 5738 CSM, TSK_Field, Diagnose)) 5739 return false; 5740 } 5741 5742 return true; 5743 } 5744 5745 /// Diagnose why the specified class does not have a trivial special member of 5746 /// the given kind. 5747 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5748 QualType Ty = Context.getRecordType(RD); 5749 5750 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 5751 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 5752 TSK_CompleteObject, /*Diagnose*/true); 5753 } 5754 5755 /// Determine whether a defaulted or deleted special member function is trivial, 5756 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5757 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5758 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5759 bool Diagnose) { 5760 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5761 5762 CXXRecordDecl *RD = MD->getParent(); 5763 5764 bool ConstArg = false; 5765 5766 // C++11 [class.copy]p12, p25: [DR1593] 5767 // A [special member] is trivial if [...] its parameter-type-list is 5768 // equivalent to the parameter-type-list of an implicit declaration [...] 5769 switch (CSM) { 5770 case CXXDefaultConstructor: 5771 case CXXDestructor: 5772 // Trivial default constructors and destructors cannot have parameters. 5773 break; 5774 5775 case CXXCopyConstructor: 5776 case CXXCopyAssignment: { 5777 // Trivial copy operations always have const, non-volatile parameter types. 5778 ConstArg = true; 5779 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5780 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5781 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5782 if (Diagnose) 5783 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5784 << Param0->getSourceRange() << Param0->getType() 5785 << Context.getLValueReferenceType( 5786 Context.getRecordType(RD).withConst()); 5787 return false; 5788 } 5789 break; 5790 } 5791 5792 case CXXMoveConstructor: 5793 case CXXMoveAssignment: { 5794 // Trivial move operations always have non-cv-qualified parameters. 5795 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5796 const RValueReferenceType *RT = 5797 Param0->getType()->getAs<RValueReferenceType>(); 5798 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5799 if (Diagnose) 5800 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5801 << Param0->getSourceRange() << Param0->getType() 5802 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5803 return false; 5804 } 5805 break; 5806 } 5807 5808 case CXXInvalid: 5809 llvm_unreachable("not a special member"); 5810 } 5811 5812 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5813 if (Diagnose) 5814 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5815 diag::note_nontrivial_default_arg) 5816 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5817 return false; 5818 } 5819 if (MD->isVariadic()) { 5820 if (Diagnose) 5821 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5822 return false; 5823 } 5824 5825 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5826 // A copy/move [constructor or assignment operator] is trivial if 5827 // -- the [member] selected to copy/move each direct base class subobject 5828 // is trivial 5829 // 5830 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5831 // A [default constructor or destructor] is trivial if 5832 // -- all the direct base classes have trivial [default constructors or 5833 // destructors] 5834 for (const auto &BI : RD->bases()) 5835 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 5836 ConstArg, CSM, TSK_BaseClass, Diagnose)) 5837 return false; 5838 5839 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5840 // A copy/move [constructor or assignment operator] for a class X is 5841 // trivial if 5842 // -- for each non-static data member of X that is of class type (or array 5843 // thereof), the constructor selected to copy/move that member is 5844 // trivial 5845 // 5846 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5847 // A [default constructor or destructor] is trivial if 5848 // -- for all of the non-static data members of its class that are of class 5849 // type (or array thereof), each such class has a trivial [default 5850 // constructor or destructor] 5851 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5852 return false; 5853 5854 // C++11 [class.dtor]p5: 5855 // A destructor is trivial if [...] 5856 // -- the destructor is not virtual 5857 if (CSM == CXXDestructor && MD->isVirtual()) { 5858 if (Diagnose) 5859 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5860 return false; 5861 } 5862 5863 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5864 // A [special member] for class X is trivial if [...] 5865 // -- class X has no virtual functions and no virtual base classes 5866 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5867 if (!Diagnose) 5868 return false; 5869 5870 if (RD->getNumVBases()) { 5871 // Check for virtual bases. We already know that the corresponding 5872 // member in all bases is trivial, so vbases must all be direct. 5873 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5874 assert(BS.isVirtual()); 5875 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5876 return false; 5877 } 5878 5879 // Must have a virtual method. 5880 for (const auto *MI : RD->methods()) { 5881 if (MI->isVirtual()) { 5882 SourceLocation MLoc = MI->getLocStart(); 5883 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5884 return false; 5885 } 5886 } 5887 5888 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5889 } 5890 5891 // Looks like it's trivial! 5892 return true; 5893 } 5894 5895 /// \brief Data used with FindHiddenVirtualMethod 5896 namespace { 5897 struct FindHiddenVirtualMethodData { 5898 Sema *S; 5899 CXXMethodDecl *Method; 5900 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5901 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5902 }; 5903 } 5904 5905 /// \brief Check whether any most overriden method from MD in Methods 5906 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5907 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5908 if (MD->size_overridden_methods() == 0) 5909 return Methods.count(MD->getCanonicalDecl()); 5910 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5911 E = MD->end_overridden_methods(); 5912 I != E; ++I) 5913 if (CheckMostOverridenMethods(*I, Methods)) 5914 return true; 5915 return false; 5916 } 5917 5918 /// \brief Member lookup function that determines whether a given C++ 5919 /// method overloads virtual methods in a base class without overriding any, 5920 /// to be used with CXXRecordDecl::lookupInBases(). 5921 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5922 CXXBasePath &Path, 5923 void *UserData) { 5924 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5925 5926 FindHiddenVirtualMethodData &Data 5927 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5928 5929 DeclarationName Name = Data.Method->getDeclName(); 5930 assert(Name.getNameKind() == DeclarationName::Identifier); 5931 5932 bool foundSameNameMethod = false; 5933 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5934 for (Path.Decls = BaseRecord->lookup(Name); 5935 !Path.Decls.empty(); 5936 Path.Decls = Path.Decls.slice(1)) { 5937 NamedDecl *D = Path.Decls.front(); 5938 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5939 MD = MD->getCanonicalDecl(); 5940 foundSameNameMethod = true; 5941 // Interested only in hidden virtual methods. 5942 if (!MD->isVirtual()) 5943 continue; 5944 // If the method we are checking overrides a method from its base 5945 // don't warn about the other overloaded methods. 5946 if (!Data.S->IsOverload(Data.Method, MD, false)) 5947 return true; 5948 // Collect the overload only if its hidden. 5949 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5950 overloadedMethods.push_back(MD); 5951 } 5952 } 5953 5954 if (foundSameNameMethod) 5955 Data.OverloadedMethods.append(overloadedMethods.begin(), 5956 overloadedMethods.end()); 5957 return foundSameNameMethod; 5958 } 5959 5960 /// \brief Add the most overriden methods from MD to Methods 5961 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5962 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5963 if (MD->size_overridden_methods() == 0) 5964 Methods.insert(MD->getCanonicalDecl()); 5965 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5966 E = MD->end_overridden_methods(); 5967 I != E; ++I) 5968 AddMostOverridenMethods(*I, Methods); 5969 } 5970 5971 /// \brief Check if a method overloads virtual methods in a base class without 5972 /// overriding any. 5973 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5974 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5975 if (!MD->getDeclName().isIdentifier()) 5976 return; 5977 5978 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5979 /*bool RecordPaths=*/false, 5980 /*bool DetectVirtual=*/false); 5981 FindHiddenVirtualMethodData Data; 5982 Data.Method = MD; 5983 Data.S = this; 5984 5985 // Keep the base methods that were overriden or introduced in the subclass 5986 // by 'using' in a set. A base method not in this set is hidden. 5987 CXXRecordDecl *DC = MD->getParent(); 5988 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5989 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5990 NamedDecl *ND = *I; 5991 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5992 ND = shad->getTargetDecl(); 5993 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5994 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5995 } 5996 5997 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 5998 OverloadedMethods = Data.OverloadedMethods; 5999 } 6000 6001 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6002 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6003 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6004 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6005 PartialDiagnostic PD = PDiag( 6006 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6007 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6008 Diag(overloadedMD->getLocation(), PD); 6009 } 6010 } 6011 6012 /// \brief Diagnose methods which overload virtual methods in a base class 6013 /// without overriding any. 6014 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6015 if (MD->isInvalidDecl()) 6016 return; 6017 6018 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6019 return; 6020 6021 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6022 FindHiddenVirtualMethods(MD, OverloadedMethods); 6023 if (!OverloadedMethods.empty()) { 6024 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6025 << MD << (OverloadedMethods.size() > 1); 6026 6027 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6028 } 6029 } 6030 6031 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6032 Decl *TagDecl, 6033 SourceLocation LBrac, 6034 SourceLocation RBrac, 6035 AttributeList *AttrList) { 6036 if (!TagDecl) 6037 return; 6038 6039 AdjustDeclIfTemplate(TagDecl); 6040 6041 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6042 if (l->getKind() != AttributeList::AT_Visibility) 6043 continue; 6044 l->setInvalid(); 6045 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6046 l->getName(); 6047 } 6048 6049 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6050 // strict aliasing violation! 6051 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6052 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6053 6054 CheckCompletedCXXClass( 6055 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6056 } 6057 6058 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6059 /// special functions, such as the default constructor, copy 6060 /// constructor, or destructor, to the given C++ class (C++ 6061 /// [special]p1). This routine can only be executed just before the 6062 /// definition of the class is complete. 6063 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6064 if (!ClassDecl->hasUserDeclaredConstructor()) 6065 ++ASTContext::NumImplicitDefaultConstructors; 6066 6067 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6068 ++ASTContext::NumImplicitCopyConstructors; 6069 6070 // If the properties or semantics of the copy constructor couldn't be 6071 // determined while the class was being declared, force a declaration 6072 // of it now. 6073 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6074 DeclareImplicitCopyConstructor(ClassDecl); 6075 } 6076 6077 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6078 ++ASTContext::NumImplicitMoveConstructors; 6079 6080 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6081 DeclareImplicitMoveConstructor(ClassDecl); 6082 } 6083 6084 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6085 ++ASTContext::NumImplicitCopyAssignmentOperators; 6086 6087 // If we have a dynamic class, then the copy assignment operator may be 6088 // virtual, so we have to declare it immediately. This ensures that, e.g., 6089 // it shows up in the right place in the vtable and that we diagnose 6090 // problems with the implicit exception specification. 6091 if (ClassDecl->isDynamicClass() || 6092 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6093 DeclareImplicitCopyAssignment(ClassDecl); 6094 } 6095 6096 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6097 ++ASTContext::NumImplicitMoveAssignmentOperators; 6098 6099 // Likewise for the move assignment operator. 6100 if (ClassDecl->isDynamicClass() || 6101 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6102 DeclareImplicitMoveAssignment(ClassDecl); 6103 } 6104 6105 if (!ClassDecl->hasUserDeclaredDestructor()) { 6106 ++ASTContext::NumImplicitDestructors; 6107 6108 // If we have a dynamic class, then the destructor may be virtual, so we 6109 // have to declare the destructor immediately. This ensures that, e.g., it 6110 // shows up in the right place in the vtable and that we diagnose problems 6111 // with the implicit exception specification. 6112 if (ClassDecl->isDynamicClass() || 6113 ClassDecl->needsOverloadResolutionForDestructor()) 6114 DeclareImplicitDestructor(ClassDecl); 6115 } 6116 } 6117 6118 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6119 if (!D) 6120 return 0; 6121 6122 // The order of template parameters is not important here. All names 6123 // get added to the same scope. 6124 SmallVector<TemplateParameterList *, 4> ParameterLists; 6125 6126 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6127 D = TD->getTemplatedDecl(); 6128 6129 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6130 ParameterLists.push_back(PSD->getTemplateParameters()); 6131 6132 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6133 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6134 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6135 6136 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6137 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6138 ParameterLists.push_back(FTD->getTemplateParameters()); 6139 } 6140 } 6141 6142 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6143 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6144 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6145 6146 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6147 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6148 ParameterLists.push_back(CTD->getTemplateParameters()); 6149 } 6150 } 6151 6152 unsigned Count = 0; 6153 for (TemplateParameterList *Params : ParameterLists) { 6154 if (Params->size() > 0) 6155 // Ignore explicit specializations; they don't contribute to the template 6156 // depth. 6157 ++Count; 6158 for (NamedDecl *Param : *Params) { 6159 if (Param->getDeclName()) { 6160 S->AddDecl(Param); 6161 IdResolver.AddDecl(Param); 6162 } 6163 } 6164 } 6165 6166 return Count; 6167 } 6168 6169 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6170 if (!RecordD) return; 6171 AdjustDeclIfTemplate(RecordD); 6172 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6173 PushDeclContext(S, Record); 6174 } 6175 6176 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6177 if (!RecordD) return; 6178 PopDeclContext(); 6179 } 6180 6181 /// This is used to implement the constant expression evaluation part of the 6182 /// attribute enable_if extension. There is nothing in standard C++ which would 6183 /// require reentering parameters. 6184 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6185 if (!Param) 6186 return; 6187 6188 S->AddDecl(Param); 6189 if (Param->getDeclName()) 6190 IdResolver.AddDecl(Param); 6191 } 6192 6193 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6194 /// parsing a top-level (non-nested) C++ class, and we are now 6195 /// parsing those parts of the given Method declaration that could 6196 /// not be parsed earlier (C++ [class.mem]p2), such as default 6197 /// arguments. This action should enter the scope of the given 6198 /// Method declaration as if we had just parsed the qualified method 6199 /// name. However, it should not bring the parameters into scope; 6200 /// that will be performed by ActOnDelayedCXXMethodParameter. 6201 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6202 } 6203 6204 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6205 /// C++ method declaration. We're (re-)introducing the given 6206 /// function parameter into scope for use in parsing later parts of 6207 /// the method declaration. For example, we could see an 6208 /// ActOnParamDefaultArgument event for this parameter. 6209 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6210 if (!ParamD) 6211 return; 6212 6213 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6214 6215 // If this parameter has an unparsed default argument, clear it out 6216 // to make way for the parsed default argument. 6217 if (Param->hasUnparsedDefaultArg()) 6218 Param->setDefaultArg(nullptr); 6219 6220 S->AddDecl(Param); 6221 if (Param->getDeclName()) 6222 IdResolver.AddDecl(Param); 6223 } 6224 6225 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6226 /// processing the delayed method declaration for Method. The method 6227 /// declaration is now considered finished. There may be a separate 6228 /// ActOnStartOfFunctionDef action later (not necessarily 6229 /// immediately!) for this method, if it was also defined inside the 6230 /// class body. 6231 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6232 if (!MethodD) 6233 return; 6234 6235 AdjustDeclIfTemplate(MethodD); 6236 6237 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6238 6239 // Now that we have our default arguments, check the constructor 6240 // again. It could produce additional diagnostics or affect whether 6241 // the class has implicitly-declared destructors, among other 6242 // things. 6243 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6244 CheckConstructor(Constructor); 6245 6246 // Check the default arguments, which we may have added. 6247 if (!Method->isInvalidDecl()) 6248 CheckCXXDefaultArguments(Method); 6249 } 6250 6251 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6252 /// the well-formedness of the constructor declarator @p D with type @p 6253 /// R. If there are any errors in the declarator, this routine will 6254 /// emit diagnostics and set the invalid bit to true. In any case, the type 6255 /// will be updated to reflect a well-formed type for the constructor and 6256 /// returned. 6257 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6258 StorageClass &SC) { 6259 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6260 6261 // C++ [class.ctor]p3: 6262 // A constructor shall not be virtual (10.3) or static (9.4). A 6263 // constructor can be invoked for a const, volatile or const 6264 // volatile object. A constructor shall not be declared const, 6265 // volatile, or const volatile (9.3.2). 6266 if (isVirtual) { 6267 if (!D.isInvalidType()) 6268 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6269 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6270 << SourceRange(D.getIdentifierLoc()); 6271 D.setInvalidType(); 6272 } 6273 if (SC == SC_Static) { 6274 if (!D.isInvalidType()) 6275 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6276 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6277 << SourceRange(D.getIdentifierLoc()); 6278 D.setInvalidType(); 6279 SC = SC_None; 6280 } 6281 6282 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6283 diagnoseIgnoredQualifiers( 6284 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6285 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6286 D.getDeclSpec().getRestrictSpecLoc(), 6287 D.getDeclSpec().getAtomicSpecLoc()); 6288 D.setInvalidType(); 6289 } 6290 6291 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6292 if (FTI.TypeQuals != 0) { 6293 if (FTI.TypeQuals & Qualifiers::Const) 6294 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6295 << "const" << SourceRange(D.getIdentifierLoc()); 6296 if (FTI.TypeQuals & Qualifiers::Volatile) 6297 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6298 << "volatile" << SourceRange(D.getIdentifierLoc()); 6299 if (FTI.TypeQuals & Qualifiers::Restrict) 6300 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6301 << "restrict" << SourceRange(D.getIdentifierLoc()); 6302 D.setInvalidType(); 6303 } 6304 6305 // C++0x [class.ctor]p4: 6306 // A constructor shall not be declared with a ref-qualifier. 6307 if (FTI.hasRefQualifier()) { 6308 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6309 << FTI.RefQualifierIsLValueRef 6310 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6311 D.setInvalidType(); 6312 } 6313 6314 // Rebuild the function type "R" without any type qualifiers (in 6315 // case any of the errors above fired) and with "void" as the 6316 // return type, since constructors don't have return types. 6317 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6318 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6319 return R; 6320 6321 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6322 EPI.TypeQuals = 0; 6323 EPI.RefQualifier = RQ_None; 6324 6325 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6326 } 6327 6328 /// CheckConstructor - Checks a fully-formed constructor for 6329 /// well-formedness, issuing any diagnostics required. Returns true if 6330 /// the constructor declarator is invalid. 6331 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6332 CXXRecordDecl *ClassDecl 6333 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6334 if (!ClassDecl) 6335 return Constructor->setInvalidDecl(); 6336 6337 // C++ [class.copy]p3: 6338 // A declaration of a constructor for a class X is ill-formed if 6339 // its first parameter is of type (optionally cv-qualified) X and 6340 // either there are no other parameters or else all other 6341 // parameters have default arguments. 6342 if (!Constructor->isInvalidDecl() && 6343 ((Constructor->getNumParams() == 1) || 6344 (Constructor->getNumParams() > 1 && 6345 Constructor->getParamDecl(1)->hasDefaultArg())) && 6346 Constructor->getTemplateSpecializationKind() 6347 != TSK_ImplicitInstantiation) { 6348 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6349 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6350 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6351 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6352 const char *ConstRef 6353 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6354 : " const &"; 6355 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6356 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6357 6358 // FIXME: Rather that making the constructor invalid, we should endeavor 6359 // to fix the type. 6360 Constructor->setInvalidDecl(); 6361 } 6362 } 6363 } 6364 6365 /// CheckDestructor - Checks a fully-formed destructor definition for 6366 /// well-formedness, issuing any diagnostics required. Returns true 6367 /// on error. 6368 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6369 CXXRecordDecl *RD = Destructor->getParent(); 6370 6371 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6372 SourceLocation Loc; 6373 6374 if (!Destructor->isImplicit()) 6375 Loc = Destructor->getLocation(); 6376 else 6377 Loc = RD->getLocation(); 6378 6379 // If we have a virtual destructor, look up the deallocation function 6380 FunctionDecl *OperatorDelete = nullptr; 6381 DeclarationName Name = 6382 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6383 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6384 return true; 6385 // If there's no class-specific operator delete, look up the global 6386 // non-array delete. 6387 if (!OperatorDelete) 6388 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6389 6390 MarkFunctionReferenced(Loc, OperatorDelete); 6391 6392 Destructor->setOperatorDelete(OperatorDelete); 6393 } 6394 6395 return false; 6396 } 6397 6398 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6399 /// the well-formednes of the destructor declarator @p D with type @p 6400 /// R. If there are any errors in the declarator, this routine will 6401 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6402 /// will be updated to reflect a well-formed type for the destructor and 6403 /// returned. 6404 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6405 StorageClass& SC) { 6406 // C++ [class.dtor]p1: 6407 // [...] A typedef-name that names a class is a class-name 6408 // (7.1.3); however, a typedef-name that names a class shall not 6409 // be used as the identifier in the declarator for a destructor 6410 // declaration. 6411 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6412 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6413 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6414 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6415 else if (const TemplateSpecializationType *TST = 6416 DeclaratorType->getAs<TemplateSpecializationType>()) 6417 if (TST->isTypeAlias()) 6418 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6419 << DeclaratorType << 1; 6420 6421 // C++ [class.dtor]p2: 6422 // A destructor is used to destroy objects of its class type. A 6423 // destructor takes no parameters, and no return type can be 6424 // specified for it (not even void). The address of a destructor 6425 // shall not be taken. A destructor shall not be static. A 6426 // destructor can be invoked for a const, volatile or const 6427 // volatile object. A destructor shall not be declared const, 6428 // volatile or const volatile (9.3.2). 6429 if (SC == SC_Static) { 6430 if (!D.isInvalidType()) 6431 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6432 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6433 << SourceRange(D.getIdentifierLoc()) 6434 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6435 6436 SC = SC_None; 6437 } 6438 if (!D.isInvalidType()) { 6439 // Destructors don't have return types, but the parser will 6440 // happily parse something like: 6441 // 6442 // class X { 6443 // float ~X(); 6444 // }; 6445 // 6446 // The return type will be eliminated later. 6447 if (D.getDeclSpec().hasTypeSpecifier()) 6448 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6449 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6450 << SourceRange(D.getIdentifierLoc()); 6451 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6452 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6453 SourceLocation(), 6454 D.getDeclSpec().getConstSpecLoc(), 6455 D.getDeclSpec().getVolatileSpecLoc(), 6456 D.getDeclSpec().getRestrictSpecLoc(), 6457 D.getDeclSpec().getAtomicSpecLoc()); 6458 D.setInvalidType(); 6459 } 6460 } 6461 6462 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6463 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6464 if (FTI.TypeQuals & Qualifiers::Const) 6465 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6466 << "const" << SourceRange(D.getIdentifierLoc()); 6467 if (FTI.TypeQuals & Qualifiers::Volatile) 6468 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6469 << "volatile" << SourceRange(D.getIdentifierLoc()); 6470 if (FTI.TypeQuals & Qualifiers::Restrict) 6471 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6472 << "restrict" << SourceRange(D.getIdentifierLoc()); 6473 D.setInvalidType(); 6474 } 6475 6476 // C++0x [class.dtor]p2: 6477 // A destructor shall not be declared with a ref-qualifier. 6478 if (FTI.hasRefQualifier()) { 6479 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6480 << FTI.RefQualifierIsLValueRef 6481 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6482 D.setInvalidType(); 6483 } 6484 6485 // Make sure we don't have any parameters. 6486 if (FTIHasNonVoidParameters(FTI)) { 6487 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6488 6489 // Delete the parameters. 6490 FTI.freeParams(); 6491 D.setInvalidType(); 6492 } 6493 6494 // Make sure the destructor isn't variadic. 6495 if (FTI.isVariadic) { 6496 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6497 D.setInvalidType(); 6498 } 6499 6500 // Rebuild the function type "R" without any type qualifiers or 6501 // parameters (in case any of the errors above fired) and with 6502 // "void" as the return type, since destructors don't have return 6503 // types. 6504 if (!D.isInvalidType()) 6505 return R; 6506 6507 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6508 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6509 EPI.Variadic = false; 6510 EPI.TypeQuals = 0; 6511 EPI.RefQualifier = RQ_None; 6512 return Context.getFunctionType(Context.VoidTy, None, EPI); 6513 } 6514 6515 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6516 /// well-formednes of the conversion function declarator @p D with 6517 /// type @p R. If there are any errors in the declarator, this routine 6518 /// will emit diagnostics and return true. Otherwise, it will return 6519 /// false. Either way, the type @p R will be updated to reflect a 6520 /// well-formed type for the conversion operator. 6521 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6522 StorageClass& SC) { 6523 // C++ [class.conv.fct]p1: 6524 // Neither parameter types nor return type can be specified. The 6525 // type of a conversion function (8.3.5) is "function taking no 6526 // parameter returning conversion-type-id." 6527 if (SC == SC_Static) { 6528 if (!D.isInvalidType()) 6529 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6530 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6531 << D.getName().getSourceRange(); 6532 D.setInvalidType(); 6533 SC = SC_None; 6534 } 6535 6536 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6537 6538 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6539 // Conversion functions don't have return types, but the parser will 6540 // happily parse something like: 6541 // 6542 // class X { 6543 // float operator bool(); 6544 // }; 6545 // 6546 // The return type will be changed later anyway. 6547 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6548 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6549 << SourceRange(D.getIdentifierLoc()); 6550 D.setInvalidType(); 6551 } 6552 6553 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6554 6555 // Make sure we don't have any parameters. 6556 if (Proto->getNumParams() > 0) { 6557 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6558 6559 // Delete the parameters. 6560 D.getFunctionTypeInfo().freeParams(); 6561 D.setInvalidType(); 6562 } else if (Proto->isVariadic()) { 6563 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6564 D.setInvalidType(); 6565 } 6566 6567 // Diagnose "&operator bool()" and other such nonsense. This 6568 // is actually a gcc extension which we don't support. 6569 if (Proto->getReturnType() != ConvType) { 6570 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6571 << Proto->getReturnType(); 6572 D.setInvalidType(); 6573 ConvType = Proto->getReturnType(); 6574 } 6575 6576 // C++ [class.conv.fct]p4: 6577 // The conversion-type-id shall not represent a function type nor 6578 // an array type. 6579 if (ConvType->isArrayType()) { 6580 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6581 ConvType = Context.getPointerType(ConvType); 6582 D.setInvalidType(); 6583 } else if (ConvType->isFunctionType()) { 6584 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6585 ConvType = Context.getPointerType(ConvType); 6586 D.setInvalidType(); 6587 } 6588 6589 // Rebuild the function type "R" without any parameters (in case any 6590 // of the errors above fired) and with the conversion type as the 6591 // return type. 6592 if (D.isInvalidType()) 6593 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6594 6595 // C++0x explicit conversion operators. 6596 if (D.getDeclSpec().isExplicitSpecified()) 6597 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6598 getLangOpts().CPlusPlus11 ? 6599 diag::warn_cxx98_compat_explicit_conversion_functions : 6600 diag::ext_explicit_conversion_functions) 6601 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6602 } 6603 6604 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6605 /// the declaration of the given C++ conversion function. This routine 6606 /// is responsible for recording the conversion function in the C++ 6607 /// class, if possible. 6608 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6609 assert(Conversion && "Expected to receive a conversion function declaration"); 6610 6611 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6612 6613 // Make sure we aren't redeclaring the conversion function. 6614 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6615 6616 // C++ [class.conv.fct]p1: 6617 // [...] A conversion function is never used to convert a 6618 // (possibly cv-qualified) object to the (possibly cv-qualified) 6619 // same object type (or a reference to it), to a (possibly 6620 // cv-qualified) base class of that type (or a reference to it), 6621 // or to (possibly cv-qualified) void. 6622 // FIXME: Suppress this warning if the conversion function ends up being a 6623 // virtual function that overrides a virtual function in a base class. 6624 QualType ClassType 6625 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6626 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6627 ConvType = ConvTypeRef->getPointeeType(); 6628 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6629 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6630 /* Suppress diagnostics for instantiations. */; 6631 else if (ConvType->isRecordType()) { 6632 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6633 if (ConvType == ClassType) 6634 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6635 << ClassType; 6636 else if (IsDerivedFrom(ClassType, ConvType)) 6637 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6638 << ClassType << ConvType; 6639 } else if (ConvType->isVoidType()) { 6640 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6641 << ClassType << ConvType; 6642 } 6643 6644 if (FunctionTemplateDecl *ConversionTemplate 6645 = Conversion->getDescribedFunctionTemplate()) 6646 return ConversionTemplate; 6647 6648 return Conversion; 6649 } 6650 6651 //===----------------------------------------------------------------------===// 6652 // Namespace Handling 6653 //===----------------------------------------------------------------------===// 6654 6655 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6656 /// reopened. 6657 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6658 SourceLocation Loc, 6659 IdentifierInfo *II, bool *IsInline, 6660 NamespaceDecl *PrevNS) { 6661 assert(*IsInline != PrevNS->isInline()); 6662 6663 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6664 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6665 // inline namespaces, with the intention of bringing names into namespace std. 6666 // 6667 // We support this just well enough to get that case working; this is not 6668 // sufficient to support reopening namespaces as inline in general. 6669 if (*IsInline && II && II->getName().startswith("__atomic") && 6670 S.getSourceManager().isInSystemHeader(Loc)) { 6671 // Mark all prior declarations of the namespace as inline. 6672 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6673 NS = NS->getPreviousDecl()) 6674 NS->setInline(*IsInline); 6675 // Patch up the lookup table for the containing namespace. This isn't really 6676 // correct, but it's good enough for this particular case. 6677 for (auto *I : PrevNS->decls()) 6678 if (auto *ND = dyn_cast<NamedDecl>(I)) 6679 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6680 return; 6681 } 6682 6683 if (PrevNS->isInline()) 6684 // The user probably just forgot the 'inline', so suggest that it 6685 // be added back. 6686 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6687 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6688 else 6689 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 6690 6691 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6692 *IsInline = PrevNS->isInline(); 6693 } 6694 6695 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6696 /// definition. 6697 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6698 SourceLocation InlineLoc, 6699 SourceLocation NamespaceLoc, 6700 SourceLocation IdentLoc, 6701 IdentifierInfo *II, 6702 SourceLocation LBrace, 6703 AttributeList *AttrList) { 6704 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6705 // For anonymous namespace, take the location of the left brace. 6706 SourceLocation Loc = II ? IdentLoc : LBrace; 6707 bool IsInline = InlineLoc.isValid(); 6708 bool IsInvalid = false; 6709 bool IsStd = false; 6710 bool AddToKnown = false; 6711 Scope *DeclRegionScope = NamespcScope->getParent(); 6712 6713 NamespaceDecl *PrevNS = nullptr; 6714 if (II) { 6715 // C++ [namespace.def]p2: 6716 // The identifier in an original-namespace-definition shall not 6717 // have been previously defined in the declarative region in 6718 // which the original-namespace-definition appears. The 6719 // identifier in an original-namespace-definition is the name of 6720 // the namespace. Subsequently in that declarative region, it is 6721 // treated as an original-namespace-name. 6722 // 6723 // Since namespace names are unique in their scope, and we don't 6724 // look through using directives, just look for any ordinary names. 6725 6726 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6727 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6728 Decl::IDNS_Namespace; 6729 NamedDecl *PrevDecl = nullptr; 6730 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6731 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6732 ++I) { 6733 if ((*I)->getIdentifierNamespace() & IDNS) { 6734 PrevDecl = *I; 6735 break; 6736 } 6737 } 6738 6739 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6740 6741 if (PrevNS) { 6742 // This is an extended namespace definition. 6743 if (IsInline != PrevNS->isInline()) 6744 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6745 &IsInline, PrevNS); 6746 } else if (PrevDecl) { 6747 // This is an invalid name redefinition. 6748 Diag(Loc, diag::err_redefinition_different_kind) 6749 << II; 6750 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6751 IsInvalid = true; 6752 // Continue on to push Namespc as current DeclContext and return it. 6753 } else if (II->isStr("std") && 6754 CurContext->getRedeclContext()->isTranslationUnit()) { 6755 // This is the first "real" definition of the namespace "std", so update 6756 // our cache of the "std" namespace to point at this definition. 6757 PrevNS = getStdNamespace(); 6758 IsStd = true; 6759 AddToKnown = !IsInline; 6760 } else { 6761 // We've seen this namespace for the first time. 6762 AddToKnown = !IsInline; 6763 } 6764 } else { 6765 // Anonymous namespaces. 6766 6767 // Determine whether the parent already has an anonymous namespace. 6768 DeclContext *Parent = CurContext->getRedeclContext(); 6769 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6770 PrevNS = TU->getAnonymousNamespace(); 6771 } else { 6772 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6773 PrevNS = ND->getAnonymousNamespace(); 6774 } 6775 6776 if (PrevNS && IsInline != PrevNS->isInline()) 6777 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6778 &IsInline, PrevNS); 6779 } 6780 6781 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6782 StartLoc, Loc, II, PrevNS); 6783 if (IsInvalid) 6784 Namespc->setInvalidDecl(); 6785 6786 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6787 6788 // FIXME: Should we be merging attributes? 6789 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6790 PushNamespaceVisibilityAttr(Attr, Loc); 6791 6792 if (IsStd) 6793 StdNamespace = Namespc; 6794 if (AddToKnown) 6795 KnownNamespaces[Namespc] = false; 6796 6797 if (II) { 6798 PushOnScopeChains(Namespc, DeclRegionScope); 6799 } else { 6800 // Link the anonymous namespace into its parent. 6801 DeclContext *Parent = CurContext->getRedeclContext(); 6802 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6803 TU->setAnonymousNamespace(Namespc); 6804 } else { 6805 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6806 } 6807 6808 CurContext->addDecl(Namespc); 6809 6810 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6811 // behaves as if it were replaced by 6812 // namespace unique { /* empty body */ } 6813 // using namespace unique; 6814 // namespace unique { namespace-body } 6815 // where all occurrences of 'unique' in a translation unit are 6816 // replaced by the same identifier and this identifier differs 6817 // from all other identifiers in the entire program. 6818 6819 // We just create the namespace with an empty name and then add an 6820 // implicit using declaration, just like the standard suggests. 6821 // 6822 // CodeGen enforces the "universally unique" aspect by giving all 6823 // declarations semantically contained within an anonymous 6824 // namespace internal linkage. 6825 6826 if (!PrevNS) { 6827 UsingDirectiveDecl* UD 6828 = UsingDirectiveDecl::Create(Context, Parent, 6829 /* 'using' */ LBrace, 6830 /* 'namespace' */ SourceLocation(), 6831 /* qualifier */ NestedNameSpecifierLoc(), 6832 /* identifier */ SourceLocation(), 6833 Namespc, 6834 /* Ancestor */ Parent); 6835 UD->setImplicit(); 6836 Parent->addDecl(UD); 6837 } 6838 } 6839 6840 ActOnDocumentableDecl(Namespc); 6841 6842 // Although we could have an invalid decl (i.e. the namespace name is a 6843 // redefinition), push it as current DeclContext and try to continue parsing. 6844 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6845 // for the namespace has the declarations that showed up in that particular 6846 // namespace definition. 6847 PushDeclContext(NamespcScope, Namespc); 6848 return Namespc; 6849 } 6850 6851 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6852 /// is a namespace alias, returns the namespace it points to. 6853 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6854 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6855 return AD->getNamespace(); 6856 return dyn_cast_or_null<NamespaceDecl>(D); 6857 } 6858 6859 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6860 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6861 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6862 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6863 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6864 Namespc->setRBraceLoc(RBrace); 6865 PopDeclContext(); 6866 if (Namespc->hasAttr<VisibilityAttr>()) 6867 PopPragmaVisibility(true, RBrace); 6868 } 6869 6870 CXXRecordDecl *Sema::getStdBadAlloc() const { 6871 return cast_or_null<CXXRecordDecl>( 6872 StdBadAlloc.get(Context.getExternalSource())); 6873 } 6874 6875 NamespaceDecl *Sema::getStdNamespace() const { 6876 return cast_or_null<NamespaceDecl>( 6877 StdNamespace.get(Context.getExternalSource())); 6878 } 6879 6880 /// \brief Retrieve the special "std" namespace, which may require us to 6881 /// implicitly define the namespace. 6882 NamespaceDecl *Sema::getOrCreateStdNamespace() { 6883 if (!StdNamespace) { 6884 // The "std" namespace has not yet been defined, so build one implicitly. 6885 StdNamespace = NamespaceDecl::Create(Context, 6886 Context.getTranslationUnitDecl(), 6887 /*Inline=*/false, 6888 SourceLocation(), SourceLocation(), 6889 &PP.getIdentifierTable().get("std"), 6890 /*PrevDecl=*/nullptr); 6891 getStdNamespace()->setImplicit(true); 6892 } 6893 6894 return getStdNamespace(); 6895 } 6896 6897 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6898 assert(getLangOpts().CPlusPlus && 6899 "Looking for std::initializer_list outside of C++."); 6900 6901 // We're looking for implicit instantiations of 6902 // template <typename E> class std::initializer_list. 6903 6904 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6905 return false; 6906 6907 ClassTemplateDecl *Template = nullptr; 6908 const TemplateArgument *Arguments = nullptr; 6909 6910 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6911 6912 ClassTemplateSpecializationDecl *Specialization = 6913 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6914 if (!Specialization) 6915 return false; 6916 6917 Template = Specialization->getSpecializedTemplate(); 6918 Arguments = Specialization->getTemplateArgs().data(); 6919 } else if (const TemplateSpecializationType *TST = 6920 Ty->getAs<TemplateSpecializationType>()) { 6921 Template = dyn_cast_or_null<ClassTemplateDecl>( 6922 TST->getTemplateName().getAsTemplateDecl()); 6923 Arguments = TST->getArgs(); 6924 } 6925 if (!Template) 6926 return false; 6927 6928 if (!StdInitializerList) { 6929 // Haven't recognized std::initializer_list yet, maybe this is it. 6930 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6931 if (TemplateClass->getIdentifier() != 6932 &PP.getIdentifierTable().get("initializer_list") || 6933 !getStdNamespace()->InEnclosingNamespaceSetOf( 6934 TemplateClass->getDeclContext())) 6935 return false; 6936 // This is a template called std::initializer_list, but is it the right 6937 // template? 6938 TemplateParameterList *Params = Template->getTemplateParameters(); 6939 if (Params->getMinRequiredArguments() != 1) 6940 return false; 6941 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6942 return false; 6943 6944 // It's the right template. 6945 StdInitializerList = Template; 6946 } 6947 6948 if (Template != StdInitializerList) 6949 return false; 6950 6951 // This is an instance of std::initializer_list. Find the argument type. 6952 if (Element) 6953 *Element = Arguments[0].getAsType(); 6954 return true; 6955 } 6956 6957 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6958 NamespaceDecl *Std = S.getStdNamespace(); 6959 if (!Std) { 6960 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6961 return nullptr; 6962 } 6963 6964 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6965 Loc, Sema::LookupOrdinaryName); 6966 if (!S.LookupQualifiedName(Result, Std)) { 6967 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6968 return nullptr; 6969 } 6970 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6971 if (!Template) { 6972 Result.suppressDiagnostics(); 6973 // We found something weird. Complain about the first thing we found. 6974 NamedDecl *Found = *Result.begin(); 6975 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6976 return nullptr; 6977 } 6978 6979 // We found some template called std::initializer_list. Now verify that it's 6980 // correct. 6981 TemplateParameterList *Params = Template->getTemplateParameters(); 6982 if (Params->getMinRequiredArguments() != 1 || 6983 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6984 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6985 return nullptr; 6986 } 6987 6988 return Template; 6989 } 6990 6991 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6992 if (!StdInitializerList) { 6993 StdInitializerList = LookupStdInitializerList(*this, Loc); 6994 if (!StdInitializerList) 6995 return QualType(); 6996 } 6997 6998 TemplateArgumentListInfo Args(Loc, Loc); 6999 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7000 Context.getTrivialTypeSourceInfo(Element, 7001 Loc))); 7002 return Context.getCanonicalType( 7003 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7004 } 7005 7006 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7007 // C++ [dcl.init.list]p2: 7008 // A constructor is an initializer-list constructor if its first parameter 7009 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7010 // std::initializer_list<E> for some type E, and either there are no other 7011 // parameters or else all other parameters have default arguments. 7012 if (Ctor->getNumParams() < 1 || 7013 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7014 return false; 7015 7016 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7017 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7018 ArgType = RT->getPointeeType().getUnqualifiedType(); 7019 7020 return isStdInitializerList(ArgType, nullptr); 7021 } 7022 7023 /// \brief Determine whether a using statement is in a context where it will be 7024 /// apply in all contexts. 7025 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7026 switch (CurContext->getDeclKind()) { 7027 case Decl::TranslationUnit: 7028 return true; 7029 case Decl::LinkageSpec: 7030 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7031 default: 7032 return false; 7033 } 7034 } 7035 7036 namespace { 7037 7038 // Callback to only accept typo corrections that are namespaces. 7039 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7040 public: 7041 bool ValidateCandidate(const TypoCorrection &candidate) override { 7042 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7043 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7044 return false; 7045 } 7046 }; 7047 7048 } 7049 7050 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7051 CXXScopeSpec &SS, 7052 SourceLocation IdentLoc, 7053 IdentifierInfo *Ident) { 7054 NamespaceValidatorCCC Validator; 7055 R.clear(); 7056 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 7057 R.getLookupKind(), Sc, &SS, 7058 Validator, 7059 Sema::CTK_ErrorRecovery)) { 7060 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7061 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7062 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7063 Ident->getName().equals(CorrectedStr); 7064 S.diagnoseTypo(Corrected, 7065 S.PDiag(diag::err_using_directive_member_suggest) 7066 << Ident << DC << DroppedSpecifier << SS.getRange(), 7067 S.PDiag(diag::note_namespace_defined_here)); 7068 } else { 7069 S.diagnoseTypo(Corrected, 7070 S.PDiag(diag::err_using_directive_suggest) << Ident, 7071 S.PDiag(diag::note_namespace_defined_here)); 7072 } 7073 R.addDecl(Corrected.getCorrectionDecl()); 7074 return true; 7075 } 7076 return false; 7077 } 7078 7079 Decl *Sema::ActOnUsingDirective(Scope *S, 7080 SourceLocation UsingLoc, 7081 SourceLocation NamespcLoc, 7082 CXXScopeSpec &SS, 7083 SourceLocation IdentLoc, 7084 IdentifierInfo *NamespcName, 7085 AttributeList *AttrList) { 7086 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7087 assert(NamespcName && "Invalid NamespcName."); 7088 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7089 7090 // This can only happen along a recovery path. 7091 while (S->getFlags() & Scope::TemplateParamScope) 7092 S = S->getParent(); 7093 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7094 7095 UsingDirectiveDecl *UDir = nullptr; 7096 NestedNameSpecifier *Qualifier = nullptr; 7097 if (SS.isSet()) 7098 Qualifier = SS.getScopeRep(); 7099 7100 // Lookup namespace name. 7101 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7102 LookupParsedName(R, S, &SS); 7103 if (R.isAmbiguous()) 7104 return nullptr; 7105 7106 if (R.empty()) { 7107 R.clear(); 7108 // Allow "using namespace std;" or "using namespace ::std;" even if 7109 // "std" hasn't been defined yet, for GCC compatibility. 7110 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7111 NamespcName->isStr("std")) { 7112 Diag(IdentLoc, diag::ext_using_undefined_std); 7113 R.addDecl(getOrCreateStdNamespace()); 7114 R.resolveKind(); 7115 } 7116 // Otherwise, attempt typo correction. 7117 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7118 } 7119 7120 if (!R.empty()) { 7121 NamedDecl *Named = R.getFoundDecl(); 7122 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7123 && "expected namespace decl"); 7124 // C++ [namespace.udir]p1: 7125 // A using-directive specifies that the names in the nominated 7126 // namespace can be used in the scope in which the 7127 // using-directive appears after the using-directive. During 7128 // unqualified name lookup (3.4.1), the names appear as if they 7129 // were declared in the nearest enclosing namespace which 7130 // contains both the using-directive and the nominated 7131 // namespace. [Note: in this context, "contains" means "contains 7132 // directly or indirectly". ] 7133 7134 // Find enclosing context containing both using-directive and 7135 // nominated namespace. 7136 NamespaceDecl *NS = getNamespaceDecl(Named); 7137 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7138 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7139 CommonAncestor = CommonAncestor->getParent(); 7140 7141 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7142 SS.getWithLocInContext(Context), 7143 IdentLoc, Named, CommonAncestor); 7144 7145 if (IsUsingDirectiveInToplevelContext(CurContext) && 7146 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7147 Diag(IdentLoc, diag::warn_using_directive_in_header); 7148 } 7149 7150 PushUsingDirective(S, UDir); 7151 } else { 7152 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7153 } 7154 7155 if (UDir) 7156 ProcessDeclAttributeList(S, UDir, AttrList); 7157 7158 return UDir; 7159 } 7160 7161 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7162 // If the scope has an associated entity and the using directive is at 7163 // namespace or translation unit scope, add the UsingDirectiveDecl into 7164 // its lookup structure so qualified name lookup can find it. 7165 DeclContext *Ctx = S->getEntity(); 7166 if (Ctx && !Ctx->isFunctionOrMethod()) 7167 Ctx->addDecl(UDir); 7168 else 7169 // Otherwise, it is at block scope. The using-directives will affect lookup 7170 // only to the end of the scope. 7171 S->PushUsingDirective(UDir); 7172 } 7173 7174 7175 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7176 AccessSpecifier AS, 7177 bool HasUsingKeyword, 7178 SourceLocation UsingLoc, 7179 CXXScopeSpec &SS, 7180 UnqualifiedId &Name, 7181 AttributeList *AttrList, 7182 bool HasTypenameKeyword, 7183 SourceLocation TypenameLoc) { 7184 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7185 7186 switch (Name.getKind()) { 7187 case UnqualifiedId::IK_ImplicitSelfParam: 7188 case UnqualifiedId::IK_Identifier: 7189 case UnqualifiedId::IK_OperatorFunctionId: 7190 case UnqualifiedId::IK_LiteralOperatorId: 7191 case UnqualifiedId::IK_ConversionFunctionId: 7192 break; 7193 7194 case UnqualifiedId::IK_ConstructorName: 7195 case UnqualifiedId::IK_ConstructorTemplateId: 7196 // C++11 inheriting constructors. 7197 Diag(Name.getLocStart(), 7198 getLangOpts().CPlusPlus11 ? 7199 diag::warn_cxx98_compat_using_decl_constructor : 7200 diag::err_using_decl_constructor) 7201 << SS.getRange(); 7202 7203 if (getLangOpts().CPlusPlus11) break; 7204 7205 return nullptr; 7206 7207 case UnqualifiedId::IK_DestructorName: 7208 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7209 << SS.getRange(); 7210 return nullptr; 7211 7212 case UnqualifiedId::IK_TemplateId: 7213 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7214 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7215 return nullptr; 7216 } 7217 7218 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7219 DeclarationName TargetName = TargetNameInfo.getName(); 7220 if (!TargetName) 7221 return nullptr; 7222 7223 // Warn about access declarations. 7224 if (!HasUsingKeyword) { 7225 Diag(Name.getLocStart(), 7226 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7227 : diag::warn_access_decl_deprecated) 7228 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7229 } 7230 7231 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7232 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7233 return nullptr; 7234 7235 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7236 TargetNameInfo, AttrList, 7237 /* IsInstantiation */ false, 7238 HasTypenameKeyword, TypenameLoc); 7239 if (UD) 7240 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7241 7242 return UD; 7243 } 7244 7245 /// \brief Determine whether a using declaration considers the given 7246 /// declarations as "equivalent", e.g., if they are redeclarations of 7247 /// the same entity or are both typedefs of the same type. 7248 static bool 7249 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7250 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7251 return true; 7252 7253 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7254 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7255 return Context.hasSameType(TD1->getUnderlyingType(), 7256 TD2->getUnderlyingType()); 7257 7258 return false; 7259 } 7260 7261 7262 /// Determines whether to create a using shadow decl for a particular 7263 /// decl, given the set of decls existing prior to this using lookup. 7264 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7265 const LookupResult &Previous, 7266 UsingShadowDecl *&PrevShadow) { 7267 // Diagnose finding a decl which is not from a base class of the 7268 // current class. We do this now because there are cases where this 7269 // function will silently decide not to build a shadow decl, which 7270 // will pre-empt further diagnostics. 7271 // 7272 // We don't need to do this in C++0x because we do the check once on 7273 // the qualifier. 7274 // 7275 // FIXME: diagnose the following if we care enough: 7276 // struct A { int foo; }; 7277 // struct B : A { using A::foo; }; 7278 // template <class T> struct C : A {}; 7279 // template <class T> struct D : C<T> { using B::foo; } // <--- 7280 // This is invalid (during instantiation) in C++03 because B::foo 7281 // resolves to the using decl in B, which is not a base class of D<T>. 7282 // We can't diagnose it immediately because C<T> is an unknown 7283 // specialization. The UsingShadowDecl in D<T> then points directly 7284 // to A::foo, which will look well-formed when we instantiate. 7285 // The right solution is to not collapse the shadow-decl chain. 7286 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7287 DeclContext *OrigDC = Orig->getDeclContext(); 7288 7289 // Handle enums and anonymous structs. 7290 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7291 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7292 while (OrigRec->isAnonymousStructOrUnion()) 7293 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7294 7295 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7296 if (OrigDC == CurContext) { 7297 Diag(Using->getLocation(), 7298 diag::err_using_decl_nested_name_specifier_is_current_class) 7299 << Using->getQualifierLoc().getSourceRange(); 7300 Diag(Orig->getLocation(), diag::note_using_decl_target); 7301 return true; 7302 } 7303 7304 Diag(Using->getQualifierLoc().getBeginLoc(), 7305 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7306 << Using->getQualifier() 7307 << cast<CXXRecordDecl>(CurContext) 7308 << Using->getQualifierLoc().getSourceRange(); 7309 Diag(Orig->getLocation(), diag::note_using_decl_target); 7310 return true; 7311 } 7312 } 7313 7314 if (Previous.empty()) return false; 7315 7316 NamedDecl *Target = Orig; 7317 if (isa<UsingShadowDecl>(Target)) 7318 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7319 7320 // If the target happens to be one of the previous declarations, we 7321 // don't have a conflict. 7322 // 7323 // FIXME: but we might be increasing its access, in which case we 7324 // should redeclare it. 7325 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7326 bool FoundEquivalentDecl = false; 7327 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7328 I != E; ++I) { 7329 NamedDecl *D = (*I)->getUnderlyingDecl(); 7330 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7331 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7332 PrevShadow = Shadow; 7333 FoundEquivalentDecl = true; 7334 } 7335 7336 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7337 } 7338 7339 if (FoundEquivalentDecl) 7340 return false; 7341 7342 if (FunctionDecl *FD = Target->getAsFunction()) { 7343 NamedDecl *OldDecl = nullptr; 7344 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7345 /*IsForUsingDecl*/ true)) { 7346 case Ovl_Overload: 7347 return false; 7348 7349 case Ovl_NonFunction: 7350 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7351 break; 7352 7353 // We found a decl with the exact signature. 7354 case Ovl_Match: 7355 // If we're in a record, we want to hide the target, so we 7356 // return true (without a diagnostic) to tell the caller not to 7357 // build a shadow decl. 7358 if (CurContext->isRecord()) 7359 return true; 7360 7361 // If we're not in a record, this is an error. 7362 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7363 break; 7364 } 7365 7366 Diag(Target->getLocation(), diag::note_using_decl_target); 7367 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7368 return true; 7369 } 7370 7371 // Target is not a function. 7372 7373 if (isa<TagDecl>(Target)) { 7374 // No conflict between a tag and a non-tag. 7375 if (!Tag) return false; 7376 7377 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7378 Diag(Target->getLocation(), diag::note_using_decl_target); 7379 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7380 return true; 7381 } 7382 7383 // No conflict between a tag and a non-tag. 7384 if (!NonTag) return false; 7385 7386 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7387 Diag(Target->getLocation(), diag::note_using_decl_target); 7388 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7389 return true; 7390 } 7391 7392 /// Builds a shadow declaration corresponding to a 'using' declaration. 7393 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7394 UsingDecl *UD, 7395 NamedDecl *Orig, 7396 UsingShadowDecl *PrevDecl) { 7397 7398 // If we resolved to another shadow declaration, just coalesce them. 7399 NamedDecl *Target = Orig; 7400 if (isa<UsingShadowDecl>(Target)) { 7401 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7402 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7403 } 7404 7405 UsingShadowDecl *Shadow 7406 = UsingShadowDecl::Create(Context, CurContext, 7407 UD->getLocation(), UD, Target); 7408 UD->addShadowDecl(Shadow); 7409 7410 Shadow->setAccess(UD->getAccess()); 7411 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7412 Shadow->setInvalidDecl(); 7413 7414 Shadow->setPreviousDecl(PrevDecl); 7415 7416 if (S) 7417 PushOnScopeChains(Shadow, S); 7418 else 7419 CurContext->addDecl(Shadow); 7420 7421 7422 return Shadow; 7423 } 7424 7425 /// Hides a using shadow declaration. This is required by the current 7426 /// using-decl implementation when a resolvable using declaration in a 7427 /// class is followed by a declaration which would hide or override 7428 /// one or more of the using decl's targets; for example: 7429 /// 7430 /// struct Base { void foo(int); }; 7431 /// struct Derived : Base { 7432 /// using Base::foo; 7433 /// void foo(int); 7434 /// }; 7435 /// 7436 /// The governing language is C++03 [namespace.udecl]p12: 7437 /// 7438 /// When a using-declaration brings names from a base class into a 7439 /// derived class scope, member functions in the derived class 7440 /// override and/or hide member functions with the same name and 7441 /// parameter types in a base class (rather than conflicting). 7442 /// 7443 /// There are two ways to implement this: 7444 /// (1) optimistically create shadow decls when they're not hidden 7445 /// by existing declarations, or 7446 /// (2) don't create any shadow decls (or at least don't make them 7447 /// visible) until we've fully parsed/instantiated the class. 7448 /// The problem with (1) is that we might have to retroactively remove 7449 /// a shadow decl, which requires several O(n) operations because the 7450 /// decl structures are (very reasonably) not designed for removal. 7451 /// (2) avoids this but is very fiddly and phase-dependent. 7452 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7453 if (Shadow->getDeclName().getNameKind() == 7454 DeclarationName::CXXConversionFunctionName) 7455 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7456 7457 // Remove it from the DeclContext... 7458 Shadow->getDeclContext()->removeDecl(Shadow); 7459 7460 // ...and the scope, if applicable... 7461 if (S) { 7462 S->RemoveDecl(Shadow); 7463 IdResolver.RemoveDecl(Shadow); 7464 } 7465 7466 // ...and the using decl. 7467 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7468 7469 // TODO: complain somehow if Shadow was used. It shouldn't 7470 // be possible for this to happen, because...? 7471 } 7472 7473 /// Find the base specifier for a base class with the given type. 7474 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7475 QualType DesiredBase, 7476 bool &AnyDependentBases) { 7477 // Check whether the named type is a direct base class. 7478 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7479 for (auto &Base : Derived->bases()) { 7480 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7481 if (CanonicalDesiredBase == BaseType) 7482 return &Base; 7483 if (BaseType->isDependentType()) 7484 AnyDependentBases = true; 7485 } 7486 return nullptr; 7487 } 7488 7489 namespace { 7490 class UsingValidatorCCC : public CorrectionCandidateCallback { 7491 public: 7492 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7493 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7494 : HasTypenameKeyword(HasTypenameKeyword), 7495 IsInstantiation(IsInstantiation), OldNNS(NNS), 7496 RequireMemberOf(RequireMemberOf) {} 7497 7498 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7499 NamedDecl *ND = Candidate.getCorrectionDecl(); 7500 7501 // Keywords are not valid here. 7502 if (!ND || isa<NamespaceDecl>(ND)) 7503 return false; 7504 7505 // Completely unqualified names are invalid for a 'using' declaration. 7506 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7507 return false; 7508 7509 if (RequireMemberOf) { 7510 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7511 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7512 // No-one ever wants a using-declaration to name an injected-class-name 7513 // of a base class, unless they're declaring an inheriting constructor. 7514 ASTContext &Ctx = ND->getASTContext(); 7515 if (!Ctx.getLangOpts().CPlusPlus11) 7516 return false; 7517 QualType FoundType = Ctx.getRecordType(FoundRecord); 7518 7519 // Check that the injected-class-name is named as a member of its own 7520 // type; we don't want to suggest 'using Derived::Base;', since that 7521 // means something else. 7522 NestedNameSpecifier *Specifier = 7523 Candidate.WillReplaceSpecifier() 7524 ? Candidate.getCorrectionSpecifier() 7525 : OldNNS; 7526 if (!Specifier->getAsType() || 7527 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7528 return false; 7529 7530 // Check that this inheriting constructor declaration actually names a 7531 // direct base class of the current class. 7532 bool AnyDependentBases = false; 7533 if (!findDirectBaseWithType(RequireMemberOf, 7534 Ctx.getRecordType(FoundRecord), 7535 AnyDependentBases) && 7536 !AnyDependentBases) 7537 return false; 7538 } else { 7539 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7540 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7541 return false; 7542 7543 // FIXME: Check that the base class member is accessible? 7544 } 7545 } 7546 7547 if (isa<TypeDecl>(ND)) 7548 return HasTypenameKeyword || !IsInstantiation; 7549 7550 return !HasTypenameKeyword; 7551 } 7552 7553 private: 7554 bool HasTypenameKeyword; 7555 bool IsInstantiation; 7556 NestedNameSpecifier *OldNNS; 7557 CXXRecordDecl *RequireMemberOf; 7558 }; 7559 } // end anonymous namespace 7560 7561 /// Builds a using declaration. 7562 /// 7563 /// \param IsInstantiation - Whether this call arises from an 7564 /// instantiation of an unresolved using declaration. We treat 7565 /// the lookup differently for these declarations. 7566 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7567 SourceLocation UsingLoc, 7568 CXXScopeSpec &SS, 7569 DeclarationNameInfo NameInfo, 7570 AttributeList *AttrList, 7571 bool IsInstantiation, 7572 bool HasTypenameKeyword, 7573 SourceLocation TypenameLoc) { 7574 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7575 SourceLocation IdentLoc = NameInfo.getLoc(); 7576 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7577 7578 // FIXME: We ignore attributes for now. 7579 7580 if (SS.isEmpty()) { 7581 Diag(IdentLoc, diag::err_using_requires_qualname); 7582 return nullptr; 7583 } 7584 7585 // Do the redeclaration lookup in the current scope. 7586 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7587 ForRedeclaration); 7588 Previous.setHideTags(false); 7589 if (S) { 7590 LookupName(Previous, S); 7591 7592 // It is really dumb that we have to do this. 7593 LookupResult::Filter F = Previous.makeFilter(); 7594 while (F.hasNext()) { 7595 NamedDecl *D = F.next(); 7596 if (!isDeclInScope(D, CurContext, S)) 7597 F.erase(); 7598 // If we found a local extern declaration that's not ordinarily visible, 7599 // and this declaration is being added to a non-block scope, ignore it. 7600 // We're only checking for scope conflicts here, not also for violations 7601 // of the linkage rules. 7602 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7603 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7604 F.erase(); 7605 } 7606 F.done(); 7607 } else { 7608 assert(IsInstantiation && "no scope in non-instantiation"); 7609 assert(CurContext->isRecord() && "scope not record in instantiation"); 7610 LookupQualifiedName(Previous, CurContext); 7611 } 7612 7613 // Check for invalid redeclarations. 7614 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7615 SS, IdentLoc, Previous)) 7616 return nullptr; 7617 7618 // Check for bad qualifiers. 7619 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7620 return nullptr; 7621 7622 DeclContext *LookupContext = computeDeclContext(SS); 7623 NamedDecl *D; 7624 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7625 if (!LookupContext) { 7626 if (HasTypenameKeyword) { 7627 // FIXME: not all declaration name kinds are legal here 7628 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7629 UsingLoc, TypenameLoc, 7630 QualifierLoc, 7631 IdentLoc, NameInfo.getName()); 7632 } else { 7633 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7634 QualifierLoc, NameInfo); 7635 } 7636 D->setAccess(AS); 7637 CurContext->addDecl(D); 7638 return D; 7639 } 7640 7641 auto Build = [&](bool Invalid) { 7642 UsingDecl *UD = 7643 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 7644 HasTypenameKeyword); 7645 UD->setAccess(AS); 7646 CurContext->addDecl(UD); 7647 UD->setInvalidDecl(Invalid); 7648 return UD; 7649 }; 7650 auto BuildInvalid = [&]{ return Build(true); }; 7651 auto BuildValid = [&]{ return Build(false); }; 7652 7653 if (RequireCompleteDeclContext(SS, LookupContext)) 7654 return BuildInvalid(); 7655 7656 // The normal rules do not apply to inheriting constructor declarations. 7657 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7658 UsingDecl *UD = BuildValid(); 7659 CheckInheritingConstructorUsingDecl(UD); 7660 return UD; 7661 } 7662 7663 // Otherwise, look up the target name. 7664 7665 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7666 7667 // Unlike most lookups, we don't always want to hide tag 7668 // declarations: tag names are visible through the using declaration 7669 // even if hidden by ordinary names, *except* in a dependent context 7670 // where it's important for the sanity of two-phase lookup. 7671 if (!IsInstantiation) 7672 R.setHideTags(false); 7673 7674 // For the purposes of this lookup, we have a base object type 7675 // equal to that of the current context. 7676 if (CurContext->isRecord()) { 7677 R.setBaseObjectType( 7678 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7679 } 7680 7681 LookupQualifiedName(R, LookupContext); 7682 7683 // Try to correct typos if possible. 7684 if (R.empty()) { 7685 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 7686 dyn_cast<CXXRecordDecl>(CurContext)); 7687 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7688 R.getLookupKind(), S, &SS, CCC, 7689 CTK_ErrorRecovery)){ 7690 // We reject any correction for which ND would be NULL. 7691 NamedDecl *ND = Corrected.getCorrectionDecl(); 7692 7693 // We reject candidates where DroppedSpecifier == true, hence the 7694 // literal '0' below. 7695 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7696 << NameInfo.getName() << LookupContext << 0 7697 << SS.getRange()); 7698 7699 // If we corrected to an inheriting constructor, handle it as one. 7700 auto *RD = dyn_cast<CXXRecordDecl>(ND); 7701 if (RD && RD->isInjectedClassName()) { 7702 // Fix up the information we'll use to build the using declaration. 7703 if (Corrected.WillReplaceSpecifier()) { 7704 NestedNameSpecifierLocBuilder Builder; 7705 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 7706 QualifierLoc.getSourceRange()); 7707 QualifierLoc = Builder.getWithLocInContext(Context); 7708 } 7709 7710 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 7711 Context.getCanonicalType(Context.getRecordType(RD)))); 7712 NameInfo.setNamedTypeInfo(nullptr); 7713 7714 // Build it and process it as an inheriting constructor. 7715 UsingDecl *UD = BuildValid(); 7716 CheckInheritingConstructorUsingDecl(UD); 7717 return UD; 7718 } 7719 7720 // FIXME: Pick up all the declarations if we found an overloaded function. 7721 R.setLookupName(Corrected.getCorrection()); 7722 R.addDecl(ND); 7723 } else { 7724 Diag(IdentLoc, diag::err_no_member) 7725 << NameInfo.getName() << LookupContext << SS.getRange(); 7726 return BuildInvalid(); 7727 } 7728 } 7729 7730 if (R.isAmbiguous()) 7731 return BuildInvalid(); 7732 7733 if (HasTypenameKeyword) { 7734 // If we asked for a typename and got a non-type decl, error out. 7735 if (!R.getAsSingle<TypeDecl>()) { 7736 Diag(IdentLoc, diag::err_using_typename_non_type); 7737 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7738 Diag((*I)->getUnderlyingDecl()->getLocation(), 7739 diag::note_using_decl_target); 7740 return BuildInvalid(); 7741 } 7742 } else { 7743 // If we asked for a non-typename and we got a type, error out, 7744 // but only if this is an instantiation of an unresolved using 7745 // decl. Otherwise just silently find the type name. 7746 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7747 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7748 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7749 return BuildInvalid(); 7750 } 7751 } 7752 7753 // C++0x N2914 [namespace.udecl]p6: 7754 // A using-declaration shall not name a namespace. 7755 if (R.getAsSingle<NamespaceDecl>()) { 7756 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7757 << SS.getRange(); 7758 return BuildInvalid(); 7759 } 7760 7761 UsingDecl *UD = BuildValid(); 7762 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7763 UsingShadowDecl *PrevDecl = nullptr; 7764 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7765 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7766 } 7767 7768 return UD; 7769 } 7770 7771 /// Additional checks for a using declaration referring to a constructor name. 7772 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7773 assert(!UD->hasTypename() && "expecting a constructor name"); 7774 7775 const Type *SourceType = UD->getQualifier()->getAsType(); 7776 assert(SourceType && 7777 "Using decl naming constructor doesn't have type in scope spec."); 7778 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7779 7780 // Check whether the named type is a direct base class. 7781 bool AnyDependentBases = false; 7782 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 7783 AnyDependentBases); 7784 if (!Base && !AnyDependentBases) { 7785 Diag(UD->getUsingLoc(), 7786 diag::err_using_decl_constructor_not_in_direct_base) 7787 << UD->getNameInfo().getSourceRange() 7788 << QualType(SourceType, 0) << TargetClass; 7789 UD->setInvalidDecl(); 7790 return true; 7791 } 7792 7793 if (Base) 7794 Base->setInheritConstructors(); 7795 7796 return false; 7797 } 7798 7799 /// Checks that the given using declaration is not an invalid 7800 /// redeclaration. Note that this is checking only for the using decl 7801 /// itself, not for any ill-formedness among the UsingShadowDecls. 7802 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7803 bool HasTypenameKeyword, 7804 const CXXScopeSpec &SS, 7805 SourceLocation NameLoc, 7806 const LookupResult &Prev) { 7807 // C++03 [namespace.udecl]p8: 7808 // C++0x [namespace.udecl]p10: 7809 // A using-declaration is a declaration and can therefore be used 7810 // repeatedly where (and only where) multiple declarations are 7811 // allowed. 7812 // 7813 // That's in non-member contexts. 7814 if (!CurContext->getRedeclContext()->isRecord()) 7815 return false; 7816 7817 NestedNameSpecifier *Qual = SS.getScopeRep(); 7818 7819 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7820 NamedDecl *D = *I; 7821 7822 bool DTypename; 7823 NestedNameSpecifier *DQual; 7824 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7825 DTypename = UD->hasTypename(); 7826 DQual = UD->getQualifier(); 7827 } else if (UnresolvedUsingValueDecl *UD 7828 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7829 DTypename = false; 7830 DQual = UD->getQualifier(); 7831 } else if (UnresolvedUsingTypenameDecl *UD 7832 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7833 DTypename = true; 7834 DQual = UD->getQualifier(); 7835 } else continue; 7836 7837 // using decls differ if one says 'typename' and the other doesn't. 7838 // FIXME: non-dependent using decls? 7839 if (HasTypenameKeyword != DTypename) continue; 7840 7841 // using decls differ if they name different scopes (but note that 7842 // template instantiation can cause this check to trigger when it 7843 // didn't before instantiation). 7844 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7845 Context.getCanonicalNestedNameSpecifier(DQual)) 7846 continue; 7847 7848 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7849 Diag(D->getLocation(), diag::note_using_decl) << 1; 7850 return true; 7851 } 7852 7853 return false; 7854 } 7855 7856 7857 /// Checks that the given nested-name qualifier used in a using decl 7858 /// in the current context is appropriately related to the current 7859 /// scope. If an error is found, diagnoses it and returns true. 7860 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7861 const CXXScopeSpec &SS, 7862 const DeclarationNameInfo &NameInfo, 7863 SourceLocation NameLoc) { 7864 DeclContext *NamedContext = computeDeclContext(SS); 7865 7866 if (!CurContext->isRecord()) { 7867 // C++03 [namespace.udecl]p3: 7868 // C++0x [namespace.udecl]p8: 7869 // A using-declaration for a class member shall be a member-declaration. 7870 7871 // If we weren't able to compute a valid scope, it must be a 7872 // dependent class scope. 7873 if (!NamedContext || NamedContext->isRecord()) { 7874 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 7875 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 7876 RD = nullptr; 7877 7878 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7879 << SS.getRange(); 7880 7881 // If we have a complete, non-dependent source type, try to suggest a 7882 // way to get the same effect. 7883 if (!RD) 7884 return true; 7885 7886 // Find what this using-declaration was referring to. 7887 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7888 R.setHideTags(false); 7889 R.suppressDiagnostics(); 7890 LookupQualifiedName(R, RD); 7891 7892 if (R.getAsSingle<TypeDecl>()) { 7893 if (getLangOpts().CPlusPlus11) { 7894 // Convert 'using X::Y;' to 'using Y = X::Y;'. 7895 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 7896 << 0 // alias declaration 7897 << FixItHint::CreateInsertion(SS.getBeginLoc(), 7898 NameInfo.getName().getAsString() + 7899 " = "); 7900 } else { 7901 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 7902 SourceLocation InsertLoc = 7903 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 7904 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 7905 << 1 // typedef declaration 7906 << FixItHint::CreateReplacement(UsingLoc, "typedef") 7907 << FixItHint::CreateInsertion( 7908 InsertLoc, " " + NameInfo.getName().getAsString()); 7909 } 7910 } else if (R.getAsSingle<VarDecl>()) { 7911 // Don't provide a fixit outside C++11 mode; we don't want to suggest 7912 // repeating the type of the static data member here. 7913 FixItHint FixIt; 7914 if (getLangOpts().CPlusPlus11) { 7915 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 7916 FixIt = FixItHint::CreateReplacement( 7917 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 7918 } 7919 7920 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 7921 << 2 // reference declaration 7922 << FixIt; 7923 } 7924 return true; 7925 } 7926 7927 // Otherwise, everything is known to be fine. 7928 return false; 7929 } 7930 7931 // The current scope is a record. 7932 7933 // If the named context is dependent, we can't decide much. 7934 if (!NamedContext) { 7935 // FIXME: in C++0x, we can diagnose if we can prove that the 7936 // nested-name-specifier does not refer to a base class, which is 7937 // still possible in some cases. 7938 7939 // Otherwise we have to conservatively report that things might be 7940 // okay. 7941 return false; 7942 } 7943 7944 if (!NamedContext->isRecord()) { 7945 // Ideally this would point at the last name in the specifier, 7946 // but we don't have that level of source info. 7947 Diag(SS.getRange().getBegin(), 7948 diag::err_using_decl_nested_name_specifier_is_not_class) 7949 << SS.getScopeRep() << SS.getRange(); 7950 return true; 7951 } 7952 7953 if (!NamedContext->isDependentContext() && 7954 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7955 return true; 7956 7957 if (getLangOpts().CPlusPlus11) { 7958 // C++0x [namespace.udecl]p3: 7959 // In a using-declaration used as a member-declaration, the 7960 // nested-name-specifier shall name a base class of the class 7961 // being defined. 7962 7963 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7964 cast<CXXRecordDecl>(NamedContext))) { 7965 if (CurContext == NamedContext) { 7966 Diag(NameLoc, 7967 diag::err_using_decl_nested_name_specifier_is_current_class) 7968 << SS.getRange(); 7969 return true; 7970 } 7971 7972 Diag(SS.getRange().getBegin(), 7973 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7974 << SS.getScopeRep() 7975 << cast<CXXRecordDecl>(CurContext) 7976 << SS.getRange(); 7977 return true; 7978 } 7979 7980 return false; 7981 } 7982 7983 // C++03 [namespace.udecl]p4: 7984 // A using-declaration used as a member-declaration shall refer 7985 // to a member of a base class of the class being defined [etc.]. 7986 7987 // Salient point: SS doesn't have to name a base class as long as 7988 // lookup only finds members from base classes. Therefore we can 7989 // diagnose here only if we can prove that that can't happen, 7990 // i.e. if the class hierarchies provably don't intersect. 7991 7992 // TODO: it would be nice if "definitely valid" results were cached 7993 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7994 // need to be repeated. 7995 7996 struct UserData { 7997 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7998 7999 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8000 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8001 Data->Bases.insert(Base); 8002 return true; 8003 } 8004 8005 bool hasDependentBases(const CXXRecordDecl *Class) { 8006 return !Class->forallBases(collect, this); 8007 } 8008 8009 /// Returns true if the base is dependent or is one of the 8010 /// accumulated base classes. 8011 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8012 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8013 return !Data->Bases.count(Base); 8014 } 8015 8016 bool mightShareBases(const CXXRecordDecl *Class) { 8017 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8018 } 8019 }; 8020 8021 UserData Data; 8022 8023 // Returns false if we find a dependent base. 8024 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8025 return false; 8026 8027 // Returns false if the class has a dependent base or if it or one 8028 // of its bases is present in the base set of the current context. 8029 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8030 return false; 8031 8032 Diag(SS.getRange().getBegin(), 8033 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8034 << SS.getScopeRep() 8035 << cast<CXXRecordDecl>(CurContext) 8036 << SS.getRange(); 8037 8038 return true; 8039 } 8040 8041 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8042 AccessSpecifier AS, 8043 MultiTemplateParamsArg TemplateParamLists, 8044 SourceLocation UsingLoc, 8045 UnqualifiedId &Name, 8046 AttributeList *AttrList, 8047 TypeResult Type) { 8048 // Skip up to the relevant declaration scope. 8049 while (S->getFlags() & Scope::TemplateParamScope) 8050 S = S->getParent(); 8051 assert((S->getFlags() & Scope::DeclScope) && 8052 "got alias-declaration outside of declaration scope"); 8053 8054 if (Type.isInvalid()) 8055 return nullptr; 8056 8057 bool Invalid = false; 8058 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8059 TypeSourceInfo *TInfo = nullptr; 8060 GetTypeFromParser(Type.get(), &TInfo); 8061 8062 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8063 return nullptr; 8064 8065 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8066 UPPC_DeclarationType)) { 8067 Invalid = true; 8068 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8069 TInfo->getTypeLoc().getBeginLoc()); 8070 } 8071 8072 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8073 LookupName(Previous, S); 8074 8075 // Warn about shadowing the name of a template parameter. 8076 if (Previous.isSingleResult() && 8077 Previous.getFoundDecl()->isTemplateParameter()) { 8078 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8079 Previous.clear(); 8080 } 8081 8082 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8083 "name in alias declaration must be an identifier"); 8084 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8085 Name.StartLocation, 8086 Name.Identifier, TInfo); 8087 8088 NewTD->setAccess(AS); 8089 8090 if (Invalid) 8091 NewTD->setInvalidDecl(); 8092 8093 ProcessDeclAttributeList(S, NewTD, AttrList); 8094 8095 CheckTypedefForVariablyModifiedType(S, NewTD); 8096 Invalid |= NewTD->isInvalidDecl(); 8097 8098 bool Redeclaration = false; 8099 8100 NamedDecl *NewND; 8101 if (TemplateParamLists.size()) { 8102 TypeAliasTemplateDecl *OldDecl = nullptr; 8103 TemplateParameterList *OldTemplateParams = nullptr; 8104 8105 if (TemplateParamLists.size() != 1) { 8106 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8107 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8108 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8109 } 8110 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8111 8112 // Only consider previous declarations in the same scope. 8113 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8114 /*ExplicitInstantiationOrSpecialization*/false); 8115 if (!Previous.empty()) { 8116 Redeclaration = true; 8117 8118 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8119 if (!OldDecl && !Invalid) { 8120 Diag(UsingLoc, diag::err_redefinition_different_kind) 8121 << Name.Identifier; 8122 8123 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8124 if (OldD->getLocation().isValid()) 8125 Diag(OldD->getLocation(), diag::note_previous_definition); 8126 8127 Invalid = true; 8128 } 8129 8130 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8131 if (TemplateParameterListsAreEqual(TemplateParams, 8132 OldDecl->getTemplateParameters(), 8133 /*Complain=*/true, 8134 TPL_TemplateMatch)) 8135 OldTemplateParams = OldDecl->getTemplateParameters(); 8136 else 8137 Invalid = true; 8138 8139 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8140 if (!Invalid && 8141 !Context.hasSameType(OldTD->getUnderlyingType(), 8142 NewTD->getUnderlyingType())) { 8143 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8144 // but we can't reasonably accept it. 8145 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8146 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8147 if (OldTD->getLocation().isValid()) 8148 Diag(OldTD->getLocation(), diag::note_previous_definition); 8149 Invalid = true; 8150 } 8151 } 8152 } 8153 8154 // Merge any previous default template arguments into our parameters, 8155 // and check the parameter list. 8156 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8157 TPC_TypeAliasTemplate)) 8158 return nullptr; 8159 8160 TypeAliasTemplateDecl *NewDecl = 8161 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8162 Name.Identifier, TemplateParams, 8163 NewTD); 8164 8165 NewDecl->setAccess(AS); 8166 8167 if (Invalid) 8168 NewDecl->setInvalidDecl(); 8169 else if (OldDecl) 8170 NewDecl->setPreviousDecl(OldDecl); 8171 8172 NewND = NewDecl; 8173 } else { 8174 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8175 NewND = NewTD; 8176 } 8177 8178 if (!Redeclaration) 8179 PushOnScopeChains(NewND, S); 8180 8181 ActOnDocumentableDecl(NewND); 8182 return NewND; 8183 } 8184 8185 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 8186 SourceLocation NamespaceLoc, 8187 SourceLocation AliasLoc, 8188 IdentifierInfo *Alias, 8189 CXXScopeSpec &SS, 8190 SourceLocation IdentLoc, 8191 IdentifierInfo *Ident) { 8192 8193 // Lookup the namespace name. 8194 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8195 LookupParsedName(R, S, &SS); 8196 8197 // Check if we have a previous declaration with the same name. 8198 NamedDecl *PrevDecl 8199 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8200 ForRedeclaration); 8201 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8202 PrevDecl = nullptr; 8203 8204 if (PrevDecl) { 8205 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8206 // We already have an alias with the same name that points to the same 8207 // namespace, so don't create a new one. 8208 // FIXME: At some point, we'll want to create the (redundant) 8209 // declaration to maintain better source information. 8210 if (!R.isAmbiguous() && !R.empty() && 8211 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 8212 return nullptr; 8213 } 8214 8215 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 8216 diag::err_redefinition_different_kind; 8217 Diag(AliasLoc, DiagID) << Alias; 8218 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8219 return nullptr; 8220 } 8221 8222 if (R.isAmbiguous()) 8223 return nullptr; 8224 8225 if (R.empty()) { 8226 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8227 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8228 return nullptr; 8229 } 8230 } 8231 8232 NamespaceAliasDecl *AliasDecl = 8233 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8234 Alias, SS.getWithLocInContext(Context), 8235 IdentLoc, R.getFoundDecl()); 8236 8237 PushOnScopeChains(AliasDecl, S); 8238 return AliasDecl; 8239 } 8240 8241 Sema::ImplicitExceptionSpecification 8242 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8243 CXXMethodDecl *MD) { 8244 CXXRecordDecl *ClassDecl = MD->getParent(); 8245 8246 // C++ [except.spec]p14: 8247 // An implicitly declared special member function (Clause 12) shall have an 8248 // exception-specification. [...] 8249 ImplicitExceptionSpecification ExceptSpec(*this); 8250 if (ClassDecl->isInvalidDecl()) 8251 return ExceptSpec; 8252 8253 // Direct base-class constructors. 8254 for (const auto &B : ClassDecl->bases()) { 8255 if (B.isVirtual()) // Handled below. 8256 continue; 8257 8258 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8259 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8260 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8261 // If this is a deleted function, add it anyway. This might be conformant 8262 // with the standard. This might not. I'm not sure. It might not matter. 8263 if (Constructor) 8264 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8265 } 8266 } 8267 8268 // Virtual base-class constructors. 8269 for (const auto &B : ClassDecl->vbases()) { 8270 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8271 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8272 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8273 // If this is a deleted function, add it anyway. This might be conformant 8274 // with the standard. This might not. I'm not sure. It might not matter. 8275 if (Constructor) 8276 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8277 } 8278 } 8279 8280 // Field constructors. 8281 for (const auto *F : ClassDecl->fields()) { 8282 if (F->hasInClassInitializer()) { 8283 if (Expr *E = F->getInClassInitializer()) 8284 ExceptSpec.CalledExpr(E); 8285 else if (!F->isInvalidDecl()) 8286 // DR1351: 8287 // If the brace-or-equal-initializer of a non-static data member 8288 // invokes a defaulted default constructor of its class or of an 8289 // enclosing class in a potentially evaluated subexpression, the 8290 // program is ill-formed. 8291 // 8292 // This resolution is unworkable: the exception specification of the 8293 // default constructor can be needed in an unevaluated context, in 8294 // particular, in the operand of a noexcept-expression, and we can be 8295 // unable to compute an exception specification for an enclosed class. 8296 // 8297 // We do not allow an in-class initializer to require the evaluation 8298 // of the exception specification for any in-class initializer whose 8299 // definition is not lexically complete. 8300 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8301 } else if (const RecordType *RecordTy 8302 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8303 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8304 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8305 // If this is a deleted function, add it anyway. This might be conformant 8306 // with the standard. This might not. I'm not sure. It might not matter. 8307 // In particular, the problem is that this function never gets called. It 8308 // might just be ill-formed because this function attempts to refer to 8309 // a deleted function here. 8310 if (Constructor) 8311 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8312 } 8313 } 8314 8315 return ExceptSpec; 8316 } 8317 8318 Sema::ImplicitExceptionSpecification 8319 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8320 CXXRecordDecl *ClassDecl = CD->getParent(); 8321 8322 // C++ [except.spec]p14: 8323 // An inheriting constructor [...] shall have an exception-specification. [...] 8324 ImplicitExceptionSpecification ExceptSpec(*this); 8325 if (ClassDecl->isInvalidDecl()) 8326 return ExceptSpec; 8327 8328 // Inherited constructor. 8329 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8330 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8331 // FIXME: Copying or moving the parameters could add extra exceptions to the 8332 // set, as could the default arguments for the inherited constructor. This 8333 // will be addressed when we implement the resolution of core issue 1351. 8334 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8335 8336 // Direct base-class constructors. 8337 for (const auto &B : ClassDecl->bases()) { 8338 if (B.isVirtual()) // Handled below. 8339 continue; 8340 8341 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8342 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8343 if (BaseClassDecl == InheritedDecl) 8344 continue; 8345 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8346 if (Constructor) 8347 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8348 } 8349 } 8350 8351 // Virtual base-class constructors. 8352 for (const auto &B : ClassDecl->vbases()) { 8353 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8354 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8355 if (BaseClassDecl == InheritedDecl) 8356 continue; 8357 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8358 if (Constructor) 8359 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8360 } 8361 } 8362 8363 // Field constructors. 8364 for (const auto *F : ClassDecl->fields()) { 8365 if (F->hasInClassInitializer()) { 8366 if (Expr *E = F->getInClassInitializer()) 8367 ExceptSpec.CalledExpr(E); 8368 else if (!F->isInvalidDecl()) 8369 Diag(CD->getLocation(), 8370 diag::err_in_class_initializer_references_def_ctor) << CD; 8371 } else if (const RecordType *RecordTy 8372 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8373 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8374 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8375 if (Constructor) 8376 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8377 } 8378 } 8379 8380 return ExceptSpec; 8381 } 8382 8383 namespace { 8384 /// RAII object to register a special member as being currently declared. 8385 struct DeclaringSpecialMember { 8386 Sema &S; 8387 Sema::SpecialMemberDecl D; 8388 bool WasAlreadyBeingDeclared; 8389 8390 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8391 : S(S), D(RD, CSM) { 8392 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8393 if (WasAlreadyBeingDeclared) 8394 // This almost never happens, but if it does, ensure that our cache 8395 // doesn't contain a stale result. 8396 S.SpecialMemberCache.clear(); 8397 8398 // FIXME: Register a note to be produced if we encounter an error while 8399 // declaring the special member. 8400 } 8401 ~DeclaringSpecialMember() { 8402 if (!WasAlreadyBeingDeclared) 8403 S.SpecialMembersBeingDeclared.erase(D); 8404 } 8405 8406 /// \brief Are we already trying to declare this special member? 8407 bool isAlreadyBeingDeclared() const { 8408 return WasAlreadyBeingDeclared; 8409 } 8410 }; 8411 } 8412 8413 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8414 CXXRecordDecl *ClassDecl) { 8415 // C++ [class.ctor]p5: 8416 // A default constructor for a class X is a constructor of class X 8417 // that can be called without an argument. If there is no 8418 // user-declared constructor for class X, a default constructor is 8419 // implicitly declared. An implicitly-declared default constructor 8420 // is an inline public member of its class. 8421 assert(ClassDecl->needsImplicitDefaultConstructor() && 8422 "Should not build implicit default constructor!"); 8423 8424 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8425 if (DSM.isAlreadyBeingDeclared()) 8426 return nullptr; 8427 8428 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8429 CXXDefaultConstructor, 8430 false); 8431 8432 // Create the actual constructor declaration. 8433 CanQualType ClassType 8434 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8435 SourceLocation ClassLoc = ClassDecl->getLocation(); 8436 DeclarationName Name 8437 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8438 DeclarationNameInfo NameInfo(Name, ClassLoc); 8439 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8440 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8441 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8442 /*isImplicitlyDeclared=*/true, Constexpr); 8443 DefaultCon->setAccess(AS_public); 8444 DefaultCon->setDefaulted(); 8445 DefaultCon->setImplicit(); 8446 8447 // Build an exception specification pointing back at this constructor. 8448 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8449 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8450 8451 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8452 // constructors is easy to compute. 8453 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8454 8455 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8456 SetDeclDeleted(DefaultCon, ClassLoc); 8457 8458 // Note that we have declared this constructor. 8459 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8460 8461 if (Scope *S = getScopeForContext(ClassDecl)) 8462 PushOnScopeChains(DefaultCon, S, false); 8463 ClassDecl->addDecl(DefaultCon); 8464 8465 return DefaultCon; 8466 } 8467 8468 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8469 CXXConstructorDecl *Constructor) { 8470 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8471 !Constructor->doesThisDeclarationHaveABody() && 8472 !Constructor->isDeleted()) && 8473 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8474 8475 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8476 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8477 8478 SynthesizedFunctionScope Scope(*this, Constructor); 8479 DiagnosticErrorTrap Trap(Diags); 8480 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8481 Trap.hasErrorOccurred()) { 8482 Diag(CurrentLocation, diag::note_member_synthesized_at) 8483 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8484 Constructor->setInvalidDecl(); 8485 return; 8486 } 8487 8488 SourceLocation Loc = Constructor->getLocEnd().isValid() 8489 ? Constructor->getLocEnd() 8490 : Constructor->getLocation(); 8491 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8492 8493 Constructor->markUsed(Context); 8494 MarkVTableUsed(CurrentLocation, ClassDecl); 8495 8496 if (ASTMutationListener *L = getASTMutationListener()) { 8497 L->CompletedImplicitDefinition(Constructor); 8498 } 8499 8500 DiagnoseUninitializedFields(*this, Constructor); 8501 } 8502 8503 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8504 // Perform any delayed checks on exception specifications. 8505 CheckDelayedMemberExceptionSpecs(); 8506 } 8507 8508 namespace { 8509 /// Information on inheriting constructors to declare. 8510 class InheritingConstructorInfo { 8511 public: 8512 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8513 : SemaRef(SemaRef), Derived(Derived) { 8514 // Mark the constructors that we already have in the derived class. 8515 // 8516 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8517 // unless there is a user-declared constructor with the same signature in 8518 // the class where the using-declaration appears. 8519 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8520 } 8521 8522 void inheritAll(CXXRecordDecl *RD) { 8523 visitAll(RD, &InheritingConstructorInfo::inherit); 8524 } 8525 8526 private: 8527 /// Information about an inheriting constructor. 8528 struct InheritingConstructor { 8529 InheritingConstructor() 8530 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8531 8532 /// If \c true, a constructor with this signature is already declared 8533 /// in the derived class. 8534 bool DeclaredInDerived; 8535 8536 /// The constructor which is inherited. 8537 const CXXConstructorDecl *BaseCtor; 8538 8539 /// The derived constructor we declared. 8540 CXXConstructorDecl *DerivedCtor; 8541 }; 8542 8543 /// Inheriting constructors with a given canonical type. There can be at 8544 /// most one such non-template constructor, and any number of templated 8545 /// constructors. 8546 struct InheritingConstructorsForType { 8547 InheritingConstructor NonTemplate; 8548 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8549 Templates; 8550 8551 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8552 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8553 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8554 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8555 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8556 false, S.TPL_TemplateMatch)) 8557 return Templates[I].second; 8558 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8559 return Templates.back().second; 8560 } 8561 8562 return NonTemplate; 8563 } 8564 }; 8565 8566 /// Get or create the inheriting constructor record for a constructor. 8567 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8568 QualType CtorType) { 8569 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8570 .getEntry(SemaRef, Ctor); 8571 } 8572 8573 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8574 8575 /// Process all constructors for a class. 8576 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8577 for (const auto *Ctor : RD->ctors()) 8578 (this->*Callback)(Ctor); 8579 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8580 I(RD->decls_begin()), E(RD->decls_end()); 8581 I != E; ++I) { 8582 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8583 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8584 (this->*Callback)(CD); 8585 } 8586 } 8587 8588 /// Note that a constructor (or constructor template) was declared in Derived. 8589 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8590 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8591 } 8592 8593 /// Inherit a single constructor. 8594 void inherit(const CXXConstructorDecl *Ctor) { 8595 const FunctionProtoType *CtorType = 8596 Ctor->getType()->castAs<FunctionProtoType>(); 8597 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes()); 8598 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8599 8600 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8601 8602 // Core issue (no number yet): the ellipsis is always discarded. 8603 if (EPI.Variadic) { 8604 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8605 SemaRef.Diag(Ctor->getLocation(), 8606 diag::note_using_decl_constructor_ellipsis); 8607 EPI.Variadic = false; 8608 } 8609 8610 // Declare a constructor for each number of parameters. 8611 // 8612 // C++11 [class.inhctor]p1: 8613 // The candidate set of inherited constructors from the class X named in 8614 // the using-declaration consists of [... modulo defects ...] for each 8615 // constructor or constructor template of X, the set of constructors or 8616 // constructor templates that results from omitting any ellipsis parameter 8617 // specification and successively omitting parameters with a default 8618 // argument from the end of the parameter-type-list 8619 unsigned MinParams = minParamsToInherit(Ctor); 8620 unsigned Params = Ctor->getNumParams(); 8621 if (Params >= MinParams) { 8622 do 8623 declareCtor(UsingLoc, Ctor, 8624 SemaRef.Context.getFunctionType( 8625 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8626 while (Params > MinParams && 8627 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8628 } 8629 } 8630 8631 /// Find the using-declaration which specified that we should inherit the 8632 /// constructors of \p Base. 8633 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8634 // No fancy lookup required; just look for the base constructor name 8635 // directly within the derived class. 8636 ASTContext &Context = SemaRef.Context; 8637 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8638 Context.getCanonicalType(Context.getRecordType(Base))); 8639 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8640 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8641 } 8642 8643 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8644 // C++11 [class.inhctor]p3: 8645 // [F]or each constructor template in the candidate set of inherited 8646 // constructors, a constructor template is implicitly declared 8647 if (Ctor->getDescribedFunctionTemplate()) 8648 return 0; 8649 8650 // For each non-template constructor in the candidate set of inherited 8651 // constructors other than a constructor having no parameters or a 8652 // copy/move constructor having a single parameter, a constructor is 8653 // implicitly declared [...] 8654 if (Ctor->getNumParams() == 0) 8655 return 1; 8656 if (Ctor->isCopyOrMoveConstructor()) 8657 return 2; 8658 8659 // Per discussion on core reflector, never inherit a constructor which 8660 // would become a default, copy, or move constructor of Derived either. 8661 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8662 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8663 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8664 } 8665 8666 /// Declare a single inheriting constructor, inheriting the specified 8667 /// constructor, with the given type. 8668 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8669 QualType DerivedType) { 8670 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8671 8672 // C++11 [class.inhctor]p3: 8673 // ... a constructor is implicitly declared with the same constructor 8674 // characteristics unless there is a user-declared constructor with 8675 // the same signature in the class where the using-declaration appears 8676 if (Entry.DeclaredInDerived) 8677 return; 8678 8679 // C++11 [class.inhctor]p7: 8680 // If two using-declarations declare inheriting constructors with the 8681 // same signature, the program is ill-formed 8682 if (Entry.DerivedCtor) { 8683 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8684 // Only diagnose this once per constructor. 8685 if (Entry.DerivedCtor->isInvalidDecl()) 8686 return; 8687 Entry.DerivedCtor->setInvalidDecl(); 8688 8689 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8690 SemaRef.Diag(BaseCtor->getLocation(), 8691 diag::note_using_decl_constructor_conflict_current_ctor); 8692 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8693 diag::note_using_decl_constructor_conflict_previous_ctor); 8694 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8695 diag::note_using_decl_constructor_conflict_previous_using); 8696 } else { 8697 // Core issue (no number): if the same inheriting constructor is 8698 // produced by multiple base class constructors from the same base 8699 // class, the inheriting constructor is defined as deleted. 8700 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8701 } 8702 8703 return; 8704 } 8705 8706 ASTContext &Context = SemaRef.Context; 8707 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8708 Context.getCanonicalType(Context.getRecordType(Derived))); 8709 DeclarationNameInfo NameInfo(Name, UsingLoc); 8710 8711 TemplateParameterList *TemplateParams = nullptr; 8712 if (const FunctionTemplateDecl *FTD = 8713 BaseCtor->getDescribedFunctionTemplate()) { 8714 TemplateParams = FTD->getTemplateParameters(); 8715 // We're reusing template parameters from a different DeclContext. This 8716 // is questionable at best, but works out because the template depth in 8717 // both places is guaranteed to be 0. 8718 // FIXME: Rebuild the template parameters in the new context, and 8719 // transform the function type to refer to them. 8720 } 8721 8722 // Build type source info pointing at the using-declaration. This is 8723 // required by template instantiation. 8724 TypeSourceInfo *TInfo = 8725 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8726 FunctionProtoTypeLoc ProtoLoc = 8727 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8728 8729 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8730 Context, Derived, UsingLoc, NameInfo, DerivedType, 8731 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8732 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8733 8734 // Build an unevaluated exception specification for this constructor. 8735 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8736 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8737 EPI.ExceptionSpecType = EST_Unevaluated; 8738 EPI.ExceptionSpecDecl = DerivedCtor; 8739 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 8740 FPT->getParamTypes(), EPI)); 8741 8742 // Build the parameter declarations. 8743 SmallVector<ParmVarDecl *, 16> ParamDecls; 8744 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 8745 TypeSourceInfo *TInfo = 8746 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 8747 ParmVarDecl *PD = ParmVarDecl::Create( 8748 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 8749 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 8750 PD->setScopeInfo(0, I); 8751 PD->setImplicit(); 8752 ParamDecls.push_back(PD); 8753 ProtoLoc.setParam(I, PD); 8754 } 8755 8756 // Set up the new constructor. 8757 DerivedCtor->setAccess(BaseCtor->getAccess()); 8758 DerivedCtor->setParams(ParamDecls); 8759 DerivedCtor->setInheritedConstructor(BaseCtor); 8760 if (BaseCtor->isDeleted()) 8761 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8762 8763 // If this is a constructor template, build the template declaration. 8764 if (TemplateParams) { 8765 FunctionTemplateDecl *DerivedTemplate = 8766 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8767 TemplateParams, DerivedCtor); 8768 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8769 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8770 Derived->addDecl(DerivedTemplate); 8771 } else { 8772 Derived->addDecl(DerivedCtor); 8773 } 8774 8775 Entry.BaseCtor = BaseCtor; 8776 Entry.DerivedCtor = DerivedCtor; 8777 } 8778 8779 Sema &SemaRef; 8780 CXXRecordDecl *Derived; 8781 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8782 MapType Map; 8783 }; 8784 } 8785 8786 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8787 // Defer declaring the inheriting constructors until the class is 8788 // instantiated. 8789 if (ClassDecl->isDependentContext()) 8790 return; 8791 8792 // Find base classes from which we might inherit constructors. 8793 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8794 for (const auto &BaseIt : ClassDecl->bases()) 8795 if (BaseIt.getInheritConstructors()) 8796 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 8797 8798 // Go no further if we're not inheriting any constructors. 8799 if (InheritedBases.empty()) 8800 return; 8801 8802 // Declare the inherited constructors. 8803 InheritingConstructorInfo ICI(*this, ClassDecl); 8804 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8805 ICI.inheritAll(InheritedBases[I]); 8806 } 8807 8808 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8809 CXXConstructorDecl *Constructor) { 8810 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8811 assert(Constructor->getInheritedConstructor() && 8812 !Constructor->doesThisDeclarationHaveABody() && 8813 !Constructor->isDeleted()); 8814 8815 SynthesizedFunctionScope Scope(*this, Constructor); 8816 DiagnosticErrorTrap Trap(Diags); 8817 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8818 Trap.hasErrorOccurred()) { 8819 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8820 << Context.getTagDeclType(ClassDecl); 8821 Constructor->setInvalidDecl(); 8822 return; 8823 } 8824 8825 SourceLocation Loc = Constructor->getLocation(); 8826 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8827 8828 Constructor->markUsed(Context); 8829 MarkVTableUsed(CurrentLocation, ClassDecl); 8830 8831 if (ASTMutationListener *L = getASTMutationListener()) { 8832 L->CompletedImplicitDefinition(Constructor); 8833 } 8834 } 8835 8836 8837 Sema::ImplicitExceptionSpecification 8838 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8839 CXXRecordDecl *ClassDecl = MD->getParent(); 8840 8841 // C++ [except.spec]p14: 8842 // An implicitly declared special member function (Clause 12) shall have 8843 // an exception-specification. 8844 ImplicitExceptionSpecification ExceptSpec(*this); 8845 if (ClassDecl->isInvalidDecl()) 8846 return ExceptSpec; 8847 8848 // Direct base-class destructors. 8849 for (const auto &B : ClassDecl->bases()) { 8850 if (B.isVirtual()) // Handled below. 8851 continue; 8852 8853 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8854 ExceptSpec.CalledDecl(B.getLocStart(), 8855 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8856 } 8857 8858 // Virtual base-class destructors. 8859 for (const auto &B : ClassDecl->vbases()) { 8860 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8861 ExceptSpec.CalledDecl(B.getLocStart(), 8862 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8863 } 8864 8865 // Field destructors. 8866 for (const auto *F : ClassDecl->fields()) { 8867 if (const RecordType *RecordTy 8868 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8869 ExceptSpec.CalledDecl(F->getLocation(), 8870 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8871 } 8872 8873 return ExceptSpec; 8874 } 8875 8876 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8877 // C++ [class.dtor]p2: 8878 // If a class has no user-declared destructor, a destructor is 8879 // declared implicitly. An implicitly-declared destructor is an 8880 // inline public member of its class. 8881 assert(ClassDecl->needsImplicitDestructor()); 8882 8883 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8884 if (DSM.isAlreadyBeingDeclared()) 8885 return nullptr; 8886 8887 // Create the actual destructor declaration. 8888 CanQualType ClassType 8889 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8890 SourceLocation ClassLoc = ClassDecl->getLocation(); 8891 DeclarationName Name 8892 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8893 DeclarationNameInfo NameInfo(Name, ClassLoc); 8894 CXXDestructorDecl *Destructor 8895 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8896 QualType(), nullptr, /*isInline=*/true, 8897 /*isImplicitlyDeclared=*/true); 8898 Destructor->setAccess(AS_public); 8899 Destructor->setDefaulted(); 8900 Destructor->setImplicit(); 8901 8902 // Build an exception specification pointing back at this destructor. 8903 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8904 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8905 8906 AddOverriddenMethods(ClassDecl, Destructor); 8907 8908 // We don't need to use SpecialMemberIsTrivial here; triviality for 8909 // destructors is easy to compute. 8910 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8911 8912 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8913 SetDeclDeleted(Destructor, ClassLoc); 8914 8915 // Note that we have declared this destructor. 8916 ++ASTContext::NumImplicitDestructorsDeclared; 8917 8918 // Introduce this destructor into its scope. 8919 if (Scope *S = getScopeForContext(ClassDecl)) 8920 PushOnScopeChains(Destructor, S, false); 8921 ClassDecl->addDecl(Destructor); 8922 8923 return Destructor; 8924 } 8925 8926 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8927 CXXDestructorDecl *Destructor) { 8928 assert((Destructor->isDefaulted() && 8929 !Destructor->doesThisDeclarationHaveABody() && 8930 !Destructor->isDeleted()) && 8931 "DefineImplicitDestructor - call it for implicit default dtor"); 8932 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8933 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8934 8935 if (Destructor->isInvalidDecl()) 8936 return; 8937 8938 SynthesizedFunctionScope Scope(*this, Destructor); 8939 8940 DiagnosticErrorTrap Trap(Diags); 8941 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8942 Destructor->getParent()); 8943 8944 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8945 Diag(CurrentLocation, diag::note_member_synthesized_at) 8946 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8947 8948 Destructor->setInvalidDecl(); 8949 return; 8950 } 8951 8952 SourceLocation Loc = Destructor->getLocEnd().isValid() 8953 ? Destructor->getLocEnd() 8954 : Destructor->getLocation(); 8955 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8956 Destructor->markUsed(Context); 8957 MarkVTableUsed(CurrentLocation, ClassDecl); 8958 8959 if (ASTMutationListener *L = getASTMutationListener()) { 8960 L->CompletedImplicitDefinition(Destructor); 8961 } 8962 } 8963 8964 /// \brief Perform any semantic analysis which needs to be delayed until all 8965 /// pending class member declarations have been parsed. 8966 void Sema::ActOnFinishCXXMemberDecls() { 8967 // If the context is an invalid C++ class, just suppress these checks. 8968 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8969 if (Record->isInvalidDecl()) { 8970 DelayedDefaultedMemberExceptionSpecs.clear(); 8971 DelayedDestructorExceptionSpecChecks.clear(); 8972 return; 8973 } 8974 } 8975 } 8976 8977 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8978 CXXDestructorDecl *Destructor) { 8979 assert(getLangOpts().CPlusPlus11 && 8980 "adjusting dtor exception specs was introduced in c++11"); 8981 8982 // C++11 [class.dtor]p3: 8983 // A declaration of a destructor that does not have an exception- 8984 // specification is implicitly considered to have the same exception- 8985 // specification as an implicit declaration. 8986 const FunctionProtoType *DtorType = Destructor->getType()-> 8987 getAs<FunctionProtoType>(); 8988 if (DtorType->hasExceptionSpec()) 8989 return; 8990 8991 // Replace the destructor's type, building off the existing one. Fortunately, 8992 // the only thing of interest in the destructor type is its extended info. 8993 // The return and arguments are fixed. 8994 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8995 EPI.ExceptionSpecType = EST_Unevaluated; 8996 EPI.ExceptionSpecDecl = Destructor; 8997 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8998 8999 // FIXME: If the destructor has a body that could throw, and the newly created 9000 // spec doesn't allow exceptions, we should emit a warning, because this 9001 // change in behavior can break conforming C++03 programs at runtime. 9002 // However, we don't have a body or an exception specification yet, so it 9003 // needs to be done somewhere else. 9004 } 9005 9006 namespace { 9007 /// \brief An abstract base class for all helper classes used in building the 9008 // copy/move operators. These classes serve as factory functions and help us 9009 // avoid using the same Expr* in the AST twice. 9010 class ExprBuilder { 9011 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9012 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9013 9014 protected: 9015 static Expr *assertNotNull(Expr *E) { 9016 assert(E && "Expression construction must not fail."); 9017 return E; 9018 } 9019 9020 public: 9021 ExprBuilder() {} 9022 virtual ~ExprBuilder() {} 9023 9024 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9025 }; 9026 9027 class RefBuilder: public ExprBuilder { 9028 VarDecl *Var; 9029 QualType VarType; 9030 9031 public: 9032 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9033 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9034 } 9035 9036 RefBuilder(VarDecl *Var, QualType VarType) 9037 : Var(Var), VarType(VarType) {} 9038 }; 9039 9040 class ThisBuilder: public ExprBuilder { 9041 public: 9042 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9043 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9044 } 9045 }; 9046 9047 class CastBuilder: public ExprBuilder { 9048 const ExprBuilder &Builder; 9049 QualType Type; 9050 ExprValueKind Kind; 9051 const CXXCastPath &Path; 9052 9053 public: 9054 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9055 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9056 CK_UncheckedDerivedToBase, Kind, 9057 &Path).get()); 9058 } 9059 9060 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9061 const CXXCastPath &Path) 9062 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9063 }; 9064 9065 class DerefBuilder: public ExprBuilder { 9066 const ExprBuilder &Builder; 9067 9068 public: 9069 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9070 return assertNotNull( 9071 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9072 } 9073 9074 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9075 }; 9076 9077 class MemberBuilder: public ExprBuilder { 9078 const ExprBuilder &Builder; 9079 QualType Type; 9080 CXXScopeSpec SS; 9081 bool IsArrow; 9082 LookupResult &MemberLookup; 9083 9084 public: 9085 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9086 return assertNotNull(S.BuildMemberReferenceExpr( 9087 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9088 nullptr, MemberLookup, nullptr).get()); 9089 } 9090 9091 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9092 LookupResult &MemberLookup) 9093 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9094 MemberLookup(MemberLookup) {} 9095 }; 9096 9097 class MoveCastBuilder: public ExprBuilder { 9098 const ExprBuilder &Builder; 9099 9100 public: 9101 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9102 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9103 } 9104 9105 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9106 }; 9107 9108 class LvalueConvBuilder: public ExprBuilder { 9109 const ExprBuilder &Builder; 9110 9111 public: 9112 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9113 return assertNotNull( 9114 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9115 } 9116 9117 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9118 }; 9119 9120 class SubscriptBuilder: public ExprBuilder { 9121 const ExprBuilder &Base; 9122 const ExprBuilder &Index; 9123 9124 public: 9125 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9126 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9127 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9128 } 9129 9130 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9131 : Base(Base), Index(Index) {} 9132 }; 9133 9134 } // end anonymous namespace 9135 9136 /// When generating a defaulted copy or move assignment operator, if a field 9137 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9138 /// do so. This optimization only applies for arrays of scalars, and for arrays 9139 /// of class type where the selected copy/move-assignment operator is trivial. 9140 static StmtResult 9141 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9142 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9143 // Compute the size of the memory buffer to be copied. 9144 QualType SizeType = S.Context.getSizeType(); 9145 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9146 S.Context.getTypeSizeInChars(T).getQuantity()); 9147 9148 // Take the address of the field references for "from" and "to". We 9149 // directly construct UnaryOperators here because semantic analysis 9150 // does not permit us to take the address of an xvalue. 9151 Expr *From = FromB.build(S, Loc); 9152 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9153 S.Context.getPointerType(From->getType()), 9154 VK_RValue, OK_Ordinary, Loc); 9155 Expr *To = ToB.build(S, Loc); 9156 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9157 S.Context.getPointerType(To->getType()), 9158 VK_RValue, OK_Ordinary, Loc); 9159 9160 const Type *E = T->getBaseElementTypeUnsafe(); 9161 bool NeedsCollectableMemCpy = 9162 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9163 9164 // Create a reference to the __builtin_objc_memmove_collectable function 9165 StringRef MemCpyName = NeedsCollectableMemCpy ? 9166 "__builtin_objc_memmove_collectable" : 9167 "__builtin_memcpy"; 9168 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9169 Sema::LookupOrdinaryName); 9170 S.LookupName(R, S.TUScope, true); 9171 9172 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9173 if (!MemCpy) 9174 // Something went horribly wrong earlier, and we will have complained 9175 // about it. 9176 return StmtError(); 9177 9178 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9179 VK_RValue, Loc, nullptr); 9180 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9181 9182 Expr *CallArgs[] = { 9183 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9184 }; 9185 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9186 Loc, CallArgs, Loc); 9187 9188 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9189 return Call.getAs<Stmt>(); 9190 } 9191 9192 /// \brief Builds a statement that copies/moves the given entity from \p From to 9193 /// \c To. 9194 /// 9195 /// This routine is used to copy/move the members of a class with an 9196 /// implicitly-declared copy/move assignment operator. When the entities being 9197 /// copied are arrays, this routine builds for loops to copy them. 9198 /// 9199 /// \param S The Sema object used for type-checking. 9200 /// 9201 /// \param Loc The location where the implicit copy/move is being generated. 9202 /// 9203 /// \param T The type of the expressions being copied/moved. Both expressions 9204 /// must have this type. 9205 /// 9206 /// \param To The expression we are copying/moving to. 9207 /// 9208 /// \param From The expression we are copying/moving from. 9209 /// 9210 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9211 /// Otherwise, it's a non-static member subobject. 9212 /// 9213 /// \param Copying Whether we're copying or moving. 9214 /// 9215 /// \param Depth Internal parameter recording the depth of the recursion. 9216 /// 9217 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9218 /// if a memcpy should be used instead. 9219 static StmtResult 9220 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9221 const ExprBuilder &To, const ExprBuilder &From, 9222 bool CopyingBaseSubobject, bool Copying, 9223 unsigned Depth = 0) { 9224 // C++11 [class.copy]p28: 9225 // Each subobject is assigned in the manner appropriate to its type: 9226 // 9227 // - if the subobject is of class type, as if by a call to operator= with 9228 // the subobject as the object expression and the corresponding 9229 // subobject of x as a single function argument (as if by explicit 9230 // qualification; that is, ignoring any possible virtual overriding 9231 // functions in more derived classes); 9232 // 9233 // C++03 [class.copy]p13: 9234 // - if the subobject is of class type, the copy assignment operator for 9235 // the class is used (as if by explicit qualification; that is, 9236 // ignoring any possible virtual overriding functions in more derived 9237 // classes); 9238 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9239 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9240 9241 // Look for operator=. 9242 DeclarationName Name 9243 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9244 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9245 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9246 9247 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9248 // operator. 9249 if (!S.getLangOpts().CPlusPlus11) { 9250 LookupResult::Filter F = OpLookup.makeFilter(); 9251 while (F.hasNext()) { 9252 NamedDecl *D = F.next(); 9253 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9254 if (Method->isCopyAssignmentOperator() || 9255 (!Copying && Method->isMoveAssignmentOperator())) 9256 continue; 9257 9258 F.erase(); 9259 } 9260 F.done(); 9261 } 9262 9263 // Suppress the protected check (C++ [class.protected]) for each of the 9264 // assignment operators we found. This strange dance is required when 9265 // we're assigning via a base classes's copy-assignment operator. To 9266 // ensure that we're getting the right base class subobject (without 9267 // ambiguities), we need to cast "this" to that subobject type; to 9268 // ensure that we don't go through the virtual call mechanism, we need 9269 // to qualify the operator= name with the base class (see below). However, 9270 // this means that if the base class has a protected copy assignment 9271 // operator, the protected member access check will fail. So, we 9272 // rewrite "protected" access to "public" access in this case, since we 9273 // know by construction that we're calling from a derived class. 9274 if (CopyingBaseSubobject) { 9275 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9276 L != LEnd; ++L) { 9277 if (L.getAccess() == AS_protected) 9278 L.setAccess(AS_public); 9279 } 9280 } 9281 9282 // Create the nested-name-specifier that will be used to qualify the 9283 // reference to operator=; this is required to suppress the virtual 9284 // call mechanism. 9285 CXXScopeSpec SS; 9286 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9287 SS.MakeTrivial(S.Context, 9288 NestedNameSpecifier::Create(S.Context, nullptr, false, 9289 CanonicalT), 9290 Loc); 9291 9292 // Create the reference to operator=. 9293 ExprResult OpEqualRef 9294 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9295 SS, /*TemplateKWLoc=*/SourceLocation(), 9296 /*FirstQualifierInScope=*/nullptr, 9297 OpLookup, 9298 /*TemplateArgs=*/nullptr, 9299 /*SuppressQualifierCheck=*/true); 9300 if (OpEqualRef.isInvalid()) 9301 return StmtError(); 9302 9303 // Build the call to the assignment operator. 9304 9305 Expr *FromInst = From.build(S, Loc); 9306 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9307 OpEqualRef.getAs<Expr>(), 9308 Loc, FromInst, Loc); 9309 if (Call.isInvalid()) 9310 return StmtError(); 9311 9312 // If we built a call to a trivial 'operator=' while copying an array, 9313 // bail out. We'll replace the whole shebang with a memcpy. 9314 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9315 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9316 return StmtResult((Stmt*)nullptr); 9317 9318 // Convert to an expression-statement, and clean up any produced 9319 // temporaries. 9320 return S.ActOnExprStmt(Call); 9321 } 9322 9323 // - if the subobject is of scalar type, the built-in assignment 9324 // operator is used. 9325 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9326 if (!ArrayTy) { 9327 ExprResult Assignment = S.CreateBuiltinBinOp( 9328 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9329 if (Assignment.isInvalid()) 9330 return StmtError(); 9331 return S.ActOnExprStmt(Assignment); 9332 } 9333 9334 // - if the subobject is an array, each element is assigned, in the 9335 // manner appropriate to the element type; 9336 9337 // Construct a loop over the array bounds, e.g., 9338 // 9339 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9340 // 9341 // that will copy each of the array elements. 9342 QualType SizeType = S.Context.getSizeType(); 9343 9344 // Create the iteration variable. 9345 IdentifierInfo *IterationVarName = nullptr; 9346 { 9347 SmallString<8> Str; 9348 llvm::raw_svector_ostream OS(Str); 9349 OS << "__i" << Depth; 9350 IterationVarName = &S.Context.Idents.get(OS.str()); 9351 } 9352 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9353 IterationVarName, SizeType, 9354 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9355 SC_None); 9356 9357 // Initialize the iteration variable to zero. 9358 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9359 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9360 9361 // Creates a reference to the iteration variable. 9362 RefBuilder IterationVarRef(IterationVar, SizeType); 9363 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9364 9365 // Create the DeclStmt that holds the iteration variable. 9366 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9367 9368 // Subscript the "from" and "to" expressions with the iteration variable. 9369 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9370 MoveCastBuilder FromIndexMove(FromIndexCopy); 9371 const ExprBuilder *FromIndex; 9372 if (Copying) 9373 FromIndex = &FromIndexCopy; 9374 else 9375 FromIndex = &FromIndexMove; 9376 9377 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9378 9379 // Build the copy/move for an individual element of the array. 9380 StmtResult Copy = 9381 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9382 ToIndex, *FromIndex, CopyingBaseSubobject, 9383 Copying, Depth + 1); 9384 // Bail out if copying fails or if we determined that we should use memcpy. 9385 if (Copy.isInvalid() || !Copy.get()) 9386 return Copy; 9387 9388 // Create the comparison against the array bound. 9389 llvm::APInt Upper 9390 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9391 Expr *Comparison 9392 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9393 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9394 BO_NE, S.Context.BoolTy, 9395 VK_RValue, OK_Ordinary, Loc, false); 9396 9397 // Create the pre-increment of the iteration variable. 9398 Expr *Increment 9399 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9400 SizeType, VK_LValue, OK_Ordinary, Loc); 9401 9402 // Construct the loop that copies all elements of this array. 9403 return S.ActOnForStmt(Loc, Loc, InitStmt, 9404 S.MakeFullExpr(Comparison), 9405 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9406 Loc, Copy.get()); 9407 } 9408 9409 static StmtResult 9410 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9411 const ExprBuilder &To, const ExprBuilder &From, 9412 bool CopyingBaseSubobject, bool Copying) { 9413 // Maybe we should use a memcpy? 9414 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9415 T.isTriviallyCopyableType(S.Context)) 9416 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9417 9418 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9419 CopyingBaseSubobject, 9420 Copying, 0)); 9421 9422 // If we ended up picking a trivial assignment operator for an array of a 9423 // non-trivially-copyable class type, just emit a memcpy. 9424 if (!Result.isInvalid() && !Result.get()) 9425 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9426 9427 return Result; 9428 } 9429 9430 Sema::ImplicitExceptionSpecification 9431 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9432 CXXRecordDecl *ClassDecl = MD->getParent(); 9433 9434 ImplicitExceptionSpecification ExceptSpec(*this); 9435 if (ClassDecl->isInvalidDecl()) 9436 return ExceptSpec; 9437 9438 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9439 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9440 unsigned ArgQuals = 9441 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9442 9443 // C++ [except.spec]p14: 9444 // An implicitly declared special member function (Clause 12) shall have an 9445 // exception-specification. [...] 9446 9447 // It is unspecified whether or not an implicit copy assignment operator 9448 // attempts to deduplicate calls to assignment operators of virtual bases are 9449 // made. As such, this exception specification is effectively unspecified. 9450 // Based on a similar decision made for constness in C++0x, we're erring on 9451 // the side of assuming such calls to be made regardless of whether they 9452 // actually happen. 9453 for (const auto &Base : ClassDecl->bases()) { 9454 if (Base.isVirtual()) 9455 continue; 9456 9457 CXXRecordDecl *BaseClassDecl 9458 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9459 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9460 ArgQuals, false, 0)) 9461 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9462 } 9463 9464 for (const auto &Base : ClassDecl->vbases()) { 9465 CXXRecordDecl *BaseClassDecl 9466 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9467 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9468 ArgQuals, false, 0)) 9469 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9470 } 9471 9472 for (const auto *Field : ClassDecl->fields()) { 9473 QualType FieldType = Context.getBaseElementType(Field->getType()); 9474 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9475 if (CXXMethodDecl *CopyAssign = 9476 LookupCopyingAssignment(FieldClassDecl, 9477 ArgQuals | FieldType.getCVRQualifiers(), 9478 false, 0)) 9479 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9480 } 9481 } 9482 9483 return ExceptSpec; 9484 } 9485 9486 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9487 // Note: The following rules are largely analoguous to the copy 9488 // constructor rules. Note that virtual bases are not taken into account 9489 // for determining the argument type of the operator. Note also that 9490 // operators taking an object instead of a reference are allowed. 9491 assert(ClassDecl->needsImplicitCopyAssignment()); 9492 9493 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9494 if (DSM.isAlreadyBeingDeclared()) 9495 return nullptr; 9496 9497 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9498 QualType RetType = Context.getLValueReferenceType(ArgType); 9499 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9500 if (Const) 9501 ArgType = ArgType.withConst(); 9502 ArgType = Context.getLValueReferenceType(ArgType); 9503 9504 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9505 CXXCopyAssignment, 9506 Const); 9507 9508 // An implicitly-declared copy assignment operator is an inline public 9509 // member of its class. 9510 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9511 SourceLocation ClassLoc = ClassDecl->getLocation(); 9512 DeclarationNameInfo NameInfo(Name, ClassLoc); 9513 CXXMethodDecl *CopyAssignment = 9514 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9515 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9516 /*isInline=*/true, Constexpr, SourceLocation()); 9517 CopyAssignment->setAccess(AS_public); 9518 CopyAssignment->setDefaulted(); 9519 CopyAssignment->setImplicit(); 9520 9521 // Build an exception specification pointing back at this member. 9522 FunctionProtoType::ExtProtoInfo EPI = 9523 getImplicitMethodEPI(*this, CopyAssignment); 9524 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9525 9526 // Add the parameter to the operator. 9527 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9528 ClassLoc, ClassLoc, 9529 /*Id=*/nullptr, ArgType, 9530 /*TInfo=*/nullptr, SC_None, 9531 nullptr); 9532 CopyAssignment->setParams(FromParam); 9533 9534 AddOverriddenMethods(ClassDecl, CopyAssignment); 9535 9536 CopyAssignment->setTrivial( 9537 ClassDecl->needsOverloadResolutionForCopyAssignment() 9538 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9539 : ClassDecl->hasTrivialCopyAssignment()); 9540 9541 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9542 SetDeclDeleted(CopyAssignment, ClassLoc); 9543 9544 // Note that we have added this copy-assignment operator. 9545 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9546 9547 if (Scope *S = getScopeForContext(ClassDecl)) 9548 PushOnScopeChains(CopyAssignment, S, false); 9549 ClassDecl->addDecl(CopyAssignment); 9550 9551 return CopyAssignment; 9552 } 9553 9554 /// Diagnose an implicit copy operation for a class which is odr-used, but 9555 /// which is deprecated because the class has a user-declared copy constructor, 9556 /// copy assignment operator, or destructor. 9557 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9558 SourceLocation UseLoc) { 9559 assert(CopyOp->isImplicit()); 9560 9561 CXXRecordDecl *RD = CopyOp->getParent(); 9562 CXXMethodDecl *UserDeclaredOperation = nullptr; 9563 9564 // In Microsoft mode, assignment operations don't affect constructors and 9565 // vice versa. 9566 if (RD->hasUserDeclaredDestructor()) { 9567 UserDeclaredOperation = RD->getDestructor(); 9568 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9569 RD->hasUserDeclaredCopyConstructor() && 9570 !S.getLangOpts().MSVCCompat) { 9571 // Find any user-declared copy constructor. 9572 for (auto *I : RD->ctors()) { 9573 if (I->isCopyConstructor()) { 9574 UserDeclaredOperation = I; 9575 break; 9576 } 9577 } 9578 assert(UserDeclaredOperation); 9579 } else if (isa<CXXConstructorDecl>(CopyOp) && 9580 RD->hasUserDeclaredCopyAssignment() && 9581 !S.getLangOpts().MSVCCompat) { 9582 // Find any user-declared move assignment operator. 9583 for (auto *I : RD->methods()) { 9584 if (I->isCopyAssignmentOperator()) { 9585 UserDeclaredOperation = I; 9586 break; 9587 } 9588 } 9589 assert(UserDeclaredOperation); 9590 } 9591 9592 if (UserDeclaredOperation) { 9593 S.Diag(UserDeclaredOperation->getLocation(), 9594 diag::warn_deprecated_copy_operation) 9595 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9596 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9597 S.Diag(UseLoc, diag::note_member_synthesized_at) 9598 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9599 : Sema::CXXCopyAssignment) 9600 << RD; 9601 } 9602 } 9603 9604 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9605 CXXMethodDecl *CopyAssignOperator) { 9606 assert((CopyAssignOperator->isDefaulted() && 9607 CopyAssignOperator->isOverloadedOperator() && 9608 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9609 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9610 !CopyAssignOperator->isDeleted()) && 9611 "DefineImplicitCopyAssignment called for wrong function"); 9612 9613 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9614 9615 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9616 CopyAssignOperator->setInvalidDecl(); 9617 return; 9618 } 9619 9620 // C++11 [class.copy]p18: 9621 // The [definition of an implicitly declared copy assignment operator] is 9622 // deprecated if the class has a user-declared copy constructor or a 9623 // user-declared destructor. 9624 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9625 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9626 9627 CopyAssignOperator->markUsed(Context); 9628 9629 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9630 DiagnosticErrorTrap Trap(Diags); 9631 9632 // C++0x [class.copy]p30: 9633 // The implicitly-defined or explicitly-defaulted copy assignment operator 9634 // for a non-union class X performs memberwise copy assignment of its 9635 // subobjects. The direct base classes of X are assigned first, in the 9636 // order of their declaration in the base-specifier-list, and then the 9637 // immediate non-static data members of X are assigned, in the order in 9638 // which they were declared in the class definition. 9639 9640 // The statements that form the synthesized function body. 9641 SmallVector<Stmt*, 8> Statements; 9642 9643 // The parameter for the "other" object, which we are copying from. 9644 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9645 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9646 QualType OtherRefType = Other->getType(); 9647 if (const LValueReferenceType *OtherRef 9648 = OtherRefType->getAs<LValueReferenceType>()) { 9649 OtherRefType = OtherRef->getPointeeType(); 9650 OtherQuals = OtherRefType.getQualifiers(); 9651 } 9652 9653 // Our location for everything implicitly-generated. 9654 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 9655 ? CopyAssignOperator->getLocEnd() 9656 : CopyAssignOperator->getLocation(); 9657 9658 // Builds a DeclRefExpr for the "other" object. 9659 RefBuilder OtherRef(Other, OtherRefType); 9660 9661 // Builds the "this" pointer. 9662 ThisBuilder This; 9663 9664 // Assign base classes. 9665 bool Invalid = false; 9666 for (auto &Base : ClassDecl->bases()) { 9667 // Form the assignment: 9668 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9669 QualType BaseType = Base.getType().getUnqualifiedType(); 9670 if (!BaseType->isRecordType()) { 9671 Invalid = true; 9672 continue; 9673 } 9674 9675 CXXCastPath BasePath; 9676 BasePath.push_back(&Base); 9677 9678 // Construct the "from" expression, which is an implicit cast to the 9679 // appropriately-qualified base type. 9680 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9681 VK_LValue, BasePath); 9682 9683 // Dereference "this". 9684 DerefBuilder DerefThis(This); 9685 CastBuilder To(DerefThis, 9686 Context.getCVRQualifiedType( 9687 BaseType, CopyAssignOperator->getTypeQualifiers()), 9688 VK_LValue, BasePath); 9689 9690 // Build the copy. 9691 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9692 To, From, 9693 /*CopyingBaseSubobject=*/true, 9694 /*Copying=*/true); 9695 if (Copy.isInvalid()) { 9696 Diag(CurrentLocation, diag::note_member_synthesized_at) 9697 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9698 CopyAssignOperator->setInvalidDecl(); 9699 return; 9700 } 9701 9702 // Success! Record the copy. 9703 Statements.push_back(Copy.getAs<Expr>()); 9704 } 9705 9706 // Assign non-static members. 9707 for (auto *Field : ClassDecl->fields()) { 9708 if (Field->isUnnamedBitfield()) 9709 continue; 9710 9711 if (Field->isInvalidDecl()) { 9712 Invalid = true; 9713 continue; 9714 } 9715 9716 // Check for members of reference type; we can't copy those. 9717 if (Field->getType()->isReferenceType()) { 9718 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9719 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9720 Diag(Field->getLocation(), diag::note_declared_at); 9721 Diag(CurrentLocation, diag::note_member_synthesized_at) 9722 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9723 Invalid = true; 9724 continue; 9725 } 9726 9727 // Check for members of const-qualified, non-class type. 9728 QualType BaseType = Context.getBaseElementType(Field->getType()); 9729 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9730 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9731 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9732 Diag(Field->getLocation(), diag::note_declared_at); 9733 Diag(CurrentLocation, diag::note_member_synthesized_at) 9734 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9735 Invalid = true; 9736 continue; 9737 } 9738 9739 // Suppress assigning zero-width bitfields. 9740 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9741 continue; 9742 9743 QualType FieldType = Field->getType().getNonReferenceType(); 9744 if (FieldType->isIncompleteArrayType()) { 9745 assert(ClassDecl->hasFlexibleArrayMember() && 9746 "Incomplete array type is not valid"); 9747 continue; 9748 } 9749 9750 // Build references to the field in the object we're copying from and to. 9751 CXXScopeSpec SS; // Intentionally empty 9752 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9753 LookupMemberName); 9754 MemberLookup.addDecl(Field); 9755 MemberLookup.resolveKind(); 9756 9757 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9758 9759 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9760 9761 // Build the copy of this field. 9762 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9763 To, From, 9764 /*CopyingBaseSubobject=*/false, 9765 /*Copying=*/true); 9766 if (Copy.isInvalid()) { 9767 Diag(CurrentLocation, diag::note_member_synthesized_at) 9768 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9769 CopyAssignOperator->setInvalidDecl(); 9770 return; 9771 } 9772 9773 // Success! Record the copy. 9774 Statements.push_back(Copy.getAs<Stmt>()); 9775 } 9776 9777 if (!Invalid) { 9778 // Add a "return *this;" 9779 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9780 9781 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 9782 if (Return.isInvalid()) 9783 Invalid = true; 9784 else { 9785 Statements.push_back(Return.getAs<Stmt>()); 9786 9787 if (Trap.hasErrorOccurred()) { 9788 Diag(CurrentLocation, diag::note_member_synthesized_at) 9789 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9790 Invalid = true; 9791 } 9792 } 9793 } 9794 9795 if (Invalid) { 9796 CopyAssignOperator->setInvalidDecl(); 9797 return; 9798 } 9799 9800 StmtResult Body; 9801 { 9802 CompoundScopeRAII CompoundScope(*this); 9803 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9804 /*isStmtExpr=*/false); 9805 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9806 } 9807 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 9808 9809 if (ASTMutationListener *L = getASTMutationListener()) { 9810 L->CompletedImplicitDefinition(CopyAssignOperator); 9811 } 9812 } 9813 9814 Sema::ImplicitExceptionSpecification 9815 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9816 CXXRecordDecl *ClassDecl = MD->getParent(); 9817 9818 ImplicitExceptionSpecification ExceptSpec(*this); 9819 if (ClassDecl->isInvalidDecl()) 9820 return ExceptSpec; 9821 9822 // C++0x [except.spec]p14: 9823 // An implicitly declared special member function (Clause 12) shall have an 9824 // exception-specification. [...] 9825 9826 // It is unspecified whether or not an implicit move assignment operator 9827 // attempts to deduplicate calls to assignment operators of virtual bases are 9828 // made. As such, this exception specification is effectively unspecified. 9829 // Based on a similar decision made for constness in C++0x, we're erring on 9830 // the side of assuming such calls to be made regardless of whether they 9831 // actually happen. 9832 // Note that a move constructor is not implicitly declared when there are 9833 // virtual bases, but it can still be user-declared and explicitly defaulted. 9834 for (const auto &Base : ClassDecl->bases()) { 9835 if (Base.isVirtual()) 9836 continue; 9837 9838 CXXRecordDecl *BaseClassDecl 9839 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9840 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9841 0, false, 0)) 9842 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9843 } 9844 9845 for (const auto &Base : ClassDecl->vbases()) { 9846 CXXRecordDecl *BaseClassDecl 9847 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9848 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9849 0, false, 0)) 9850 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9851 } 9852 9853 for (const auto *Field : ClassDecl->fields()) { 9854 QualType FieldType = Context.getBaseElementType(Field->getType()); 9855 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9856 if (CXXMethodDecl *MoveAssign = 9857 LookupMovingAssignment(FieldClassDecl, 9858 FieldType.getCVRQualifiers(), 9859 false, 0)) 9860 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9861 } 9862 } 9863 9864 return ExceptSpec; 9865 } 9866 9867 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9868 assert(ClassDecl->needsImplicitMoveAssignment()); 9869 9870 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9871 if (DSM.isAlreadyBeingDeclared()) 9872 return nullptr; 9873 9874 // Note: The following rules are largely analoguous to the move 9875 // constructor rules. 9876 9877 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9878 QualType RetType = Context.getLValueReferenceType(ArgType); 9879 ArgType = Context.getRValueReferenceType(ArgType); 9880 9881 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9882 CXXMoveAssignment, 9883 false); 9884 9885 // An implicitly-declared move assignment operator is an inline public 9886 // member of its class. 9887 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9888 SourceLocation ClassLoc = ClassDecl->getLocation(); 9889 DeclarationNameInfo NameInfo(Name, ClassLoc); 9890 CXXMethodDecl *MoveAssignment = 9891 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9892 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9893 /*isInline=*/true, Constexpr, SourceLocation()); 9894 MoveAssignment->setAccess(AS_public); 9895 MoveAssignment->setDefaulted(); 9896 MoveAssignment->setImplicit(); 9897 9898 // Build an exception specification pointing back at this member. 9899 FunctionProtoType::ExtProtoInfo EPI = 9900 getImplicitMethodEPI(*this, MoveAssignment); 9901 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9902 9903 // Add the parameter to the operator. 9904 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9905 ClassLoc, ClassLoc, 9906 /*Id=*/nullptr, ArgType, 9907 /*TInfo=*/nullptr, SC_None, 9908 nullptr); 9909 MoveAssignment->setParams(FromParam); 9910 9911 AddOverriddenMethods(ClassDecl, MoveAssignment); 9912 9913 MoveAssignment->setTrivial( 9914 ClassDecl->needsOverloadResolutionForMoveAssignment() 9915 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9916 : ClassDecl->hasTrivialMoveAssignment()); 9917 9918 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9919 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 9920 SetDeclDeleted(MoveAssignment, ClassLoc); 9921 } 9922 9923 // Note that we have added this copy-assignment operator. 9924 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9925 9926 if (Scope *S = getScopeForContext(ClassDecl)) 9927 PushOnScopeChains(MoveAssignment, S, false); 9928 ClassDecl->addDecl(MoveAssignment); 9929 9930 return MoveAssignment; 9931 } 9932 9933 /// Check if we're implicitly defining a move assignment operator for a class 9934 /// with virtual bases. Such a move assignment might move-assign the virtual 9935 /// base multiple times. 9936 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 9937 SourceLocation CurrentLocation) { 9938 assert(!Class->isDependentContext() && "should not define dependent move"); 9939 9940 // Only a virtual base could get implicitly move-assigned multiple times. 9941 // Only a non-trivial move assignment can observe this. We only want to 9942 // diagnose if we implicitly define an assignment operator that assigns 9943 // two base classes, both of which move-assign the same virtual base. 9944 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 9945 Class->getNumBases() < 2) 9946 return; 9947 9948 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 9949 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 9950 VBaseMap VBases; 9951 9952 for (auto &BI : Class->bases()) { 9953 Worklist.push_back(&BI); 9954 while (!Worklist.empty()) { 9955 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 9956 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 9957 9958 // If the base has no non-trivial move assignment operators, 9959 // we don't care about moves from it. 9960 if (!Base->hasNonTrivialMoveAssignment()) 9961 continue; 9962 9963 // If there's nothing virtual here, skip it. 9964 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 9965 continue; 9966 9967 // If we're not actually going to call a move assignment for this base, 9968 // or the selected move assignment is trivial, skip it. 9969 Sema::SpecialMemberOverloadResult *SMOR = 9970 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 9971 /*ConstArg*/false, /*VolatileArg*/false, 9972 /*RValueThis*/true, /*ConstThis*/false, 9973 /*VolatileThis*/false); 9974 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 9975 !SMOR->getMethod()->isMoveAssignmentOperator()) 9976 continue; 9977 9978 if (BaseSpec->isVirtual()) { 9979 // We're going to move-assign this virtual base, and its move 9980 // assignment operator is not trivial. If this can happen for 9981 // multiple distinct direct bases of Class, diagnose it. (If it 9982 // only happens in one base, we'll diagnose it when synthesizing 9983 // that base class's move assignment operator.) 9984 CXXBaseSpecifier *&Existing = 9985 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 9986 .first->second; 9987 if (Existing && Existing != &BI) { 9988 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 9989 << Class << Base; 9990 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 9991 << (Base->getCanonicalDecl() == 9992 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9993 << Base << Existing->getType() << Existing->getSourceRange(); 9994 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 9995 << (Base->getCanonicalDecl() == 9996 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9997 << Base << BI.getType() << BaseSpec->getSourceRange(); 9998 9999 // Only diagnose each vbase once. 10000 Existing = nullptr; 10001 } 10002 } else { 10003 // Only walk over bases that have defaulted move assignment operators. 10004 // We assume that any user-provided move assignment operator handles 10005 // the multiple-moves-of-vbase case itself somehow. 10006 if (!SMOR->getMethod()->isDefaulted()) 10007 continue; 10008 10009 // We're going to move the base classes of Base. Add them to the list. 10010 for (auto &BI : Base->bases()) 10011 Worklist.push_back(&BI); 10012 } 10013 } 10014 } 10015 } 10016 10017 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10018 CXXMethodDecl *MoveAssignOperator) { 10019 assert((MoveAssignOperator->isDefaulted() && 10020 MoveAssignOperator->isOverloadedOperator() && 10021 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10022 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10023 !MoveAssignOperator->isDeleted()) && 10024 "DefineImplicitMoveAssignment called for wrong function"); 10025 10026 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10027 10028 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10029 MoveAssignOperator->setInvalidDecl(); 10030 return; 10031 } 10032 10033 MoveAssignOperator->markUsed(Context); 10034 10035 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10036 DiagnosticErrorTrap Trap(Diags); 10037 10038 // C++0x [class.copy]p28: 10039 // The implicitly-defined or move assignment operator for a non-union class 10040 // X performs memberwise move assignment of its subobjects. The direct base 10041 // classes of X are assigned first, in the order of their declaration in the 10042 // base-specifier-list, and then the immediate non-static data members of X 10043 // are assigned, in the order in which they were declared in the class 10044 // definition. 10045 10046 // Issue a warning if our implicit move assignment operator will move 10047 // from a virtual base more than once. 10048 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10049 10050 // The statements that form the synthesized function body. 10051 SmallVector<Stmt*, 8> Statements; 10052 10053 // The parameter for the "other" object, which we are move from. 10054 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10055 QualType OtherRefType = Other->getType()-> 10056 getAs<RValueReferenceType>()->getPointeeType(); 10057 assert(!OtherRefType.getQualifiers() && 10058 "Bad argument type of defaulted move assignment"); 10059 10060 // Our location for everything implicitly-generated. 10061 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10062 ? MoveAssignOperator->getLocEnd() 10063 : MoveAssignOperator->getLocation(); 10064 10065 // Builds a reference to the "other" object. 10066 RefBuilder OtherRef(Other, OtherRefType); 10067 // Cast to rvalue. 10068 MoveCastBuilder MoveOther(OtherRef); 10069 10070 // Builds the "this" pointer. 10071 ThisBuilder This; 10072 10073 // Assign base classes. 10074 bool Invalid = false; 10075 for (auto &Base : ClassDecl->bases()) { 10076 // C++11 [class.copy]p28: 10077 // It is unspecified whether subobjects representing virtual base classes 10078 // are assigned more than once by the implicitly-defined copy assignment 10079 // operator. 10080 // FIXME: Do not assign to a vbase that will be assigned by some other base 10081 // class. For a move-assignment, this can result in the vbase being moved 10082 // multiple times. 10083 10084 // Form the assignment: 10085 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10086 QualType BaseType = Base.getType().getUnqualifiedType(); 10087 if (!BaseType->isRecordType()) { 10088 Invalid = true; 10089 continue; 10090 } 10091 10092 CXXCastPath BasePath; 10093 BasePath.push_back(&Base); 10094 10095 // Construct the "from" expression, which is an implicit cast to the 10096 // appropriately-qualified base type. 10097 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10098 10099 // Dereference "this". 10100 DerefBuilder DerefThis(This); 10101 10102 // Implicitly cast "this" to the appropriately-qualified base type. 10103 CastBuilder To(DerefThis, 10104 Context.getCVRQualifiedType( 10105 BaseType, MoveAssignOperator->getTypeQualifiers()), 10106 VK_LValue, BasePath); 10107 10108 // Build the move. 10109 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10110 To, From, 10111 /*CopyingBaseSubobject=*/true, 10112 /*Copying=*/false); 10113 if (Move.isInvalid()) { 10114 Diag(CurrentLocation, diag::note_member_synthesized_at) 10115 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10116 MoveAssignOperator->setInvalidDecl(); 10117 return; 10118 } 10119 10120 // Success! Record the move. 10121 Statements.push_back(Move.getAs<Expr>()); 10122 } 10123 10124 // Assign non-static members. 10125 for (auto *Field : ClassDecl->fields()) { 10126 if (Field->isUnnamedBitfield()) 10127 continue; 10128 10129 if (Field->isInvalidDecl()) { 10130 Invalid = true; 10131 continue; 10132 } 10133 10134 // Check for members of reference type; we can't move those. 10135 if (Field->getType()->isReferenceType()) { 10136 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10137 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10138 Diag(Field->getLocation(), diag::note_declared_at); 10139 Diag(CurrentLocation, diag::note_member_synthesized_at) 10140 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10141 Invalid = true; 10142 continue; 10143 } 10144 10145 // Check for members of const-qualified, non-class type. 10146 QualType BaseType = Context.getBaseElementType(Field->getType()); 10147 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10148 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10149 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10150 Diag(Field->getLocation(), diag::note_declared_at); 10151 Diag(CurrentLocation, diag::note_member_synthesized_at) 10152 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10153 Invalid = true; 10154 continue; 10155 } 10156 10157 // Suppress assigning zero-width bitfields. 10158 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10159 continue; 10160 10161 QualType FieldType = Field->getType().getNonReferenceType(); 10162 if (FieldType->isIncompleteArrayType()) { 10163 assert(ClassDecl->hasFlexibleArrayMember() && 10164 "Incomplete array type is not valid"); 10165 continue; 10166 } 10167 10168 // Build references to the field in the object we're copying from and to. 10169 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10170 LookupMemberName); 10171 MemberLookup.addDecl(Field); 10172 MemberLookup.resolveKind(); 10173 MemberBuilder From(MoveOther, OtherRefType, 10174 /*IsArrow=*/false, MemberLookup); 10175 MemberBuilder To(This, getCurrentThisType(), 10176 /*IsArrow=*/true, MemberLookup); 10177 10178 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10179 "Member reference with rvalue base must be rvalue except for reference " 10180 "members, which aren't allowed for move assignment."); 10181 10182 // Build the move of this field. 10183 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10184 To, From, 10185 /*CopyingBaseSubobject=*/false, 10186 /*Copying=*/false); 10187 if (Move.isInvalid()) { 10188 Diag(CurrentLocation, diag::note_member_synthesized_at) 10189 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10190 MoveAssignOperator->setInvalidDecl(); 10191 return; 10192 } 10193 10194 // Success! Record the copy. 10195 Statements.push_back(Move.getAs<Stmt>()); 10196 } 10197 10198 if (!Invalid) { 10199 // Add a "return *this;" 10200 ExprResult ThisObj = 10201 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10202 10203 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10204 if (Return.isInvalid()) 10205 Invalid = true; 10206 else { 10207 Statements.push_back(Return.getAs<Stmt>()); 10208 10209 if (Trap.hasErrorOccurred()) { 10210 Diag(CurrentLocation, diag::note_member_synthesized_at) 10211 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10212 Invalid = true; 10213 } 10214 } 10215 } 10216 10217 if (Invalid) { 10218 MoveAssignOperator->setInvalidDecl(); 10219 return; 10220 } 10221 10222 StmtResult Body; 10223 { 10224 CompoundScopeRAII CompoundScope(*this); 10225 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10226 /*isStmtExpr=*/false); 10227 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10228 } 10229 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10230 10231 if (ASTMutationListener *L = getASTMutationListener()) { 10232 L->CompletedImplicitDefinition(MoveAssignOperator); 10233 } 10234 } 10235 10236 Sema::ImplicitExceptionSpecification 10237 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10238 CXXRecordDecl *ClassDecl = MD->getParent(); 10239 10240 ImplicitExceptionSpecification ExceptSpec(*this); 10241 if (ClassDecl->isInvalidDecl()) 10242 return ExceptSpec; 10243 10244 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10245 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10246 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10247 10248 // C++ [except.spec]p14: 10249 // An implicitly declared special member function (Clause 12) shall have an 10250 // exception-specification. [...] 10251 for (const auto &Base : ClassDecl->bases()) { 10252 // Virtual bases are handled below. 10253 if (Base.isVirtual()) 10254 continue; 10255 10256 CXXRecordDecl *BaseClassDecl 10257 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10258 if (CXXConstructorDecl *CopyConstructor = 10259 LookupCopyingConstructor(BaseClassDecl, Quals)) 10260 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10261 } 10262 for (const auto &Base : ClassDecl->vbases()) { 10263 CXXRecordDecl *BaseClassDecl 10264 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10265 if (CXXConstructorDecl *CopyConstructor = 10266 LookupCopyingConstructor(BaseClassDecl, Quals)) 10267 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10268 } 10269 for (const auto *Field : ClassDecl->fields()) { 10270 QualType FieldType = Context.getBaseElementType(Field->getType()); 10271 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10272 if (CXXConstructorDecl *CopyConstructor = 10273 LookupCopyingConstructor(FieldClassDecl, 10274 Quals | FieldType.getCVRQualifiers())) 10275 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10276 } 10277 } 10278 10279 return ExceptSpec; 10280 } 10281 10282 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10283 CXXRecordDecl *ClassDecl) { 10284 // C++ [class.copy]p4: 10285 // If the class definition does not explicitly declare a copy 10286 // constructor, one is declared implicitly. 10287 assert(ClassDecl->needsImplicitCopyConstructor()); 10288 10289 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10290 if (DSM.isAlreadyBeingDeclared()) 10291 return nullptr; 10292 10293 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10294 QualType ArgType = ClassType; 10295 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10296 if (Const) 10297 ArgType = ArgType.withConst(); 10298 ArgType = Context.getLValueReferenceType(ArgType); 10299 10300 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10301 CXXCopyConstructor, 10302 Const); 10303 10304 DeclarationName Name 10305 = Context.DeclarationNames.getCXXConstructorName( 10306 Context.getCanonicalType(ClassType)); 10307 SourceLocation ClassLoc = ClassDecl->getLocation(); 10308 DeclarationNameInfo NameInfo(Name, ClassLoc); 10309 10310 // An implicitly-declared copy constructor is an inline public 10311 // member of its class. 10312 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10313 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10314 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10315 Constexpr); 10316 CopyConstructor->setAccess(AS_public); 10317 CopyConstructor->setDefaulted(); 10318 10319 // Build an exception specification pointing back at this member. 10320 FunctionProtoType::ExtProtoInfo EPI = 10321 getImplicitMethodEPI(*this, CopyConstructor); 10322 CopyConstructor->setType( 10323 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10324 10325 // Add the parameter to the constructor. 10326 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10327 ClassLoc, ClassLoc, 10328 /*IdentifierInfo=*/nullptr, 10329 ArgType, /*TInfo=*/nullptr, 10330 SC_None, nullptr); 10331 CopyConstructor->setParams(FromParam); 10332 10333 CopyConstructor->setTrivial( 10334 ClassDecl->needsOverloadResolutionForCopyConstructor() 10335 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10336 : ClassDecl->hasTrivialCopyConstructor()); 10337 10338 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10339 SetDeclDeleted(CopyConstructor, ClassLoc); 10340 10341 // Note that we have declared this constructor. 10342 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10343 10344 if (Scope *S = getScopeForContext(ClassDecl)) 10345 PushOnScopeChains(CopyConstructor, S, false); 10346 ClassDecl->addDecl(CopyConstructor); 10347 10348 return CopyConstructor; 10349 } 10350 10351 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10352 CXXConstructorDecl *CopyConstructor) { 10353 assert((CopyConstructor->isDefaulted() && 10354 CopyConstructor->isCopyConstructor() && 10355 !CopyConstructor->doesThisDeclarationHaveABody() && 10356 !CopyConstructor->isDeleted()) && 10357 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10358 10359 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10360 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10361 10362 // C++11 [class.copy]p7: 10363 // The [definition of an implicitly declared copy constructor] is 10364 // deprecated if the class has a user-declared copy assignment operator 10365 // or a user-declared destructor. 10366 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10367 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10368 10369 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10370 DiagnosticErrorTrap Trap(Diags); 10371 10372 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10373 Trap.hasErrorOccurred()) { 10374 Diag(CurrentLocation, diag::note_member_synthesized_at) 10375 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10376 CopyConstructor->setInvalidDecl(); 10377 } else { 10378 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10379 ? CopyConstructor->getLocEnd() 10380 : CopyConstructor->getLocation(); 10381 Sema::CompoundScopeRAII CompoundScope(*this); 10382 CopyConstructor->setBody( 10383 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10384 } 10385 10386 CopyConstructor->markUsed(Context); 10387 if (ASTMutationListener *L = getASTMutationListener()) { 10388 L->CompletedImplicitDefinition(CopyConstructor); 10389 } 10390 } 10391 10392 Sema::ImplicitExceptionSpecification 10393 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10394 CXXRecordDecl *ClassDecl = MD->getParent(); 10395 10396 // C++ [except.spec]p14: 10397 // An implicitly declared special member function (Clause 12) shall have an 10398 // exception-specification. [...] 10399 ImplicitExceptionSpecification ExceptSpec(*this); 10400 if (ClassDecl->isInvalidDecl()) 10401 return ExceptSpec; 10402 10403 // Direct base-class constructors. 10404 for (const auto &B : ClassDecl->bases()) { 10405 if (B.isVirtual()) // Handled below. 10406 continue; 10407 10408 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10409 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10410 CXXConstructorDecl *Constructor = 10411 LookupMovingConstructor(BaseClassDecl, 0); 10412 // If this is a deleted function, add it anyway. This might be conformant 10413 // with the standard. This might not. I'm not sure. It might not matter. 10414 if (Constructor) 10415 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10416 } 10417 } 10418 10419 // Virtual base-class constructors. 10420 for (const auto &B : ClassDecl->vbases()) { 10421 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10422 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10423 CXXConstructorDecl *Constructor = 10424 LookupMovingConstructor(BaseClassDecl, 0); 10425 // If this is a deleted function, add it anyway. This might be conformant 10426 // with the standard. This might not. I'm not sure. It might not matter. 10427 if (Constructor) 10428 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10429 } 10430 } 10431 10432 // Field constructors. 10433 for (const auto *F : ClassDecl->fields()) { 10434 QualType FieldType = Context.getBaseElementType(F->getType()); 10435 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10436 CXXConstructorDecl *Constructor = 10437 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10438 // If this is a deleted function, add it anyway. This might be conformant 10439 // with the standard. This might not. I'm not sure. It might not matter. 10440 // In particular, the problem is that this function never gets called. It 10441 // might just be ill-formed because this function attempts to refer to 10442 // a deleted function here. 10443 if (Constructor) 10444 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10445 } 10446 } 10447 10448 return ExceptSpec; 10449 } 10450 10451 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10452 CXXRecordDecl *ClassDecl) { 10453 assert(ClassDecl->needsImplicitMoveConstructor()); 10454 10455 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10456 if (DSM.isAlreadyBeingDeclared()) 10457 return nullptr; 10458 10459 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10460 QualType ArgType = Context.getRValueReferenceType(ClassType); 10461 10462 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10463 CXXMoveConstructor, 10464 false); 10465 10466 DeclarationName Name 10467 = Context.DeclarationNames.getCXXConstructorName( 10468 Context.getCanonicalType(ClassType)); 10469 SourceLocation ClassLoc = ClassDecl->getLocation(); 10470 DeclarationNameInfo NameInfo(Name, ClassLoc); 10471 10472 // C++11 [class.copy]p11: 10473 // An implicitly-declared copy/move constructor is an inline public 10474 // member of its class. 10475 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10476 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10477 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10478 Constexpr); 10479 MoveConstructor->setAccess(AS_public); 10480 MoveConstructor->setDefaulted(); 10481 10482 // Build an exception specification pointing back at this member. 10483 FunctionProtoType::ExtProtoInfo EPI = 10484 getImplicitMethodEPI(*this, MoveConstructor); 10485 MoveConstructor->setType( 10486 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10487 10488 // Add the parameter to the constructor. 10489 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10490 ClassLoc, ClassLoc, 10491 /*IdentifierInfo=*/nullptr, 10492 ArgType, /*TInfo=*/nullptr, 10493 SC_None, nullptr); 10494 MoveConstructor->setParams(FromParam); 10495 10496 MoveConstructor->setTrivial( 10497 ClassDecl->needsOverloadResolutionForMoveConstructor() 10498 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10499 : ClassDecl->hasTrivialMoveConstructor()); 10500 10501 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10502 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10503 SetDeclDeleted(MoveConstructor, ClassLoc); 10504 } 10505 10506 // Note that we have declared this constructor. 10507 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10508 10509 if (Scope *S = getScopeForContext(ClassDecl)) 10510 PushOnScopeChains(MoveConstructor, S, false); 10511 ClassDecl->addDecl(MoveConstructor); 10512 10513 return MoveConstructor; 10514 } 10515 10516 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10517 CXXConstructorDecl *MoveConstructor) { 10518 assert((MoveConstructor->isDefaulted() && 10519 MoveConstructor->isMoveConstructor() && 10520 !MoveConstructor->doesThisDeclarationHaveABody() && 10521 !MoveConstructor->isDeleted()) && 10522 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10523 10524 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10525 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10526 10527 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10528 DiagnosticErrorTrap Trap(Diags); 10529 10530 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10531 Trap.hasErrorOccurred()) { 10532 Diag(CurrentLocation, diag::note_member_synthesized_at) 10533 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10534 MoveConstructor->setInvalidDecl(); 10535 } else { 10536 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 10537 ? MoveConstructor->getLocEnd() 10538 : MoveConstructor->getLocation(); 10539 Sema::CompoundScopeRAII CompoundScope(*this); 10540 MoveConstructor->setBody(ActOnCompoundStmt( 10541 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 10542 } 10543 10544 MoveConstructor->markUsed(Context); 10545 10546 if (ASTMutationListener *L = getASTMutationListener()) { 10547 L->CompletedImplicitDefinition(MoveConstructor); 10548 } 10549 } 10550 10551 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10552 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10553 } 10554 10555 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10556 SourceLocation CurrentLocation, 10557 CXXConversionDecl *Conv) { 10558 CXXRecordDecl *Lambda = Conv->getParent(); 10559 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10560 // If we are defining a specialization of a conversion to function-ptr 10561 // cache the deduced template arguments for this specialization 10562 // so that we can use them to retrieve the corresponding call-operator 10563 // and static-invoker. 10564 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 10565 10566 // Retrieve the corresponding call-operator specialization. 10567 if (Lambda->isGenericLambda()) { 10568 assert(Conv->isFunctionTemplateSpecialization()); 10569 FunctionTemplateDecl *CallOpTemplate = 10570 CallOp->getDescribedFunctionTemplate(); 10571 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10572 void *InsertPos = nullptr; 10573 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10574 DeducedTemplateArgs->asArray(), 10575 InsertPos); 10576 assert(CallOpSpec && 10577 "Conversion operator must have a corresponding call operator"); 10578 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10579 } 10580 // Mark the call operator referenced (and add to pending instantiations 10581 // if necessary). 10582 // For both the conversion and static-invoker template specializations 10583 // we construct their body's in this function, so no need to add them 10584 // to the PendingInstantiations. 10585 MarkFunctionReferenced(CurrentLocation, CallOp); 10586 10587 SynthesizedFunctionScope Scope(*this, Conv); 10588 DiagnosticErrorTrap Trap(Diags); 10589 10590 // Retrieve the static invoker... 10591 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10592 // ... and get the corresponding specialization for a generic lambda. 10593 if (Lambda->isGenericLambda()) { 10594 assert(DeducedTemplateArgs && 10595 "Must have deduced template arguments from Conversion Operator"); 10596 FunctionTemplateDecl *InvokeTemplate = 10597 Invoker->getDescribedFunctionTemplate(); 10598 void *InsertPos = nullptr; 10599 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10600 DeducedTemplateArgs->asArray(), 10601 InsertPos); 10602 assert(InvokeSpec && 10603 "Must have a corresponding static invoker specialization"); 10604 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10605 } 10606 // Construct the body of the conversion function { return __invoke; }. 10607 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10608 VK_LValue, Conv->getLocation()).get(); 10609 assert(FunctionRef && "Can't refer to __invoke function?"); 10610 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 10611 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10612 Conv->getLocation(), 10613 Conv->getLocation())); 10614 10615 Conv->markUsed(Context); 10616 Conv->setReferenced(); 10617 10618 // Fill in the __invoke function with a dummy implementation. IR generation 10619 // will fill in the actual details. 10620 Invoker->markUsed(Context); 10621 Invoker->setReferenced(); 10622 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10623 10624 if (ASTMutationListener *L = getASTMutationListener()) { 10625 L->CompletedImplicitDefinition(Conv); 10626 L->CompletedImplicitDefinition(Invoker); 10627 } 10628 } 10629 10630 10631 10632 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10633 SourceLocation CurrentLocation, 10634 CXXConversionDecl *Conv) 10635 { 10636 assert(!Conv->getParent()->isGenericLambda()); 10637 10638 Conv->markUsed(Context); 10639 10640 SynthesizedFunctionScope Scope(*this, Conv); 10641 DiagnosticErrorTrap Trap(Diags); 10642 10643 // Copy-initialize the lambda object as needed to capture it. 10644 Expr *This = ActOnCXXThis(CurrentLocation).get(); 10645 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 10646 10647 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10648 Conv->getLocation(), 10649 Conv, DerefThis); 10650 10651 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10652 // behavior. Note that only the general conversion function does this 10653 // (since it's unusable otherwise); in the case where we inline the 10654 // block literal, it has block literal lifetime semantics. 10655 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10656 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10657 CK_CopyAndAutoreleaseBlockObject, 10658 BuildBlock.get(), nullptr, VK_RValue); 10659 10660 if (BuildBlock.isInvalid()) { 10661 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10662 Conv->setInvalidDecl(); 10663 return; 10664 } 10665 10666 // Create the return statement that returns the block from the conversion 10667 // function. 10668 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 10669 if (Return.isInvalid()) { 10670 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10671 Conv->setInvalidDecl(); 10672 return; 10673 } 10674 10675 // Set the body of the conversion function. 10676 Stmt *ReturnS = Return.get(); 10677 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10678 Conv->getLocation(), 10679 Conv->getLocation())); 10680 10681 // We're done; notify the mutation listener, if any. 10682 if (ASTMutationListener *L = getASTMutationListener()) { 10683 L->CompletedImplicitDefinition(Conv); 10684 } 10685 } 10686 10687 /// \brief Determine whether the given list arguments contains exactly one 10688 /// "real" (non-default) argument. 10689 static bool hasOneRealArgument(MultiExprArg Args) { 10690 switch (Args.size()) { 10691 case 0: 10692 return false; 10693 10694 default: 10695 if (!Args[1]->isDefaultArgument()) 10696 return false; 10697 10698 // fall through 10699 case 1: 10700 return !Args[0]->isDefaultArgument(); 10701 } 10702 10703 return false; 10704 } 10705 10706 ExprResult 10707 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10708 CXXConstructorDecl *Constructor, 10709 MultiExprArg ExprArgs, 10710 bool HadMultipleCandidates, 10711 bool IsListInitialization, 10712 bool RequiresZeroInit, 10713 unsigned ConstructKind, 10714 SourceRange ParenRange) { 10715 bool Elidable = false; 10716 10717 // C++0x [class.copy]p34: 10718 // When certain criteria are met, an implementation is allowed to 10719 // omit the copy/move construction of a class object, even if the 10720 // copy/move constructor and/or destructor for the object have 10721 // side effects. [...] 10722 // - when a temporary class object that has not been bound to a 10723 // reference (12.2) would be copied/moved to a class object 10724 // with the same cv-unqualified type, the copy/move operation 10725 // can be omitted by constructing the temporary object 10726 // directly into the target of the omitted copy/move 10727 if (ConstructKind == CXXConstructExpr::CK_Complete && 10728 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10729 Expr *SubExpr = ExprArgs[0]; 10730 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10731 } 10732 10733 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10734 Elidable, ExprArgs, HadMultipleCandidates, 10735 IsListInitialization, RequiresZeroInit, 10736 ConstructKind, ParenRange); 10737 } 10738 10739 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10740 /// including handling of its default argument expressions. 10741 ExprResult 10742 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10743 CXXConstructorDecl *Constructor, bool Elidable, 10744 MultiExprArg ExprArgs, 10745 bool HadMultipleCandidates, 10746 bool IsListInitialization, 10747 bool RequiresZeroInit, 10748 unsigned ConstructKind, 10749 SourceRange ParenRange) { 10750 MarkFunctionReferenced(ConstructLoc, Constructor); 10751 return CXXConstructExpr::Create( 10752 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 10753 HadMultipleCandidates, IsListInitialization, RequiresZeroInit, 10754 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10755 ParenRange); 10756 } 10757 10758 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10759 if (VD->isInvalidDecl()) return; 10760 10761 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10762 if (ClassDecl->isInvalidDecl()) return; 10763 if (ClassDecl->hasIrrelevantDestructor()) return; 10764 if (ClassDecl->isDependentContext()) return; 10765 10766 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10767 MarkFunctionReferenced(VD->getLocation(), Destructor); 10768 CheckDestructorAccess(VD->getLocation(), Destructor, 10769 PDiag(diag::err_access_dtor_var) 10770 << VD->getDeclName() 10771 << VD->getType()); 10772 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10773 10774 if (Destructor->isTrivial()) return; 10775 if (!VD->hasGlobalStorage()) return; 10776 10777 // Emit warning for non-trivial dtor in global scope (a real global, 10778 // class-static, function-static). 10779 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10780 10781 // TODO: this should be re-enabled for static locals by !CXAAtExit 10782 if (!VD->isStaticLocal()) 10783 Diag(VD->getLocation(), diag::warn_global_destructor); 10784 } 10785 10786 /// \brief Given a constructor and the set of arguments provided for the 10787 /// constructor, convert the arguments and add any required default arguments 10788 /// to form a proper call to this constructor. 10789 /// 10790 /// \returns true if an error occurred, false otherwise. 10791 bool 10792 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10793 MultiExprArg ArgsPtr, 10794 SourceLocation Loc, 10795 SmallVectorImpl<Expr*> &ConvertedArgs, 10796 bool AllowExplicit, 10797 bool IsListInitialization) { 10798 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10799 unsigned NumArgs = ArgsPtr.size(); 10800 Expr **Args = ArgsPtr.data(); 10801 10802 const FunctionProtoType *Proto 10803 = Constructor->getType()->getAs<FunctionProtoType>(); 10804 assert(Proto && "Constructor without a prototype?"); 10805 unsigned NumParams = Proto->getNumParams(); 10806 10807 // If too few arguments are available, we'll fill in the rest with defaults. 10808 if (NumArgs < NumParams) 10809 ConvertedArgs.reserve(NumParams); 10810 else 10811 ConvertedArgs.reserve(NumArgs); 10812 10813 VariadicCallType CallType = 10814 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10815 SmallVector<Expr *, 8> AllArgs; 10816 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10817 Proto, 0, 10818 llvm::makeArrayRef(Args, NumArgs), 10819 AllArgs, 10820 CallType, AllowExplicit, 10821 IsListInitialization); 10822 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10823 10824 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10825 10826 CheckConstructorCall(Constructor, 10827 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10828 AllArgs.size()), 10829 Proto, Loc); 10830 10831 return Invalid; 10832 } 10833 10834 static inline bool 10835 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10836 const FunctionDecl *FnDecl) { 10837 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10838 if (isa<NamespaceDecl>(DC)) { 10839 return SemaRef.Diag(FnDecl->getLocation(), 10840 diag::err_operator_new_delete_declared_in_namespace) 10841 << FnDecl->getDeclName(); 10842 } 10843 10844 if (isa<TranslationUnitDecl>(DC) && 10845 FnDecl->getStorageClass() == SC_Static) { 10846 return SemaRef.Diag(FnDecl->getLocation(), 10847 diag::err_operator_new_delete_declared_static) 10848 << FnDecl->getDeclName(); 10849 } 10850 10851 return false; 10852 } 10853 10854 static inline bool 10855 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10856 CanQualType ExpectedResultType, 10857 CanQualType ExpectedFirstParamType, 10858 unsigned DependentParamTypeDiag, 10859 unsigned InvalidParamTypeDiag) { 10860 QualType ResultType = 10861 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 10862 10863 // Check that the result type is not dependent. 10864 if (ResultType->isDependentType()) 10865 return SemaRef.Diag(FnDecl->getLocation(), 10866 diag::err_operator_new_delete_dependent_result_type) 10867 << FnDecl->getDeclName() << ExpectedResultType; 10868 10869 // Check that the result type is what we expect. 10870 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10871 return SemaRef.Diag(FnDecl->getLocation(), 10872 diag::err_operator_new_delete_invalid_result_type) 10873 << FnDecl->getDeclName() << ExpectedResultType; 10874 10875 // A function template must have at least 2 parameters. 10876 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10877 return SemaRef.Diag(FnDecl->getLocation(), 10878 diag::err_operator_new_delete_template_too_few_parameters) 10879 << FnDecl->getDeclName(); 10880 10881 // The function decl must have at least 1 parameter. 10882 if (FnDecl->getNumParams() == 0) 10883 return SemaRef.Diag(FnDecl->getLocation(), 10884 diag::err_operator_new_delete_too_few_parameters) 10885 << FnDecl->getDeclName(); 10886 10887 // Check the first parameter type is not dependent. 10888 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10889 if (FirstParamType->isDependentType()) 10890 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10891 << FnDecl->getDeclName() << ExpectedFirstParamType; 10892 10893 // Check that the first parameter type is what we expect. 10894 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10895 ExpectedFirstParamType) 10896 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10897 << FnDecl->getDeclName() << ExpectedFirstParamType; 10898 10899 return false; 10900 } 10901 10902 static bool 10903 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10904 // C++ [basic.stc.dynamic.allocation]p1: 10905 // A program is ill-formed if an allocation function is declared in a 10906 // namespace scope other than global scope or declared static in global 10907 // scope. 10908 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10909 return true; 10910 10911 CanQualType SizeTy = 10912 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10913 10914 // C++ [basic.stc.dynamic.allocation]p1: 10915 // The return type shall be void*. The first parameter shall have type 10916 // std::size_t. 10917 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10918 SizeTy, 10919 diag::err_operator_new_dependent_param_type, 10920 diag::err_operator_new_param_type)) 10921 return true; 10922 10923 // C++ [basic.stc.dynamic.allocation]p1: 10924 // The first parameter shall not have an associated default argument. 10925 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10926 return SemaRef.Diag(FnDecl->getLocation(), 10927 diag::err_operator_new_default_arg) 10928 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10929 10930 return false; 10931 } 10932 10933 static bool 10934 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10935 // C++ [basic.stc.dynamic.deallocation]p1: 10936 // A program is ill-formed if deallocation functions are declared in a 10937 // namespace scope other than global scope or declared static in global 10938 // scope. 10939 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10940 return true; 10941 10942 // C++ [basic.stc.dynamic.deallocation]p2: 10943 // Each deallocation function shall return void and its first parameter 10944 // shall be void*. 10945 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10946 SemaRef.Context.VoidPtrTy, 10947 diag::err_operator_delete_dependent_param_type, 10948 diag::err_operator_delete_param_type)) 10949 return true; 10950 10951 return false; 10952 } 10953 10954 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 10955 /// of this overloaded operator is well-formed. If so, returns false; 10956 /// otherwise, emits appropriate diagnostics and returns true. 10957 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10958 assert(FnDecl && FnDecl->isOverloadedOperator() && 10959 "Expected an overloaded operator declaration"); 10960 10961 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10962 10963 // C++ [over.oper]p5: 10964 // The allocation and deallocation functions, operator new, 10965 // operator new[], operator delete and operator delete[], are 10966 // described completely in 3.7.3. The attributes and restrictions 10967 // found in the rest of this subclause do not apply to them unless 10968 // explicitly stated in 3.7.3. 10969 if (Op == OO_Delete || Op == OO_Array_Delete) 10970 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10971 10972 if (Op == OO_New || Op == OO_Array_New) 10973 return CheckOperatorNewDeclaration(*this, FnDecl); 10974 10975 // C++ [over.oper]p6: 10976 // An operator function shall either be a non-static member 10977 // function or be a non-member function and have at least one 10978 // parameter whose type is a class, a reference to a class, an 10979 // enumeration, or a reference to an enumeration. 10980 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10981 if (MethodDecl->isStatic()) 10982 return Diag(FnDecl->getLocation(), 10983 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10984 } else { 10985 bool ClassOrEnumParam = false; 10986 for (auto Param : FnDecl->params()) { 10987 QualType ParamType = Param->getType().getNonReferenceType(); 10988 if (ParamType->isDependentType() || ParamType->isRecordType() || 10989 ParamType->isEnumeralType()) { 10990 ClassOrEnumParam = true; 10991 break; 10992 } 10993 } 10994 10995 if (!ClassOrEnumParam) 10996 return Diag(FnDecl->getLocation(), 10997 diag::err_operator_overload_needs_class_or_enum) 10998 << FnDecl->getDeclName(); 10999 } 11000 11001 // C++ [over.oper]p8: 11002 // An operator function cannot have default arguments (8.3.6), 11003 // except where explicitly stated below. 11004 // 11005 // Only the function-call operator allows default arguments 11006 // (C++ [over.call]p1). 11007 if (Op != OO_Call) { 11008 for (auto Param : FnDecl->params()) { 11009 if (Param->hasDefaultArg()) 11010 return Diag(Param->getLocation(), 11011 diag::err_operator_overload_default_arg) 11012 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11013 } 11014 } 11015 11016 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11017 { false, false, false } 11018 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11019 , { Unary, Binary, MemberOnly } 11020 #include "clang/Basic/OperatorKinds.def" 11021 }; 11022 11023 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11024 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11025 bool MustBeMemberOperator = OperatorUses[Op][2]; 11026 11027 // C++ [over.oper]p8: 11028 // [...] Operator functions cannot have more or fewer parameters 11029 // than the number required for the corresponding operator, as 11030 // described in the rest of this subclause. 11031 unsigned NumParams = FnDecl->getNumParams() 11032 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11033 if (Op != OO_Call && 11034 ((NumParams == 1 && !CanBeUnaryOperator) || 11035 (NumParams == 2 && !CanBeBinaryOperator) || 11036 (NumParams < 1) || (NumParams > 2))) { 11037 // We have the wrong number of parameters. 11038 unsigned ErrorKind; 11039 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11040 ErrorKind = 2; // 2 -> unary or binary. 11041 } else if (CanBeUnaryOperator) { 11042 ErrorKind = 0; // 0 -> unary 11043 } else { 11044 assert(CanBeBinaryOperator && 11045 "All non-call overloaded operators are unary or binary!"); 11046 ErrorKind = 1; // 1 -> binary 11047 } 11048 11049 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11050 << FnDecl->getDeclName() << NumParams << ErrorKind; 11051 } 11052 11053 // Overloaded operators other than operator() cannot be variadic. 11054 if (Op != OO_Call && 11055 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11056 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11057 << FnDecl->getDeclName(); 11058 } 11059 11060 // Some operators must be non-static member functions. 11061 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11062 return Diag(FnDecl->getLocation(), 11063 diag::err_operator_overload_must_be_member) 11064 << FnDecl->getDeclName(); 11065 } 11066 11067 // C++ [over.inc]p1: 11068 // The user-defined function called operator++ implements the 11069 // prefix and postfix ++ operator. If this function is a member 11070 // function with no parameters, or a non-member function with one 11071 // parameter of class or enumeration type, it defines the prefix 11072 // increment operator ++ for objects of that type. If the function 11073 // is a member function with one parameter (which shall be of type 11074 // int) or a non-member function with two parameters (the second 11075 // of which shall be of type int), it defines the postfix 11076 // increment operator ++ for objects of that type. 11077 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11078 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11079 QualType ParamType = LastParam->getType(); 11080 11081 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11082 !ParamType->isDependentType()) 11083 return Diag(LastParam->getLocation(), 11084 diag::err_operator_overload_post_incdec_must_be_int) 11085 << LastParam->getType() << (Op == OO_MinusMinus); 11086 } 11087 11088 return false; 11089 } 11090 11091 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11092 /// of this literal operator function is well-formed. If so, returns 11093 /// false; otherwise, emits appropriate diagnostics and returns true. 11094 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11095 if (isa<CXXMethodDecl>(FnDecl)) { 11096 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11097 << FnDecl->getDeclName(); 11098 return true; 11099 } 11100 11101 if (FnDecl->isExternC()) { 11102 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11103 return true; 11104 } 11105 11106 bool Valid = false; 11107 11108 // This might be the definition of a literal operator template. 11109 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11110 // This might be a specialization of a literal operator template. 11111 if (!TpDecl) 11112 TpDecl = FnDecl->getPrimaryTemplate(); 11113 11114 // template <char...> type operator "" name() and 11115 // template <class T, T...> type operator "" name() are the only valid 11116 // template signatures, and the only valid signatures with no parameters. 11117 if (TpDecl) { 11118 if (FnDecl->param_size() == 0) { 11119 // Must have one or two template parameters 11120 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11121 if (Params->size() == 1) { 11122 NonTypeTemplateParmDecl *PmDecl = 11123 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11124 11125 // The template parameter must be a char parameter pack. 11126 if (PmDecl && PmDecl->isTemplateParameterPack() && 11127 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11128 Valid = true; 11129 } else if (Params->size() == 2) { 11130 TemplateTypeParmDecl *PmType = 11131 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11132 NonTypeTemplateParmDecl *PmArgs = 11133 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11134 11135 // The second template parameter must be a parameter pack with the 11136 // first template parameter as its type. 11137 if (PmType && PmArgs && 11138 !PmType->isTemplateParameterPack() && 11139 PmArgs->isTemplateParameterPack()) { 11140 const TemplateTypeParmType *TArgs = 11141 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11142 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11143 TArgs->getIndex() == PmType->getIndex()) { 11144 Valid = true; 11145 if (ActiveTemplateInstantiations.empty()) 11146 Diag(FnDecl->getLocation(), 11147 diag::ext_string_literal_operator_template); 11148 } 11149 } 11150 } 11151 } 11152 } else if (FnDecl->param_size()) { 11153 // Check the first parameter 11154 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11155 11156 QualType T = (*Param)->getType().getUnqualifiedType(); 11157 11158 // unsigned long long int, long double, and any character type are allowed 11159 // as the only parameters. 11160 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11161 Context.hasSameType(T, Context.LongDoubleTy) || 11162 Context.hasSameType(T, Context.CharTy) || 11163 Context.hasSameType(T, Context.WideCharTy) || 11164 Context.hasSameType(T, Context.Char16Ty) || 11165 Context.hasSameType(T, Context.Char32Ty)) { 11166 if (++Param == FnDecl->param_end()) 11167 Valid = true; 11168 goto FinishedParams; 11169 } 11170 11171 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11172 const PointerType *PT = T->getAs<PointerType>(); 11173 if (!PT) 11174 goto FinishedParams; 11175 T = PT->getPointeeType(); 11176 if (!T.isConstQualified() || T.isVolatileQualified()) 11177 goto FinishedParams; 11178 T = T.getUnqualifiedType(); 11179 11180 // Move on to the second parameter; 11181 ++Param; 11182 11183 // If there is no second parameter, the first must be a const char * 11184 if (Param == FnDecl->param_end()) { 11185 if (Context.hasSameType(T, Context.CharTy)) 11186 Valid = true; 11187 goto FinishedParams; 11188 } 11189 11190 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11191 // are allowed as the first parameter to a two-parameter function 11192 if (!(Context.hasSameType(T, Context.CharTy) || 11193 Context.hasSameType(T, Context.WideCharTy) || 11194 Context.hasSameType(T, Context.Char16Ty) || 11195 Context.hasSameType(T, Context.Char32Ty))) 11196 goto FinishedParams; 11197 11198 // The second and final parameter must be an std::size_t 11199 T = (*Param)->getType().getUnqualifiedType(); 11200 if (Context.hasSameType(T, Context.getSizeType()) && 11201 ++Param == FnDecl->param_end()) 11202 Valid = true; 11203 } 11204 11205 // FIXME: This diagnostic is absolutely terrible. 11206 FinishedParams: 11207 if (!Valid) { 11208 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11209 << FnDecl->getDeclName(); 11210 return true; 11211 } 11212 11213 // A parameter-declaration-clause containing a default argument is not 11214 // equivalent to any of the permitted forms. 11215 for (auto Param : FnDecl->params()) { 11216 if (Param->hasDefaultArg()) { 11217 Diag(Param->getDefaultArgRange().getBegin(), 11218 diag::err_literal_operator_default_argument) 11219 << Param->getDefaultArgRange(); 11220 break; 11221 } 11222 } 11223 11224 StringRef LiteralName 11225 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11226 if (LiteralName[0] != '_') { 11227 // C++11 [usrlit.suffix]p1: 11228 // Literal suffix identifiers that do not start with an underscore 11229 // are reserved for future standardization. 11230 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11231 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11232 } 11233 11234 return false; 11235 } 11236 11237 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11238 /// linkage specification, including the language and (if present) 11239 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11240 /// language string literal. LBraceLoc, if valid, provides the location of 11241 /// the '{' brace. Otherwise, this linkage specification does not 11242 /// have any braces. 11243 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11244 Expr *LangStr, 11245 SourceLocation LBraceLoc) { 11246 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11247 if (!Lit->isAscii()) { 11248 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11249 << LangStr->getSourceRange(); 11250 return nullptr; 11251 } 11252 11253 StringRef Lang = Lit->getString(); 11254 LinkageSpecDecl::LanguageIDs Language; 11255 if (Lang == "C") 11256 Language = LinkageSpecDecl::lang_c; 11257 else if (Lang == "C++") 11258 Language = LinkageSpecDecl::lang_cxx; 11259 else { 11260 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11261 << LangStr->getSourceRange(); 11262 return nullptr; 11263 } 11264 11265 // FIXME: Add all the various semantics of linkage specifications 11266 11267 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11268 LangStr->getExprLoc(), Language, 11269 LBraceLoc.isValid()); 11270 CurContext->addDecl(D); 11271 PushDeclContext(S, D); 11272 return D; 11273 } 11274 11275 /// ActOnFinishLinkageSpecification - Complete the definition of 11276 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11277 /// valid, it's the position of the closing '}' brace in a linkage 11278 /// specification that uses braces. 11279 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11280 Decl *LinkageSpec, 11281 SourceLocation RBraceLoc) { 11282 if (RBraceLoc.isValid()) { 11283 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11284 LSDecl->setRBraceLoc(RBraceLoc); 11285 } 11286 PopDeclContext(); 11287 return LinkageSpec; 11288 } 11289 11290 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11291 AttributeList *AttrList, 11292 SourceLocation SemiLoc) { 11293 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11294 // Attribute declarations appertain to empty declaration so we handle 11295 // them here. 11296 if (AttrList) 11297 ProcessDeclAttributeList(S, ED, AttrList); 11298 11299 CurContext->addDecl(ED); 11300 return ED; 11301 } 11302 11303 /// \brief Perform semantic analysis for the variable declaration that 11304 /// occurs within a C++ catch clause, returning the newly-created 11305 /// variable. 11306 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11307 TypeSourceInfo *TInfo, 11308 SourceLocation StartLoc, 11309 SourceLocation Loc, 11310 IdentifierInfo *Name) { 11311 bool Invalid = false; 11312 QualType ExDeclType = TInfo->getType(); 11313 11314 // Arrays and functions decay. 11315 if (ExDeclType->isArrayType()) 11316 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11317 else if (ExDeclType->isFunctionType()) 11318 ExDeclType = Context.getPointerType(ExDeclType); 11319 11320 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11321 // The exception-declaration shall not denote a pointer or reference to an 11322 // incomplete type, other than [cv] void*. 11323 // N2844 forbids rvalue references. 11324 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11325 Diag(Loc, diag::err_catch_rvalue_ref); 11326 Invalid = true; 11327 } 11328 11329 QualType BaseType = ExDeclType; 11330 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11331 unsigned DK = diag::err_catch_incomplete; 11332 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11333 BaseType = Ptr->getPointeeType(); 11334 Mode = 1; 11335 DK = diag::err_catch_incomplete_ptr; 11336 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11337 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11338 BaseType = Ref->getPointeeType(); 11339 Mode = 2; 11340 DK = diag::err_catch_incomplete_ref; 11341 } 11342 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11343 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11344 Invalid = true; 11345 11346 if (!Invalid && !ExDeclType->isDependentType() && 11347 RequireNonAbstractType(Loc, ExDeclType, 11348 diag::err_abstract_type_in_decl, 11349 AbstractVariableType)) 11350 Invalid = true; 11351 11352 // Only the non-fragile NeXT runtime currently supports C++ catches 11353 // of ObjC types, and no runtime supports catching ObjC types by value. 11354 if (!Invalid && getLangOpts().ObjC1) { 11355 QualType T = ExDeclType; 11356 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11357 T = RT->getPointeeType(); 11358 11359 if (T->isObjCObjectType()) { 11360 Diag(Loc, diag::err_objc_object_catch); 11361 Invalid = true; 11362 } else if (T->isObjCObjectPointerType()) { 11363 // FIXME: should this be a test for macosx-fragile specifically? 11364 if (getLangOpts().ObjCRuntime.isFragile()) 11365 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11366 } 11367 } 11368 11369 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11370 ExDeclType, TInfo, SC_None); 11371 ExDecl->setExceptionVariable(true); 11372 11373 // In ARC, infer 'retaining' for variables of retainable type. 11374 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11375 Invalid = true; 11376 11377 if (!Invalid && !ExDeclType->isDependentType()) { 11378 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11379 // Insulate this from anything else we might currently be parsing. 11380 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11381 11382 // C++ [except.handle]p16: 11383 // The object declared in an exception-declaration or, if the 11384 // exception-declaration does not specify a name, a temporary (12.2) is 11385 // copy-initialized (8.5) from the exception object. [...] 11386 // The object is destroyed when the handler exits, after the destruction 11387 // of any automatic objects initialized within the handler. 11388 // 11389 // We just pretend to initialize the object with itself, then make sure 11390 // it can be destroyed later. 11391 QualType initType = ExDeclType; 11392 11393 InitializedEntity entity = 11394 InitializedEntity::InitializeVariable(ExDecl); 11395 InitializationKind initKind = 11396 InitializationKind::CreateCopy(Loc, SourceLocation()); 11397 11398 Expr *opaqueValue = 11399 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11400 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11401 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11402 if (result.isInvalid()) 11403 Invalid = true; 11404 else { 11405 // If the constructor used was non-trivial, set this as the 11406 // "initializer". 11407 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11408 if (!construct->getConstructor()->isTrivial()) { 11409 Expr *init = MaybeCreateExprWithCleanups(construct); 11410 ExDecl->setInit(init); 11411 } 11412 11413 // And make sure it's destructable. 11414 FinalizeVarWithDestructor(ExDecl, recordType); 11415 } 11416 } 11417 } 11418 11419 if (Invalid) 11420 ExDecl->setInvalidDecl(); 11421 11422 return ExDecl; 11423 } 11424 11425 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11426 /// handler. 11427 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11428 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11429 bool Invalid = D.isInvalidType(); 11430 11431 // Check for unexpanded parameter packs. 11432 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11433 UPPC_ExceptionType)) { 11434 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11435 D.getIdentifierLoc()); 11436 Invalid = true; 11437 } 11438 11439 IdentifierInfo *II = D.getIdentifier(); 11440 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11441 LookupOrdinaryName, 11442 ForRedeclaration)) { 11443 // The scope should be freshly made just for us. There is just no way 11444 // it contains any previous declaration, except for function parameters in 11445 // a function-try-block's catch statement. 11446 assert(!S->isDeclScope(PrevDecl)); 11447 if (isDeclInScope(PrevDecl, CurContext, S)) { 11448 Diag(D.getIdentifierLoc(), diag::err_redefinition) 11449 << D.getIdentifier(); 11450 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11451 Invalid = true; 11452 } else if (PrevDecl->isTemplateParameter()) 11453 // Maybe we will complain about the shadowed template parameter. 11454 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11455 } 11456 11457 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11458 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11459 << D.getCXXScopeSpec().getRange(); 11460 Invalid = true; 11461 } 11462 11463 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11464 D.getLocStart(), 11465 D.getIdentifierLoc(), 11466 D.getIdentifier()); 11467 if (Invalid) 11468 ExDecl->setInvalidDecl(); 11469 11470 // Add the exception declaration into this scope. 11471 if (II) 11472 PushOnScopeChains(ExDecl, S); 11473 else 11474 CurContext->addDecl(ExDecl); 11475 11476 ProcessDeclAttributes(S, ExDecl, D); 11477 return ExDecl; 11478 } 11479 11480 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11481 Expr *AssertExpr, 11482 Expr *AssertMessageExpr, 11483 SourceLocation RParenLoc) { 11484 StringLiteral *AssertMessage = 11485 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 11486 11487 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11488 return nullptr; 11489 11490 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11491 AssertMessage, RParenLoc, false); 11492 } 11493 11494 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11495 Expr *AssertExpr, 11496 StringLiteral *AssertMessage, 11497 SourceLocation RParenLoc, 11498 bool Failed) { 11499 assert(AssertExpr != nullptr && "Expected non-null condition"); 11500 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11501 !Failed) { 11502 // In a static_assert-declaration, the constant-expression shall be a 11503 // constant expression that can be contextually converted to bool. 11504 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11505 if (Converted.isInvalid()) 11506 Failed = true; 11507 11508 llvm::APSInt Cond; 11509 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11510 diag::err_static_assert_expression_is_not_constant, 11511 /*AllowFold=*/false).isInvalid()) 11512 Failed = true; 11513 11514 if (!Failed && !Cond) { 11515 SmallString<256> MsgBuffer; 11516 llvm::raw_svector_ostream Msg(MsgBuffer); 11517 if (AssertMessage) 11518 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 11519 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11520 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 11521 Failed = true; 11522 } 11523 } 11524 11525 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11526 AssertExpr, AssertMessage, RParenLoc, 11527 Failed); 11528 11529 CurContext->addDecl(Decl); 11530 return Decl; 11531 } 11532 11533 /// \brief Perform semantic analysis of the given friend type declaration. 11534 /// 11535 /// \returns A friend declaration that. 11536 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11537 SourceLocation FriendLoc, 11538 TypeSourceInfo *TSInfo) { 11539 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11540 11541 QualType T = TSInfo->getType(); 11542 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11543 11544 // C++03 [class.friend]p2: 11545 // An elaborated-type-specifier shall be used in a friend declaration 11546 // for a class.* 11547 // 11548 // * The class-key of the elaborated-type-specifier is required. 11549 if (!ActiveTemplateInstantiations.empty()) { 11550 // Do not complain about the form of friend template types during 11551 // template instantiation; we will already have complained when the 11552 // template was declared. 11553 } else { 11554 if (!T->isElaboratedTypeSpecifier()) { 11555 // If we evaluated the type to a record type, suggest putting 11556 // a tag in front. 11557 if (const RecordType *RT = T->getAs<RecordType>()) { 11558 RecordDecl *RD = RT->getDecl(); 11559 11560 SmallString<16> InsertionText(" "); 11561 InsertionText += RD->getKindName(); 11562 11563 Diag(TypeRange.getBegin(), 11564 getLangOpts().CPlusPlus11 ? 11565 diag::warn_cxx98_compat_unelaborated_friend_type : 11566 diag::ext_unelaborated_friend_type) 11567 << (unsigned) RD->getTagKind() 11568 << T 11569 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11570 InsertionText); 11571 } else { 11572 Diag(FriendLoc, 11573 getLangOpts().CPlusPlus11 ? 11574 diag::warn_cxx98_compat_nonclass_type_friend : 11575 diag::ext_nonclass_type_friend) 11576 << T 11577 << TypeRange; 11578 } 11579 } else if (T->getAs<EnumType>()) { 11580 Diag(FriendLoc, 11581 getLangOpts().CPlusPlus11 ? 11582 diag::warn_cxx98_compat_enum_friend : 11583 diag::ext_enum_friend) 11584 << T 11585 << TypeRange; 11586 } 11587 11588 // C++11 [class.friend]p3: 11589 // A friend declaration that does not declare a function shall have one 11590 // of the following forms: 11591 // friend elaborated-type-specifier ; 11592 // friend simple-type-specifier ; 11593 // friend typename-specifier ; 11594 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11595 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11596 } 11597 11598 // If the type specifier in a friend declaration designates a (possibly 11599 // cv-qualified) class type, that class is declared as a friend; otherwise, 11600 // the friend declaration is ignored. 11601 return FriendDecl::Create(Context, CurContext, 11602 TSInfo->getTypeLoc().getLocStart(), TSInfo, 11603 FriendLoc); 11604 } 11605 11606 /// Handle a friend tag declaration where the scope specifier was 11607 /// templated. 11608 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11609 unsigned TagSpec, SourceLocation TagLoc, 11610 CXXScopeSpec &SS, 11611 IdentifierInfo *Name, 11612 SourceLocation NameLoc, 11613 AttributeList *Attr, 11614 MultiTemplateParamsArg TempParamLists) { 11615 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11616 11617 bool isExplicitSpecialization = false; 11618 bool Invalid = false; 11619 11620 if (TemplateParameterList *TemplateParams = 11621 MatchTemplateParametersToScopeSpecifier( 11622 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 11623 isExplicitSpecialization, Invalid)) { 11624 if (TemplateParams->size() > 0) { 11625 // This is a declaration of a class template. 11626 if (Invalid) 11627 return nullptr; 11628 11629 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11630 SS, Name, NameLoc, Attr, 11631 TemplateParams, AS_public, 11632 /*ModulePrivateLoc=*/SourceLocation(), 11633 TempParamLists.size() - 1, 11634 TempParamLists.data()).get(); 11635 } else { 11636 // The "template<>" header is extraneous. 11637 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11638 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11639 isExplicitSpecialization = true; 11640 } 11641 } 11642 11643 if (Invalid) return nullptr; 11644 11645 bool isAllExplicitSpecializations = true; 11646 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11647 if (TempParamLists[I]->size()) { 11648 isAllExplicitSpecializations = false; 11649 break; 11650 } 11651 } 11652 11653 // FIXME: don't ignore attributes. 11654 11655 // If it's explicit specializations all the way down, just forget 11656 // about the template header and build an appropriate non-templated 11657 // friend. TODO: for source fidelity, remember the headers. 11658 if (isAllExplicitSpecializations) { 11659 if (SS.isEmpty()) { 11660 bool Owned = false; 11661 bool IsDependent = false; 11662 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11663 Attr, AS_public, 11664 /*ModulePrivateLoc=*/SourceLocation(), 11665 MultiTemplateParamsArg(), Owned, IsDependent, 11666 /*ScopedEnumKWLoc=*/SourceLocation(), 11667 /*ScopedEnumUsesClassTag=*/false, 11668 /*UnderlyingType=*/TypeResult(), 11669 /*IsTypeSpecifier=*/false); 11670 } 11671 11672 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11673 ElaboratedTypeKeyword Keyword 11674 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11675 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11676 *Name, NameLoc); 11677 if (T.isNull()) 11678 return nullptr; 11679 11680 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11681 if (isa<DependentNameType>(T)) { 11682 DependentNameTypeLoc TL = 11683 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11684 TL.setElaboratedKeywordLoc(TagLoc); 11685 TL.setQualifierLoc(QualifierLoc); 11686 TL.setNameLoc(NameLoc); 11687 } else { 11688 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11689 TL.setElaboratedKeywordLoc(TagLoc); 11690 TL.setQualifierLoc(QualifierLoc); 11691 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11692 } 11693 11694 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11695 TSI, FriendLoc, TempParamLists); 11696 Friend->setAccess(AS_public); 11697 CurContext->addDecl(Friend); 11698 return Friend; 11699 } 11700 11701 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11702 11703 11704 11705 // Handle the case of a templated-scope friend class. e.g. 11706 // template <class T> class A<T>::B; 11707 // FIXME: we don't support these right now. 11708 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 11709 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 11710 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11711 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11712 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11713 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11714 TL.setElaboratedKeywordLoc(TagLoc); 11715 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11716 TL.setNameLoc(NameLoc); 11717 11718 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11719 TSI, FriendLoc, TempParamLists); 11720 Friend->setAccess(AS_public); 11721 Friend->setUnsupportedFriend(true); 11722 CurContext->addDecl(Friend); 11723 return Friend; 11724 } 11725 11726 11727 /// Handle a friend type declaration. This works in tandem with 11728 /// ActOnTag. 11729 /// 11730 /// Notes on friend class templates: 11731 /// 11732 /// We generally treat friend class declarations as if they were 11733 /// declaring a class. So, for example, the elaborated type specifier 11734 /// in a friend declaration is required to obey the restrictions of a 11735 /// class-head (i.e. no typedefs in the scope chain), template 11736 /// parameters are required to match up with simple template-ids, &c. 11737 /// However, unlike when declaring a template specialization, it's 11738 /// okay to refer to a template specialization without an empty 11739 /// template parameter declaration, e.g. 11740 /// friend class A<T>::B<unsigned>; 11741 /// We permit this as a special case; if there are any template 11742 /// parameters present at all, require proper matching, i.e. 11743 /// template <> template \<class T> friend class A<int>::B; 11744 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11745 MultiTemplateParamsArg TempParams) { 11746 SourceLocation Loc = DS.getLocStart(); 11747 11748 assert(DS.isFriendSpecified()); 11749 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11750 11751 // Try to convert the decl specifier to a type. This works for 11752 // friend templates because ActOnTag never produces a ClassTemplateDecl 11753 // for a TUK_Friend. 11754 Declarator TheDeclarator(DS, Declarator::MemberContext); 11755 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11756 QualType T = TSI->getType(); 11757 if (TheDeclarator.isInvalidType()) 11758 return nullptr; 11759 11760 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11761 return nullptr; 11762 11763 // This is definitely an error in C++98. It's probably meant to 11764 // be forbidden in C++0x, too, but the specification is just 11765 // poorly written. 11766 // 11767 // The problem is with declarations like the following: 11768 // template <T> friend A<T>::foo; 11769 // where deciding whether a class C is a friend or not now hinges 11770 // on whether there exists an instantiation of A that causes 11771 // 'foo' to equal C. There are restrictions on class-heads 11772 // (which we declare (by fiat) elaborated friend declarations to 11773 // be) that makes this tractable. 11774 // 11775 // FIXME: handle "template <> friend class A<T>;", which 11776 // is possibly well-formed? Who even knows? 11777 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11778 Diag(Loc, diag::err_tagless_friend_type_template) 11779 << DS.getSourceRange(); 11780 return nullptr; 11781 } 11782 11783 // C++98 [class.friend]p1: A friend of a class is a function 11784 // or class that is not a member of the class . . . 11785 // This is fixed in DR77, which just barely didn't make the C++03 11786 // deadline. It's also a very silly restriction that seriously 11787 // affects inner classes and which nobody else seems to implement; 11788 // thus we never diagnose it, not even in -pedantic. 11789 // 11790 // But note that we could warn about it: it's always useless to 11791 // friend one of your own members (it's not, however, worthless to 11792 // friend a member of an arbitrary specialization of your template). 11793 11794 Decl *D; 11795 if (unsigned NumTempParamLists = TempParams.size()) 11796 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11797 NumTempParamLists, 11798 TempParams.data(), 11799 TSI, 11800 DS.getFriendSpecLoc()); 11801 else 11802 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11803 11804 if (!D) 11805 return nullptr; 11806 11807 D->setAccess(AS_public); 11808 CurContext->addDecl(D); 11809 11810 return D; 11811 } 11812 11813 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11814 MultiTemplateParamsArg TemplateParams) { 11815 const DeclSpec &DS = D.getDeclSpec(); 11816 11817 assert(DS.isFriendSpecified()); 11818 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11819 11820 SourceLocation Loc = D.getIdentifierLoc(); 11821 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11822 11823 // C++ [class.friend]p1 11824 // A friend of a class is a function or class.... 11825 // Note that this sees through typedefs, which is intended. 11826 // It *doesn't* see through dependent types, which is correct 11827 // according to [temp.arg.type]p3: 11828 // If a declaration acquires a function type through a 11829 // type dependent on a template-parameter and this causes 11830 // a declaration that does not use the syntactic form of a 11831 // function declarator to have a function type, the program 11832 // is ill-formed. 11833 if (!TInfo->getType()->isFunctionType()) { 11834 Diag(Loc, diag::err_unexpected_friend); 11835 11836 // It might be worthwhile to try to recover by creating an 11837 // appropriate declaration. 11838 return nullptr; 11839 } 11840 11841 // C++ [namespace.memdef]p3 11842 // - If a friend declaration in a non-local class first declares a 11843 // class or function, the friend class or function is a member 11844 // of the innermost enclosing namespace. 11845 // - The name of the friend is not found by simple name lookup 11846 // until a matching declaration is provided in that namespace 11847 // scope (either before or after the class declaration granting 11848 // friendship). 11849 // - If a friend function is called, its name may be found by the 11850 // name lookup that considers functions from namespaces and 11851 // classes associated with the types of the function arguments. 11852 // - When looking for a prior declaration of a class or a function 11853 // declared as a friend, scopes outside the innermost enclosing 11854 // namespace scope are not considered. 11855 11856 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11857 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11858 DeclarationName Name = NameInfo.getName(); 11859 assert(Name); 11860 11861 // Check for unexpanded parameter packs. 11862 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11863 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11864 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11865 return nullptr; 11866 11867 // The context we found the declaration in, or in which we should 11868 // create the declaration. 11869 DeclContext *DC; 11870 Scope *DCScope = S; 11871 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11872 ForRedeclaration); 11873 11874 // There are five cases here. 11875 // - There's no scope specifier and we're in a local class. Only look 11876 // for functions declared in the immediately-enclosing block scope. 11877 // We recover from invalid scope qualifiers as if they just weren't there. 11878 FunctionDecl *FunctionContainingLocalClass = nullptr; 11879 if ((SS.isInvalid() || !SS.isSet()) && 11880 (FunctionContainingLocalClass = 11881 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11882 // C++11 [class.friend]p11: 11883 // If a friend declaration appears in a local class and the name 11884 // specified is an unqualified name, a prior declaration is 11885 // looked up without considering scopes that are outside the 11886 // innermost enclosing non-class scope. For a friend function 11887 // declaration, if there is no prior declaration, the program is 11888 // ill-formed. 11889 11890 // Find the innermost enclosing non-class scope. This is the block 11891 // scope containing the local class definition (or for a nested class, 11892 // the outer local class). 11893 DCScope = S->getFnParent(); 11894 11895 // Look up the function name in the scope. 11896 Previous.clear(LookupLocalFriendName); 11897 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11898 11899 if (!Previous.empty()) { 11900 // All possible previous declarations must have the same context: 11901 // either they were declared at block scope or they are members of 11902 // one of the enclosing local classes. 11903 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11904 } else { 11905 // This is ill-formed, but provide the context that we would have 11906 // declared the function in, if we were permitted to, for error recovery. 11907 DC = FunctionContainingLocalClass; 11908 } 11909 adjustContextForLocalExternDecl(DC); 11910 11911 // C++ [class.friend]p6: 11912 // A function can be defined in a friend declaration of a class if and 11913 // only if the class is a non-local class (9.8), the function name is 11914 // unqualified, and the function has namespace scope. 11915 if (D.isFunctionDefinition()) { 11916 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11917 } 11918 11919 // - There's no scope specifier, in which case we just go to the 11920 // appropriate scope and look for a function or function template 11921 // there as appropriate. 11922 } else if (SS.isInvalid() || !SS.isSet()) { 11923 // C++11 [namespace.memdef]p3: 11924 // If the name in a friend declaration is neither qualified nor 11925 // a template-id and the declaration is a function or an 11926 // elaborated-type-specifier, the lookup to determine whether 11927 // the entity has been previously declared shall not consider 11928 // any scopes outside the innermost enclosing namespace. 11929 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11930 11931 // Find the appropriate context according to the above. 11932 DC = CurContext; 11933 11934 // Skip class contexts. If someone can cite chapter and verse 11935 // for this behavior, that would be nice --- it's what GCC and 11936 // EDG do, and it seems like a reasonable intent, but the spec 11937 // really only says that checks for unqualified existing 11938 // declarations should stop at the nearest enclosing namespace, 11939 // not that they should only consider the nearest enclosing 11940 // namespace. 11941 while (DC->isRecord()) 11942 DC = DC->getParent(); 11943 11944 DeclContext *LookupDC = DC; 11945 while (LookupDC->isTransparentContext()) 11946 LookupDC = LookupDC->getParent(); 11947 11948 while (true) { 11949 LookupQualifiedName(Previous, LookupDC); 11950 11951 if (!Previous.empty()) { 11952 DC = LookupDC; 11953 break; 11954 } 11955 11956 if (isTemplateId) { 11957 if (isa<TranslationUnitDecl>(LookupDC)) break; 11958 } else { 11959 if (LookupDC->isFileContext()) break; 11960 } 11961 LookupDC = LookupDC->getParent(); 11962 } 11963 11964 DCScope = getScopeForDeclContext(S, DC); 11965 11966 // - There's a non-dependent scope specifier, in which case we 11967 // compute it and do a previous lookup there for a function 11968 // or function template. 11969 } else if (!SS.getScopeRep()->isDependent()) { 11970 DC = computeDeclContext(SS); 11971 if (!DC) return nullptr; 11972 11973 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 11974 11975 LookupQualifiedName(Previous, DC); 11976 11977 // Ignore things found implicitly in the wrong scope. 11978 // TODO: better diagnostics for this case. Suggesting the right 11979 // qualified scope would be nice... 11980 LookupResult::Filter F = Previous.makeFilter(); 11981 while (F.hasNext()) { 11982 NamedDecl *D = F.next(); 11983 if (!DC->InEnclosingNamespaceSetOf( 11984 D->getDeclContext()->getRedeclContext())) 11985 F.erase(); 11986 } 11987 F.done(); 11988 11989 if (Previous.empty()) { 11990 D.setInvalidType(); 11991 Diag(Loc, diag::err_qualified_friend_not_found) 11992 << Name << TInfo->getType(); 11993 return nullptr; 11994 } 11995 11996 // C++ [class.friend]p1: A friend of a class is a function or 11997 // class that is not a member of the class . . . 11998 if (DC->Equals(CurContext)) 11999 Diag(DS.getFriendSpecLoc(), 12000 getLangOpts().CPlusPlus11 ? 12001 diag::warn_cxx98_compat_friend_is_member : 12002 diag::err_friend_is_member); 12003 12004 if (D.isFunctionDefinition()) { 12005 // C++ [class.friend]p6: 12006 // A function can be defined in a friend declaration of a class if and 12007 // only if the class is a non-local class (9.8), the function name is 12008 // unqualified, and the function has namespace scope. 12009 SemaDiagnosticBuilder DB 12010 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12011 12012 DB << SS.getScopeRep(); 12013 if (DC->isFileContext()) 12014 DB << FixItHint::CreateRemoval(SS.getRange()); 12015 SS.clear(); 12016 } 12017 12018 // - There's a scope specifier that does not match any template 12019 // parameter lists, in which case we use some arbitrary context, 12020 // create a method or method template, and wait for instantiation. 12021 // - There's a scope specifier that does match some template 12022 // parameter lists, which we don't handle right now. 12023 } else { 12024 if (D.isFunctionDefinition()) { 12025 // C++ [class.friend]p6: 12026 // A function can be defined in a friend declaration of a class if and 12027 // only if the class is a non-local class (9.8), the function name is 12028 // unqualified, and the function has namespace scope. 12029 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12030 << SS.getScopeRep(); 12031 } 12032 12033 DC = CurContext; 12034 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12035 } 12036 12037 if (!DC->isRecord()) { 12038 // This implies that it has to be an operator or function. 12039 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12040 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12041 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12042 Diag(Loc, diag::err_introducing_special_friend) << 12043 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12044 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12045 return nullptr; 12046 } 12047 } 12048 12049 // FIXME: This is an egregious hack to cope with cases where the scope stack 12050 // does not contain the declaration context, i.e., in an out-of-line 12051 // definition of a class. 12052 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12053 if (!DCScope) { 12054 FakeDCScope.setEntity(DC); 12055 DCScope = &FakeDCScope; 12056 } 12057 12058 bool AddToScope = true; 12059 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12060 TemplateParams, AddToScope); 12061 if (!ND) return nullptr; 12062 12063 assert(ND->getLexicalDeclContext() == CurContext); 12064 12065 // If we performed typo correction, we might have added a scope specifier 12066 // and changed the decl context. 12067 DC = ND->getDeclContext(); 12068 12069 // Add the function declaration to the appropriate lookup tables, 12070 // adjusting the redeclarations list as necessary. We don't 12071 // want to do this yet if the friending class is dependent. 12072 // 12073 // Also update the scope-based lookup if the target context's 12074 // lookup context is in lexical scope. 12075 if (!CurContext->isDependentContext()) { 12076 DC = DC->getRedeclContext(); 12077 DC->makeDeclVisibleInContext(ND); 12078 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12079 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12080 } 12081 12082 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12083 D.getIdentifierLoc(), ND, 12084 DS.getFriendSpecLoc()); 12085 FrD->setAccess(AS_public); 12086 CurContext->addDecl(FrD); 12087 12088 if (ND->isInvalidDecl()) { 12089 FrD->setInvalidDecl(); 12090 } else { 12091 if (DC->isRecord()) CheckFriendAccess(ND); 12092 12093 FunctionDecl *FD; 12094 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12095 FD = FTD->getTemplatedDecl(); 12096 else 12097 FD = cast<FunctionDecl>(ND); 12098 12099 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12100 // default argument expression, that declaration shall be a definition 12101 // and shall be the only declaration of the function or function 12102 // template in the translation unit. 12103 if (functionDeclHasDefaultArgument(FD)) { 12104 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12105 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12106 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12107 } else if (!D.isFunctionDefinition()) 12108 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12109 } 12110 12111 // Mark templated-scope function declarations as unsupported. 12112 if (FD->getNumTemplateParameterLists()) 12113 FrD->setUnsupportedFriend(true); 12114 } 12115 12116 return ND; 12117 } 12118 12119 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12120 AdjustDeclIfTemplate(Dcl); 12121 12122 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12123 if (!Fn) { 12124 Diag(DelLoc, diag::err_deleted_non_function); 12125 return; 12126 } 12127 12128 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12129 // Don't consider the implicit declaration we generate for explicit 12130 // specializations. FIXME: Do not generate these implicit declarations. 12131 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12132 Prev->getPreviousDecl()) && 12133 !Prev->isDefined()) { 12134 Diag(DelLoc, diag::err_deleted_decl_not_first); 12135 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12136 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12137 : diag::note_previous_declaration); 12138 } 12139 // If the declaration wasn't the first, we delete the function anyway for 12140 // recovery. 12141 Fn = Fn->getCanonicalDecl(); 12142 } 12143 12144 // dllimport/dllexport cannot be deleted. 12145 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12146 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12147 Fn->setInvalidDecl(); 12148 } 12149 12150 if (Fn->isDeleted()) 12151 return; 12152 12153 // See if we're deleting a function which is already known to override a 12154 // non-deleted virtual function. 12155 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12156 bool IssuedDiagnostic = false; 12157 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12158 E = MD->end_overridden_methods(); 12159 I != E; ++I) { 12160 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12161 if (!IssuedDiagnostic) { 12162 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12163 IssuedDiagnostic = true; 12164 } 12165 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12166 } 12167 } 12168 } 12169 12170 // C++11 [basic.start.main]p3: 12171 // A program that defines main as deleted [...] is ill-formed. 12172 if (Fn->isMain()) 12173 Diag(DelLoc, diag::err_deleted_main); 12174 12175 Fn->setDeletedAsWritten(); 12176 } 12177 12178 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12179 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12180 12181 if (MD) { 12182 if (MD->getParent()->isDependentType()) { 12183 MD->setDefaulted(); 12184 MD->setExplicitlyDefaulted(); 12185 return; 12186 } 12187 12188 CXXSpecialMember Member = getSpecialMember(MD); 12189 if (Member == CXXInvalid) { 12190 if (!MD->isInvalidDecl()) 12191 Diag(DefaultLoc, diag::err_default_special_members); 12192 return; 12193 } 12194 12195 MD->setDefaulted(); 12196 MD->setExplicitlyDefaulted(); 12197 12198 // If this definition appears within the record, do the checking when 12199 // the record is complete. 12200 const FunctionDecl *Primary = MD; 12201 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12202 // Find the uninstantiated declaration that actually had the '= default' 12203 // on it. 12204 Pattern->isDefined(Primary); 12205 12206 // If the method was defaulted on its first declaration, we will have 12207 // already performed the checking in CheckCompletedCXXClass. Such a 12208 // declaration doesn't trigger an implicit definition. 12209 if (Primary == Primary->getCanonicalDecl()) 12210 return; 12211 12212 CheckExplicitlyDefaultedSpecialMember(MD); 12213 12214 // The exception specification is needed because we are defining the 12215 // function. 12216 ResolveExceptionSpec(DefaultLoc, 12217 MD->getType()->castAs<FunctionProtoType>()); 12218 12219 if (MD->isInvalidDecl()) 12220 return; 12221 12222 switch (Member) { 12223 case CXXDefaultConstructor: 12224 DefineImplicitDefaultConstructor(DefaultLoc, 12225 cast<CXXConstructorDecl>(MD)); 12226 break; 12227 case CXXCopyConstructor: 12228 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12229 break; 12230 case CXXCopyAssignment: 12231 DefineImplicitCopyAssignment(DefaultLoc, MD); 12232 break; 12233 case CXXDestructor: 12234 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12235 break; 12236 case CXXMoveConstructor: 12237 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12238 break; 12239 case CXXMoveAssignment: 12240 DefineImplicitMoveAssignment(DefaultLoc, MD); 12241 break; 12242 case CXXInvalid: 12243 llvm_unreachable("Invalid special member."); 12244 } 12245 } else { 12246 Diag(DefaultLoc, diag::err_default_special_members); 12247 } 12248 } 12249 12250 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12251 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12252 Stmt *SubStmt = *CI; 12253 if (!SubStmt) 12254 continue; 12255 if (isa<ReturnStmt>(SubStmt)) 12256 Self.Diag(SubStmt->getLocStart(), 12257 diag::err_return_in_constructor_handler); 12258 if (!isa<Expr>(SubStmt)) 12259 SearchForReturnInStmt(Self, SubStmt); 12260 } 12261 } 12262 12263 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12264 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12265 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12266 SearchForReturnInStmt(*this, Handler); 12267 } 12268 } 12269 12270 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12271 const CXXMethodDecl *Old) { 12272 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12273 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12274 12275 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12276 12277 // If the calling conventions match, everything is fine 12278 if (NewCC == OldCC) 12279 return false; 12280 12281 // If the calling conventions mismatch because the new function is static, 12282 // suppress the calling convention mismatch error; the error about static 12283 // function override (err_static_overrides_virtual from 12284 // Sema::CheckFunctionDeclaration) is more clear. 12285 if (New->getStorageClass() == SC_Static) 12286 return false; 12287 12288 Diag(New->getLocation(), 12289 diag::err_conflicting_overriding_cc_attributes) 12290 << New->getDeclName() << New->getType() << Old->getType(); 12291 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12292 return true; 12293 } 12294 12295 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12296 const CXXMethodDecl *Old) { 12297 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12298 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12299 12300 if (Context.hasSameType(NewTy, OldTy) || 12301 NewTy->isDependentType() || OldTy->isDependentType()) 12302 return false; 12303 12304 // Check if the return types are covariant 12305 QualType NewClassTy, OldClassTy; 12306 12307 /// Both types must be pointers or references to classes. 12308 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12309 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12310 NewClassTy = NewPT->getPointeeType(); 12311 OldClassTy = OldPT->getPointeeType(); 12312 } 12313 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12314 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12315 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12316 NewClassTy = NewRT->getPointeeType(); 12317 OldClassTy = OldRT->getPointeeType(); 12318 } 12319 } 12320 } 12321 12322 // The return types aren't either both pointers or references to a class type. 12323 if (NewClassTy.isNull()) { 12324 Diag(New->getLocation(), 12325 diag::err_different_return_type_for_overriding_virtual_function) 12326 << New->getDeclName() << NewTy << OldTy 12327 << New->getReturnTypeSourceRange(); 12328 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12329 << Old->getReturnTypeSourceRange(); 12330 12331 return true; 12332 } 12333 12334 // C++ [class.virtual]p6: 12335 // If the return type of D::f differs from the return type of B::f, the 12336 // class type in the return type of D::f shall be complete at the point of 12337 // declaration of D::f or shall be the class type D. 12338 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12339 if (!RT->isBeingDefined() && 12340 RequireCompleteType(New->getLocation(), NewClassTy, 12341 diag::err_covariant_return_incomplete, 12342 New->getDeclName())) 12343 return true; 12344 } 12345 12346 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12347 // Check if the new class derives from the old class. 12348 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12349 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12350 << New->getDeclName() << NewTy << OldTy 12351 << New->getReturnTypeSourceRange(); 12352 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12353 << Old->getReturnTypeSourceRange(); 12354 return true; 12355 } 12356 12357 // Check if we the conversion from derived to base is valid. 12358 if (CheckDerivedToBaseConversion( 12359 NewClassTy, OldClassTy, 12360 diag::err_covariant_return_inaccessible_base, 12361 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12362 New->getLocation(), New->getReturnTypeSourceRange(), 12363 New->getDeclName(), nullptr)) { 12364 // FIXME: this note won't trigger for delayed access control 12365 // diagnostics, and it's impossible to get an undelayed error 12366 // here from access control during the original parse because 12367 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12368 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12369 << Old->getReturnTypeSourceRange(); 12370 return true; 12371 } 12372 } 12373 12374 // The qualifiers of the return types must be the same. 12375 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12376 Diag(New->getLocation(), 12377 diag::err_covariant_return_type_different_qualifications) 12378 << New->getDeclName() << NewTy << OldTy 12379 << New->getReturnTypeSourceRange(); 12380 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12381 << Old->getReturnTypeSourceRange(); 12382 return true; 12383 }; 12384 12385 12386 // The new class type must have the same or less qualifiers as the old type. 12387 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12388 Diag(New->getLocation(), 12389 diag::err_covariant_return_type_class_type_more_qualified) 12390 << New->getDeclName() << NewTy << OldTy 12391 << New->getReturnTypeSourceRange(); 12392 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12393 << Old->getReturnTypeSourceRange(); 12394 return true; 12395 }; 12396 12397 return false; 12398 } 12399 12400 /// \brief Mark the given method pure. 12401 /// 12402 /// \param Method the method to be marked pure. 12403 /// 12404 /// \param InitRange the source range that covers the "0" initializer. 12405 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12406 SourceLocation EndLoc = InitRange.getEnd(); 12407 if (EndLoc.isValid()) 12408 Method->setRangeEnd(EndLoc); 12409 12410 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12411 Method->setPure(); 12412 return false; 12413 } 12414 12415 if (!Method->isInvalidDecl()) 12416 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12417 << Method->getDeclName() << InitRange; 12418 return true; 12419 } 12420 12421 /// \brief Determine whether the given declaration is a static data member. 12422 static bool isStaticDataMember(const Decl *D) { 12423 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12424 return Var->isStaticDataMember(); 12425 12426 return false; 12427 } 12428 12429 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12430 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12431 /// is a fresh scope pushed for just this purpose. 12432 /// 12433 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12434 /// static data member of class X, names should be looked up in the scope of 12435 /// class X. 12436 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12437 // If there is no declaration, there was an error parsing it. 12438 if (!D || D->isInvalidDecl()) 12439 return; 12440 12441 // We will always have a nested name specifier here, but this declaration 12442 // might not be out of line if the specifier names the current namespace: 12443 // extern int n; 12444 // int ::n = 0; 12445 if (D->isOutOfLine()) 12446 EnterDeclaratorContext(S, D->getDeclContext()); 12447 12448 // If we are parsing the initializer for a static data member, push a 12449 // new expression evaluation context that is associated with this static 12450 // data member. 12451 if (isStaticDataMember(D)) 12452 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12453 } 12454 12455 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12456 /// initializer for the out-of-line declaration 'D'. 12457 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12458 // If there is no declaration, there was an error parsing it. 12459 if (!D || D->isInvalidDecl()) 12460 return; 12461 12462 if (isStaticDataMember(D)) 12463 PopExpressionEvaluationContext(); 12464 12465 if (D->isOutOfLine()) 12466 ExitDeclaratorContext(S); 12467 } 12468 12469 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12470 /// C++ if/switch/while/for statement. 12471 /// e.g: "if (int x = f()) {...}" 12472 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12473 // C++ 6.4p2: 12474 // The declarator shall not specify a function or an array. 12475 // The type-specifier-seq shall not contain typedef and shall not declare a 12476 // new class or enumeration. 12477 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12478 "Parser allowed 'typedef' as storage class of condition decl."); 12479 12480 Decl *Dcl = ActOnDeclarator(S, D); 12481 if (!Dcl) 12482 return true; 12483 12484 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12485 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12486 << D.getSourceRange(); 12487 return true; 12488 } 12489 12490 return Dcl; 12491 } 12492 12493 void Sema::LoadExternalVTableUses() { 12494 if (!ExternalSource) 12495 return; 12496 12497 SmallVector<ExternalVTableUse, 4> VTables; 12498 ExternalSource->ReadUsedVTables(VTables); 12499 SmallVector<VTableUse, 4> NewUses; 12500 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12501 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12502 = VTablesUsed.find(VTables[I].Record); 12503 // Even if a definition wasn't required before, it may be required now. 12504 if (Pos != VTablesUsed.end()) { 12505 if (!Pos->second && VTables[I].DefinitionRequired) 12506 Pos->second = true; 12507 continue; 12508 } 12509 12510 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12511 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12512 } 12513 12514 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12515 } 12516 12517 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12518 bool DefinitionRequired) { 12519 // Ignore any vtable uses in unevaluated operands or for classes that do 12520 // not have a vtable. 12521 if (!Class->isDynamicClass() || Class->isDependentContext() || 12522 CurContext->isDependentContext() || isUnevaluatedContext()) 12523 return; 12524 12525 // Try to insert this class into the map. 12526 LoadExternalVTableUses(); 12527 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12528 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12529 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12530 if (!Pos.second) { 12531 // If we already had an entry, check to see if we are promoting this vtable 12532 // to required a definition. If so, we need to reappend to the VTableUses 12533 // list, since we may have already processed the first entry. 12534 if (DefinitionRequired && !Pos.first->second) { 12535 Pos.first->second = true; 12536 } else { 12537 // Otherwise, we can early exit. 12538 return; 12539 } 12540 } else { 12541 // The Microsoft ABI requires that we perform the destructor body 12542 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12543 // the deleting destructor is emitted with the vtable, not with the 12544 // destructor definition as in the Itanium ABI. 12545 // If it has a definition, we do the check at that point instead. 12546 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12547 Class->hasUserDeclaredDestructor() && 12548 !Class->getDestructor()->isDefined() && 12549 !Class->getDestructor()->isDeleted()) { 12550 CXXDestructorDecl *DD = Class->getDestructor(); 12551 ContextRAII SavedContext(*this, DD); 12552 CheckDestructor(DD); 12553 } 12554 } 12555 12556 // Local classes need to have their virtual members marked 12557 // immediately. For all other classes, we mark their virtual members 12558 // at the end of the translation unit. 12559 if (Class->isLocalClass()) 12560 MarkVirtualMembersReferenced(Loc, Class); 12561 else 12562 VTableUses.push_back(std::make_pair(Class, Loc)); 12563 } 12564 12565 bool Sema::DefineUsedVTables() { 12566 LoadExternalVTableUses(); 12567 if (VTableUses.empty()) 12568 return false; 12569 12570 // Note: The VTableUses vector could grow as a result of marking 12571 // the members of a class as "used", so we check the size each 12572 // time through the loop and prefer indices (which are stable) to 12573 // iterators (which are not). 12574 bool DefinedAnything = false; 12575 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12576 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12577 if (!Class) 12578 continue; 12579 12580 SourceLocation Loc = VTableUses[I].second; 12581 12582 bool DefineVTable = true; 12583 12584 // If this class has a key function, but that key function is 12585 // defined in another translation unit, we don't need to emit the 12586 // vtable even though we're using it. 12587 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12588 if (KeyFunction && !KeyFunction->hasBody()) { 12589 // The key function is in another translation unit. 12590 DefineVTable = false; 12591 TemplateSpecializationKind TSK = 12592 KeyFunction->getTemplateSpecializationKind(); 12593 assert(TSK != TSK_ExplicitInstantiationDefinition && 12594 TSK != TSK_ImplicitInstantiation && 12595 "Instantiations don't have key functions"); 12596 (void)TSK; 12597 } else if (!KeyFunction) { 12598 // If we have a class with no key function that is the subject 12599 // of an explicit instantiation declaration, suppress the 12600 // vtable; it will live with the explicit instantiation 12601 // definition. 12602 bool IsExplicitInstantiationDeclaration 12603 = Class->getTemplateSpecializationKind() 12604 == TSK_ExplicitInstantiationDeclaration; 12605 for (auto R : Class->redecls()) { 12606 TemplateSpecializationKind TSK 12607 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 12608 if (TSK == TSK_ExplicitInstantiationDeclaration) 12609 IsExplicitInstantiationDeclaration = true; 12610 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12611 IsExplicitInstantiationDeclaration = false; 12612 break; 12613 } 12614 } 12615 12616 if (IsExplicitInstantiationDeclaration) 12617 DefineVTable = false; 12618 } 12619 12620 // The exception specifications for all virtual members may be needed even 12621 // if we are not providing an authoritative form of the vtable in this TU. 12622 // We may choose to emit it available_externally anyway. 12623 if (!DefineVTable) { 12624 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12625 continue; 12626 } 12627 12628 // Mark all of the virtual members of this class as referenced, so 12629 // that we can build a vtable. Then, tell the AST consumer that a 12630 // vtable for this class is required. 12631 DefinedAnything = true; 12632 MarkVirtualMembersReferenced(Loc, Class); 12633 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12634 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12635 12636 // Optionally warn if we're emitting a weak vtable. 12637 if (Class->isExternallyVisible() && 12638 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12639 const FunctionDecl *KeyFunctionDef = nullptr; 12640 if (!KeyFunction || 12641 (KeyFunction->hasBody(KeyFunctionDef) && 12642 KeyFunctionDef->isInlined())) 12643 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12644 TSK_ExplicitInstantiationDefinition 12645 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12646 << Class; 12647 } 12648 } 12649 VTableUses.clear(); 12650 12651 return DefinedAnything; 12652 } 12653 12654 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12655 const CXXRecordDecl *RD) { 12656 for (const auto *I : RD->methods()) 12657 if (I->isVirtual() && !I->isPure()) 12658 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 12659 } 12660 12661 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12662 const CXXRecordDecl *RD) { 12663 // Mark all functions which will appear in RD's vtable as used. 12664 CXXFinalOverriderMap FinalOverriders; 12665 RD->getFinalOverriders(FinalOverriders); 12666 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12667 E = FinalOverriders.end(); 12668 I != E; ++I) { 12669 for (OverridingMethods::const_iterator OI = I->second.begin(), 12670 OE = I->second.end(); 12671 OI != OE; ++OI) { 12672 assert(OI->second.size() > 0 && "no final overrider"); 12673 CXXMethodDecl *Overrider = OI->second.front().Method; 12674 12675 // C++ [basic.def.odr]p2: 12676 // [...] A virtual member function is used if it is not pure. [...] 12677 if (!Overrider->isPure()) 12678 MarkFunctionReferenced(Loc, Overrider); 12679 } 12680 } 12681 12682 // Only classes that have virtual bases need a VTT. 12683 if (RD->getNumVBases() == 0) 12684 return; 12685 12686 for (const auto &I : RD->bases()) { 12687 const CXXRecordDecl *Base = 12688 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 12689 if (Base->getNumVBases() == 0) 12690 continue; 12691 MarkVirtualMembersReferenced(Loc, Base); 12692 } 12693 } 12694 12695 /// SetIvarInitializers - This routine builds initialization ASTs for the 12696 /// Objective-C implementation whose ivars need be initialized. 12697 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12698 if (!getLangOpts().CPlusPlus) 12699 return; 12700 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12701 SmallVector<ObjCIvarDecl*, 8> ivars; 12702 CollectIvarsToConstructOrDestruct(OID, ivars); 12703 if (ivars.empty()) 12704 return; 12705 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12706 for (unsigned i = 0; i < ivars.size(); i++) { 12707 FieldDecl *Field = ivars[i]; 12708 if (Field->isInvalidDecl()) 12709 continue; 12710 12711 CXXCtorInitializer *Member; 12712 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12713 InitializationKind InitKind = 12714 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12715 12716 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12717 ExprResult MemberInit = 12718 InitSeq.Perform(*this, InitEntity, InitKind, None); 12719 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12720 // Note, MemberInit could actually come back empty if no initialization 12721 // is required (e.g., because it would call a trivial default constructor) 12722 if (!MemberInit.get() || MemberInit.isInvalid()) 12723 continue; 12724 12725 Member = 12726 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12727 SourceLocation(), 12728 MemberInit.getAs<Expr>(), 12729 SourceLocation()); 12730 AllToInit.push_back(Member); 12731 12732 // Be sure that the destructor is accessible and is marked as referenced. 12733 if (const RecordType *RecordTy 12734 = Context.getBaseElementType(Field->getType()) 12735 ->getAs<RecordType>()) { 12736 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12737 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12738 MarkFunctionReferenced(Field->getLocation(), Destructor); 12739 CheckDestructorAccess(Field->getLocation(), Destructor, 12740 PDiag(diag::err_access_dtor_ivar) 12741 << Context.getBaseElementType(Field->getType())); 12742 } 12743 } 12744 } 12745 ObjCImplementation->setIvarInitializers(Context, 12746 AllToInit.data(), AllToInit.size()); 12747 } 12748 } 12749 12750 static 12751 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12752 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12753 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12754 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12755 Sema &S) { 12756 if (Ctor->isInvalidDecl()) 12757 return; 12758 12759 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12760 12761 // Target may not be determinable yet, for instance if this is a dependent 12762 // call in an uninstantiated template. 12763 if (Target) { 12764 const FunctionDecl *FNTarget = nullptr; 12765 (void)Target->hasBody(FNTarget); 12766 Target = const_cast<CXXConstructorDecl*>( 12767 cast_or_null<CXXConstructorDecl>(FNTarget)); 12768 } 12769 12770 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12771 // Avoid dereferencing a null pointer here. 12772 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 12773 12774 if (!Current.insert(Canonical)) 12775 return; 12776 12777 // We know that beyond here, we aren't chaining into a cycle. 12778 if (!Target || !Target->isDelegatingConstructor() || 12779 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12780 Valid.insert(Current.begin(), Current.end()); 12781 Current.clear(); 12782 // We've hit a cycle. 12783 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12784 Current.count(TCanonical)) { 12785 // If we haven't diagnosed this cycle yet, do so now. 12786 if (!Invalid.count(TCanonical)) { 12787 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12788 diag::warn_delegating_ctor_cycle) 12789 << Ctor; 12790 12791 // Don't add a note for a function delegating directly to itself. 12792 if (TCanonical != Canonical) 12793 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12794 12795 CXXConstructorDecl *C = Target; 12796 while (C->getCanonicalDecl() != Canonical) { 12797 const FunctionDecl *FNTarget = nullptr; 12798 (void)C->getTargetConstructor()->hasBody(FNTarget); 12799 assert(FNTarget && "Ctor cycle through bodiless function"); 12800 12801 C = const_cast<CXXConstructorDecl*>( 12802 cast<CXXConstructorDecl>(FNTarget)); 12803 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12804 } 12805 } 12806 12807 Invalid.insert(Current.begin(), Current.end()); 12808 Current.clear(); 12809 } else { 12810 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12811 } 12812 } 12813 12814 12815 void Sema::CheckDelegatingCtorCycles() { 12816 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12817 12818 for (DelegatingCtorDeclsType::iterator 12819 I = DelegatingCtorDecls.begin(ExternalSource), 12820 E = DelegatingCtorDecls.end(); 12821 I != E; ++I) 12822 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12823 12824 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12825 CE = Invalid.end(); 12826 CI != CE; ++CI) 12827 (*CI)->setInvalidDecl(); 12828 } 12829 12830 namespace { 12831 /// \brief AST visitor that finds references to the 'this' expression. 12832 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12833 Sema &S; 12834 12835 public: 12836 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12837 12838 bool VisitCXXThisExpr(CXXThisExpr *E) { 12839 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12840 << E->isImplicit(); 12841 return false; 12842 } 12843 }; 12844 } 12845 12846 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12847 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12848 if (!TSInfo) 12849 return false; 12850 12851 TypeLoc TL = TSInfo->getTypeLoc(); 12852 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12853 if (!ProtoTL) 12854 return false; 12855 12856 // C++11 [expr.prim.general]p3: 12857 // [The expression this] shall not appear before the optional 12858 // cv-qualifier-seq and it shall not appear within the declaration of a 12859 // static member function (although its type and value category are defined 12860 // within a static member function as they are within a non-static member 12861 // function). [ Note: this is because declaration matching does not occur 12862 // until the complete declarator is known. - end note ] 12863 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12864 FindCXXThisExpr Finder(*this); 12865 12866 // If the return type came after the cv-qualifier-seq, check it now. 12867 if (Proto->hasTrailingReturn() && 12868 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 12869 return true; 12870 12871 // Check the exception specification. 12872 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12873 return true; 12874 12875 return checkThisInStaticMemberFunctionAttributes(Method); 12876 } 12877 12878 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12879 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12880 if (!TSInfo) 12881 return false; 12882 12883 TypeLoc TL = TSInfo->getTypeLoc(); 12884 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12885 if (!ProtoTL) 12886 return false; 12887 12888 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12889 FindCXXThisExpr Finder(*this); 12890 12891 switch (Proto->getExceptionSpecType()) { 12892 case EST_Uninstantiated: 12893 case EST_Unevaluated: 12894 case EST_BasicNoexcept: 12895 case EST_DynamicNone: 12896 case EST_MSAny: 12897 case EST_None: 12898 break; 12899 12900 case EST_ComputedNoexcept: 12901 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12902 return true; 12903 12904 case EST_Dynamic: 12905 for (const auto &E : Proto->exceptions()) { 12906 if (!Finder.TraverseType(E)) 12907 return true; 12908 } 12909 break; 12910 } 12911 12912 return false; 12913 } 12914 12915 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12916 FindCXXThisExpr Finder(*this); 12917 12918 // Check attributes. 12919 for (const auto *A : Method->attrs()) { 12920 // FIXME: This should be emitted by tblgen. 12921 Expr *Arg = nullptr; 12922 ArrayRef<Expr *> Args; 12923 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 12924 Arg = G->getArg(); 12925 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 12926 Arg = G->getArg(); 12927 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 12928 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12929 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 12930 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12931 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 12932 Arg = ETLF->getSuccessValue(); 12933 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12934 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 12935 Arg = STLF->getSuccessValue(); 12936 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12937 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 12938 Arg = LR->getArg(); 12939 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 12940 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12941 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 12942 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12943 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 12944 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12945 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 12946 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12947 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 12948 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12949 12950 if (Arg && !Finder.TraverseStmt(Arg)) 12951 return true; 12952 12953 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12954 if (!Finder.TraverseStmt(Args[I])) 12955 return true; 12956 } 12957 } 12958 12959 return false; 12960 } 12961 12962 void 12963 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12964 ArrayRef<ParsedType> DynamicExceptions, 12965 ArrayRef<SourceRange> DynamicExceptionRanges, 12966 Expr *NoexceptExpr, 12967 SmallVectorImpl<QualType> &Exceptions, 12968 FunctionProtoType::ExtProtoInfo &EPI) { 12969 Exceptions.clear(); 12970 EPI.ExceptionSpecType = EST; 12971 if (EST == EST_Dynamic) { 12972 Exceptions.reserve(DynamicExceptions.size()); 12973 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12974 // FIXME: Preserve type source info. 12975 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12976 12977 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12978 collectUnexpandedParameterPacks(ET, Unexpanded); 12979 if (!Unexpanded.empty()) { 12980 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12981 UPPC_ExceptionType, 12982 Unexpanded); 12983 continue; 12984 } 12985 12986 // Check that the type is valid for an exception spec, and 12987 // drop it if not. 12988 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12989 Exceptions.push_back(ET); 12990 } 12991 EPI.NumExceptions = Exceptions.size(); 12992 EPI.Exceptions = Exceptions.data(); 12993 return; 12994 } 12995 12996 if (EST == EST_ComputedNoexcept) { 12997 // If an error occurred, there's no expression here. 12998 if (NoexceptExpr) { 12999 assert((NoexceptExpr->isTypeDependent() || 13000 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13001 Context.BoolTy) && 13002 "Parser should have made sure that the expression is boolean"); 13003 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13004 EPI.ExceptionSpecType = EST_BasicNoexcept; 13005 return; 13006 } 13007 13008 if (!NoexceptExpr->isValueDependent()) 13009 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13010 diag::err_noexcept_needs_constant_expression, 13011 /*AllowFold*/ false).get(); 13012 EPI.NoexceptExpr = NoexceptExpr; 13013 } 13014 return; 13015 } 13016 } 13017 13018 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function 13019 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 13020 // Implicitly declared functions (e.g. copy constructors) are 13021 // __host__ __device__ 13022 if (D->isImplicit()) 13023 return CFT_HostDevice; 13024 13025 if (D->hasAttr<CUDAGlobalAttr>()) 13026 return CFT_Global; 13027 13028 if (D->hasAttr<CUDADeviceAttr>()) { 13029 if (D->hasAttr<CUDAHostAttr>()) 13030 return CFT_HostDevice; 13031 return CFT_Device; 13032 } 13033 13034 return CFT_Host; 13035 } 13036 13037 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 13038 CUDAFunctionTarget CalleeTarget) { 13039 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 13040 // Callable from the device only." 13041 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 13042 return true; 13043 13044 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 13045 // Callable from the host only." 13046 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 13047 // Callable from the host only." 13048 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 13049 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 13050 return true; 13051 13052 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 13053 return true; 13054 13055 return false; 13056 } 13057 13058 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13059 /// 13060 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13061 SourceLocation DeclStart, 13062 Declarator &D, Expr *BitWidth, 13063 InClassInitStyle InitStyle, 13064 AccessSpecifier AS, 13065 AttributeList *MSPropertyAttr) { 13066 IdentifierInfo *II = D.getIdentifier(); 13067 if (!II) { 13068 Diag(DeclStart, diag::err_anonymous_property); 13069 return nullptr; 13070 } 13071 SourceLocation Loc = D.getIdentifierLoc(); 13072 13073 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13074 QualType T = TInfo->getType(); 13075 if (getLangOpts().CPlusPlus) { 13076 CheckExtraCXXDefaultArguments(D); 13077 13078 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13079 UPPC_DataMemberType)) { 13080 D.setInvalidType(); 13081 T = Context.IntTy; 13082 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13083 } 13084 } 13085 13086 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13087 13088 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13089 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13090 diag::err_invalid_thread) 13091 << DeclSpec::getSpecifierName(TSCS); 13092 13093 // Check to see if this name was declared as a member previously 13094 NamedDecl *PrevDecl = nullptr; 13095 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13096 LookupName(Previous, S); 13097 switch (Previous.getResultKind()) { 13098 case LookupResult::Found: 13099 case LookupResult::FoundUnresolvedValue: 13100 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13101 break; 13102 13103 case LookupResult::FoundOverloaded: 13104 PrevDecl = Previous.getRepresentativeDecl(); 13105 break; 13106 13107 case LookupResult::NotFound: 13108 case LookupResult::NotFoundInCurrentInstantiation: 13109 case LookupResult::Ambiguous: 13110 break; 13111 } 13112 13113 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13114 // Maybe we will complain about the shadowed template parameter. 13115 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13116 // Just pretend that we didn't see the previous declaration. 13117 PrevDecl = nullptr; 13118 } 13119 13120 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13121 PrevDecl = nullptr; 13122 13123 SourceLocation TSSL = D.getLocStart(); 13124 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13125 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13126 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13127 ProcessDeclAttributes(TUScope, NewPD, D); 13128 NewPD->setAccess(AS); 13129 13130 if (NewPD->isInvalidDecl()) 13131 Record->setInvalidDecl(); 13132 13133 if (D.getDeclSpec().isModulePrivateSpecified()) 13134 NewPD->setModulePrivate(); 13135 13136 if (NewPD->isInvalidDecl() && PrevDecl) { 13137 // Don't introduce NewFD into scope; there's already something 13138 // with the same name in the same scope. 13139 } else if (II) { 13140 PushOnScopeChains(NewPD, S); 13141 } else 13142 Record->addDecl(NewPD); 13143 13144 return NewPD; 13145 } 13146