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 Check the validity of a C++ base class specifier. 1300 /// 1301 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1302 /// and returns NULL otherwise. 1303 CXXBaseSpecifier * 1304 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1305 SourceRange SpecifierRange, 1306 bool Virtual, AccessSpecifier Access, 1307 TypeSourceInfo *TInfo, 1308 SourceLocation EllipsisLoc) { 1309 QualType BaseType = TInfo->getType(); 1310 1311 // C++ [class.union]p1: 1312 // A union shall not have base classes. 1313 if (Class->isUnion()) { 1314 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1315 << SpecifierRange; 1316 return nullptr; 1317 } 1318 1319 if (EllipsisLoc.isValid() && 1320 !TInfo->getType()->containsUnexpandedParameterPack()) { 1321 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1322 << TInfo->getTypeLoc().getSourceRange(); 1323 EllipsisLoc = SourceLocation(); 1324 } 1325 1326 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1327 1328 if (BaseType->isDependentType()) { 1329 // Make sure that we don't have circular inheritance among our dependent 1330 // bases. For non-dependent bases, the check for completeness below handles 1331 // this. 1332 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1333 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1334 ((BaseDecl = BaseDecl->getDefinition()) && 1335 findCircularInheritance(Class, BaseDecl))) { 1336 Diag(BaseLoc, diag::err_circular_inheritance) 1337 << BaseType << Context.getTypeDeclType(Class); 1338 1339 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1340 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1341 << BaseType; 1342 1343 return nullptr; 1344 } 1345 } 1346 1347 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1348 Class->getTagKind() == TTK_Class, 1349 Access, TInfo, EllipsisLoc); 1350 } 1351 1352 // Base specifiers must be record types. 1353 if (!BaseType->isRecordType()) { 1354 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1355 return nullptr; 1356 } 1357 1358 // C++ [class.union]p1: 1359 // A union shall not be used as a base class. 1360 if (BaseType->isUnionType()) { 1361 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1362 return nullptr; 1363 } 1364 1365 // C++ [class.derived]p2: 1366 // The class-name in a base-specifier shall not be an incompletely 1367 // defined class. 1368 if (RequireCompleteType(BaseLoc, BaseType, 1369 diag::err_incomplete_base_class, SpecifierRange)) { 1370 Class->setInvalidDecl(); 1371 return nullptr; 1372 } 1373 1374 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1375 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1376 assert(BaseDecl && "Record type has no declaration"); 1377 BaseDecl = BaseDecl->getDefinition(); 1378 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1379 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1380 assert(CXXBaseDecl && "Base type is not a C++ type"); 1381 1382 // A class which contains a flexible array member is not suitable for use as a 1383 // base class: 1384 // - If the layout determines that a base comes before another base, 1385 // the flexible array member would index into the subsequent base. 1386 // - If the layout determines that base comes before the derived class, 1387 // the flexible array member would index into the derived class. 1388 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1389 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1390 << CXXBaseDecl->getDeclName(); 1391 return nullptr; 1392 } 1393 1394 // C++ [class]p3: 1395 // If a class is marked final and it appears as a base-type-specifier in 1396 // base-clause, the program is ill-formed. 1397 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1398 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1399 << CXXBaseDecl->getDeclName() 1400 << FA->isSpelledAsSealed(); 1401 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1402 << CXXBaseDecl->getDeclName() << FA->getRange(); 1403 return nullptr; 1404 } 1405 1406 if (BaseDecl->isInvalidDecl()) 1407 Class->setInvalidDecl(); 1408 1409 // Create the base specifier. 1410 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1411 Class->getTagKind() == TTK_Class, 1412 Access, TInfo, EllipsisLoc); 1413 } 1414 1415 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1416 /// one entry in the base class list of a class specifier, for 1417 /// example: 1418 /// class foo : public bar, virtual private baz { 1419 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1420 BaseResult 1421 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1422 ParsedAttributes &Attributes, 1423 bool Virtual, AccessSpecifier Access, 1424 ParsedType basetype, SourceLocation BaseLoc, 1425 SourceLocation EllipsisLoc) { 1426 if (!classdecl) 1427 return true; 1428 1429 AdjustDeclIfTemplate(classdecl); 1430 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1431 if (!Class) 1432 return true; 1433 1434 // We haven't yet attached the base specifiers. 1435 Class->setIsParsingBaseSpecifiers(); 1436 1437 // We do not support any C++11 attributes on base-specifiers yet. 1438 // Diagnose any attributes we see. 1439 if (!Attributes.empty()) { 1440 for (AttributeList *Attr = Attributes.getList(); Attr; 1441 Attr = Attr->getNext()) { 1442 if (Attr->isInvalid() || 1443 Attr->getKind() == AttributeList::IgnoredAttribute) 1444 continue; 1445 Diag(Attr->getLoc(), 1446 Attr->getKind() == AttributeList::UnknownAttribute 1447 ? diag::warn_unknown_attribute_ignored 1448 : diag::err_base_specifier_attribute) 1449 << Attr->getName(); 1450 } 1451 } 1452 1453 TypeSourceInfo *TInfo = nullptr; 1454 GetTypeFromParser(basetype, &TInfo); 1455 1456 if (EllipsisLoc.isInvalid() && 1457 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1458 UPPC_BaseType)) 1459 return true; 1460 1461 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1462 Virtual, Access, TInfo, 1463 EllipsisLoc)) 1464 return BaseSpec; 1465 else 1466 Class->setInvalidDecl(); 1467 1468 return true; 1469 } 1470 1471 /// \brief Performs the actual work of attaching the given base class 1472 /// specifiers to a C++ class. 1473 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1474 unsigned NumBases) { 1475 if (NumBases == 0) 1476 return false; 1477 1478 // Used to keep track of which base types we have already seen, so 1479 // that we can properly diagnose redundant direct base types. Note 1480 // that the key is always the unqualified canonical type of the base 1481 // class. 1482 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1483 1484 // Copy non-redundant base specifiers into permanent storage. 1485 unsigned NumGoodBases = 0; 1486 bool Invalid = false; 1487 for (unsigned idx = 0; idx < NumBases; ++idx) { 1488 QualType NewBaseType 1489 = Context.getCanonicalType(Bases[idx]->getType()); 1490 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1491 1492 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1493 if (KnownBase) { 1494 // C++ [class.mi]p3: 1495 // A class shall not be specified as a direct base class of a 1496 // derived class more than once. 1497 Diag(Bases[idx]->getLocStart(), 1498 diag::err_duplicate_base_class) 1499 << KnownBase->getType() 1500 << Bases[idx]->getSourceRange(); 1501 1502 // Delete the duplicate base class specifier; we're going to 1503 // overwrite its pointer later. 1504 Context.Deallocate(Bases[idx]); 1505 1506 Invalid = true; 1507 } else { 1508 // Okay, add this new base class. 1509 KnownBase = Bases[idx]; 1510 Bases[NumGoodBases++] = Bases[idx]; 1511 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1512 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1513 if (Class->isInterface() && 1514 (!RD->isInterface() || 1515 KnownBase->getAccessSpecifier() != AS_public)) { 1516 // The Microsoft extension __interface does not permit bases that 1517 // are not themselves public interfaces. 1518 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1519 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1520 << RD->getSourceRange(); 1521 Invalid = true; 1522 } 1523 if (RD->hasAttr<WeakAttr>()) 1524 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1525 } 1526 } 1527 } 1528 1529 // Attach the remaining base class specifiers to the derived class. 1530 Class->setBases(Bases, NumGoodBases); 1531 1532 // Delete the remaining (good) base class specifiers, since their 1533 // data has been copied into the CXXRecordDecl. 1534 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1535 Context.Deallocate(Bases[idx]); 1536 1537 return Invalid; 1538 } 1539 1540 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1541 /// class, after checking whether there are any duplicate base 1542 /// classes. 1543 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1544 unsigned NumBases) { 1545 if (!ClassDecl || !Bases || !NumBases) 1546 return; 1547 1548 AdjustDeclIfTemplate(ClassDecl); 1549 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1550 } 1551 1552 /// \brief Determine whether the type \p Derived is a C++ class that is 1553 /// derived from the type \p Base. 1554 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1555 if (!getLangOpts().CPlusPlus) 1556 return false; 1557 1558 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1559 if (!DerivedRD) 1560 return false; 1561 1562 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1563 if (!BaseRD) 1564 return false; 1565 1566 // If either the base or the derived type is invalid, don't try to 1567 // check whether one is derived from the other. 1568 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1569 return false; 1570 1571 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1572 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1573 } 1574 1575 /// \brief Determine whether the type \p Derived is a C++ class that is 1576 /// derived from the type \p Base. 1577 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1578 if (!getLangOpts().CPlusPlus) 1579 return false; 1580 1581 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1582 if (!DerivedRD) 1583 return false; 1584 1585 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1586 if (!BaseRD) 1587 return false; 1588 1589 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1590 } 1591 1592 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1593 CXXCastPath &BasePathArray) { 1594 assert(BasePathArray.empty() && "Base path array must be empty!"); 1595 assert(Paths.isRecordingPaths() && "Must record paths!"); 1596 1597 const CXXBasePath &Path = Paths.front(); 1598 1599 // We first go backward and check if we have a virtual base. 1600 // FIXME: It would be better if CXXBasePath had the base specifier for 1601 // the nearest virtual base. 1602 unsigned Start = 0; 1603 for (unsigned I = Path.size(); I != 0; --I) { 1604 if (Path[I - 1].Base->isVirtual()) { 1605 Start = I - 1; 1606 break; 1607 } 1608 } 1609 1610 // Now add all bases. 1611 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1612 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1613 } 1614 1615 /// \brief Determine whether the given base path includes a virtual 1616 /// base class. 1617 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1618 for (CXXCastPath::const_iterator B = BasePath.begin(), 1619 BEnd = BasePath.end(); 1620 B != BEnd; ++B) 1621 if ((*B)->isVirtual()) 1622 return true; 1623 1624 return false; 1625 } 1626 1627 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1628 /// conversion (where Derived and Base are class types) is 1629 /// well-formed, meaning that the conversion is unambiguous (and 1630 /// that all of the base classes are accessible). Returns true 1631 /// and emits a diagnostic if the code is ill-formed, returns false 1632 /// otherwise. Loc is the location where this routine should point to 1633 /// if there is an error, and Range is the source range to highlight 1634 /// if there is an error. 1635 bool 1636 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1637 unsigned InaccessibleBaseID, 1638 unsigned AmbigiousBaseConvID, 1639 SourceLocation Loc, SourceRange Range, 1640 DeclarationName Name, 1641 CXXCastPath *BasePath) { 1642 // First, determine whether the path from Derived to Base is 1643 // ambiguous. This is slightly more expensive than checking whether 1644 // the Derived to Base conversion exists, because here we need to 1645 // explore multiple paths to determine if there is an ambiguity. 1646 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1647 /*DetectVirtual=*/false); 1648 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1649 assert(DerivationOkay && 1650 "Can only be used with a derived-to-base conversion"); 1651 (void)DerivationOkay; 1652 1653 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1654 if (InaccessibleBaseID) { 1655 // Check that the base class can be accessed. 1656 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1657 InaccessibleBaseID)) { 1658 case AR_inaccessible: 1659 return true; 1660 case AR_accessible: 1661 case AR_dependent: 1662 case AR_delayed: 1663 break; 1664 } 1665 } 1666 1667 // Build a base path if necessary. 1668 if (BasePath) 1669 BuildBasePathArray(Paths, *BasePath); 1670 return false; 1671 } 1672 1673 if (AmbigiousBaseConvID) { 1674 // We know that the derived-to-base conversion is ambiguous, and 1675 // we're going to produce a diagnostic. Perform the derived-to-base 1676 // search just one more time to compute all of the possible paths so 1677 // that we can print them out. This is more expensive than any of 1678 // the previous derived-to-base checks we've done, but at this point 1679 // performance isn't as much of an issue. 1680 Paths.clear(); 1681 Paths.setRecordingPaths(true); 1682 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1683 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1684 (void)StillOkay; 1685 1686 // Build up a textual representation of the ambiguous paths, e.g., 1687 // D -> B -> A, that will be used to illustrate the ambiguous 1688 // conversions in the diagnostic. We only print one of the paths 1689 // to each base class subobject. 1690 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1691 1692 Diag(Loc, AmbigiousBaseConvID) 1693 << Derived << Base << PathDisplayStr << Range << Name; 1694 } 1695 return true; 1696 } 1697 1698 bool 1699 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1700 SourceLocation Loc, SourceRange Range, 1701 CXXCastPath *BasePath, 1702 bool IgnoreAccess) { 1703 return CheckDerivedToBaseConversion(Derived, Base, 1704 IgnoreAccess ? 0 1705 : diag::err_upcast_to_inaccessible_base, 1706 diag::err_ambiguous_derived_to_base_conv, 1707 Loc, Range, DeclarationName(), 1708 BasePath); 1709 } 1710 1711 1712 /// @brief Builds a string representing ambiguous paths from a 1713 /// specific derived class to different subobjects of the same base 1714 /// class. 1715 /// 1716 /// This function builds a string that can be used in error messages 1717 /// to show the different paths that one can take through the 1718 /// inheritance hierarchy to go from the derived class to different 1719 /// subobjects of a base class. The result looks something like this: 1720 /// @code 1721 /// struct D -> struct B -> struct A 1722 /// struct D -> struct C -> struct A 1723 /// @endcode 1724 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1725 std::string PathDisplayStr; 1726 std::set<unsigned> DisplayedPaths; 1727 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1728 Path != Paths.end(); ++Path) { 1729 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1730 // We haven't displayed a path to this particular base 1731 // class subobject yet. 1732 PathDisplayStr += "\n "; 1733 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1734 for (CXXBasePath::const_iterator Element = Path->begin(); 1735 Element != Path->end(); ++Element) 1736 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1737 } 1738 } 1739 1740 return PathDisplayStr; 1741 } 1742 1743 //===----------------------------------------------------------------------===// 1744 // C++ class member Handling 1745 //===----------------------------------------------------------------------===// 1746 1747 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1748 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1749 SourceLocation ASLoc, 1750 SourceLocation ColonLoc, 1751 AttributeList *Attrs) { 1752 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1753 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1754 ASLoc, ColonLoc); 1755 CurContext->addHiddenDecl(ASDecl); 1756 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1757 } 1758 1759 /// CheckOverrideControl - Check C++11 override control semantics. 1760 void Sema::CheckOverrideControl(NamedDecl *D) { 1761 if (D->isInvalidDecl()) 1762 return; 1763 1764 // We only care about "override" and "final" declarations. 1765 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1766 return; 1767 1768 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1769 1770 // We can't check dependent instance methods. 1771 if (MD && MD->isInstance() && 1772 (MD->getParent()->hasAnyDependentBases() || 1773 MD->getType()->isDependentType())) 1774 return; 1775 1776 if (MD && !MD->isVirtual()) { 1777 // If we have a non-virtual method, check if if hides a virtual method. 1778 // (In that case, it's most likely the method has the wrong type.) 1779 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1780 FindHiddenVirtualMethods(MD, OverloadedMethods); 1781 1782 if (!OverloadedMethods.empty()) { 1783 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1784 Diag(OA->getLocation(), 1785 diag::override_keyword_hides_virtual_member_function) 1786 << "override" << (OverloadedMethods.size() > 1); 1787 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1788 Diag(FA->getLocation(), 1789 diag::override_keyword_hides_virtual_member_function) 1790 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1791 << (OverloadedMethods.size() > 1); 1792 } 1793 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1794 MD->setInvalidDecl(); 1795 return; 1796 } 1797 // Fall through into the general case diagnostic. 1798 // FIXME: We might want to attempt typo correction here. 1799 } 1800 1801 if (!MD || !MD->isVirtual()) { 1802 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1803 Diag(OA->getLocation(), 1804 diag::override_keyword_only_allowed_on_virtual_member_functions) 1805 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1806 D->dropAttr<OverrideAttr>(); 1807 } 1808 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1809 Diag(FA->getLocation(), 1810 diag::override_keyword_only_allowed_on_virtual_member_functions) 1811 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1812 << FixItHint::CreateRemoval(FA->getLocation()); 1813 D->dropAttr<FinalAttr>(); 1814 } 1815 return; 1816 } 1817 1818 // C++11 [class.virtual]p5: 1819 // If a virtual function is marked with the virt-specifier override and 1820 // does not override a member function of a base class, the program is 1821 // ill-formed. 1822 bool HasOverriddenMethods = 1823 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1824 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1825 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1826 << MD->getDeclName(); 1827 } 1828 1829 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1830 /// function overrides a virtual member function marked 'final', according to 1831 /// C++11 [class.virtual]p4. 1832 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1833 const CXXMethodDecl *Old) { 1834 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1835 if (!FA) 1836 return false; 1837 1838 Diag(New->getLocation(), diag::err_final_function_overridden) 1839 << New->getDeclName() 1840 << FA->isSpelledAsSealed(); 1841 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1842 return true; 1843 } 1844 1845 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1846 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1847 // FIXME: Destruction of ObjC lifetime types has side-effects. 1848 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1849 return !RD->isCompleteDefinition() || 1850 !RD->hasTrivialDefaultConstructor() || 1851 !RD->hasTrivialDestructor(); 1852 return false; 1853 } 1854 1855 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1856 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1857 if (it->isDeclspecPropertyAttribute()) 1858 return it; 1859 return nullptr; 1860 } 1861 1862 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1863 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1864 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1865 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1866 /// present (but parsing it has been deferred). 1867 NamedDecl * 1868 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1869 MultiTemplateParamsArg TemplateParameterLists, 1870 Expr *BW, const VirtSpecifiers &VS, 1871 InClassInitStyle InitStyle) { 1872 const DeclSpec &DS = D.getDeclSpec(); 1873 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1874 DeclarationName Name = NameInfo.getName(); 1875 SourceLocation Loc = NameInfo.getLoc(); 1876 1877 // For anonymous bitfields, the location should point to the type. 1878 if (Loc.isInvalid()) 1879 Loc = D.getLocStart(); 1880 1881 Expr *BitWidth = static_cast<Expr*>(BW); 1882 1883 assert(isa<CXXRecordDecl>(CurContext)); 1884 assert(!DS.isFriendSpecified()); 1885 1886 bool isFunc = D.isDeclarationOfFunction(); 1887 1888 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1889 // The Microsoft extension __interface only permits public member functions 1890 // and prohibits constructors, destructors, operators, non-public member 1891 // functions, static methods and data members. 1892 unsigned InvalidDecl; 1893 bool ShowDeclName = true; 1894 if (!isFunc) 1895 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1896 else if (AS != AS_public) 1897 InvalidDecl = 2; 1898 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1899 InvalidDecl = 3; 1900 else switch (Name.getNameKind()) { 1901 case DeclarationName::CXXConstructorName: 1902 InvalidDecl = 4; 1903 ShowDeclName = false; 1904 break; 1905 1906 case DeclarationName::CXXDestructorName: 1907 InvalidDecl = 5; 1908 ShowDeclName = false; 1909 break; 1910 1911 case DeclarationName::CXXOperatorName: 1912 case DeclarationName::CXXConversionFunctionName: 1913 InvalidDecl = 6; 1914 break; 1915 1916 default: 1917 InvalidDecl = 0; 1918 break; 1919 } 1920 1921 if (InvalidDecl) { 1922 if (ShowDeclName) 1923 Diag(Loc, diag::err_invalid_member_in_interface) 1924 << (InvalidDecl-1) << Name; 1925 else 1926 Diag(Loc, diag::err_invalid_member_in_interface) 1927 << (InvalidDecl-1) << ""; 1928 return nullptr; 1929 } 1930 } 1931 1932 // C++ 9.2p6: A member shall not be declared to have automatic storage 1933 // duration (auto, register) or with the extern storage-class-specifier. 1934 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1935 // data members and cannot be applied to names declared const or static, 1936 // and cannot be applied to reference members. 1937 switch (DS.getStorageClassSpec()) { 1938 case DeclSpec::SCS_unspecified: 1939 case DeclSpec::SCS_typedef: 1940 case DeclSpec::SCS_static: 1941 break; 1942 case DeclSpec::SCS_mutable: 1943 if (isFunc) { 1944 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1945 1946 // FIXME: It would be nicer if the keyword was ignored only for this 1947 // declarator. Otherwise we could get follow-up errors. 1948 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1949 } 1950 break; 1951 default: 1952 Diag(DS.getStorageClassSpecLoc(), 1953 diag::err_storageclass_invalid_for_member); 1954 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1955 break; 1956 } 1957 1958 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1959 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1960 !isFunc); 1961 1962 if (DS.isConstexprSpecified() && isInstField) { 1963 SemaDiagnosticBuilder B = 1964 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1965 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1966 if (InitStyle == ICIS_NoInit) { 1967 B << 0 << 0; 1968 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 1969 B << FixItHint::CreateRemoval(ConstexprLoc); 1970 else { 1971 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1972 D.getMutableDeclSpec().ClearConstexprSpec(); 1973 const char *PrevSpec; 1974 unsigned DiagID; 1975 bool Failed = D.getMutableDeclSpec().SetTypeQual( 1976 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 1977 (void)Failed; 1978 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1979 } 1980 } else { 1981 B << 1; 1982 const char *PrevSpec; 1983 unsigned DiagID; 1984 if (D.getMutableDeclSpec().SetStorageClassSpec( 1985 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 1986 Context.getPrintingPolicy())) { 1987 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1988 "This is the only DeclSpec that should fail to be applied"); 1989 B << 1; 1990 } else { 1991 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1992 isInstField = false; 1993 } 1994 } 1995 } 1996 1997 NamedDecl *Member; 1998 if (isInstField) { 1999 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2000 2001 // Data members must have identifiers for names. 2002 if (!Name.isIdentifier()) { 2003 Diag(Loc, diag::err_bad_variable_name) 2004 << Name; 2005 return nullptr; 2006 } 2007 2008 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2009 2010 // Member field could not be with "template" keyword. 2011 // So TemplateParameterLists should be empty in this case. 2012 if (TemplateParameterLists.size()) { 2013 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2014 if (TemplateParams->size()) { 2015 // There is no such thing as a member field template. 2016 Diag(D.getIdentifierLoc(), diag::err_template_member) 2017 << II 2018 << SourceRange(TemplateParams->getTemplateLoc(), 2019 TemplateParams->getRAngleLoc()); 2020 } else { 2021 // There is an extraneous 'template<>' for this member. 2022 Diag(TemplateParams->getTemplateLoc(), 2023 diag::err_template_member_noparams) 2024 << II 2025 << SourceRange(TemplateParams->getTemplateLoc(), 2026 TemplateParams->getRAngleLoc()); 2027 } 2028 return nullptr; 2029 } 2030 2031 if (SS.isSet() && !SS.isInvalid()) { 2032 // The user provided a superfluous scope specifier inside a class 2033 // definition: 2034 // 2035 // class X { 2036 // int X::member; 2037 // }; 2038 if (DeclContext *DC = computeDeclContext(SS, false)) 2039 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2040 else 2041 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2042 << Name << SS.getRange(); 2043 2044 SS.clear(); 2045 } 2046 2047 AttributeList *MSPropertyAttr = 2048 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2049 if (MSPropertyAttr) { 2050 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2051 BitWidth, InitStyle, AS, MSPropertyAttr); 2052 if (!Member) 2053 return nullptr; 2054 isInstField = false; 2055 } else { 2056 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2057 BitWidth, InitStyle, AS); 2058 assert(Member && "HandleField never returns null"); 2059 } 2060 } else { 2061 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2062 2063 Member = HandleDeclarator(S, D, TemplateParameterLists); 2064 if (!Member) 2065 return nullptr; 2066 2067 // Non-instance-fields can't have a bitfield. 2068 if (BitWidth) { 2069 if (Member->isInvalidDecl()) { 2070 // don't emit another diagnostic. 2071 } else if (isa<VarDecl>(Member)) { 2072 // C++ 9.6p3: A bit-field shall not be a static member. 2073 // "static member 'A' cannot be a bit-field" 2074 Diag(Loc, diag::err_static_not_bitfield) 2075 << Name << BitWidth->getSourceRange(); 2076 } else if (isa<TypedefDecl>(Member)) { 2077 // "typedef member 'x' cannot be a bit-field" 2078 Diag(Loc, diag::err_typedef_not_bitfield) 2079 << Name << BitWidth->getSourceRange(); 2080 } else { 2081 // A function typedef ("typedef int f(); f a;"). 2082 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2083 Diag(Loc, diag::err_not_integral_type_bitfield) 2084 << Name << cast<ValueDecl>(Member)->getType() 2085 << BitWidth->getSourceRange(); 2086 } 2087 2088 BitWidth = nullptr; 2089 Member->setInvalidDecl(); 2090 } 2091 2092 Member->setAccess(AS); 2093 2094 // If we have declared a member function template or static data member 2095 // template, set the access of the templated declaration as well. 2096 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2097 FunTmpl->getTemplatedDecl()->setAccess(AS); 2098 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2099 VarTmpl->getTemplatedDecl()->setAccess(AS); 2100 } 2101 2102 if (VS.isOverrideSpecified()) 2103 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2104 if (VS.isFinalSpecified()) 2105 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2106 VS.isFinalSpelledSealed())); 2107 2108 if (VS.getLastLocation().isValid()) { 2109 // Update the end location of a method that has a virt-specifiers. 2110 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2111 MD->setRangeEnd(VS.getLastLocation()); 2112 } 2113 2114 CheckOverrideControl(Member); 2115 2116 assert((Name || isInstField) && "No identifier for non-field ?"); 2117 2118 if (isInstField) { 2119 FieldDecl *FD = cast<FieldDecl>(Member); 2120 FieldCollector->Add(FD); 2121 2122 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2123 // Remember all explicit private FieldDecls that have a name, no side 2124 // effects and are not part of a dependent type declaration. 2125 if (!FD->isImplicit() && FD->getDeclName() && 2126 FD->getAccess() == AS_private && 2127 !FD->hasAttr<UnusedAttr>() && 2128 !FD->getParent()->isDependentContext() && 2129 !InitializationHasSideEffects(*FD)) 2130 UnusedPrivateFields.insert(FD); 2131 } 2132 } 2133 2134 return Member; 2135 } 2136 2137 namespace { 2138 class UninitializedFieldVisitor 2139 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2140 Sema &S; 2141 // List of Decls to generate a warning on. Also remove Decls that become 2142 // initialized. 2143 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2144 // If non-null, add a note to the warning pointing back to the constructor. 2145 const CXXConstructorDecl *Constructor; 2146 public: 2147 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2148 UninitializedFieldVisitor(Sema &S, 2149 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2150 const CXXConstructorDecl *Constructor) 2151 : Inherited(S.Context), S(S), Decls(Decls), 2152 Constructor(Constructor) { } 2153 2154 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2155 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2156 return; 2157 2158 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2159 // or union. 2160 MemberExpr *FieldME = ME; 2161 2162 Expr *Base = ME; 2163 while (isa<MemberExpr>(Base)) { 2164 ME = cast<MemberExpr>(Base); 2165 2166 if (isa<VarDecl>(ME->getMemberDecl())) 2167 return; 2168 2169 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2170 if (!FD->isAnonymousStructOrUnion()) 2171 FieldME = ME; 2172 2173 Base = ME->getBase(); 2174 } 2175 2176 if (!isa<CXXThisExpr>(Base)) 2177 return; 2178 2179 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2180 2181 if (!Decls.count(FoundVD)) 2182 return; 2183 2184 const bool IsReference = FoundVD->getType()->isReferenceType(); 2185 2186 // Prevent double warnings on use of unbounded references. 2187 if (IsReference != CheckReferenceOnly) 2188 return; 2189 2190 unsigned diag = IsReference 2191 ? diag::warn_reference_field_is_uninit 2192 : diag::warn_field_is_uninit; 2193 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2194 if (Constructor) 2195 S.Diag(Constructor->getLocation(), 2196 diag::note_uninit_in_this_constructor) 2197 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2198 2199 } 2200 2201 void HandleValue(Expr *E) { 2202 E = E->IgnoreParens(); 2203 2204 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2205 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2206 return; 2207 } 2208 2209 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2210 HandleValue(CO->getTrueExpr()); 2211 HandleValue(CO->getFalseExpr()); 2212 return; 2213 } 2214 2215 if (BinaryConditionalOperator *BCO = 2216 dyn_cast<BinaryConditionalOperator>(E)) { 2217 HandleValue(BCO->getCommon()); 2218 HandleValue(BCO->getFalseExpr()); 2219 return; 2220 } 2221 2222 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2223 switch (BO->getOpcode()) { 2224 default: 2225 return; 2226 case(BO_PtrMemD): 2227 case(BO_PtrMemI): 2228 HandleValue(BO->getLHS()); 2229 return; 2230 case(BO_Comma): 2231 HandleValue(BO->getRHS()); 2232 return; 2233 } 2234 } 2235 } 2236 2237 void VisitMemberExpr(MemberExpr *ME) { 2238 // All uses of unbounded reference fields will warn. 2239 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2240 2241 Inherited::VisitMemberExpr(ME); 2242 } 2243 2244 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2245 if (E->getCastKind() == CK_LValueToRValue) 2246 HandleValue(E->getSubExpr()); 2247 2248 Inherited::VisitImplicitCastExpr(E); 2249 } 2250 2251 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2252 if (E->getConstructor()->isCopyConstructor()) 2253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0))) 2254 if (ICE->getCastKind() == CK_NoOp) 2255 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr())) 2256 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2257 2258 Inherited::VisitCXXConstructExpr(E); 2259 } 2260 2261 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2262 Expr *Callee = E->getCallee(); 2263 if (isa<MemberExpr>(Callee)) 2264 HandleValue(Callee); 2265 2266 Inherited::VisitCXXMemberCallExpr(E); 2267 } 2268 2269 void VisitBinaryOperator(BinaryOperator *E) { 2270 // If a field assignment is detected, remove the field from the 2271 // uninitiailized field set. 2272 if (E->getOpcode() == BO_Assign) 2273 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2274 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2275 if (!FD->getType()->isReferenceType()) 2276 Decls.erase(FD); 2277 2278 Inherited::VisitBinaryOperator(E); 2279 } 2280 }; 2281 static void CheckInitExprContainsUninitializedFields( 2282 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2283 const CXXConstructorDecl *Constructor) { 2284 if (Decls.size() == 0) 2285 return; 2286 2287 if (!E) 2288 return; 2289 2290 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) { 2291 E = Default->getExpr(); 2292 if (!E) 2293 return; 2294 // In class initializers will point to the constructor. 2295 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E); 2296 } else { 2297 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E); 2298 } 2299 } 2300 2301 // Diagnose value-uses of fields to initialize themselves, e.g. 2302 // foo(foo) 2303 // where foo is not also a parameter to the constructor. 2304 // Also diagnose across field uninitialized use such as 2305 // x(y), y(x) 2306 // TODO: implement -Wuninitialized and fold this into that framework. 2307 static void DiagnoseUninitializedFields( 2308 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2309 2310 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2311 Constructor->getLocation())) { 2312 return; 2313 } 2314 2315 if (Constructor->isInvalidDecl()) 2316 return; 2317 2318 const CXXRecordDecl *RD = Constructor->getParent(); 2319 2320 // Holds fields that are uninitialized. 2321 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2322 2323 // At the beginning, all fields are uninitialized. 2324 for (auto *I : RD->decls()) { 2325 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2326 UninitializedFields.insert(FD); 2327 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2328 UninitializedFields.insert(IFD->getAnonField()); 2329 } 2330 } 2331 2332 for (const auto *FieldInit : Constructor->inits()) { 2333 Expr *InitExpr = FieldInit->getInit(); 2334 2335 CheckInitExprContainsUninitializedFields( 2336 SemaRef, InitExpr, UninitializedFields, Constructor); 2337 2338 if (FieldDecl *Field = FieldInit->getAnyMember()) 2339 UninitializedFields.erase(Field); 2340 } 2341 } 2342 } // namespace 2343 2344 /// \brief Enter a new C++ default initializer scope. After calling this, the 2345 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2346 /// parsing or instantiating the initializer failed. 2347 void Sema::ActOnStartCXXInClassMemberInitializer() { 2348 // Create a synthetic function scope to represent the call to the constructor 2349 // that notionally surrounds a use of this initializer. 2350 PushFunctionScope(); 2351 } 2352 2353 /// \brief This is invoked after parsing an in-class initializer for a 2354 /// non-static C++ class member, and after instantiating an in-class initializer 2355 /// in a class template. Such actions are deferred until the class is complete. 2356 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2357 SourceLocation InitLoc, 2358 Expr *InitExpr) { 2359 // Pop the notional constructor scope we created earlier. 2360 PopFunctionScopeInfo(nullptr, D); 2361 2362 FieldDecl *FD = cast<FieldDecl>(D); 2363 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2364 "must set init style when field is created"); 2365 2366 if (!InitExpr) { 2367 FD->setInvalidDecl(); 2368 FD->removeInClassInitializer(); 2369 return; 2370 } 2371 2372 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2373 FD->setInvalidDecl(); 2374 FD->removeInClassInitializer(); 2375 return; 2376 } 2377 2378 ExprResult Init = InitExpr; 2379 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2380 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2381 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2382 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2383 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2384 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2385 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2386 if (Init.isInvalid()) { 2387 FD->setInvalidDecl(); 2388 return; 2389 } 2390 } 2391 2392 // C++11 [class.base.init]p7: 2393 // The initialization of each base and member constitutes a 2394 // full-expression. 2395 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2396 if (Init.isInvalid()) { 2397 FD->setInvalidDecl(); 2398 return; 2399 } 2400 2401 InitExpr = Init.get(); 2402 2403 FD->setInClassInitializer(InitExpr); 2404 } 2405 2406 /// \brief Find the direct and/or virtual base specifiers that 2407 /// correspond to the given base type, for use in base initialization 2408 /// within a constructor. 2409 static bool FindBaseInitializer(Sema &SemaRef, 2410 CXXRecordDecl *ClassDecl, 2411 QualType BaseType, 2412 const CXXBaseSpecifier *&DirectBaseSpec, 2413 const CXXBaseSpecifier *&VirtualBaseSpec) { 2414 // First, check for a direct base class. 2415 DirectBaseSpec = nullptr; 2416 for (const auto &Base : ClassDecl->bases()) { 2417 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2418 // We found a direct base of this type. That's what we're 2419 // initializing. 2420 DirectBaseSpec = &Base; 2421 break; 2422 } 2423 } 2424 2425 // Check for a virtual base class. 2426 // FIXME: We might be able to short-circuit this if we know in advance that 2427 // there are no virtual bases. 2428 VirtualBaseSpec = nullptr; 2429 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2430 // We haven't found a base yet; search the class hierarchy for a 2431 // virtual base class. 2432 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2433 /*DetectVirtual=*/false); 2434 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2435 BaseType, Paths)) { 2436 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2437 Path != Paths.end(); ++Path) { 2438 if (Path->back().Base->isVirtual()) { 2439 VirtualBaseSpec = Path->back().Base; 2440 break; 2441 } 2442 } 2443 } 2444 } 2445 2446 return DirectBaseSpec || VirtualBaseSpec; 2447 } 2448 2449 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2450 MemInitResult 2451 Sema::ActOnMemInitializer(Decl *ConstructorD, 2452 Scope *S, 2453 CXXScopeSpec &SS, 2454 IdentifierInfo *MemberOrBase, 2455 ParsedType TemplateTypeTy, 2456 const DeclSpec &DS, 2457 SourceLocation IdLoc, 2458 Expr *InitList, 2459 SourceLocation EllipsisLoc) { 2460 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2461 DS, IdLoc, InitList, 2462 EllipsisLoc); 2463 } 2464 2465 /// \brief Handle a C++ member initializer using parentheses syntax. 2466 MemInitResult 2467 Sema::ActOnMemInitializer(Decl *ConstructorD, 2468 Scope *S, 2469 CXXScopeSpec &SS, 2470 IdentifierInfo *MemberOrBase, 2471 ParsedType TemplateTypeTy, 2472 const DeclSpec &DS, 2473 SourceLocation IdLoc, 2474 SourceLocation LParenLoc, 2475 ArrayRef<Expr *> Args, 2476 SourceLocation RParenLoc, 2477 SourceLocation EllipsisLoc) { 2478 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2479 Args, RParenLoc); 2480 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2481 DS, IdLoc, List, EllipsisLoc); 2482 } 2483 2484 namespace { 2485 2486 // Callback to only accept typo corrections that can be a valid C++ member 2487 // intializer: either a non-static field member or a base class. 2488 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2489 public: 2490 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2491 : ClassDecl(ClassDecl) {} 2492 2493 bool ValidateCandidate(const TypoCorrection &candidate) override { 2494 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2495 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2496 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2497 return isa<TypeDecl>(ND); 2498 } 2499 return false; 2500 } 2501 2502 private: 2503 CXXRecordDecl *ClassDecl; 2504 }; 2505 2506 } 2507 2508 /// \brief Handle a C++ member initializer. 2509 MemInitResult 2510 Sema::BuildMemInitializer(Decl *ConstructorD, 2511 Scope *S, 2512 CXXScopeSpec &SS, 2513 IdentifierInfo *MemberOrBase, 2514 ParsedType TemplateTypeTy, 2515 const DeclSpec &DS, 2516 SourceLocation IdLoc, 2517 Expr *Init, 2518 SourceLocation EllipsisLoc) { 2519 if (!ConstructorD) 2520 return true; 2521 2522 AdjustDeclIfTemplate(ConstructorD); 2523 2524 CXXConstructorDecl *Constructor 2525 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2526 if (!Constructor) { 2527 // The user wrote a constructor initializer on a function that is 2528 // not a C++ constructor. Ignore the error for now, because we may 2529 // have more member initializers coming; we'll diagnose it just 2530 // once in ActOnMemInitializers. 2531 return true; 2532 } 2533 2534 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2535 2536 // C++ [class.base.init]p2: 2537 // Names in a mem-initializer-id are looked up in the scope of the 2538 // constructor's class and, if not found in that scope, are looked 2539 // up in the scope containing the constructor's definition. 2540 // [Note: if the constructor's class contains a member with the 2541 // same name as a direct or virtual base class of the class, a 2542 // mem-initializer-id naming the member or base class and composed 2543 // of a single identifier refers to the class member. A 2544 // mem-initializer-id for the hidden base class may be specified 2545 // using a qualified name. ] 2546 if (!SS.getScopeRep() && !TemplateTypeTy) { 2547 // Look for a member, first. 2548 DeclContext::lookup_result Result 2549 = ClassDecl->lookup(MemberOrBase); 2550 if (!Result.empty()) { 2551 ValueDecl *Member; 2552 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2553 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2554 if (EllipsisLoc.isValid()) 2555 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2556 << MemberOrBase 2557 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2558 2559 return BuildMemberInitializer(Member, Init, IdLoc); 2560 } 2561 } 2562 } 2563 // It didn't name a member, so see if it names a class. 2564 QualType BaseType; 2565 TypeSourceInfo *TInfo = nullptr; 2566 2567 if (TemplateTypeTy) { 2568 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2569 } else if (DS.getTypeSpecType() == TST_decltype) { 2570 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2571 } else { 2572 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2573 LookupParsedName(R, S, &SS); 2574 2575 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2576 if (!TyD) { 2577 if (R.isAmbiguous()) return true; 2578 2579 // We don't want access-control diagnostics here. 2580 R.suppressDiagnostics(); 2581 2582 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2583 bool NotUnknownSpecialization = false; 2584 DeclContext *DC = computeDeclContext(SS, false); 2585 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2586 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2587 2588 if (!NotUnknownSpecialization) { 2589 // When the scope specifier can refer to a member of an unknown 2590 // specialization, we take it as a type name. 2591 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2592 SS.getWithLocInContext(Context), 2593 *MemberOrBase, IdLoc); 2594 if (BaseType.isNull()) 2595 return true; 2596 2597 R.clear(); 2598 R.setLookupName(MemberOrBase); 2599 } 2600 } 2601 2602 // If no results were found, try to correct typos. 2603 TypoCorrection Corr; 2604 MemInitializerValidatorCCC Validator(ClassDecl); 2605 if (R.empty() && BaseType.isNull() && 2606 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2607 Validator, CTK_ErrorRecovery, ClassDecl))) { 2608 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2609 // We have found a non-static data member with a similar 2610 // name to what was typed; complain and initialize that 2611 // member. 2612 diagnoseTypo(Corr, 2613 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2614 << MemberOrBase << true); 2615 return BuildMemberInitializer(Member, Init, IdLoc); 2616 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2617 const CXXBaseSpecifier *DirectBaseSpec; 2618 const CXXBaseSpecifier *VirtualBaseSpec; 2619 if (FindBaseInitializer(*this, ClassDecl, 2620 Context.getTypeDeclType(Type), 2621 DirectBaseSpec, VirtualBaseSpec)) { 2622 // We have found a direct or virtual base class with a 2623 // similar name to what was typed; complain and initialize 2624 // that base class. 2625 diagnoseTypo(Corr, 2626 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2627 << MemberOrBase << false, 2628 PDiag() /*Suppress note, we provide our own.*/); 2629 2630 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2631 : VirtualBaseSpec; 2632 Diag(BaseSpec->getLocStart(), 2633 diag::note_base_class_specified_here) 2634 << BaseSpec->getType() 2635 << BaseSpec->getSourceRange(); 2636 2637 TyD = Type; 2638 } 2639 } 2640 } 2641 2642 if (!TyD && BaseType.isNull()) { 2643 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2644 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2645 return true; 2646 } 2647 } 2648 2649 if (BaseType.isNull()) { 2650 BaseType = Context.getTypeDeclType(TyD); 2651 if (SS.isSet()) 2652 // FIXME: preserve source range information 2653 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2654 BaseType); 2655 } 2656 } 2657 2658 if (!TInfo) 2659 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2660 2661 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2662 } 2663 2664 /// Checks a member initializer expression for cases where reference (or 2665 /// pointer) members are bound to by-value parameters (or their addresses). 2666 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2667 Expr *Init, 2668 SourceLocation IdLoc) { 2669 QualType MemberTy = Member->getType(); 2670 2671 // We only handle pointers and references currently. 2672 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2673 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2674 return; 2675 2676 const bool IsPointer = MemberTy->isPointerType(); 2677 if (IsPointer) { 2678 if (const UnaryOperator *Op 2679 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2680 // The only case we're worried about with pointers requires taking the 2681 // address. 2682 if (Op->getOpcode() != UO_AddrOf) 2683 return; 2684 2685 Init = Op->getSubExpr(); 2686 } else { 2687 // We only handle address-of expression initializers for pointers. 2688 return; 2689 } 2690 } 2691 2692 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2693 // We only warn when referring to a non-reference parameter declaration. 2694 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2695 if (!Parameter || Parameter->getType()->isReferenceType()) 2696 return; 2697 2698 S.Diag(Init->getExprLoc(), 2699 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2700 : diag::warn_bind_ref_member_to_parameter) 2701 << Member << Parameter << Init->getSourceRange(); 2702 } else { 2703 // Other initializers are fine. 2704 return; 2705 } 2706 2707 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2708 << (unsigned)IsPointer; 2709 } 2710 2711 MemInitResult 2712 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2713 SourceLocation IdLoc) { 2714 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2715 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2716 assert((DirectMember || IndirectMember) && 2717 "Member must be a FieldDecl or IndirectFieldDecl"); 2718 2719 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2720 return true; 2721 2722 if (Member->isInvalidDecl()) 2723 return true; 2724 2725 MultiExprArg Args; 2726 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2727 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2728 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2729 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2730 } else { 2731 // Template instantiation doesn't reconstruct ParenListExprs for us. 2732 Args = Init; 2733 } 2734 2735 SourceRange InitRange = Init->getSourceRange(); 2736 2737 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2738 // Can't check initialization for a member of dependent type or when 2739 // any of the arguments are type-dependent expressions. 2740 DiscardCleanupsInEvaluationContext(); 2741 } else { 2742 bool InitList = false; 2743 if (isa<InitListExpr>(Init)) { 2744 InitList = true; 2745 Args = Init; 2746 } 2747 2748 // Initialize the member. 2749 InitializedEntity MemberEntity = 2750 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 2751 : InitializedEntity::InitializeMember(IndirectMember, 2752 nullptr); 2753 InitializationKind Kind = 2754 InitList ? InitializationKind::CreateDirectList(IdLoc) 2755 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2756 InitRange.getEnd()); 2757 2758 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2759 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 2760 nullptr); 2761 if (MemberInit.isInvalid()) 2762 return true; 2763 2764 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2765 2766 // C++11 [class.base.init]p7: 2767 // The initialization of each base and member constitutes a 2768 // full-expression. 2769 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2770 if (MemberInit.isInvalid()) 2771 return true; 2772 2773 Init = MemberInit.get(); 2774 } 2775 2776 if (DirectMember) { 2777 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2778 InitRange.getBegin(), Init, 2779 InitRange.getEnd()); 2780 } else { 2781 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2782 InitRange.getBegin(), Init, 2783 InitRange.getEnd()); 2784 } 2785 } 2786 2787 MemInitResult 2788 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2789 CXXRecordDecl *ClassDecl) { 2790 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2791 if (!LangOpts.CPlusPlus11) 2792 return Diag(NameLoc, diag::err_delegating_ctor) 2793 << TInfo->getTypeLoc().getLocalSourceRange(); 2794 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2795 2796 bool InitList = true; 2797 MultiExprArg Args = Init; 2798 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2799 InitList = false; 2800 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2801 } 2802 2803 SourceRange InitRange = Init->getSourceRange(); 2804 // Initialize the object. 2805 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2806 QualType(ClassDecl->getTypeForDecl(), 0)); 2807 InitializationKind Kind = 2808 InitList ? InitializationKind::CreateDirectList(NameLoc) 2809 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2810 InitRange.getEnd()); 2811 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2812 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2813 Args, nullptr); 2814 if (DelegationInit.isInvalid()) 2815 return true; 2816 2817 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2818 "Delegating constructor with no target?"); 2819 2820 // C++11 [class.base.init]p7: 2821 // The initialization of each base and member constitutes a 2822 // full-expression. 2823 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2824 InitRange.getBegin()); 2825 if (DelegationInit.isInvalid()) 2826 return true; 2827 2828 // If we are in a dependent context, template instantiation will 2829 // perform this type-checking again. Just save the arguments that we 2830 // received in a ParenListExpr. 2831 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2832 // of the information that we have about the base 2833 // initializer. However, deconstructing the ASTs is a dicey process, 2834 // and this approach is far more likely to get the corner cases right. 2835 if (CurContext->isDependentContext()) 2836 DelegationInit = Init; 2837 2838 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2839 DelegationInit.getAs<Expr>(), 2840 InitRange.getEnd()); 2841 } 2842 2843 MemInitResult 2844 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2845 Expr *Init, CXXRecordDecl *ClassDecl, 2846 SourceLocation EllipsisLoc) { 2847 SourceLocation BaseLoc 2848 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2849 2850 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2851 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2852 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2853 2854 // C++ [class.base.init]p2: 2855 // [...] Unless the mem-initializer-id names a nonstatic data 2856 // member of the constructor's class or a direct or virtual base 2857 // of that class, the mem-initializer is ill-formed. A 2858 // mem-initializer-list can initialize a base class using any 2859 // name that denotes that base class type. 2860 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2861 2862 SourceRange InitRange = Init->getSourceRange(); 2863 if (EllipsisLoc.isValid()) { 2864 // This is a pack expansion. 2865 if (!BaseType->containsUnexpandedParameterPack()) { 2866 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2867 << SourceRange(BaseLoc, InitRange.getEnd()); 2868 2869 EllipsisLoc = SourceLocation(); 2870 } 2871 } else { 2872 // Check for any unexpanded parameter packs. 2873 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2874 return true; 2875 2876 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2877 return true; 2878 } 2879 2880 // Check for direct and virtual base classes. 2881 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 2882 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 2883 if (!Dependent) { 2884 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2885 BaseType)) 2886 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2887 2888 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2889 VirtualBaseSpec); 2890 2891 // C++ [base.class.init]p2: 2892 // Unless the mem-initializer-id names a nonstatic data member of the 2893 // constructor's class or a direct or virtual base of that class, the 2894 // mem-initializer is ill-formed. 2895 if (!DirectBaseSpec && !VirtualBaseSpec) { 2896 // If the class has any dependent bases, then it's possible that 2897 // one of those types will resolve to the same type as 2898 // BaseType. Therefore, just treat this as a dependent base 2899 // class initialization. FIXME: Should we try to check the 2900 // initialization anyway? It seems odd. 2901 if (ClassDecl->hasAnyDependentBases()) 2902 Dependent = true; 2903 else 2904 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2905 << BaseType << Context.getTypeDeclType(ClassDecl) 2906 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2907 } 2908 } 2909 2910 if (Dependent) { 2911 DiscardCleanupsInEvaluationContext(); 2912 2913 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2914 /*IsVirtual=*/false, 2915 InitRange.getBegin(), Init, 2916 InitRange.getEnd(), EllipsisLoc); 2917 } 2918 2919 // C++ [base.class.init]p2: 2920 // If a mem-initializer-id is ambiguous because it designates both 2921 // a direct non-virtual base class and an inherited virtual base 2922 // class, the mem-initializer is ill-formed. 2923 if (DirectBaseSpec && VirtualBaseSpec) 2924 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2925 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2926 2927 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2928 if (!BaseSpec) 2929 BaseSpec = VirtualBaseSpec; 2930 2931 // Initialize the base. 2932 bool InitList = true; 2933 MultiExprArg Args = Init; 2934 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2935 InitList = false; 2936 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2937 } 2938 2939 InitializedEntity BaseEntity = 2940 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2941 InitializationKind Kind = 2942 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2943 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2944 InitRange.getEnd()); 2945 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2946 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 2947 if (BaseInit.isInvalid()) 2948 return true; 2949 2950 // C++11 [class.base.init]p7: 2951 // The initialization of each base and member constitutes a 2952 // full-expression. 2953 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2954 if (BaseInit.isInvalid()) 2955 return true; 2956 2957 // If we are in a dependent context, template instantiation will 2958 // perform this type-checking again. Just save the arguments that we 2959 // received in a ParenListExpr. 2960 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2961 // of the information that we have about the base 2962 // initializer. However, deconstructing the ASTs is a dicey process, 2963 // and this approach is far more likely to get the corner cases right. 2964 if (CurContext->isDependentContext()) 2965 BaseInit = Init; 2966 2967 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2968 BaseSpec->isVirtual(), 2969 InitRange.getBegin(), 2970 BaseInit.getAs<Expr>(), 2971 InitRange.getEnd(), EllipsisLoc); 2972 } 2973 2974 // Create a static_cast\<T&&>(expr). 2975 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2976 if (T.isNull()) T = E->getType(); 2977 QualType TargetType = SemaRef.BuildReferenceType( 2978 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2979 SourceLocation ExprLoc = E->getLocStart(); 2980 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2981 TargetType, ExprLoc); 2982 2983 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2984 SourceRange(ExprLoc, ExprLoc), 2985 E->getSourceRange()).get(); 2986 } 2987 2988 /// ImplicitInitializerKind - How an implicit base or member initializer should 2989 /// initialize its base or member. 2990 enum ImplicitInitializerKind { 2991 IIK_Default, 2992 IIK_Copy, 2993 IIK_Move, 2994 IIK_Inherit 2995 }; 2996 2997 static bool 2998 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2999 ImplicitInitializerKind ImplicitInitKind, 3000 CXXBaseSpecifier *BaseSpec, 3001 bool IsInheritedVirtualBase, 3002 CXXCtorInitializer *&CXXBaseInit) { 3003 InitializedEntity InitEntity 3004 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3005 IsInheritedVirtualBase); 3006 3007 ExprResult BaseInit; 3008 3009 switch (ImplicitInitKind) { 3010 case IIK_Inherit: { 3011 const CXXRecordDecl *Inherited = 3012 Constructor->getInheritedConstructor()->getParent(); 3013 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3014 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3015 // C++11 [class.inhctor]p8: 3016 // Each expression in the expression-list is of the form 3017 // static_cast<T&&>(p), where p is the name of the corresponding 3018 // constructor parameter and T is the declared type of p. 3019 SmallVector<Expr*, 16> Args; 3020 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3021 ParmVarDecl *PD = Constructor->getParamDecl(I); 3022 ExprResult ArgExpr = 3023 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3024 VK_LValue, SourceLocation()); 3025 if (ArgExpr.isInvalid()) 3026 return true; 3027 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3028 } 3029 3030 InitializationKind InitKind = InitializationKind::CreateDirect( 3031 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3032 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3033 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3034 break; 3035 } 3036 } 3037 // Fall through. 3038 case IIK_Default: { 3039 InitializationKind InitKind 3040 = InitializationKind::CreateDefault(Constructor->getLocation()); 3041 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3042 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3043 break; 3044 } 3045 3046 case IIK_Move: 3047 case IIK_Copy: { 3048 bool Moving = ImplicitInitKind == IIK_Move; 3049 ParmVarDecl *Param = Constructor->getParamDecl(0); 3050 QualType ParamType = Param->getType().getNonReferenceType(); 3051 3052 Expr *CopyCtorArg = 3053 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3054 SourceLocation(), Param, false, 3055 Constructor->getLocation(), ParamType, 3056 VK_LValue, nullptr); 3057 3058 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3059 3060 // Cast to the base class to avoid ambiguities. 3061 QualType ArgTy = 3062 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3063 ParamType.getQualifiers()); 3064 3065 if (Moving) { 3066 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3067 } 3068 3069 CXXCastPath BasePath; 3070 BasePath.push_back(BaseSpec); 3071 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3072 CK_UncheckedDerivedToBase, 3073 Moving ? VK_XValue : VK_LValue, 3074 &BasePath).get(); 3075 3076 InitializationKind InitKind 3077 = InitializationKind::CreateDirect(Constructor->getLocation(), 3078 SourceLocation(), SourceLocation()); 3079 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3080 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3081 break; 3082 } 3083 } 3084 3085 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3086 if (BaseInit.isInvalid()) 3087 return true; 3088 3089 CXXBaseInit = 3090 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3091 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3092 SourceLocation()), 3093 BaseSpec->isVirtual(), 3094 SourceLocation(), 3095 BaseInit.getAs<Expr>(), 3096 SourceLocation(), 3097 SourceLocation()); 3098 3099 return false; 3100 } 3101 3102 static bool RefersToRValueRef(Expr *MemRef) { 3103 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3104 return Referenced->getType()->isRValueReferenceType(); 3105 } 3106 3107 static bool 3108 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3109 ImplicitInitializerKind ImplicitInitKind, 3110 FieldDecl *Field, IndirectFieldDecl *Indirect, 3111 CXXCtorInitializer *&CXXMemberInit) { 3112 if (Field->isInvalidDecl()) 3113 return true; 3114 3115 SourceLocation Loc = Constructor->getLocation(); 3116 3117 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3118 bool Moving = ImplicitInitKind == IIK_Move; 3119 ParmVarDecl *Param = Constructor->getParamDecl(0); 3120 QualType ParamType = Param->getType().getNonReferenceType(); 3121 3122 // Suppress copying zero-width bitfields. 3123 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3124 return false; 3125 3126 Expr *MemberExprBase = 3127 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3128 SourceLocation(), Param, false, 3129 Loc, ParamType, VK_LValue, nullptr); 3130 3131 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3132 3133 if (Moving) { 3134 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3135 } 3136 3137 // Build a reference to this field within the parameter. 3138 CXXScopeSpec SS; 3139 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3140 Sema::LookupMemberName); 3141 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3142 : cast<ValueDecl>(Field), AS_public); 3143 MemberLookup.resolveKind(); 3144 ExprResult CtorArg 3145 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3146 ParamType, Loc, 3147 /*IsArrow=*/false, 3148 SS, 3149 /*TemplateKWLoc=*/SourceLocation(), 3150 /*FirstQualifierInScope=*/nullptr, 3151 MemberLookup, 3152 /*TemplateArgs=*/nullptr); 3153 if (CtorArg.isInvalid()) 3154 return true; 3155 3156 // C++11 [class.copy]p15: 3157 // - if a member m has rvalue reference type T&&, it is direct-initialized 3158 // with static_cast<T&&>(x.m); 3159 if (RefersToRValueRef(CtorArg.get())) { 3160 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3161 } 3162 3163 // When the field we are copying is an array, create index variables for 3164 // each dimension of the array. We use these index variables to subscript 3165 // the source array, and other clients (e.g., CodeGen) will perform the 3166 // necessary iteration with these index variables. 3167 SmallVector<VarDecl *, 4> IndexVariables; 3168 QualType BaseType = Field->getType(); 3169 QualType SizeType = SemaRef.Context.getSizeType(); 3170 bool InitializingArray = false; 3171 while (const ConstantArrayType *Array 3172 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3173 InitializingArray = true; 3174 // Create the iteration variable for this array index. 3175 IdentifierInfo *IterationVarName = nullptr; 3176 { 3177 SmallString<8> Str; 3178 llvm::raw_svector_ostream OS(Str); 3179 OS << "__i" << IndexVariables.size(); 3180 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3181 } 3182 VarDecl *IterationVar 3183 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3184 IterationVarName, SizeType, 3185 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3186 SC_None); 3187 IndexVariables.push_back(IterationVar); 3188 3189 // Create a reference to the iteration variable. 3190 ExprResult IterationVarRef 3191 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3192 assert(!IterationVarRef.isInvalid() && 3193 "Reference to invented variable cannot fail!"); 3194 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3195 assert(!IterationVarRef.isInvalid() && 3196 "Conversion of invented variable cannot fail!"); 3197 3198 // Subscript the array with this iteration variable. 3199 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3200 IterationVarRef.get(), 3201 Loc); 3202 if (CtorArg.isInvalid()) 3203 return true; 3204 3205 BaseType = Array->getElementType(); 3206 } 3207 3208 // The array subscript expression is an lvalue, which is wrong for moving. 3209 if (Moving && InitializingArray) 3210 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3211 3212 // Construct the entity that we will be initializing. For an array, this 3213 // will be first element in the array, which may require several levels 3214 // of array-subscript entities. 3215 SmallVector<InitializedEntity, 4> Entities; 3216 Entities.reserve(1 + IndexVariables.size()); 3217 if (Indirect) 3218 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3219 else 3220 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3221 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3222 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3223 0, 3224 Entities.back())); 3225 3226 // Direct-initialize to use the copy constructor. 3227 InitializationKind InitKind = 3228 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3229 3230 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3231 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3232 3233 ExprResult MemberInit 3234 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3235 MultiExprArg(&CtorArgE, 1)); 3236 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3237 if (MemberInit.isInvalid()) 3238 return true; 3239 3240 if (Indirect) { 3241 assert(IndexVariables.size() == 0 && 3242 "Indirect field improperly initialized"); 3243 CXXMemberInit 3244 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3245 Loc, Loc, 3246 MemberInit.getAs<Expr>(), 3247 Loc); 3248 } else 3249 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3250 Loc, MemberInit.getAs<Expr>(), 3251 Loc, 3252 IndexVariables.data(), 3253 IndexVariables.size()); 3254 return false; 3255 } 3256 3257 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3258 "Unhandled implicit init kind!"); 3259 3260 QualType FieldBaseElementType = 3261 SemaRef.Context.getBaseElementType(Field->getType()); 3262 3263 if (FieldBaseElementType->isRecordType()) { 3264 InitializedEntity InitEntity 3265 = Indirect? InitializedEntity::InitializeMember(Indirect) 3266 : InitializedEntity::InitializeMember(Field); 3267 InitializationKind InitKind = 3268 InitializationKind::CreateDefault(Loc); 3269 3270 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3271 ExprResult MemberInit = 3272 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3273 3274 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3275 if (MemberInit.isInvalid()) 3276 return true; 3277 3278 if (Indirect) 3279 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3280 Indirect, Loc, 3281 Loc, 3282 MemberInit.get(), 3283 Loc); 3284 else 3285 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3286 Field, Loc, Loc, 3287 MemberInit.get(), 3288 Loc); 3289 return false; 3290 } 3291 3292 if (!Field->getParent()->isUnion()) { 3293 if (FieldBaseElementType->isReferenceType()) { 3294 SemaRef.Diag(Constructor->getLocation(), 3295 diag::err_uninitialized_member_in_ctor) 3296 << (int)Constructor->isImplicit() 3297 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3298 << 0 << Field->getDeclName(); 3299 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3300 return true; 3301 } 3302 3303 if (FieldBaseElementType.isConstQualified()) { 3304 SemaRef.Diag(Constructor->getLocation(), 3305 diag::err_uninitialized_member_in_ctor) 3306 << (int)Constructor->isImplicit() 3307 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3308 << 1 << Field->getDeclName(); 3309 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3310 return true; 3311 } 3312 } 3313 3314 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3315 FieldBaseElementType->isObjCRetainableType() && 3316 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3317 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3318 // ARC: 3319 // Default-initialize Objective-C pointers to NULL. 3320 CXXMemberInit 3321 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3322 Loc, Loc, 3323 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3324 Loc); 3325 return false; 3326 } 3327 3328 // Nothing to initialize. 3329 CXXMemberInit = nullptr; 3330 return false; 3331 } 3332 3333 namespace { 3334 struct BaseAndFieldInfo { 3335 Sema &S; 3336 CXXConstructorDecl *Ctor; 3337 bool AnyErrorsInInits; 3338 ImplicitInitializerKind IIK; 3339 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3340 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3341 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3342 3343 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3344 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3345 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3346 if (Generated && Ctor->isCopyConstructor()) 3347 IIK = IIK_Copy; 3348 else if (Generated && Ctor->isMoveConstructor()) 3349 IIK = IIK_Move; 3350 else if (Ctor->getInheritedConstructor()) 3351 IIK = IIK_Inherit; 3352 else 3353 IIK = IIK_Default; 3354 } 3355 3356 bool isImplicitCopyOrMove() const { 3357 switch (IIK) { 3358 case IIK_Copy: 3359 case IIK_Move: 3360 return true; 3361 3362 case IIK_Default: 3363 case IIK_Inherit: 3364 return false; 3365 } 3366 3367 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3368 } 3369 3370 bool addFieldInitializer(CXXCtorInitializer *Init) { 3371 AllToInit.push_back(Init); 3372 3373 // Check whether this initializer makes the field "used". 3374 if (Init->getInit()->HasSideEffects(S.Context)) 3375 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3376 3377 return false; 3378 } 3379 3380 bool isInactiveUnionMember(FieldDecl *Field) { 3381 RecordDecl *Record = Field->getParent(); 3382 if (!Record->isUnion()) 3383 return false; 3384 3385 if (FieldDecl *Active = 3386 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3387 return Active != Field->getCanonicalDecl(); 3388 3389 // In an implicit copy or move constructor, ignore any in-class initializer. 3390 if (isImplicitCopyOrMove()) 3391 return true; 3392 3393 // If there's no explicit initialization, the field is active only if it 3394 // has an in-class initializer... 3395 if (Field->hasInClassInitializer()) 3396 return false; 3397 // ... or it's an anonymous struct or union whose class has an in-class 3398 // initializer. 3399 if (!Field->isAnonymousStructOrUnion()) 3400 return true; 3401 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3402 return !FieldRD->hasInClassInitializer(); 3403 } 3404 3405 /// \brief Determine whether the given field is, or is within, a union member 3406 /// that is inactive (because there was an initializer given for a different 3407 /// member of the union, or because the union was not initialized at all). 3408 bool isWithinInactiveUnionMember(FieldDecl *Field, 3409 IndirectFieldDecl *Indirect) { 3410 if (!Indirect) 3411 return isInactiveUnionMember(Field); 3412 3413 for (auto *C : Indirect->chain()) { 3414 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3415 if (Field && isInactiveUnionMember(Field)) 3416 return true; 3417 } 3418 return false; 3419 } 3420 }; 3421 } 3422 3423 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3424 /// array type. 3425 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3426 if (T->isIncompleteArrayType()) 3427 return true; 3428 3429 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3430 if (!ArrayT->getSize()) 3431 return true; 3432 3433 T = ArrayT->getElementType(); 3434 } 3435 3436 return false; 3437 } 3438 3439 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3440 FieldDecl *Field, 3441 IndirectFieldDecl *Indirect = nullptr) { 3442 if (Field->isInvalidDecl()) 3443 return false; 3444 3445 // Overwhelmingly common case: we have a direct initializer for this field. 3446 if (CXXCtorInitializer *Init = 3447 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3448 return Info.addFieldInitializer(Init); 3449 3450 // C++11 [class.base.init]p8: 3451 // if the entity is a non-static data member that has a 3452 // brace-or-equal-initializer and either 3453 // -- the constructor's class is a union and no other variant member of that 3454 // union is designated by a mem-initializer-id or 3455 // -- the constructor's class is not a union, and, if the entity is a member 3456 // of an anonymous union, no other member of that union is designated by 3457 // a mem-initializer-id, 3458 // the entity is initialized as specified in [dcl.init]. 3459 // 3460 // We also apply the same rules to handle anonymous structs within anonymous 3461 // unions. 3462 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3463 return false; 3464 3465 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3466 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3467 Info.Ctor->getLocation(), Field); 3468 CXXCtorInitializer *Init; 3469 if (Indirect) 3470 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3471 SourceLocation(), 3472 SourceLocation(), DIE, 3473 SourceLocation()); 3474 else 3475 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3476 SourceLocation(), 3477 SourceLocation(), DIE, 3478 SourceLocation()); 3479 return Info.addFieldInitializer(Init); 3480 } 3481 3482 // Don't initialize incomplete or zero-length arrays. 3483 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3484 return false; 3485 3486 // Don't try to build an implicit initializer if there were semantic 3487 // errors in any of the initializers (and therefore we might be 3488 // missing some that the user actually wrote). 3489 if (Info.AnyErrorsInInits) 3490 return false; 3491 3492 CXXCtorInitializer *Init = nullptr; 3493 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3494 Indirect, Init)) 3495 return true; 3496 3497 if (!Init) 3498 return false; 3499 3500 return Info.addFieldInitializer(Init); 3501 } 3502 3503 bool 3504 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3505 CXXCtorInitializer *Initializer) { 3506 assert(Initializer->isDelegatingInitializer()); 3507 Constructor->setNumCtorInitializers(1); 3508 CXXCtorInitializer **initializer = 3509 new (Context) CXXCtorInitializer*[1]; 3510 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3511 Constructor->setCtorInitializers(initializer); 3512 3513 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3514 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3515 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3516 } 3517 3518 DelegatingCtorDecls.push_back(Constructor); 3519 3520 return false; 3521 } 3522 3523 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3524 ArrayRef<CXXCtorInitializer *> Initializers) { 3525 if (Constructor->isDependentContext()) { 3526 // Just store the initializers as written, they will be checked during 3527 // instantiation. 3528 if (!Initializers.empty()) { 3529 Constructor->setNumCtorInitializers(Initializers.size()); 3530 CXXCtorInitializer **baseOrMemberInitializers = 3531 new (Context) CXXCtorInitializer*[Initializers.size()]; 3532 memcpy(baseOrMemberInitializers, Initializers.data(), 3533 Initializers.size() * sizeof(CXXCtorInitializer*)); 3534 Constructor->setCtorInitializers(baseOrMemberInitializers); 3535 } 3536 3537 // Let template instantiation know whether we had errors. 3538 if (AnyErrors) 3539 Constructor->setInvalidDecl(); 3540 3541 return false; 3542 } 3543 3544 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3545 3546 // We need to build the initializer AST according to order of construction 3547 // and not what user specified in the Initializers list. 3548 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3549 if (!ClassDecl) 3550 return true; 3551 3552 bool HadError = false; 3553 3554 for (unsigned i = 0; i < Initializers.size(); i++) { 3555 CXXCtorInitializer *Member = Initializers[i]; 3556 3557 if (Member->isBaseInitializer()) 3558 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3559 else { 3560 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3561 3562 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3563 for (auto *C : F->chain()) { 3564 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3565 if (FD && FD->getParent()->isUnion()) 3566 Info.ActiveUnionMember.insert(std::make_pair( 3567 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3568 } 3569 } else if (FieldDecl *FD = Member->getMember()) { 3570 if (FD->getParent()->isUnion()) 3571 Info.ActiveUnionMember.insert(std::make_pair( 3572 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3573 } 3574 } 3575 } 3576 3577 // Keep track of the direct virtual bases. 3578 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3579 for (auto &I : ClassDecl->bases()) { 3580 if (I.isVirtual()) 3581 DirectVBases.insert(&I); 3582 } 3583 3584 // Push virtual bases before others. 3585 for (auto &VBase : ClassDecl->vbases()) { 3586 if (CXXCtorInitializer *Value 3587 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3588 // [class.base.init]p7, per DR257: 3589 // A mem-initializer where the mem-initializer-id names a virtual base 3590 // class is ignored during execution of a constructor of any class that 3591 // is not the most derived class. 3592 if (ClassDecl->isAbstract()) { 3593 // FIXME: Provide a fixit to remove the base specifier. This requires 3594 // tracking the location of the associated comma for a base specifier. 3595 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3596 << VBase.getType() << ClassDecl; 3597 DiagnoseAbstractType(ClassDecl); 3598 } 3599 3600 Info.AllToInit.push_back(Value); 3601 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3602 // [class.base.init]p8, per DR257: 3603 // If a given [...] base class is not named by a mem-initializer-id 3604 // [...] and the entity is not a virtual base class of an abstract 3605 // class, then [...] the entity is default-initialized. 3606 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3607 CXXCtorInitializer *CXXBaseInit; 3608 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3609 &VBase, IsInheritedVirtualBase, 3610 CXXBaseInit)) { 3611 HadError = true; 3612 continue; 3613 } 3614 3615 Info.AllToInit.push_back(CXXBaseInit); 3616 } 3617 } 3618 3619 // Non-virtual bases. 3620 for (auto &Base : ClassDecl->bases()) { 3621 // Virtuals are in the virtual base list and already constructed. 3622 if (Base.isVirtual()) 3623 continue; 3624 3625 if (CXXCtorInitializer *Value 3626 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3627 Info.AllToInit.push_back(Value); 3628 } else if (!AnyErrors) { 3629 CXXCtorInitializer *CXXBaseInit; 3630 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3631 &Base, /*IsInheritedVirtualBase=*/false, 3632 CXXBaseInit)) { 3633 HadError = true; 3634 continue; 3635 } 3636 3637 Info.AllToInit.push_back(CXXBaseInit); 3638 } 3639 } 3640 3641 // Fields. 3642 for (auto *Mem : ClassDecl->decls()) { 3643 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3644 // C++ [class.bit]p2: 3645 // A declaration for a bit-field that omits the identifier declares an 3646 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3647 // initialized. 3648 if (F->isUnnamedBitfield()) 3649 continue; 3650 3651 // If we're not generating the implicit copy/move constructor, then we'll 3652 // handle anonymous struct/union fields based on their individual 3653 // indirect fields. 3654 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3655 continue; 3656 3657 if (CollectFieldInitializer(*this, Info, F)) 3658 HadError = true; 3659 continue; 3660 } 3661 3662 // Beyond this point, we only consider default initialization. 3663 if (Info.isImplicitCopyOrMove()) 3664 continue; 3665 3666 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3667 if (F->getType()->isIncompleteArrayType()) { 3668 assert(ClassDecl->hasFlexibleArrayMember() && 3669 "Incomplete array type is not valid"); 3670 continue; 3671 } 3672 3673 // Initialize each field of an anonymous struct individually. 3674 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3675 HadError = true; 3676 3677 continue; 3678 } 3679 } 3680 3681 unsigned NumInitializers = Info.AllToInit.size(); 3682 if (NumInitializers > 0) { 3683 Constructor->setNumCtorInitializers(NumInitializers); 3684 CXXCtorInitializer **baseOrMemberInitializers = 3685 new (Context) CXXCtorInitializer*[NumInitializers]; 3686 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3687 NumInitializers * sizeof(CXXCtorInitializer*)); 3688 Constructor->setCtorInitializers(baseOrMemberInitializers); 3689 3690 // Constructors implicitly reference the base and member 3691 // destructors. 3692 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3693 Constructor->getParent()); 3694 } 3695 3696 return HadError; 3697 } 3698 3699 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3700 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3701 const RecordDecl *RD = RT->getDecl(); 3702 if (RD->isAnonymousStructOrUnion()) { 3703 for (auto *Field : RD->fields()) 3704 PopulateKeysForFields(Field, IdealInits); 3705 return; 3706 } 3707 } 3708 IdealInits.push_back(Field->getCanonicalDecl()); 3709 } 3710 3711 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3712 return Context.getCanonicalType(BaseType).getTypePtr(); 3713 } 3714 3715 static const void *GetKeyForMember(ASTContext &Context, 3716 CXXCtorInitializer *Member) { 3717 if (!Member->isAnyMemberInitializer()) 3718 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3719 3720 return Member->getAnyMember()->getCanonicalDecl(); 3721 } 3722 3723 static void DiagnoseBaseOrMemInitializerOrder( 3724 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3725 ArrayRef<CXXCtorInitializer *> Inits) { 3726 if (Constructor->getDeclContext()->isDependentContext()) 3727 return; 3728 3729 // Don't check initializers order unless the warning is enabled at the 3730 // location of at least one initializer. 3731 bool ShouldCheckOrder = false; 3732 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3733 CXXCtorInitializer *Init = Inits[InitIndex]; 3734 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 3735 Init->getSourceLocation())) { 3736 ShouldCheckOrder = true; 3737 break; 3738 } 3739 } 3740 if (!ShouldCheckOrder) 3741 return; 3742 3743 // Build the list of bases and members in the order that they'll 3744 // actually be initialized. The explicit initializers should be in 3745 // this same order but may be missing things. 3746 SmallVector<const void*, 32> IdealInitKeys; 3747 3748 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3749 3750 // 1. Virtual bases. 3751 for (const auto &VBase : ClassDecl->vbases()) 3752 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 3753 3754 // 2. Non-virtual bases. 3755 for (const auto &Base : ClassDecl->bases()) { 3756 if (Base.isVirtual()) 3757 continue; 3758 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 3759 } 3760 3761 // 3. Direct fields. 3762 for (auto *Field : ClassDecl->fields()) { 3763 if (Field->isUnnamedBitfield()) 3764 continue; 3765 3766 PopulateKeysForFields(Field, IdealInitKeys); 3767 } 3768 3769 unsigned NumIdealInits = IdealInitKeys.size(); 3770 unsigned IdealIndex = 0; 3771 3772 CXXCtorInitializer *PrevInit = nullptr; 3773 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3774 CXXCtorInitializer *Init = Inits[InitIndex]; 3775 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3776 3777 // Scan forward to try to find this initializer in the idealized 3778 // initializers list. 3779 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3780 if (InitKey == IdealInitKeys[IdealIndex]) 3781 break; 3782 3783 // If we didn't find this initializer, it must be because we 3784 // scanned past it on a previous iteration. That can only 3785 // happen if we're out of order; emit a warning. 3786 if (IdealIndex == NumIdealInits && PrevInit) { 3787 Sema::SemaDiagnosticBuilder D = 3788 SemaRef.Diag(PrevInit->getSourceLocation(), 3789 diag::warn_initializer_out_of_order); 3790 3791 if (PrevInit->isAnyMemberInitializer()) 3792 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3793 else 3794 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3795 3796 if (Init->isAnyMemberInitializer()) 3797 D << 0 << Init->getAnyMember()->getDeclName(); 3798 else 3799 D << 1 << Init->getTypeSourceInfo()->getType(); 3800 3801 // Move back to the initializer's location in the ideal list. 3802 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3803 if (InitKey == IdealInitKeys[IdealIndex]) 3804 break; 3805 3806 assert(IdealIndex != NumIdealInits && 3807 "initializer not found in initializer list"); 3808 } 3809 3810 PrevInit = Init; 3811 } 3812 } 3813 3814 namespace { 3815 bool CheckRedundantInit(Sema &S, 3816 CXXCtorInitializer *Init, 3817 CXXCtorInitializer *&PrevInit) { 3818 if (!PrevInit) { 3819 PrevInit = Init; 3820 return false; 3821 } 3822 3823 if (FieldDecl *Field = Init->getAnyMember()) 3824 S.Diag(Init->getSourceLocation(), 3825 diag::err_multiple_mem_initialization) 3826 << Field->getDeclName() 3827 << Init->getSourceRange(); 3828 else { 3829 const Type *BaseClass = Init->getBaseClass(); 3830 assert(BaseClass && "neither field nor base"); 3831 S.Diag(Init->getSourceLocation(), 3832 diag::err_multiple_base_initialization) 3833 << QualType(BaseClass, 0) 3834 << Init->getSourceRange(); 3835 } 3836 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3837 << 0 << PrevInit->getSourceRange(); 3838 3839 return true; 3840 } 3841 3842 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3843 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3844 3845 bool CheckRedundantUnionInit(Sema &S, 3846 CXXCtorInitializer *Init, 3847 RedundantUnionMap &Unions) { 3848 FieldDecl *Field = Init->getAnyMember(); 3849 RecordDecl *Parent = Field->getParent(); 3850 NamedDecl *Child = Field; 3851 3852 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3853 if (Parent->isUnion()) { 3854 UnionEntry &En = Unions[Parent]; 3855 if (En.first && En.first != Child) { 3856 S.Diag(Init->getSourceLocation(), 3857 diag::err_multiple_mem_union_initialization) 3858 << Field->getDeclName() 3859 << Init->getSourceRange(); 3860 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3861 << 0 << En.second->getSourceRange(); 3862 return true; 3863 } 3864 if (!En.first) { 3865 En.first = Child; 3866 En.second = Init; 3867 } 3868 if (!Parent->isAnonymousStructOrUnion()) 3869 return false; 3870 } 3871 3872 Child = Parent; 3873 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3874 } 3875 3876 return false; 3877 } 3878 } 3879 3880 /// ActOnMemInitializers - Handle the member initializers for a constructor. 3881 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3882 SourceLocation ColonLoc, 3883 ArrayRef<CXXCtorInitializer*> MemInits, 3884 bool AnyErrors) { 3885 if (!ConstructorDecl) 3886 return; 3887 3888 AdjustDeclIfTemplate(ConstructorDecl); 3889 3890 CXXConstructorDecl *Constructor 3891 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3892 3893 if (!Constructor) { 3894 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3895 return; 3896 } 3897 3898 // Mapping for the duplicate initializers check. 3899 // For member initializers, this is keyed with a FieldDecl*. 3900 // For base initializers, this is keyed with a Type*. 3901 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3902 3903 // Mapping for the inconsistent anonymous-union initializers check. 3904 RedundantUnionMap MemberUnions; 3905 3906 bool HadError = false; 3907 for (unsigned i = 0; i < MemInits.size(); i++) { 3908 CXXCtorInitializer *Init = MemInits[i]; 3909 3910 // Set the source order index. 3911 Init->setSourceOrder(i); 3912 3913 if (Init->isAnyMemberInitializer()) { 3914 const void *Key = GetKeyForMember(Context, Init); 3915 if (CheckRedundantInit(*this, Init, Members[Key]) || 3916 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3917 HadError = true; 3918 } else if (Init->isBaseInitializer()) { 3919 const void *Key = GetKeyForMember(Context, Init); 3920 if (CheckRedundantInit(*this, Init, Members[Key])) 3921 HadError = true; 3922 } else { 3923 assert(Init->isDelegatingInitializer()); 3924 // This must be the only initializer 3925 if (MemInits.size() != 1) { 3926 Diag(Init->getSourceLocation(), 3927 diag::err_delegating_initializer_alone) 3928 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3929 // We will treat this as being the only initializer. 3930 } 3931 SetDelegatingInitializer(Constructor, MemInits[i]); 3932 // Return immediately as the initializer is set. 3933 return; 3934 } 3935 } 3936 3937 if (HadError) 3938 return; 3939 3940 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3941 3942 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3943 3944 DiagnoseUninitializedFields(*this, Constructor); 3945 } 3946 3947 void 3948 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3949 CXXRecordDecl *ClassDecl) { 3950 // Ignore dependent contexts. Also ignore unions, since their members never 3951 // have destructors implicitly called. 3952 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3953 return; 3954 3955 // FIXME: all the access-control diagnostics are positioned on the 3956 // field/base declaration. That's probably good; that said, the 3957 // user might reasonably want to know why the destructor is being 3958 // emitted, and we currently don't say. 3959 3960 // Non-static data members. 3961 for (auto *Field : ClassDecl->fields()) { 3962 if (Field->isInvalidDecl()) 3963 continue; 3964 3965 // Don't destroy incomplete or zero-length arrays. 3966 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3967 continue; 3968 3969 QualType FieldType = Context.getBaseElementType(Field->getType()); 3970 3971 const RecordType* RT = FieldType->getAs<RecordType>(); 3972 if (!RT) 3973 continue; 3974 3975 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3976 if (FieldClassDecl->isInvalidDecl()) 3977 continue; 3978 if (FieldClassDecl->hasIrrelevantDestructor()) 3979 continue; 3980 // The destructor for an implicit anonymous union member is never invoked. 3981 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3982 continue; 3983 3984 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3985 assert(Dtor && "No dtor found for FieldClassDecl!"); 3986 CheckDestructorAccess(Field->getLocation(), Dtor, 3987 PDiag(diag::err_access_dtor_field) 3988 << Field->getDeclName() 3989 << FieldType); 3990 3991 MarkFunctionReferenced(Location, Dtor); 3992 DiagnoseUseOfDecl(Dtor, Location); 3993 } 3994 3995 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3996 3997 // Bases. 3998 for (const auto &Base : ClassDecl->bases()) { 3999 // Bases are always records in a well-formed non-dependent class. 4000 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4001 4002 // Remember direct virtual bases. 4003 if (Base.isVirtual()) 4004 DirectVirtualBases.insert(RT); 4005 4006 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4007 // If our base class is invalid, we probably can't get its dtor anyway. 4008 if (BaseClassDecl->isInvalidDecl()) 4009 continue; 4010 if (BaseClassDecl->hasIrrelevantDestructor()) 4011 continue; 4012 4013 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4014 assert(Dtor && "No dtor found for BaseClassDecl!"); 4015 4016 // FIXME: caret should be on the start of the class name 4017 CheckDestructorAccess(Base.getLocStart(), Dtor, 4018 PDiag(diag::err_access_dtor_base) 4019 << Base.getType() 4020 << Base.getSourceRange(), 4021 Context.getTypeDeclType(ClassDecl)); 4022 4023 MarkFunctionReferenced(Location, Dtor); 4024 DiagnoseUseOfDecl(Dtor, Location); 4025 } 4026 4027 // Virtual bases. 4028 for (const auto &VBase : ClassDecl->vbases()) { 4029 // Bases are always records in a well-formed non-dependent class. 4030 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4031 4032 // Ignore direct virtual bases. 4033 if (DirectVirtualBases.count(RT)) 4034 continue; 4035 4036 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4037 // If our base class is invalid, we probably can't get its dtor anyway. 4038 if (BaseClassDecl->isInvalidDecl()) 4039 continue; 4040 if (BaseClassDecl->hasIrrelevantDestructor()) 4041 continue; 4042 4043 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4044 assert(Dtor && "No dtor found for BaseClassDecl!"); 4045 if (CheckDestructorAccess( 4046 ClassDecl->getLocation(), Dtor, 4047 PDiag(diag::err_access_dtor_vbase) 4048 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4049 Context.getTypeDeclType(ClassDecl)) == 4050 AR_accessible) { 4051 CheckDerivedToBaseConversion( 4052 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4053 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4054 SourceRange(), DeclarationName(), nullptr); 4055 } 4056 4057 MarkFunctionReferenced(Location, Dtor); 4058 DiagnoseUseOfDecl(Dtor, Location); 4059 } 4060 } 4061 4062 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4063 if (!CDtorDecl) 4064 return; 4065 4066 if (CXXConstructorDecl *Constructor 4067 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4068 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4069 DiagnoseUninitializedFields(*this, Constructor); 4070 } 4071 } 4072 4073 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4074 unsigned DiagID, AbstractDiagSelID SelID) { 4075 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4076 unsigned DiagID; 4077 AbstractDiagSelID SelID; 4078 4079 public: 4080 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4081 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4082 4083 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4084 if (Suppressed) return; 4085 if (SelID == -1) 4086 S.Diag(Loc, DiagID) << T; 4087 else 4088 S.Diag(Loc, DiagID) << SelID << T; 4089 } 4090 } Diagnoser(DiagID, SelID); 4091 4092 return RequireNonAbstractType(Loc, T, Diagnoser); 4093 } 4094 4095 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4096 TypeDiagnoser &Diagnoser) { 4097 if (!getLangOpts().CPlusPlus) 4098 return false; 4099 4100 if (const ArrayType *AT = Context.getAsArrayType(T)) 4101 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4102 4103 if (const PointerType *PT = T->getAs<PointerType>()) { 4104 // Find the innermost pointer type. 4105 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4106 PT = T; 4107 4108 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4109 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4110 } 4111 4112 const RecordType *RT = T->getAs<RecordType>(); 4113 if (!RT) 4114 return false; 4115 4116 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4117 4118 // We can't answer whether something is abstract until it has a 4119 // definition. If it's currently being defined, we'll walk back 4120 // over all the declarations when we have a full definition. 4121 const CXXRecordDecl *Def = RD->getDefinition(); 4122 if (!Def || Def->isBeingDefined()) 4123 return false; 4124 4125 if (!RD->isAbstract()) 4126 return false; 4127 4128 Diagnoser.diagnose(*this, Loc, T); 4129 DiagnoseAbstractType(RD); 4130 4131 return true; 4132 } 4133 4134 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4135 // Check if we've already emitted the list of pure virtual functions 4136 // for this class. 4137 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4138 return; 4139 4140 // If the diagnostic is suppressed, don't emit the notes. We're only 4141 // going to emit them once, so try to attach them to a diagnostic we're 4142 // actually going to show. 4143 if (Diags.isLastDiagnosticIgnored()) 4144 return; 4145 4146 CXXFinalOverriderMap FinalOverriders; 4147 RD->getFinalOverriders(FinalOverriders); 4148 4149 // Keep a set of seen pure methods so we won't diagnose the same method 4150 // more than once. 4151 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4152 4153 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4154 MEnd = FinalOverriders.end(); 4155 M != MEnd; 4156 ++M) { 4157 for (OverridingMethods::iterator SO = M->second.begin(), 4158 SOEnd = M->second.end(); 4159 SO != SOEnd; ++SO) { 4160 // C++ [class.abstract]p4: 4161 // A class is abstract if it contains or inherits at least one 4162 // pure virtual function for which the final overrider is pure 4163 // virtual. 4164 4165 // 4166 if (SO->second.size() != 1) 4167 continue; 4168 4169 if (!SO->second.front().Method->isPure()) 4170 continue; 4171 4172 if (!SeenPureMethods.insert(SO->second.front().Method)) 4173 continue; 4174 4175 Diag(SO->second.front().Method->getLocation(), 4176 diag::note_pure_virtual_function) 4177 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4178 } 4179 } 4180 4181 if (!PureVirtualClassDiagSet) 4182 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4183 PureVirtualClassDiagSet->insert(RD); 4184 } 4185 4186 namespace { 4187 struct AbstractUsageInfo { 4188 Sema &S; 4189 CXXRecordDecl *Record; 4190 CanQualType AbstractType; 4191 bool Invalid; 4192 4193 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4194 : S(S), Record(Record), 4195 AbstractType(S.Context.getCanonicalType( 4196 S.Context.getTypeDeclType(Record))), 4197 Invalid(false) {} 4198 4199 void DiagnoseAbstractType() { 4200 if (Invalid) return; 4201 S.DiagnoseAbstractType(Record); 4202 Invalid = true; 4203 } 4204 4205 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4206 }; 4207 4208 struct CheckAbstractUsage { 4209 AbstractUsageInfo &Info; 4210 const NamedDecl *Ctx; 4211 4212 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4213 : Info(Info), Ctx(Ctx) {} 4214 4215 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4216 switch (TL.getTypeLocClass()) { 4217 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4218 #define TYPELOC(CLASS, PARENT) \ 4219 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4220 #include "clang/AST/TypeLocNodes.def" 4221 } 4222 } 4223 4224 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4225 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4226 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4227 if (!TL.getParam(I)) 4228 continue; 4229 4230 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4231 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4232 } 4233 } 4234 4235 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4236 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4237 } 4238 4239 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4240 // Visit the type parameters from a permissive context. 4241 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4242 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4243 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4244 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4245 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4246 // TODO: other template argument types? 4247 } 4248 } 4249 4250 // Visit pointee types from a permissive context. 4251 #define CheckPolymorphic(Type) \ 4252 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4253 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4254 } 4255 CheckPolymorphic(PointerTypeLoc) 4256 CheckPolymorphic(ReferenceTypeLoc) 4257 CheckPolymorphic(MemberPointerTypeLoc) 4258 CheckPolymorphic(BlockPointerTypeLoc) 4259 CheckPolymorphic(AtomicTypeLoc) 4260 4261 /// Handle all the types we haven't given a more specific 4262 /// implementation for above. 4263 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4264 // Every other kind of type that we haven't called out already 4265 // that has an inner type is either (1) sugar or (2) contains that 4266 // inner type in some way as a subobject. 4267 if (TypeLoc Next = TL.getNextTypeLoc()) 4268 return Visit(Next, Sel); 4269 4270 // If there's no inner type and we're in a permissive context, 4271 // don't diagnose. 4272 if (Sel == Sema::AbstractNone) return; 4273 4274 // Check whether the type matches the abstract type. 4275 QualType T = TL.getType(); 4276 if (T->isArrayType()) { 4277 Sel = Sema::AbstractArrayType; 4278 T = Info.S.Context.getBaseElementType(T); 4279 } 4280 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4281 if (CT != Info.AbstractType) return; 4282 4283 // It matched; do some magic. 4284 if (Sel == Sema::AbstractArrayType) { 4285 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4286 << T << TL.getSourceRange(); 4287 } else { 4288 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4289 << Sel << T << TL.getSourceRange(); 4290 } 4291 Info.DiagnoseAbstractType(); 4292 } 4293 }; 4294 4295 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4296 Sema::AbstractDiagSelID Sel) { 4297 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4298 } 4299 4300 } 4301 4302 /// Check for invalid uses of an abstract type in a method declaration. 4303 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4304 CXXMethodDecl *MD) { 4305 // No need to do the check on definitions, which require that 4306 // the return/param types be complete. 4307 if (MD->doesThisDeclarationHaveABody()) 4308 return; 4309 4310 // For safety's sake, just ignore it if we don't have type source 4311 // information. This should never happen for non-implicit methods, 4312 // but... 4313 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4314 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4315 } 4316 4317 /// Check for invalid uses of an abstract type within a class definition. 4318 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4319 CXXRecordDecl *RD) { 4320 for (auto *D : RD->decls()) { 4321 if (D->isImplicit()) continue; 4322 4323 // Methods and method templates. 4324 if (isa<CXXMethodDecl>(D)) { 4325 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4326 } else if (isa<FunctionTemplateDecl>(D)) { 4327 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4328 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4329 4330 // Fields and static variables. 4331 } else if (isa<FieldDecl>(D)) { 4332 FieldDecl *FD = cast<FieldDecl>(D); 4333 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4334 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4335 } else if (isa<VarDecl>(D)) { 4336 VarDecl *VD = cast<VarDecl>(D); 4337 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4338 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4339 4340 // Nested classes and class templates. 4341 } else if (isa<CXXRecordDecl>(D)) { 4342 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4343 } else if (isa<ClassTemplateDecl>(D)) { 4344 CheckAbstractClassUsage(Info, 4345 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4346 } 4347 } 4348 } 4349 4350 /// \brief Check class-level dllimport/dllexport attribute. 4351 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4352 Attr *ClassAttr = getDLLAttr(Class); 4353 if (!ClassAttr) 4354 return; 4355 4356 bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4357 4358 // Force declaration of implicit members so they can inherit the attribute. 4359 S.ForceDeclarationOfImplicitMembers(Class); 4360 4361 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4362 // seem to be true in practice? 4363 4364 // FIXME: We also need to propagate the attribute upwards to class template 4365 // specialization bases. 4366 4367 for (Decl *Member : Class->decls()) { 4368 VarDecl *VD = dyn_cast<VarDecl>(Member); 4369 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4370 4371 // Only methods and static fields inherit the attributes. 4372 if (!VD && !MD) 4373 continue; 4374 4375 // Don't process deleted methods. 4376 if (MD && MD->isDeleted()) 4377 continue; 4378 4379 if (MD && MD->isMoveAssignmentOperator() && !ClassExported && 4380 MD->isInlined()) { 4381 // Current MSVC versions don't export the move assignment operators, so 4382 // don't attempt to import them if we have a definition. 4383 continue; 4384 } 4385 4386 if (InheritableAttr *MemberAttr = getDLLAttr(Member)) { 4387 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4388 !MemberAttr->isInherited()) { 4389 S.Diag(MemberAttr->getLocation(), 4390 diag::err_attribute_dll_member_of_dll_class) 4391 << MemberAttr << ClassAttr; 4392 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4393 Member->setInvalidDecl(); 4394 continue; 4395 } 4396 } else { 4397 auto *NewAttr = 4398 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4399 NewAttr->setInherited(true); 4400 Member->addAttr(NewAttr); 4401 } 4402 4403 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 4404 if (ClassExported) { 4405 if (MD->isUserProvided()) { 4406 // Instantiate non-default methods. 4407 S.MarkFunctionReferenced(Class->getLocation(), MD); 4408 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4409 MD->isCopyAssignmentOperator() || 4410 MD->isMoveAssignmentOperator()) { 4411 // Instantiate non-trivial or explicitly defaulted methods, and the 4412 // copy assignment / move assignment operators. 4413 S.MarkFunctionReferenced(Class->getLocation(), MD); 4414 // Resolve its exception specification; CodeGen needs it. 4415 auto *FPT = MD->getType()->getAs<FunctionProtoType>(); 4416 S.ResolveExceptionSpec(Class->getLocation(), FPT); 4417 S.ActOnFinishInlineMethodDef(MD); 4418 } 4419 } 4420 } 4421 } 4422 } 4423 4424 /// \brief Perform semantic checks on a class definition that has been 4425 /// completing, introducing implicitly-declared members, checking for 4426 /// abstract types, etc. 4427 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4428 if (!Record) 4429 return; 4430 4431 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4432 AbstractUsageInfo Info(*this, Record); 4433 CheckAbstractClassUsage(Info, Record); 4434 } 4435 4436 // If this is not an aggregate type and has no user-declared constructor, 4437 // complain about any non-static data members of reference or const scalar 4438 // type, since they will never get initializers. 4439 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4440 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4441 !Record->isLambda()) { 4442 bool Complained = false; 4443 for (const auto *F : Record->fields()) { 4444 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4445 continue; 4446 4447 if (F->getType()->isReferenceType() || 4448 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4449 if (!Complained) { 4450 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4451 << Record->getTagKind() << Record; 4452 Complained = true; 4453 } 4454 4455 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4456 << F->getType()->isReferenceType() 4457 << F->getDeclName(); 4458 } 4459 } 4460 } 4461 4462 if (Record->isDynamicClass() && !Record->isDependentType()) 4463 DynamicClasses.push_back(Record); 4464 4465 if (Record->getIdentifier()) { 4466 // C++ [class.mem]p13: 4467 // If T is the name of a class, then each of the following shall have a 4468 // name different from T: 4469 // - every member of every anonymous union that is a member of class T. 4470 // 4471 // C++ [class.mem]p14: 4472 // In addition, if class T has a user-declared constructor (12.1), every 4473 // non-static data member of class T shall have a name different from T. 4474 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4475 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4476 ++I) { 4477 NamedDecl *D = *I; 4478 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4479 isa<IndirectFieldDecl>(D)) { 4480 Diag(D->getLocation(), diag::err_member_name_of_class) 4481 << D->getDeclName(); 4482 break; 4483 } 4484 } 4485 } 4486 4487 // Warn if the class has virtual methods but non-virtual public destructor. 4488 if (Record->isPolymorphic() && !Record->isDependentType()) { 4489 CXXDestructorDecl *dtor = Record->getDestructor(); 4490 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4491 !Record->hasAttr<FinalAttr>()) 4492 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4493 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4494 } 4495 4496 if (Record->isAbstract()) { 4497 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4498 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4499 << FA->isSpelledAsSealed(); 4500 DiagnoseAbstractType(Record); 4501 } 4502 } 4503 4504 if (!Record->isDependentType()) { 4505 for (auto *M : Record->methods()) { 4506 // See if a method overloads virtual methods in a base 4507 // class without overriding any. 4508 if (!M->isStatic()) 4509 DiagnoseHiddenVirtualMethods(M); 4510 4511 // Check whether the explicitly-defaulted special members are valid. 4512 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4513 CheckExplicitlyDefaultedSpecialMember(M); 4514 4515 // For an explicitly defaulted or deleted special member, we defer 4516 // determining triviality until the class is complete. That time is now! 4517 if (!M->isImplicit() && !M->isUserProvided()) { 4518 CXXSpecialMember CSM = getSpecialMember(M); 4519 if (CSM != CXXInvalid) { 4520 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4521 4522 // Inform the class that we've finished declaring this member. 4523 Record->finishedDefaultedOrDeletedMember(M); 4524 } 4525 } 4526 } 4527 } 4528 4529 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4530 // function that is not a constructor declares that member function to be 4531 // const. [...] The class of which that function is a member shall be 4532 // a literal type. 4533 // 4534 // If the class has virtual bases, any constexpr members will already have 4535 // been diagnosed by the checks performed on the member declaration, so 4536 // suppress this (less useful) diagnostic. 4537 // 4538 // We delay this until we know whether an explicitly-defaulted (or deleted) 4539 // destructor for the class is trivial. 4540 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4541 !Record->isLiteral() && !Record->getNumVBases()) { 4542 for (const auto *M : Record->methods()) { 4543 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) { 4544 switch (Record->getTemplateSpecializationKind()) { 4545 case TSK_ImplicitInstantiation: 4546 case TSK_ExplicitInstantiationDeclaration: 4547 case TSK_ExplicitInstantiationDefinition: 4548 // If a template instantiates to a non-literal type, but its members 4549 // instantiate to constexpr functions, the template is technically 4550 // ill-formed, but we allow it for sanity. 4551 continue; 4552 4553 case TSK_Undeclared: 4554 case TSK_ExplicitSpecialization: 4555 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4556 diag::err_constexpr_method_non_literal); 4557 break; 4558 } 4559 4560 // Only produce one error per class. 4561 break; 4562 } 4563 } 4564 } 4565 4566 // ms_struct is a request to use the same ABI rules as MSVC. Check 4567 // whether this class uses any C++ features that are implemented 4568 // completely differently in MSVC, and if so, emit a diagnostic. 4569 // That diagnostic defaults to an error, but we allow projects to 4570 // map it down to a warning (or ignore it). It's a fairly common 4571 // practice among users of the ms_struct pragma to mass-annotate 4572 // headers, sweeping up a bunch of types that the project doesn't 4573 // really rely on MSVC-compatible layout for. We must therefore 4574 // support "ms_struct except for C++ stuff" as a secondary ABI. 4575 if (Record->isMsStruct(Context) && 4576 (Record->isPolymorphic() || Record->getNumBases())) { 4577 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4578 } 4579 4580 // Declare inheriting constructors. We do this eagerly here because: 4581 // - The standard requires an eager diagnostic for conflicting inheriting 4582 // constructors from different classes. 4583 // - The lazy declaration of the other implicit constructors is so as to not 4584 // waste space and performance on classes that are not meant to be 4585 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4586 // have inheriting constructors. 4587 DeclareInheritingConstructors(Record); 4588 4589 checkDLLAttribute(*this, Record); 4590 } 4591 4592 /// Look up the special member function that would be called by a special 4593 /// member function for a subobject of class type. 4594 /// 4595 /// \param Class The class type of the subobject. 4596 /// \param CSM The kind of special member function. 4597 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4598 /// \param ConstRHS True if this is a copy operation with a const object 4599 /// on its RHS, that is, if the argument to the outer special member 4600 /// function is 'const' and this is not a field marked 'mutable'. 4601 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4602 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4603 unsigned FieldQuals, bool ConstRHS) { 4604 unsigned LHSQuals = 0; 4605 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4606 LHSQuals = FieldQuals; 4607 4608 unsigned RHSQuals = FieldQuals; 4609 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4610 RHSQuals = 0; 4611 else if (ConstRHS) 4612 RHSQuals |= Qualifiers::Const; 4613 4614 return S.LookupSpecialMember(Class, CSM, 4615 RHSQuals & Qualifiers::Const, 4616 RHSQuals & Qualifiers::Volatile, 4617 false, 4618 LHSQuals & Qualifiers::Const, 4619 LHSQuals & Qualifiers::Volatile); 4620 } 4621 4622 /// Is the special member function which would be selected to perform the 4623 /// specified operation on the specified class type a constexpr constructor? 4624 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4625 Sema::CXXSpecialMember CSM, 4626 unsigned Quals, bool ConstRHS) { 4627 Sema::SpecialMemberOverloadResult *SMOR = 4628 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4629 if (!SMOR || !SMOR->getMethod()) 4630 // A constructor we wouldn't select can't be "involved in initializing" 4631 // anything. 4632 return true; 4633 return SMOR->getMethod()->isConstexpr(); 4634 } 4635 4636 /// Determine whether the specified special member function would be constexpr 4637 /// if it were implicitly defined. 4638 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4639 Sema::CXXSpecialMember CSM, 4640 bool ConstArg) { 4641 if (!S.getLangOpts().CPlusPlus11) 4642 return false; 4643 4644 // C++11 [dcl.constexpr]p4: 4645 // In the definition of a constexpr constructor [...] 4646 bool Ctor = true; 4647 switch (CSM) { 4648 case Sema::CXXDefaultConstructor: 4649 // Since default constructor lookup is essentially trivial (and cannot 4650 // involve, for instance, template instantiation), we compute whether a 4651 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4652 // 4653 // This is important for performance; we need to know whether the default 4654 // constructor is constexpr to determine whether the type is a literal type. 4655 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4656 4657 case Sema::CXXCopyConstructor: 4658 case Sema::CXXMoveConstructor: 4659 // For copy or move constructors, we need to perform overload resolution. 4660 break; 4661 4662 case Sema::CXXCopyAssignment: 4663 case Sema::CXXMoveAssignment: 4664 if (!S.getLangOpts().CPlusPlus1y) 4665 return false; 4666 // In C++1y, we need to perform overload resolution. 4667 Ctor = false; 4668 break; 4669 4670 case Sema::CXXDestructor: 4671 case Sema::CXXInvalid: 4672 return false; 4673 } 4674 4675 // -- if the class is a non-empty union, or for each non-empty anonymous 4676 // union member of a non-union class, exactly one non-static data member 4677 // shall be initialized; [DR1359] 4678 // 4679 // If we squint, this is guaranteed, since exactly one non-static data member 4680 // will be initialized (if the constructor isn't deleted), we just don't know 4681 // which one. 4682 if (Ctor && ClassDecl->isUnion()) 4683 return true; 4684 4685 // -- the class shall not have any virtual base classes; 4686 if (Ctor && ClassDecl->getNumVBases()) 4687 return false; 4688 4689 // C++1y [class.copy]p26: 4690 // -- [the class] is a literal type, and 4691 if (!Ctor && !ClassDecl->isLiteral()) 4692 return false; 4693 4694 // -- every constructor involved in initializing [...] base class 4695 // sub-objects shall be a constexpr constructor; 4696 // -- the assignment operator selected to copy/move each direct base 4697 // class is a constexpr function, and 4698 for (const auto &B : ClassDecl->bases()) { 4699 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 4700 if (!BaseType) continue; 4701 4702 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4703 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 4704 return false; 4705 } 4706 4707 // -- every constructor involved in initializing non-static data members 4708 // [...] shall be a constexpr constructor; 4709 // -- every non-static data member and base class sub-object shall be 4710 // initialized 4711 // -- for each non-static data member of X that is of class type (or array 4712 // thereof), the assignment operator selected to copy/move that member is 4713 // a constexpr function 4714 for (const auto *F : ClassDecl->fields()) { 4715 if (F->isInvalidDecl()) 4716 continue; 4717 QualType BaseType = S.Context.getBaseElementType(F->getType()); 4718 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 4719 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4720 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 4721 BaseType.getCVRQualifiers(), 4722 ConstArg && !F->isMutable())) 4723 return false; 4724 } 4725 } 4726 4727 // All OK, it's constexpr! 4728 return true; 4729 } 4730 4731 static Sema::ImplicitExceptionSpecification 4732 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4733 switch (S.getSpecialMember(MD)) { 4734 case Sema::CXXDefaultConstructor: 4735 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4736 case Sema::CXXCopyConstructor: 4737 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4738 case Sema::CXXCopyAssignment: 4739 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4740 case Sema::CXXMoveConstructor: 4741 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4742 case Sema::CXXMoveAssignment: 4743 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4744 case Sema::CXXDestructor: 4745 return S.ComputeDefaultedDtorExceptionSpec(MD); 4746 case Sema::CXXInvalid: 4747 break; 4748 } 4749 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4750 "only special members have implicit exception specs"); 4751 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4752 } 4753 4754 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4755 CXXMethodDecl *MD) { 4756 FunctionProtoType::ExtProtoInfo EPI; 4757 4758 // Build an exception specification pointing back at this member. 4759 EPI.ExceptionSpecType = EST_Unevaluated; 4760 EPI.ExceptionSpecDecl = MD; 4761 4762 // Set the calling convention to the default for C++ instance methods. 4763 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4764 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4765 /*IsCXXMethod=*/true)); 4766 return EPI; 4767 } 4768 4769 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4770 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4771 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4772 return; 4773 4774 // Evaluate the exception specification. 4775 ImplicitExceptionSpecification ExceptSpec = 4776 computeImplicitExceptionSpec(*this, Loc, MD); 4777 4778 FunctionProtoType::ExtProtoInfo EPI; 4779 ExceptSpec.getEPI(EPI); 4780 4781 // Update the type of the special member to use it. 4782 UpdateExceptionSpec(MD, EPI); 4783 4784 // A user-provided destructor can be defined outside the class. When that 4785 // happens, be sure to update the exception specification on both 4786 // declarations. 4787 const FunctionProtoType *CanonicalFPT = 4788 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4789 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4790 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI); 4791 } 4792 4793 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4794 CXXRecordDecl *RD = MD->getParent(); 4795 CXXSpecialMember CSM = getSpecialMember(MD); 4796 4797 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4798 "not an explicitly-defaulted special member"); 4799 4800 // Whether this was the first-declared instance of the constructor. 4801 // This affects whether we implicitly add an exception spec and constexpr. 4802 bool First = MD == MD->getCanonicalDecl(); 4803 4804 bool HadError = false; 4805 4806 // C++11 [dcl.fct.def.default]p1: 4807 // A function that is explicitly defaulted shall 4808 // -- be a special member function (checked elsewhere), 4809 // -- have the same type (except for ref-qualifiers, and except that a 4810 // copy operation can take a non-const reference) as an implicit 4811 // declaration, and 4812 // -- not have default arguments. 4813 unsigned ExpectedParams = 1; 4814 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4815 ExpectedParams = 0; 4816 if (MD->getNumParams() != ExpectedParams) { 4817 // This also checks for default arguments: a copy or move constructor with a 4818 // default argument is classified as a default constructor, and assignment 4819 // operations and destructors can't have default arguments. 4820 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4821 << CSM << MD->getSourceRange(); 4822 HadError = true; 4823 } else if (MD->isVariadic()) { 4824 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4825 << CSM << MD->getSourceRange(); 4826 HadError = true; 4827 } 4828 4829 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4830 4831 bool CanHaveConstParam = false; 4832 if (CSM == CXXCopyConstructor) 4833 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4834 else if (CSM == CXXCopyAssignment) 4835 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4836 4837 QualType ReturnType = Context.VoidTy; 4838 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4839 // Check for return type matching. 4840 ReturnType = Type->getReturnType(); 4841 QualType ExpectedReturnType = 4842 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4843 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4844 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4845 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4846 HadError = true; 4847 } 4848 4849 // A defaulted special member cannot have cv-qualifiers. 4850 if (Type->getTypeQuals()) { 4851 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4852 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4853 HadError = true; 4854 } 4855 } 4856 4857 // Check for parameter type matching. 4858 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 4859 bool HasConstParam = false; 4860 if (ExpectedParams && ArgType->isReferenceType()) { 4861 // Argument must be reference to possibly-const T. 4862 QualType ReferentType = ArgType->getPointeeType(); 4863 HasConstParam = ReferentType.isConstQualified(); 4864 4865 if (ReferentType.isVolatileQualified()) { 4866 Diag(MD->getLocation(), 4867 diag::err_defaulted_special_member_volatile_param) << CSM; 4868 HadError = true; 4869 } 4870 4871 if (HasConstParam && !CanHaveConstParam) { 4872 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4873 Diag(MD->getLocation(), 4874 diag::err_defaulted_special_member_copy_const_param) 4875 << (CSM == CXXCopyAssignment); 4876 // FIXME: Explain why this special member can't be const. 4877 } else { 4878 Diag(MD->getLocation(), 4879 diag::err_defaulted_special_member_move_const_param) 4880 << (CSM == CXXMoveAssignment); 4881 } 4882 HadError = true; 4883 } 4884 } else if (ExpectedParams) { 4885 // A copy assignment operator can take its argument by value, but a 4886 // defaulted one cannot. 4887 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4888 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4889 HadError = true; 4890 } 4891 4892 // C++11 [dcl.fct.def.default]p2: 4893 // An explicitly-defaulted function may be declared constexpr only if it 4894 // would have been implicitly declared as constexpr, 4895 // Do not apply this rule to members of class templates, since core issue 1358 4896 // makes such functions always instantiate to constexpr functions. For 4897 // functions which cannot be constexpr (for non-constructors in C++11 and for 4898 // destructors in C++1y), this is checked elsewhere. 4899 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4900 HasConstParam); 4901 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4902 : isa<CXXConstructorDecl>(MD)) && 4903 MD->isConstexpr() && !Constexpr && 4904 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4905 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4906 // FIXME: Explain why the special member can't be constexpr. 4907 HadError = true; 4908 } 4909 4910 // and may have an explicit exception-specification only if it is compatible 4911 // with the exception-specification on the implicit declaration. 4912 if (Type->hasExceptionSpec()) { 4913 // Delay the check if this is the first declaration of the special member, 4914 // since we may not have parsed some necessary in-class initializers yet. 4915 if (First) { 4916 // If the exception specification needs to be instantiated, do so now, 4917 // before we clobber it with an EST_Unevaluated specification below. 4918 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4919 InstantiateExceptionSpec(MD->getLocStart(), MD); 4920 Type = MD->getType()->getAs<FunctionProtoType>(); 4921 } 4922 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4923 } else 4924 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4925 } 4926 4927 // If a function is explicitly defaulted on its first declaration, 4928 if (First) { 4929 // -- it is implicitly considered to be constexpr if the implicit 4930 // definition would be, 4931 MD->setConstexpr(Constexpr); 4932 4933 // -- it is implicitly considered to have the same exception-specification 4934 // as if it had been implicitly declared, 4935 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4936 EPI.ExceptionSpecType = EST_Unevaluated; 4937 EPI.ExceptionSpecDecl = MD; 4938 MD->setType(Context.getFunctionType(ReturnType, 4939 ArrayRef<QualType>(&ArgType, 4940 ExpectedParams), 4941 EPI)); 4942 } 4943 4944 if (ShouldDeleteSpecialMember(MD, CSM)) { 4945 if (First) { 4946 SetDeclDeleted(MD, MD->getLocation()); 4947 } else { 4948 // C++11 [dcl.fct.def.default]p4: 4949 // [For a] user-provided explicitly-defaulted function [...] if such a 4950 // function is implicitly defined as deleted, the program is ill-formed. 4951 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4952 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 4953 HadError = true; 4954 } 4955 } 4956 4957 if (HadError) 4958 MD->setInvalidDecl(); 4959 } 4960 4961 /// Check whether the exception specification provided for an 4962 /// explicitly-defaulted special member matches the exception specification 4963 /// that would have been generated for an implicit special member, per 4964 /// C++11 [dcl.fct.def.default]p2. 4965 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4966 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4967 // Compute the implicit exception specification. 4968 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4969 /*IsCXXMethod=*/true); 4970 FunctionProtoType::ExtProtoInfo EPI(CC); 4971 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4972 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4973 Context.getFunctionType(Context.VoidTy, None, EPI)); 4974 4975 // Ensure that it matches. 4976 CheckEquivalentExceptionSpec( 4977 PDiag(diag::err_incorrect_defaulted_exception_spec) 4978 << getSpecialMember(MD), PDiag(), 4979 ImplicitType, SourceLocation(), 4980 SpecifiedType, MD->getLocation()); 4981 } 4982 4983 void Sema::CheckDelayedMemberExceptionSpecs() { 4984 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 4985 2> Checks; 4986 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 4987 4988 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 4989 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 4990 4991 // Perform any deferred checking of exception specifications for virtual 4992 // destructors. 4993 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 4994 const CXXDestructorDecl *Dtor = Checks[i].first; 4995 assert(!Dtor->getParent()->isDependentType() && 4996 "Should not ever add destructors of templates into the list."); 4997 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 4998 } 4999 5000 // Check that any explicitly-defaulted methods have exception specifications 5001 // compatible with their implicit exception specifications. 5002 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 5003 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 5004 Specs[I].second); 5005 } 5006 5007 namespace { 5008 struct SpecialMemberDeletionInfo { 5009 Sema &S; 5010 CXXMethodDecl *MD; 5011 Sema::CXXSpecialMember CSM; 5012 bool Diagnose; 5013 5014 // Properties of the special member, computed for convenience. 5015 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5016 SourceLocation Loc; 5017 5018 bool AllFieldsAreConst; 5019 5020 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5021 Sema::CXXSpecialMember CSM, bool Diagnose) 5022 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5023 IsConstructor(false), IsAssignment(false), IsMove(false), 5024 ConstArg(false), Loc(MD->getLocation()), 5025 AllFieldsAreConst(true) { 5026 switch (CSM) { 5027 case Sema::CXXDefaultConstructor: 5028 case Sema::CXXCopyConstructor: 5029 IsConstructor = true; 5030 break; 5031 case Sema::CXXMoveConstructor: 5032 IsConstructor = true; 5033 IsMove = true; 5034 break; 5035 case Sema::CXXCopyAssignment: 5036 IsAssignment = true; 5037 break; 5038 case Sema::CXXMoveAssignment: 5039 IsAssignment = true; 5040 IsMove = true; 5041 break; 5042 case Sema::CXXDestructor: 5043 break; 5044 case Sema::CXXInvalid: 5045 llvm_unreachable("invalid special member kind"); 5046 } 5047 5048 if (MD->getNumParams()) { 5049 if (const ReferenceType *RT = 5050 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5051 ConstArg = RT->getPointeeType().isConstQualified(); 5052 } 5053 } 5054 5055 bool inUnion() const { return MD->getParent()->isUnion(); } 5056 5057 /// Look up the corresponding special member in the given class. 5058 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5059 unsigned Quals, bool IsMutable) { 5060 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5061 ConstArg && !IsMutable); 5062 } 5063 5064 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5065 5066 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5067 bool shouldDeleteForField(FieldDecl *FD); 5068 bool shouldDeleteForAllConstMembers(); 5069 5070 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5071 unsigned Quals); 5072 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5073 Sema::SpecialMemberOverloadResult *SMOR, 5074 bool IsDtorCallInCtor); 5075 5076 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5077 }; 5078 } 5079 5080 /// Is the given special member inaccessible when used on the given 5081 /// sub-object. 5082 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5083 CXXMethodDecl *target) { 5084 /// If we're operating on a base class, the object type is the 5085 /// type of this special member. 5086 QualType objectTy; 5087 AccessSpecifier access = target->getAccess(); 5088 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5089 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5090 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5091 5092 // If we're operating on a field, the object type is the type of the field. 5093 } else { 5094 objectTy = S.Context.getTypeDeclType(target->getParent()); 5095 } 5096 5097 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5098 } 5099 5100 /// Check whether we should delete a special member due to the implicit 5101 /// definition containing a call to a special member of a subobject. 5102 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5103 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5104 bool IsDtorCallInCtor) { 5105 CXXMethodDecl *Decl = SMOR->getMethod(); 5106 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5107 5108 int DiagKind = -1; 5109 5110 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5111 DiagKind = !Decl ? 0 : 1; 5112 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5113 DiagKind = 2; 5114 else if (!isAccessible(Subobj, Decl)) 5115 DiagKind = 3; 5116 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5117 !Decl->isTrivial()) { 5118 // A member of a union must have a trivial corresponding special member. 5119 // As a weird special case, a destructor call from a union's constructor 5120 // must be accessible and non-deleted, but need not be trivial. Such a 5121 // destructor is never actually called, but is semantically checked as 5122 // if it were. 5123 DiagKind = 4; 5124 } 5125 5126 if (DiagKind == -1) 5127 return false; 5128 5129 if (Diagnose) { 5130 if (Field) { 5131 S.Diag(Field->getLocation(), 5132 diag::note_deleted_special_member_class_subobject) 5133 << CSM << MD->getParent() << /*IsField*/true 5134 << Field << DiagKind << IsDtorCallInCtor; 5135 } else { 5136 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5137 S.Diag(Base->getLocStart(), 5138 diag::note_deleted_special_member_class_subobject) 5139 << CSM << MD->getParent() << /*IsField*/false 5140 << Base->getType() << DiagKind << IsDtorCallInCtor; 5141 } 5142 5143 if (DiagKind == 1) 5144 S.NoteDeletedFunction(Decl); 5145 // FIXME: Explain inaccessibility if DiagKind == 3. 5146 } 5147 5148 return true; 5149 } 5150 5151 /// Check whether we should delete a special member function due to having a 5152 /// direct or virtual base class or non-static data member of class type M. 5153 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5154 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5155 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5156 bool IsMutable = Field && Field->isMutable(); 5157 5158 // C++11 [class.ctor]p5: 5159 // -- any direct or virtual base class, or non-static data member with no 5160 // brace-or-equal-initializer, has class type M (or array thereof) and 5161 // either M has no default constructor or overload resolution as applied 5162 // to M's default constructor results in an ambiguity or in a function 5163 // that is deleted or inaccessible 5164 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5165 // -- a direct or virtual base class B that cannot be copied/moved because 5166 // overload resolution, as applied to B's corresponding special member, 5167 // results in an ambiguity or a function that is deleted or inaccessible 5168 // from the defaulted special member 5169 // C++11 [class.dtor]p5: 5170 // -- any direct or virtual base class [...] has a type with a destructor 5171 // that is deleted or inaccessible 5172 if (!(CSM == Sema::CXXDefaultConstructor && 5173 Field && Field->hasInClassInitializer()) && 5174 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5175 false)) 5176 return true; 5177 5178 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5179 // -- any direct or virtual base class or non-static data member has a 5180 // type with a destructor that is deleted or inaccessible 5181 if (IsConstructor) { 5182 Sema::SpecialMemberOverloadResult *SMOR = 5183 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5184 false, false, false, false, false); 5185 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5186 return true; 5187 } 5188 5189 return false; 5190 } 5191 5192 /// Check whether we should delete a special member function due to the class 5193 /// having a particular direct or virtual base class. 5194 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5195 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5196 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5197 } 5198 5199 /// Check whether we should delete a special member function due to the class 5200 /// having a particular non-static data member. 5201 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5202 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5203 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5204 5205 if (CSM == Sema::CXXDefaultConstructor) { 5206 // For a default constructor, all references must be initialized in-class 5207 // and, if a union, it must have a non-const member. 5208 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5209 if (Diagnose) 5210 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5211 << MD->getParent() << FD << FieldType << /*Reference*/0; 5212 return true; 5213 } 5214 // C++11 [class.ctor]p5: any non-variant non-static data member of 5215 // const-qualified type (or array thereof) with no 5216 // brace-or-equal-initializer does not have a user-provided default 5217 // constructor. 5218 if (!inUnion() && FieldType.isConstQualified() && 5219 !FD->hasInClassInitializer() && 5220 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5221 if (Diagnose) 5222 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5223 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5224 return true; 5225 } 5226 5227 if (inUnion() && !FieldType.isConstQualified()) 5228 AllFieldsAreConst = false; 5229 } else if (CSM == Sema::CXXCopyConstructor) { 5230 // For a copy constructor, data members must not be of rvalue reference 5231 // type. 5232 if (FieldType->isRValueReferenceType()) { 5233 if (Diagnose) 5234 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5235 << MD->getParent() << FD << FieldType; 5236 return true; 5237 } 5238 } else if (IsAssignment) { 5239 // For an assignment operator, data members must not be of reference type. 5240 if (FieldType->isReferenceType()) { 5241 if (Diagnose) 5242 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5243 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5244 return true; 5245 } 5246 if (!FieldRecord && FieldType.isConstQualified()) { 5247 // C++11 [class.copy]p23: 5248 // -- a non-static data member of const non-class type (or array thereof) 5249 if (Diagnose) 5250 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5251 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5252 return true; 5253 } 5254 } 5255 5256 if (FieldRecord) { 5257 // Some additional restrictions exist on the variant members. 5258 if (!inUnion() && FieldRecord->isUnion() && 5259 FieldRecord->isAnonymousStructOrUnion()) { 5260 bool AllVariantFieldsAreConst = true; 5261 5262 // FIXME: Handle anonymous unions declared within anonymous unions. 5263 for (auto *UI : FieldRecord->fields()) { 5264 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5265 5266 if (!UnionFieldType.isConstQualified()) 5267 AllVariantFieldsAreConst = false; 5268 5269 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5270 if (UnionFieldRecord && 5271 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5272 UnionFieldType.getCVRQualifiers())) 5273 return true; 5274 } 5275 5276 // At least one member in each anonymous union must be non-const 5277 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5278 !FieldRecord->field_empty()) { 5279 if (Diagnose) 5280 S.Diag(FieldRecord->getLocation(), 5281 diag::note_deleted_default_ctor_all_const) 5282 << MD->getParent() << /*anonymous union*/1; 5283 return true; 5284 } 5285 5286 // Don't check the implicit member of the anonymous union type. 5287 // This is technically non-conformant, but sanity demands it. 5288 return false; 5289 } 5290 5291 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5292 FieldType.getCVRQualifiers())) 5293 return true; 5294 } 5295 5296 return false; 5297 } 5298 5299 /// C++11 [class.ctor] p5: 5300 /// A defaulted default constructor for a class X is defined as deleted if 5301 /// X is a union and all of its variant members are of const-qualified type. 5302 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5303 // This is a silly definition, because it gives an empty union a deleted 5304 // default constructor. Don't do that. 5305 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5306 !MD->getParent()->field_empty()) { 5307 if (Diagnose) 5308 S.Diag(MD->getParent()->getLocation(), 5309 diag::note_deleted_default_ctor_all_const) 5310 << MD->getParent() << /*not anonymous union*/0; 5311 return true; 5312 } 5313 return false; 5314 } 5315 5316 /// Determine whether a defaulted special member function should be defined as 5317 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5318 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5319 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5320 bool Diagnose) { 5321 if (MD->isInvalidDecl()) 5322 return false; 5323 CXXRecordDecl *RD = MD->getParent(); 5324 assert(!RD->isDependentType() && "do deletion after instantiation"); 5325 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5326 return false; 5327 5328 // C++11 [expr.lambda.prim]p19: 5329 // The closure type associated with a lambda-expression has a 5330 // deleted (8.4.3) default constructor and a deleted copy 5331 // assignment operator. 5332 if (RD->isLambda() && 5333 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5334 if (Diagnose) 5335 Diag(RD->getLocation(), diag::note_lambda_decl); 5336 return true; 5337 } 5338 5339 // For an anonymous struct or union, the copy and assignment special members 5340 // will never be used, so skip the check. For an anonymous union declared at 5341 // namespace scope, the constructor and destructor are used. 5342 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5343 RD->isAnonymousStructOrUnion()) 5344 return false; 5345 5346 // C++11 [class.copy]p7, p18: 5347 // If the class definition declares a move constructor or move assignment 5348 // operator, an implicitly declared copy constructor or copy assignment 5349 // operator is defined as deleted. 5350 if (MD->isImplicit() && 5351 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5352 CXXMethodDecl *UserDeclaredMove = nullptr; 5353 5354 // In Microsoft mode, a user-declared move only causes the deletion of the 5355 // corresponding copy operation, not both copy operations. 5356 if (RD->hasUserDeclaredMoveConstructor() && 5357 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5358 if (!Diagnose) return true; 5359 5360 // Find any user-declared move constructor. 5361 for (auto *I : RD->ctors()) { 5362 if (I->isMoveConstructor()) { 5363 UserDeclaredMove = I; 5364 break; 5365 } 5366 } 5367 assert(UserDeclaredMove); 5368 } else if (RD->hasUserDeclaredMoveAssignment() && 5369 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5370 if (!Diagnose) return true; 5371 5372 // Find any user-declared move assignment operator. 5373 for (auto *I : RD->methods()) { 5374 if (I->isMoveAssignmentOperator()) { 5375 UserDeclaredMove = I; 5376 break; 5377 } 5378 } 5379 assert(UserDeclaredMove); 5380 } 5381 5382 if (UserDeclaredMove) { 5383 Diag(UserDeclaredMove->getLocation(), 5384 diag::note_deleted_copy_user_declared_move) 5385 << (CSM == CXXCopyAssignment) << RD 5386 << UserDeclaredMove->isMoveAssignmentOperator(); 5387 return true; 5388 } 5389 } 5390 5391 // Do access control from the special member function 5392 ContextRAII MethodContext(*this, MD); 5393 5394 // C++11 [class.dtor]p5: 5395 // -- for a virtual destructor, lookup of the non-array deallocation function 5396 // results in an ambiguity or in a function that is deleted or inaccessible 5397 if (CSM == CXXDestructor && MD->isVirtual()) { 5398 FunctionDecl *OperatorDelete = nullptr; 5399 DeclarationName Name = 5400 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5401 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5402 OperatorDelete, false)) { 5403 if (Diagnose) 5404 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5405 return true; 5406 } 5407 } 5408 5409 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5410 5411 for (auto &BI : RD->bases()) 5412 if (!BI.isVirtual() && 5413 SMI.shouldDeleteForBase(&BI)) 5414 return true; 5415 5416 // Per DR1611, do not consider virtual bases of constructors of abstract 5417 // classes, since we are not going to construct them. 5418 if (!RD->isAbstract() || !SMI.IsConstructor) { 5419 for (auto &BI : RD->vbases()) 5420 if (SMI.shouldDeleteForBase(&BI)) 5421 return true; 5422 } 5423 5424 for (auto *FI : RD->fields()) 5425 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5426 SMI.shouldDeleteForField(FI)) 5427 return true; 5428 5429 if (SMI.shouldDeleteForAllConstMembers()) 5430 return true; 5431 5432 return false; 5433 } 5434 5435 /// Perform lookup for a special member of the specified kind, and determine 5436 /// whether it is trivial. If the triviality can be determined without the 5437 /// lookup, skip it. This is intended for use when determining whether a 5438 /// special member of a containing object is trivial, and thus does not ever 5439 /// perform overload resolution for default constructors. 5440 /// 5441 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5442 /// member that was most likely to be intended to be trivial, if any. 5443 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5444 Sema::CXXSpecialMember CSM, unsigned Quals, 5445 bool ConstRHS, CXXMethodDecl **Selected) { 5446 if (Selected) 5447 *Selected = nullptr; 5448 5449 switch (CSM) { 5450 case Sema::CXXInvalid: 5451 llvm_unreachable("not a special member"); 5452 5453 case Sema::CXXDefaultConstructor: 5454 // C++11 [class.ctor]p5: 5455 // A default constructor is trivial if: 5456 // - all the [direct subobjects] have trivial default constructors 5457 // 5458 // Note, no overload resolution is performed in this case. 5459 if (RD->hasTrivialDefaultConstructor()) 5460 return true; 5461 5462 if (Selected) { 5463 // If there's a default constructor which could have been trivial, dig it 5464 // out. Otherwise, if there's any user-provided default constructor, point 5465 // to that as an example of why there's not a trivial one. 5466 CXXConstructorDecl *DefCtor = nullptr; 5467 if (RD->needsImplicitDefaultConstructor()) 5468 S.DeclareImplicitDefaultConstructor(RD); 5469 for (auto *CI : RD->ctors()) { 5470 if (!CI->isDefaultConstructor()) 5471 continue; 5472 DefCtor = CI; 5473 if (!DefCtor->isUserProvided()) 5474 break; 5475 } 5476 5477 *Selected = DefCtor; 5478 } 5479 5480 return false; 5481 5482 case Sema::CXXDestructor: 5483 // C++11 [class.dtor]p5: 5484 // A destructor is trivial if: 5485 // - all the direct [subobjects] have trivial destructors 5486 if (RD->hasTrivialDestructor()) 5487 return true; 5488 5489 if (Selected) { 5490 if (RD->needsImplicitDestructor()) 5491 S.DeclareImplicitDestructor(RD); 5492 *Selected = RD->getDestructor(); 5493 } 5494 5495 return false; 5496 5497 case Sema::CXXCopyConstructor: 5498 // C++11 [class.copy]p12: 5499 // A copy constructor is trivial if: 5500 // - the constructor selected to copy each direct [subobject] is trivial 5501 if (RD->hasTrivialCopyConstructor()) { 5502 if (Quals == Qualifiers::Const) 5503 // We must either select the trivial copy constructor or reach an 5504 // ambiguity; no need to actually perform overload resolution. 5505 return true; 5506 } else if (!Selected) { 5507 return false; 5508 } 5509 // In C++98, we are not supposed to perform overload resolution here, but we 5510 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5511 // cases like B as having a non-trivial copy constructor: 5512 // struct A { template<typename T> A(T&); }; 5513 // struct B { mutable A a; }; 5514 goto NeedOverloadResolution; 5515 5516 case Sema::CXXCopyAssignment: 5517 // C++11 [class.copy]p25: 5518 // A copy assignment operator is trivial if: 5519 // - the assignment operator selected to copy each direct [subobject] is 5520 // trivial 5521 if (RD->hasTrivialCopyAssignment()) { 5522 if (Quals == Qualifiers::Const) 5523 return true; 5524 } else if (!Selected) { 5525 return false; 5526 } 5527 // In C++98, we are not supposed to perform overload resolution here, but we 5528 // treat that as a language defect. 5529 goto NeedOverloadResolution; 5530 5531 case Sema::CXXMoveConstructor: 5532 case Sema::CXXMoveAssignment: 5533 NeedOverloadResolution: 5534 Sema::SpecialMemberOverloadResult *SMOR = 5535 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5536 5537 // The standard doesn't describe how to behave if the lookup is ambiguous. 5538 // We treat it as not making the member non-trivial, just like the standard 5539 // mandates for the default constructor. This should rarely matter, because 5540 // the member will also be deleted. 5541 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5542 return true; 5543 5544 if (!SMOR->getMethod()) { 5545 assert(SMOR->getKind() == 5546 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5547 return false; 5548 } 5549 5550 // We deliberately don't check if we found a deleted special member. We're 5551 // not supposed to! 5552 if (Selected) 5553 *Selected = SMOR->getMethod(); 5554 return SMOR->getMethod()->isTrivial(); 5555 } 5556 5557 llvm_unreachable("unknown special method kind"); 5558 } 5559 5560 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5561 for (auto *CI : RD->ctors()) 5562 if (!CI->isImplicit()) 5563 return CI; 5564 5565 // Look for constructor templates. 5566 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5567 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5568 if (CXXConstructorDecl *CD = 5569 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5570 return CD; 5571 } 5572 5573 return nullptr; 5574 } 5575 5576 /// The kind of subobject we are checking for triviality. The values of this 5577 /// enumeration are used in diagnostics. 5578 enum TrivialSubobjectKind { 5579 /// The subobject is a base class. 5580 TSK_BaseClass, 5581 /// The subobject is a non-static data member. 5582 TSK_Field, 5583 /// The object is actually the complete object. 5584 TSK_CompleteObject 5585 }; 5586 5587 /// Check whether the special member selected for a given type would be trivial. 5588 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5589 QualType SubType, bool ConstRHS, 5590 Sema::CXXSpecialMember CSM, 5591 TrivialSubobjectKind Kind, 5592 bool Diagnose) { 5593 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5594 if (!SubRD) 5595 return true; 5596 5597 CXXMethodDecl *Selected; 5598 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5599 ConstRHS, Diagnose ? &Selected : nullptr)) 5600 return true; 5601 5602 if (Diagnose) { 5603 if (ConstRHS) 5604 SubType.addConst(); 5605 5606 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5607 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5608 << Kind << SubType.getUnqualifiedType(); 5609 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5610 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5611 } else if (!Selected) 5612 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5613 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5614 else if (Selected->isUserProvided()) { 5615 if (Kind == TSK_CompleteObject) 5616 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5617 << Kind << SubType.getUnqualifiedType() << CSM; 5618 else { 5619 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5620 << Kind << SubType.getUnqualifiedType() << CSM; 5621 S.Diag(Selected->getLocation(), diag::note_declared_at); 5622 } 5623 } else { 5624 if (Kind != TSK_CompleteObject) 5625 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5626 << Kind << SubType.getUnqualifiedType() << CSM; 5627 5628 // Explain why the defaulted or deleted special member isn't trivial. 5629 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5630 } 5631 } 5632 5633 return false; 5634 } 5635 5636 /// Check whether the members of a class type allow a special member to be 5637 /// trivial. 5638 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5639 Sema::CXXSpecialMember CSM, 5640 bool ConstArg, bool Diagnose) { 5641 for (const auto *FI : RD->fields()) { 5642 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5643 continue; 5644 5645 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5646 5647 // Pretend anonymous struct or union members are members of this class. 5648 if (FI->isAnonymousStructOrUnion()) { 5649 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5650 CSM, ConstArg, Diagnose)) 5651 return false; 5652 continue; 5653 } 5654 5655 // C++11 [class.ctor]p5: 5656 // A default constructor is trivial if [...] 5657 // -- no non-static data member of its class has a 5658 // brace-or-equal-initializer 5659 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5660 if (Diagnose) 5661 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5662 return false; 5663 } 5664 5665 // Objective C ARC 4.3.5: 5666 // [...] nontrivally ownership-qualified types are [...] not trivially 5667 // default constructible, copy constructible, move constructible, copy 5668 // assignable, move assignable, or destructible [...] 5669 if (S.getLangOpts().ObjCAutoRefCount && 5670 FieldType.hasNonTrivialObjCLifetime()) { 5671 if (Diagnose) 5672 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5673 << RD << FieldType.getObjCLifetime(); 5674 return false; 5675 } 5676 5677 bool ConstRHS = ConstArg && !FI->isMutable(); 5678 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 5679 CSM, TSK_Field, Diagnose)) 5680 return false; 5681 } 5682 5683 return true; 5684 } 5685 5686 /// Diagnose why the specified class does not have a trivial special member of 5687 /// the given kind. 5688 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5689 QualType Ty = Context.getRecordType(RD); 5690 5691 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 5692 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 5693 TSK_CompleteObject, /*Diagnose*/true); 5694 } 5695 5696 /// Determine whether a defaulted or deleted special member function is trivial, 5697 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5698 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5699 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5700 bool Diagnose) { 5701 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5702 5703 CXXRecordDecl *RD = MD->getParent(); 5704 5705 bool ConstArg = false; 5706 5707 // C++11 [class.copy]p12, p25: [DR1593] 5708 // A [special member] is trivial if [...] its parameter-type-list is 5709 // equivalent to the parameter-type-list of an implicit declaration [...] 5710 switch (CSM) { 5711 case CXXDefaultConstructor: 5712 case CXXDestructor: 5713 // Trivial default constructors and destructors cannot have parameters. 5714 break; 5715 5716 case CXXCopyConstructor: 5717 case CXXCopyAssignment: { 5718 // Trivial copy operations always have const, non-volatile parameter types. 5719 ConstArg = true; 5720 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5721 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5722 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5723 if (Diagnose) 5724 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5725 << Param0->getSourceRange() << Param0->getType() 5726 << Context.getLValueReferenceType( 5727 Context.getRecordType(RD).withConst()); 5728 return false; 5729 } 5730 break; 5731 } 5732 5733 case CXXMoveConstructor: 5734 case CXXMoveAssignment: { 5735 // Trivial move operations always have non-cv-qualified parameters. 5736 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5737 const RValueReferenceType *RT = 5738 Param0->getType()->getAs<RValueReferenceType>(); 5739 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5740 if (Diagnose) 5741 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5742 << Param0->getSourceRange() << Param0->getType() 5743 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5744 return false; 5745 } 5746 break; 5747 } 5748 5749 case CXXInvalid: 5750 llvm_unreachable("not a special member"); 5751 } 5752 5753 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5754 if (Diagnose) 5755 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5756 diag::note_nontrivial_default_arg) 5757 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5758 return false; 5759 } 5760 if (MD->isVariadic()) { 5761 if (Diagnose) 5762 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5763 return false; 5764 } 5765 5766 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5767 // A copy/move [constructor or assignment operator] is trivial if 5768 // -- the [member] selected to copy/move each direct base class subobject 5769 // is trivial 5770 // 5771 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5772 // A [default constructor or destructor] is trivial if 5773 // -- all the direct base classes have trivial [default constructors or 5774 // destructors] 5775 for (const auto &BI : RD->bases()) 5776 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 5777 ConstArg, CSM, TSK_BaseClass, Diagnose)) 5778 return false; 5779 5780 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5781 // A copy/move [constructor or assignment operator] for a class X is 5782 // trivial if 5783 // -- for each non-static data member of X that is of class type (or array 5784 // thereof), the constructor selected to copy/move that member is 5785 // trivial 5786 // 5787 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5788 // A [default constructor or destructor] is trivial if 5789 // -- for all of the non-static data members of its class that are of class 5790 // type (or array thereof), each such class has a trivial [default 5791 // constructor or destructor] 5792 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5793 return false; 5794 5795 // C++11 [class.dtor]p5: 5796 // A destructor is trivial if [...] 5797 // -- the destructor is not virtual 5798 if (CSM == CXXDestructor && MD->isVirtual()) { 5799 if (Diagnose) 5800 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5801 return false; 5802 } 5803 5804 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5805 // A [special member] for class X is trivial if [...] 5806 // -- class X has no virtual functions and no virtual base classes 5807 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5808 if (!Diagnose) 5809 return false; 5810 5811 if (RD->getNumVBases()) { 5812 // Check for virtual bases. We already know that the corresponding 5813 // member in all bases is trivial, so vbases must all be direct. 5814 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5815 assert(BS.isVirtual()); 5816 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5817 return false; 5818 } 5819 5820 // Must have a virtual method. 5821 for (const auto *MI : RD->methods()) { 5822 if (MI->isVirtual()) { 5823 SourceLocation MLoc = MI->getLocStart(); 5824 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5825 return false; 5826 } 5827 } 5828 5829 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5830 } 5831 5832 // Looks like it's trivial! 5833 return true; 5834 } 5835 5836 /// \brief Data used with FindHiddenVirtualMethod 5837 namespace { 5838 struct FindHiddenVirtualMethodData { 5839 Sema *S; 5840 CXXMethodDecl *Method; 5841 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5842 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5843 }; 5844 } 5845 5846 /// \brief Check whether any most overriden method from MD in Methods 5847 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5848 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5849 if (MD->size_overridden_methods() == 0) 5850 return Methods.count(MD->getCanonicalDecl()); 5851 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5852 E = MD->end_overridden_methods(); 5853 I != E; ++I) 5854 if (CheckMostOverridenMethods(*I, Methods)) 5855 return true; 5856 return false; 5857 } 5858 5859 /// \brief Member lookup function that determines whether a given C++ 5860 /// method overloads virtual methods in a base class without overriding any, 5861 /// to be used with CXXRecordDecl::lookupInBases(). 5862 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5863 CXXBasePath &Path, 5864 void *UserData) { 5865 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5866 5867 FindHiddenVirtualMethodData &Data 5868 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5869 5870 DeclarationName Name = Data.Method->getDeclName(); 5871 assert(Name.getNameKind() == DeclarationName::Identifier); 5872 5873 bool foundSameNameMethod = false; 5874 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5875 for (Path.Decls = BaseRecord->lookup(Name); 5876 !Path.Decls.empty(); 5877 Path.Decls = Path.Decls.slice(1)) { 5878 NamedDecl *D = Path.Decls.front(); 5879 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5880 MD = MD->getCanonicalDecl(); 5881 foundSameNameMethod = true; 5882 // Interested only in hidden virtual methods. 5883 if (!MD->isVirtual()) 5884 continue; 5885 // If the method we are checking overrides a method from its base 5886 // don't warn about the other overloaded methods. 5887 if (!Data.S->IsOverload(Data.Method, MD, false)) 5888 return true; 5889 // Collect the overload only if its hidden. 5890 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5891 overloadedMethods.push_back(MD); 5892 } 5893 } 5894 5895 if (foundSameNameMethod) 5896 Data.OverloadedMethods.append(overloadedMethods.begin(), 5897 overloadedMethods.end()); 5898 return foundSameNameMethod; 5899 } 5900 5901 /// \brief Add the most overriden methods from MD to Methods 5902 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5903 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5904 if (MD->size_overridden_methods() == 0) 5905 Methods.insert(MD->getCanonicalDecl()); 5906 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5907 E = MD->end_overridden_methods(); 5908 I != E; ++I) 5909 AddMostOverridenMethods(*I, Methods); 5910 } 5911 5912 /// \brief Check if a method overloads virtual methods in a base class without 5913 /// overriding any. 5914 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5915 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5916 if (!MD->getDeclName().isIdentifier()) 5917 return; 5918 5919 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5920 /*bool RecordPaths=*/false, 5921 /*bool DetectVirtual=*/false); 5922 FindHiddenVirtualMethodData Data; 5923 Data.Method = MD; 5924 Data.S = this; 5925 5926 // Keep the base methods that were overriden or introduced in the subclass 5927 // by 'using' in a set. A base method not in this set is hidden. 5928 CXXRecordDecl *DC = MD->getParent(); 5929 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5930 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5931 NamedDecl *ND = *I; 5932 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5933 ND = shad->getTargetDecl(); 5934 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5935 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5936 } 5937 5938 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 5939 OverloadedMethods = Data.OverloadedMethods; 5940 } 5941 5942 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 5943 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5944 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 5945 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 5946 PartialDiagnostic PD = PDiag( 5947 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5948 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5949 Diag(overloadedMD->getLocation(), PD); 5950 } 5951 } 5952 5953 /// \brief Diagnose methods which overload virtual methods in a base class 5954 /// without overriding any. 5955 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 5956 if (MD->isInvalidDecl()) 5957 return; 5958 5959 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 5960 return; 5961 5962 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5963 FindHiddenVirtualMethods(MD, OverloadedMethods); 5964 if (!OverloadedMethods.empty()) { 5965 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5966 << MD << (OverloadedMethods.size() > 1); 5967 5968 NoteHiddenVirtualMethods(MD, OverloadedMethods); 5969 } 5970 } 5971 5972 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5973 Decl *TagDecl, 5974 SourceLocation LBrac, 5975 SourceLocation RBrac, 5976 AttributeList *AttrList) { 5977 if (!TagDecl) 5978 return; 5979 5980 AdjustDeclIfTemplate(TagDecl); 5981 5982 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5983 if (l->getKind() != AttributeList::AT_Visibility) 5984 continue; 5985 l->setInvalid(); 5986 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5987 l->getName(); 5988 } 5989 5990 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5991 // strict aliasing violation! 5992 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5993 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5994 5995 CheckCompletedCXXClass( 5996 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5997 } 5998 5999 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6000 /// special functions, such as the default constructor, copy 6001 /// constructor, or destructor, to the given C++ class (C++ 6002 /// [special]p1). This routine can only be executed just before the 6003 /// definition of the class is complete. 6004 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6005 if (!ClassDecl->hasUserDeclaredConstructor()) 6006 ++ASTContext::NumImplicitDefaultConstructors; 6007 6008 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6009 ++ASTContext::NumImplicitCopyConstructors; 6010 6011 // If the properties or semantics of the copy constructor couldn't be 6012 // determined while the class was being declared, force a declaration 6013 // of it now. 6014 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6015 DeclareImplicitCopyConstructor(ClassDecl); 6016 } 6017 6018 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6019 ++ASTContext::NumImplicitMoveConstructors; 6020 6021 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6022 DeclareImplicitMoveConstructor(ClassDecl); 6023 } 6024 6025 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6026 ++ASTContext::NumImplicitCopyAssignmentOperators; 6027 6028 // If we have a dynamic class, then the copy assignment operator may be 6029 // virtual, so we have to declare it immediately. This ensures that, e.g., 6030 // it shows up in the right place in the vtable and that we diagnose 6031 // problems with the implicit exception specification. 6032 if (ClassDecl->isDynamicClass() || 6033 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6034 DeclareImplicitCopyAssignment(ClassDecl); 6035 } 6036 6037 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6038 ++ASTContext::NumImplicitMoveAssignmentOperators; 6039 6040 // Likewise for the move assignment operator. 6041 if (ClassDecl->isDynamicClass() || 6042 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6043 DeclareImplicitMoveAssignment(ClassDecl); 6044 } 6045 6046 if (!ClassDecl->hasUserDeclaredDestructor()) { 6047 ++ASTContext::NumImplicitDestructors; 6048 6049 // If we have a dynamic class, then the destructor may be virtual, so we 6050 // have to declare the destructor immediately. This ensures that, e.g., it 6051 // shows up in the right place in the vtable and that we diagnose problems 6052 // with the implicit exception specification. 6053 if (ClassDecl->isDynamicClass() || 6054 ClassDecl->needsOverloadResolutionForDestructor()) 6055 DeclareImplicitDestructor(ClassDecl); 6056 } 6057 } 6058 6059 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6060 if (!D) 6061 return 0; 6062 6063 // The order of template parameters is not important here. All names 6064 // get added to the same scope. 6065 SmallVector<TemplateParameterList *, 4> ParameterLists; 6066 6067 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6068 D = TD->getTemplatedDecl(); 6069 6070 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6071 ParameterLists.push_back(PSD->getTemplateParameters()); 6072 6073 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6074 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6075 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6076 6077 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6078 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6079 ParameterLists.push_back(FTD->getTemplateParameters()); 6080 } 6081 } 6082 6083 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6084 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6085 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6086 6087 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6088 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6089 ParameterLists.push_back(CTD->getTemplateParameters()); 6090 } 6091 } 6092 6093 unsigned Count = 0; 6094 for (TemplateParameterList *Params : ParameterLists) { 6095 if (Params->size() > 0) 6096 // Ignore explicit specializations; they don't contribute to the template 6097 // depth. 6098 ++Count; 6099 for (NamedDecl *Param : *Params) { 6100 if (Param->getDeclName()) { 6101 S->AddDecl(Param); 6102 IdResolver.AddDecl(Param); 6103 } 6104 } 6105 } 6106 6107 return Count; 6108 } 6109 6110 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6111 if (!RecordD) return; 6112 AdjustDeclIfTemplate(RecordD); 6113 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6114 PushDeclContext(S, Record); 6115 } 6116 6117 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6118 if (!RecordD) return; 6119 PopDeclContext(); 6120 } 6121 6122 /// This is used to implement the constant expression evaluation part of the 6123 /// attribute enable_if extension. There is nothing in standard C++ which would 6124 /// require reentering parameters. 6125 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6126 if (!Param) 6127 return; 6128 6129 S->AddDecl(Param); 6130 if (Param->getDeclName()) 6131 IdResolver.AddDecl(Param); 6132 } 6133 6134 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6135 /// parsing a top-level (non-nested) C++ class, and we are now 6136 /// parsing those parts of the given Method declaration that could 6137 /// not be parsed earlier (C++ [class.mem]p2), such as default 6138 /// arguments. This action should enter the scope of the given 6139 /// Method declaration as if we had just parsed the qualified method 6140 /// name. However, it should not bring the parameters into scope; 6141 /// that will be performed by ActOnDelayedCXXMethodParameter. 6142 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6143 } 6144 6145 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6146 /// C++ method declaration. We're (re-)introducing the given 6147 /// function parameter into scope for use in parsing later parts of 6148 /// the method declaration. For example, we could see an 6149 /// ActOnParamDefaultArgument event for this parameter. 6150 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6151 if (!ParamD) 6152 return; 6153 6154 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6155 6156 // If this parameter has an unparsed default argument, clear it out 6157 // to make way for the parsed default argument. 6158 if (Param->hasUnparsedDefaultArg()) 6159 Param->setDefaultArg(nullptr); 6160 6161 S->AddDecl(Param); 6162 if (Param->getDeclName()) 6163 IdResolver.AddDecl(Param); 6164 } 6165 6166 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6167 /// processing the delayed method declaration for Method. The method 6168 /// declaration is now considered finished. There may be a separate 6169 /// ActOnStartOfFunctionDef action later (not necessarily 6170 /// immediately!) for this method, if it was also defined inside the 6171 /// class body. 6172 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6173 if (!MethodD) 6174 return; 6175 6176 AdjustDeclIfTemplate(MethodD); 6177 6178 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6179 6180 // Now that we have our default arguments, check the constructor 6181 // again. It could produce additional diagnostics or affect whether 6182 // the class has implicitly-declared destructors, among other 6183 // things. 6184 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6185 CheckConstructor(Constructor); 6186 6187 // Check the default arguments, which we may have added. 6188 if (!Method->isInvalidDecl()) 6189 CheckCXXDefaultArguments(Method); 6190 } 6191 6192 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6193 /// the well-formedness of the constructor declarator @p D with type @p 6194 /// R. If there are any errors in the declarator, this routine will 6195 /// emit diagnostics and set the invalid bit to true. In any case, the type 6196 /// will be updated to reflect a well-formed type for the constructor and 6197 /// returned. 6198 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6199 StorageClass &SC) { 6200 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6201 6202 // C++ [class.ctor]p3: 6203 // A constructor shall not be virtual (10.3) or static (9.4). A 6204 // constructor can be invoked for a const, volatile or const 6205 // volatile object. A constructor shall not be declared const, 6206 // volatile, or const volatile (9.3.2). 6207 if (isVirtual) { 6208 if (!D.isInvalidType()) 6209 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6210 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6211 << SourceRange(D.getIdentifierLoc()); 6212 D.setInvalidType(); 6213 } 6214 if (SC == SC_Static) { 6215 if (!D.isInvalidType()) 6216 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6217 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6218 << SourceRange(D.getIdentifierLoc()); 6219 D.setInvalidType(); 6220 SC = SC_None; 6221 } 6222 6223 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6224 if (FTI.TypeQuals != 0) { 6225 if (FTI.TypeQuals & Qualifiers::Const) 6226 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6227 << "const" << SourceRange(D.getIdentifierLoc()); 6228 if (FTI.TypeQuals & Qualifiers::Volatile) 6229 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6230 << "volatile" << SourceRange(D.getIdentifierLoc()); 6231 if (FTI.TypeQuals & Qualifiers::Restrict) 6232 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6233 << "restrict" << SourceRange(D.getIdentifierLoc()); 6234 D.setInvalidType(); 6235 } 6236 6237 // C++0x [class.ctor]p4: 6238 // A constructor shall not be declared with a ref-qualifier. 6239 if (FTI.hasRefQualifier()) { 6240 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6241 << FTI.RefQualifierIsLValueRef 6242 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6243 D.setInvalidType(); 6244 } 6245 6246 // Rebuild the function type "R" without any type qualifiers (in 6247 // case any of the errors above fired) and with "void" as the 6248 // return type, since constructors don't have return types. 6249 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6250 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6251 return R; 6252 6253 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6254 EPI.TypeQuals = 0; 6255 EPI.RefQualifier = RQ_None; 6256 6257 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6258 } 6259 6260 /// CheckConstructor - Checks a fully-formed constructor for 6261 /// well-formedness, issuing any diagnostics required. Returns true if 6262 /// the constructor declarator is invalid. 6263 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6264 CXXRecordDecl *ClassDecl 6265 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6266 if (!ClassDecl) 6267 return Constructor->setInvalidDecl(); 6268 6269 // C++ [class.copy]p3: 6270 // A declaration of a constructor for a class X is ill-formed if 6271 // its first parameter is of type (optionally cv-qualified) X and 6272 // either there are no other parameters or else all other 6273 // parameters have default arguments. 6274 if (!Constructor->isInvalidDecl() && 6275 ((Constructor->getNumParams() == 1) || 6276 (Constructor->getNumParams() > 1 && 6277 Constructor->getParamDecl(1)->hasDefaultArg())) && 6278 Constructor->getTemplateSpecializationKind() 6279 != TSK_ImplicitInstantiation) { 6280 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6281 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6282 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6283 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6284 const char *ConstRef 6285 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6286 : " const &"; 6287 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6288 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6289 6290 // FIXME: Rather that making the constructor invalid, we should endeavor 6291 // to fix the type. 6292 Constructor->setInvalidDecl(); 6293 } 6294 } 6295 } 6296 6297 /// CheckDestructor - Checks a fully-formed destructor definition for 6298 /// well-formedness, issuing any diagnostics required. Returns true 6299 /// on error. 6300 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6301 CXXRecordDecl *RD = Destructor->getParent(); 6302 6303 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6304 SourceLocation Loc; 6305 6306 if (!Destructor->isImplicit()) 6307 Loc = Destructor->getLocation(); 6308 else 6309 Loc = RD->getLocation(); 6310 6311 // If we have a virtual destructor, look up the deallocation function 6312 FunctionDecl *OperatorDelete = nullptr; 6313 DeclarationName Name = 6314 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6315 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6316 return true; 6317 // If there's no class-specific operator delete, look up the global 6318 // non-array delete. 6319 if (!OperatorDelete) 6320 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6321 6322 MarkFunctionReferenced(Loc, OperatorDelete); 6323 6324 Destructor->setOperatorDelete(OperatorDelete); 6325 } 6326 6327 return false; 6328 } 6329 6330 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6331 /// the well-formednes of the destructor declarator @p D with type @p 6332 /// R. If there are any errors in the declarator, this routine will 6333 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6334 /// will be updated to reflect a well-formed type for the destructor and 6335 /// returned. 6336 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6337 StorageClass& SC) { 6338 // C++ [class.dtor]p1: 6339 // [...] A typedef-name that names a class is a class-name 6340 // (7.1.3); however, a typedef-name that names a class shall not 6341 // be used as the identifier in the declarator for a destructor 6342 // declaration. 6343 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6344 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6345 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6346 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6347 else if (const TemplateSpecializationType *TST = 6348 DeclaratorType->getAs<TemplateSpecializationType>()) 6349 if (TST->isTypeAlias()) 6350 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6351 << DeclaratorType << 1; 6352 6353 // C++ [class.dtor]p2: 6354 // A destructor is used to destroy objects of its class type. A 6355 // destructor takes no parameters, and no return type can be 6356 // specified for it (not even void). The address of a destructor 6357 // shall not be taken. A destructor shall not be static. A 6358 // destructor can be invoked for a const, volatile or const 6359 // volatile object. A destructor shall not be declared const, 6360 // volatile or const volatile (9.3.2). 6361 if (SC == SC_Static) { 6362 if (!D.isInvalidType()) 6363 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6364 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6365 << SourceRange(D.getIdentifierLoc()) 6366 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6367 6368 SC = SC_None; 6369 } 6370 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6371 // Destructors don't have return types, but the parser will 6372 // happily parse something like: 6373 // 6374 // class X { 6375 // float ~X(); 6376 // }; 6377 // 6378 // The return type will be eliminated later. 6379 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6380 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6381 << SourceRange(D.getIdentifierLoc()); 6382 } 6383 6384 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6385 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6386 if (FTI.TypeQuals & Qualifiers::Const) 6387 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6388 << "const" << SourceRange(D.getIdentifierLoc()); 6389 if (FTI.TypeQuals & Qualifiers::Volatile) 6390 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6391 << "volatile" << SourceRange(D.getIdentifierLoc()); 6392 if (FTI.TypeQuals & Qualifiers::Restrict) 6393 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6394 << "restrict" << SourceRange(D.getIdentifierLoc()); 6395 D.setInvalidType(); 6396 } 6397 6398 // C++0x [class.dtor]p2: 6399 // A destructor shall not be declared with a ref-qualifier. 6400 if (FTI.hasRefQualifier()) { 6401 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6402 << FTI.RefQualifierIsLValueRef 6403 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6404 D.setInvalidType(); 6405 } 6406 6407 // Make sure we don't have any parameters. 6408 if (FTIHasNonVoidParameters(FTI)) { 6409 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6410 6411 // Delete the parameters. 6412 FTI.freeParams(); 6413 D.setInvalidType(); 6414 } 6415 6416 // Make sure the destructor isn't variadic. 6417 if (FTI.isVariadic) { 6418 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6419 D.setInvalidType(); 6420 } 6421 6422 // Rebuild the function type "R" without any type qualifiers or 6423 // parameters (in case any of the errors above fired) and with 6424 // "void" as the return type, since destructors don't have return 6425 // types. 6426 if (!D.isInvalidType()) 6427 return R; 6428 6429 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6430 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6431 EPI.Variadic = false; 6432 EPI.TypeQuals = 0; 6433 EPI.RefQualifier = RQ_None; 6434 return Context.getFunctionType(Context.VoidTy, None, EPI); 6435 } 6436 6437 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6438 /// well-formednes of the conversion function declarator @p D with 6439 /// type @p R. If there are any errors in the declarator, this routine 6440 /// will emit diagnostics and return true. Otherwise, it will return 6441 /// false. Either way, the type @p R will be updated to reflect a 6442 /// well-formed type for the conversion operator. 6443 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6444 StorageClass& SC) { 6445 // C++ [class.conv.fct]p1: 6446 // Neither parameter types nor return type can be specified. The 6447 // type of a conversion function (8.3.5) is "function taking no 6448 // parameter returning conversion-type-id." 6449 if (SC == SC_Static) { 6450 if (!D.isInvalidType()) 6451 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6452 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6453 << D.getName().getSourceRange(); 6454 D.setInvalidType(); 6455 SC = SC_None; 6456 } 6457 6458 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6459 6460 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6461 // Conversion functions don't have return types, but the parser will 6462 // happily parse something like: 6463 // 6464 // class X { 6465 // float operator bool(); 6466 // }; 6467 // 6468 // The return type will be changed later anyway. 6469 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6470 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6471 << SourceRange(D.getIdentifierLoc()); 6472 D.setInvalidType(); 6473 } 6474 6475 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6476 6477 // Make sure we don't have any parameters. 6478 if (Proto->getNumParams() > 0) { 6479 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6480 6481 // Delete the parameters. 6482 D.getFunctionTypeInfo().freeParams(); 6483 D.setInvalidType(); 6484 } else if (Proto->isVariadic()) { 6485 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6486 D.setInvalidType(); 6487 } 6488 6489 // Diagnose "&operator bool()" and other such nonsense. This 6490 // is actually a gcc extension which we don't support. 6491 if (Proto->getReturnType() != ConvType) { 6492 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6493 << Proto->getReturnType(); 6494 D.setInvalidType(); 6495 ConvType = Proto->getReturnType(); 6496 } 6497 6498 // C++ [class.conv.fct]p4: 6499 // The conversion-type-id shall not represent a function type nor 6500 // an array type. 6501 if (ConvType->isArrayType()) { 6502 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6503 ConvType = Context.getPointerType(ConvType); 6504 D.setInvalidType(); 6505 } else if (ConvType->isFunctionType()) { 6506 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6507 ConvType = Context.getPointerType(ConvType); 6508 D.setInvalidType(); 6509 } 6510 6511 // Rebuild the function type "R" without any parameters (in case any 6512 // of the errors above fired) and with the conversion type as the 6513 // return type. 6514 if (D.isInvalidType()) 6515 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6516 6517 // C++0x explicit conversion operators. 6518 if (D.getDeclSpec().isExplicitSpecified()) 6519 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6520 getLangOpts().CPlusPlus11 ? 6521 diag::warn_cxx98_compat_explicit_conversion_functions : 6522 diag::ext_explicit_conversion_functions) 6523 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6524 } 6525 6526 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6527 /// the declaration of the given C++ conversion function. This routine 6528 /// is responsible for recording the conversion function in the C++ 6529 /// class, if possible. 6530 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6531 assert(Conversion && "Expected to receive a conversion function declaration"); 6532 6533 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6534 6535 // Make sure we aren't redeclaring the conversion function. 6536 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6537 6538 // C++ [class.conv.fct]p1: 6539 // [...] A conversion function is never used to convert a 6540 // (possibly cv-qualified) object to the (possibly cv-qualified) 6541 // same object type (or a reference to it), to a (possibly 6542 // cv-qualified) base class of that type (or a reference to it), 6543 // or to (possibly cv-qualified) void. 6544 // FIXME: Suppress this warning if the conversion function ends up being a 6545 // virtual function that overrides a virtual function in a base class. 6546 QualType ClassType 6547 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6548 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6549 ConvType = ConvTypeRef->getPointeeType(); 6550 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6551 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6552 /* Suppress diagnostics for instantiations. */; 6553 else if (ConvType->isRecordType()) { 6554 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6555 if (ConvType == ClassType) 6556 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6557 << ClassType; 6558 else if (IsDerivedFrom(ClassType, ConvType)) 6559 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6560 << ClassType << ConvType; 6561 } else if (ConvType->isVoidType()) { 6562 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6563 << ClassType << ConvType; 6564 } 6565 6566 if (FunctionTemplateDecl *ConversionTemplate 6567 = Conversion->getDescribedFunctionTemplate()) 6568 return ConversionTemplate; 6569 6570 return Conversion; 6571 } 6572 6573 //===----------------------------------------------------------------------===// 6574 // Namespace Handling 6575 //===----------------------------------------------------------------------===// 6576 6577 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6578 /// reopened. 6579 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6580 SourceLocation Loc, 6581 IdentifierInfo *II, bool *IsInline, 6582 NamespaceDecl *PrevNS) { 6583 assert(*IsInline != PrevNS->isInline()); 6584 6585 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6586 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6587 // inline namespaces, with the intention of bringing names into namespace std. 6588 // 6589 // We support this just well enough to get that case working; this is not 6590 // sufficient to support reopening namespaces as inline in general. 6591 if (*IsInline && II && II->getName().startswith("__atomic") && 6592 S.getSourceManager().isInSystemHeader(Loc)) { 6593 // Mark all prior declarations of the namespace as inline. 6594 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6595 NS = NS->getPreviousDecl()) 6596 NS->setInline(*IsInline); 6597 // Patch up the lookup table for the containing namespace. This isn't really 6598 // correct, but it's good enough for this particular case. 6599 for (auto *I : PrevNS->decls()) 6600 if (auto *ND = dyn_cast<NamedDecl>(I)) 6601 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6602 return; 6603 } 6604 6605 if (PrevNS->isInline()) 6606 // The user probably just forgot the 'inline', so suggest that it 6607 // be added back. 6608 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6609 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6610 else 6611 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 6612 6613 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6614 *IsInline = PrevNS->isInline(); 6615 } 6616 6617 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6618 /// definition. 6619 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6620 SourceLocation InlineLoc, 6621 SourceLocation NamespaceLoc, 6622 SourceLocation IdentLoc, 6623 IdentifierInfo *II, 6624 SourceLocation LBrace, 6625 AttributeList *AttrList) { 6626 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6627 // For anonymous namespace, take the location of the left brace. 6628 SourceLocation Loc = II ? IdentLoc : LBrace; 6629 bool IsInline = InlineLoc.isValid(); 6630 bool IsInvalid = false; 6631 bool IsStd = false; 6632 bool AddToKnown = false; 6633 Scope *DeclRegionScope = NamespcScope->getParent(); 6634 6635 NamespaceDecl *PrevNS = nullptr; 6636 if (II) { 6637 // C++ [namespace.def]p2: 6638 // The identifier in an original-namespace-definition shall not 6639 // have been previously defined in the declarative region in 6640 // which the original-namespace-definition appears. The 6641 // identifier in an original-namespace-definition is the name of 6642 // the namespace. Subsequently in that declarative region, it is 6643 // treated as an original-namespace-name. 6644 // 6645 // Since namespace names are unique in their scope, and we don't 6646 // look through using directives, just look for any ordinary names. 6647 6648 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6649 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6650 Decl::IDNS_Namespace; 6651 NamedDecl *PrevDecl = nullptr; 6652 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6653 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6654 ++I) { 6655 if ((*I)->getIdentifierNamespace() & IDNS) { 6656 PrevDecl = *I; 6657 break; 6658 } 6659 } 6660 6661 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6662 6663 if (PrevNS) { 6664 // This is an extended namespace definition. 6665 if (IsInline != PrevNS->isInline()) 6666 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6667 &IsInline, PrevNS); 6668 } else if (PrevDecl) { 6669 // This is an invalid name redefinition. 6670 Diag(Loc, diag::err_redefinition_different_kind) 6671 << II; 6672 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6673 IsInvalid = true; 6674 // Continue on to push Namespc as current DeclContext and return it. 6675 } else if (II->isStr("std") && 6676 CurContext->getRedeclContext()->isTranslationUnit()) { 6677 // This is the first "real" definition of the namespace "std", so update 6678 // our cache of the "std" namespace to point at this definition. 6679 PrevNS = getStdNamespace(); 6680 IsStd = true; 6681 AddToKnown = !IsInline; 6682 } else { 6683 // We've seen this namespace for the first time. 6684 AddToKnown = !IsInline; 6685 } 6686 } else { 6687 // Anonymous namespaces. 6688 6689 // Determine whether the parent already has an anonymous namespace. 6690 DeclContext *Parent = CurContext->getRedeclContext(); 6691 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6692 PrevNS = TU->getAnonymousNamespace(); 6693 } else { 6694 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6695 PrevNS = ND->getAnonymousNamespace(); 6696 } 6697 6698 if (PrevNS && IsInline != PrevNS->isInline()) 6699 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6700 &IsInline, PrevNS); 6701 } 6702 6703 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6704 StartLoc, Loc, II, PrevNS); 6705 if (IsInvalid) 6706 Namespc->setInvalidDecl(); 6707 6708 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6709 6710 // FIXME: Should we be merging attributes? 6711 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6712 PushNamespaceVisibilityAttr(Attr, Loc); 6713 6714 if (IsStd) 6715 StdNamespace = Namespc; 6716 if (AddToKnown) 6717 KnownNamespaces[Namespc] = false; 6718 6719 if (II) { 6720 PushOnScopeChains(Namespc, DeclRegionScope); 6721 } else { 6722 // Link the anonymous namespace into its parent. 6723 DeclContext *Parent = CurContext->getRedeclContext(); 6724 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6725 TU->setAnonymousNamespace(Namespc); 6726 } else { 6727 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6728 } 6729 6730 CurContext->addDecl(Namespc); 6731 6732 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6733 // behaves as if it were replaced by 6734 // namespace unique { /* empty body */ } 6735 // using namespace unique; 6736 // namespace unique { namespace-body } 6737 // where all occurrences of 'unique' in a translation unit are 6738 // replaced by the same identifier and this identifier differs 6739 // from all other identifiers in the entire program. 6740 6741 // We just create the namespace with an empty name and then add an 6742 // implicit using declaration, just like the standard suggests. 6743 // 6744 // CodeGen enforces the "universally unique" aspect by giving all 6745 // declarations semantically contained within an anonymous 6746 // namespace internal linkage. 6747 6748 if (!PrevNS) { 6749 UsingDirectiveDecl* UD 6750 = UsingDirectiveDecl::Create(Context, Parent, 6751 /* 'using' */ LBrace, 6752 /* 'namespace' */ SourceLocation(), 6753 /* qualifier */ NestedNameSpecifierLoc(), 6754 /* identifier */ SourceLocation(), 6755 Namespc, 6756 /* Ancestor */ Parent); 6757 UD->setImplicit(); 6758 Parent->addDecl(UD); 6759 } 6760 } 6761 6762 ActOnDocumentableDecl(Namespc); 6763 6764 // Although we could have an invalid decl (i.e. the namespace name is a 6765 // redefinition), push it as current DeclContext and try to continue parsing. 6766 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6767 // for the namespace has the declarations that showed up in that particular 6768 // namespace definition. 6769 PushDeclContext(NamespcScope, Namespc); 6770 return Namespc; 6771 } 6772 6773 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6774 /// is a namespace alias, returns the namespace it points to. 6775 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6776 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6777 return AD->getNamespace(); 6778 return dyn_cast_or_null<NamespaceDecl>(D); 6779 } 6780 6781 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6782 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6783 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6784 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6785 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6786 Namespc->setRBraceLoc(RBrace); 6787 PopDeclContext(); 6788 if (Namespc->hasAttr<VisibilityAttr>()) 6789 PopPragmaVisibility(true, RBrace); 6790 } 6791 6792 CXXRecordDecl *Sema::getStdBadAlloc() const { 6793 return cast_or_null<CXXRecordDecl>( 6794 StdBadAlloc.get(Context.getExternalSource())); 6795 } 6796 6797 NamespaceDecl *Sema::getStdNamespace() const { 6798 return cast_or_null<NamespaceDecl>( 6799 StdNamespace.get(Context.getExternalSource())); 6800 } 6801 6802 /// \brief Retrieve the special "std" namespace, which may require us to 6803 /// implicitly define the namespace. 6804 NamespaceDecl *Sema::getOrCreateStdNamespace() { 6805 if (!StdNamespace) { 6806 // The "std" namespace has not yet been defined, so build one implicitly. 6807 StdNamespace = NamespaceDecl::Create(Context, 6808 Context.getTranslationUnitDecl(), 6809 /*Inline=*/false, 6810 SourceLocation(), SourceLocation(), 6811 &PP.getIdentifierTable().get("std"), 6812 /*PrevDecl=*/nullptr); 6813 getStdNamespace()->setImplicit(true); 6814 } 6815 6816 return getStdNamespace(); 6817 } 6818 6819 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6820 assert(getLangOpts().CPlusPlus && 6821 "Looking for std::initializer_list outside of C++."); 6822 6823 // We're looking for implicit instantiations of 6824 // template <typename E> class std::initializer_list. 6825 6826 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6827 return false; 6828 6829 ClassTemplateDecl *Template = nullptr; 6830 const TemplateArgument *Arguments = nullptr; 6831 6832 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6833 6834 ClassTemplateSpecializationDecl *Specialization = 6835 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6836 if (!Specialization) 6837 return false; 6838 6839 Template = Specialization->getSpecializedTemplate(); 6840 Arguments = Specialization->getTemplateArgs().data(); 6841 } else if (const TemplateSpecializationType *TST = 6842 Ty->getAs<TemplateSpecializationType>()) { 6843 Template = dyn_cast_or_null<ClassTemplateDecl>( 6844 TST->getTemplateName().getAsTemplateDecl()); 6845 Arguments = TST->getArgs(); 6846 } 6847 if (!Template) 6848 return false; 6849 6850 if (!StdInitializerList) { 6851 // Haven't recognized std::initializer_list yet, maybe this is it. 6852 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6853 if (TemplateClass->getIdentifier() != 6854 &PP.getIdentifierTable().get("initializer_list") || 6855 !getStdNamespace()->InEnclosingNamespaceSetOf( 6856 TemplateClass->getDeclContext())) 6857 return false; 6858 // This is a template called std::initializer_list, but is it the right 6859 // template? 6860 TemplateParameterList *Params = Template->getTemplateParameters(); 6861 if (Params->getMinRequiredArguments() != 1) 6862 return false; 6863 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6864 return false; 6865 6866 // It's the right template. 6867 StdInitializerList = Template; 6868 } 6869 6870 if (Template != StdInitializerList) 6871 return false; 6872 6873 // This is an instance of std::initializer_list. Find the argument type. 6874 if (Element) 6875 *Element = Arguments[0].getAsType(); 6876 return true; 6877 } 6878 6879 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6880 NamespaceDecl *Std = S.getStdNamespace(); 6881 if (!Std) { 6882 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6883 return nullptr; 6884 } 6885 6886 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6887 Loc, Sema::LookupOrdinaryName); 6888 if (!S.LookupQualifiedName(Result, Std)) { 6889 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6890 return nullptr; 6891 } 6892 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6893 if (!Template) { 6894 Result.suppressDiagnostics(); 6895 // We found something weird. Complain about the first thing we found. 6896 NamedDecl *Found = *Result.begin(); 6897 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6898 return nullptr; 6899 } 6900 6901 // We found some template called std::initializer_list. Now verify that it's 6902 // correct. 6903 TemplateParameterList *Params = Template->getTemplateParameters(); 6904 if (Params->getMinRequiredArguments() != 1 || 6905 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6906 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6907 return nullptr; 6908 } 6909 6910 return Template; 6911 } 6912 6913 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6914 if (!StdInitializerList) { 6915 StdInitializerList = LookupStdInitializerList(*this, Loc); 6916 if (!StdInitializerList) 6917 return QualType(); 6918 } 6919 6920 TemplateArgumentListInfo Args(Loc, Loc); 6921 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6922 Context.getTrivialTypeSourceInfo(Element, 6923 Loc))); 6924 return Context.getCanonicalType( 6925 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6926 } 6927 6928 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6929 // C++ [dcl.init.list]p2: 6930 // A constructor is an initializer-list constructor if its first parameter 6931 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6932 // std::initializer_list<E> for some type E, and either there are no other 6933 // parameters or else all other parameters have default arguments. 6934 if (Ctor->getNumParams() < 1 || 6935 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6936 return false; 6937 6938 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6939 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6940 ArgType = RT->getPointeeType().getUnqualifiedType(); 6941 6942 return isStdInitializerList(ArgType, nullptr); 6943 } 6944 6945 /// \brief Determine whether a using statement is in a context where it will be 6946 /// apply in all contexts. 6947 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6948 switch (CurContext->getDeclKind()) { 6949 case Decl::TranslationUnit: 6950 return true; 6951 case Decl::LinkageSpec: 6952 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6953 default: 6954 return false; 6955 } 6956 } 6957 6958 namespace { 6959 6960 // Callback to only accept typo corrections that are namespaces. 6961 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6962 public: 6963 bool ValidateCandidate(const TypoCorrection &candidate) override { 6964 if (NamedDecl *ND = candidate.getCorrectionDecl()) 6965 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6966 return false; 6967 } 6968 }; 6969 6970 } 6971 6972 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6973 CXXScopeSpec &SS, 6974 SourceLocation IdentLoc, 6975 IdentifierInfo *Ident) { 6976 NamespaceValidatorCCC Validator; 6977 R.clear(); 6978 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6979 R.getLookupKind(), Sc, &SS, 6980 Validator, 6981 Sema::CTK_ErrorRecovery)) { 6982 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 6983 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6984 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 6985 Ident->getName().equals(CorrectedStr); 6986 S.diagnoseTypo(Corrected, 6987 S.PDiag(diag::err_using_directive_member_suggest) 6988 << Ident << DC << DroppedSpecifier << SS.getRange(), 6989 S.PDiag(diag::note_namespace_defined_here)); 6990 } else { 6991 S.diagnoseTypo(Corrected, 6992 S.PDiag(diag::err_using_directive_suggest) << Ident, 6993 S.PDiag(diag::note_namespace_defined_here)); 6994 } 6995 R.addDecl(Corrected.getCorrectionDecl()); 6996 return true; 6997 } 6998 return false; 6999 } 7000 7001 Decl *Sema::ActOnUsingDirective(Scope *S, 7002 SourceLocation UsingLoc, 7003 SourceLocation NamespcLoc, 7004 CXXScopeSpec &SS, 7005 SourceLocation IdentLoc, 7006 IdentifierInfo *NamespcName, 7007 AttributeList *AttrList) { 7008 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7009 assert(NamespcName && "Invalid NamespcName."); 7010 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7011 7012 // This can only happen along a recovery path. 7013 while (S->getFlags() & Scope::TemplateParamScope) 7014 S = S->getParent(); 7015 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7016 7017 UsingDirectiveDecl *UDir = nullptr; 7018 NestedNameSpecifier *Qualifier = nullptr; 7019 if (SS.isSet()) 7020 Qualifier = SS.getScopeRep(); 7021 7022 // Lookup namespace name. 7023 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7024 LookupParsedName(R, S, &SS); 7025 if (R.isAmbiguous()) 7026 return nullptr; 7027 7028 if (R.empty()) { 7029 R.clear(); 7030 // Allow "using namespace std;" or "using namespace ::std;" even if 7031 // "std" hasn't been defined yet, for GCC compatibility. 7032 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7033 NamespcName->isStr("std")) { 7034 Diag(IdentLoc, diag::ext_using_undefined_std); 7035 R.addDecl(getOrCreateStdNamespace()); 7036 R.resolveKind(); 7037 } 7038 // Otherwise, attempt typo correction. 7039 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7040 } 7041 7042 if (!R.empty()) { 7043 NamedDecl *Named = R.getFoundDecl(); 7044 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7045 && "expected namespace decl"); 7046 // C++ [namespace.udir]p1: 7047 // A using-directive specifies that the names in the nominated 7048 // namespace can be used in the scope in which the 7049 // using-directive appears after the using-directive. During 7050 // unqualified name lookup (3.4.1), the names appear as if they 7051 // were declared in the nearest enclosing namespace which 7052 // contains both the using-directive and the nominated 7053 // namespace. [Note: in this context, "contains" means "contains 7054 // directly or indirectly". ] 7055 7056 // Find enclosing context containing both using-directive and 7057 // nominated namespace. 7058 NamespaceDecl *NS = getNamespaceDecl(Named); 7059 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7060 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7061 CommonAncestor = CommonAncestor->getParent(); 7062 7063 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7064 SS.getWithLocInContext(Context), 7065 IdentLoc, Named, CommonAncestor); 7066 7067 if (IsUsingDirectiveInToplevelContext(CurContext) && 7068 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7069 Diag(IdentLoc, diag::warn_using_directive_in_header); 7070 } 7071 7072 PushUsingDirective(S, UDir); 7073 } else { 7074 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7075 } 7076 7077 if (UDir) 7078 ProcessDeclAttributeList(S, UDir, AttrList); 7079 7080 return UDir; 7081 } 7082 7083 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7084 // If the scope has an associated entity and the using directive is at 7085 // namespace or translation unit scope, add the UsingDirectiveDecl into 7086 // its lookup structure so qualified name lookup can find it. 7087 DeclContext *Ctx = S->getEntity(); 7088 if (Ctx && !Ctx->isFunctionOrMethod()) 7089 Ctx->addDecl(UDir); 7090 else 7091 // Otherwise, it is at block scope. The using-directives will affect lookup 7092 // only to the end of the scope. 7093 S->PushUsingDirective(UDir); 7094 } 7095 7096 7097 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7098 AccessSpecifier AS, 7099 bool HasUsingKeyword, 7100 SourceLocation UsingLoc, 7101 CXXScopeSpec &SS, 7102 UnqualifiedId &Name, 7103 AttributeList *AttrList, 7104 bool HasTypenameKeyword, 7105 SourceLocation TypenameLoc) { 7106 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7107 7108 switch (Name.getKind()) { 7109 case UnqualifiedId::IK_ImplicitSelfParam: 7110 case UnqualifiedId::IK_Identifier: 7111 case UnqualifiedId::IK_OperatorFunctionId: 7112 case UnqualifiedId::IK_LiteralOperatorId: 7113 case UnqualifiedId::IK_ConversionFunctionId: 7114 break; 7115 7116 case UnqualifiedId::IK_ConstructorName: 7117 case UnqualifiedId::IK_ConstructorTemplateId: 7118 // C++11 inheriting constructors. 7119 Diag(Name.getLocStart(), 7120 getLangOpts().CPlusPlus11 ? 7121 diag::warn_cxx98_compat_using_decl_constructor : 7122 diag::err_using_decl_constructor) 7123 << SS.getRange(); 7124 7125 if (getLangOpts().CPlusPlus11) break; 7126 7127 return nullptr; 7128 7129 case UnqualifiedId::IK_DestructorName: 7130 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7131 << SS.getRange(); 7132 return nullptr; 7133 7134 case UnqualifiedId::IK_TemplateId: 7135 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7136 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7137 return nullptr; 7138 } 7139 7140 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7141 DeclarationName TargetName = TargetNameInfo.getName(); 7142 if (!TargetName) 7143 return nullptr; 7144 7145 // Warn about access declarations. 7146 if (!HasUsingKeyword) { 7147 Diag(Name.getLocStart(), 7148 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7149 : diag::warn_access_decl_deprecated) 7150 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7151 } 7152 7153 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7154 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7155 return nullptr; 7156 7157 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7158 TargetNameInfo, AttrList, 7159 /* IsInstantiation */ false, 7160 HasTypenameKeyword, TypenameLoc); 7161 if (UD) 7162 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7163 7164 return UD; 7165 } 7166 7167 /// \brief Determine whether a using declaration considers the given 7168 /// declarations as "equivalent", e.g., if they are redeclarations of 7169 /// the same entity or are both typedefs of the same type. 7170 static bool 7171 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7172 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7173 return true; 7174 7175 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7176 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7177 return Context.hasSameType(TD1->getUnderlyingType(), 7178 TD2->getUnderlyingType()); 7179 7180 return false; 7181 } 7182 7183 7184 /// Determines whether to create a using shadow decl for a particular 7185 /// decl, given the set of decls existing prior to this using lookup. 7186 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7187 const LookupResult &Previous, 7188 UsingShadowDecl *&PrevShadow) { 7189 // Diagnose finding a decl which is not from a base class of the 7190 // current class. We do this now because there are cases where this 7191 // function will silently decide not to build a shadow decl, which 7192 // will pre-empt further diagnostics. 7193 // 7194 // We don't need to do this in C++0x because we do the check once on 7195 // the qualifier. 7196 // 7197 // FIXME: diagnose the following if we care enough: 7198 // struct A { int foo; }; 7199 // struct B : A { using A::foo; }; 7200 // template <class T> struct C : A {}; 7201 // template <class T> struct D : C<T> { using B::foo; } // <--- 7202 // This is invalid (during instantiation) in C++03 because B::foo 7203 // resolves to the using decl in B, which is not a base class of D<T>. 7204 // We can't diagnose it immediately because C<T> is an unknown 7205 // specialization. The UsingShadowDecl in D<T> then points directly 7206 // to A::foo, which will look well-formed when we instantiate. 7207 // The right solution is to not collapse the shadow-decl chain. 7208 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7209 DeclContext *OrigDC = Orig->getDeclContext(); 7210 7211 // Handle enums and anonymous structs. 7212 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7213 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7214 while (OrigRec->isAnonymousStructOrUnion()) 7215 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7216 7217 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7218 if (OrigDC == CurContext) { 7219 Diag(Using->getLocation(), 7220 diag::err_using_decl_nested_name_specifier_is_current_class) 7221 << Using->getQualifierLoc().getSourceRange(); 7222 Diag(Orig->getLocation(), diag::note_using_decl_target); 7223 return true; 7224 } 7225 7226 Diag(Using->getQualifierLoc().getBeginLoc(), 7227 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7228 << Using->getQualifier() 7229 << cast<CXXRecordDecl>(CurContext) 7230 << Using->getQualifierLoc().getSourceRange(); 7231 Diag(Orig->getLocation(), diag::note_using_decl_target); 7232 return true; 7233 } 7234 } 7235 7236 if (Previous.empty()) return false; 7237 7238 NamedDecl *Target = Orig; 7239 if (isa<UsingShadowDecl>(Target)) 7240 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7241 7242 // If the target happens to be one of the previous declarations, we 7243 // don't have a conflict. 7244 // 7245 // FIXME: but we might be increasing its access, in which case we 7246 // should redeclare it. 7247 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7248 bool FoundEquivalentDecl = false; 7249 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7250 I != E; ++I) { 7251 NamedDecl *D = (*I)->getUnderlyingDecl(); 7252 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7253 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7254 PrevShadow = Shadow; 7255 FoundEquivalentDecl = true; 7256 } 7257 7258 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7259 } 7260 7261 if (FoundEquivalentDecl) 7262 return false; 7263 7264 if (FunctionDecl *FD = Target->getAsFunction()) { 7265 NamedDecl *OldDecl = nullptr; 7266 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7267 /*IsForUsingDecl*/ true)) { 7268 case Ovl_Overload: 7269 return false; 7270 7271 case Ovl_NonFunction: 7272 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7273 break; 7274 7275 // We found a decl with the exact signature. 7276 case Ovl_Match: 7277 // If we're in a record, we want to hide the target, so we 7278 // return true (without a diagnostic) to tell the caller not to 7279 // build a shadow decl. 7280 if (CurContext->isRecord()) 7281 return true; 7282 7283 // If we're not in a record, this is an error. 7284 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7285 break; 7286 } 7287 7288 Diag(Target->getLocation(), diag::note_using_decl_target); 7289 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7290 return true; 7291 } 7292 7293 // Target is not a function. 7294 7295 if (isa<TagDecl>(Target)) { 7296 // No conflict between a tag and a non-tag. 7297 if (!Tag) return false; 7298 7299 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7300 Diag(Target->getLocation(), diag::note_using_decl_target); 7301 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7302 return true; 7303 } 7304 7305 // No conflict between a tag and a non-tag. 7306 if (!NonTag) return false; 7307 7308 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7309 Diag(Target->getLocation(), diag::note_using_decl_target); 7310 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7311 return true; 7312 } 7313 7314 /// Builds a shadow declaration corresponding to a 'using' declaration. 7315 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7316 UsingDecl *UD, 7317 NamedDecl *Orig, 7318 UsingShadowDecl *PrevDecl) { 7319 7320 // If we resolved to another shadow declaration, just coalesce them. 7321 NamedDecl *Target = Orig; 7322 if (isa<UsingShadowDecl>(Target)) { 7323 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7324 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7325 } 7326 7327 UsingShadowDecl *Shadow 7328 = UsingShadowDecl::Create(Context, CurContext, 7329 UD->getLocation(), UD, Target); 7330 UD->addShadowDecl(Shadow); 7331 7332 Shadow->setAccess(UD->getAccess()); 7333 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7334 Shadow->setInvalidDecl(); 7335 7336 Shadow->setPreviousDecl(PrevDecl); 7337 7338 if (S) 7339 PushOnScopeChains(Shadow, S); 7340 else 7341 CurContext->addDecl(Shadow); 7342 7343 7344 return Shadow; 7345 } 7346 7347 /// Hides a using shadow declaration. This is required by the current 7348 /// using-decl implementation when a resolvable using declaration in a 7349 /// class is followed by a declaration which would hide or override 7350 /// one or more of the using decl's targets; for example: 7351 /// 7352 /// struct Base { void foo(int); }; 7353 /// struct Derived : Base { 7354 /// using Base::foo; 7355 /// void foo(int); 7356 /// }; 7357 /// 7358 /// The governing language is C++03 [namespace.udecl]p12: 7359 /// 7360 /// When a using-declaration brings names from a base class into a 7361 /// derived class scope, member functions in the derived class 7362 /// override and/or hide member functions with the same name and 7363 /// parameter types in a base class (rather than conflicting). 7364 /// 7365 /// There are two ways to implement this: 7366 /// (1) optimistically create shadow decls when they're not hidden 7367 /// by existing declarations, or 7368 /// (2) don't create any shadow decls (or at least don't make them 7369 /// visible) until we've fully parsed/instantiated the class. 7370 /// The problem with (1) is that we might have to retroactively remove 7371 /// a shadow decl, which requires several O(n) operations because the 7372 /// decl structures are (very reasonably) not designed for removal. 7373 /// (2) avoids this but is very fiddly and phase-dependent. 7374 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7375 if (Shadow->getDeclName().getNameKind() == 7376 DeclarationName::CXXConversionFunctionName) 7377 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7378 7379 // Remove it from the DeclContext... 7380 Shadow->getDeclContext()->removeDecl(Shadow); 7381 7382 // ...and the scope, if applicable... 7383 if (S) { 7384 S->RemoveDecl(Shadow); 7385 IdResolver.RemoveDecl(Shadow); 7386 } 7387 7388 // ...and the using decl. 7389 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7390 7391 // TODO: complain somehow if Shadow was used. It shouldn't 7392 // be possible for this to happen, because...? 7393 } 7394 7395 /// Find the base specifier for a base class with the given type. 7396 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7397 QualType DesiredBase, 7398 bool &AnyDependentBases) { 7399 // Check whether the named type is a direct base class. 7400 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7401 for (auto &Base : Derived->bases()) { 7402 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7403 if (CanonicalDesiredBase == BaseType) 7404 return &Base; 7405 if (BaseType->isDependentType()) 7406 AnyDependentBases = true; 7407 } 7408 return nullptr; 7409 } 7410 7411 namespace { 7412 class UsingValidatorCCC : public CorrectionCandidateCallback { 7413 public: 7414 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7415 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7416 : HasTypenameKeyword(HasTypenameKeyword), 7417 IsInstantiation(IsInstantiation), OldNNS(NNS), 7418 RequireMemberOf(RequireMemberOf) {} 7419 7420 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7421 NamedDecl *ND = Candidate.getCorrectionDecl(); 7422 7423 // Keywords are not valid here. 7424 if (!ND || isa<NamespaceDecl>(ND)) 7425 return false; 7426 7427 // Completely unqualified names are invalid for a 'using' declaration. 7428 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7429 return false; 7430 7431 if (RequireMemberOf) { 7432 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7433 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7434 // No-one ever wants a using-declaration to name an injected-class-name 7435 // of a base class, unless they're declaring an inheriting constructor. 7436 ASTContext &Ctx = ND->getASTContext(); 7437 if (!Ctx.getLangOpts().CPlusPlus11) 7438 return false; 7439 QualType FoundType = Ctx.getRecordType(FoundRecord); 7440 7441 // Check that the injected-class-name is named as a member of its own 7442 // type; we don't want to suggest 'using Derived::Base;', since that 7443 // means something else. 7444 NestedNameSpecifier *Specifier = 7445 Candidate.WillReplaceSpecifier() 7446 ? Candidate.getCorrectionSpecifier() 7447 : OldNNS; 7448 if (!Specifier->getAsType() || 7449 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7450 return false; 7451 7452 // Check that this inheriting constructor declaration actually names a 7453 // direct base class of the current class. 7454 bool AnyDependentBases = false; 7455 if (!findDirectBaseWithType(RequireMemberOf, 7456 Ctx.getRecordType(FoundRecord), 7457 AnyDependentBases) && 7458 !AnyDependentBases) 7459 return false; 7460 } else { 7461 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7462 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7463 return false; 7464 7465 // FIXME: Check that the base class member is accessible? 7466 } 7467 } 7468 7469 if (isa<TypeDecl>(ND)) 7470 return HasTypenameKeyword || !IsInstantiation; 7471 7472 return !HasTypenameKeyword; 7473 } 7474 7475 private: 7476 bool HasTypenameKeyword; 7477 bool IsInstantiation; 7478 NestedNameSpecifier *OldNNS; 7479 CXXRecordDecl *RequireMemberOf; 7480 }; 7481 } // end anonymous namespace 7482 7483 /// Builds a using declaration. 7484 /// 7485 /// \param IsInstantiation - Whether this call arises from an 7486 /// instantiation of an unresolved using declaration. We treat 7487 /// the lookup differently for these declarations. 7488 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7489 SourceLocation UsingLoc, 7490 CXXScopeSpec &SS, 7491 DeclarationNameInfo NameInfo, 7492 AttributeList *AttrList, 7493 bool IsInstantiation, 7494 bool HasTypenameKeyword, 7495 SourceLocation TypenameLoc) { 7496 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7497 SourceLocation IdentLoc = NameInfo.getLoc(); 7498 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7499 7500 // FIXME: We ignore attributes for now. 7501 7502 if (SS.isEmpty()) { 7503 Diag(IdentLoc, diag::err_using_requires_qualname); 7504 return nullptr; 7505 } 7506 7507 // Do the redeclaration lookup in the current scope. 7508 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7509 ForRedeclaration); 7510 Previous.setHideTags(false); 7511 if (S) { 7512 LookupName(Previous, S); 7513 7514 // It is really dumb that we have to do this. 7515 LookupResult::Filter F = Previous.makeFilter(); 7516 while (F.hasNext()) { 7517 NamedDecl *D = F.next(); 7518 if (!isDeclInScope(D, CurContext, S)) 7519 F.erase(); 7520 // If we found a local extern declaration that's not ordinarily visible, 7521 // and this declaration is being added to a non-block scope, ignore it. 7522 // We're only checking for scope conflicts here, not also for violations 7523 // of the linkage rules. 7524 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7525 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7526 F.erase(); 7527 } 7528 F.done(); 7529 } else { 7530 assert(IsInstantiation && "no scope in non-instantiation"); 7531 assert(CurContext->isRecord() && "scope not record in instantiation"); 7532 LookupQualifiedName(Previous, CurContext); 7533 } 7534 7535 // Check for invalid redeclarations. 7536 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7537 SS, IdentLoc, Previous)) 7538 return nullptr; 7539 7540 // Check for bad qualifiers. 7541 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7542 return nullptr; 7543 7544 DeclContext *LookupContext = computeDeclContext(SS); 7545 NamedDecl *D; 7546 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7547 if (!LookupContext) { 7548 if (HasTypenameKeyword) { 7549 // FIXME: not all declaration name kinds are legal here 7550 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7551 UsingLoc, TypenameLoc, 7552 QualifierLoc, 7553 IdentLoc, NameInfo.getName()); 7554 } else { 7555 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7556 QualifierLoc, NameInfo); 7557 } 7558 D->setAccess(AS); 7559 CurContext->addDecl(D); 7560 return D; 7561 } 7562 7563 auto Build = [&](bool Invalid) { 7564 UsingDecl *UD = 7565 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 7566 HasTypenameKeyword); 7567 UD->setAccess(AS); 7568 CurContext->addDecl(UD); 7569 UD->setInvalidDecl(Invalid); 7570 return UD; 7571 }; 7572 auto BuildInvalid = [&]{ return Build(true); }; 7573 auto BuildValid = [&]{ return Build(false); }; 7574 7575 if (RequireCompleteDeclContext(SS, LookupContext)) 7576 return BuildInvalid(); 7577 7578 // The normal rules do not apply to inheriting constructor declarations. 7579 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7580 UsingDecl *UD = BuildValid(); 7581 CheckInheritingConstructorUsingDecl(UD); 7582 return UD; 7583 } 7584 7585 // Otherwise, look up the target name. 7586 7587 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7588 7589 // Unlike most lookups, we don't always want to hide tag 7590 // declarations: tag names are visible through the using declaration 7591 // even if hidden by ordinary names, *except* in a dependent context 7592 // where it's important for the sanity of two-phase lookup. 7593 if (!IsInstantiation) 7594 R.setHideTags(false); 7595 7596 // For the purposes of this lookup, we have a base object type 7597 // equal to that of the current context. 7598 if (CurContext->isRecord()) { 7599 R.setBaseObjectType( 7600 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7601 } 7602 7603 LookupQualifiedName(R, LookupContext); 7604 7605 // Try to correct typos if possible. 7606 if (R.empty()) { 7607 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 7608 dyn_cast<CXXRecordDecl>(CurContext)); 7609 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7610 R.getLookupKind(), S, &SS, CCC, 7611 CTK_ErrorRecovery)){ 7612 // We reject any correction for which ND would be NULL. 7613 NamedDecl *ND = Corrected.getCorrectionDecl(); 7614 7615 // We reject candidates where DroppedSpecifier == true, hence the 7616 // literal '0' below. 7617 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7618 << NameInfo.getName() << LookupContext << 0 7619 << SS.getRange()); 7620 7621 // If we corrected to an inheriting constructor, handle it as one. 7622 auto *RD = dyn_cast<CXXRecordDecl>(ND); 7623 if (RD && RD->isInjectedClassName()) { 7624 // Fix up the information we'll use to build the using declaration. 7625 if (Corrected.WillReplaceSpecifier()) { 7626 NestedNameSpecifierLocBuilder Builder; 7627 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 7628 QualifierLoc.getSourceRange()); 7629 QualifierLoc = Builder.getWithLocInContext(Context); 7630 } 7631 7632 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 7633 Context.getCanonicalType(Context.getRecordType(RD)))); 7634 NameInfo.setNamedTypeInfo(nullptr); 7635 7636 // Build it and process it as an inheriting constructor. 7637 UsingDecl *UD = BuildValid(); 7638 CheckInheritingConstructorUsingDecl(UD); 7639 return UD; 7640 } 7641 7642 // FIXME: Pick up all the declarations if we found an overloaded function. 7643 R.setLookupName(Corrected.getCorrection()); 7644 R.addDecl(ND); 7645 } else { 7646 Diag(IdentLoc, diag::err_no_member) 7647 << NameInfo.getName() << LookupContext << SS.getRange(); 7648 return BuildInvalid(); 7649 } 7650 } 7651 7652 if (R.isAmbiguous()) 7653 return BuildInvalid(); 7654 7655 if (HasTypenameKeyword) { 7656 // If we asked for a typename and got a non-type decl, error out. 7657 if (!R.getAsSingle<TypeDecl>()) { 7658 Diag(IdentLoc, diag::err_using_typename_non_type); 7659 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7660 Diag((*I)->getUnderlyingDecl()->getLocation(), 7661 diag::note_using_decl_target); 7662 return BuildInvalid(); 7663 } 7664 } else { 7665 // If we asked for a non-typename and we got a type, error out, 7666 // but only if this is an instantiation of an unresolved using 7667 // decl. Otherwise just silently find the type name. 7668 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7669 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7670 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7671 return BuildInvalid(); 7672 } 7673 } 7674 7675 // C++0x N2914 [namespace.udecl]p6: 7676 // A using-declaration shall not name a namespace. 7677 if (R.getAsSingle<NamespaceDecl>()) { 7678 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7679 << SS.getRange(); 7680 return BuildInvalid(); 7681 } 7682 7683 UsingDecl *UD = BuildValid(); 7684 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7685 UsingShadowDecl *PrevDecl = nullptr; 7686 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7687 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7688 } 7689 7690 return UD; 7691 } 7692 7693 /// Additional checks for a using declaration referring to a constructor name. 7694 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7695 assert(!UD->hasTypename() && "expecting a constructor name"); 7696 7697 const Type *SourceType = UD->getQualifier()->getAsType(); 7698 assert(SourceType && 7699 "Using decl naming constructor doesn't have type in scope spec."); 7700 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7701 7702 // Check whether the named type is a direct base class. 7703 bool AnyDependentBases = false; 7704 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 7705 AnyDependentBases); 7706 if (!Base && !AnyDependentBases) { 7707 Diag(UD->getUsingLoc(), 7708 diag::err_using_decl_constructor_not_in_direct_base) 7709 << UD->getNameInfo().getSourceRange() 7710 << QualType(SourceType, 0) << TargetClass; 7711 UD->setInvalidDecl(); 7712 return true; 7713 } 7714 7715 if (Base) 7716 Base->setInheritConstructors(); 7717 7718 return false; 7719 } 7720 7721 /// Checks that the given using declaration is not an invalid 7722 /// redeclaration. Note that this is checking only for the using decl 7723 /// itself, not for any ill-formedness among the UsingShadowDecls. 7724 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7725 bool HasTypenameKeyword, 7726 const CXXScopeSpec &SS, 7727 SourceLocation NameLoc, 7728 const LookupResult &Prev) { 7729 // C++03 [namespace.udecl]p8: 7730 // C++0x [namespace.udecl]p10: 7731 // A using-declaration is a declaration and can therefore be used 7732 // repeatedly where (and only where) multiple declarations are 7733 // allowed. 7734 // 7735 // That's in non-member contexts. 7736 if (!CurContext->getRedeclContext()->isRecord()) 7737 return false; 7738 7739 NestedNameSpecifier *Qual = SS.getScopeRep(); 7740 7741 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7742 NamedDecl *D = *I; 7743 7744 bool DTypename; 7745 NestedNameSpecifier *DQual; 7746 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7747 DTypename = UD->hasTypename(); 7748 DQual = UD->getQualifier(); 7749 } else if (UnresolvedUsingValueDecl *UD 7750 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7751 DTypename = false; 7752 DQual = UD->getQualifier(); 7753 } else if (UnresolvedUsingTypenameDecl *UD 7754 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7755 DTypename = true; 7756 DQual = UD->getQualifier(); 7757 } else continue; 7758 7759 // using decls differ if one says 'typename' and the other doesn't. 7760 // FIXME: non-dependent using decls? 7761 if (HasTypenameKeyword != DTypename) continue; 7762 7763 // using decls differ if they name different scopes (but note that 7764 // template instantiation can cause this check to trigger when it 7765 // didn't before instantiation). 7766 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7767 Context.getCanonicalNestedNameSpecifier(DQual)) 7768 continue; 7769 7770 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7771 Diag(D->getLocation(), diag::note_using_decl) << 1; 7772 return true; 7773 } 7774 7775 return false; 7776 } 7777 7778 7779 /// Checks that the given nested-name qualifier used in a using decl 7780 /// in the current context is appropriately related to the current 7781 /// scope. If an error is found, diagnoses it and returns true. 7782 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7783 const CXXScopeSpec &SS, 7784 const DeclarationNameInfo &NameInfo, 7785 SourceLocation NameLoc) { 7786 DeclContext *NamedContext = computeDeclContext(SS); 7787 7788 if (!CurContext->isRecord()) { 7789 // C++03 [namespace.udecl]p3: 7790 // C++0x [namespace.udecl]p8: 7791 // A using-declaration for a class member shall be a member-declaration. 7792 7793 // If we weren't able to compute a valid scope, it must be a 7794 // dependent class scope. 7795 if (!NamedContext || NamedContext->isRecord()) { 7796 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 7797 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 7798 RD = nullptr; 7799 7800 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7801 << SS.getRange(); 7802 7803 // If we have a complete, non-dependent source type, try to suggest a 7804 // way to get the same effect. 7805 if (!RD) 7806 return true; 7807 7808 // Find what this using-declaration was referring to. 7809 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7810 R.setHideTags(false); 7811 R.suppressDiagnostics(); 7812 LookupQualifiedName(R, RD); 7813 7814 if (R.getAsSingle<TypeDecl>()) { 7815 if (getLangOpts().CPlusPlus11) { 7816 // Convert 'using X::Y;' to 'using Y = X::Y;'. 7817 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 7818 << 0 // alias declaration 7819 << FixItHint::CreateInsertion(SS.getBeginLoc(), 7820 NameInfo.getName().getAsString() + 7821 " = "); 7822 } else { 7823 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 7824 SourceLocation InsertLoc = 7825 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 7826 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 7827 << 1 // typedef declaration 7828 << FixItHint::CreateReplacement(UsingLoc, "typedef") 7829 << FixItHint::CreateInsertion( 7830 InsertLoc, " " + NameInfo.getName().getAsString()); 7831 } 7832 } else if (R.getAsSingle<VarDecl>()) { 7833 // Don't provide a fixit outside C++11 mode; we don't want to suggest 7834 // repeating the type of the static data member here. 7835 FixItHint FixIt; 7836 if (getLangOpts().CPlusPlus11) { 7837 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 7838 FixIt = FixItHint::CreateReplacement( 7839 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 7840 } 7841 7842 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 7843 << 2 // reference declaration 7844 << FixIt; 7845 } 7846 return true; 7847 } 7848 7849 // Otherwise, everything is known to be fine. 7850 return false; 7851 } 7852 7853 // The current scope is a record. 7854 7855 // If the named context is dependent, we can't decide much. 7856 if (!NamedContext) { 7857 // FIXME: in C++0x, we can diagnose if we can prove that the 7858 // nested-name-specifier does not refer to a base class, which is 7859 // still possible in some cases. 7860 7861 // Otherwise we have to conservatively report that things might be 7862 // okay. 7863 return false; 7864 } 7865 7866 if (!NamedContext->isRecord()) { 7867 // Ideally this would point at the last name in the specifier, 7868 // but we don't have that level of source info. 7869 Diag(SS.getRange().getBegin(), 7870 diag::err_using_decl_nested_name_specifier_is_not_class) 7871 << SS.getScopeRep() << SS.getRange(); 7872 return true; 7873 } 7874 7875 if (!NamedContext->isDependentContext() && 7876 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7877 return true; 7878 7879 if (getLangOpts().CPlusPlus11) { 7880 // C++0x [namespace.udecl]p3: 7881 // In a using-declaration used as a member-declaration, the 7882 // nested-name-specifier shall name a base class of the class 7883 // being defined. 7884 7885 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7886 cast<CXXRecordDecl>(NamedContext))) { 7887 if (CurContext == NamedContext) { 7888 Diag(NameLoc, 7889 diag::err_using_decl_nested_name_specifier_is_current_class) 7890 << SS.getRange(); 7891 return true; 7892 } 7893 7894 Diag(SS.getRange().getBegin(), 7895 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7896 << SS.getScopeRep() 7897 << cast<CXXRecordDecl>(CurContext) 7898 << SS.getRange(); 7899 return true; 7900 } 7901 7902 return false; 7903 } 7904 7905 // C++03 [namespace.udecl]p4: 7906 // A using-declaration used as a member-declaration shall refer 7907 // to a member of a base class of the class being defined [etc.]. 7908 7909 // Salient point: SS doesn't have to name a base class as long as 7910 // lookup only finds members from base classes. Therefore we can 7911 // diagnose here only if we can prove that that can't happen, 7912 // i.e. if the class hierarchies provably don't intersect. 7913 7914 // TODO: it would be nice if "definitely valid" results were cached 7915 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7916 // need to be repeated. 7917 7918 struct UserData { 7919 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7920 7921 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7922 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7923 Data->Bases.insert(Base); 7924 return true; 7925 } 7926 7927 bool hasDependentBases(const CXXRecordDecl *Class) { 7928 return !Class->forallBases(collect, this); 7929 } 7930 7931 /// Returns true if the base is dependent or is one of the 7932 /// accumulated base classes. 7933 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7934 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7935 return !Data->Bases.count(Base); 7936 } 7937 7938 bool mightShareBases(const CXXRecordDecl *Class) { 7939 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7940 } 7941 }; 7942 7943 UserData Data; 7944 7945 // Returns false if we find a dependent base. 7946 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7947 return false; 7948 7949 // Returns false if the class has a dependent base or if it or one 7950 // of its bases is present in the base set of the current context. 7951 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7952 return false; 7953 7954 Diag(SS.getRange().getBegin(), 7955 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7956 << SS.getScopeRep() 7957 << cast<CXXRecordDecl>(CurContext) 7958 << SS.getRange(); 7959 7960 return true; 7961 } 7962 7963 Decl *Sema::ActOnAliasDeclaration(Scope *S, 7964 AccessSpecifier AS, 7965 MultiTemplateParamsArg TemplateParamLists, 7966 SourceLocation UsingLoc, 7967 UnqualifiedId &Name, 7968 AttributeList *AttrList, 7969 TypeResult Type) { 7970 // Skip up to the relevant declaration scope. 7971 while (S->getFlags() & Scope::TemplateParamScope) 7972 S = S->getParent(); 7973 assert((S->getFlags() & Scope::DeclScope) && 7974 "got alias-declaration outside of declaration scope"); 7975 7976 if (Type.isInvalid()) 7977 return nullptr; 7978 7979 bool Invalid = false; 7980 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7981 TypeSourceInfo *TInfo = nullptr; 7982 GetTypeFromParser(Type.get(), &TInfo); 7983 7984 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7985 return nullptr; 7986 7987 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7988 UPPC_DeclarationType)) { 7989 Invalid = true; 7990 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7991 TInfo->getTypeLoc().getBeginLoc()); 7992 } 7993 7994 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7995 LookupName(Previous, S); 7996 7997 // Warn about shadowing the name of a template parameter. 7998 if (Previous.isSingleResult() && 7999 Previous.getFoundDecl()->isTemplateParameter()) { 8000 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8001 Previous.clear(); 8002 } 8003 8004 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8005 "name in alias declaration must be an identifier"); 8006 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8007 Name.StartLocation, 8008 Name.Identifier, TInfo); 8009 8010 NewTD->setAccess(AS); 8011 8012 if (Invalid) 8013 NewTD->setInvalidDecl(); 8014 8015 ProcessDeclAttributeList(S, NewTD, AttrList); 8016 8017 CheckTypedefForVariablyModifiedType(S, NewTD); 8018 Invalid |= NewTD->isInvalidDecl(); 8019 8020 bool Redeclaration = false; 8021 8022 NamedDecl *NewND; 8023 if (TemplateParamLists.size()) { 8024 TypeAliasTemplateDecl *OldDecl = nullptr; 8025 TemplateParameterList *OldTemplateParams = nullptr; 8026 8027 if (TemplateParamLists.size() != 1) { 8028 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8029 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8030 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8031 } 8032 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8033 8034 // Only consider previous declarations in the same scope. 8035 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8036 /*ExplicitInstantiationOrSpecialization*/false); 8037 if (!Previous.empty()) { 8038 Redeclaration = true; 8039 8040 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8041 if (!OldDecl && !Invalid) { 8042 Diag(UsingLoc, diag::err_redefinition_different_kind) 8043 << Name.Identifier; 8044 8045 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8046 if (OldD->getLocation().isValid()) 8047 Diag(OldD->getLocation(), diag::note_previous_definition); 8048 8049 Invalid = true; 8050 } 8051 8052 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8053 if (TemplateParameterListsAreEqual(TemplateParams, 8054 OldDecl->getTemplateParameters(), 8055 /*Complain=*/true, 8056 TPL_TemplateMatch)) 8057 OldTemplateParams = OldDecl->getTemplateParameters(); 8058 else 8059 Invalid = true; 8060 8061 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8062 if (!Invalid && 8063 !Context.hasSameType(OldTD->getUnderlyingType(), 8064 NewTD->getUnderlyingType())) { 8065 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8066 // but we can't reasonably accept it. 8067 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8068 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8069 if (OldTD->getLocation().isValid()) 8070 Diag(OldTD->getLocation(), diag::note_previous_definition); 8071 Invalid = true; 8072 } 8073 } 8074 } 8075 8076 // Merge any previous default template arguments into our parameters, 8077 // and check the parameter list. 8078 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8079 TPC_TypeAliasTemplate)) 8080 return nullptr; 8081 8082 TypeAliasTemplateDecl *NewDecl = 8083 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8084 Name.Identifier, TemplateParams, 8085 NewTD); 8086 8087 NewDecl->setAccess(AS); 8088 8089 if (Invalid) 8090 NewDecl->setInvalidDecl(); 8091 else if (OldDecl) 8092 NewDecl->setPreviousDecl(OldDecl); 8093 8094 NewND = NewDecl; 8095 } else { 8096 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8097 NewND = NewTD; 8098 } 8099 8100 if (!Redeclaration) 8101 PushOnScopeChains(NewND, S); 8102 8103 ActOnDocumentableDecl(NewND); 8104 return NewND; 8105 } 8106 8107 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 8108 SourceLocation NamespaceLoc, 8109 SourceLocation AliasLoc, 8110 IdentifierInfo *Alias, 8111 CXXScopeSpec &SS, 8112 SourceLocation IdentLoc, 8113 IdentifierInfo *Ident) { 8114 8115 // Lookup the namespace name. 8116 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8117 LookupParsedName(R, S, &SS); 8118 8119 // Check if we have a previous declaration with the same name. 8120 NamedDecl *PrevDecl 8121 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8122 ForRedeclaration); 8123 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8124 PrevDecl = nullptr; 8125 8126 if (PrevDecl) { 8127 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8128 // We already have an alias with the same name that points to the same 8129 // namespace, so don't create a new one. 8130 // FIXME: At some point, we'll want to create the (redundant) 8131 // declaration to maintain better source information. 8132 if (!R.isAmbiguous() && !R.empty() && 8133 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 8134 return nullptr; 8135 } 8136 8137 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 8138 diag::err_redefinition_different_kind; 8139 Diag(AliasLoc, DiagID) << Alias; 8140 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8141 return nullptr; 8142 } 8143 8144 if (R.isAmbiguous()) 8145 return nullptr; 8146 8147 if (R.empty()) { 8148 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8149 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8150 return nullptr; 8151 } 8152 } 8153 8154 NamespaceAliasDecl *AliasDecl = 8155 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8156 Alias, SS.getWithLocInContext(Context), 8157 IdentLoc, R.getFoundDecl()); 8158 8159 PushOnScopeChains(AliasDecl, S); 8160 return AliasDecl; 8161 } 8162 8163 Sema::ImplicitExceptionSpecification 8164 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8165 CXXMethodDecl *MD) { 8166 CXXRecordDecl *ClassDecl = MD->getParent(); 8167 8168 // C++ [except.spec]p14: 8169 // An implicitly declared special member function (Clause 12) shall have an 8170 // exception-specification. [...] 8171 ImplicitExceptionSpecification ExceptSpec(*this); 8172 if (ClassDecl->isInvalidDecl()) 8173 return ExceptSpec; 8174 8175 // Direct base-class constructors. 8176 for (const auto &B : ClassDecl->bases()) { 8177 if (B.isVirtual()) // Handled below. 8178 continue; 8179 8180 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8181 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8182 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8183 // If this is a deleted function, add it anyway. This might be conformant 8184 // with the standard. This might not. I'm not sure. It might not matter. 8185 if (Constructor) 8186 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8187 } 8188 } 8189 8190 // Virtual base-class constructors. 8191 for (const auto &B : ClassDecl->vbases()) { 8192 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8193 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8194 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8195 // If this is a deleted function, add it anyway. This might be conformant 8196 // with the standard. This might not. I'm not sure. It might not matter. 8197 if (Constructor) 8198 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8199 } 8200 } 8201 8202 // Field constructors. 8203 for (const auto *F : ClassDecl->fields()) { 8204 if (F->hasInClassInitializer()) { 8205 if (Expr *E = F->getInClassInitializer()) 8206 ExceptSpec.CalledExpr(E); 8207 else if (!F->isInvalidDecl()) 8208 // DR1351: 8209 // If the brace-or-equal-initializer of a non-static data member 8210 // invokes a defaulted default constructor of its class or of an 8211 // enclosing class in a potentially evaluated subexpression, the 8212 // program is ill-formed. 8213 // 8214 // This resolution is unworkable: the exception specification of the 8215 // default constructor can be needed in an unevaluated context, in 8216 // particular, in the operand of a noexcept-expression, and we can be 8217 // unable to compute an exception specification for an enclosed class. 8218 // 8219 // We do not allow an in-class initializer to require the evaluation 8220 // of the exception specification for any in-class initializer whose 8221 // definition is not lexically complete. 8222 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8223 } else if (const RecordType *RecordTy 8224 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8225 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8226 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8227 // If this is a deleted function, add it anyway. This might be conformant 8228 // with the standard. This might not. I'm not sure. It might not matter. 8229 // In particular, the problem is that this function never gets called. It 8230 // might just be ill-formed because this function attempts to refer to 8231 // a deleted function here. 8232 if (Constructor) 8233 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8234 } 8235 } 8236 8237 return ExceptSpec; 8238 } 8239 8240 Sema::ImplicitExceptionSpecification 8241 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8242 CXXRecordDecl *ClassDecl = CD->getParent(); 8243 8244 // C++ [except.spec]p14: 8245 // An inheriting constructor [...] shall have an exception-specification. [...] 8246 ImplicitExceptionSpecification ExceptSpec(*this); 8247 if (ClassDecl->isInvalidDecl()) 8248 return ExceptSpec; 8249 8250 // Inherited constructor. 8251 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8252 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8253 // FIXME: Copying or moving the parameters could add extra exceptions to the 8254 // set, as could the default arguments for the inherited constructor. This 8255 // will be addressed when we implement the resolution of core issue 1351. 8256 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8257 8258 // Direct base-class constructors. 8259 for (const auto &B : ClassDecl->bases()) { 8260 if (B.isVirtual()) // Handled below. 8261 continue; 8262 8263 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8264 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8265 if (BaseClassDecl == InheritedDecl) 8266 continue; 8267 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8268 if (Constructor) 8269 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8270 } 8271 } 8272 8273 // Virtual base-class constructors. 8274 for (const auto &B : ClassDecl->vbases()) { 8275 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8276 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8277 if (BaseClassDecl == InheritedDecl) 8278 continue; 8279 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8280 if (Constructor) 8281 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8282 } 8283 } 8284 8285 // Field constructors. 8286 for (const auto *F : ClassDecl->fields()) { 8287 if (F->hasInClassInitializer()) { 8288 if (Expr *E = F->getInClassInitializer()) 8289 ExceptSpec.CalledExpr(E); 8290 else if (!F->isInvalidDecl()) 8291 Diag(CD->getLocation(), 8292 diag::err_in_class_initializer_references_def_ctor) << CD; 8293 } else if (const RecordType *RecordTy 8294 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8295 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8296 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8297 if (Constructor) 8298 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8299 } 8300 } 8301 8302 return ExceptSpec; 8303 } 8304 8305 namespace { 8306 /// RAII object to register a special member as being currently declared. 8307 struct DeclaringSpecialMember { 8308 Sema &S; 8309 Sema::SpecialMemberDecl D; 8310 bool WasAlreadyBeingDeclared; 8311 8312 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8313 : S(S), D(RD, CSM) { 8314 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8315 if (WasAlreadyBeingDeclared) 8316 // This almost never happens, but if it does, ensure that our cache 8317 // doesn't contain a stale result. 8318 S.SpecialMemberCache.clear(); 8319 8320 // FIXME: Register a note to be produced if we encounter an error while 8321 // declaring the special member. 8322 } 8323 ~DeclaringSpecialMember() { 8324 if (!WasAlreadyBeingDeclared) 8325 S.SpecialMembersBeingDeclared.erase(D); 8326 } 8327 8328 /// \brief Are we already trying to declare this special member? 8329 bool isAlreadyBeingDeclared() const { 8330 return WasAlreadyBeingDeclared; 8331 } 8332 }; 8333 } 8334 8335 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8336 CXXRecordDecl *ClassDecl) { 8337 // C++ [class.ctor]p5: 8338 // A default constructor for a class X is a constructor of class X 8339 // that can be called without an argument. If there is no 8340 // user-declared constructor for class X, a default constructor is 8341 // implicitly declared. An implicitly-declared default constructor 8342 // is an inline public member of its class. 8343 assert(ClassDecl->needsImplicitDefaultConstructor() && 8344 "Should not build implicit default constructor!"); 8345 8346 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8347 if (DSM.isAlreadyBeingDeclared()) 8348 return nullptr; 8349 8350 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8351 CXXDefaultConstructor, 8352 false); 8353 8354 // Create the actual constructor declaration. 8355 CanQualType ClassType 8356 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8357 SourceLocation ClassLoc = ClassDecl->getLocation(); 8358 DeclarationName Name 8359 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8360 DeclarationNameInfo NameInfo(Name, ClassLoc); 8361 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8362 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8363 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8364 /*isImplicitlyDeclared=*/true, Constexpr); 8365 DefaultCon->setAccess(AS_public); 8366 DefaultCon->setDefaulted(); 8367 DefaultCon->setImplicit(); 8368 8369 // Build an exception specification pointing back at this constructor. 8370 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8371 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8372 8373 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8374 // constructors is easy to compute. 8375 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8376 8377 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8378 SetDeclDeleted(DefaultCon, ClassLoc); 8379 8380 // Note that we have declared this constructor. 8381 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8382 8383 if (Scope *S = getScopeForContext(ClassDecl)) 8384 PushOnScopeChains(DefaultCon, S, false); 8385 ClassDecl->addDecl(DefaultCon); 8386 8387 return DefaultCon; 8388 } 8389 8390 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8391 CXXConstructorDecl *Constructor) { 8392 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8393 !Constructor->doesThisDeclarationHaveABody() && 8394 !Constructor->isDeleted()) && 8395 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8396 8397 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8398 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8399 8400 SynthesizedFunctionScope Scope(*this, Constructor); 8401 DiagnosticErrorTrap Trap(Diags); 8402 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8403 Trap.hasErrorOccurred()) { 8404 Diag(CurrentLocation, diag::note_member_synthesized_at) 8405 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8406 Constructor->setInvalidDecl(); 8407 return; 8408 } 8409 8410 SourceLocation Loc = Constructor->getLocEnd().isValid() 8411 ? Constructor->getLocEnd() 8412 : Constructor->getLocation(); 8413 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8414 8415 Constructor->markUsed(Context); 8416 MarkVTableUsed(CurrentLocation, ClassDecl); 8417 8418 if (ASTMutationListener *L = getASTMutationListener()) { 8419 L->CompletedImplicitDefinition(Constructor); 8420 } 8421 8422 DiagnoseUninitializedFields(*this, Constructor); 8423 } 8424 8425 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8426 // Perform any delayed checks on exception specifications. 8427 CheckDelayedMemberExceptionSpecs(); 8428 } 8429 8430 namespace { 8431 /// Information on inheriting constructors to declare. 8432 class InheritingConstructorInfo { 8433 public: 8434 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8435 : SemaRef(SemaRef), Derived(Derived) { 8436 // Mark the constructors that we already have in the derived class. 8437 // 8438 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8439 // unless there is a user-declared constructor with the same signature in 8440 // the class where the using-declaration appears. 8441 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8442 } 8443 8444 void inheritAll(CXXRecordDecl *RD) { 8445 visitAll(RD, &InheritingConstructorInfo::inherit); 8446 } 8447 8448 private: 8449 /// Information about an inheriting constructor. 8450 struct InheritingConstructor { 8451 InheritingConstructor() 8452 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8453 8454 /// If \c true, a constructor with this signature is already declared 8455 /// in the derived class. 8456 bool DeclaredInDerived; 8457 8458 /// The constructor which is inherited. 8459 const CXXConstructorDecl *BaseCtor; 8460 8461 /// The derived constructor we declared. 8462 CXXConstructorDecl *DerivedCtor; 8463 }; 8464 8465 /// Inheriting constructors with a given canonical type. There can be at 8466 /// most one such non-template constructor, and any number of templated 8467 /// constructors. 8468 struct InheritingConstructorsForType { 8469 InheritingConstructor NonTemplate; 8470 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8471 Templates; 8472 8473 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8474 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8475 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8476 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8477 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8478 false, S.TPL_TemplateMatch)) 8479 return Templates[I].second; 8480 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8481 return Templates.back().second; 8482 } 8483 8484 return NonTemplate; 8485 } 8486 }; 8487 8488 /// Get or create the inheriting constructor record for a constructor. 8489 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8490 QualType CtorType) { 8491 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8492 .getEntry(SemaRef, Ctor); 8493 } 8494 8495 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8496 8497 /// Process all constructors for a class. 8498 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8499 for (const auto *Ctor : RD->ctors()) 8500 (this->*Callback)(Ctor); 8501 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8502 I(RD->decls_begin()), E(RD->decls_end()); 8503 I != E; ++I) { 8504 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8505 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8506 (this->*Callback)(CD); 8507 } 8508 } 8509 8510 /// Note that a constructor (or constructor template) was declared in Derived. 8511 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8512 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8513 } 8514 8515 /// Inherit a single constructor. 8516 void inherit(const CXXConstructorDecl *Ctor) { 8517 const FunctionProtoType *CtorType = 8518 Ctor->getType()->castAs<FunctionProtoType>(); 8519 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes()); 8520 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8521 8522 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8523 8524 // Core issue (no number yet): the ellipsis is always discarded. 8525 if (EPI.Variadic) { 8526 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8527 SemaRef.Diag(Ctor->getLocation(), 8528 diag::note_using_decl_constructor_ellipsis); 8529 EPI.Variadic = false; 8530 } 8531 8532 // Declare a constructor for each number of parameters. 8533 // 8534 // C++11 [class.inhctor]p1: 8535 // The candidate set of inherited constructors from the class X named in 8536 // the using-declaration consists of [... modulo defects ...] for each 8537 // constructor or constructor template of X, the set of constructors or 8538 // constructor templates that results from omitting any ellipsis parameter 8539 // specification and successively omitting parameters with a default 8540 // argument from the end of the parameter-type-list 8541 unsigned MinParams = minParamsToInherit(Ctor); 8542 unsigned Params = Ctor->getNumParams(); 8543 if (Params >= MinParams) { 8544 do 8545 declareCtor(UsingLoc, Ctor, 8546 SemaRef.Context.getFunctionType( 8547 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8548 while (Params > MinParams && 8549 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8550 } 8551 } 8552 8553 /// Find the using-declaration which specified that we should inherit the 8554 /// constructors of \p Base. 8555 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8556 // No fancy lookup required; just look for the base constructor name 8557 // directly within the derived class. 8558 ASTContext &Context = SemaRef.Context; 8559 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8560 Context.getCanonicalType(Context.getRecordType(Base))); 8561 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8562 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8563 } 8564 8565 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8566 // C++11 [class.inhctor]p3: 8567 // [F]or each constructor template in the candidate set of inherited 8568 // constructors, a constructor template is implicitly declared 8569 if (Ctor->getDescribedFunctionTemplate()) 8570 return 0; 8571 8572 // For each non-template constructor in the candidate set of inherited 8573 // constructors other than a constructor having no parameters or a 8574 // copy/move constructor having a single parameter, a constructor is 8575 // implicitly declared [...] 8576 if (Ctor->getNumParams() == 0) 8577 return 1; 8578 if (Ctor->isCopyOrMoveConstructor()) 8579 return 2; 8580 8581 // Per discussion on core reflector, never inherit a constructor which 8582 // would become a default, copy, or move constructor of Derived either. 8583 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8584 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8585 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8586 } 8587 8588 /// Declare a single inheriting constructor, inheriting the specified 8589 /// constructor, with the given type. 8590 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8591 QualType DerivedType) { 8592 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8593 8594 // C++11 [class.inhctor]p3: 8595 // ... a constructor is implicitly declared with the same constructor 8596 // characteristics unless there is a user-declared constructor with 8597 // the same signature in the class where the using-declaration appears 8598 if (Entry.DeclaredInDerived) 8599 return; 8600 8601 // C++11 [class.inhctor]p7: 8602 // If two using-declarations declare inheriting constructors with the 8603 // same signature, the program is ill-formed 8604 if (Entry.DerivedCtor) { 8605 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8606 // Only diagnose this once per constructor. 8607 if (Entry.DerivedCtor->isInvalidDecl()) 8608 return; 8609 Entry.DerivedCtor->setInvalidDecl(); 8610 8611 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8612 SemaRef.Diag(BaseCtor->getLocation(), 8613 diag::note_using_decl_constructor_conflict_current_ctor); 8614 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8615 diag::note_using_decl_constructor_conflict_previous_ctor); 8616 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8617 diag::note_using_decl_constructor_conflict_previous_using); 8618 } else { 8619 // Core issue (no number): if the same inheriting constructor is 8620 // produced by multiple base class constructors from the same base 8621 // class, the inheriting constructor is defined as deleted. 8622 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8623 } 8624 8625 return; 8626 } 8627 8628 ASTContext &Context = SemaRef.Context; 8629 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8630 Context.getCanonicalType(Context.getRecordType(Derived))); 8631 DeclarationNameInfo NameInfo(Name, UsingLoc); 8632 8633 TemplateParameterList *TemplateParams = nullptr; 8634 if (const FunctionTemplateDecl *FTD = 8635 BaseCtor->getDescribedFunctionTemplate()) { 8636 TemplateParams = FTD->getTemplateParameters(); 8637 // We're reusing template parameters from a different DeclContext. This 8638 // is questionable at best, but works out because the template depth in 8639 // both places is guaranteed to be 0. 8640 // FIXME: Rebuild the template parameters in the new context, and 8641 // transform the function type to refer to them. 8642 } 8643 8644 // Build type source info pointing at the using-declaration. This is 8645 // required by template instantiation. 8646 TypeSourceInfo *TInfo = 8647 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8648 FunctionProtoTypeLoc ProtoLoc = 8649 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8650 8651 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8652 Context, Derived, UsingLoc, NameInfo, DerivedType, 8653 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8654 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8655 8656 // Build an unevaluated exception specification for this constructor. 8657 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8658 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8659 EPI.ExceptionSpecType = EST_Unevaluated; 8660 EPI.ExceptionSpecDecl = DerivedCtor; 8661 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 8662 FPT->getParamTypes(), EPI)); 8663 8664 // Build the parameter declarations. 8665 SmallVector<ParmVarDecl *, 16> ParamDecls; 8666 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 8667 TypeSourceInfo *TInfo = 8668 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 8669 ParmVarDecl *PD = ParmVarDecl::Create( 8670 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 8671 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 8672 PD->setScopeInfo(0, I); 8673 PD->setImplicit(); 8674 ParamDecls.push_back(PD); 8675 ProtoLoc.setParam(I, PD); 8676 } 8677 8678 // Set up the new constructor. 8679 DerivedCtor->setAccess(BaseCtor->getAccess()); 8680 DerivedCtor->setParams(ParamDecls); 8681 DerivedCtor->setInheritedConstructor(BaseCtor); 8682 if (BaseCtor->isDeleted()) 8683 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8684 8685 // If this is a constructor template, build the template declaration. 8686 if (TemplateParams) { 8687 FunctionTemplateDecl *DerivedTemplate = 8688 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8689 TemplateParams, DerivedCtor); 8690 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8691 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8692 Derived->addDecl(DerivedTemplate); 8693 } else { 8694 Derived->addDecl(DerivedCtor); 8695 } 8696 8697 Entry.BaseCtor = BaseCtor; 8698 Entry.DerivedCtor = DerivedCtor; 8699 } 8700 8701 Sema &SemaRef; 8702 CXXRecordDecl *Derived; 8703 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8704 MapType Map; 8705 }; 8706 } 8707 8708 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8709 // Defer declaring the inheriting constructors until the class is 8710 // instantiated. 8711 if (ClassDecl->isDependentContext()) 8712 return; 8713 8714 // Find base classes from which we might inherit constructors. 8715 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8716 for (const auto &BaseIt : ClassDecl->bases()) 8717 if (BaseIt.getInheritConstructors()) 8718 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 8719 8720 // Go no further if we're not inheriting any constructors. 8721 if (InheritedBases.empty()) 8722 return; 8723 8724 // Declare the inherited constructors. 8725 InheritingConstructorInfo ICI(*this, ClassDecl); 8726 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8727 ICI.inheritAll(InheritedBases[I]); 8728 } 8729 8730 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8731 CXXConstructorDecl *Constructor) { 8732 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8733 assert(Constructor->getInheritedConstructor() && 8734 !Constructor->doesThisDeclarationHaveABody() && 8735 !Constructor->isDeleted()); 8736 8737 SynthesizedFunctionScope Scope(*this, Constructor); 8738 DiagnosticErrorTrap Trap(Diags); 8739 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8740 Trap.hasErrorOccurred()) { 8741 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8742 << Context.getTagDeclType(ClassDecl); 8743 Constructor->setInvalidDecl(); 8744 return; 8745 } 8746 8747 SourceLocation Loc = Constructor->getLocation(); 8748 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8749 8750 Constructor->markUsed(Context); 8751 MarkVTableUsed(CurrentLocation, ClassDecl); 8752 8753 if (ASTMutationListener *L = getASTMutationListener()) { 8754 L->CompletedImplicitDefinition(Constructor); 8755 } 8756 } 8757 8758 8759 Sema::ImplicitExceptionSpecification 8760 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8761 CXXRecordDecl *ClassDecl = MD->getParent(); 8762 8763 // C++ [except.spec]p14: 8764 // An implicitly declared special member function (Clause 12) shall have 8765 // an exception-specification. 8766 ImplicitExceptionSpecification ExceptSpec(*this); 8767 if (ClassDecl->isInvalidDecl()) 8768 return ExceptSpec; 8769 8770 // Direct base-class destructors. 8771 for (const auto &B : ClassDecl->bases()) { 8772 if (B.isVirtual()) // Handled below. 8773 continue; 8774 8775 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8776 ExceptSpec.CalledDecl(B.getLocStart(), 8777 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8778 } 8779 8780 // Virtual base-class destructors. 8781 for (const auto &B : ClassDecl->vbases()) { 8782 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8783 ExceptSpec.CalledDecl(B.getLocStart(), 8784 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8785 } 8786 8787 // Field destructors. 8788 for (const auto *F : ClassDecl->fields()) { 8789 if (const RecordType *RecordTy 8790 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8791 ExceptSpec.CalledDecl(F->getLocation(), 8792 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8793 } 8794 8795 return ExceptSpec; 8796 } 8797 8798 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8799 // C++ [class.dtor]p2: 8800 // If a class has no user-declared destructor, a destructor is 8801 // declared implicitly. An implicitly-declared destructor is an 8802 // inline public member of its class. 8803 assert(ClassDecl->needsImplicitDestructor()); 8804 8805 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8806 if (DSM.isAlreadyBeingDeclared()) 8807 return nullptr; 8808 8809 // Create the actual destructor declaration. 8810 CanQualType ClassType 8811 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8812 SourceLocation ClassLoc = ClassDecl->getLocation(); 8813 DeclarationName Name 8814 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8815 DeclarationNameInfo NameInfo(Name, ClassLoc); 8816 CXXDestructorDecl *Destructor 8817 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8818 QualType(), nullptr, /*isInline=*/true, 8819 /*isImplicitlyDeclared=*/true); 8820 Destructor->setAccess(AS_public); 8821 Destructor->setDefaulted(); 8822 Destructor->setImplicit(); 8823 8824 // Build an exception specification pointing back at this destructor. 8825 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8826 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8827 8828 AddOverriddenMethods(ClassDecl, Destructor); 8829 8830 // We don't need to use SpecialMemberIsTrivial here; triviality for 8831 // destructors is easy to compute. 8832 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8833 8834 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8835 SetDeclDeleted(Destructor, ClassLoc); 8836 8837 // Note that we have declared this destructor. 8838 ++ASTContext::NumImplicitDestructorsDeclared; 8839 8840 // Introduce this destructor into its scope. 8841 if (Scope *S = getScopeForContext(ClassDecl)) 8842 PushOnScopeChains(Destructor, S, false); 8843 ClassDecl->addDecl(Destructor); 8844 8845 return Destructor; 8846 } 8847 8848 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8849 CXXDestructorDecl *Destructor) { 8850 assert((Destructor->isDefaulted() && 8851 !Destructor->doesThisDeclarationHaveABody() && 8852 !Destructor->isDeleted()) && 8853 "DefineImplicitDestructor - call it for implicit default dtor"); 8854 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8855 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8856 8857 if (Destructor->isInvalidDecl()) 8858 return; 8859 8860 SynthesizedFunctionScope Scope(*this, Destructor); 8861 8862 DiagnosticErrorTrap Trap(Diags); 8863 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8864 Destructor->getParent()); 8865 8866 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8867 Diag(CurrentLocation, diag::note_member_synthesized_at) 8868 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8869 8870 Destructor->setInvalidDecl(); 8871 return; 8872 } 8873 8874 SourceLocation Loc = Destructor->getLocEnd().isValid() 8875 ? Destructor->getLocEnd() 8876 : Destructor->getLocation(); 8877 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8878 Destructor->markUsed(Context); 8879 MarkVTableUsed(CurrentLocation, ClassDecl); 8880 8881 if (ASTMutationListener *L = getASTMutationListener()) { 8882 L->CompletedImplicitDefinition(Destructor); 8883 } 8884 } 8885 8886 /// \brief Perform any semantic analysis which needs to be delayed until all 8887 /// pending class member declarations have been parsed. 8888 void Sema::ActOnFinishCXXMemberDecls() { 8889 // If the context is an invalid C++ class, just suppress these checks. 8890 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8891 if (Record->isInvalidDecl()) { 8892 DelayedDefaultedMemberExceptionSpecs.clear(); 8893 DelayedDestructorExceptionSpecChecks.clear(); 8894 return; 8895 } 8896 } 8897 } 8898 8899 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8900 CXXDestructorDecl *Destructor) { 8901 assert(getLangOpts().CPlusPlus11 && 8902 "adjusting dtor exception specs was introduced in c++11"); 8903 8904 // C++11 [class.dtor]p3: 8905 // A declaration of a destructor that does not have an exception- 8906 // specification is implicitly considered to have the same exception- 8907 // specification as an implicit declaration. 8908 const FunctionProtoType *DtorType = Destructor->getType()-> 8909 getAs<FunctionProtoType>(); 8910 if (DtorType->hasExceptionSpec()) 8911 return; 8912 8913 // Replace the destructor's type, building off the existing one. Fortunately, 8914 // the only thing of interest in the destructor type is its extended info. 8915 // The return and arguments are fixed. 8916 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8917 EPI.ExceptionSpecType = EST_Unevaluated; 8918 EPI.ExceptionSpecDecl = Destructor; 8919 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8920 8921 // FIXME: If the destructor has a body that could throw, and the newly created 8922 // spec doesn't allow exceptions, we should emit a warning, because this 8923 // change in behavior can break conforming C++03 programs at runtime. 8924 // However, we don't have a body or an exception specification yet, so it 8925 // needs to be done somewhere else. 8926 } 8927 8928 namespace { 8929 /// \brief An abstract base class for all helper classes used in building the 8930 // copy/move operators. These classes serve as factory functions and help us 8931 // avoid using the same Expr* in the AST twice. 8932 class ExprBuilder { 8933 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8934 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8935 8936 protected: 8937 static Expr *assertNotNull(Expr *E) { 8938 assert(E && "Expression construction must not fail."); 8939 return E; 8940 } 8941 8942 public: 8943 ExprBuilder() {} 8944 virtual ~ExprBuilder() {} 8945 8946 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 8947 }; 8948 8949 class RefBuilder: public ExprBuilder { 8950 VarDecl *Var; 8951 QualType VarType; 8952 8953 public: 8954 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8955 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 8956 } 8957 8958 RefBuilder(VarDecl *Var, QualType VarType) 8959 : Var(Var), VarType(VarType) {} 8960 }; 8961 8962 class ThisBuilder: public ExprBuilder { 8963 public: 8964 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8965 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 8966 } 8967 }; 8968 8969 class CastBuilder: public ExprBuilder { 8970 const ExprBuilder &Builder; 8971 QualType Type; 8972 ExprValueKind Kind; 8973 const CXXCastPath &Path; 8974 8975 public: 8976 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8977 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 8978 CK_UncheckedDerivedToBase, Kind, 8979 &Path).get()); 8980 } 8981 8982 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 8983 const CXXCastPath &Path) 8984 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 8985 }; 8986 8987 class DerefBuilder: public ExprBuilder { 8988 const ExprBuilder &Builder; 8989 8990 public: 8991 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8992 return assertNotNull( 8993 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 8994 } 8995 8996 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8997 }; 8998 8999 class MemberBuilder: public ExprBuilder { 9000 const ExprBuilder &Builder; 9001 QualType Type; 9002 CXXScopeSpec SS; 9003 bool IsArrow; 9004 LookupResult &MemberLookup; 9005 9006 public: 9007 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9008 return assertNotNull(S.BuildMemberReferenceExpr( 9009 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9010 nullptr, MemberLookup, nullptr).get()); 9011 } 9012 9013 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9014 LookupResult &MemberLookup) 9015 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9016 MemberLookup(MemberLookup) {} 9017 }; 9018 9019 class MoveCastBuilder: public ExprBuilder { 9020 const ExprBuilder &Builder; 9021 9022 public: 9023 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9024 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9025 } 9026 9027 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9028 }; 9029 9030 class LvalueConvBuilder: public ExprBuilder { 9031 const ExprBuilder &Builder; 9032 9033 public: 9034 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9035 return assertNotNull( 9036 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9037 } 9038 9039 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9040 }; 9041 9042 class SubscriptBuilder: public ExprBuilder { 9043 const ExprBuilder &Base; 9044 const ExprBuilder &Index; 9045 9046 public: 9047 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9048 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9049 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9050 } 9051 9052 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9053 : Base(Base), Index(Index) {} 9054 }; 9055 9056 } // end anonymous namespace 9057 9058 /// When generating a defaulted copy or move assignment operator, if a field 9059 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9060 /// do so. This optimization only applies for arrays of scalars, and for arrays 9061 /// of class type where the selected copy/move-assignment operator is trivial. 9062 static StmtResult 9063 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9064 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9065 // Compute the size of the memory buffer to be copied. 9066 QualType SizeType = S.Context.getSizeType(); 9067 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9068 S.Context.getTypeSizeInChars(T).getQuantity()); 9069 9070 // Take the address of the field references for "from" and "to". We 9071 // directly construct UnaryOperators here because semantic analysis 9072 // does not permit us to take the address of an xvalue. 9073 Expr *From = FromB.build(S, Loc); 9074 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9075 S.Context.getPointerType(From->getType()), 9076 VK_RValue, OK_Ordinary, Loc); 9077 Expr *To = ToB.build(S, Loc); 9078 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9079 S.Context.getPointerType(To->getType()), 9080 VK_RValue, OK_Ordinary, Loc); 9081 9082 const Type *E = T->getBaseElementTypeUnsafe(); 9083 bool NeedsCollectableMemCpy = 9084 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9085 9086 // Create a reference to the __builtin_objc_memmove_collectable function 9087 StringRef MemCpyName = NeedsCollectableMemCpy ? 9088 "__builtin_objc_memmove_collectable" : 9089 "__builtin_memcpy"; 9090 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9091 Sema::LookupOrdinaryName); 9092 S.LookupName(R, S.TUScope, true); 9093 9094 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9095 if (!MemCpy) 9096 // Something went horribly wrong earlier, and we will have complained 9097 // about it. 9098 return StmtError(); 9099 9100 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9101 VK_RValue, Loc, nullptr); 9102 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9103 9104 Expr *CallArgs[] = { 9105 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9106 }; 9107 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9108 Loc, CallArgs, Loc); 9109 9110 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9111 return Call.getAs<Stmt>(); 9112 } 9113 9114 /// \brief Builds a statement that copies/moves the given entity from \p From to 9115 /// \c To. 9116 /// 9117 /// This routine is used to copy/move the members of a class with an 9118 /// implicitly-declared copy/move assignment operator. When the entities being 9119 /// copied are arrays, this routine builds for loops to copy them. 9120 /// 9121 /// \param S The Sema object used for type-checking. 9122 /// 9123 /// \param Loc The location where the implicit copy/move is being generated. 9124 /// 9125 /// \param T The type of the expressions being copied/moved. Both expressions 9126 /// must have this type. 9127 /// 9128 /// \param To The expression we are copying/moving to. 9129 /// 9130 /// \param From The expression we are copying/moving from. 9131 /// 9132 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9133 /// Otherwise, it's a non-static member subobject. 9134 /// 9135 /// \param Copying Whether we're copying or moving. 9136 /// 9137 /// \param Depth Internal parameter recording the depth of the recursion. 9138 /// 9139 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9140 /// if a memcpy should be used instead. 9141 static StmtResult 9142 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9143 const ExprBuilder &To, const ExprBuilder &From, 9144 bool CopyingBaseSubobject, bool Copying, 9145 unsigned Depth = 0) { 9146 // C++11 [class.copy]p28: 9147 // Each subobject is assigned in the manner appropriate to its type: 9148 // 9149 // - if the subobject is of class type, as if by a call to operator= with 9150 // the subobject as the object expression and the corresponding 9151 // subobject of x as a single function argument (as if by explicit 9152 // qualification; that is, ignoring any possible virtual overriding 9153 // functions in more derived classes); 9154 // 9155 // C++03 [class.copy]p13: 9156 // - if the subobject is of class type, the copy assignment operator for 9157 // the class is used (as if by explicit qualification; that is, 9158 // ignoring any possible virtual overriding functions in more derived 9159 // classes); 9160 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9161 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9162 9163 // Look for operator=. 9164 DeclarationName Name 9165 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9166 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9167 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9168 9169 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9170 // operator. 9171 if (!S.getLangOpts().CPlusPlus11) { 9172 LookupResult::Filter F = OpLookup.makeFilter(); 9173 while (F.hasNext()) { 9174 NamedDecl *D = F.next(); 9175 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9176 if (Method->isCopyAssignmentOperator() || 9177 (!Copying && Method->isMoveAssignmentOperator())) 9178 continue; 9179 9180 F.erase(); 9181 } 9182 F.done(); 9183 } 9184 9185 // Suppress the protected check (C++ [class.protected]) for each of the 9186 // assignment operators we found. This strange dance is required when 9187 // we're assigning via a base classes's copy-assignment operator. To 9188 // ensure that we're getting the right base class subobject (without 9189 // ambiguities), we need to cast "this" to that subobject type; to 9190 // ensure that we don't go through the virtual call mechanism, we need 9191 // to qualify the operator= name with the base class (see below). However, 9192 // this means that if the base class has a protected copy assignment 9193 // operator, the protected member access check will fail. So, we 9194 // rewrite "protected" access to "public" access in this case, since we 9195 // know by construction that we're calling from a derived class. 9196 if (CopyingBaseSubobject) { 9197 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9198 L != LEnd; ++L) { 9199 if (L.getAccess() == AS_protected) 9200 L.setAccess(AS_public); 9201 } 9202 } 9203 9204 // Create the nested-name-specifier that will be used to qualify the 9205 // reference to operator=; this is required to suppress the virtual 9206 // call mechanism. 9207 CXXScopeSpec SS; 9208 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9209 SS.MakeTrivial(S.Context, 9210 NestedNameSpecifier::Create(S.Context, nullptr, false, 9211 CanonicalT), 9212 Loc); 9213 9214 // Create the reference to operator=. 9215 ExprResult OpEqualRef 9216 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9217 SS, /*TemplateKWLoc=*/SourceLocation(), 9218 /*FirstQualifierInScope=*/nullptr, 9219 OpLookup, 9220 /*TemplateArgs=*/nullptr, 9221 /*SuppressQualifierCheck=*/true); 9222 if (OpEqualRef.isInvalid()) 9223 return StmtError(); 9224 9225 // Build the call to the assignment operator. 9226 9227 Expr *FromInst = From.build(S, Loc); 9228 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9229 OpEqualRef.getAs<Expr>(), 9230 Loc, FromInst, Loc); 9231 if (Call.isInvalid()) 9232 return StmtError(); 9233 9234 // If we built a call to a trivial 'operator=' while copying an array, 9235 // bail out. We'll replace the whole shebang with a memcpy. 9236 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9237 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9238 return StmtResult((Stmt*)nullptr); 9239 9240 // Convert to an expression-statement, and clean up any produced 9241 // temporaries. 9242 return S.ActOnExprStmt(Call); 9243 } 9244 9245 // - if the subobject is of scalar type, the built-in assignment 9246 // operator is used. 9247 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9248 if (!ArrayTy) { 9249 ExprResult Assignment = S.CreateBuiltinBinOp( 9250 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9251 if (Assignment.isInvalid()) 9252 return StmtError(); 9253 return S.ActOnExprStmt(Assignment); 9254 } 9255 9256 // - if the subobject is an array, each element is assigned, in the 9257 // manner appropriate to the element type; 9258 9259 // Construct a loop over the array bounds, e.g., 9260 // 9261 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9262 // 9263 // that will copy each of the array elements. 9264 QualType SizeType = S.Context.getSizeType(); 9265 9266 // Create the iteration variable. 9267 IdentifierInfo *IterationVarName = nullptr; 9268 { 9269 SmallString<8> Str; 9270 llvm::raw_svector_ostream OS(Str); 9271 OS << "__i" << Depth; 9272 IterationVarName = &S.Context.Idents.get(OS.str()); 9273 } 9274 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9275 IterationVarName, SizeType, 9276 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9277 SC_None); 9278 9279 // Initialize the iteration variable to zero. 9280 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9281 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9282 9283 // Creates a reference to the iteration variable. 9284 RefBuilder IterationVarRef(IterationVar, SizeType); 9285 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9286 9287 // Create the DeclStmt that holds the iteration variable. 9288 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9289 9290 // Subscript the "from" and "to" expressions with the iteration variable. 9291 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9292 MoveCastBuilder FromIndexMove(FromIndexCopy); 9293 const ExprBuilder *FromIndex; 9294 if (Copying) 9295 FromIndex = &FromIndexCopy; 9296 else 9297 FromIndex = &FromIndexMove; 9298 9299 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9300 9301 // Build the copy/move for an individual element of the array. 9302 StmtResult Copy = 9303 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9304 ToIndex, *FromIndex, CopyingBaseSubobject, 9305 Copying, Depth + 1); 9306 // Bail out if copying fails or if we determined that we should use memcpy. 9307 if (Copy.isInvalid() || !Copy.get()) 9308 return Copy; 9309 9310 // Create the comparison against the array bound. 9311 llvm::APInt Upper 9312 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9313 Expr *Comparison 9314 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9315 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9316 BO_NE, S.Context.BoolTy, 9317 VK_RValue, OK_Ordinary, Loc, false); 9318 9319 // Create the pre-increment of the iteration variable. 9320 Expr *Increment 9321 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9322 SizeType, VK_LValue, OK_Ordinary, Loc); 9323 9324 // Construct the loop that copies all elements of this array. 9325 return S.ActOnForStmt(Loc, Loc, InitStmt, 9326 S.MakeFullExpr(Comparison), 9327 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9328 Loc, Copy.get()); 9329 } 9330 9331 static StmtResult 9332 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9333 const ExprBuilder &To, const ExprBuilder &From, 9334 bool CopyingBaseSubobject, bool Copying) { 9335 // Maybe we should use a memcpy? 9336 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9337 T.isTriviallyCopyableType(S.Context)) 9338 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9339 9340 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9341 CopyingBaseSubobject, 9342 Copying, 0)); 9343 9344 // If we ended up picking a trivial assignment operator for an array of a 9345 // non-trivially-copyable class type, just emit a memcpy. 9346 if (!Result.isInvalid() && !Result.get()) 9347 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9348 9349 return Result; 9350 } 9351 9352 Sema::ImplicitExceptionSpecification 9353 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9354 CXXRecordDecl *ClassDecl = MD->getParent(); 9355 9356 ImplicitExceptionSpecification ExceptSpec(*this); 9357 if (ClassDecl->isInvalidDecl()) 9358 return ExceptSpec; 9359 9360 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9361 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9362 unsigned ArgQuals = 9363 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9364 9365 // C++ [except.spec]p14: 9366 // An implicitly declared special member function (Clause 12) shall have an 9367 // exception-specification. [...] 9368 9369 // It is unspecified whether or not an implicit copy assignment operator 9370 // attempts to deduplicate calls to assignment operators of virtual bases are 9371 // made. As such, this exception specification is effectively unspecified. 9372 // Based on a similar decision made for constness in C++0x, we're erring on 9373 // the side of assuming such calls to be made regardless of whether they 9374 // actually happen. 9375 for (const auto &Base : ClassDecl->bases()) { 9376 if (Base.isVirtual()) 9377 continue; 9378 9379 CXXRecordDecl *BaseClassDecl 9380 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9381 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9382 ArgQuals, false, 0)) 9383 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9384 } 9385 9386 for (const auto &Base : ClassDecl->vbases()) { 9387 CXXRecordDecl *BaseClassDecl 9388 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9389 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9390 ArgQuals, false, 0)) 9391 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9392 } 9393 9394 for (const auto *Field : ClassDecl->fields()) { 9395 QualType FieldType = Context.getBaseElementType(Field->getType()); 9396 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9397 if (CXXMethodDecl *CopyAssign = 9398 LookupCopyingAssignment(FieldClassDecl, 9399 ArgQuals | FieldType.getCVRQualifiers(), 9400 false, 0)) 9401 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9402 } 9403 } 9404 9405 return ExceptSpec; 9406 } 9407 9408 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9409 // Note: The following rules are largely analoguous to the copy 9410 // constructor rules. Note that virtual bases are not taken into account 9411 // for determining the argument type of the operator. Note also that 9412 // operators taking an object instead of a reference are allowed. 9413 assert(ClassDecl->needsImplicitCopyAssignment()); 9414 9415 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9416 if (DSM.isAlreadyBeingDeclared()) 9417 return nullptr; 9418 9419 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9420 QualType RetType = Context.getLValueReferenceType(ArgType); 9421 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9422 if (Const) 9423 ArgType = ArgType.withConst(); 9424 ArgType = Context.getLValueReferenceType(ArgType); 9425 9426 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9427 CXXCopyAssignment, 9428 Const); 9429 9430 // An implicitly-declared copy assignment operator is an inline public 9431 // member of its class. 9432 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9433 SourceLocation ClassLoc = ClassDecl->getLocation(); 9434 DeclarationNameInfo NameInfo(Name, ClassLoc); 9435 CXXMethodDecl *CopyAssignment = 9436 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9437 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9438 /*isInline=*/true, Constexpr, SourceLocation()); 9439 CopyAssignment->setAccess(AS_public); 9440 CopyAssignment->setDefaulted(); 9441 CopyAssignment->setImplicit(); 9442 9443 // Build an exception specification pointing back at this member. 9444 FunctionProtoType::ExtProtoInfo EPI = 9445 getImplicitMethodEPI(*this, CopyAssignment); 9446 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9447 9448 // Add the parameter to the operator. 9449 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9450 ClassLoc, ClassLoc, 9451 /*Id=*/nullptr, ArgType, 9452 /*TInfo=*/nullptr, SC_None, 9453 nullptr); 9454 CopyAssignment->setParams(FromParam); 9455 9456 AddOverriddenMethods(ClassDecl, CopyAssignment); 9457 9458 CopyAssignment->setTrivial( 9459 ClassDecl->needsOverloadResolutionForCopyAssignment() 9460 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9461 : ClassDecl->hasTrivialCopyAssignment()); 9462 9463 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9464 SetDeclDeleted(CopyAssignment, ClassLoc); 9465 9466 // Note that we have added this copy-assignment operator. 9467 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9468 9469 if (Scope *S = getScopeForContext(ClassDecl)) 9470 PushOnScopeChains(CopyAssignment, S, false); 9471 ClassDecl->addDecl(CopyAssignment); 9472 9473 return CopyAssignment; 9474 } 9475 9476 /// Diagnose an implicit copy operation for a class which is odr-used, but 9477 /// which is deprecated because the class has a user-declared copy constructor, 9478 /// copy assignment operator, or destructor. 9479 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9480 SourceLocation UseLoc) { 9481 assert(CopyOp->isImplicit()); 9482 9483 CXXRecordDecl *RD = CopyOp->getParent(); 9484 CXXMethodDecl *UserDeclaredOperation = nullptr; 9485 9486 // In Microsoft mode, assignment operations don't affect constructors and 9487 // vice versa. 9488 if (RD->hasUserDeclaredDestructor()) { 9489 UserDeclaredOperation = RD->getDestructor(); 9490 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9491 RD->hasUserDeclaredCopyConstructor() && 9492 !S.getLangOpts().MSVCCompat) { 9493 // Find any user-declared copy constructor. 9494 for (auto *I : RD->ctors()) { 9495 if (I->isCopyConstructor()) { 9496 UserDeclaredOperation = I; 9497 break; 9498 } 9499 } 9500 assert(UserDeclaredOperation); 9501 } else if (isa<CXXConstructorDecl>(CopyOp) && 9502 RD->hasUserDeclaredCopyAssignment() && 9503 !S.getLangOpts().MSVCCompat) { 9504 // Find any user-declared move assignment operator. 9505 for (auto *I : RD->methods()) { 9506 if (I->isCopyAssignmentOperator()) { 9507 UserDeclaredOperation = I; 9508 break; 9509 } 9510 } 9511 assert(UserDeclaredOperation); 9512 } 9513 9514 if (UserDeclaredOperation) { 9515 S.Diag(UserDeclaredOperation->getLocation(), 9516 diag::warn_deprecated_copy_operation) 9517 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9518 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9519 S.Diag(UseLoc, diag::note_member_synthesized_at) 9520 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9521 : Sema::CXXCopyAssignment) 9522 << RD; 9523 } 9524 } 9525 9526 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9527 CXXMethodDecl *CopyAssignOperator) { 9528 assert((CopyAssignOperator->isDefaulted() && 9529 CopyAssignOperator->isOverloadedOperator() && 9530 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9531 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9532 !CopyAssignOperator->isDeleted()) && 9533 "DefineImplicitCopyAssignment called for wrong function"); 9534 9535 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9536 9537 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9538 CopyAssignOperator->setInvalidDecl(); 9539 return; 9540 } 9541 9542 // C++11 [class.copy]p18: 9543 // The [definition of an implicitly declared copy assignment operator] is 9544 // deprecated if the class has a user-declared copy constructor or a 9545 // user-declared destructor. 9546 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9547 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9548 9549 CopyAssignOperator->markUsed(Context); 9550 9551 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9552 DiagnosticErrorTrap Trap(Diags); 9553 9554 // C++0x [class.copy]p30: 9555 // The implicitly-defined or explicitly-defaulted copy assignment operator 9556 // for a non-union class X performs memberwise copy assignment of its 9557 // subobjects. The direct base classes of X are assigned first, in the 9558 // order of their declaration in the base-specifier-list, and then the 9559 // immediate non-static data members of X are assigned, in the order in 9560 // which they were declared in the class definition. 9561 9562 // The statements that form the synthesized function body. 9563 SmallVector<Stmt*, 8> Statements; 9564 9565 // The parameter for the "other" object, which we are copying from. 9566 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9567 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9568 QualType OtherRefType = Other->getType(); 9569 if (const LValueReferenceType *OtherRef 9570 = OtherRefType->getAs<LValueReferenceType>()) { 9571 OtherRefType = OtherRef->getPointeeType(); 9572 OtherQuals = OtherRefType.getQualifiers(); 9573 } 9574 9575 // Our location for everything implicitly-generated. 9576 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 9577 ? CopyAssignOperator->getLocEnd() 9578 : CopyAssignOperator->getLocation(); 9579 9580 // Builds a DeclRefExpr for the "other" object. 9581 RefBuilder OtherRef(Other, OtherRefType); 9582 9583 // Builds the "this" pointer. 9584 ThisBuilder This; 9585 9586 // Assign base classes. 9587 bool Invalid = false; 9588 for (auto &Base : ClassDecl->bases()) { 9589 // Form the assignment: 9590 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9591 QualType BaseType = Base.getType().getUnqualifiedType(); 9592 if (!BaseType->isRecordType()) { 9593 Invalid = true; 9594 continue; 9595 } 9596 9597 CXXCastPath BasePath; 9598 BasePath.push_back(&Base); 9599 9600 // Construct the "from" expression, which is an implicit cast to the 9601 // appropriately-qualified base type. 9602 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9603 VK_LValue, BasePath); 9604 9605 // Dereference "this". 9606 DerefBuilder DerefThis(This); 9607 CastBuilder To(DerefThis, 9608 Context.getCVRQualifiedType( 9609 BaseType, CopyAssignOperator->getTypeQualifiers()), 9610 VK_LValue, BasePath); 9611 9612 // Build the copy. 9613 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9614 To, From, 9615 /*CopyingBaseSubobject=*/true, 9616 /*Copying=*/true); 9617 if (Copy.isInvalid()) { 9618 Diag(CurrentLocation, diag::note_member_synthesized_at) 9619 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9620 CopyAssignOperator->setInvalidDecl(); 9621 return; 9622 } 9623 9624 // Success! Record the copy. 9625 Statements.push_back(Copy.getAs<Expr>()); 9626 } 9627 9628 // Assign non-static members. 9629 for (auto *Field : ClassDecl->fields()) { 9630 if (Field->isUnnamedBitfield()) 9631 continue; 9632 9633 if (Field->isInvalidDecl()) { 9634 Invalid = true; 9635 continue; 9636 } 9637 9638 // Check for members of reference type; we can't copy those. 9639 if (Field->getType()->isReferenceType()) { 9640 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9641 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9642 Diag(Field->getLocation(), diag::note_declared_at); 9643 Diag(CurrentLocation, diag::note_member_synthesized_at) 9644 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9645 Invalid = true; 9646 continue; 9647 } 9648 9649 // Check for members of const-qualified, non-class type. 9650 QualType BaseType = Context.getBaseElementType(Field->getType()); 9651 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9652 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9653 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9654 Diag(Field->getLocation(), diag::note_declared_at); 9655 Diag(CurrentLocation, diag::note_member_synthesized_at) 9656 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9657 Invalid = true; 9658 continue; 9659 } 9660 9661 // Suppress assigning zero-width bitfields. 9662 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9663 continue; 9664 9665 QualType FieldType = Field->getType().getNonReferenceType(); 9666 if (FieldType->isIncompleteArrayType()) { 9667 assert(ClassDecl->hasFlexibleArrayMember() && 9668 "Incomplete array type is not valid"); 9669 continue; 9670 } 9671 9672 // Build references to the field in the object we're copying from and to. 9673 CXXScopeSpec SS; // Intentionally empty 9674 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9675 LookupMemberName); 9676 MemberLookup.addDecl(Field); 9677 MemberLookup.resolveKind(); 9678 9679 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9680 9681 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9682 9683 // Build the copy of this field. 9684 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9685 To, From, 9686 /*CopyingBaseSubobject=*/false, 9687 /*Copying=*/true); 9688 if (Copy.isInvalid()) { 9689 Diag(CurrentLocation, diag::note_member_synthesized_at) 9690 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9691 CopyAssignOperator->setInvalidDecl(); 9692 return; 9693 } 9694 9695 // Success! Record the copy. 9696 Statements.push_back(Copy.getAs<Stmt>()); 9697 } 9698 9699 if (!Invalid) { 9700 // Add a "return *this;" 9701 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9702 9703 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 9704 if (Return.isInvalid()) 9705 Invalid = true; 9706 else { 9707 Statements.push_back(Return.getAs<Stmt>()); 9708 9709 if (Trap.hasErrorOccurred()) { 9710 Diag(CurrentLocation, diag::note_member_synthesized_at) 9711 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9712 Invalid = true; 9713 } 9714 } 9715 } 9716 9717 if (Invalid) { 9718 CopyAssignOperator->setInvalidDecl(); 9719 return; 9720 } 9721 9722 StmtResult Body; 9723 { 9724 CompoundScopeRAII CompoundScope(*this); 9725 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9726 /*isStmtExpr=*/false); 9727 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9728 } 9729 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 9730 9731 if (ASTMutationListener *L = getASTMutationListener()) { 9732 L->CompletedImplicitDefinition(CopyAssignOperator); 9733 } 9734 } 9735 9736 Sema::ImplicitExceptionSpecification 9737 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9738 CXXRecordDecl *ClassDecl = MD->getParent(); 9739 9740 ImplicitExceptionSpecification ExceptSpec(*this); 9741 if (ClassDecl->isInvalidDecl()) 9742 return ExceptSpec; 9743 9744 // C++0x [except.spec]p14: 9745 // An implicitly declared special member function (Clause 12) shall have an 9746 // exception-specification. [...] 9747 9748 // It is unspecified whether or not an implicit move assignment operator 9749 // attempts to deduplicate calls to assignment operators of virtual bases are 9750 // made. As such, this exception specification is effectively unspecified. 9751 // Based on a similar decision made for constness in C++0x, we're erring on 9752 // the side of assuming such calls to be made regardless of whether they 9753 // actually happen. 9754 // Note that a move constructor is not implicitly declared when there are 9755 // virtual bases, but it can still be user-declared and explicitly defaulted. 9756 for (const auto &Base : ClassDecl->bases()) { 9757 if (Base.isVirtual()) 9758 continue; 9759 9760 CXXRecordDecl *BaseClassDecl 9761 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9762 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9763 0, false, 0)) 9764 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9765 } 9766 9767 for (const auto &Base : ClassDecl->vbases()) { 9768 CXXRecordDecl *BaseClassDecl 9769 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9770 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9771 0, false, 0)) 9772 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9773 } 9774 9775 for (const auto *Field : ClassDecl->fields()) { 9776 QualType FieldType = Context.getBaseElementType(Field->getType()); 9777 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9778 if (CXXMethodDecl *MoveAssign = 9779 LookupMovingAssignment(FieldClassDecl, 9780 FieldType.getCVRQualifiers(), 9781 false, 0)) 9782 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9783 } 9784 } 9785 9786 return ExceptSpec; 9787 } 9788 9789 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9790 assert(ClassDecl->needsImplicitMoveAssignment()); 9791 9792 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9793 if (DSM.isAlreadyBeingDeclared()) 9794 return nullptr; 9795 9796 // Note: The following rules are largely analoguous to the move 9797 // constructor rules. 9798 9799 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9800 QualType RetType = Context.getLValueReferenceType(ArgType); 9801 ArgType = Context.getRValueReferenceType(ArgType); 9802 9803 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9804 CXXMoveAssignment, 9805 false); 9806 9807 // An implicitly-declared move assignment operator is an inline public 9808 // member of its class. 9809 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9810 SourceLocation ClassLoc = ClassDecl->getLocation(); 9811 DeclarationNameInfo NameInfo(Name, ClassLoc); 9812 CXXMethodDecl *MoveAssignment = 9813 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9814 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9815 /*isInline=*/true, Constexpr, SourceLocation()); 9816 MoveAssignment->setAccess(AS_public); 9817 MoveAssignment->setDefaulted(); 9818 MoveAssignment->setImplicit(); 9819 9820 // Build an exception specification pointing back at this member. 9821 FunctionProtoType::ExtProtoInfo EPI = 9822 getImplicitMethodEPI(*this, MoveAssignment); 9823 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9824 9825 // Add the parameter to the operator. 9826 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9827 ClassLoc, ClassLoc, 9828 /*Id=*/nullptr, ArgType, 9829 /*TInfo=*/nullptr, SC_None, 9830 nullptr); 9831 MoveAssignment->setParams(FromParam); 9832 9833 AddOverriddenMethods(ClassDecl, MoveAssignment); 9834 9835 MoveAssignment->setTrivial( 9836 ClassDecl->needsOverloadResolutionForMoveAssignment() 9837 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9838 : ClassDecl->hasTrivialMoveAssignment()); 9839 9840 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9841 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 9842 SetDeclDeleted(MoveAssignment, ClassLoc); 9843 } 9844 9845 // Note that we have added this copy-assignment operator. 9846 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9847 9848 if (Scope *S = getScopeForContext(ClassDecl)) 9849 PushOnScopeChains(MoveAssignment, S, false); 9850 ClassDecl->addDecl(MoveAssignment); 9851 9852 return MoveAssignment; 9853 } 9854 9855 /// Check if we're implicitly defining a move assignment operator for a class 9856 /// with virtual bases. Such a move assignment might move-assign the virtual 9857 /// base multiple times. 9858 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 9859 SourceLocation CurrentLocation) { 9860 assert(!Class->isDependentContext() && "should not define dependent move"); 9861 9862 // Only a virtual base could get implicitly move-assigned multiple times. 9863 // Only a non-trivial move assignment can observe this. We only want to 9864 // diagnose if we implicitly define an assignment operator that assigns 9865 // two base classes, both of which move-assign the same virtual base. 9866 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 9867 Class->getNumBases() < 2) 9868 return; 9869 9870 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 9871 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 9872 VBaseMap VBases; 9873 9874 for (auto &BI : Class->bases()) { 9875 Worklist.push_back(&BI); 9876 while (!Worklist.empty()) { 9877 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 9878 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 9879 9880 // If the base has no non-trivial move assignment operators, 9881 // we don't care about moves from it. 9882 if (!Base->hasNonTrivialMoveAssignment()) 9883 continue; 9884 9885 // If there's nothing virtual here, skip it. 9886 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 9887 continue; 9888 9889 // If we're not actually going to call a move assignment for this base, 9890 // or the selected move assignment is trivial, skip it. 9891 Sema::SpecialMemberOverloadResult *SMOR = 9892 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 9893 /*ConstArg*/false, /*VolatileArg*/false, 9894 /*RValueThis*/true, /*ConstThis*/false, 9895 /*VolatileThis*/false); 9896 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 9897 !SMOR->getMethod()->isMoveAssignmentOperator()) 9898 continue; 9899 9900 if (BaseSpec->isVirtual()) { 9901 // We're going to move-assign this virtual base, and its move 9902 // assignment operator is not trivial. If this can happen for 9903 // multiple distinct direct bases of Class, diagnose it. (If it 9904 // only happens in one base, we'll diagnose it when synthesizing 9905 // that base class's move assignment operator.) 9906 CXXBaseSpecifier *&Existing = 9907 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 9908 .first->second; 9909 if (Existing && Existing != &BI) { 9910 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 9911 << Class << Base; 9912 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 9913 << (Base->getCanonicalDecl() == 9914 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9915 << Base << Existing->getType() << Existing->getSourceRange(); 9916 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 9917 << (Base->getCanonicalDecl() == 9918 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9919 << Base << BI.getType() << BaseSpec->getSourceRange(); 9920 9921 // Only diagnose each vbase once. 9922 Existing = nullptr; 9923 } 9924 } else { 9925 // Only walk over bases that have defaulted move assignment operators. 9926 // We assume that any user-provided move assignment operator handles 9927 // the multiple-moves-of-vbase case itself somehow. 9928 if (!SMOR->getMethod()->isDefaulted()) 9929 continue; 9930 9931 // We're going to move the base classes of Base. Add them to the list. 9932 for (auto &BI : Base->bases()) 9933 Worklist.push_back(&BI); 9934 } 9935 } 9936 } 9937 } 9938 9939 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9940 CXXMethodDecl *MoveAssignOperator) { 9941 assert((MoveAssignOperator->isDefaulted() && 9942 MoveAssignOperator->isOverloadedOperator() && 9943 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9944 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9945 !MoveAssignOperator->isDeleted()) && 9946 "DefineImplicitMoveAssignment called for wrong function"); 9947 9948 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9949 9950 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9951 MoveAssignOperator->setInvalidDecl(); 9952 return; 9953 } 9954 9955 MoveAssignOperator->markUsed(Context); 9956 9957 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9958 DiagnosticErrorTrap Trap(Diags); 9959 9960 // C++0x [class.copy]p28: 9961 // The implicitly-defined or move assignment operator for a non-union class 9962 // X performs memberwise move assignment of its subobjects. The direct base 9963 // classes of X are assigned first, in the order of their declaration in the 9964 // base-specifier-list, and then the immediate non-static data members of X 9965 // are assigned, in the order in which they were declared in the class 9966 // definition. 9967 9968 // Issue a warning if our implicit move assignment operator will move 9969 // from a virtual base more than once. 9970 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 9971 9972 // The statements that form the synthesized function body. 9973 SmallVector<Stmt*, 8> Statements; 9974 9975 // The parameter for the "other" object, which we are move from. 9976 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9977 QualType OtherRefType = Other->getType()-> 9978 getAs<RValueReferenceType>()->getPointeeType(); 9979 assert(!OtherRefType.getQualifiers() && 9980 "Bad argument type of defaulted move assignment"); 9981 9982 // Our location for everything implicitly-generated. 9983 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 9984 ? MoveAssignOperator->getLocEnd() 9985 : MoveAssignOperator->getLocation(); 9986 9987 // Builds a reference to the "other" object. 9988 RefBuilder OtherRef(Other, OtherRefType); 9989 // Cast to rvalue. 9990 MoveCastBuilder MoveOther(OtherRef); 9991 9992 // Builds the "this" pointer. 9993 ThisBuilder This; 9994 9995 // Assign base classes. 9996 bool Invalid = false; 9997 for (auto &Base : ClassDecl->bases()) { 9998 // C++11 [class.copy]p28: 9999 // It is unspecified whether subobjects representing virtual base classes 10000 // are assigned more than once by the implicitly-defined copy assignment 10001 // operator. 10002 // FIXME: Do not assign to a vbase that will be assigned by some other base 10003 // class. For a move-assignment, this can result in the vbase being moved 10004 // multiple times. 10005 10006 // Form the assignment: 10007 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10008 QualType BaseType = Base.getType().getUnqualifiedType(); 10009 if (!BaseType->isRecordType()) { 10010 Invalid = true; 10011 continue; 10012 } 10013 10014 CXXCastPath BasePath; 10015 BasePath.push_back(&Base); 10016 10017 // Construct the "from" expression, which is an implicit cast to the 10018 // appropriately-qualified base type. 10019 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10020 10021 // Dereference "this". 10022 DerefBuilder DerefThis(This); 10023 10024 // Implicitly cast "this" to the appropriately-qualified base type. 10025 CastBuilder To(DerefThis, 10026 Context.getCVRQualifiedType( 10027 BaseType, MoveAssignOperator->getTypeQualifiers()), 10028 VK_LValue, BasePath); 10029 10030 // Build the move. 10031 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10032 To, From, 10033 /*CopyingBaseSubobject=*/true, 10034 /*Copying=*/false); 10035 if (Move.isInvalid()) { 10036 Diag(CurrentLocation, diag::note_member_synthesized_at) 10037 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10038 MoveAssignOperator->setInvalidDecl(); 10039 return; 10040 } 10041 10042 // Success! Record the move. 10043 Statements.push_back(Move.getAs<Expr>()); 10044 } 10045 10046 // Assign non-static members. 10047 for (auto *Field : ClassDecl->fields()) { 10048 if (Field->isUnnamedBitfield()) 10049 continue; 10050 10051 if (Field->isInvalidDecl()) { 10052 Invalid = true; 10053 continue; 10054 } 10055 10056 // Check for members of reference type; we can't move those. 10057 if (Field->getType()->isReferenceType()) { 10058 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10059 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10060 Diag(Field->getLocation(), diag::note_declared_at); 10061 Diag(CurrentLocation, diag::note_member_synthesized_at) 10062 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10063 Invalid = true; 10064 continue; 10065 } 10066 10067 // Check for members of const-qualified, non-class type. 10068 QualType BaseType = Context.getBaseElementType(Field->getType()); 10069 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10070 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10071 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10072 Diag(Field->getLocation(), diag::note_declared_at); 10073 Diag(CurrentLocation, diag::note_member_synthesized_at) 10074 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10075 Invalid = true; 10076 continue; 10077 } 10078 10079 // Suppress assigning zero-width bitfields. 10080 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10081 continue; 10082 10083 QualType FieldType = Field->getType().getNonReferenceType(); 10084 if (FieldType->isIncompleteArrayType()) { 10085 assert(ClassDecl->hasFlexibleArrayMember() && 10086 "Incomplete array type is not valid"); 10087 continue; 10088 } 10089 10090 // Build references to the field in the object we're copying from and to. 10091 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10092 LookupMemberName); 10093 MemberLookup.addDecl(Field); 10094 MemberLookup.resolveKind(); 10095 MemberBuilder From(MoveOther, OtherRefType, 10096 /*IsArrow=*/false, MemberLookup); 10097 MemberBuilder To(This, getCurrentThisType(), 10098 /*IsArrow=*/true, MemberLookup); 10099 10100 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10101 "Member reference with rvalue base must be rvalue except for reference " 10102 "members, which aren't allowed for move assignment."); 10103 10104 // Build the move of this field. 10105 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10106 To, From, 10107 /*CopyingBaseSubobject=*/false, 10108 /*Copying=*/false); 10109 if (Move.isInvalid()) { 10110 Diag(CurrentLocation, diag::note_member_synthesized_at) 10111 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10112 MoveAssignOperator->setInvalidDecl(); 10113 return; 10114 } 10115 10116 // Success! Record the copy. 10117 Statements.push_back(Move.getAs<Stmt>()); 10118 } 10119 10120 if (!Invalid) { 10121 // Add a "return *this;" 10122 ExprResult ThisObj = 10123 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10124 10125 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10126 if (Return.isInvalid()) 10127 Invalid = true; 10128 else { 10129 Statements.push_back(Return.getAs<Stmt>()); 10130 10131 if (Trap.hasErrorOccurred()) { 10132 Diag(CurrentLocation, diag::note_member_synthesized_at) 10133 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10134 Invalid = true; 10135 } 10136 } 10137 } 10138 10139 if (Invalid) { 10140 MoveAssignOperator->setInvalidDecl(); 10141 return; 10142 } 10143 10144 StmtResult Body; 10145 { 10146 CompoundScopeRAII CompoundScope(*this); 10147 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10148 /*isStmtExpr=*/false); 10149 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10150 } 10151 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10152 10153 if (ASTMutationListener *L = getASTMutationListener()) { 10154 L->CompletedImplicitDefinition(MoveAssignOperator); 10155 } 10156 } 10157 10158 Sema::ImplicitExceptionSpecification 10159 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10160 CXXRecordDecl *ClassDecl = MD->getParent(); 10161 10162 ImplicitExceptionSpecification ExceptSpec(*this); 10163 if (ClassDecl->isInvalidDecl()) 10164 return ExceptSpec; 10165 10166 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10167 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10168 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10169 10170 // C++ [except.spec]p14: 10171 // An implicitly declared special member function (Clause 12) shall have an 10172 // exception-specification. [...] 10173 for (const auto &Base : ClassDecl->bases()) { 10174 // Virtual bases are handled below. 10175 if (Base.isVirtual()) 10176 continue; 10177 10178 CXXRecordDecl *BaseClassDecl 10179 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10180 if (CXXConstructorDecl *CopyConstructor = 10181 LookupCopyingConstructor(BaseClassDecl, Quals)) 10182 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10183 } 10184 for (const auto &Base : ClassDecl->vbases()) { 10185 CXXRecordDecl *BaseClassDecl 10186 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10187 if (CXXConstructorDecl *CopyConstructor = 10188 LookupCopyingConstructor(BaseClassDecl, Quals)) 10189 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10190 } 10191 for (const auto *Field : ClassDecl->fields()) { 10192 QualType FieldType = Context.getBaseElementType(Field->getType()); 10193 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10194 if (CXXConstructorDecl *CopyConstructor = 10195 LookupCopyingConstructor(FieldClassDecl, 10196 Quals | FieldType.getCVRQualifiers())) 10197 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10198 } 10199 } 10200 10201 return ExceptSpec; 10202 } 10203 10204 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10205 CXXRecordDecl *ClassDecl) { 10206 // C++ [class.copy]p4: 10207 // If the class definition does not explicitly declare a copy 10208 // constructor, one is declared implicitly. 10209 assert(ClassDecl->needsImplicitCopyConstructor()); 10210 10211 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10212 if (DSM.isAlreadyBeingDeclared()) 10213 return nullptr; 10214 10215 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10216 QualType ArgType = ClassType; 10217 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10218 if (Const) 10219 ArgType = ArgType.withConst(); 10220 ArgType = Context.getLValueReferenceType(ArgType); 10221 10222 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10223 CXXCopyConstructor, 10224 Const); 10225 10226 DeclarationName Name 10227 = Context.DeclarationNames.getCXXConstructorName( 10228 Context.getCanonicalType(ClassType)); 10229 SourceLocation ClassLoc = ClassDecl->getLocation(); 10230 DeclarationNameInfo NameInfo(Name, ClassLoc); 10231 10232 // An implicitly-declared copy constructor is an inline public 10233 // member of its class. 10234 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10235 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10236 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10237 Constexpr); 10238 CopyConstructor->setAccess(AS_public); 10239 CopyConstructor->setDefaulted(); 10240 10241 // Build an exception specification pointing back at this member. 10242 FunctionProtoType::ExtProtoInfo EPI = 10243 getImplicitMethodEPI(*this, CopyConstructor); 10244 CopyConstructor->setType( 10245 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10246 10247 // Add the parameter to the constructor. 10248 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10249 ClassLoc, ClassLoc, 10250 /*IdentifierInfo=*/nullptr, 10251 ArgType, /*TInfo=*/nullptr, 10252 SC_None, nullptr); 10253 CopyConstructor->setParams(FromParam); 10254 10255 CopyConstructor->setTrivial( 10256 ClassDecl->needsOverloadResolutionForCopyConstructor() 10257 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10258 : ClassDecl->hasTrivialCopyConstructor()); 10259 10260 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10261 SetDeclDeleted(CopyConstructor, ClassLoc); 10262 10263 // Note that we have declared this constructor. 10264 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10265 10266 if (Scope *S = getScopeForContext(ClassDecl)) 10267 PushOnScopeChains(CopyConstructor, S, false); 10268 ClassDecl->addDecl(CopyConstructor); 10269 10270 return CopyConstructor; 10271 } 10272 10273 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10274 CXXConstructorDecl *CopyConstructor) { 10275 assert((CopyConstructor->isDefaulted() && 10276 CopyConstructor->isCopyConstructor() && 10277 !CopyConstructor->doesThisDeclarationHaveABody() && 10278 !CopyConstructor->isDeleted()) && 10279 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10280 10281 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10282 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10283 10284 // C++11 [class.copy]p7: 10285 // The [definition of an implicitly declared copy constructor] is 10286 // deprecated if the class has a user-declared copy assignment operator 10287 // or a user-declared destructor. 10288 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10289 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10290 10291 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10292 DiagnosticErrorTrap Trap(Diags); 10293 10294 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10295 Trap.hasErrorOccurred()) { 10296 Diag(CurrentLocation, diag::note_member_synthesized_at) 10297 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10298 CopyConstructor->setInvalidDecl(); 10299 } else { 10300 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10301 ? CopyConstructor->getLocEnd() 10302 : CopyConstructor->getLocation(); 10303 Sema::CompoundScopeRAII CompoundScope(*this); 10304 CopyConstructor->setBody( 10305 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10306 } 10307 10308 CopyConstructor->markUsed(Context); 10309 if (ASTMutationListener *L = getASTMutationListener()) { 10310 L->CompletedImplicitDefinition(CopyConstructor); 10311 } 10312 } 10313 10314 Sema::ImplicitExceptionSpecification 10315 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10316 CXXRecordDecl *ClassDecl = MD->getParent(); 10317 10318 // C++ [except.spec]p14: 10319 // An implicitly declared special member function (Clause 12) shall have an 10320 // exception-specification. [...] 10321 ImplicitExceptionSpecification ExceptSpec(*this); 10322 if (ClassDecl->isInvalidDecl()) 10323 return ExceptSpec; 10324 10325 // Direct base-class constructors. 10326 for (const auto &B : ClassDecl->bases()) { 10327 if (B.isVirtual()) // Handled below. 10328 continue; 10329 10330 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10331 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10332 CXXConstructorDecl *Constructor = 10333 LookupMovingConstructor(BaseClassDecl, 0); 10334 // If this is a deleted function, add it anyway. This might be conformant 10335 // with the standard. This might not. I'm not sure. It might not matter. 10336 if (Constructor) 10337 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10338 } 10339 } 10340 10341 // Virtual base-class constructors. 10342 for (const auto &B : ClassDecl->vbases()) { 10343 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10344 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10345 CXXConstructorDecl *Constructor = 10346 LookupMovingConstructor(BaseClassDecl, 0); 10347 // If this is a deleted function, add it anyway. This might be conformant 10348 // with the standard. This might not. I'm not sure. It might not matter. 10349 if (Constructor) 10350 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10351 } 10352 } 10353 10354 // Field constructors. 10355 for (const auto *F : ClassDecl->fields()) { 10356 QualType FieldType = Context.getBaseElementType(F->getType()); 10357 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10358 CXXConstructorDecl *Constructor = 10359 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10360 // If this is a deleted function, add it anyway. This might be conformant 10361 // with the standard. This might not. I'm not sure. It might not matter. 10362 // In particular, the problem is that this function never gets called. It 10363 // might just be ill-formed because this function attempts to refer to 10364 // a deleted function here. 10365 if (Constructor) 10366 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10367 } 10368 } 10369 10370 return ExceptSpec; 10371 } 10372 10373 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10374 CXXRecordDecl *ClassDecl) { 10375 assert(ClassDecl->needsImplicitMoveConstructor()); 10376 10377 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10378 if (DSM.isAlreadyBeingDeclared()) 10379 return nullptr; 10380 10381 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10382 QualType ArgType = Context.getRValueReferenceType(ClassType); 10383 10384 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10385 CXXMoveConstructor, 10386 false); 10387 10388 DeclarationName Name 10389 = Context.DeclarationNames.getCXXConstructorName( 10390 Context.getCanonicalType(ClassType)); 10391 SourceLocation ClassLoc = ClassDecl->getLocation(); 10392 DeclarationNameInfo NameInfo(Name, ClassLoc); 10393 10394 // C++11 [class.copy]p11: 10395 // An implicitly-declared copy/move constructor is an inline public 10396 // member of its class. 10397 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10398 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10399 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10400 Constexpr); 10401 MoveConstructor->setAccess(AS_public); 10402 MoveConstructor->setDefaulted(); 10403 10404 // Build an exception specification pointing back at this member. 10405 FunctionProtoType::ExtProtoInfo EPI = 10406 getImplicitMethodEPI(*this, MoveConstructor); 10407 MoveConstructor->setType( 10408 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10409 10410 // Add the parameter to the constructor. 10411 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10412 ClassLoc, ClassLoc, 10413 /*IdentifierInfo=*/nullptr, 10414 ArgType, /*TInfo=*/nullptr, 10415 SC_None, nullptr); 10416 MoveConstructor->setParams(FromParam); 10417 10418 MoveConstructor->setTrivial( 10419 ClassDecl->needsOverloadResolutionForMoveConstructor() 10420 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10421 : ClassDecl->hasTrivialMoveConstructor()); 10422 10423 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10424 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10425 SetDeclDeleted(MoveConstructor, ClassLoc); 10426 } 10427 10428 // Note that we have declared this constructor. 10429 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10430 10431 if (Scope *S = getScopeForContext(ClassDecl)) 10432 PushOnScopeChains(MoveConstructor, S, false); 10433 ClassDecl->addDecl(MoveConstructor); 10434 10435 return MoveConstructor; 10436 } 10437 10438 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10439 CXXConstructorDecl *MoveConstructor) { 10440 assert((MoveConstructor->isDefaulted() && 10441 MoveConstructor->isMoveConstructor() && 10442 !MoveConstructor->doesThisDeclarationHaveABody() && 10443 !MoveConstructor->isDeleted()) && 10444 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10445 10446 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10447 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10448 10449 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10450 DiagnosticErrorTrap Trap(Diags); 10451 10452 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10453 Trap.hasErrorOccurred()) { 10454 Diag(CurrentLocation, diag::note_member_synthesized_at) 10455 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10456 MoveConstructor->setInvalidDecl(); 10457 } else { 10458 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 10459 ? MoveConstructor->getLocEnd() 10460 : MoveConstructor->getLocation(); 10461 Sema::CompoundScopeRAII CompoundScope(*this); 10462 MoveConstructor->setBody(ActOnCompoundStmt( 10463 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 10464 } 10465 10466 MoveConstructor->markUsed(Context); 10467 10468 if (ASTMutationListener *L = getASTMutationListener()) { 10469 L->CompletedImplicitDefinition(MoveConstructor); 10470 } 10471 } 10472 10473 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10474 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10475 } 10476 10477 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10478 SourceLocation CurrentLocation, 10479 CXXConversionDecl *Conv) { 10480 CXXRecordDecl *Lambda = Conv->getParent(); 10481 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10482 // If we are defining a specialization of a conversion to function-ptr 10483 // cache the deduced template arguments for this specialization 10484 // so that we can use them to retrieve the corresponding call-operator 10485 // and static-invoker. 10486 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 10487 10488 // Retrieve the corresponding call-operator specialization. 10489 if (Lambda->isGenericLambda()) { 10490 assert(Conv->isFunctionTemplateSpecialization()); 10491 FunctionTemplateDecl *CallOpTemplate = 10492 CallOp->getDescribedFunctionTemplate(); 10493 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10494 void *InsertPos = nullptr; 10495 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10496 DeducedTemplateArgs->data(), 10497 DeducedTemplateArgs->size(), 10498 InsertPos); 10499 assert(CallOpSpec && 10500 "Conversion operator must have a corresponding call operator"); 10501 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10502 } 10503 // Mark the call operator referenced (and add to pending instantiations 10504 // if necessary). 10505 // For both the conversion and static-invoker template specializations 10506 // we construct their body's in this function, so no need to add them 10507 // to the PendingInstantiations. 10508 MarkFunctionReferenced(CurrentLocation, CallOp); 10509 10510 SynthesizedFunctionScope Scope(*this, Conv); 10511 DiagnosticErrorTrap Trap(Diags); 10512 10513 // Retrieve the static invoker... 10514 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10515 // ... and get the corresponding specialization for a generic lambda. 10516 if (Lambda->isGenericLambda()) { 10517 assert(DeducedTemplateArgs && 10518 "Must have deduced template arguments from Conversion Operator"); 10519 FunctionTemplateDecl *InvokeTemplate = 10520 Invoker->getDescribedFunctionTemplate(); 10521 void *InsertPos = nullptr; 10522 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10523 DeducedTemplateArgs->data(), 10524 DeducedTemplateArgs->size(), 10525 InsertPos); 10526 assert(InvokeSpec && 10527 "Must have a corresponding static invoker specialization"); 10528 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10529 } 10530 // Construct the body of the conversion function { return __invoke; }. 10531 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10532 VK_LValue, Conv->getLocation()).get(); 10533 assert(FunctionRef && "Can't refer to __invoke function?"); 10534 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 10535 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10536 Conv->getLocation(), 10537 Conv->getLocation())); 10538 10539 Conv->markUsed(Context); 10540 Conv->setReferenced(); 10541 10542 // Fill in the __invoke function with a dummy implementation. IR generation 10543 // will fill in the actual details. 10544 Invoker->markUsed(Context); 10545 Invoker->setReferenced(); 10546 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10547 10548 if (ASTMutationListener *L = getASTMutationListener()) { 10549 L->CompletedImplicitDefinition(Conv); 10550 L->CompletedImplicitDefinition(Invoker); 10551 } 10552 } 10553 10554 10555 10556 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10557 SourceLocation CurrentLocation, 10558 CXXConversionDecl *Conv) 10559 { 10560 assert(!Conv->getParent()->isGenericLambda()); 10561 10562 Conv->markUsed(Context); 10563 10564 SynthesizedFunctionScope Scope(*this, Conv); 10565 DiagnosticErrorTrap Trap(Diags); 10566 10567 // Copy-initialize the lambda object as needed to capture it. 10568 Expr *This = ActOnCXXThis(CurrentLocation).get(); 10569 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 10570 10571 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10572 Conv->getLocation(), 10573 Conv, DerefThis); 10574 10575 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10576 // behavior. Note that only the general conversion function does this 10577 // (since it's unusable otherwise); in the case where we inline the 10578 // block literal, it has block literal lifetime semantics. 10579 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10580 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10581 CK_CopyAndAutoreleaseBlockObject, 10582 BuildBlock.get(), nullptr, VK_RValue); 10583 10584 if (BuildBlock.isInvalid()) { 10585 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10586 Conv->setInvalidDecl(); 10587 return; 10588 } 10589 10590 // Create the return statement that returns the block from the conversion 10591 // function. 10592 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 10593 if (Return.isInvalid()) { 10594 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10595 Conv->setInvalidDecl(); 10596 return; 10597 } 10598 10599 // Set the body of the conversion function. 10600 Stmt *ReturnS = Return.get(); 10601 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10602 Conv->getLocation(), 10603 Conv->getLocation())); 10604 10605 // We're done; notify the mutation listener, if any. 10606 if (ASTMutationListener *L = getASTMutationListener()) { 10607 L->CompletedImplicitDefinition(Conv); 10608 } 10609 } 10610 10611 /// \brief Determine whether the given list arguments contains exactly one 10612 /// "real" (non-default) argument. 10613 static bool hasOneRealArgument(MultiExprArg Args) { 10614 switch (Args.size()) { 10615 case 0: 10616 return false; 10617 10618 default: 10619 if (!Args[1]->isDefaultArgument()) 10620 return false; 10621 10622 // fall through 10623 case 1: 10624 return !Args[0]->isDefaultArgument(); 10625 } 10626 10627 return false; 10628 } 10629 10630 ExprResult 10631 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10632 CXXConstructorDecl *Constructor, 10633 MultiExprArg ExprArgs, 10634 bool HadMultipleCandidates, 10635 bool IsListInitialization, 10636 bool RequiresZeroInit, 10637 unsigned ConstructKind, 10638 SourceRange ParenRange) { 10639 bool Elidable = false; 10640 10641 // C++0x [class.copy]p34: 10642 // When certain criteria are met, an implementation is allowed to 10643 // omit the copy/move construction of a class object, even if the 10644 // copy/move constructor and/or destructor for the object have 10645 // side effects. [...] 10646 // - when a temporary class object that has not been bound to a 10647 // reference (12.2) would be copied/moved to a class object 10648 // with the same cv-unqualified type, the copy/move operation 10649 // can be omitted by constructing the temporary object 10650 // directly into the target of the omitted copy/move 10651 if (ConstructKind == CXXConstructExpr::CK_Complete && 10652 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10653 Expr *SubExpr = ExprArgs[0]; 10654 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10655 } 10656 10657 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10658 Elidable, ExprArgs, HadMultipleCandidates, 10659 IsListInitialization, RequiresZeroInit, 10660 ConstructKind, ParenRange); 10661 } 10662 10663 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10664 /// including handling of its default argument expressions. 10665 ExprResult 10666 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10667 CXXConstructorDecl *Constructor, bool Elidable, 10668 MultiExprArg ExprArgs, 10669 bool HadMultipleCandidates, 10670 bool IsListInitialization, 10671 bool RequiresZeroInit, 10672 unsigned ConstructKind, 10673 SourceRange ParenRange) { 10674 MarkFunctionReferenced(ConstructLoc, Constructor); 10675 return CXXConstructExpr::Create( 10676 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 10677 HadMultipleCandidates, IsListInitialization, RequiresZeroInit, 10678 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10679 ParenRange); 10680 } 10681 10682 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10683 if (VD->isInvalidDecl()) return; 10684 10685 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10686 if (ClassDecl->isInvalidDecl()) return; 10687 if (ClassDecl->hasIrrelevantDestructor()) return; 10688 if (ClassDecl->isDependentContext()) return; 10689 10690 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10691 MarkFunctionReferenced(VD->getLocation(), Destructor); 10692 CheckDestructorAccess(VD->getLocation(), Destructor, 10693 PDiag(diag::err_access_dtor_var) 10694 << VD->getDeclName() 10695 << VD->getType()); 10696 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10697 10698 if (Destructor->isTrivial()) return; 10699 if (!VD->hasGlobalStorage()) return; 10700 10701 // Emit warning for non-trivial dtor in global scope (a real global, 10702 // class-static, function-static). 10703 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10704 10705 // TODO: this should be re-enabled for static locals by !CXAAtExit 10706 if (!VD->isStaticLocal()) 10707 Diag(VD->getLocation(), diag::warn_global_destructor); 10708 } 10709 10710 /// \brief Given a constructor and the set of arguments provided for the 10711 /// constructor, convert the arguments and add any required default arguments 10712 /// to form a proper call to this constructor. 10713 /// 10714 /// \returns true if an error occurred, false otherwise. 10715 bool 10716 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10717 MultiExprArg ArgsPtr, 10718 SourceLocation Loc, 10719 SmallVectorImpl<Expr*> &ConvertedArgs, 10720 bool AllowExplicit, 10721 bool IsListInitialization) { 10722 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10723 unsigned NumArgs = ArgsPtr.size(); 10724 Expr **Args = ArgsPtr.data(); 10725 10726 const FunctionProtoType *Proto 10727 = Constructor->getType()->getAs<FunctionProtoType>(); 10728 assert(Proto && "Constructor without a prototype?"); 10729 unsigned NumParams = Proto->getNumParams(); 10730 10731 // If too few arguments are available, we'll fill in the rest with defaults. 10732 if (NumArgs < NumParams) 10733 ConvertedArgs.reserve(NumParams); 10734 else 10735 ConvertedArgs.reserve(NumArgs); 10736 10737 VariadicCallType CallType = 10738 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10739 SmallVector<Expr *, 8> AllArgs; 10740 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10741 Proto, 0, 10742 llvm::makeArrayRef(Args, NumArgs), 10743 AllArgs, 10744 CallType, AllowExplicit, 10745 IsListInitialization); 10746 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10747 10748 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10749 10750 CheckConstructorCall(Constructor, 10751 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10752 AllArgs.size()), 10753 Proto, Loc); 10754 10755 return Invalid; 10756 } 10757 10758 static inline bool 10759 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10760 const FunctionDecl *FnDecl) { 10761 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10762 if (isa<NamespaceDecl>(DC)) { 10763 return SemaRef.Diag(FnDecl->getLocation(), 10764 diag::err_operator_new_delete_declared_in_namespace) 10765 << FnDecl->getDeclName(); 10766 } 10767 10768 if (isa<TranslationUnitDecl>(DC) && 10769 FnDecl->getStorageClass() == SC_Static) { 10770 return SemaRef.Diag(FnDecl->getLocation(), 10771 diag::err_operator_new_delete_declared_static) 10772 << FnDecl->getDeclName(); 10773 } 10774 10775 return false; 10776 } 10777 10778 static inline bool 10779 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10780 CanQualType ExpectedResultType, 10781 CanQualType ExpectedFirstParamType, 10782 unsigned DependentParamTypeDiag, 10783 unsigned InvalidParamTypeDiag) { 10784 QualType ResultType = 10785 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 10786 10787 // Check that the result type is not dependent. 10788 if (ResultType->isDependentType()) 10789 return SemaRef.Diag(FnDecl->getLocation(), 10790 diag::err_operator_new_delete_dependent_result_type) 10791 << FnDecl->getDeclName() << ExpectedResultType; 10792 10793 // Check that the result type is what we expect. 10794 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10795 return SemaRef.Diag(FnDecl->getLocation(), 10796 diag::err_operator_new_delete_invalid_result_type) 10797 << FnDecl->getDeclName() << ExpectedResultType; 10798 10799 // A function template must have at least 2 parameters. 10800 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10801 return SemaRef.Diag(FnDecl->getLocation(), 10802 diag::err_operator_new_delete_template_too_few_parameters) 10803 << FnDecl->getDeclName(); 10804 10805 // The function decl must have at least 1 parameter. 10806 if (FnDecl->getNumParams() == 0) 10807 return SemaRef.Diag(FnDecl->getLocation(), 10808 diag::err_operator_new_delete_too_few_parameters) 10809 << FnDecl->getDeclName(); 10810 10811 // Check the first parameter type is not dependent. 10812 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10813 if (FirstParamType->isDependentType()) 10814 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10815 << FnDecl->getDeclName() << ExpectedFirstParamType; 10816 10817 // Check that the first parameter type is what we expect. 10818 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10819 ExpectedFirstParamType) 10820 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10821 << FnDecl->getDeclName() << ExpectedFirstParamType; 10822 10823 return false; 10824 } 10825 10826 static bool 10827 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10828 // C++ [basic.stc.dynamic.allocation]p1: 10829 // A program is ill-formed if an allocation function is declared in a 10830 // namespace scope other than global scope or declared static in global 10831 // scope. 10832 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10833 return true; 10834 10835 CanQualType SizeTy = 10836 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10837 10838 // C++ [basic.stc.dynamic.allocation]p1: 10839 // The return type shall be void*. The first parameter shall have type 10840 // std::size_t. 10841 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10842 SizeTy, 10843 diag::err_operator_new_dependent_param_type, 10844 diag::err_operator_new_param_type)) 10845 return true; 10846 10847 // C++ [basic.stc.dynamic.allocation]p1: 10848 // The first parameter shall not have an associated default argument. 10849 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10850 return SemaRef.Diag(FnDecl->getLocation(), 10851 diag::err_operator_new_default_arg) 10852 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10853 10854 return false; 10855 } 10856 10857 static bool 10858 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10859 // C++ [basic.stc.dynamic.deallocation]p1: 10860 // A program is ill-formed if deallocation functions are declared in a 10861 // namespace scope other than global scope or declared static in global 10862 // scope. 10863 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10864 return true; 10865 10866 // C++ [basic.stc.dynamic.deallocation]p2: 10867 // Each deallocation function shall return void and its first parameter 10868 // shall be void*. 10869 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10870 SemaRef.Context.VoidPtrTy, 10871 diag::err_operator_delete_dependent_param_type, 10872 diag::err_operator_delete_param_type)) 10873 return true; 10874 10875 return false; 10876 } 10877 10878 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 10879 /// of this overloaded operator is well-formed. If so, returns false; 10880 /// otherwise, emits appropriate diagnostics and returns true. 10881 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10882 assert(FnDecl && FnDecl->isOverloadedOperator() && 10883 "Expected an overloaded operator declaration"); 10884 10885 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10886 10887 // C++ [over.oper]p5: 10888 // The allocation and deallocation functions, operator new, 10889 // operator new[], operator delete and operator delete[], are 10890 // described completely in 3.7.3. The attributes and restrictions 10891 // found in the rest of this subclause do not apply to them unless 10892 // explicitly stated in 3.7.3. 10893 if (Op == OO_Delete || Op == OO_Array_Delete) 10894 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10895 10896 if (Op == OO_New || Op == OO_Array_New) 10897 return CheckOperatorNewDeclaration(*this, FnDecl); 10898 10899 // C++ [over.oper]p6: 10900 // An operator function shall either be a non-static member 10901 // function or be a non-member function and have at least one 10902 // parameter whose type is a class, a reference to a class, an 10903 // enumeration, or a reference to an enumeration. 10904 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10905 if (MethodDecl->isStatic()) 10906 return Diag(FnDecl->getLocation(), 10907 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10908 } else { 10909 bool ClassOrEnumParam = false; 10910 for (auto Param : FnDecl->params()) { 10911 QualType ParamType = Param->getType().getNonReferenceType(); 10912 if (ParamType->isDependentType() || ParamType->isRecordType() || 10913 ParamType->isEnumeralType()) { 10914 ClassOrEnumParam = true; 10915 break; 10916 } 10917 } 10918 10919 if (!ClassOrEnumParam) 10920 return Diag(FnDecl->getLocation(), 10921 diag::err_operator_overload_needs_class_or_enum) 10922 << FnDecl->getDeclName(); 10923 } 10924 10925 // C++ [over.oper]p8: 10926 // An operator function cannot have default arguments (8.3.6), 10927 // except where explicitly stated below. 10928 // 10929 // Only the function-call operator allows default arguments 10930 // (C++ [over.call]p1). 10931 if (Op != OO_Call) { 10932 for (auto Param : FnDecl->params()) { 10933 if (Param->hasDefaultArg()) 10934 return Diag(Param->getLocation(), 10935 diag::err_operator_overload_default_arg) 10936 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 10937 } 10938 } 10939 10940 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10941 { false, false, false } 10942 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10943 , { Unary, Binary, MemberOnly } 10944 #include "clang/Basic/OperatorKinds.def" 10945 }; 10946 10947 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10948 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10949 bool MustBeMemberOperator = OperatorUses[Op][2]; 10950 10951 // C++ [over.oper]p8: 10952 // [...] Operator functions cannot have more or fewer parameters 10953 // than the number required for the corresponding operator, as 10954 // described in the rest of this subclause. 10955 unsigned NumParams = FnDecl->getNumParams() 10956 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10957 if (Op != OO_Call && 10958 ((NumParams == 1 && !CanBeUnaryOperator) || 10959 (NumParams == 2 && !CanBeBinaryOperator) || 10960 (NumParams < 1) || (NumParams > 2))) { 10961 // We have the wrong number of parameters. 10962 unsigned ErrorKind; 10963 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10964 ErrorKind = 2; // 2 -> unary or binary. 10965 } else if (CanBeUnaryOperator) { 10966 ErrorKind = 0; // 0 -> unary 10967 } else { 10968 assert(CanBeBinaryOperator && 10969 "All non-call overloaded operators are unary or binary!"); 10970 ErrorKind = 1; // 1 -> binary 10971 } 10972 10973 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10974 << FnDecl->getDeclName() << NumParams << ErrorKind; 10975 } 10976 10977 // Overloaded operators other than operator() cannot be variadic. 10978 if (Op != OO_Call && 10979 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10980 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10981 << FnDecl->getDeclName(); 10982 } 10983 10984 // Some operators must be non-static member functions. 10985 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10986 return Diag(FnDecl->getLocation(), 10987 diag::err_operator_overload_must_be_member) 10988 << FnDecl->getDeclName(); 10989 } 10990 10991 // C++ [over.inc]p1: 10992 // The user-defined function called operator++ implements the 10993 // prefix and postfix ++ operator. If this function is a member 10994 // function with no parameters, or a non-member function with one 10995 // parameter of class or enumeration type, it defines the prefix 10996 // increment operator ++ for objects of that type. If the function 10997 // is a member function with one parameter (which shall be of type 10998 // int) or a non-member function with two parameters (the second 10999 // of which shall be of type int), it defines the postfix 11000 // increment operator ++ for objects of that type. 11001 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11002 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11003 QualType ParamType = LastParam->getType(); 11004 11005 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11006 !ParamType->isDependentType()) 11007 return Diag(LastParam->getLocation(), 11008 diag::err_operator_overload_post_incdec_must_be_int) 11009 << LastParam->getType() << (Op == OO_MinusMinus); 11010 } 11011 11012 return false; 11013 } 11014 11015 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11016 /// of this literal operator function is well-formed. If so, returns 11017 /// false; otherwise, emits appropriate diagnostics and returns true. 11018 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11019 if (isa<CXXMethodDecl>(FnDecl)) { 11020 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11021 << FnDecl->getDeclName(); 11022 return true; 11023 } 11024 11025 if (FnDecl->isExternC()) { 11026 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11027 return true; 11028 } 11029 11030 bool Valid = false; 11031 11032 // This might be the definition of a literal operator template. 11033 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11034 // This might be a specialization of a literal operator template. 11035 if (!TpDecl) 11036 TpDecl = FnDecl->getPrimaryTemplate(); 11037 11038 // template <char...> type operator "" name() and 11039 // template <class T, T...> type operator "" name() are the only valid 11040 // template signatures, and the only valid signatures with no parameters. 11041 if (TpDecl) { 11042 if (FnDecl->param_size() == 0) { 11043 // Must have one or two template parameters 11044 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11045 if (Params->size() == 1) { 11046 NonTypeTemplateParmDecl *PmDecl = 11047 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11048 11049 // The template parameter must be a char parameter pack. 11050 if (PmDecl && PmDecl->isTemplateParameterPack() && 11051 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11052 Valid = true; 11053 } else if (Params->size() == 2) { 11054 TemplateTypeParmDecl *PmType = 11055 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11056 NonTypeTemplateParmDecl *PmArgs = 11057 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11058 11059 // The second template parameter must be a parameter pack with the 11060 // first template parameter as its type. 11061 if (PmType && PmArgs && 11062 !PmType->isTemplateParameterPack() && 11063 PmArgs->isTemplateParameterPack()) { 11064 const TemplateTypeParmType *TArgs = 11065 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11066 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11067 TArgs->getIndex() == PmType->getIndex()) { 11068 Valid = true; 11069 if (ActiveTemplateInstantiations.empty()) 11070 Diag(FnDecl->getLocation(), 11071 diag::ext_string_literal_operator_template); 11072 } 11073 } 11074 } 11075 } 11076 } else if (FnDecl->param_size()) { 11077 // Check the first parameter 11078 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11079 11080 QualType T = (*Param)->getType().getUnqualifiedType(); 11081 11082 // unsigned long long int, long double, and any character type are allowed 11083 // as the only parameters. 11084 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11085 Context.hasSameType(T, Context.LongDoubleTy) || 11086 Context.hasSameType(T, Context.CharTy) || 11087 Context.hasSameType(T, Context.WideCharTy) || 11088 Context.hasSameType(T, Context.Char16Ty) || 11089 Context.hasSameType(T, Context.Char32Ty)) { 11090 if (++Param == FnDecl->param_end()) 11091 Valid = true; 11092 goto FinishedParams; 11093 } 11094 11095 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11096 const PointerType *PT = T->getAs<PointerType>(); 11097 if (!PT) 11098 goto FinishedParams; 11099 T = PT->getPointeeType(); 11100 if (!T.isConstQualified() || T.isVolatileQualified()) 11101 goto FinishedParams; 11102 T = T.getUnqualifiedType(); 11103 11104 // Move on to the second parameter; 11105 ++Param; 11106 11107 // If there is no second parameter, the first must be a const char * 11108 if (Param == FnDecl->param_end()) { 11109 if (Context.hasSameType(T, Context.CharTy)) 11110 Valid = true; 11111 goto FinishedParams; 11112 } 11113 11114 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11115 // are allowed as the first parameter to a two-parameter function 11116 if (!(Context.hasSameType(T, Context.CharTy) || 11117 Context.hasSameType(T, Context.WideCharTy) || 11118 Context.hasSameType(T, Context.Char16Ty) || 11119 Context.hasSameType(T, Context.Char32Ty))) 11120 goto FinishedParams; 11121 11122 // The second and final parameter must be an std::size_t 11123 T = (*Param)->getType().getUnqualifiedType(); 11124 if (Context.hasSameType(T, Context.getSizeType()) && 11125 ++Param == FnDecl->param_end()) 11126 Valid = true; 11127 } 11128 11129 // FIXME: This diagnostic is absolutely terrible. 11130 FinishedParams: 11131 if (!Valid) { 11132 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11133 << FnDecl->getDeclName(); 11134 return true; 11135 } 11136 11137 // A parameter-declaration-clause containing a default argument is not 11138 // equivalent to any of the permitted forms. 11139 for (auto Param : FnDecl->params()) { 11140 if (Param->hasDefaultArg()) { 11141 Diag(Param->getDefaultArgRange().getBegin(), 11142 diag::err_literal_operator_default_argument) 11143 << Param->getDefaultArgRange(); 11144 break; 11145 } 11146 } 11147 11148 StringRef LiteralName 11149 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11150 if (LiteralName[0] != '_') { 11151 // C++11 [usrlit.suffix]p1: 11152 // Literal suffix identifiers that do not start with an underscore 11153 // are reserved for future standardization. 11154 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11155 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11156 } 11157 11158 return false; 11159 } 11160 11161 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11162 /// linkage specification, including the language and (if present) 11163 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11164 /// language string literal. LBraceLoc, if valid, provides the location of 11165 /// the '{' brace. Otherwise, this linkage specification does not 11166 /// have any braces. 11167 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11168 Expr *LangStr, 11169 SourceLocation LBraceLoc) { 11170 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11171 if (!Lit->isAscii()) { 11172 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11173 << LangStr->getSourceRange(); 11174 return nullptr; 11175 } 11176 11177 StringRef Lang = Lit->getString(); 11178 LinkageSpecDecl::LanguageIDs Language; 11179 if (Lang == "C") 11180 Language = LinkageSpecDecl::lang_c; 11181 else if (Lang == "C++") 11182 Language = LinkageSpecDecl::lang_cxx; 11183 else { 11184 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11185 << LangStr->getSourceRange(); 11186 return nullptr; 11187 } 11188 11189 // FIXME: Add all the various semantics of linkage specifications 11190 11191 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11192 LangStr->getExprLoc(), Language, 11193 LBraceLoc.isValid()); 11194 CurContext->addDecl(D); 11195 PushDeclContext(S, D); 11196 return D; 11197 } 11198 11199 /// ActOnFinishLinkageSpecification - Complete the definition of 11200 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11201 /// valid, it's the position of the closing '}' brace in a linkage 11202 /// specification that uses braces. 11203 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11204 Decl *LinkageSpec, 11205 SourceLocation RBraceLoc) { 11206 if (RBraceLoc.isValid()) { 11207 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11208 LSDecl->setRBraceLoc(RBraceLoc); 11209 } 11210 PopDeclContext(); 11211 return LinkageSpec; 11212 } 11213 11214 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11215 AttributeList *AttrList, 11216 SourceLocation SemiLoc) { 11217 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11218 // Attribute declarations appertain to empty declaration so we handle 11219 // them here. 11220 if (AttrList) 11221 ProcessDeclAttributeList(S, ED, AttrList); 11222 11223 CurContext->addDecl(ED); 11224 return ED; 11225 } 11226 11227 /// \brief Perform semantic analysis for the variable declaration that 11228 /// occurs within a C++ catch clause, returning the newly-created 11229 /// variable. 11230 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11231 TypeSourceInfo *TInfo, 11232 SourceLocation StartLoc, 11233 SourceLocation Loc, 11234 IdentifierInfo *Name) { 11235 bool Invalid = false; 11236 QualType ExDeclType = TInfo->getType(); 11237 11238 // Arrays and functions decay. 11239 if (ExDeclType->isArrayType()) 11240 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11241 else if (ExDeclType->isFunctionType()) 11242 ExDeclType = Context.getPointerType(ExDeclType); 11243 11244 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11245 // The exception-declaration shall not denote a pointer or reference to an 11246 // incomplete type, other than [cv] void*. 11247 // N2844 forbids rvalue references. 11248 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11249 Diag(Loc, diag::err_catch_rvalue_ref); 11250 Invalid = true; 11251 } 11252 11253 QualType BaseType = ExDeclType; 11254 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11255 unsigned DK = diag::err_catch_incomplete; 11256 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11257 BaseType = Ptr->getPointeeType(); 11258 Mode = 1; 11259 DK = diag::err_catch_incomplete_ptr; 11260 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11261 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11262 BaseType = Ref->getPointeeType(); 11263 Mode = 2; 11264 DK = diag::err_catch_incomplete_ref; 11265 } 11266 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11267 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11268 Invalid = true; 11269 11270 if (!Invalid && !ExDeclType->isDependentType() && 11271 RequireNonAbstractType(Loc, ExDeclType, 11272 diag::err_abstract_type_in_decl, 11273 AbstractVariableType)) 11274 Invalid = true; 11275 11276 // Only the non-fragile NeXT runtime currently supports C++ catches 11277 // of ObjC types, and no runtime supports catching ObjC types by value. 11278 if (!Invalid && getLangOpts().ObjC1) { 11279 QualType T = ExDeclType; 11280 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11281 T = RT->getPointeeType(); 11282 11283 if (T->isObjCObjectType()) { 11284 Diag(Loc, diag::err_objc_object_catch); 11285 Invalid = true; 11286 } else if (T->isObjCObjectPointerType()) { 11287 // FIXME: should this be a test for macosx-fragile specifically? 11288 if (getLangOpts().ObjCRuntime.isFragile()) 11289 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11290 } 11291 } 11292 11293 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11294 ExDeclType, TInfo, SC_None); 11295 ExDecl->setExceptionVariable(true); 11296 11297 // In ARC, infer 'retaining' for variables of retainable type. 11298 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11299 Invalid = true; 11300 11301 if (!Invalid && !ExDeclType->isDependentType()) { 11302 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11303 // Insulate this from anything else we might currently be parsing. 11304 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11305 11306 // C++ [except.handle]p16: 11307 // The object declared in an exception-declaration or, if the 11308 // exception-declaration does not specify a name, a temporary (12.2) is 11309 // copy-initialized (8.5) from the exception object. [...] 11310 // The object is destroyed when the handler exits, after the destruction 11311 // of any automatic objects initialized within the handler. 11312 // 11313 // We just pretend to initialize the object with itself, then make sure 11314 // it can be destroyed later. 11315 QualType initType = ExDeclType; 11316 11317 InitializedEntity entity = 11318 InitializedEntity::InitializeVariable(ExDecl); 11319 InitializationKind initKind = 11320 InitializationKind::CreateCopy(Loc, SourceLocation()); 11321 11322 Expr *opaqueValue = 11323 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11324 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11325 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11326 if (result.isInvalid()) 11327 Invalid = true; 11328 else { 11329 // If the constructor used was non-trivial, set this as the 11330 // "initializer". 11331 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11332 if (!construct->getConstructor()->isTrivial()) { 11333 Expr *init = MaybeCreateExprWithCleanups(construct); 11334 ExDecl->setInit(init); 11335 } 11336 11337 // And make sure it's destructable. 11338 FinalizeVarWithDestructor(ExDecl, recordType); 11339 } 11340 } 11341 } 11342 11343 if (Invalid) 11344 ExDecl->setInvalidDecl(); 11345 11346 return ExDecl; 11347 } 11348 11349 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11350 /// handler. 11351 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11352 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11353 bool Invalid = D.isInvalidType(); 11354 11355 // Check for unexpanded parameter packs. 11356 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11357 UPPC_ExceptionType)) { 11358 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11359 D.getIdentifierLoc()); 11360 Invalid = true; 11361 } 11362 11363 IdentifierInfo *II = D.getIdentifier(); 11364 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11365 LookupOrdinaryName, 11366 ForRedeclaration)) { 11367 // The scope should be freshly made just for us. There is just no way 11368 // it contains any previous declaration, except for function parameters in 11369 // a function-try-block's catch statement. 11370 assert(!S->isDeclScope(PrevDecl)); 11371 if (isDeclInScope(PrevDecl, CurContext, S)) { 11372 Diag(D.getIdentifierLoc(), diag::err_redefinition) 11373 << D.getIdentifier(); 11374 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11375 Invalid = true; 11376 } else if (PrevDecl->isTemplateParameter()) 11377 // Maybe we will complain about the shadowed template parameter. 11378 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11379 } 11380 11381 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11382 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11383 << D.getCXXScopeSpec().getRange(); 11384 Invalid = true; 11385 } 11386 11387 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11388 D.getLocStart(), 11389 D.getIdentifierLoc(), 11390 D.getIdentifier()); 11391 if (Invalid) 11392 ExDecl->setInvalidDecl(); 11393 11394 // Add the exception declaration into this scope. 11395 if (II) 11396 PushOnScopeChains(ExDecl, S); 11397 else 11398 CurContext->addDecl(ExDecl); 11399 11400 ProcessDeclAttributes(S, ExDecl, D); 11401 return ExDecl; 11402 } 11403 11404 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11405 Expr *AssertExpr, 11406 Expr *AssertMessageExpr, 11407 SourceLocation RParenLoc) { 11408 StringLiteral *AssertMessage = 11409 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 11410 11411 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11412 return nullptr; 11413 11414 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11415 AssertMessage, RParenLoc, false); 11416 } 11417 11418 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11419 Expr *AssertExpr, 11420 StringLiteral *AssertMessage, 11421 SourceLocation RParenLoc, 11422 bool Failed) { 11423 assert(AssertExpr != nullptr && "Expected non-null condition"); 11424 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11425 !Failed) { 11426 // In a static_assert-declaration, the constant-expression shall be a 11427 // constant expression that can be contextually converted to bool. 11428 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11429 if (Converted.isInvalid()) 11430 Failed = true; 11431 11432 llvm::APSInt Cond; 11433 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11434 diag::err_static_assert_expression_is_not_constant, 11435 /*AllowFold=*/false).isInvalid()) 11436 Failed = true; 11437 11438 if (!Failed && !Cond) { 11439 SmallString<256> MsgBuffer; 11440 llvm::raw_svector_ostream Msg(MsgBuffer); 11441 if (AssertMessage) 11442 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 11443 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11444 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 11445 Failed = true; 11446 } 11447 } 11448 11449 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11450 AssertExpr, AssertMessage, RParenLoc, 11451 Failed); 11452 11453 CurContext->addDecl(Decl); 11454 return Decl; 11455 } 11456 11457 /// \brief Perform semantic analysis of the given friend type declaration. 11458 /// 11459 /// \returns A friend declaration that. 11460 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11461 SourceLocation FriendLoc, 11462 TypeSourceInfo *TSInfo) { 11463 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11464 11465 QualType T = TSInfo->getType(); 11466 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11467 11468 // C++03 [class.friend]p2: 11469 // An elaborated-type-specifier shall be used in a friend declaration 11470 // for a class.* 11471 // 11472 // * The class-key of the elaborated-type-specifier is required. 11473 if (!ActiveTemplateInstantiations.empty()) { 11474 // Do not complain about the form of friend template types during 11475 // template instantiation; we will already have complained when the 11476 // template was declared. 11477 } else { 11478 if (!T->isElaboratedTypeSpecifier()) { 11479 // If we evaluated the type to a record type, suggest putting 11480 // a tag in front. 11481 if (const RecordType *RT = T->getAs<RecordType>()) { 11482 RecordDecl *RD = RT->getDecl(); 11483 11484 SmallString<16> InsertionText(" "); 11485 InsertionText += RD->getKindName(); 11486 11487 Diag(TypeRange.getBegin(), 11488 getLangOpts().CPlusPlus11 ? 11489 diag::warn_cxx98_compat_unelaborated_friend_type : 11490 diag::ext_unelaborated_friend_type) 11491 << (unsigned) RD->getTagKind() 11492 << T 11493 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11494 InsertionText); 11495 } else { 11496 Diag(FriendLoc, 11497 getLangOpts().CPlusPlus11 ? 11498 diag::warn_cxx98_compat_nonclass_type_friend : 11499 diag::ext_nonclass_type_friend) 11500 << T 11501 << TypeRange; 11502 } 11503 } else if (T->getAs<EnumType>()) { 11504 Diag(FriendLoc, 11505 getLangOpts().CPlusPlus11 ? 11506 diag::warn_cxx98_compat_enum_friend : 11507 diag::ext_enum_friend) 11508 << T 11509 << TypeRange; 11510 } 11511 11512 // C++11 [class.friend]p3: 11513 // A friend declaration that does not declare a function shall have one 11514 // of the following forms: 11515 // friend elaborated-type-specifier ; 11516 // friend simple-type-specifier ; 11517 // friend typename-specifier ; 11518 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11519 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11520 } 11521 11522 // If the type specifier in a friend declaration designates a (possibly 11523 // cv-qualified) class type, that class is declared as a friend; otherwise, 11524 // the friend declaration is ignored. 11525 return FriendDecl::Create(Context, CurContext, 11526 TSInfo->getTypeLoc().getLocStart(), TSInfo, 11527 FriendLoc); 11528 } 11529 11530 /// Handle a friend tag declaration where the scope specifier was 11531 /// templated. 11532 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11533 unsigned TagSpec, SourceLocation TagLoc, 11534 CXXScopeSpec &SS, 11535 IdentifierInfo *Name, 11536 SourceLocation NameLoc, 11537 AttributeList *Attr, 11538 MultiTemplateParamsArg TempParamLists) { 11539 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11540 11541 bool isExplicitSpecialization = false; 11542 bool Invalid = false; 11543 11544 if (TemplateParameterList *TemplateParams = 11545 MatchTemplateParametersToScopeSpecifier( 11546 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 11547 isExplicitSpecialization, Invalid)) { 11548 if (TemplateParams->size() > 0) { 11549 // This is a declaration of a class template. 11550 if (Invalid) 11551 return nullptr; 11552 11553 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11554 SS, Name, NameLoc, Attr, 11555 TemplateParams, AS_public, 11556 /*ModulePrivateLoc=*/SourceLocation(), 11557 TempParamLists.size() - 1, 11558 TempParamLists.data()).get(); 11559 } else { 11560 // The "template<>" header is extraneous. 11561 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11562 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11563 isExplicitSpecialization = true; 11564 } 11565 } 11566 11567 if (Invalid) return nullptr; 11568 11569 bool isAllExplicitSpecializations = true; 11570 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11571 if (TempParamLists[I]->size()) { 11572 isAllExplicitSpecializations = false; 11573 break; 11574 } 11575 } 11576 11577 // FIXME: don't ignore attributes. 11578 11579 // If it's explicit specializations all the way down, just forget 11580 // about the template header and build an appropriate non-templated 11581 // friend. TODO: for source fidelity, remember the headers. 11582 if (isAllExplicitSpecializations) { 11583 if (SS.isEmpty()) { 11584 bool Owned = false; 11585 bool IsDependent = false; 11586 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11587 Attr, AS_public, 11588 /*ModulePrivateLoc=*/SourceLocation(), 11589 MultiTemplateParamsArg(), Owned, IsDependent, 11590 /*ScopedEnumKWLoc=*/SourceLocation(), 11591 /*ScopedEnumUsesClassTag=*/false, 11592 /*UnderlyingType=*/TypeResult(), 11593 /*IsTypeSpecifier=*/false); 11594 } 11595 11596 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11597 ElaboratedTypeKeyword Keyword 11598 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11599 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11600 *Name, NameLoc); 11601 if (T.isNull()) 11602 return nullptr; 11603 11604 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11605 if (isa<DependentNameType>(T)) { 11606 DependentNameTypeLoc TL = 11607 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11608 TL.setElaboratedKeywordLoc(TagLoc); 11609 TL.setQualifierLoc(QualifierLoc); 11610 TL.setNameLoc(NameLoc); 11611 } else { 11612 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11613 TL.setElaboratedKeywordLoc(TagLoc); 11614 TL.setQualifierLoc(QualifierLoc); 11615 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11616 } 11617 11618 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11619 TSI, FriendLoc, TempParamLists); 11620 Friend->setAccess(AS_public); 11621 CurContext->addDecl(Friend); 11622 return Friend; 11623 } 11624 11625 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11626 11627 11628 11629 // Handle the case of a templated-scope friend class. e.g. 11630 // template <class T> class A<T>::B; 11631 // FIXME: we don't support these right now. 11632 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 11633 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 11634 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11635 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11636 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11637 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11638 TL.setElaboratedKeywordLoc(TagLoc); 11639 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11640 TL.setNameLoc(NameLoc); 11641 11642 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11643 TSI, FriendLoc, TempParamLists); 11644 Friend->setAccess(AS_public); 11645 Friend->setUnsupportedFriend(true); 11646 CurContext->addDecl(Friend); 11647 return Friend; 11648 } 11649 11650 11651 /// Handle a friend type declaration. This works in tandem with 11652 /// ActOnTag. 11653 /// 11654 /// Notes on friend class templates: 11655 /// 11656 /// We generally treat friend class declarations as if they were 11657 /// declaring a class. So, for example, the elaborated type specifier 11658 /// in a friend declaration is required to obey the restrictions of a 11659 /// class-head (i.e. no typedefs in the scope chain), template 11660 /// parameters are required to match up with simple template-ids, &c. 11661 /// However, unlike when declaring a template specialization, it's 11662 /// okay to refer to a template specialization without an empty 11663 /// template parameter declaration, e.g. 11664 /// friend class A<T>::B<unsigned>; 11665 /// We permit this as a special case; if there are any template 11666 /// parameters present at all, require proper matching, i.e. 11667 /// template <> template \<class T> friend class A<int>::B; 11668 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11669 MultiTemplateParamsArg TempParams) { 11670 SourceLocation Loc = DS.getLocStart(); 11671 11672 assert(DS.isFriendSpecified()); 11673 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11674 11675 // Try to convert the decl specifier to a type. This works for 11676 // friend templates because ActOnTag never produces a ClassTemplateDecl 11677 // for a TUK_Friend. 11678 Declarator TheDeclarator(DS, Declarator::MemberContext); 11679 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11680 QualType T = TSI->getType(); 11681 if (TheDeclarator.isInvalidType()) 11682 return nullptr; 11683 11684 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11685 return nullptr; 11686 11687 // This is definitely an error in C++98. It's probably meant to 11688 // be forbidden in C++0x, too, but the specification is just 11689 // poorly written. 11690 // 11691 // The problem is with declarations like the following: 11692 // template <T> friend A<T>::foo; 11693 // where deciding whether a class C is a friend or not now hinges 11694 // on whether there exists an instantiation of A that causes 11695 // 'foo' to equal C. There are restrictions on class-heads 11696 // (which we declare (by fiat) elaborated friend declarations to 11697 // be) that makes this tractable. 11698 // 11699 // FIXME: handle "template <> friend class A<T>;", which 11700 // is possibly well-formed? Who even knows? 11701 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11702 Diag(Loc, diag::err_tagless_friend_type_template) 11703 << DS.getSourceRange(); 11704 return nullptr; 11705 } 11706 11707 // C++98 [class.friend]p1: A friend of a class is a function 11708 // or class that is not a member of the class . . . 11709 // This is fixed in DR77, which just barely didn't make the C++03 11710 // deadline. It's also a very silly restriction that seriously 11711 // affects inner classes and which nobody else seems to implement; 11712 // thus we never diagnose it, not even in -pedantic. 11713 // 11714 // But note that we could warn about it: it's always useless to 11715 // friend one of your own members (it's not, however, worthless to 11716 // friend a member of an arbitrary specialization of your template). 11717 11718 Decl *D; 11719 if (unsigned NumTempParamLists = TempParams.size()) 11720 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11721 NumTempParamLists, 11722 TempParams.data(), 11723 TSI, 11724 DS.getFriendSpecLoc()); 11725 else 11726 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11727 11728 if (!D) 11729 return nullptr; 11730 11731 D->setAccess(AS_public); 11732 CurContext->addDecl(D); 11733 11734 return D; 11735 } 11736 11737 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11738 MultiTemplateParamsArg TemplateParams) { 11739 const DeclSpec &DS = D.getDeclSpec(); 11740 11741 assert(DS.isFriendSpecified()); 11742 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11743 11744 SourceLocation Loc = D.getIdentifierLoc(); 11745 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11746 11747 // C++ [class.friend]p1 11748 // A friend of a class is a function or class.... 11749 // Note that this sees through typedefs, which is intended. 11750 // It *doesn't* see through dependent types, which is correct 11751 // according to [temp.arg.type]p3: 11752 // If a declaration acquires a function type through a 11753 // type dependent on a template-parameter and this causes 11754 // a declaration that does not use the syntactic form of a 11755 // function declarator to have a function type, the program 11756 // is ill-formed. 11757 if (!TInfo->getType()->isFunctionType()) { 11758 Diag(Loc, diag::err_unexpected_friend); 11759 11760 // It might be worthwhile to try to recover by creating an 11761 // appropriate declaration. 11762 return nullptr; 11763 } 11764 11765 // C++ [namespace.memdef]p3 11766 // - If a friend declaration in a non-local class first declares a 11767 // class or function, the friend class or function is a member 11768 // of the innermost enclosing namespace. 11769 // - The name of the friend is not found by simple name lookup 11770 // until a matching declaration is provided in that namespace 11771 // scope (either before or after the class declaration granting 11772 // friendship). 11773 // - If a friend function is called, its name may be found by the 11774 // name lookup that considers functions from namespaces and 11775 // classes associated with the types of the function arguments. 11776 // - When looking for a prior declaration of a class or a function 11777 // declared as a friend, scopes outside the innermost enclosing 11778 // namespace scope are not considered. 11779 11780 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11781 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11782 DeclarationName Name = NameInfo.getName(); 11783 assert(Name); 11784 11785 // Check for unexpanded parameter packs. 11786 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11787 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11788 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11789 return nullptr; 11790 11791 // The context we found the declaration in, or in which we should 11792 // create the declaration. 11793 DeclContext *DC; 11794 Scope *DCScope = S; 11795 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11796 ForRedeclaration); 11797 11798 // There are five cases here. 11799 // - There's no scope specifier and we're in a local class. Only look 11800 // for functions declared in the immediately-enclosing block scope. 11801 // We recover from invalid scope qualifiers as if they just weren't there. 11802 FunctionDecl *FunctionContainingLocalClass = nullptr; 11803 if ((SS.isInvalid() || !SS.isSet()) && 11804 (FunctionContainingLocalClass = 11805 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11806 // C++11 [class.friend]p11: 11807 // If a friend declaration appears in a local class and the name 11808 // specified is an unqualified name, a prior declaration is 11809 // looked up without considering scopes that are outside the 11810 // innermost enclosing non-class scope. For a friend function 11811 // declaration, if there is no prior declaration, the program is 11812 // ill-formed. 11813 11814 // Find the innermost enclosing non-class scope. This is the block 11815 // scope containing the local class definition (or for a nested class, 11816 // the outer local class). 11817 DCScope = S->getFnParent(); 11818 11819 // Look up the function name in the scope. 11820 Previous.clear(LookupLocalFriendName); 11821 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11822 11823 if (!Previous.empty()) { 11824 // All possible previous declarations must have the same context: 11825 // either they were declared at block scope or they are members of 11826 // one of the enclosing local classes. 11827 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11828 } else { 11829 // This is ill-formed, but provide the context that we would have 11830 // declared the function in, if we were permitted to, for error recovery. 11831 DC = FunctionContainingLocalClass; 11832 } 11833 adjustContextForLocalExternDecl(DC); 11834 11835 // C++ [class.friend]p6: 11836 // A function can be defined in a friend declaration of a class if and 11837 // only if the class is a non-local class (9.8), the function name is 11838 // unqualified, and the function has namespace scope. 11839 if (D.isFunctionDefinition()) { 11840 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11841 } 11842 11843 // - There's no scope specifier, in which case we just go to the 11844 // appropriate scope and look for a function or function template 11845 // there as appropriate. 11846 } else if (SS.isInvalid() || !SS.isSet()) { 11847 // C++11 [namespace.memdef]p3: 11848 // If the name in a friend declaration is neither qualified nor 11849 // a template-id and the declaration is a function or an 11850 // elaborated-type-specifier, the lookup to determine whether 11851 // the entity has been previously declared shall not consider 11852 // any scopes outside the innermost enclosing namespace. 11853 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11854 11855 // Find the appropriate context according to the above. 11856 DC = CurContext; 11857 11858 // Skip class contexts. If someone can cite chapter and verse 11859 // for this behavior, that would be nice --- it's what GCC and 11860 // EDG do, and it seems like a reasonable intent, but the spec 11861 // really only says that checks for unqualified existing 11862 // declarations should stop at the nearest enclosing namespace, 11863 // not that they should only consider the nearest enclosing 11864 // namespace. 11865 while (DC->isRecord()) 11866 DC = DC->getParent(); 11867 11868 DeclContext *LookupDC = DC; 11869 while (LookupDC->isTransparentContext()) 11870 LookupDC = LookupDC->getParent(); 11871 11872 while (true) { 11873 LookupQualifiedName(Previous, LookupDC); 11874 11875 if (!Previous.empty()) { 11876 DC = LookupDC; 11877 break; 11878 } 11879 11880 if (isTemplateId) { 11881 if (isa<TranslationUnitDecl>(LookupDC)) break; 11882 } else { 11883 if (LookupDC->isFileContext()) break; 11884 } 11885 LookupDC = LookupDC->getParent(); 11886 } 11887 11888 DCScope = getScopeForDeclContext(S, DC); 11889 11890 // - There's a non-dependent scope specifier, in which case we 11891 // compute it and do a previous lookup there for a function 11892 // or function template. 11893 } else if (!SS.getScopeRep()->isDependent()) { 11894 DC = computeDeclContext(SS); 11895 if (!DC) return nullptr; 11896 11897 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 11898 11899 LookupQualifiedName(Previous, DC); 11900 11901 // Ignore things found implicitly in the wrong scope. 11902 // TODO: better diagnostics for this case. Suggesting the right 11903 // qualified scope would be nice... 11904 LookupResult::Filter F = Previous.makeFilter(); 11905 while (F.hasNext()) { 11906 NamedDecl *D = F.next(); 11907 if (!DC->InEnclosingNamespaceSetOf( 11908 D->getDeclContext()->getRedeclContext())) 11909 F.erase(); 11910 } 11911 F.done(); 11912 11913 if (Previous.empty()) { 11914 D.setInvalidType(); 11915 Diag(Loc, diag::err_qualified_friend_not_found) 11916 << Name << TInfo->getType(); 11917 return nullptr; 11918 } 11919 11920 // C++ [class.friend]p1: A friend of a class is a function or 11921 // class that is not a member of the class . . . 11922 if (DC->Equals(CurContext)) 11923 Diag(DS.getFriendSpecLoc(), 11924 getLangOpts().CPlusPlus11 ? 11925 diag::warn_cxx98_compat_friend_is_member : 11926 diag::err_friend_is_member); 11927 11928 if (D.isFunctionDefinition()) { 11929 // C++ [class.friend]p6: 11930 // A function can be defined in a friend declaration of a class if and 11931 // only if the class is a non-local class (9.8), the function name is 11932 // unqualified, and the function has namespace scope. 11933 SemaDiagnosticBuilder DB 11934 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11935 11936 DB << SS.getScopeRep(); 11937 if (DC->isFileContext()) 11938 DB << FixItHint::CreateRemoval(SS.getRange()); 11939 SS.clear(); 11940 } 11941 11942 // - There's a scope specifier that does not match any template 11943 // parameter lists, in which case we use some arbitrary context, 11944 // create a method or method template, and wait for instantiation. 11945 // - There's a scope specifier that does match some template 11946 // parameter lists, which we don't handle right now. 11947 } else { 11948 if (D.isFunctionDefinition()) { 11949 // C++ [class.friend]p6: 11950 // A function can be defined in a friend declaration of a class if and 11951 // only if the class is a non-local class (9.8), the function name is 11952 // unqualified, and the function has namespace scope. 11953 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11954 << SS.getScopeRep(); 11955 } 11956 11957 DC = CurContext; 11958 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11959 } 11960 11961 if (!DC->isRecord()) { 11962 // This implies that it has to be an operator or function. 11963 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11964 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11965 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11966 Diag(Loc, diag::err_introducing_special_friend) << 11967 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11968 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11969 return nullptr; 11970 } 11971 } 11972 11973 // FIXME: This is an egregious hack to cope with cases where the scope stack 11974 // does not contain the declaration context, i.e., in an out-of-line 11975 // definition of a class. 11976 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11977 if (!DCScope) { 11978 FakeDCScope.setEntity(DC); 11979 DCScope = &FakeDCScope; 11980 } 11981 11982 bool AddToScope = true; 11983 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11984 TemplateParams, AddToScope); 11985 if (!ND) return nullptr; 11986 11987 assert(ND->getLexicalDeclContext() == CurContext); 11988 11989 // If we performed typo correction, we might have added a scope specifier 11990 // and changed the decl context. 11991 DC = ND->getDeclContext(); 11992 11993 // Add the function declaration to the appropriate lookup tables, 11994 // adjusting the redeclarations list as necessary. We don't 11995 // want to do this yet if the friending class is dependent. 11996 // 11997 // Also update the scope-based lookup if the target context's 11998 // lookup context is in lexical scope. 11999 if (!CurContext->isDependentContext()) { 12000 DC = DC->getRedeclContext(); 12001 DC->makeDeclVisibleInContext(ND); 12002 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12003 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12004 } 12005 12006 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12007 D.getIdentifierLoc(), ND, 12008 DS.getFriendSpecLoc()); 12009 FrD->setAccess(AS_public); 12010 CurContext->addDecl(FrD); 12011 12012 if (ND->isInvalidDecl()) { 12013 FrD->setInvalidDecl(); 12014 } else { 12015 if (DC->isRecord()) CheckFriendAccess(ND); 12016 12017 FunctionDecl *FD; 12018 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12019 FD = FTD->getTemplatedDecl(); 12020 else 12021 FD = cast<FunctionDecl>(ND); 12022 12023 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12024 // default argument expression, that declaration shall be a definition 12025 // and shall be the only declaration of the function or function 12026 // template in the translation unit. 12027 if (functionDeclHasDefaultArgument(FD)) { 12028 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12029 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12030 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12031 } else if (!D.isFunctionDefinition()) 12032 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12033 } 12034 12035 // Mark templated-scope function declarations as unsupported. 12036 if (FD->getNumTemplateParameterLists()) 12037 FrD->setUnsupportedFriend(true); 12038 } 12039 12040 return ND; 12041 } 12042 12043 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12044 AdjustDeclIfTemplate(Dcl); 12045 12046 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12047 if (!Fn) { 12048 Diag(DelLoc, diag::err_deleted_non_function); 12049 return; 12050 } 12051 12052 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12053 // Don't consider the implicit declaration we generate for explicit 12054 // specializations. FIXME: Do not generate these implicit declarations. 12055 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12056 Prev->getPreviousDecl()) && 12057 !Prev->isDefined()) { 12058 Diag(DelLoc, diag::err_deleted_decl_not_first); 12059 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12060 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12061 : diag::note_previous_declaration); 12062 } 12063 // If the declaration wasn't the first, we delete the function anyway for 12064 // recovery. 12065 Fn = Fn->getCanonicalDecl(); 12066 } 12067 12068 // dllimport/dllexport cannot be deleted. 12069 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12070 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12071 Fn->setInvalidDecl(); 12072 } 12073 12074 if (Fn->isDeleted()) 12075 return; 12076 12077 // See if we're deleting a function which is already known to override a 12078 // non-deleted virtual function. 12079 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12080 bool IssuedDiagnostic = false; 12081 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12082 E = MD->end_overridden_methods(); 12083 I != E; ++I) { 12084 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12085 if (!IssuedDiagnostic) { 12086 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12087 IssuedDiagnostic = true; 12088 } 12089 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12090 } 12091 } 12092 } 12093 12094 // C++11 [basic.start.main]p3: 12095 // A program that defines main as deleted [...] is ill-formed. 12096 if (Fn->isMain()) 12097 Diag(DelLoc, diag::err_deleted_main); 12098 12099 Fn->setDeletedAsWritten(); 12100 } 12101 12102 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12103 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12104 12105 if (MD) { 12106 if (MD->getParent()->isDependentType()) { 12107 MD->setDefaulted(); 12108 MD->setExplicitlyDefaulted(); 12109 return; 12110 } 12111 12112 CXXSpecialMember Member = getSpecialMember(MD); 12113 if (Member == CXXInvalid) { 12114 if (!MD->isInvalidDecl()) 12115 Diag(DefaultLoc, diag::err_default_special_members); 12116 return; 12117 } 12118 12119 MD->setDefaulted(); 12120 MD->setExplicitlyDefaulted(); 12121 12122 // If this definition appears within the record, do the checking when 12123 // the record is complete. 12124 const FunctionDecl *Primary = MD; 12125 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12126 // Find the uninstantiated declaration that actually had the '= default' 12127 // on it. 12128 Pattern->isDefined(Primary); 12129 12130 // If the method was defaulted on its first declaration, we will have 12131 // already performed the checking in CheckCompletedCXXClass. Such a 12132 // declaration doesn't trigger an implicit definition. 12133 if (Primary == Primary->getCanonicalDecl()) 12134 return; 12135 12136 CheckExplicitlyDefaultedSpecialMember(MD); 12137 12138 // The exception specification is needed because we are defining the 12139 // function. 12140 ResolveExceptionSpec(DefaultLoc, 12141 MD->getType()->castAs<FunctionProtoType>()); 12142 12143 if (MD->isInvalidDecl()) 12144 return; 12145 12146 switch (Member) { 12147 case CXXDefaultConstructor: 12148 DefineImplicitDefaultConstructor(DefaultLoc, 12149 cast<CXXConstructorDecl>(MD)); 12150 break; 12151 case CXXCopyConstructor: 12152 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12153 break; 12154 case CXXCopyAssignment: 12155 DefineImplicitCopyAssignment(DefaultLoc, MD); 12156 break; 12157 case CXXDestructor: 12158 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12159 break; 12160 case CXXMoveConstructor: 12161 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12162 break; 12163 case CXXMoveAssignment: 12164 DefineImplicitMoveAssignment(DefaultLoc, MD); 12165 break; 12166 case CXXInvalid: 12167 llvm_unreachable("Invalid special member."); 12168 } 12169 } else { 12170 Diag(DefaultLoc, diag::err_default_special_members); 12171 } 12172 } 12173 12174 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12175 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12176 Stmt *SubStmt = *CI; 12177 if (!SubStmt) 12178 continue; 12179 if (isa<ReturnStmt>(SubStmt)) 12180 Self.Diag(SubStmt->getLocStart(), 12181 diag::err_return_in_constructor_handler); 12182 if (!isa<Expr>(SubStmt)) 12183 SearchForReturnInStmt(Self, SubStmt); 12184 } 12185 } 12186 12187 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12188 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12189 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12190 SearchForReturnInStmt(*this, Handler); 12191 } 12192 } 12193 12194 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12195 const CXXMethodDecl *Old) { 12196 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12197 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12198 12199 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12200 12201 // If the calling conventions match, everything is fine 12202 if (NewCC == OldCC) 12203 return false; 12204 12205 // If the calling conventions mismatch because the new function is static, 12206 // suppress the calling convention mismatch error; the error about static 12207 // function override (err_static_overrides_virtual from 12208 // Sema::CheckFunctionDeclaration) is more clear. 12209 if (New->getStorageClass() == SC_Static) 12210 return false; 12211 12212 Diag(New->getLocation(), 12213 diag::err_conflicting_overriding_cc_attributes) 12214 << New->getDeclName() << New->getType() << Old->getType(); 12215 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12216 return true; 12217 } 12218 12219 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12220 const CXXMethodDecl *Old) { 12221 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12222 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12223 12224 if (Context.hasSameType(NewTy, OldTy) || 12225 NewTy->isDependentType() || OldTy->isDependentType()) 12226 return false; 12227 12228 // Check if the return types are covariant 12229 QualType NewClassTy, OldClassTy; 12230 12231 /// Both types must be pointers or references to classes. 12232 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12233 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12234 NewClassTy = NewPT->getPointeeType(); 12235 OldClassTy = OldPT->getPointeeType(); 12236 } 12237 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12238 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12239 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12240 NewClassTy = NewRT->getPointeeType(); 12241 OldClassTy = OldRT->getPointeeType(); 12242 } 12243 } 12244 } 12245 12246 // The return types aren't either both pointers or references to a class type. 12247 if (NewClassTy.isNull()) { 12248 Diag(New->getLocation(), 12249 diag::err_different_return_type_for_overriding_virtual_function) 12250 << New->getDeclName() << NewTy << OldTy; 12251 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12252 12253 return true; 12254 } 12255 12256 // C++ [class.virtual]p6: 12257 // If the return type of D::f differs from the return type of B::f, the 12258 // class type in the return type of D::f shall be complete at the point of 12259 // declaration of D::f or shall be the class type D. 12260 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12261 if (!RT->isBeingDefined() && 12262 RequireCompleteType(New->getLocation(), NewClassTy, 12263 diag::err_covariant_return_incomplete, 12264 New->getDeclName())) 12265 return true; 12266 } 12267 12268 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12269 // Check if the new class derives from the old class. 12270 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12271 Diag(New->getLocation(), 12272 diag::err_covariant_return_not_derived) 12273 << New->getDeclName() << NewTy << OldTy; 12274 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12275 return true; 12276 } 12277 12278 // Check if we the conversion from derived to base is valid. 12279 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 12280 diag::err_covariant_return_inaccessible_base, 12281 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12282 // FIXME: Should this point to the return type? 12283 New->getLocation(), SourceRange(), New->getDeclName(), 12284 nullptr)) { 12285 // FIXME: this note won't trigger for delayed access control 12286 // diagnostics, and it's impossible to get an undelayed error 12287 // here from access control during the original parse because 12288 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12289 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12290 return true; 12291 } 12292 } 12293 12294 // The qualifiers of the return types must be the same. 12295 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12296 Diag(New->getLocation(), 12297 diag::err_covariant_return_type_different_qualifications) 12298 << New->getDeclName() << NewTy << OldTy; 12299 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12300 return true; 12301 }; 12302 12303 12304 // The new class type must have the same or less qualifiers as the old type. 12305 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12306 Diag(New->getLocation(), 12307 diag::err_covariant_return_type_class_type_more_qualified) 12308 << New->getDeclName() << NewTy << OldTy; 12309 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12310 return true; 12311 }; 12312 12313 return false; 12314 } 12315 12316 /// \brief Mark the given method pure. 12317 /// 12318 /// \param Method the method to be marked pure. 12319 /// 12320 /// \param InitRange the source range that covers the "0" initializer. 12321 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12322 SourceLocation EndLoc = InitRange.getEnd(); 12323 if (EndLoc.isValid()) 12324 Method->setRangeEnd(EndLoc); 12325 12326 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12327 Method->setPure(); 12328 return false; 12329 } 12330 12331 if (!Method->isInvalidDecl()) 12332 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12333 << Method->getDeclName() << InitRange; 12334 return true; 12335 } 12336 12337 /// \brief Determine whether the given declaration is a static data member. 12338 static bool isStaticDataMember(const Decl *D) { 12339 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12340 return Var->isStaticDataMember(); 12341 12342 return false; 12343 } 12344 12345 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12346 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12347 /// is a fresh scope pushed for just this purpose. 12348 /// 12349 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12350 /// static data member of class X, names should be looked up in the scope of 12351 /// class X. 12352 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12353 // If there is no declaration, there was an error parsing it. 12354 if (!D || D->isInvalidDecl()) 12355 return; 12356 12357 // We will always have a nested name specifier here, but this declaration 12358 // might not be out of line if the specifier names the current namespace: 12359 // extern int n; 12360 // int ::n = 0; 12361 if (D->isOutOfLine()) 12362 EnterDeclaratorContext(S, D->getDeclContext()); 12363 12364 // If we are parsing the initializer for a static data member, push a 12365 // new expression evaluation context that is associated with this static 12366 // data member. 12367 if (isStaticDataMember(D)) 12368 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12369 } 12370 12371 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12372 /// initializer for the out-of-line declaration 'D'. 12373 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12374 // If there is no declaration, there was an error parsing it. 12375 if (!D || D->isInvalidDecl()) 12376 return; 12377 12378 if (isStaticDataMember(D)) 12379 PopExpressionEvaluationContext(); 12380 12381 if (D->isOutOfLine()) 12382 ExitDeclaratorContext(S); 12383 } 12384 12385 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12386 /// C++ if/switch/while/for statement. 12387 /// e.g: "if (int x = f()) {...}" 12388 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12389 // C++ 6.4p2: 12390 // The declarator shall not specify a function or an array. 12391 // The type-specifier-seq shall not contain typedef and shall not declare a 12392 // new class or enumeration. 12393 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12394 "Parser allowed 'typedef' as storage class of condition decl."); 12395 12396 Decl *Dcl = ActOnDeclarator(S, D); 12397 if (!Dcl) 12398 return true; 12399 12400 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12401 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12402 << D.getSourceRange(); 12403 return true; 12404 } 12405 12406 return Dcl; 12407 } 12408 12409 void Sema::LoadExternalVTableUses() { 12410 if (!ExternalSource) 12411 return; 12412 12413 SmallVector<ExternalVTableUse, 4> VTables; 12414 ExternalSource->ReadUsedVTables(VTables); 12415 SmallVector<VTableUse, 4> NewUses; 12416 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12417 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12418 = VTablesUsed.find(VTables[I].Record); 12419 // Even if a definition wasn't required before, it may be required now. 12420 if (Pos != VTablesUsed.end()) { 12421 if (!Pos->second && VTables[I].DefinitionRequired) 12422 Pos->second = true; 12423 continue; 12424 } 12425 12426 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12427 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12428 } 12429 12430 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12431 } 12432 12433 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12434 bool DefinitionRequired) { 12435 // Ignore any vtable uses in unevaluated operands or for classes that do 12436 // not have a vtable. 12437 if (!Class->isDynamicClass() || Class->isDependentContext() || 12438 CurContext->isDependentContext() || isUnevaluatedContext()) 12439 return; 12440 12441 // Try to insert this class into the map. 12442 LoadExternalVTableUses(); 12443 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12444 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12445 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12446 if (!Pos.second) { 12447 // If we already had an entry, check to see if we are promoting this vtable 12448 // to required a definition. If so, we need to reappend to the VTableUses 12449 // list, since we may have already processed the first entry. 12450 if (DefinitionRequired && !Pos.first->second) { 12451 Pos.first->second = true; 12452 } else { 12453 // Otherwise, we can early exit. 12454 return; 12455 } 12456 } else { 12457 // The Microsoft ABI requires that we perform the destructor body 12458 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12459 // the deleting destructor is emitted with the vtable, not with the 12460 // destructor definition as in the Itanium ABI. 12461 // If it has a definition, we do the check at that point instead. 12462 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12463 Class->hasUserDeclaredDestructor() && 12464 !Class->getDestructor()->isDefined() && 12465 !Class->getDestructor()->isDeleted()) { 12466 CXXDestructorDecl *DD = Class->getDestructor(); 12467 ContextRAII SavedContext(*this, DD); 12468 CheckDestructor(DD); 12469 } 12470 } 12471 12472 // Local classes need to have their virtual members marked 12473 // immediately. For all other classes, we mark their virtual members 12474 // at the end of the translation unit. 12475 if (Class->isLocalClass()) 12476 MarkVirtualMembersReferenced(Loc, Class); 12477 else 12478 VTableUses.push_back(std::make_pair(Class, Loc)); 12479 } 12480 12481 bool Sema::DefineUsedVTables() { 12482 LoadExternalVTableUses(); 12483 if (VTableUses.empty()) 12484 return false; 12485 12486 // Note: The VTableUses vector could grow as a result of marking 12487 // the members of a class as "used", so we check the size each 12488 // time through the loop and prefer indices (which are stable) to 12489 // iterators (which are not). 12490 bool DefinedAnything = false; 12491 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12492 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12493 if (!Class) 12494 continue; 12495 12496 SourceLocation Loc = VTableUses[I].second; 12497 12498 bool DefineVTable = true; 12499 12500 // If this class has a key function, but that key function is 12501 // defined in another translation unit, we don't need to emit the 12502 // vtable even though we're using it. 12503 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12504 if (KeyFunction && !KeyFunction->hasBody()) { 12505 // The key function is in another translation unit. 12506 DefineVTable = false; 12507 TemplateSpecializationKind TSK = 12508 KeyFunction->getTemplateSpecializationKind(); 12509 assert(TSK != TSK_ExplicitInstantiationDefinition && 12510 TSK != TSK_ImplicitInstantiation && 12511 "Instantiations don't have key functions"); 12512 (void)TSK; 12513 } else if (!KeyFunction) { 12514 // If we have a class with no key function that is the subject 12515 // of an explicit instantiation declaration, suppress the 12516 // vtable; it will live with the explicit instantiation 12517 // definition. 12518 bool IsExplicitInstantiationDeclaration 12519 = Class->getTemplateSpecializationKind() 12520 == TSK_ExplicitInstantiationDeclaration; 12521 for (auto R : Class->redecls()) { 12522 TemplateSpecializationKind TSK 12523 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 12524 if (TSK == TSK_ExplicitInstantiationDeclaration) 12525 IsExplicitInstantiationDeclaration = true; 12526 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12527 IsExplicitInstantiationDeclaration = false; 12528 break; 12529 } 12530 } 12531 12532 if (IsExplicitInstantiationDeclaration) 12533 DefineVTable = false; 12534 } 12535 12536 // The exception specifications for all virtual members may be needed even 12537 // if we are not providing an authoritative form of the vtable in this TU. 12538 // We may choose to emit it available_externally anyway. 12539 if (!DefineVTable) { 12540 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12541 continue; 12542 } 12543 12544 // Mark all of the virtual members of this class as referenced, so 12545 // that we can build a vtable. Then, tell the AST consumer that a 12546 // vtable for this class is required. 12547 DefinedAnything = true; 12548 MarkVirtualMembersReferenced(Loc, Class); 12549 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12550 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12551 12552 // Optionally warn if we're emitting a weak vtable. 12553 if (Class->isExternallyVisible() && 12554 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12555 const FunctionDecl *KeyFunctionDef = nullptr; 12556 if (!KeyFunction || 12557 (KeyFunction->hasBody(KeyFunctionDef) && 12558 KeyFunctionDef->isInlined())) 12559 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12560 TSK_ExplicitInstantiationDefinition 12561 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12562 << Class; 12563 } 12564 } 12565 VTableUses.clear(); 12566 12567 return DefinedAnything; 12568 } 12569 12570 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12571 const CXXRecordDecl *RD) { 12572 for (const auto *I : RD->methods()) 12573 if (I->isVirtual() && !I->isPure()) 12574 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 12575 } 12576 12577 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12578 const CXXRecordDecl *RD) { 12579 // Mark all functions which will appear in RD's vtable as used. 12580 CXXFinalOverriderMap FinalOverriders; 12581 RD->getFinalOverriders(FinalOverriders); 12582 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12583 E = FinalOverriders.end(); 12584 I != E; ++I) { 12585 for (OverridingMethods::const_iterator OI = I->second.begin(), 12586 OE = I->second.end(); 12587 OI != OE; ++OI) { 12588 assert(OI->second.size() > 0 && "no final overrider"); 12589 CXXMethodDecl *Overrider = OI->second.front().Method; 12590 12591 // C++ [basic.def.odr]p2: 12592 // [...] A virtual member function is used if it is not pure. [...] 12593 if (!Overrider->isPure()) 12594 MarkFunctionReferenced(Loc, Overrider); 12595 } 12596 } 12597 12598 // Only classes that have virtual bases need a VTT. 12599 if (RD->getNumVBases() == 0) 12600 return; 12601 12602 for (const auto &I : RD->bases()) { 12603 const CXXRecordDecl *Base = 12604 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 12605 if (Base->getNumVBases() == 0) 12606 continue; 12607 MarkVirtualMembersReferenced(Loc, Base); 12608 } 12609 } 12610 12611 /// SetIvarInitializers - This routine builds initialization ASTs for the 12612 /// Objective-C implementation whose ivars need be initialized. 12613 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12614 if (!getLangOpts().CPlusPlus) 12615 return; 12616 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12617 SmallVector<ObjCIvarDecl*, 8> ivars; 12618 CollectIvarsToConstructOrDestruct(OID, ivars); 12619 if (ivars.empty()) 12620 return; 12621 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12622 for (unsigned i = 0; i < ivars.size(); i++) { 12623 FieldDecl *Field = ivars[i]; 12624 if (Field->isInvalidDecl()) 12625 continue; 12626 12627 CXXCtorInitializer *Member; 12628 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12629 InitializationKind InitKind = 12630 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12631 12632 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12633 ExprResult MemberInit = 12634 InitSeq.Perform(*this, InitEntity, InitKind, None); 12635 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12636 // Note, MemberInit could actually come back empty if no initialization 12637 // is required (e.g., because it would call a trivial default constructor) 12638 if (!MemberInit.get() || MemberInit.isInvalid()) 12639 continue; 12640 12641 Member = 12642 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12643 SourceLocation(), 12644 MemberInit.getAs<Expr>(), 12645 SourceLocation()); 12646 AllToInit.push_back(Member); 12647 12648 // Be sure that the destructor is accessible and is marked as referenced. 12649 if (const RecordType *RecordTy 12650 = Context.getBaseElementType(Field->getType()) 12651 ->getAs<RecordType>()) { 12652 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12653 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12654 MarkFunctionReferenced(Field->getLocation(), Destructor); 12655 CheckDestructorAccess(Field->getLocation(), Destructor, 12656 PDiag(diag::err_access_dtor_ivar) 12657 << Context.getBaseElementType(Field->getType())); 12658 } 12659 } 12660 } 12661 ObjCImplementation->setIvarInitializers(Context, 12662 AllToInit.data(), AllToInit.size()); 12663 } 12664 } 12665 12666 static 12667 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12668 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12669 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12670 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12671 Sema &S) { 12672 if (Ctor->isInvalidDecl()) 12673 return; 12674 12675 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12676 12677 // Target may not be determinable yet, for instance if this is a dependent 12678 // call in an uninstantiated template. 12679 if (Target) { 12680 const FunctionDecl *FNTarget = nullptr; 12681 (void)Target->hasBody(FNTarget); 12682 Target = const_cast<CXXConstructorDecl*>( 12683 cast_or_null<CXXConstructorDecl>(FNTarget)); 12684 } 12685 12686 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12687 // Avoid dereferencing a null pointer here. 12688 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 12689 12690 if (!Current.insert(Canonical)) 12691 return; 12692 12693 // We know that beyond here, we aren't chaining into a cycle. 12694 if (!Target || !Target->isDelegatingConstructor() || 12695 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12696 Valid.insert(Current.begin(), Current.end()); 12697 Current.clear(); 12698 // We've hit a cycle. 12699 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12700 Current.count(TCanonical)) { 12701 // If we haven't diagnosed this cycle yet, do so now. 12702 if (!Invalid.count(TCanonical)) { 12703 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12704 diag::warn_delegating_ctor_cycle) 12705 << Ctor; 12706 12707 // Don't add a note for a function delegating directly to itself. 12708 if (TCanonical != Canonical) 12709 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12710 12711 CXXConstructorDecl *C = Target; 12712 while (C->getCanonicalDecl() != Canonical) { 12713 const FunctionDecl *FNTarget = nullptr; 12714 (void)C->getTargetConstructor()->hasBody(FNTarget); 12715 assert(FNTarget && "Ctor cycle through bodiless function"); 12716 12717 C = const_cast<CXXConstructorDecl*>( 12718 cast<CXXConstructorDecl>(FNTarget)); 12719 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12720 } 12721 } 12722 12723 Invalid.insert(Current.begin(), Current.end()); 12724 Current.clear(); 12725 } else { 12726 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12727 } 12728 } 12729 12730 12731 void Sema::CheckDelegatingCtorCycles() { 12732 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12733 12734 for (DelegatingCtorDeclsType::iterator 12735 I = DelegatingCtorDecls.begin(ExternalSource), 12736 E = DelegatingCtorDecls.end(); 12737 I != E; ++I) 12738 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12739 12740 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12741 CE = Invalid.end(); 12742 CI != CE; ++CI) 12743 (*CI)->setInvalidDecl(); 12744 } 12745 12746 namespace { 12747 /// \brief AST visitor that finds references to the 'this' expression. 12748 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12749 Sema &S; 12750 12751 public: 12752 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12753 12754 bool VisitCXXThisExpr(CXXThisExpr *E) { 12755 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12756 << E->isImplicit(); 12757 return false; 12758 } 12759 }; 12760 } 12761 12762 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12763 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12764 if (!TSInfo) 12765 return false; 12766 12767 TypeLoc TL = TSInfo->getTypeLoc(); 12768 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12769 if (!ProtoTL) 12770 return false; 12771 12772 // C++11 [expr.prim.general]p3: 12773 // [The expression this] shall not appear before the optional 12774 // cv-qualifier-seq and it shall not appear within the declaration of a 12775 // static member function (although its type and value category are defined 12776 // within a static member function as they are within a non-static member 12777 // function). [ Note: this is because declaration matching does not occur 12778 // until the complete declarator is known. - end note ] 12779 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12780 FindCXXThisExpr Finder(*this); 12781 12782 // If the return type came after the cv-qualifier-seq, check it now. 12783 if (Proto->hasTrailingReturn() && 12784 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 12785 return true; 12786 12787 // Check the exception specification. 12788 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12789 return true; 12790 12791 return checkThisInStaticMemberFunctionAttributes(Method); 12792 } 12793 12794 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12795 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12796 if (!TSInfo) 12797 return false; 12798 12799 TypeLoc TL = TSInfo->getTypeLoc(); 12800 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12801 if (!ProtoTL) 12802 return false; 12803 12804 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12805 FindCXXThisExpr Finder(*this); 12806 12807 switch (Proto->getExceptionSpecType()) { 12808 case EST_Uninstantiated: 12809 case EST_Unevaluated: 12810 case EST_BasicNoexcept: 12811 case EST_DynamicNone: 12812 case EST_MSAny: 12813 case EST_None: 12814 break; 12815 12816 case EST_ComputedNoexcept: 12817 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12818 return true; 12819 12820 case EST_Dynamic: 12821 for (const auto &E : Proto->exceptions()) { 12822 if (!Finder.TraverseType(E)) 12823 return true; 12824 } 12825 break; 12826 } 12827 12828 return false; 12829 } 12830 12831 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12832 FindCXXThisExpr Finder(*this); 12833 12834 // Check attributes. 12835 for (const auto *A : Method->attrs()) { 12836 // FIXME: This should be emitted by tblgen. 12837 Expr *Arg = nullptr; 12838 ArrayRef<Expr *> Args; 12839 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 12840 Arg = G->getArg(); 12841 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 12842 Arg = G->getArg(); 12843 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 12844 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12845 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 12846 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12847 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 12848 Arg = ETLF->getSuccessValue(); 12849 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12850 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 12851 Arg = STLF->getSuccessValue(); 12852 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12853 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 12854 Arg = LR->getArg(); 12855 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 12856 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12857 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 12858 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12859 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 12860 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12861 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 12862 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12863 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 12864 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12865 12866 if (Arg && !Finder.TraverseStmt(Arg)) 12867 return true; 12868 12869 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12870 if (!Finder.TraverseStmt(Args[I])) 12871 return true; 12872 } 12873 } 12874 12875 return false; 12876 } 12877 12878 void 12879 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12880 ArrayRef<ParsedType> DynamicExceptions, 12881 ArrayRef<SourceRange> DynamicExceptionRanges, 12882 Expr *NoexceptExpr, 12883 SmallVectorImpl<QualType> &Exceptions, 12884 FunctionProtoType::ExtProtoInfo &EPI) { 12885 Exceptions.clear(); 12886 EPI.ExceptionSpecType = EST; 12887 if (EST == EST_Dynamic) { 12888 Exceptions.reserve(DynamicExceptions.size()); 12889 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12890 // FIXME: Preserve type source info. 12891 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12892 12893 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12894 collectUnexpandedParameterPacks(ET, Unexpanded); 12895 if (!Unexpanded.empty()) { 12896 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12897 UPPC_ExceptionType, 12898 Unexpanded); 12899 continue; 12900 } 12901 12902 // Check that the type is valid for an exception spec, and 12903 // drop it if not. 12904 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12905 Exceptions.push_back(ET); 12906 } 12907 EPI.NumExceptions = Exceptions.size(); 12908 EPI.Exceptions = Exceptions.data(); 12909 return; 12910 } 12911 12912 if (EST == EST_ComputedNoexcept) { 12913 // If an error occurred, there's no expression here. 12914 if (NoexceptExpr) { 12915 assert((NoexceptExpr->isTypeDependent() || 12916 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12917 Context.BoolTy) && 12918 "Parser should have made sure that the expression is boolean"); 12919 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12920 EPI.ExceptionSpecType = EST_BasicNoexcept; 12921 return; 12922 } 12923 12924 if (!NoexceptExpr->isValueDependent()) 12925 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 12926 diag::err_noexcept_needs_constant_expression, 12927 /*AllowFold*/ false).get(); 12928 EPI.NoexceptExpr = NoexceptExpr; 12929 } 12930 return; 12931 } 12932 } 12933 12934 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12935 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12936 // Implicitly declared functions (e.g. copy constructors) are 12937 // __host__ __device__ 12938 if (D->isImplicit()) 12939 return CFT_HostDevice; 12940 12941 if (D->hasAttr<CUDAGlobalAttr>()) 12942 return CFT_Global; 12943 12944 if (D->hasAttr<CUDADeviceAttr>()) { 12945 if (D->hasAttr<CUDAHostAttr>()) 12946 return CFT_HostDevice; 12947 return CFT_Device; 12948 } 12949 12950 return CFT_Host; 12951 } 12952 12953 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12954 CUDAFunctionTarget CalleeTarget) { 12955 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12956 // Callable from the device only." 12957 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12958 return true; 12959 12960 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12961 // Callable from the host only." 12962 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12963 // Callable from the host only." 12964 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12965 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12966 return true; 12967 12968 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12969 return true; 12970 12971 return false; 12972 } 12973 12974 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12975 /// 12976 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12977 SourceLocation DeclStart, 12978 Declarator &D, Expr *BitWidth, 12979 InClassInitStyle InitStyle, 12980 AccessSpecifier AS, 12981 AttributeList *MSPropertyAttr) { 12982 IdentifierInfo *II = D.getIdentifier(); 12983 if (!II) { 12984 Diag(DeclStart, diag::err_anonymous_property); 12985 return nullptr; 12986 } 12987 SourceLocation Loc = D.getIdentifierLoc(); 12988 12989 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12990 QualType T = TInfo->getType(); 12991 if (getLangOpts().CPlusPlus) { 12992 CheckExtraCXXDefaultArguments(D); 12993 12994 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12995 UPPC_DataMemberType)) { 12996 D.setInvalidType(); 12997 T = Context.IntTy; 12998 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12999 } 13000 } 13001 13002 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13003 13004 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13005 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13006 diag::err_invalid_thread) 13007 << DeclSpec::getSpecifierName(TSCS); 13008 13009 // Check to see if this name was declared as a member previously 13010 NamedDecl *PrevDecl = nullptr; 13011 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13012 LookupName(Previous, S); 13013 switch (Previous.getResultKind()) { 13014 case LookupResult::Found: 13015 case LookupResult::FoundUnresolvedValue: 13016 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13017 break; 13018 13019 case LookupResult::FoundOverloaded: 13020 PrevDecl = Previous.getRepresentativeDecl(); 13021 break; 13022 13023 case LookupResult::NotFound: 13024 case LookupResult::NotFoundInCurrentInstantiation: 13025 case LookupResult::Ambiguous: 13026 break; 13027 } 13028 13029 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13030 // Maybe we will complain about the shadowed template parameter. 13031 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13032 // Just pretend that we didn't see the previous declaration. 13033 PrevDecl = nullptr; 13034 } 13035 13036 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13037 PrevDecl = nullptr; 13038 13039 SourceLocation TSSL = D.getLocStart(); 13040 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13041 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13042 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13043 ProcessDeclAttributes(TUScope, NewPD, D); 13044 NewPD->setAccess(AS); 13045 13046 if (NewPD->isInvalidDecl()) 13047 Record->setInvalidDecl(); 13048 13049 if (D.getDeclSpec().isModulePrivateSpecified()) 13050 NewPD->setModulePrivate(); 13051 13052 if (NewPD->isInvalidDecl() && PrevDecl) { 13053 // Don't introduce NewFD into scope; there's already something 13054 // with the same name in the same scope. 13055 } else if (II) { 13056 PushOnScopeChains(NewPD, S); 13057 } else 13058 Record->addDecl(NewPD); 13059 13060 return NewPD; 13061 } 13062