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