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 "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.getAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // Check that the default argument is well-formed 322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 323 if (DefaultArgChecker.Visit(DefaultArg)) { 324 Param->setInvalidDecl(); 325 return; 326 } 327 328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 329 } 330 331 /// ActOnParamUnparsedDefaultArgument - We've seen a default 332 /// argument for a function parameter, but we can't parse it yet 333 /// because we're inside a class definition. Note that this default 334 /// argument will be parsed later. 335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 336 SourceLocation EqualLoc, 337 SourceLocation ArgLoc) { 338 if (!param) 339 return; 340 341 ParmVarDecl *Param = cast<ParmVarDecl>(param); 342 Param->setUnparsedDefaultArg(); 343 UnparsedDefaultArgLocs[Param] = ArgLoc; 344 } 345 346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 347 /// the default argument for the parameter param failed. 348 void Sema::ActOnParamDefaultArgumentError(Decl *param, 349 SourceLocation EqualLoc) { 350 if (!param) 351 return; 352 353 ParmVarDecl *Param = cast<ParmVarDecl>(param); 354 Param->setInvalidDecl(); 355 UnparsedDefaultArgLocs.erase(Param); 356 Param->setDefaultArg(new(Context) 357 OpaqueValueExpr(EqualLoc, 358 Param->getType().getNonReferenceType(), 359 VK_RValue)); 360 } 361 362 /// CheckExtraCXXDefaultArguments - Check for any extra default 363 /// arguments in the declarator, which is not a function declaration 364 /// or definition and therefore is not permitted to have default 365 /// arguments. This routine should be invoked for every declarator 366 /// that is not a function declaration or definition. 367 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 368 // C++ [dcl.fct.default]p3 369 // A default argument expression shall be specified only in the 370 // parameter-declaration-clause of a function declaration or in a 371 // template-parameter (14.1). It shall not be specified for a 372 // parameter pack. If it is specified in a 373 // parameter-declaration-clause, it shall not occur within a 374 // declarator or abstract-declarator of a parameter-declaration. 375 bool MightBeFunction = D.isFunctionDeclarationContext(); 376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 377 DeclaratorChunk &chunk = D.getTypeObject(i); 378 if (chunk.Kind == DeclaratorChunk::Function) { 379 if (MightBeFunction) { 380 // This is a function declaration. It can have default arguments, but 381 // keep looking in case its return type is a function type with default 382 // arguments. 383 MightBeFunction = false; 384 continue; 385 } 386 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 387 ++argIdx) { 388 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 389 if (Param->hasUnparsedDefaultArg()) { 390 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 391 SourceRange SR; 392 if (Toks->size() > 1) 393 SR = SourceRange((*Toks)[1].getLocation(), 394 Toks->back().getLocation()); 395 else 396 SR = UnparsedDefaultArgLocs[Param]; 397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 398 << SR; 399 delete Toks; 400 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 401 } else if (Param->getDefaultArg()) { 402 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 403 << Param->getDefaultArg()->getSourceRange(); 404 Param->setDefaultArg(nullptr); 405 } 406 } 407 } else if (chunk.Kind != DeclaratorChunk::Paren) { 408 MightBeFunction = false; 409 } 410 } 411 } 412 413 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 414 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 415 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 416 if (!PVD->hasDefaultArg()) 417 return false; 418 if (!PVD->hasInheritedDefaultArg()) 419 return true; 420 } 421 return false; 422 } 423 424 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 425 /// function, once we already know that they have the same 426 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 427 /// error, false otherwise. 428 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 429 Scope *S) { 430 bool Invalid = false; 431 432 // C++ [dcl.fct.default]p4: 433 // For non-template functions, default arguments can be added in 434 // later declarations of a function in the same 435 // scope. Declarations in different scopes have completely 436 // distinct sets of default arguments. That is, declarations in 437 // inner scopes do not acquire default arguments from 438 // declarations in outer scopes, and vice versa. In a given 439 // function declaration, all parameters subsequent to a 440 // parameter with a default argument shall have default 441 // arguments supplied in this or previous declarations. A 442 // default argument shall not be redefined by a later 443 // declaration (not even to the same value). 444 // 445 // C++ [dcl.fct.default]p6: 446 // Except for member functions of class templates, the default arguments 447 // in a member function definition that appears outside of the class 448 // definition are added to the set of default arguments provided by the 449 // member function declaration in the class definition. 450 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 451 ParmVarDecl *OldParam = Old->getParamDecl(p); 452 ParmVarDecl *NewParam = New->getParamDecl(p); 453 454 bool OldParamHasDfl = OldParam->hasDefaultArg(); 455 bool NewParamHasDfl = NewParam->hasDefaultArg(); 456 457 // The declaration context corresponding to the scope is the semantic 458 // parent, unless this is a local function declaration, in which case 459 // it is that surrounding function. 460 DeclContext *ScopeDC = New->isLocalExternDecl() 461 ? New->getLexicalDeclContext() 462 : New->getDeclContext(); 463 if (S && !isDeclInScope(Old, ScopeDC, S) && 464 !New->getDeclContext()->isRecord()) 465 // Ignore default parameters of old decl if they are not in 466 // the same scope and this is not an out-of-line definition of 467 // a member function. 468 OldParamHasDfl = false; 469 if (New->isLocalExternDecl() != Old->isLocalExternDecl()) 470 // If only one of these is a local function declaration, then they are 471 // declared in different scopes, even though isDeclInScope may think 472 // they're in the same scope. (If both are local, the scope check is 473 // sufficent, and if neither is local, then they are in the same scope.) 474 OldParamHasDfl = false; 475 476 if (OldParamHasDfl && NewParamHasDfl) { 477 478 unsigned DiagDefaultParamID = 479 diag::err_param_default_argument_redefinition; 480 481 // MSVC accepts that default parameters be redefined for member functions 482 // of template class. The new default parameter's value is ignored. 483 Invalid = true; 484 if (getLangOpts().MicrosoftExt) { 485 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 486 if (MD && MD->getParent()->getDescribedClassTemplate()) { 487 // Merge the old default argument into the new parameter. 488 NewParam->setHasInheritedDefaultArg(); 489 if (OldParam->hasUninstantiatedDefaultArg()) 490 NewParam->setUninstantiatedDefaultArg( 491 OldParam->getUninstantiatedDefaultArg()); 492 else 493 NewParam->setDefaultArg(OldParam->getInit()); 494 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 495 Invalid = false; 496 } 497 } 498 499 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 500 // hint here. Alternatively, we could walk the type-source information 501 // for NewParam to find the last source location in the type... but it 502 // isn't worth the effort right now. This is the kind of test case that 503 // is hard to get right: 504 // int f(int); 505 // void g(int (*fp)(int) = f); 506 // void g(int (*fp)(int) = &f); 507 Diag(NewParam->getLocation(), DiagDefaultParamID) 508 << NewParam->getDefaultArgRange(); 509 510 // Look for the function declaration where the default argument was 511 // actually written, which may be a declaration prior to Old. 512 for (auto Older = Old; OldParam->hasInheritedDefaultArg();) { 513 Older = Older->getPreviousDecl(); 514 OldParam = Older->getParamDecl(p); 515 } 516 517 Diag(OldParam->getLocation(), diag::note_previous_definition) 518 << OldParam->getDefaultArgRange(); 519 } else if (OldParamHasDfl) { 520 // Merge the old default argument into the new parameter. 521 // It's important to use getInit() here; getDefaultArg() 522 // strips off any top-level ExprWithCleanups. 523 NewParam->setHasInheritedDefaultArg(); 524 if (OldParam->hasUnparsedDefaultArg()) 525 NewParam->setUnparsedDefaultArg(); 526 else if (OldParam->hasUninstantiatedDefaultArg()) 527 NewParam->setUninstantiatedDefaultArg( 528 OldParam->getUninstantiatedDefaultArg()); 529 else 530 NewParam->setDefaultArg(OldParam->getInit()); 531 } else if (NewParamHasDfl) { 532 if (New->getDescribedFunctionTemplate()) { 533 // Paragraph 4, quoted above, only applies to non-template functions. 534 Diag(NewParam->getLocation(), 535 diag::err_param_default_argument_template_redecl) 536 << NewParam->getDefaultArgRange(); 537 Diag(Old->getLocation(), diag::note_template_prev_declaration) 538 << false; 539 } else if (New->getTemplateSpecializationKind() 540 != TSK_ImplicitInstantiation && 541 New->getTemplateSpecializationKind() != TSK_Undeclared) { 542 // C++ [temp.expr.spec]p21: 543 // Default function arguments shall not be specified in a declaration 544 // or a definition for one of the following explicit specializations: 545 // - the explicit specialization of a function template; 546 // - the explicit specialization of a member function template; 547 // - the explicit specialization of a member function of a class 548 // template where the class template specialization to which the 549 // member function specialization belongs is implicitly 550 // instantiated. 551 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 552 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 553 << New->getDeclName() 554 << NewParam->getDefaultArgRange(); 555 } else if (New->getDeclContext()->isDependentContext()) { 556 // C++ [dcl.fct.default]p6 (DR217): 557 // Default arguments for a member function of a class template shall 558 // be specified on the initial declaration of the member function 559 // within the class template. 560 // 561 // Reading the tea leaves a bit in DR217 and its reference to DR205 562 // leads me to the conclusion that one cannot add default function 563 // arguments for an out-of-line definition of a member function of a 564 // dependent type. 565 int WhichKind = 2; 566 if (CXXRecordDecl *Record 567 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 568 if (Record->getDescribedClassTemplate()) 569 WhichKind = 0; 570 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 571 WhichKind = 1; 572 else 573 WhichKind = 2; 574 } 575 576 Diag(NewParam->getLocation(), 577 diag::err_param_default_argument_member_template_redecl) 578 << WhichKind 579 << NewParam->getDefaultArgRange(); 580 } 581 } 582 } 583 584 // DR1344: If a default argument is added outside a class definition and that 585 // default argument makes the function a special member function, the program 586 // is ill-formed. This can only happen for constructors. 587 if (isa<CXXConstructorDecl>(New) && 588 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 589 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 590 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 591 if (NewSM != OldSM) { 592 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 593 assert(NewParam->hasDefaultArg()); 594 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 595 << NewParam->getDefaultArgRange() << NewSM; 596 Diag(Old->getLocation(), diag::note_previous_declaration); 597 } 598 } 599 600 const FunctionDecl *Def; 601 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 602 // template has a constexpr specifier then all its declarations shall 603 // contain the constexpr specifier. 604 if (New->isConstexpr() != Old->isConstexpr()) { 605 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 606 << New << New->isConstexpr(); 607 Diag(Old->getLocation(), diag::note_previous_declaration); 608 Invalid = true; 609 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 610 // C++11 [dcl.fcn.spec]p4: 611 // If the definition of a function appears in a translation unit before its 612 // first declaration as inline, the program is ill-formed. 613 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 614 Diag(Def->getLocation(), diag::note_previous_definition); 615 Invalid = true; 616 } 617 618 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 619 // argument expression, that declaration shall be a definition and shall be 620 // the only declaration of the function or function template in the 621 // translation unit. 622 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 623 functionDeclHasDefaultArgument(Old)) { 624 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 625 Diag(Old->getLocation(), diag::note_previous_declaration); 626 Invalid = true; 627 } 628 629 if (CheckEquivalentExceptionSpec(Old, New)) 630 Invalid = true; 631 632 return Invalid; 633 } 634 635 /// \brief Merge the exception specifications of two variable declarations. 636 /// 637 /// This is called when there's a redeclaration of a VarDecl. The function 638 /// checks if the redeclaration might have an exception specification and 639 /// validates compatibility and merges the specs if necessary. 640 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 641 // Shortcut if exceptions are disabled. 642 if (!getLangOpts().CXXExceptions) 643 return; 644 645 assert(Context.hasSameType(New->getType(), Old->getType()) && 646 "Should only be called if types are otherwise the same."); 647 648 QualType NewType = New->getType(); 649 QualType OldType = Old->getType(); 650 651 // We're only interested in pointers and references to functions, as well 652 // as pointers to member functions. 653 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 654 NewType = R->getPointeeType(); 655 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 656 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 657 NewType = P->getPointeeType(); 658 OldType = OldType->getAs<PointerType>()->getPointeeType(); 659 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 660 NewType = M->getPointeeType(); 661 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 662 } 663 664 if (!NewType->isFunctionProtoType()) 665 return; 666 667 // There's lots of special cases for functions. For function pointers, system 668 // libraries are hopefully not as broken so that we don't need these 669 // workarounds. 670 if (CheckEquivalentExceptionSpec( 671 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 672 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 673 New->setInvalidDecl(); 674 } 675 } 676 677 /// CheckCXXDefaultArguments - Verify that the default arguments for a 678 /// function declaration are well-formed according to C++ 679 /// [dcl.fct.default]. 680 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 681 unsigned NumParams = FD->getNumParams(); 682 unsigned p; 683 684 // Find first parameter with a default argument 685 for (p = 0; p < NumParams; ++p) { 686 ParmVarDecl *Param = FD->getParamDecl(p); 687 if (Param->hasDefaultArg()) 688 break; 689 } 690 691 // C++ [dcl.fct.default]p4: 692 // In a given function declaration, all parameters 693 // subsequent to a parameter with a default argument shall 694 // have default arguments supplied in this or previous 695 // declarations. A default argument shall not be redefined 696 // by a later declaration (not even to the same value). 697 unsigned LastMissingDefaultArg = 0; 698 for (; p < NumParams; ++p) { 699 ParmVarDecl *Param = FD->getParamDecl(p); 700 if (!Param->hasDefaultArg()) { 701 if (Param->isInvalidDecl()) 702 /* We already complained about this parameter. */; 703 else if (Param->getIdentifier()) 704 Diag(Param->getLocation(), 705 diag::err_param_default_argument_missing_name) 706 << Param->getIdentifier(); 707 else 708 Diag(Param->getLocation(), 709 diag::err_param_default_argument_missing); 710 711 LastMissingDefaultArg = p; 712 } 713 } 714 715 if (LastMissingDefaultArg > 0) { 716 // Some default arguments were missing. Clear out all of the 717 // default arguments up to (and including) the last missing 718 // default argument, so that we leave the function parameters 719 // in a semantically valid state. 720 for (p = 0; p <= LastMissingDefaultArg; ++p) { 721 ParmVarDecl *Param = FD->getParamDecl(p); 722 if (Param->hasDefaultArg()) { 723 Param->setDefaultArg(nullptr); 724 } 725 } 726 } 727 } 728 729 // CheckConstexprParameterTypes - Check whether a function's parameter types 730 // are all literal types. If so, return true. If not, produce a suitable 731 // diagnostic and return false. 732 static bool CheckConstexprParameterTypes(Sema &SemaRef, 733 const FunctionDecl *FD) { 734 unsigned ArgIndex = 0; 735 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 736 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 737 e = FT->param_type_end(); 738 i != e; ++i, ++ArgIndex) { 739 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 740 SourceLocation ParamLoc = PD->getLocation(); 741 if (!(*i)->isDependentType() && 742 SemaRef.RequireLiteralType(ParamLoc, *i, 743 diag::err_constexpr_non_literal_param, 744 ArgIndex+1, PD->getSourceRange(), 745 isa<CXXConstructorDecl>(FD))) 746 return false; 747 } 748 return true; 749 } 750 751 /// \brief Get diagnostic %select index for tag kind for 752 /// record diagnostic message. 753 /// WARNING: Indexes apply to particular diagnostics only! 754 /// 755 /// \returns diagnostic %select index. 756 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 757 switch (Tag) { 758 case TTK_Struct: return 0; 759 case TTK_Interface: return 1; 760 case TTK_Class: return 2; 761 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 762 } 763 } 764 765 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 766 // the requirements of a constexpr function definition or a constexpr 767 // constructor definition. If so, return true. If not, produce appropriate 768 // diagnostics and return false. 769 // 770 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 771 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 772 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 773 if (MD && MD->isInstance()) { 774 // C++11 [dcl.constexpr]p4: 775 // The definition of a constexpr constructor shall satisfy the following 776 // constraints: 777 // - the class shall not have any virtual base classes; 778 const CXXRecordDecl *RD = MD->getParent(); 779 if (RD->getNumVBases()) { 780 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 781 << isa<CXXConstructorDecl>(NewFD) 782 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 783 for (const auto &I : RD->vbases()) 784 Diag(I.getLocStart(), 785 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 786 return false; 787 } 788 } 789 790 if (!isa<CXXConstructorDecl>(NewFD)) { 791 // C++11 [dcl.constexpr]p3: 792 // The definition of a constexpr function shall satisfy the following 793 // constraints: 794 // - it shall not be virtual; 795 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 796 if (Method && Method->isVirtual()) { 797 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 798 799 // If it's not obvious why this function is virtual, find an overridden 800 // function which uses the 'virtual' keyword. 801 const CXXMethodDecl *WrittenVirtual = Method; 802 while (!WrittenVirtual->isVirtualAsWritten()) 803 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 804 if (WrittenVirtual != Method) 805 Diag(WrittenVirtual->getLocation(), 806 diag::note_overridden_virtual_function); 807 return false; 808 } 809 810 // - its return type shall be a literal type; 811 QualType RT = NewFD->getReturnType(); 812 if (!RT->isDependentType() && 813 RequireLiteralType(NewFD->getLocation(), RT, 814 diag::err_constexpr_non_literal_return)) 815 return false; 816 } 817 818 // - each of its parameter types shall be a literal type; 819 if (!CheckConstexprParameterTypes(*this, NewFD)) 820 return false; 821 822 return true; 823 } 824 825 /// Check the given declaration statement is legal within a constexpr function 826 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 827 /// 828 /// \return true if the body is OK (maybe only as an extension), false if we 829 /// have diagnosed a problem. 830 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 831 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 832 // C++11 [dcl.constexpr]p3 and p4: 833 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 834 // contain only 835 for (const auto *DclIt : DS->decls()) { 836 switch (DclIt->getKind()) { 837 case Decl::StaticAssert: 838 case Decl::Using: 839 case Decl::UsingShadow: 840 case Decl::UsingDirective: 841 case Decl::UnresolvedUsingTypename: 842 case Decl::UnresolvedUsingValue: 843 // - static_assert-declarations 844 // - using-declarations, 845 // - using-directives, 846 continue; 847 848 case Decl::Typedef: 849 case Decl::TypeAlias: { 850 // - typedef declarations and alias-declarations that do not define 851 // classes or enumerations, 852 const auto *TN = cast<TypedefNameDecl>(DclIt); 853 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 854 // Don't allow variably-modified types in constexpr functions. 855 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 856 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 857 << TL.getSourceRange() << TL.getType() 858 << isa<CXXConstructorDecl>(Dcl); 859 return false; 860 } 861 continue; 862 } 863 864 case Decl::Enum: 865 case Decl::CXXRecord: 866 // C++1y allows types to be defined, not just declared. 867 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 868 SemaRef.Diag(DS->getLocStart(), 869 SemaRef.getLangOpts().CPlusPlus14 870 ? diag::warn_cxx11_compat_constexpr_type_definition 871 : diag::ext_constexpr_type_definition) 872 << isa<CXXConstructorDecl>(Dcl); 873 continue; 874 875 case Decl::EnumConstant: 876 case Decl::IndirectField: 877 case Decl::ParmVar: 878 // These can only appear with other declarations which are banned in 879 // C++11 and permitted in C++1y, so ignore them. 880 continue; 881 882 case Decl::Var: { 883 // C++1y [dcl.constexpr]p3 allows anything except: 884 // a definition of a variable of non-literal type or of static or 885 // thread storage duration or for which no initialization is performed. 886 const auto *VD = cast<VarDecl>(DclIt); 887 if (VD->isThisDeclarationADefinition()) { 888 if (VD->isStaticLocal()) { 889 SemaRef.Diag(VD->getLocation(), 890 diag::err_constexpr_local_var_static) 891 << isa<CXXConstructorDecl>(Dcl) 892 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 893 return false; 894 } 895 if (!VD->getType()->isDependentType() && 896 SemaRef.RequireLiteralType( 897 VD->getLocation(), VD->getType(), 898 diag::err_constexpr_local_var_non_literal_type, 899 isa<CXXConstructorDecl>(Dcl))) 900 return false; 901 if (!VD->getType()->isDependentType() && 902 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 903 SemaRef.Diag(VD->getLocation(), 904 diag::err_constexpr_local_var_no_init) 905 << isa<CXXConstructorDecl>(Dcl); 906 return false; 907 } 908 } 909 SemaRef.Diag(VD->getLocation(), 910 SemaRef.getLangOpts().CPlusPlus14 911 ? diag::warn_cxx11_compat_constexpr_local_var 912 : diag::ext_constexpr_local_var) 913 << isa<CXXConstructorDecl>(Dcl); 914 continue; 915 } 916 917 case Decl::NamespaceAlias: 918 case Decl::Function: 919 // These are disallowed in C++11 and permitted in C++1y. Allow them 920 // everywhere as an extension. 921 if (!Cxx1yLoc.isValid()) 922 Cxx1yLoc = DS->getLocStart(); 923 continue; 924 925 default: 926 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 927 << isa<CXXConstructorDecl>(Dcl); 928 return false; 929 } 930 } 931 932 return true; 933 } 934 935 /// Check that the given field is initialized within a constexpr constructor. 936 /// 937 /// \param Dcl The constexpr constructor being checked. 938 /// \param Field The field being checked. This may be a member of an anonymous 939 /// struct or union nested within the class being checked. 940 /// \param Inits All declarations, including anonymous struct/union members and 941 /// indirect members, for which any initialization was provided. 942 /// \param Diagnosed Set to true if an error is produced. 943 static void CheckConstexprCtorInitializer(Sema &SemaRef, 944 const FunctionDecl *Dcl, 945 FieldDecl *Field, 946 llvm::SmallSet<Decl*, 16> &Inits, 947 bool &Diagnosed) { 948 if (Field->isInvalidDecl()) 949 return; 950 951 if (Field->isUnnamedBitfield()) 952 return; 953 954 // Anonymous unions with no variant members and empty anonymous structs do not 955 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 956 // indirect fields don't need initializing. 957 if (Field->isAnonymousStructOrUnion() && 958 (Field->getType()->isUnionType() 959 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 960 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 961 return; 962 963 if (!Inits.count(Field)) { 964 if (!Diagnosed) { 965 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 966 Diagnosed = true; 967 } 968 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 969 } else if (Field->isAnonymousStructOrUnion()) { 970 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 971 for (auto *I : RD->fields()) 972 // If an anonymous union contains an anonymous struct of which any member 973 // is initialized, all members must be initialized. 974 if (!RD->isUnion() || Inits.count(I)) 975 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 976 } 977 } 978 979 /// Check the provided statement is allowed in a constexpr function 980 /// definition. 981 static bool 982 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 983 SmallVectorImpl<SourceLocation> &ReturnStmts, 984 SourceLocation &Cxx1yLoc) { 985 // - its function-body shall be [...] a compound-statement that contains only 986 switch (S->getStmtClass()) { 987 case Stmt::NullStmtClass: 988 // - null statements, 989 return true; 990 991 case Stmt::DeclStmtClass: 992 // - static_assert-declarations 993 // - using-declarations, 994 // - using-directives, 995 // - typedef declarations and alias-declarations that do not define 996 // classes or enumerations, 997 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 998 return false; 999 return true; 1000 1001 case Stmt::ReturnStmtClass: 1002 // - and exactly one return statement; 1003 if (isa<CXXConstructorDecl>(Dcl)) { 1004 // C++1y allows return statements in constexpr constructors. 1005 if (!Cxx1yLoc.isValid()) 1006 Cxx1yLoc = S->getLocStart(); 1007 return true; 1008 } 1009 1010 ReturnStmts.push_back(S->getLocStart()); 1011 return true; 1012 1013 case Stmt::CompoundStmtClass: { 1014 // C++1y allows compound-statements. 1015 if (!Cxx1yLoc.isValid()) 1016 Cxx1yLoc = S->getLocStart(); 1017 1018 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1019 for (auto *BodyIt : CompStmt->body()) { 1020 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1021 Cxx1yLoc)) 1022 return false; 1023 } 1024 return true; 1025 } 1026 1027 case Stmt::AttributedStmtClass: 1028 if (!Cxx1yLoc.isValid()) 1029 Cxx1yLoc = S->getLocStart(); 1030 return true; 1031 1032 case Stmt::IfStmtClass: { 1033 // C++1y allows if-statements. 1034 if (!Cxx1yLoc.isValid()) 1035 Cxx1yLoc = S->getLocStart(); 1036 1037 IfStmt *If = cast<IfStmt>(S); 1038 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1039 Cxx1yLoc)) 1040 return false; 1041 if (If->getElse() && 1042 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1043 Cxx1yLoc)) 1044 return false; 1045 return true; 1046 } 1047 1048 case Stmt::WhileStmtClass: 1049 case Stmt::DoStmtClass: 1050 case Stmt::ForStmtClass: 1051 case Stmt::CXXForRangeStmtClass: 1052 case Stmt::ContinueStmtClass: 1053 // C++1y allows all of these. We don't allow them as extensions in C++11, 1054 // because they don't make sense without variable mutation. 1055 if (!SemaRef.getLangOpts().CPlusPlus14) 1056 break; 1057 if (!Cxx1yLoc.isValid()) 1058 Cxx1yLoc = S->getLocStart(); 1059 for (Stmt::child_range Children = S->children(); Children; ++Children) 1060 if (*Children && 1061 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1062 Cxx1yLoc)) 1063 return false; 1064 return true; 1065 1066 case Stmt::SwitchStmtClass: 1067 case Stmt::CaseStmtClass: 1068 case Stmt::DefaultStmtClass: 1069 case Stmt::BreakStmtClass: 1070 // C++1y allows switch-statements, and since they don't need variable 1071 // mutation, we can reasonably allow them in C++11 as an extension. 1072 if (!Cxx1yLoc.isValid()) 1073 Cxx1yLoc = S->getLocStart(); 1074 for (Stmt::child_range Children = S->children(); Children; ++Children) 1075 if (*Children && 1076 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1077 Cxx1yLoc)) 1078 return false; 1079 return true; 1080 1081 default: 1082 if (!isa<Expr>(S)) 1083 break; 1084 1085 // C++1y allows expression-statements. 1086 if (!Cxx1yLoc.isValid()) 1087 Cxx1yLoc = S->getLocStart(); 1088 return true; 1089 } 1090 1091 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1092 << isa<CXXConstructorDecl>(Dcl); 1093 return false; 1094 } 1095 1096 /// Check the body for the given constexpr function declaration only contains 1097 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1098 /// 1099 /// \return true if the body is OK, false if we have diagnosed a problem. 1100 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1101 if (isa<CXXTryStmt>(Body)) { 1102 // C++11 [dcl.constexpr]p3: 1103 // The definition of a constexpr function shall satisfy the following 1104 // constraints: [...] 1105 // - its function-body shall be = delete, = default, or a 1106 // compound-statement 1107 // 1108 // C++11 [dcl.constexpr]p4: 1109 // In the definition of a constexpr constructor, [...] 1110 // - its function-body shall not be a function-try-block; 1111 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1112 << isa<CXXConstructorDecl>(Dcl); 1113 return false; 1114 } 1115 1116 SmallVector<SourceLocation, 4> ReturnStmts; 1117 1118 // - its function-body shall be [...] a compound-statement that contains only 1119 // [... list of cases ...] 1120 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1121 SourceLocation Cxx1yLoc; 1122 for (auto *BodyIt : CompBody->body()) { 1123 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1124 return false; 1125 } 1126 1127 if (Cxx1yLoc.isValid()) 1128 Diag(Cxx1yLoc, 1129 getLangOpts().CPlusPlus14 1130 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1131 : diag::ext_constexpr_body_invalid_stmt) 1132 << isa<CXXConstructorDecl>(Dcl); 1133 1134 if (const CXXConstructorDecl *Constructor 1135 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1136 const CXXRecordDecl *RD = Constructor->getParent(); 1137 // DR1359: 1138 // - every non-variant non-static data member and base class sub-object 1139 // shall be initialized; 1140 // DR1460: 1141 // - if the class is a union having variant members, exactly one of them 1142 // shall be initialized; 1143 if (RD->isUnion()) { 1144 if (Constructor->getNumCtorInitializers() == 0 && 1145 RD->hasVariantMembers()) { 1146 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1147 return false; 1148 } 1149 } else if (!Constructor->isDependentContext() && 1150 !Constructor->isDelegatingConstructor()) { 1151 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1152 1153 // Skip detailed checking if we have enough initializers, and we would 1154 // allow at most one initializer per member. 1155 bool AnyAnonStructUnionMembers = false; 1156 unsigned Fields = 0; 1157 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1158 E = RD->field_end(); I != E; ++I, ++Fields) { 1159 if (I->isAnonymousStructOrUnion()) { 1160 AnyAnonStructUnionMembers = true; 1161 break; 1162 } 1163 } 1164 // DR1460: 1165 // - if the class is a union-like class, but is not a union, for each of 1166 // its anonymous union members having variant members, exactly one of 1167 // them shall be initialized; 1168 if (AnyAnonStructUnionMembers || 1169 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1170 // Check initialization of non-static data members. Base classes are 1171 // always initialized so do not need to be checked. Dependent bases 1172 // might not have initializers in the member initializer list. 1173 llvm::SmallSet<Decl*, 16> Inits; 1174 for (const auto *I: Constructor->inits()) { 1175 if (FieldDecl *FD = I->getMember()) 1176 Inits.insert(FD); 1177 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1178 Inits.insert(ID->chain_begin(), ID->chain_end()); 1179 } 1180 1181 bool Diagnosed = false; 1182 for (auto *I : RD->fields()) 1183 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1184 if (Diagnosed) 1185 return false; 1186 } 1187 } 1188 } else { 1189 if (ReturnStmts.empty()) { 1190 // C++1y doesn't require constexpr functions to contain a 'return' 1191 // statement. We still do, unless the return type might be void, because 1192 // otherwise if there's no return statement, the function cannot 1193 // be used in a core constant expression. 1194 bool OK = getLangOpts().CPlusPlus14 && 1195 (Dcl->getReturnType()->isVoidType() || 1196 Dcl->getReturnType()->isDependentType()); 1197 Diag(Dcl->getLocation(), 1198 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1199 : diag::err_constexpr_body_no_return); 1200 return OK; 1201 } 1202 if (ReturnStmts.size() > 1) { 1203 Diag(ReturnStmts.back(), 1204 getLangOpts().CPlusPlus14 1205 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1206 : diag::ext_constexpr_body_multiple_return); 1207 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1208 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1209 } 1210 } 1211 1212 // C++11 [dcl.constexpr]p5: 1213 // if no function argument values exist such that the function invocation 1214 // substitution would produce a constant expression, the program is 1215 // ill-formed; no diagnostic required. 1216 // C++11 [dcl.constexpr]p3: 1217 // - every constructor call and implicit conversion used in initializing the 1218 // return value shall be one of those allowed in a constant expression. 1219 // C++11 [dcl.constexpr]p4: 1220 // - every constructor involved in initializing non-static data members and 1221 // base class sub-objects shall be a constexpr constructor. 1222 SmallVector<PartialDiagnosticAt, 8> Diags; 1223 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1224 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1225 << isa<CXXConstructorDecl>(Dcl); 1226 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1227 Diag(Diags[I].first, Diags[I].second); 1228 // Don't return false here: we allow this for compatibility in 1229 // system headers. 1230 } 1231 1232 return true; 1233 } 1234 1235 /// isCurrentClassName - Determine whether the identifier II is the 1236 /// name of the class type currently being defined. In the case of 1237 /// nested classes, this will only return true if II is the name of 1238 /// the innermost class. 1239 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1240 const CXXScopeSpec *SS) { 1241 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1242 1243 CXXRecordDecl *CurDecl; 1244 if (SS && SS->isSet() && !SS->isInvalid()) { 1245 DeclContext *DC = computeDeclContext(*SS, true); 1246 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1247 } else 1248 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1249 1250 if (CurDecl && CurDecl->getIdentifier()) 1251 return &II == CurDecl->getIdentifier(); 1252 return false; 1253 } 1254 1255 /// \brief Determine whether the identifier II is a typo for the name of 1256 /// the class type currently being defined. If so, update it to the identifier 1257 /// that should have been used. 1258 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1259 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1260 1261 if (!getLangOpts().SpellChecking) 1262 return false; 1263 1264 CXXRecordDecl *CurDecl; 1265 if (SS && SS->isSet() && !SS->isInvalid()) { 1266 DeclContext *DC = computeDeclContext(*SS, true); 1267 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1268 } else 1269 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1270 1271 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1272 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1273 < II->getLength()) { 1274 II = CurDecl->getIdentifier(); 1275 return true; 1276 } 1277 1278 return false; 1279 } 1280 1281 /// \brief Determine whether the given class is a base class of the given 1282 /// class, including looking at dependent bases. 1283 static bool findCircularInheritance(const CXXRecordDecl *Class, 1284 const CXXRecordDecl *Current) { 1285 SmallVector<const CXXRecordDecl*, 8> Queue; 1286 1287 Class = Class->getCanonicalDecl(); 1288 while (true) { 1289 for (const auto &I : Current->bases()) { 1290 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1291 if (!Base) 1292 continue; 1293 1294 Base = Base->getDefinition(); 1295 if (!Base) 1296 continue; 1297 1298 if (Base->getCanonicalDecl() == Class) 1299 return true; 1300 1301 Queue.push_back(Base); 1302 } 1303 1304 if (Queue.empty()) 1305 return false; 1306 1307 Current = Queue.pop_back_val(); 1308 } 1309 1310 return false; 1311 } 1312 1313 /// \brief Perform propagation of DLL attributes from a derived class to a 1314 /// templated base class for MS compatibility. 1315 static void propagateDLLAttrToBaseClassTemplate( 1316 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1317 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1318 if (getDLLAttr( 1319 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1320 // If the base class template has a DLL attribute, don't try to change it. 1321 return; 1322 } 1323 1324 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1325 // If the base class is not already specialized, we can do the propagation. 1326 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1327 NewAttr->setInherited(true); 1328 BaseTemplateSpec->addAttr(NewAttr); 1329 return; 1330 } 1331 1332 bool DifferentAttribute = false; 1333 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1334 if (!SpecializationAttr->isInherited()) { 1335 // The template has previously been specialized or instantiated with an 1336 // explicit attribute. We should not try to change it. 1337 return; 1338 } 1339 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1340 // The specialization already has the right attribute. 1341 return; 1342 } 1343 DifferentAttribute = true; 1344 } 1345 1346 // The template was previously instantiated or explicitly specialized without 1347 // a dll attribute, or the template was previously instantiated with a 1348 // different inherited attribute. It's too late for us to change the 1349 // attribute, so warn that this is unsupported. 1350 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1351 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1352 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1353 if (BaseTemplateSpec->isExplicitSpecialization()) { 1354 S.Diag(BaseTemplateSpec->getLocation(), 1355 diag::note_template_class_explicit_specialization_was_here) 1356 << BaseTemplateSpec; 1357 } else { 1358 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1359 diag::note_template_class_instantiation_was_here) 1360 << BaseTemplateSpec; 1361 } 1362 } 1363 1364 /// \brief Check the validity of a C++ base class specifier. 1365 /// 1366 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1367 /// and returns NULL otherwise. 1368 CXXBaseSpecifier * 1369 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1370 SourceRange SpecifierRange, 1371 bool Virtual, AccessSpecifier Access, 1372 TypeSourceInfo *TInfo, 1373 SourceLocation EllipsisLoc) { 1374 QualType BaseType = TInfo->getType(); 1375 1376 // C++ [class.union]p1: 1377 // A union shall not have base classes. 1378 if (Class->isUnion()) { 1379 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1380 << SpecifierRange; 1381 return nullptr; 1382 } 1383 1384 if (EllipsisLoc.isValid() && 1385 !TInfo->getType()->containsUnexpandedParameterPack()) { 1386 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1387 << TInfo->getTypeLoc().getSourceRange(); 1388 EllipsisLoc = SourceLocation(); 1389 } 1390 1391 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1392 1393 if (BaseType->isDependentType()) { 1394 // Make sure that we don't have circular inheritance among our dependent 1395 // bases. For non-dependent bases, the check for completeness below handles 1396 // this. 1397 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1398 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1399 ((BaseDecl = BaseDecl->getDefinition()) && 1400 findCircularInheritance(Class, BaseDecl))) { 1401 Diag(BaseLoc, diag::err_circular_inheritance) 1402 << BaseType << Context.getTypeDeclType(Class); 1403 1404 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1405 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1406 << BaseType; 1407 1408 return nullptr; 1409 } 1410 } 1411 1412 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1413 Class->getTagKind() == TTK_Class, 1414 Access, TInfo, EllipsisLoc); 1415 } 1416 1417 // Base specifiers must be record types. 1418 if (!BaseType->isRecordType()) { 1419 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1420 return nullptr; 1421 } 1422 1423 // C++ [class.union]p1: 1424 // A union shall not be used as a base class. 1425 if (BaseType->isUnionType()) { 1426 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1427 return nullptr; 1428 } 1429 1430 // For the MS ABI, propagate DLL attributes to base class templates. 1431 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1432 if (Attr *ClassAttr = getDLLAttr(Class)) { 1433 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1434 BaseType->getAsCXXRecordDecl())) { 1435 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1436 BaseTemplate, BaseLoc); 1437 } 1438 } 1439 } 1440 1441 // C++ [class.derived]p2: 1442 // The class-name in a base-specifier shall not be an incompletely 1443 // defined class. 1444 if (RequireCompleteType(BaseLoc, BaseType, 1445 diag::err_incomplete_base_class, SpecifierRange)) { 1446 Class->setInvalidDecl(); 1447 return nullptr; 1448 } 1449 1450 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1451 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1452 assert(BaseDecl && "Record type has no declaration"); 1453 BaseDecl = BaseDecl->getDefinition(); 1454 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1455 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1456 assert(CXXBaseDecl && "Base type is not a C++ type"); 1457 1458 // A class which contains a flexible array member is not suitable for use as a 1459 // base class: 1460 // - If the layout determines that a base comes before another base, 1461 // the flexible array member would index into the subsequent base. 1462 // - If the layout determines that base comes before the derived class, 1463 // the flexible array member would index into the derived class. 1464 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1465 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1466 << CXXBaseDecl->getDeclName(); 1467 return nullptr; 1468 } 1469 1470 // C++ [class]p3: 1471 // If a class is marked final and it appears as a base-type-specifier in 1472 // base-clause, the program is ill-formed. 1473 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1474 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1475 << CXXBaseDecl->getDeclName() 1476 << FA->isSpelledAsSealed(); 1477 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1478 << CXXBaseDecl->getDeclName() << FA->getRange(); 1479 return nullptr; 1480 } 1481 1482 if (BaseDecl->isInvalidDecl()) 1483 Class->setInvalidDecl(); 1484 1485 // Create the base specifier. 1486 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1487 Class->getTagKind() == TTK_Class, 1488 Access, TInfo, EllipsisLoc); 1489 } 1490 1491 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1492 /// one entry in the base class list of a class specifier, for 1493 /// example: 1494 /// class foo : public bar, virtual private baz { 1495 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1496 BaseResult 1497 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1498 ParsedAttributes &Attributes, 1499 bool Virtual, AccessSpecifier Access, 1500 ParsedType basetype, SourceLocation BaseLoc, 1501 SourceLocation EllipsisLoc) { 1502 if (!classdecl) 1503 return true; 1504 1505 AdjustDeclIfTemplate(classdecl); 1506 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1507 if (!Class) 1508 return true; 1509 1510 // We haven't yet attached the base specifiers. 1511 Class->setIsParsingBaseSpecifiers(); 1512 1513 // We do not support any C++11 attributes on base-specifiers yet. 1514 // Diagnose any attributes we see. 1515 if (!Attributes.empty()) { 1516 for (AttributeList *Attr = Attributes.getList(); Attr; 1517 Attr = Attr->getNext()) { 1518 if (Attr->isInvalid() || 1519 Attr->getKind() == AttributeList::IgnoredAttribute) 1520 continue; 1521 Diag(Attr->getLoc(), 1522 Attr->getKind() == AttributeList::UnknownAttribute 1523 ? diag::warn_unknown_attribute_ignored 1524 : diag::err_base_specifier_attribute) 1525 << Attr->getName(); 1526 } 1527 } 1528 1529 TypeSourceInfo *TInfo = nullptr; 1530 GetTypeFromParser(basetype, &TInfo); 1531 1532 if (EllipsisLoc.isInvalid() && 1533 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1534 UPPC_BaseType)) 1535 return true; 1536 1537 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1538 Virtual, Access, TInfo, 1539 EllipsisLoc)) 1540 return BaseSpec; 1541 else 1542 Class->setInvalidDecl(); 1543 1544 return true; 1545 } 1546 1547 /// Use small set to collect indirect bases. As this is only used 1548 /// locally, there's no need to abstract the small size parameter. 1549 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 1550 1551 /// \brief Recursively add the bases of Type. Don't add Type itself. 1552 static void 1553 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 1554 const QualType &Type) 1555 { 1556 // Even though the incoming type is a base, it might not be 1557 // a class -- it could be a template parm, for instance. 1558 if (auto Rec = Type->getAs<RecordType>()) { 1559 auto Decl = Rec->getAsCXXRecordDecl(); 1560 1561 // Iterate over its bases. 1562 for (const auto &BaseSpec : Decl->bases()) { 1563 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 1564 .getUnqualifiedType(); 1565 if (Set.insert(Base).second) 1566 // If we've not already seen it, recurse. 1567 NoteIndirectBases(Context, Set, Base); 1568 } 1569 } 1570 } 1571 1572 /// \brief Performs the actual work of attaching the given base class 1573 /// specifiers to a C++ class. 1574 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1575 unsigned NumBases) { 1576 if (NumBases == 0) 1577 return false; 1578 1579 // Used to keep track of which base types we have already seen, so 1580 // that we can properly diagnose redundant direct base types. Note 1581 // that the key is always the unqualified canonical type of the base 1582 // class. 1583 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1584 1585 // Used to track indirect bases so we can see if a direct base is 1586 // ambiguous. 1587 IndirectBaseSet IndirectBaseTypes; 1588 1589 // Copy non-redundant base specifiers into permanent storage. 1590 unsigned NumGoodBases = 0; 1591 bool Invalid = false; 1592 for (unsigned idx = 0; idx < NumBases; ++idx) { 1593 QualType NewBaseType 1594 = Context.getCanonicalType(Bases[idx]->getType()); 1595 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1596 1597 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1598 if (KnownBase) { 1599 // C++ [class.mi]p3: 1600 // A class shall not be specified as a direct base class of a 1601 // derived class more than once. 1602 Diag(Bases[idx]->getLocStart(), 1603 diag::err_duplicate_base_class) 1604 << KnownBase->getType() 1605 << Bases[idx]->getSourceRange(); 1606 1607 // Delete the duplicate base class specifier; we're going to 1608 // overwrite its pointer later. 1609 Context.Deallocate(Bases[idx]); 1610 1611 Invalid = true; 1612 } else { 1613 // Okay, add this new base class. 1614 KnownBase = Bases[idx]; 1615 Bases[NumGoodBases++] = Bases[idx]; 1616 1617 // Note this base's direct & indirect bases, if there could be ambiguity. 1618 if (NumBases > 1) 1619 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 1620 1621 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1622 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1623 if (Class->isInterface() && 1624 (!RD->isInterface() || 1625 KnownBase->getAccessSpecifier() != AS_public)) { 1626 // The Microsoft extension __interface does not permit bases that 1627 // are not themselves public interfaces. 1628 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1629 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1630 << RD->getSourceRange(); 1631 Invalid = true; 1632 } 1633 if (RD->hasAttr<WeakAttr>()) 1634 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1635 } 1636 } 1637 } 1638 1639 // Attach the remaining base class specifiers to the derived class. 1640 Class->setBases(Bases, NumGoodBases); 1641 1642 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 1643 // Check whether this direct base is inaccessible due to ambiguity. 1644 QualType BaseType = Bases[idx]->getType(); 1645 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 1646 .getUnqualifiedType(); 1647 1648 if (IndirectBaseTypes.count(CanonicalBase)) { 1649 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1650 /*DetectVirtual=*/true); 1651 bool found 1652 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 1653 assert(found); 1654 (void)found; 1655 1656 if (Paths.isAmbiguous(CanonicalBase)) 1657 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 1658 << BaseType << getAmbiguousPathsDisplayString(Paths) 1659 << Bases[idx]->getSourceRange(); 1660 else 1661 assert(Bases[idx]->isVirtual()); 1662 } 1663 1664 // Delete the base class specifier, since its data has been copied 1665 // into the CXXRecordDecl. 1666 Context.Deallocate(Bases[idx]); 1667 } 1668 1669 return Invalid; 1670 } 1671 1672 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1673 /// class, after checking whether there are any duplicate base 1674 /// classes. 1675 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1676 unsigned NumBases) { 1677 if (!ClassDecl || !Bases || !NumBases) 1678 return; 1679 1680 AdjustDeclIfTemplate(ClassDecl); 1681 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1682 } 1683 1684 /// \brief Determine whether the type \p Derived is a C++ class that is 1685 /// derived from the type \p Base. 1686 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1687 if (!getLangOpts().CPlusPlus) 1688 return false; 1689 1690 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1691 if (!DerivedRD) 1692 return false; 1693 1694 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1695 if (!BaseRD) 1696 return false; 1697 1698 // If either the base or the derived type is invalid, don't try to 1699 // check whether one is derived from the other. 1700 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1701 return false; 1702 1703 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1704 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1705 } 1706 1707 /// \brief Determine whether the type \p Derived is a C++ class that is 1708 /// derived from the type \p Base. 1709 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1710 if (!getLangOpts().CPlusPlus) 1711 return false; 1712 1713 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1714 if (!DerivedRD) 1715 return false; 1716 1717 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1718 if (!BaseRD) 1719 return false; 1720 1721 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1722 } 1723 1724 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1725 CXXCastPath &BasePathArray) { 1726 assert(BasePathArray.empty() && "Base path array must be empty!"); 1727 assert(Paths.isRecordingPaths() && "Must record paths!"); 1728 1729 const CXXBasePath &Path = Paths.front(); 1730 1731 // We first go backward and check if we have a virtual base. 1732 // FIXME: It would be better if CXXBasePath had the base specifier for 1733 // the nearest virtual base. 1734 unsigned Start = 0; 1735 for (unsigned I = Path.size(); I != 0; --I) { 1736 if (Path[I - 1].Base->isVirtual()) { 1737 Start = I - 1; 1738 break; 1739 } 1740 } 1741 1742 // Now add all bases. 1743 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1744 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1745 } 1746 1747 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1748 /// conversion (where Derived and Base are class types) is 1749 /// well-formed, meaning that the conversion is unambiguous (and 1750 /// that all of the base classes are accessible). Returns true 1751 /// and emits a diagnostic if the code is ill-formed, returns false 1752 /// otherwise. Loc is the location where this routine should point to 1753 /// if there is an error, and Range is the source range to highlight 1754 /// if there is an error. 1755 bool 1756 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1757 unsigned InaccessibleBaseID, 1758 unsigned AmbigiousBaseConvID, 1759 SourceLocation Loc, SourceRange Range, 1760 DeclarationName Name, 1761 CXXCastPath *BasePath) { 1762 // First, determine whether the path from Derived to Base is 1763 // ambiguous. This is slightly more expensive than checking whether 1764 // the Derived to Base conversion exists, because here we need to 1765 // explore multiple paths to determine if there is an ambiguity. 1766 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1767 /*DetectVirtual=*/false); 1768 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1769 assert(DerivationOkay && 1770 "Can only be used with a derived-to-base conversion"); 1771 (void)DerivationOkay; 1772 1773 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1774 if (InaccessibleBaseID) { 1775 // Check that the base class can be accessed. 1776 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1777 InaccessibleBaseID)) { 1778 case AR_inaccessible: 1779 return true; 1780 case AR_accessible: 1781 case AR_dependent: 1782 case AR_delayed: 1783 break; 1784 } 1785 } 1786 1787 // Build a base path if necessary. 1788 if (BasePath) 1789 BuildBasePathArray(Paths, *BasePath); 1790 return false; 1791 } 1792 1793 if (AmbigiousBaseConvID) { 1794 // We know that the derived-to-base conversion is ambiguous, and 1795 // we're going to produce a diagnostic. Perform the derived-to-base 1796 // search just one more time to compute all of the possible paths so 1797 // that we can print them out. This is more expensive than any of 1798 // the previous derived-to-base checks we've done, but at this point 1799 // performance isn't as much of an issue. 1800 Paths.clear(); 1801 Paths.setRecordingPaths(true); 1802 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1803 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1804 (void)StillOkay; 1805 1806 // Build up a textual representation of the ambiguous paths, e.g., 1807 // D -> B -> A, that will be used to illustrate the ambiguous 1808 // conversions in the diagnostic. We only print one of the paths 1809 // to each base class subobject. 1810 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1811 1812 Diag(Loc, AmbigiousBaseConvID) 1813 << Derived << Base << PathDisplayStr << Range << Name; 1814 } 1815 return true; 1816 } 1817 1818 bool 1819 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1820 SourceLocation Loc, SourceRange Range, 1821 CXXCastPath *BasePath, 1822 bool IgnoreAccess) { 1823 return CheckDerivedToBaseConversion(Derived, Base, 1824 IgnoreAccess ? 0 1825 : diag::err_upcast_to_inaccessible_base, 1826 diag::err_ambiguous_derived_to_base_conv, 1827 Loc, Range, DeclarationName(), 1828 BasePath); 1829 } 1830 1831 1832 /// @brief Builds a string representing ambiguous paths from a 1833 /// specific derived class to different subobjects of the same base 1834 /// class. 1835 /// 1836 /// This function builds a string that can be used in error messages 1837 /// to show the different paths that one can take through the 1838 /// inheritance hierarchy to go from the derived class to different 1839 /// subobjects of a base class. The result looks something like this: 1840 /// @code 1841 /// struct D -> struct B -> struct A 1842 /// struct D -> struct C -> struct A 1843 /// @endcode 1844 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1845 std::string PathDisplayStr; 1846 std::set<unsigned> DisplayedPaths; 1847 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1848 Path != Paths.end(); ++Path) { 1849 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1850 // We haven't displayed a path to this particular base 1851 // class subobject yet. 1852 PathDisplayStr += "\n "; 1853 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1854 for (CXXBasePath::const_iterator Element = Path->begin(); 1855 Element != Path->end(); ++Element) 1856 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1857 } 1858 } 1859 1860 return PathDisplayStr; 1861 } 1862 1863 //===----------------------------------------------------------------------===// 1864 // C++ class member Handling 1865 //===----------------------------------------------------------------------===// 1866 1867 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1868 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1869 SourceLocation ASLoc, 1870 SourceLocation ColonLoc, 1871 AttributeList *Attrs) { 1872 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1873 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1874 ASLoc, ColonLoc); 1875 CurContext->addHiddenDecl(ASDecl); 1876 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1877 } 1878 1879 /// CheckOverrideControl - Check C++11 override control semantics. 1880 void Sema::CheckOverrideControl(NamedDecl *D) { 1881 if (D->isInvalidDecl()) 1882 return; 1883 1884 // We only care about "override" and "final" declarations. 1885 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1886 return; 1887 1888 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1889 1890 // We can't check dependent instance methods. 1891 if (MD && MD->isInstance() && 1892 (MD->getParent()->hasAnyDependentBases() || 1893 MD->getType()->isDependentType())) 1894 return; 1895 1896 if (MD && !MD->isVirtual()) { 1897 // If we have a non-virtual method, check if if hides a virtual method. 1898 // (In that case, it's most likely the method has the wrong type.) 1899 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1900 FindHiddenVirtualMethods(MD, OverloadedMethods); 1901 1902 if (!OverloadedMethods.empty()) { 1903 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1904 Diag(OA->getLocation(), 1905 diag::override_keyword_hides_virtual_member_function) 1906 << "override" << (OverloadedMethods.size() > 1); 1907 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1908 Diag(FA->getLocation(), 1909 diag::override_keyword_hides_virtual_member_function) 1910 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1911 << (OverloadedMethods.size() > 1); 1912 } 1913 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1914 MD->setInvalidDecl(); 1915 return; 1916 } 1917 // Fall through into the general case diagnostic. 1918 // FIXME: We might want to attempt typo correction here. 1919 } 1920 1921 if (!MD || !MD->isVirtual()) { 1922 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1923 Diag(OA->getLocation(), 1924 diag::override_keyword_only_allowed_on_virtual_member_functions) 1925 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1926 D->dropAttr<OverrideAttr>(); 1927 } 1928 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1929 Diag(FA->getLocation(), 1930 diag::override_keyword_only_allowed_on_virtual_member_functions) 1931 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1932 << FixItHint::CreateRemoval(FA->getLocation()); 1933 D->dropAttr<FinalAttr>(); 1934 } 1935 return; 1936 } 1937 1938 // C++11 [class.virtual]p5: 1939 // If a function is marked with the virt-specifier override and 1940 // does not override a member function of a base class, the program is 1941 // ill-formed. 1942 bool HasOverriddenMethods = 1943 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1944 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1945 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1946 << MD->getDeclName(); 1947 } 1948 1949 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1950 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1951 return; 1952 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1953 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1954 isa<CXXDestructorDecl>(MD)) 1955 return; 1956 1957 SourceLocation Loc = MD->getLocation(); 1958 SourceLocation SpellingLoc = Loc; 1959 if (getSourceManager().isMacroArgExpansion(Loc)) 1960 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1961 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1962 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1963 return; 1964 1965 if (MD->size_overridden_methods() > 0) { 1966 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 1967 << MD->getDeclName(); 1968 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 1969 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 1970 } 1971 } 1972 1973 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1974 /// function overrides a virtual member function marked 'final', according to 1975 /// C++11 [class.virtual]p4. 1976 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1977 const CXXMethodDecl *Old) { 1978 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1979 if (!FA) 1980 return false; 1981 1982 Diag(New->getLocation(), diag::err_final_function_overridden) 1983 << New->getDeclName() 1984 << FA->isSpelledAsSealed(); 1985 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1986 return true; 1987 } 1988 1989 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1990 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1991 // FIXME: Destruction of ObjC lifetime types has side-effects. 1992 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1993 return !RD->isCompleteDefinition() || 1994 !RD->hasTrivialDefaultConstructor() || 1995 !RD->hasTrivialDestructor(); 1996 return false; 1997 } 1998 1999 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2000 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2001 if (it->isDeclspecPropertyAttribute()) 2002 return it; 2003 return nullptr; 2004 } 2005 2006 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2007 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2008 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2009 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2010 /// present (but parsing it has been deferred). 2011 NamedDecl * 2012 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2013 MultiTemplateParamsArg TemplateParameterLists, 2014 Expr *BW, const VirtSpecifiers &VS, 2015 InClassInitStyle InitStyle) { 2016 const DeclSpec &DS = D.getDeclSpec(); 2017 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2018 DeclarationName Name = NameInfo.getName(); 2019 SourceLocation Loc = NameInfo.getLoc(); 2020 2021 // For anonymous bitfields, the location should point to the type. 2022 if (Loc.isInvalid()) 2023 Loc = D.getLocStart(); 2024 2025 Expr *BitWidth = static_cast<Expr*>(BW); 2026 2027 assert(isa<CXXRecordDecl>(CurContext)); 2028 assert(!DS.isFriendSpecified()); 2029 2030 bool isFunc = D.isDeclarationOfFunction(); 2031 2032 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2033 // The Microsoft extension __interface only permits public member functions 2034 // and prohibits constructors, destructors, operators, non-public member 2035 // functions, static methods and data members. 2036 unsigned InvalidDecl; 2037 bool ShowDeclName = true; 2038 if (!isFunc) 2039 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2040 else if (AS != AS_public) 2041 InvalidDecl = 2; 2042 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2043 InvalidDecl = 3; 2044 else switch (Name.getNameKind()) { 2045 case DeclarationName::CXXConstructorName: 2046 InvalidDecl = 4; 2047 ShowDeclName = false; 2048 break; 2049 2050 case DeclarationName::CXXDestructorName: 2051 InvalidDecl = 5; 2052 ShowDeclName = false; 2053 break; 2054 2055 case DeclarationName::CXXOperatorName: 2056 case DeclarationName::CXXConversionFunctionName: 2057 InvalidDecl = 6; 2058 break; 2059 2060 default: 2061 InvalidDecl = 0; 2062 break; 2063 } 2064 2065 if (InvalidDecl) { 2066 if (ShowDeclName) 2067 Diag(Loc, diag::err_invalid_member_in_interface) 2068 << (InvalidDecl-1) << Name; 2069 else 2070 Diag(Loc, diag::err_invalid_member_in_interface) 2071 << (InvalidDecl-1) << ""; 2072 return nullptr; 2073 } 2074 } 2075 2076 // C++ 9.2p6: A member shall not be declared to have automatic storage 2077 // duration (auto, register) or with the extern storage-class-specifier. 2078 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2079 // data members and cannot be applied to names declared const or static, 2080 // and cannot be applied to reference members. 2081 switch (DS.getStorageClassSpec()) { 2082 case DeclSpec::SCS_unspecified: 2083 case DeclSpec::SCS_typedef: 2084 case DeclSpec::SCS_static: 2085 break; 2086 case DeclSpec::SCS_mutable: 2087 if (isFunc) { 2088 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2089 2090 // FIXME: It would be nicer if the keyword was ignored only for this 2091 // declarator. Otherwise we could get follow-up errors. 2092 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2093 } 2094 break; 2095 default: 2096 Diag(DS.getStorageClassSpecLoc(), 2097 diag::err_storageclass_invalid_for_member); 2098 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2099 break; 2100 } 2101 2102 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2103 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2104 !isFunc); 2105 2106 if (DS.isConstexprSpecified() && isInstField) { 2107 SemaDiagnosticBuilder B = 2108 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2109 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2110 if (InitStyle == ICIS_NoInit) { 2111 B << 0 << 0; 2112 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2113 B << FixItHint::CreateRemoval(ConstexprLoc); 2114 else { 2115 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2116 D.getMutableDeclSpec().ClearConstexprSpec(); 2117 const char *PrevSpec; 2118 unsigned DiagID; 2119 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2120 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2121 (void)Failed; 2122 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2123 } 2124 } else { 2125 B << 1; 2126 const char *PrevSpec; 2127 unsigned DiagID; 2128 if (D.getMutableDeclSpec().SetStorageClassSpec( 2129 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2130 Context.getPrintingPolicy())) { 2131 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2132 "This is the only DeclSpec that should fail to be applied"); 2133 B << 1; 2134 } else { 2135 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2136 isInstField = false; 2137 } 2138 } 2139 } 2140 2141 NamedDecl *Member; 2142 if (isInstField) { 2143 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2144 2145 // Data members must have identifiers for names. 2146 if (!Name.isIdentifier()) { 2147 Diag(Loc, diag::err_bad_variable_name) 2148 << Name; 2149 return nullptr; 2150 } 2151 2152 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2153 2154 // Member field could not be with "template" keyword. 2155 // So TemplateParameterLists should be empty in this case. 2156 if (TemplateParameterLists.size()) { 2157 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2158 if (TemplateParams->size()) { 2159 // There is no such thing as a member field template. 2160 Diag(D.getIdentifierLoc(), diag::err_template_member) 2161 << II 2162 << SourceRange(TemplateParams->getTemplateLoc(), 2163 TemplateParams->getRAngleLoc()); 2164 } else { 2165 // There is an extraneous 'template<>' for this member. 2166 Diag(TemplateParams->getTemplateLoc(), 2167 diag::err_template_member_noparams) 2168 << II 2169 << SourceRange(TemplateParams->getTemplateLoc(), 2170 TemplateParams->getRAngleLoc()); 2171 } 2172 return nullptr; 2173 } 2174 2175 if (SS.isSet() && !SS.isInvalid()) { 2176 // The user provided a superfluous scope specifier inside a class 2177 // definition: 2178 // 2179 // class X { 2180 // int X::member; 2181 // }; 2182 if (DeclContext *DC = computeDeclContext(SS, false)) 2183 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2184 else 2185 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2186 << Name << SS.getRange(); 2187 2188 SS.clear(); 2189 } 2190 2191 AttributeList *MSPropertyAttr = 2192 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2193 if (MSPropertyAttr) { 2194 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2195 BitWidth, InitStyle, AS, MSPropertyAttr); 2196 if (!Member) 2197 return nullptr; 2198 isInstField = false; 2199 } else { 2200 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2201 BitWidth, InitStyle, AS); 2202 assert(Member && "HandleField never returns null"); 2203 } 2204 } else { 2205 assert(InitStyle == ICIS_NoInit || 2206 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2207 2208 Member = HandleDeclarator(S, D, TemplateParameterLists); 2209 if (!Member) 2210 return nullptr; 2211 2212 // Non-instance-fields can't have a bitfield. 2213 if (BitWidth) { 2214 if (Member->isInvalidDecl()) { 2215 // don't emit another diagnostic. 2216 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 2217 // C++ 9.6p3: A bit-field shall not be a static member. 2218 // "static member 'A' cannot be a bit-field" 2219 Diag(Loc, diag::err_static_not_bitfield) 2220 << Name << BitWidth->getSourceRange(); 2221 } else if (isa<TypedefDecl>(Member)) { 2222 // "typedef member 'x' cannot be a bit-field" 2223 Diag(Loc, diag::err_typedef_not_bitfield) 2224 << Name << BitWidth->getSourceRange(); 2225 } else { 2226 // A function typedef ("typedef int f(); f a;"). 2227 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2228 Diag(Loc, diag::err_not_integral_type_bitfield) 2229 << Name << cast<ValueDecl>(Member)->getType() 2230 << BitWidth->getSourceRange(); 2231 } 2232 2233 BitWidth = nullptr; 2234 Member->setInvalidDecl(); 2235 } 2236 2237 Member->setAccess(AS); 2238 2239 // If we have declared a member function template or static data member 2240 // template, set the access of the templated declaration as well. 2241 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2242 FunTmpl->getTemplatedDecl()->setAccess(AS); 2243 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2244 VarTmpl->getTemplatedDecl()->setAccess(AS); 2245 } 2246 2247 if (VS.isOverrideSpecified()) 2248 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2249 if (VS.isFinalSpecified()) 2250 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2251 VS.isFinalSpelledSealed())); 2252 2253 if (VS.getLastLocation().isValid()) { 2254 // Update the end location of a method that has a virt-specifiers. 2255 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2256 MD->setRangeEnd(VS.getLastLocation()); 2257 } 2258 2259 CheckOverrideControl(Member); 2260 2261 assert((Name || isInstField) && "No identifier for non-field ?"); 2262 2263 if (isInstField) { 2264 FieldDecl *FD = cast<FieldDecl>(Member); 2265 FieldCollector->Add(FD); 2266 2267 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2268 // Remember all explicit private FieldDecls that have a name, no side 2269 // effects and are not part of a dependent type declaration. 2270 if (!FD->isImplicit() && FD->getDeclName() && 2271 FD->getAccess() == AS_private && 2272 !FD->hasAttr<UnusedAttr>() && 2273 !FD->getParent()->isDependentContext() && 2274 !InitializationHasSideEffects(*FD)) 2275 UnusedPrivateFields.insert(FD); 2276 } 2277 } 2278 2279 return Member; 2280 } 2281 2282 namespace { 2283 class UninitializedFieldVisitor 2284 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2285 Sema &S; 2286 // List of Decls to generate a warning on. Also remove Decls that become 2287 // initialized. 2288 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2289 // List of base classes of the record. Classes are removed after their 2290 // initializers. 2291 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 2292 // Vector of decls to be removed from the Decl set prior to visiting the 2293 // nodes. These Decls may have been initialized in the prior initializer. 2294 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2295 // If non-null, add a note to the warning pointing back to the constructor. 2296 const CXXConstructorDecl *Constructor; 2297 // Variables to hold state when processing an initializer list. When 2298 // InitList is true, special case initialization of FieldDecls matching 2299 // InitListFieldDecl. 2300 bool InitList; 2301 FieldDecl *InitListFieldDecl; 2302 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2303 2304 public: 2305 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2306 UninitializedFieldVisitor(Sema &S, 2307 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 2308 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 2309 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 2310 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 2311 2312 // Returns true if the use of ME is not an uninitialized use. 2313 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2314 bool CheckReferenceOnly) { 2315 llvm::SmallVector<FieldDecl*, 4> Fields; 2316 bool ReferenceField = false; 2317 while (ME) { 2318 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2319 if (!FD) 2320 return false; 2321 Fields.push_back(FD); 2322 if (FD->getType()->isReferenceType()) 2323 ReferenceField = true; 2324 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2325 } 2326 2327 // Binding a reference to an unintialized field is not an 2328 // uninitialized use. 2329 if (CheckReferenceOnly && !ReferenceField) 2330 return true; 2331 2332 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2333 // Discard the first field since it is the field decl that is being 2334 // initialized. 2335 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2336 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2337 } 2338 2339 for (auto UsedIter = UsedFieldIndex.begin(), 2340 UsedEnd = UsedFieldIndex.end(), 2341 OrigIter = InitFieldIndex.begin(), 2342 OrigEnd = InitFieldIndex.end(); 2343 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2344 if (*UsedIter < *OrigIter) 2345 return true; 2346 if (*UsedIter > *OrigIter) 2347 break; 2348 } 2349 2350 return false; 2351 } 2352 2353 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2354 bool AddressOf) { 2355 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2356 return; 2357 2358 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2359 // or union. 2360 MemberExpr *FieldME = ME; 2361 2362 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2363 2364 Expr *Base = ME; 2365 while (MemberExpr *SubME = 2366 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 2367 2368 if (isa<VarDecl>(SubME->getMemberDecl())) 2369 return; 2370 2371 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2372 if (!FD->isAnonymousStructOrUnion()) 2373 FieldME = SubME; 2374 2375 if (!FieldME->getType().isPODType(S.Context)) 2376 AllPODFields = false; 2377 2378 Base = SubME->getBase(); 2379 } 2380 2381 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 2382 return; 2383 2384 if (AddressOf && AllPODFields) 2385 return; 2386 2387 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2388 2389 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 2390 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 2391 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 2392 } 2393 2394 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 2395 QualType T = BaseCast->getType(); 2396 if (T->isPointerType() && 2397 BaseClasses.count(T->getPointeeType())) { 2398 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 2399 << T->getPointeeType() << FoundVD; 2400 } 2401 } 2402 } 2403 2404 if (!Decls.count(FoundVD)) 2405 return; 2406 2407 const bool IsReference = FoundVD->getType()->isReferenceType(); 2408 2409 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2410 // Special checking for initializer lists. 2411 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2412 return; 2413 } 2414 } else { 2415 // Prevent double warnings on use of unbounded references. 2416 if (CheckReferenceOnly && !IsReference) 2417 return; 2418 } 2419 2420 unsigned diag = IsReference 2421 ? diag::warn_reference_field_is_uninit 2422 : diag::warn_field_is_uninit; 2423 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2424 if (Constructor) 2425 S.Diag(Constructor->getLocation(), 2426 diag::note_uninit_in_this_constructor) 2427 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2428 2429 } 2430 2431 void HandleValue(Expr *E, bool AddressOf) { 2432 E = E->IgnoreParens(); 2433 2434 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2435 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2436 AddressOf /*AddressOf*/); 2437 return; 2438 } 2439 2440 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2441 Visit(CO->getCond()); 2442 HandleValue(CO->getTrueExpr(), AddressOf); 2443 HandleValue(CO->getFalseExpr(), AddressOf); 2444 return; 2445 } 2446 2447 if (BinaryConditionalOperator *BCO = 2448 dyn_cast<BinaryConditionalOperator>(E)) { 2449 Visit(BCO->getCond()); 2450 HandleValue(BCO->getFalseExpr(), AddressOf); 2451 return; 2452 } 2453 2454 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2455 HandleValue(OVE->getSourceExpr(), AddressOf); 2456 return; 2457 } 2458 2459 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2460 switch (BO->getOpcode()) { 2461 default: 2462 break; 2463 case(BO_PtrMemD): 2464 case(BO_PtrMemI): 2465 HandleValue(BO->getLHS(), AddressOf); 2466 Visit(BO->getRHS()); 2467 return; 2468 case(BO_Comma): 2469 Visit(BO->getLHS()); 2470 HandleValue(BO->getRHS(), AddressOf); 2471 return; 2472 } 2473 } 2474 2475 Visit(E); 2476 } 2477 2478 void CheckInitListExpr(InitListExpr *ILE) { 2479 InitFieldIndex.push_back(0); 2480 for (auto Child : ILE->children()) { 2481 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2482 CheckInitListExpr(SubList); 2483 } else { 2484 Visit(Child); 2485 } 2486 ++InitFieldIndex.back(); 2487 } 2488 InitFieldIndex.pop_back(); 2489 } 2490 2491 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2492 FieldDecl *Field, const Type *BaseClass) { 2493 // Remove Decls that may have been initialized in the previous 2494 // initializer. 2495 for (ValueDecl* VD : DeclsToRemove) 2496 Decls.erase(VD); 2497 DeclsToRemove.clear(); 2498 2499 Constructor = FieldConstructor; 2500 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2501 2502 if (ILE && Field) { 2503 InitList = true; 2504 InitListFieldDecl = Field; 2505 InitFieldIndex.clear(); 2506 CheckInitListExpr(ILE); 2507 } else { 2508 InitList = false; 2509 Visit(E); 2510 } 2511 2512 if (Field) 2513 Decls.erase(Field); 2514 if (BaseClass) 2515 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 2516 } 2517 2518 void VisitMemberExpr(MemberExpr *ME) { 2519 // All uses of unbounded reference fields will warn. 2520 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2521 } 2522 2523 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2524 if (E->getCastKind() == CK_LValueToRValue) { 2525 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2526 return; 2527 } 2528 2529 Inherited::VisitImplicitCastExpr(E); 2530 } 2531 2532 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2533 if (E->getConstructor()->isCopyConstructor()) { 2534 Expr *ArgExpr = E->getArg(0); 2535 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2536 if (ILE->getNumInits() == 1) 2537 ArgExpr = ILE->getInit(0); 2538 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2539 if (ICE->getCastKind() == CK_NoOp) 2540 ArgExpr = ICE->getSubExpr(); 2541 HandleValue(ArgExpr, false /*AddressOf*/); 2542 return; 2543 } 2544 Inherited::VisitCXXConstructExpr(E); 2545 } 2546 2547 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2548 Expr *Callee = E->getCallee(); 2549 if (isa<MemberExpr>(Callee)) { 2550 HandleValue(Callee, false /*AddressOf*/); 2551 for (auto Arg : E->arguments()) 2552 Visit(Arg); 2553 return; 2554 } 2555 2556 Inherited::VisitCXXMemberCallExpr(E); 2557 } 2558 2559 void VisitCallExpr(CallExpr *E) { 2560 // Treat std::move as a use. 2561 if (E->getNumArgs() == 1) { 2562 if (FunctionDecl *FD = E->getDirectCallee()) { 2563 if (FD->isInStdNamespace() && FD->getIdentifier() && 2564 FD->getIdentifier()->isStr("move")) { 2565 HandleValue(E->getArg(0), false /*AddressOf*/); 2566 return; 2567 } 2568 } 2569 } 2570 2571 Inherited::VisitCallExpr(E); 2572 } 2573 2574 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2575 Expr *Callee = E->getCallee(); 2576 2577 if (isa<UnresolvedLookupExpr>(Callee)) 2578 return Inherited::VisitCXXOperatorCallExpr(E); 2579 2580 Visit(Callee); 2581 for (auto Arg : E->arguments()) 2582 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2583 } 2584 2585 void VisitBinaryOperator(BinaryOperator *E) { 2586 // If a field assignment is detected, remove the field from the 2587 // uninitiailized field set. 2588 if (E->getOpcode() == BO_Assign) 2589 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2590 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2591 if (!FD->getType()->isReferenceType()) 2592 DeclsToRemove.push_back(FD); 2593 2594 if (E->isCompoundAssignmentOp()) { 2595 HandleValue(E->getLHS(), false /*AddressOf*/); 2596 Visit(E->getRHS()); 2597 return; 2598 } 2599 2600 Inherited::VisitBinaryOperator(E); 2601 } 2602 2603 void VisitUnaryOperator(UnaryOperator *E) { 2604 if (E->isIncrementDecrementOp()) { 2605 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2606 return; 2607 } 2608 if (E->getOpcode() == UO_AddrOf) { 2609 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2610 HandleValue(ME->getBase(), true /*AddressOf*/); 2611 return; 2612 } 2613 } 2614 2615 Inherited::VisitUnaryOperator(E); 2616 } 2617 }; 2618 2619 // Diagnose value-uses of fields to initialize themselves, e.g. 2620 // foo(foo) 2621 // where foo is not also a parameter to the constructor. 2622 // Also diagnose across field uninitialized use such as 2623 // x(y), y(x) 2624 // TODO: implement -Wuninitialized and fold this into that framework. 2625 static void DiagnoseUninitializedFields( 2626 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2627 2628 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2629 Constructor->getLocation())) { 2630 return; 2631 } 2632 2633 if (Constructor->isInvalidDecl()) 2634 return; 2635 2636 const CXXRecordDecl *RD = Constructor->getParent(); 2637 2638 if (RD->getDescribedClassTemplate()) 2639 return; 2640 2641 // Holds fields that are uninitialized. 2642 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2643 2644 // At the beginning, all fields are uninitialized. 2645 for (auto *I : RD->decls()) { 2646 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2647 UninitializedFields.insert(FD); 2648 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2649 UninitializedFields.insert(IFD->getAnonField()); 2650 } 2651 } 2652 2653 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 2654 for (auto I : RD->bases()) 2655 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 2656 2657 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2658 return; 2659 2660 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2661 UninitializedFields, 2662 UninitializedBaseClasses); 2663 2664 for (const auto *FieldInit : Constructor->inits()) { 2665 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2666 break; 2667 2668 Expr *InitExpr = FieldInit->getInit(); 2669 if (!InitExpr) 2670 continue; 2671 2672 if (CXXDefaultInitExpr *Default = 2673 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2674 InitExpr = Default->getExpr(); 2675 if (!InitExpr) 2676 continue; 2677 // In class initializers will point to the constructor. 2678 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2679 FieldInit->getAnyMember(), 2680 FieldInit->getBaseClass()); 2681 } else { 2682 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2683 FieldInit->getAnyMember(), 2684 FieldInit->getBaseClass()); 2685 } 2686 } 2687 } 2688 } // namespace 2689 2690 /// \brief Enter a new C++ default initializer scope. After calling this, the 2691 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2692 /// parsing or instantiating the initializer failed. 2693 void Sema::ActOnStartCXXInClassMemberInitializer() { 2694 // Create a synthetic function scope to represent the call to the constructor 2695 // that notionally surrounds a use of this initializer. 2696 PushFunctionScope(); 2697 } 2698 2699 /// \brief This is invoked after parsing an in-class initializer for a 2700 /// non-static C++ class member, and after instantiating an in-class initializer 2701 /// in a class template. Such actions are deferred until the class is complete. 2702 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2703 SourceLocation InitLoc, 2704 Expr *InitExpr) { 2705 // Pop the notional constructor scope we created earlier. 2706 PopFunctionScopeInfo(nullptr, D); 2707 2708 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2709 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 2710 "must set init style when field is created"); 2711 2712 if (!InitExpr) { 2713 D->setInvalidDecl(); 2714 if (FD) 2715 FD->removeInClassInitializer(); 2716 return; 2717 } 2718 2719 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2720 FD->setInvalidDecl(); 2721 FD->removeInClassInitializer(); 2722 return; 2723 } 2724 2725 ExprResult Init = InitExpr; 2726 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2727 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2728 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2729 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2730 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2731 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2732 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2733 if (Init.isInvalid()) { 2734 FD->setInvalidDecl(); 2735 return; 2736 } 2737 } 2738 2739 // C++11 [class.base.init]p7: 2740 // The initialization of each base and member constitutes a 2741 // full-expression. 2742 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2743 if (Init.isInvalid()) { 2744 FD->setInvalidDecl(); 2745 return; 2746 } 2747 2748 InitExpr = Init.get(); 2749 2750 FD->setInClassInitializer(InitExpr); 2751 } 2752 2753 /// \brief Find the direct and/or virtual base specifiers that 2754 /// correspond to the given base type, for use in base initialization 2755 /// within a constructor. 2756 static bool FindBaseInitializer(Sema &SemaRef, 2757 CXXRecordDecl *ClassDecl, 2758 QualType BaseType, 2759 const CXXBaseSpecifier *&DirectBaseSpec, 2760 const CXXBaseSpecifier *&VirtualBaseSpec) { 2761 // First, check for a direct base class. 2762 DirectBaseSpec = nullptr; 2763 for (const auto &Base : ClassDecl->bases()) { 2764 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2765 // We found a direct base of this type. That's what we're 2766 // initializing. 2767 DirectBaseSpec = &Base; 2768 break; 2769 } 2770 } 2771 2772 // Check for a virtual base class. 2773 // FIXME: We might be able to short-circuit this if we know in advance that 2774 // there are no virtual bases. 2775 VirtualBaseSpec = nullptr; 2776 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2777 // We haven't found a base yet; search the class hierarchy for a 2778 // virtual base class. 2779 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2780 /*DetectVirtual=*/false); 2781 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2782 BaseType, Paths)) { 2783 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2784 Path != Paths.end(); ++Path) { 2785 if (Path->back().Base->isVirtual()) { 2786 VirtualBaseSpec = Path->back().Base; 2787 break; 2788 } 2789 } 2790 } 2791 } 2792 2793 return DirectBaseSpec || VirtualBaseSpec; 2794 } 2795 2796 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2797 MemInitResult 2798 Sema::ActOnMemInitializer(Decl *ConstructorD, 2799 Scope *S, 2800 CXXScopeSpec &SS, 2801 IdentifierInfo *MemberOrBase, 2802 ParsedType TemplateTypeTy, 2803 const DeclSpec &DS, 2804 SourceLocation IdLoc, 2805 Expr *InitList, 2806 SourceLocation EllipsisLoc) { 2807 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2808 DS, IdLoc, InitList, 2809 EllipsisLoc); 2810 } 2811 2812 /// \brief Handle a C++ member initializer using parentheses syntax. 2813 MemInitResult 2814 Sema::ActOnMemInitializer(Decl *ConstructorD, 2815 Scope *S, 2816 CXXScopeSpec &SS, 2817 IdentifierInfo *MemberOrBase, 2818 ParsedType TemplateTypeTy, 2819 const DeclSpec &DS, 2820 SourceLocation IdLoc, 2821 SourceLocation LParenLoc, 2822 ArrayRef<Expr *> Args, 2823 SourceLocation RParenLoc, 2824 SourceLocation EllipsisLoc) { 2825 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2826 Args, RParenLoc); 2827 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2828 DS, IdLoc, List, EllipsisLoc); 2829 } 2830 2831 namespace { 2832 2833 // Callback to only accept typo corrections that can be a valid C++ member 2834 // intializer: either a non-static field member or a base class. 2835 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2836 public: 2837 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2838 : ClassDecl(ClassDecl) {} 2839 2840 bool ValidateCandidate(const TypoCorrection &candidate) override { 2841 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2842 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2843 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2844 return isa<TypeDecl>(ND); 2845 } 2846 return false; 2847 } 2848 2849 private: 2850 CXXRecordDecl *ClassDecl; 2851 }; 2852 2853 } 2854 2855 /// \brief Handle a C++ member initializer. 2856 MemInitResult 2857 Sema::BuildMemInitializer(Decl *ConstructorD, 2858 Scope *S, 2859 CXXScopeSpec &SS, 2860 IdentifierInfo *MemberOrBase, 2861 ParsedType TemplateTypeTy, 2862 const DeclSpec &DS, 2863 SourceLocation IdLoc, 2864 Expr *Init, 2865 SourceLocation EllipsisLoc) { 2866 ExprResult Res = CorrectDelayedTyposInExpr(Init); 2867 if (!Res.isUsable()) 2868 return true; 2869 Init = Res.get(); 2870 2871 if (!ConstructorD) 2872 return true; 2873 2874 AdjustDeclIfTemplate(ConstructorD); 2875 2876 CXXConstructorDecl *Constructor 2877 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2878 if (!Constructor) { 2879 // The user wrote a constructor initializer on a function that is 2880 // not a C++ constructor. Ignore the error for now, because we may 2881 // have more member initializers coming; we'll diagnose it just 2882 // once in ActOnMemInitializers. 2883 return true; 2884 } 2885 2886 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2887 2888 // C++ [class.base.init]p2: 2889 // Names in a mem-initializer-id are looked up in the scope of the 2890 // constructor's class and, if not found in that scope, are looked 2891 // up in the scope containing the constructor's definition. 2892 // [Note: if the constructor's class contains a member with the 2893 // same name as a direct or virtual base class of the class, a 2894 // mem-initializer-id naming the member or base class and composed 2895 // of a single identifier refers to the class member. A 2896 // mem-initializer-id for the hidden base class may be specified 2897 // using a qualified name. ] 2898 if (!SS.getScopeRep() && !TemplateTypeTy) { 2899 // Look for a member, first. 2900 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2901 if (!Result.empty()) { 2902 ValueDecl *Member; 2903 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2904 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2905 if (EllipsisLoc.isValid()) 2906 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2907 << MemberOrBase 2908 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2909 2910 return BuildMemberInitializer(Member, Init, IdLoc); 2911 } 2912 } 2913 } 2914 // It didn't name a member, so see if it names a class. 2915 QualType BaseType; 2916 TypeSourceInfo *TInfo = nullptr; 2917 2918 if (TemplateTypeTy) { 2919 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2920 } else if (DS.getTypeSpecType() == TST_decltype) { 2921 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2922 } else { 2923 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2924 LookupParsedName(R, S, &SS); 2925 2926 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2927 if (!TyD) { 2928 if (R.isAmbiguous()) return true; 2929 2930 // We don't want access-control diagnostics here. 2931 R.suppressDiagnostics(); 2932 2933 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2934 bool NotUnknownSpecialization = false; 2935 DeclContext *DC = computeDeclContext(SS, false); 2936 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2937 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2938 2939 if (!NotUnknownSpecialization) { 2940 // When the scope specifier can refer to a member of an unknown 2941 // specialization, we take it as a type name. 2942 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2943 SS.getWithLocInContext(Context), 2944 *MemberOrBase, IdLoc); 2945 if (BaseType.isNull()) 2946 return true; 2947 2948 R.clear(); 2949 R.setLookupName(MemberOrBase); 2950 } 2951 } 2952 2953 // If no results were found, try to correct typos. 2954 TypoCorrection Corr; 2955 if (R.empty() && BaseType.isNull() && 2956 (Corr = CorrectTypo( 2957 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2958 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2959 CTK_ErrorRecovery, ClassDecl))) { 2960 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2961 // We have found a non-static data member with a similar 2962 // name to what was typed; complain and initialize that 2963 // member. 2964 diagnoseTypo(Corr, 2965 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2966 << MemberOrBase << true); 2967 return BuildMemberInitializer(Member, Init, IdLoc); 2968 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2969 const CXXBaseSpecifier *DirectBaseSpec; 2970 const CXXBaseSpecifier *VirtualBaseSpec; 2971 if (FindBaseInitializer(*this, ClassDecl, 2972 Context.getTypeDeclType(Type), 2973 DirectBaseSpec, VirtualBaseSpec)) { 2974 // We have found a direct or virtual base class with a 2975 // similar name to what was typed; complain and initialize 2976 // that base class. 2977 diagnoseTypo(Corr, 2978 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2979 << MemberOrBase << false, 2980 PDiag() /*Suppress note, we provide our own.*/); 2981 2982 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2983 : VirtualBaseSpec; 2984 Diag(BaseSpec->getLocStart(), 2985 diag::note_base_class_specified_here) 2986 << BaseSpec->getType() 2987 << BaseSpec->getSourceRange(); 2988 2989 TyD = Type; 2990 } 2991 } 2992 } 2993 2994 if (!TyD && BaseType.isNull()) { 2995 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2996 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2997 return true; 2998 } 2999 } 3000 3001 if (BaseType.isNull()) { 3002 BaseType = Context.getTypeDeclType(TyD); 3003 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3004 if (SS.isSet()) 3005 // FIXME: preserve source range information 3006 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3007 BaseType); 3008 } 3009 } 3010 3011 if (!TInfo) 3012 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3013 3014 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3015 } 3016 3017 /// Checks a member initializer expression for cases where reference (or 3018 /// pointer) members are bound to by-value parameters (or their addresses). 3019 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3020 Expr *Init, 3021 SourceLocation IdLoc) { 3022 QualType MemberTy = Member->getType(); 3023 3024 // We only handle pointers and references currently. 3025 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3026 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3027 return; 3028 3029 const bool IsPointer = MemberTy->isPointerType(); 3030 if (IsPointer) { 3031 if (const UnaryOperator *Op 3032 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3033 // The only case we're worried about with pointers requires taking the 3034 // address. 3035 if (Op->getOpcode() != UO_AddrOf) 3036 return; 3037 3038 Init = Op->getSubExpr(); 3039 } else { 3040 // We only handle address-of expression initializers for pointers. 3041 return; 3042 } 3043 } 3044 3045 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3046 // We only warn when referring to a non-reference parameter declaration. 3047 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3048 if (!Parameter || Parameter->getType()->isReferenceType()) 3049 return; 3050 3051 S.Diag(Init->getExprLoc(), 3052 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3053 : diag::warn_bind_ref_member_to_parameter) 3054 << Member << Parameter << Init->getSourceRange(); 3055 } else { 3056 // Other initializers are fine. 3057 return; 3058 } 3059 3060 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3061 << (unsigned)IsPointer; 3062 } 3063 3064 MemInitResult 3065 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3066 SourceLocation IdLoc) { 3067 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3068 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3069 assert((DirectMember || IndirectMember) && 3070 "Member must be a FieldDecl or IndirectFieldDecl"); 3071 3072 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3073 return true; 3074 3075 if (Member->isInvalidDecl()) 3076 return true; 3077 3078 MultiExprArg Args; 3079 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3080 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3081 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3082 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3083 } else { 3084 // Template instantiation doesn't reconstruct ParenListExprs for us. 3085 Args = Init; 3086 } 3087 3088 SourceRange InitRange = Init->getSourceRange(); 3089 3090 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3091 // Can't check initialization for a member of dependent type or when 3092 // any of the arguments are type-dependent expressions. 3093 DiscardCleanupsInEvaluationContext(); 3094 } else { 3095 bool InitList = false; 3096 if (isa<InitListExpr>(Init)) { 3097 InitList = true; 3098 Args = Init; 3099 } 3100 3101 // Initialize the member. 3102 InitializedEntity MemberEntity = 3103 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3104 : InitializedEntity::InitializeMember(IndirectMember, 3105 nullptr); 3106 InitializationKind Kind = 3107 InitList ? InitializationKind::CreateDirectList(IdLoc) 3108 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3109 InitRange.getEnd()); 3110 3111 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3112 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3113 nullptr); 3114 if (MemberInit.isInvalid()) 3115 return true; 3116 3117 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3118 3119 // C++11 [class.base.init]p7: 3120 // The initialization of each base and member constitutes a 3121 // full-expression. 3122 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3123 if (MemberInit.isInvalid()) 3124 return true; 3125 3126 Init = MemberInit.get(); 3127 } 3128 3129 if (DirectMember) { 3130 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3131 InitRange.getBegin(), Init, 3132 InitRange.getEnd()); 3133 } else { 3134 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3135 InitRange.getBegin(), Init, 3136 InitRange.getEnd()); 3137 } 3138 } 3139 3140 MemInitResult 3141 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3142 CXXRecordDecl *ClassDecl) { 3143 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3144 if (!LangOpts.CPlusPlus11) 3145 return Diag(NameLoc, diag::err_delegating_ctor) 3146 << TInfo->getTypeLoc().getLocalSourceRange(); 3147 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3148 3149 bool InitList = true; 3150 MultiExprArg Args = Init; 3151 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3152 InitList = false; 3153 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3154 } 3155 3156 SourceRange InitRange = Init->getSourceRange(); 3157 // Initialize the object. 3158 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3159 QualType(ClassDecl->getTypeForDecl(), 0)); 3160 InitializationKind Kind = 3161 InitList ? InitializationKind::CreateDirectList(NameLoc) 3162 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3163 InitRange.getEnd()); 3164 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3165 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3166 Args, nullptr); 3167 if (DelegationInit.isInvalid()) 3168 return true; 3169 3170 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3171 "Delegating constructor with no target?"); 3172 3173 // C++11 [class.base.init]p7: 3174 // The initialization of each base and member constitutes a 3175 // full-expression. 3176 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3177 InitRange.getBegin()); 3178 if (DelegationInit.isInvalid()) 3179 return true; 3180 3181 // If we are in a dependent context, template instantiation will 3182 // perform this type-checking again. Just save the arguments that we 3183 // received in a ParenListExpr. 3184 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3185 // of the information that we have about the base 3186 // initializer. However, deconstructing the ASTs is a dicey process, 3187 // and this approach is far more likely to get the corner cases right. 3188 if (CurContext->isDependentContext()) 3189 DelegationInit = Init; 3190 3191 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3192 DelegationInit.getAs<Expr>(), 3193 InitRange.getEnd()); 3194 } 3195 3196 MemInitResult 3197 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3198 Expr *Init, CXXRecordDecl *ClassDecl, 3199 SourceLocation EllipsisLoc) { 3200 SourceLocation BaseLoc 3201 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3202 3203 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3204 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3205 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3206 3207 // C++ [class.base.init]p2: 3208 // [...] Unless the mem-initializer-id names a nonstatic data 3209 // member of the constructor's class or a direct or virtual base 3210 // of that class, the mem-initializer is ill-formed. A 3211 // mem-initializer-list can initialize a base class using any 3212 // name that denotes that base class type. 3213 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3214 3215 SourceRange InitRange = Init->getSourceRange(); 3216 if (EllipsisLoc.isValid()) { 3217 // This is a pack expansion. 3218 if (!BaseType->containsUnexpandedParameterPack()) { 3219 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3220 << SourceRange(BaseLoc, InitRange.getEnd()); 3221 3222 EllipsisLoc = SourceLocation(); 3223 } 3224 } else { 3225 // Check for any unexpanded parameter packs. 3226 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3227 return true; 3228 3229 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3230 return true; 3231 } 3232 3233 // Check for direct and virtual base classes. 3234 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3235 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3236 if (!Dependent) { 3237 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3238 BaseType)) 3239 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3240 3241 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3242 VirtualBaseSpec); 3243 3244 // C++ [base.class.init]p2: 3245 // Unless the mem-initializer-id names a nonstatic data member of the 3246 // constructor's class or a direct or virtual base of that class, the 3247 // mem-initializer is ill-formed. 3248 if (!DirectBaseSpec && !VirtualBaseSpec) { 3249 // If the class has any dependent bases, then it's possible that 3250 // one of those types will resolve to the same type as 3251 // BaseType. Therefore, just treat this as a dependent base 3252 // class initialization. FIXME: Should we try to check the 3253 // initialization anyway? It seems odd. 3254 if (ClassDecl->hasAnyDependentBases()) 3255 Dependent = true; 3256 else 3257 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3258 << BaseType << Context.getTypeDeclType(ClassDecl) 3259 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3260 } 3261 } 3262 3263 if (Dependent) { 3264 DiscardCleanupsInEvaluationContext(); 3265 3266 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3267 /*IsVirtual=*/false, 3268 InitRange.getBegin(), Init, 3269 InitRange.getEnd(), EllipsisLoc); 3270 } 3271 3272 // C++ [base.class.init]p2: 3273 // If a mem-initializer-id is ambiguous because it designates both 3274 // a direct non-virtual base class and an inherited virtual base 3275 // class, the mem-initializer is ill-formed. 3276 if (DirectBaseSpec && VirtualBaseSpec) 3277 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3278 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3279 3280 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3281 if (!BaseSpec) 3282 BaseSpec = VirtualBaseSpec; 3283 3284 // Initialize the base. 3285 bool InitList = true; 3286 MultiExprArg Args = Init; 3287 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3288 InitList = false; 3289 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3290 } 3291 3292 InitializedEntity BaseEntity = 3293 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3294 InitializationKind Kind = 3295 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3296 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3297 InitRange.getEnd()); 3298 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3299 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3300 if (BaseInit.isInvalid()) 3301 return true; 3302 3303 // C++11 [class.base.init]p7: 3304 // The initialization of each base and member constitutes a 3305 // full-expression. 3306 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3307 if (BaseInit.isInvalid()) 3308 return true; 3309 3310 // If we are in a dependent context, template instantiation will 3311 // perform this type-checking again. Just save the arguments that we 3312 // received in a ParenListExpr. 3313 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3314 // of the information that we have about the base 3315 // initializer. However, deconstructing the ASTs is a dicey process, 3316 // and this approach is far more likely to get the corner cases right. 3317 if (CurContext->isDependentContext()) 3318 BaseInit = Init; 3319 3320 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3321 BaseSpec->isVirtual(), 3322 InitRange.getBegin(), 3323 BaseInit.getAs<Expr>(), 3324 InitRange.getEnd(), EllipsisLoc); 3325 } 3326 3327 // Create a static_cast\<T&&>(expr). 3328 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3329 if (T.isNull()) T = E->getType(); 3330 QualType TargetType = SemaRef.BuildReferenceType( 3331 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3332 SourceLocation ExprLoc = E->getLocStart(); 3333 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3334 TargetType, ExprLoc); 3335 3336 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3337 SourceRange(ExprLoc, ExprLoc), 3338 E->getSourceRange()).get(); 3339 } 3340 3341 /// ImplicitInitializerKind - How an implicit base or member initializer should 3342 /// initialize its base or member. 3343 enum ImplicitInitializerKind { 3344 IIK_Default, 3345 IIK_Copy, 3346 IIK_Move, 3347 IIK_Inherit 3348 }; 3349 3350 static bool 3351 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3352 ImplicitInitializerKind ImplicitInitKind, 3353 CXXBaseSpecifier *BaseSpec, 3354 bool IsInheritedVirtualBase, 3355 CXXCtorInitializer *&CXXBaseInit) { 3356 InitializedEntity InitEntity 3357 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3358 IsInheritedVirtualBase); 3359 3360 ExprResult BaseInit; 3361 3362 switch (ImplicitInitKind) { 3363 case IIK_Inherit: { 3364 const CXXRecordDecl *Inherited = 3365 Constructor->getInheritedConstructor()->getParent(); 3366 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3367 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3368 // C++11 [class.inhctor]p8: 3369 // Each expression in the expression-list is of the form 3370 // static_cast<T&&>(p), where p is the name of the corresponding 3371 // constructor parameter and T is the declared type of p. 3372 SmallVector<Expr*, 16> Args; 3373 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3374 ParmVarDecl *PD = Constructor->getParamDecl(I); 3375 ExprResult ArgExpr = 3376 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3377 VK_LValue, SourceLocation()); 3378 if (ArgExpr.isInvalid()) 3379 return true; 3380 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3381 } 3382 3383 InitializationKind InitKind = InitializationKind::CreateDirect( 3384 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3385 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3386 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3387 break; 3388 } 3389 } 3390 // Fall through. 3391 case IIK_Default: { 3392 InitializationKind InitKind 3393 = InitializationKind::CreateDefault(Constructor->getLocation()); 3394 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3395 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3396 break; 3397 } 3398 3399 case IIK_Move: 3400 case IIK_Copy: { 3401 bool Moving = ImplicitInitKind == IIK_Move; 3402 ParmVarDecl *Param = Constructor->getParamDecl(0); 3403 QualType ParamType = Param->getType().getNonReferenceType(); 3404 3405 Expr *CopyCtorArg = 3406 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3407 SourceLocation(), Param, false, 3408 Constructor->getLocation(), ParamType, 3409 VK_LValue, nullptr); 3410 3411 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3412 3413 // Cast to the base class to avoid ambiguities. 3414 QualType ArgTy = 3415 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3416 ParamType.getQualifiers()); 3417 3418 if (Moving) { 3419 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3420 } 3421 3422 CXXCastPath BasePath; 3423 BasePath.push_back(BaseSpec); 3424 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3425 CK_UncheckedDerivedToBase, 3426 Moving ? VK_XValue : VK_LValue, 3427 &BasePath).get(); 3428 3429 InitializationKind InitKind 3430 = InitializationKind::CreateDirect(Constructor->getLocation(), 3431 SourceLocation(), SourceLocation()); 3432 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3433 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3434 break; 3435 } 3436 } 3437 3438 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3439 if (BaseInit.isInvalid()) 3440 return true; 3441 3442 CXXBaseInit = 3443 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3444 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3445 SourceLocation()), 3446 BaseSpec->isVirtual(), 3447 SourceLocation(), 3448 BaseInit.getAs<Expr>(), 3449 SourceLocation(), 3450 SourceLocation()); 3451 3452 return false; 3453 } 3454 3455 static bool RefersToRValueRef(Expr *MemRef) { 3456 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3457 return Referenced->getType()->isRValueReferenceType(); 3458 } 3459 3460 static bool 3461 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3462 ImplicitInitializerKind ImplicitInitKind, 3463 FieldDecl *Field, IndirectFieldDecl *Indirect, 3464 CXXCtorInitializer *&CXXMemberInit) { 3465 if (Field->isInvalidDecl()) 3466 return true; 3467 3468 SourceLocation Loc = Constructor->getLocation(); 3469 3470 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3471 bool Moving = ImplicitInitKind == IIK_Move; 3472 ParmVarDecl *Param = Constructor->getParamDecl(0); 3473 QualType ParamType = Param->getType().getNonReferenceType(); 3474 3475 // Suppress copying zero-width bitfields. 3476 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3477 return false; 3478 3479 Expr *MemberExprBase = 3480 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3481 SourceLocation(), Param, false, 3482 Loc, ParamType, VK_LValue, nullptr); 3483 3484 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3485 3486 if (Moving) { 3487 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3488 } 3489 3490 // Build a reference to this field within the parameter. 3491 CXXScopeSpec SS; 3492 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3493 Sema::LookupMemberName); 3494 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3495 : cast<ValueDecl>(Field), AS_public); 3496 MemberLookup.resolveKind(); 3497 ExprResult CtorArg 3498 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3499 ParamType, Loc, 3500 /*IsArrow=*/false, 3501 SS, 3502 /*TemplateKWLoc=*/SourceLocation(), 3503 /*FirstQualifierInScope=*/nullptr, 3504 MemberLookup, 3505 /*TemplateArgs=*/nullptr); 3506 if (CtorArg.isInvalid()) 3507 return true; 3508 3509 // C++11 [class.copy]p15: 3510 // - if a member m has rvalue reference type T&&, it is direct-initialized 3511 // with static_cast<T&&>(x.m); 3512 if (RefersToRValueRef(CtorArg.get())) { 3513 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3514 } 3515 3516 // When the field we are copying is an array, create index variables for 3517 // each dimension of the array. We use these index variables to subscript 3518 // the source array, and other clients (e.g., CodeGen) will perform the 3519 // necessary iteration with these index variables. 3520 SmallVector<VarDecl *, 4> IndexVariables; 3521 QualType BaseType = Field->getType(); 3522 QualType SizeType = SemaRef.Context.getSizeType(); 3523 bool InitializingArray = false; 3524 while (const ConstantArrayType *Array 3525 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3526 InitializingArray = true; 3527 // Create the iteration variable for this array index. 3528 IdentifierInfo *IterationVarName = nullptr; 3529 { 3530 SmallString<8> Str; 3531 llvm::raw_svector_ostream OS(Str); 3532 OS << "__i" << IndexVariables.size(); 3533 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3534 } 3535 VarDecl *IterationVar 3536 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3537 IterationVarName, SizeType, 3538 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3539 SC_None); 3540 IndexVariables.push_back(IterationVar); 3541 3542 // Create a reference to the iteration variable. 3543 ExprResult IterationVarRef 3544 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3545 assert(!IterationVarRef.isInvalid() && 3546 "Reference to invented variable cannot fail!"); 3547 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3548 assert(!IterationVarRef.isInvalid() && 3549 "Conversion of invented variable cannot fail!"); 3550 3551 // Subscript the array with this iteration variable. 3552 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3553 IterationVarRef.get(), 3554 Loc); 3555 if (CtorArg.isInvalid()) 3556 return true; 3557 3558 BaseType = Array->getElementType(); 3559 } 3560 3561 // The array subscript expression is an lvalue, which is wrong for moving. 3562 if (Moving && InitializingArray) 3563 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3564 3565 // Construct the entity that we will be initializing. For an array, this 3566 // will be first element in the array, which may require several levels 3567 // of array-subscript entities. 3568 SmallVector<InitializedEntity, 4> Entities; 3569 Entities.reserve(1 + IndexVariables.size()); 3570 if (Indirect) 3571 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3572 else 3573 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3574 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3575 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3576 0, 3577 Entities.back())); 3578 3579 // Direct-initialize to use the copy constructor. 3580 InitializationKind InitKind = 3581 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3582 3583 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3584 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3585 3586 ExprResult MemberInit 3587 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3588 MultiExprArg(&CtorArgE, 1)); 3589 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3590 if (MemberInit.isInvalid()) 3591 return true; 3592 3593 if (Indirect) { 3594 assert(IndexVariables.size() == 0 && 3595 "Indirect field improperly initialized"); 3596 CXXMemberInit 3597 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3598 Loc, Loc, 3599 MemberInit.getAs<Expr>(), 3600 Loc); 3601 } else 3602 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3603 Loc, MemberInit.getAs<Expr>(), 3604 Loc, 3605 IndexVariables.data(), 3606 IndexVariables.size()); 3607 return false; 3608 } 3609 3610 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3611 "Unhandled implicit init kind!"); 3612 3613 QualType FieldBaseElementType = 3614 SemaRef.Context.getBaseElementType(Field->getType()); 3615 3616 if (FieldBaseElementType->isRecordType()) { 3617 InitializedEntity InitEntity 3618 = Indirect? InitializedEntity::InitializeMember(Indirect) 3619 : InitializedEntity::InitializeMember(Field); 3620 InitializationKind InitKind = 3621 InitializationKind::CreateDefault(Loc); 3622 3623 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3624 ExprResult MemberInit = 3625 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3626 3627 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3628 if (MemberInit.isInvalid()) 3629 return true; 3630 3631 if (Indirect) 3632 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3633 Indirect, Loc, 3634 Loc, 3635 MemberInit.get(), 3636 Loc); 3637 else 3638 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3639 Field, Loc, Loc, 3640 MemberInit.get(), 3641 Loc); 3642 return false; 3643 } 3644 3645 if (!Field->getParent()->isUnion()) { 3646 if (FieldBaseElementType->isReferenceType()) { 3647 SemaRef.Diag(Constructor->getLocation(), 3648 diag::err_uninitialized_member_in_ctor) 3649 << (int)Constructor->isImplicit() 3650 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3651 << 0 << Field->getDeclName(); 3652 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3653 return true; 3654 } 3655 3656 if (FieldBaseElementType.isConstQualified()) { 3657 SemaRef.Diag(Constructor->getLocation(), 3658 diag::err_uninitialized_member_in_ctor) 3659 << (int)Constructor->isImplicit() 3660 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3661 << 1 << Field->getDeclName(); 3662 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3663 return true; 3664 } 3665 } 3666 3667 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3668 FieldBaseElementType->isObjCRetainableType() && 3669 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3670 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3671 // ARC: 3672 // Default-initialize Objective-C pointers to NULL. 3673 CXXMemberInit 3674 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3675 Loc, Loc, 3676 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3677 Loc); 3678 return false; 3679 } 3680 3681 // Nothing to initialize. 3682 CXXMemberInit = nullptr; 3683 return false; 3684 } 3685 3686 namespace { 3687 struct BaseAndFieldInfo { 3688 Sema &S; 3689 CXXConstructorDecl *Ctor; 3690 bool AnyErrorsInInits; 3691 ImplicitInitializerKind IIK; 3692 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3693 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3694 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3695 3696 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3697 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3698 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3699 if (Generated && Ctor->isCopyConstructor()) 3700 IIK = IIK_Copy; 3701 else if (Generated && Ctor->isMoveConstructor()) 3702 IIK = IIK_Move; 3703 else if (Ctor->getInheritedConstructor()) 3704 IIK = IIK_Inherit; 3705 else 3706 IIK = IIK_Default; 3707 } 3708 3709 bool isImplicitCopyOrMove() const { 3710 switch (IIK) { 3711 case IIK_Copy: 3712 case IIK_Move: 3713 return true; 3714 3715 case IIK_Default: 3716 case IIK_Inherit: 3717 return false; 3718 } 3719 3720 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3721 } 3722 3723 bool addFieldInitializer(CXXCtorInitializer *Init) { 3724 AllToInit.push_back(Init); 3725 3726 // Check whether this initializer makes the field "used". 3727 if (Init->getInit()->HasSideEffects(S.Context)) 3728 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3729 3730 return false; 3731 } 3732 3733 bool isInactiveUnionMember(FieldDecl *Field) { 3734 RecordDecl *Record = Field->getParent(); 3735 if (!Record->isUnion()) 3736 return false; 3737 3738 if (FieldDecl *Active = 3739 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3740 return Active != Field->getCanonicalDecl(); 3741 3742 // In an implicit copy or move constructor, ignore any in-class initializer. 3743 if (isImplicitCopyOrMove()) 3744 return true; 3745 3746 // If there's no explicit initialization, the field is active only if it 3747 // has an in-class initializer... 3748 if (Field->hasInClassInitializer()) 3749 return false; 3750 // ... or it's an anonymous struct or union whose class has an in-class 3751 // initializer. 3752 if (!Field->isAnonymousStructOrUnion()) 3753 return true; 3754 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3755 return !FieldRD->hasInClassInitializer(); 3756 } 3757 3758 /// \brief Determine whether the given field is, or is within, a union member 3759 /// that is inactive (because there was an initializer given for a different 3760 /// member of the union, or because the union was not initialized at all). 3761 bool isWithinInactiveUnionMember(FieldDecl *Field, 3762 IndirectFieldDecl *Indirect) { 3763 if (!Indirect) 3764 return isInactiveUnionMember(Field); 3765 3766 for (auto *C : Indirect->chain()) { 3767 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3768 if (Field && isInactiveUnionMember(Field)) 3769 return true; 3770 } 3771 return false; 3772 } 3773 }; 3774 } 3775 3776 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3777 /// array type. 3778 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3779 if (T->isIncompleteArrayType()) 3780 return true; 3781 3782 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3783 if (!ArrayT->getSize()) 3784 return true; 3785 3786 T = ArrayT->getElementType(); 3787 } 3788 3789 return false; 3790 } 3791 3792 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3793 FieldDecl *Field, 3794 IndirectFieldDecl *Indirect = nullptr) { 3795 if (Field->isInvalidDecl()) 3796 return false; 3797 3798 // Overwhelmingly common case: we have a direct initializer for this field. 3799 if (CXXCtorInitializer *Init = 3800 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3801 return Info.addFieldInitializer(Init); 3802 3803 // C++11 [class.base.init]p8: 3804 // if the entity is a non-static data member that has a 3805 // brace-or-equal-initializer and either 3806 // -- the constructor's class is a union and no other variant member of that 3807 // union is designated by a mem-initializer-id or 3808 // -- the constructor's class is not a union, and, if the entity is a member 3809 // of an anonymous union, no other member of that union is designated by 3810 // a mem-initializer-id, 3811 // the entity is initialized as specified in [dcl.init]. 3812 // 3813 // We also apply the same rules to handle anonymous structs within anonymous 3814 // unions. 3815 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3816 return false; 3817 3818 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3819 ExprResult DIE = 3820 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3821 if (DIE.isInvalid()) 3822 return true; 3823 CXXCtorInitializer *Init; 3824 if (Indirect) 3825 Init = new (SemaRef.Context) 3826 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3827 SourceLocation(), DIE.get(), SourceLocation()); 3828 else 3829 Init = new (SemaRef.Context) 3830 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3831 SourceLocation(), DIE.get(), SourceLocation()); 3832 return Info.addFieldInitializer(Init); 3833 } 3834 3835 // Don't initialize incomplete or zero-length arrays. 3836 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3837 return false; 3838 3839 // Don't try to build an implicit initializer if there were semantic 3840 // errors in any of the initializers (and therefore we might be 3841 // missing some that the user actually wrote). 3842 if (Info.AnyErrorsInInits) 3843 return false; 3844 3845 CXXCtorInitializer *Init = nullptr; 3846 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3847 Indirect, Init)) 3848 return true; 3849 3850 if (!Init) 3851 return false; 3852 3853 return Info.addFieldInitializer(Init); 3854 } 3855 3856 bool 3857 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3858 CXXCtorInitializer *Initializer) { 3859 assert(Initializer->isDelegatingInitializer()); 3860 Constructor->setNumCtorInitializers(1); 3861 CXXCtorInitializer **initializer = 3862 new (Context) CXXCtorInitializer*[1]; 3863 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3864 Constructor->setCtorInitializers(initializer); 3865 3866 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3867 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3868 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3869 } 3870 3871 DelegatingCtorDecls.push_back(Constructor); 3872 3873 DiagnoseUninitializedFields(*this, Constructor); 3874 3875 return false; 3876 } 3877 3878 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3879 ArrayRef<CXXCtorInitializer *> Initializers) { 3880 if (Constructor->isDependentContext()) { 3881 // Just store the initializers as written, they will be checked during 3882 // instantiation. 3883 if (!Initializers.empty()) { 3884 Constructor->setNumCtorInitializers(Initializers.size()); 3885 CXXCtorInitializer **baseOrMemberInitializers = 3886 new (Context) CXXCtorInitializer*[Initializers.size()]; 3887 memcpy(baseOrMemberInitializers, Initializers.data(), 3888 Initializers.size() * sizeof(CXXCtorInitializer*)); 3889 Constructor->setCtorInitializers(baseOrMemberInitializers); 3890 } 3891 3892 // Let template instantiation know whether we had errors. 3893 if (AnyErrors) 3894 Constructor->setInvalidDecl(); 3895 3896 return false; 3897 } 3898 3899 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3900 3901 // We need to build the initializer AST according to order of construction 3902 // and not what user specified in the Initializers list. 3903 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3904 if (!ClassDecl) 3905 return true; 3906 3907 bool HadError = false; 3908 3909 for (unsigned i = 0; i < Initializers.size(); i++) { 3910 CXXCtorInitializer *Member = Initializers[i]; 3911 3912 if (Member->isBaseInitializer()) 3913 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3914 else { 3915 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3916 3917 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3918 for (auto *C : F->chain()) { 3919 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3920 if (FD && FD->getParent()->isUnion()) 3921 Info.ActiveUnionMember.insert(std::make_pair( 3922 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3923 } 3924 } else if (FieldDecl *FD = Member->getMember()) { 3925 if (FD->getParent()->isUnion()) 3926 Info.ActiveUnionMember.insert(std::make_pair( 3927 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3928 } 3929 } 3930 } 3931 3932 // Keep track of the direct virtual bases. 3933 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3934 for (auto &I : ClassDecl->bases()) { 3935 if (I.isVirtual()) 3936 DirectVBases.insert(&I); 3937 } 3938 3939 // Push virtual bases before others. 3940 for (auto &VBase : ClassDecl->vbases()) { 3941 if (CXXCtorInitializer *Value 3942 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3943 // [class.base.init]p7, per DR257: 3944 // A mem-initializer where the mem-initializer-id names a virtual base 3945 // class is ignored during execution of a constructor of any class that 3946 // is not the most derived class. 3947 if (ClassDecl->isAbstract()) { 3948 // FIXME: Provide a fixit to remove the base specifier. This requires 3949 // tracking the location of the associated comma for a base specifier. 3950 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3951 << VBase.getType() << ClassDecl; 3952 DiagnoseAbstractType(ClassDecl); 3953 } 3954 3955 Info.AllToInit.push_back(Value); 3956 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3957 // [class.base.init]p8, per DR257: 3958 // If a given [...] base class is not named by a mem-initializer-id 3959 // [...] and the entity is not a virtual base class of an abstract 3960 // class, then [...] the entity is default-initialized. 3961 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3962 CXXCtorInitializer *CXXBaseInit; 3963 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3964 &VBase, IsInheritedVirtualBase, 3965 CXXBaseInit)) { 3966 HadError = true; 3967 continue; 3968 } 3969 3970 Info.AllToInit.push_back(CXXBaseInit); 3971 } 3972 } 3973 3974 // Non-virtual bases. 3975 for (auto &Base : ClassDecl->bases()) { 3976 // Virtuals are in the virtual base list and already constructed. 3977 if (Base.isVirtual()) 3978 continue; 3979 3980 if (CXXCtorInitializer *Value 3981 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3982 Info.AllToInit.push_back(Value); 3983 } else if (!AnyErrors) { 3984 CXXCtorInitializer *CXXBaseInit; 3985 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3986 &Base, /*IsInheritedVirtualBase=*/false, 3987 CXXBaseInit)) { 3988 HadError = true; 3989 continue; 3990 } 3991 3992 Info.AllToInit.push_back(CXXBaseInit); 3993 } 3994 } 3995 3996 // Fields. 3997 for (auto *Mem : ClassDecl->decls()) { 3998 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3999 // C++ [class.bit]p2: 4000 // A declaration for a bit-field that omits the identifier declares an 4001 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4002 // initialized. 4003 if (F->isUnnamedBitfield()) 4004 continue; 4005 4006 // If we're not generating the implicit copy/move constructor, then we'll 4007 // handle anonymous struct/union fields based on their individual 4008 // indirect fields. 4009 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4010 continue; 4011 4012 if (CollectFieldInitializer(*this, Info, F)) 4013 HadError = true; 4014 continue; 4015 } 4016 4017 // Beyond this point, we only consider default initialization. 4018 if (Info.isImplicitCopyOrMove()) 4019 continue; 4020 4021 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4022 if (F->getType()->isIncompleteArrayType()) { 4023 assert(ClassDecl->hasFlexibleArrayMember() && 4024 "Incomplete array type is not valid"); 4025 continue; 4026 } 4027 4028 // Initialize each field of an anonymous struct individually. 4029 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4030 HadError = true; 4031 4032 continue; 4033 } 4034 } 4035 4036 unsigned NumInitializers = Info.AllToInit.size(); 4037 if (NumInitializers > 0) { 4038 Constructor->setNumCtorInitializers(NumInitializers); 4039 CXXCtorInitializer **baseOrMemberInitializers = 4040 new (Context) CXXCtorInitializer*[NumInitializers]; 4041 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4042 NumInitializers * sizeof(CXXCtorInitializer*)); 4043 Constructor->setCtorInitializers(baseOrMemberInitializers); 4044 4045 // Constructors implicitly reference the base and member 4046 // destructors. 4047 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4048 Constructor->getParent()); 4049 } 4050 4051 return HadError; 4052 } 4053 4054 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4055 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4056 const RecordDecl *RD = RT->getDecl(); 4057 if (RD->isAnonymousStructOrUnion()) { 4058 for (auto *Field : RD->fields()) 4059 PopulateKeysForFields(Field, IdealInits); 4060 return; 4061 } 4062 } 4063 IdealInits.push_back(Field->getCanonicalDecl()); 4064 } 4065 4066 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4067 return Context.getCanonicalType(BaseType).getTypePtr(); 4068 } 4069 4070 static const void *GetKeyForMember(ASTContext &Context, 4071 CXXCtorInitializer *Member) { 4072 if (!Member->isAnyMemberInitializer()) 4073 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4074 4075 return Member->getAnyMember()->getCanonicalDecl(); 4076 } 4077 4078 static void DiagnoseBaseOrMemInitializerOrder( 4079 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4080 ArrayRef<CXXCtorInitializer *> Inits) { 4081 if (Constructor->getDeclContext()->isDependentContext()) 4082 return; 4083 4084 // Don't check initializers order unless the warning is enabled at the 4085 // location of at least one initializer. 4086 bool ShouldCheckOrder = false; 4087 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4088 CXXCtorInitializer *Init = Inits[InitIndex]; 4089 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4090 Init->getSourceLocation())) { 4091 ShouldCheckOrder = true; 4092 break; 4093 } 4094 } 4095 if (!ShouldCheckOrder) 4096 return; 4097 4098 // Build the list of bases and members in the order that they'll 4099 // actually be initialized. The explicit initializers should be in 4100 // this same order but may be missing things. 4101 SmallVector<const void*, 32> IdealInitKeys; 4102 4103 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4104 4105 // 1. Virtual bases. 4106 for (const auto &VBase : ClassDecl->vbases()) 4107 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4108 4109 // 2. Non-virtual bases. 4110 for (const auto &Base : ClassDecl->bases()) { 4111 if (Base.isVirtual()) 4112 continue; 4113 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4114 } 4115 4116 // 3. Direct fields. 4117 for (auto *Field : ClassDecl->fields()) { 4118 if (Field->isUnnamedBitfield()) 4119 continue; 4120 4121 PopulateKeysForFields(Field, IdealInitKeys); 4122 } 4123 4124 unsigned NumIdealInits = IdealInitKeys.size(); 4125 unsigned IdealIndex = 0; 4126 4127 CXXCtorInitializer *PrevInit = nullptr; 4128 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4129 CXXCtorInitializer *Init = Inits[InitIndex]; 4130 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4131 4132 // Scan forward to try to find this initializer in the idealized 4133 // initializers list. 4134 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4135 if (InitKey == IdealInitKeys[IdealIndex]) 4136 break; 4137 4138 // If we didn't find this initializer, it must be because we 4139 // scanned past it on a previous iteration. That can only 4140 // happen if we're out of order; emit a warning. 4141 if (IdealIndex == NumIdealInits && PrevInit) { 4142 Sema::SemaDiagnosticBuilder D = 4143 SemaRef.Diag(PrevInit->getSourceLocation(), 4144 diag::warn_initializer_out_of_order); 4145 4146 if (PrevInit->isAnyMemberInitializer()) 4147 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4148 else 4149 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4150 4151 if (Init->isAnyMemberInitializer()) 4152 D << 0 << Init->getAnyMember()->getDeclName(); 4153 else 4154 D << 1 << Init->getTypeSourceInfo()->getType(); 4155 4156 // Move back to the initializer's location in the ideal list. 4157 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4158 if (InitKey == IdealInitKeys[IdealIndex]) 4159 break; 4160 4161 assert(IdealIndex != NumIdealInits && 4162 "initializer not found in initializer list"); 4163 } 4164 4165 PrevInit = Init; 4166 } 4167 } 4168 4169 namespace { 4170 bool CheckRedundantInit(Sema &S, 4171 CXXCtorInitializer *Init, 4172 CXXCtorInitializer *&PrevInit) { 4173 if (!PrevInit) { 4174 PrevInit = Init; 4175 return false; 4176 } 4177 4178 if (FieldDecl *Field = Init->getAnyMember()) 4179 S.Diag(Init->getSourceLocation(), 4180 diag::err_multiple_mem_initialization) 4181 << Field->getDeclName() 4182 << Init->getSourceRange(); 4183 else { 4184 const Type *BaseClass = Init->getBaseClass(); 4185 assert(BaseClass && "neither field nor base"); 4186 S.Diag(Init->getSourceLocation(), 4187 diag::err_multiple_base_initialization) 4188 << QualType(BaseClass, 0) 4189 << Init->getSourceRange(); 4190 } 4191 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4192 << 0 << PrevInit->getSourceRange(); 4193 4194 return true; 4195 } 4196 4197 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4198 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4199 4200 bool CheckRedundantUnionInit(Sema &S, 4201 CXXCtorInitializer *Init, 4202 RedundantUnionMap &Unions) { 4203 FieldDecl *Field = Init->getAnyMember(); 4204 RecordDecl *Parent = Field->getParent(); 4205 NamedDecl *Child = Field; 4206 4207 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4208 if (Parent->isUnion()) { 4209 UnionEntry &En = Unions[Parent]; 4210 if (En.first && En.first != Child) { 4211 S.Diag(Init->getSourceLocation(), 4212 diag::err_multiple_mem_union_initialization) 4213 << Field->getDeclName() 4214 << Init->getSourceRange(); 4215 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4216 << 0 << En.second->getSourceRange(); 4217 return true; 4218 } 4219 if (!En.first) { 4220 En.first = Child; 4221 En.second = Init; 4222 } 4223 if (!Parent->isAnonymousStructOrUnion()) 4224 return false; 4225 } 4226 4227 Child = Parent; 4228 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4229 } 4230 4231 return false; 4232 } 4233 } 4234 4235 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4236 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4237 SourceLocation ColonLoc, 4238 ArrayRef<CXXCtorInitializer*> MemInits, 4239 bool AnyErrors) { 4240 if (!ConstructorDecl) 4241 return; 4242 4243 AdjustDeclIfTemplate(ConstructorDecl); 4244 4245 CXXConstructorDecl *Constructor 4246 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4247 4248 if (!Constructor) { 4249 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4250 return; 4251 } 4252 4253 // Mapping for the duplicate initializers check. 4254 // For member initializers, this is keyed with a FieldDecl*. 4255 // For base initializers, this is keyed with a Type*. 4256 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4257 4258 // Mapping for the inconsistent anonymous-union initializers check. 4259 RedundantUnionMap MemberUnions; 4260 4261 bool HadError = false; 4262 for (unsigned i = 0; i < MemInits.size(); i++) { 4263 CXXCtorInitializer *Init = MemInits[i]; 4264 4265 // Set the source order index. 4266 Init->setSourceOrder(i); 4267 4268 if (Init->isAnyMemberInitializer()) { 4269 const void *Key = GetKeyForMember(Context, Init); 4270 if (CheckRedundantInit(*this, Init, Members[Key]) || 4271 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4272 HadError = true; 4273 } else if (Init->isBaseInitializer()) { 4274 const void *Key = GetKeyForMember(Context, Init); 4275 if (CheckRedundantInit(*this, Init, Members[Key])) 4276 HadError = true; 4277 } else { 4278 assert(Init->isDelegatingInitializer()); 4279 // This must be the only initializer 4280 if (MemInits.size() != 1) { 4281 Diag(Init->getSourceLocation(), 4282 diag::err_delegating_initializer_alone) 4283 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4284 // We will treat this as being the only initializer. 4285 } 4286 SetDelegatingInitializer(Constructor, MemInits[i]); 4287 // Return immediately as the initializer is set. 4288 return; 4289 } 4290 } 4291 4292 if (HadError) 4293 return; 4294 4295 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4296 4297 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4298 4299 DiagnoseUninitializedFields(*this, Constructor); 4300 } 4301 4302 void 4303 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4304 CXXRecordDecl *ClassDecl) { 4305 // Ignore dependent contexts. Also ignore unions, since their members never 4306 // have destructors implicitly called. 4307 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4308 return; 4309 4310 // FIXME: all the access-control diagnostics are positioned on the 4311 // field/base declaration. That's probably good; that said, the 4312 // user might reasonably want to know why the destructor is being 4313 // emitted, and we currently don't say. 4314 4315 // Non-static data members. 4316 for (auto *Field : ClassDecl->fields()) { 4317 if (Field->isInvalidDecl()) 4318 continue; 4319 4320 // Don't destroy incomplete or zero-length arrays. 4321 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4322 continue; 4323 4324 QualType FieldType = Context.getBaseElementType(Field->getType()); 4325 4326 const RecordType* RT = FieldType->getAs<RecordType>(); 4327 if (!RT) 4328 continue; 4329 4330 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4331 if (FieldClassDecl->isInvalidDecl()) 4332 continue; 4333 if (FieldClassDecl->hasIrrelevantDestructor()) 4334 continue; 4335 // The destructor for an implicit anonymous union member is never invoked. 4336 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4337 continue; 4338 4339 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4340 assert(Dtor && "No dtor found for FieldClassDecl!"); 4341 CheckDestructorAccess(Field->getLocation(), Dtor, 4342 PDiag(diag::err_access_dtor_field) 4343 << Field->getDeclName() 4344 << FieldType); 4345 4346 MarkFunctionReferenced(Location, Dtor); 4347 DiagnoseUseOfDecl(Dtor, Location); 4348 } 4349 4350 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4351 4352 // Bases. 4353 for (const auto &Base : ClassDecl->bases()) { 4354 // Bases are always records in a well-formed non-dependent class. 4355 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4356 4357 // Remember direct virtual bases. 4358 if (Base.isVirtual()) 4359 DirectVirtualBases.insert(RT); 4360 4361 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4362 // If our base class is invalid, we probably can't get its dtor anyway. 4363 if (BaseClassDecl->isInvalidDecl()) 4364 continue; 4365 if (BaseClassDecl->hasIrrelevantDestructor()) 4366 continue; 4367 4368 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4369 assert(Dtor && "No dtor found for BaseClassDecl!"); 4370 4371 // FIXME: caret should be on the start of the class name 4372 CheckDestructorAccess(Base.getLocStart(), Dtor, 4373 PDiag(diag::err_access_dtor_base) 4374 << Base.getType() 4375 << Base.getSourceRange(), 4376 Context.getTypeDeclType(ClassDecl)); 4377 4378 MarkFunctionReferenced(Location, Dtor); 4379 DiagnoseUseOfDecl(Dtor, Location); 4380 } 4381 4382 // Virtual bases. 4383 for (const auto &VBase : ClassDecl->vbases()) { 4384 // Bases are always records in a well-formed non-dependent class. 4385 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4386 4387 // Ignore direct virtual bases. 4388 if (DirectVirtualBases.count(RT)) 4389 continue; 4390 4391 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4392 // If our base class is invalid, we probably can't get its dtor anyway. 4393 if (BaseClassDecl->isInvalidDecl()) 4394 continue; 4395 if (BaseClassDecl->hasIrrelevantDestructor()) 4396 continue; 4397 4398 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4399 assert(Dtor && "No dtor found for BaseClassDecl!"); 4400 if (CheckDestructorAccess( 4401 ClassDecl->getLocation(), Dtor, 4402 PDiag(diag::err_access_dtor_vbase) 4403 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4404 Context.getTypeDeclType(ClassDecl)) == 4405 AR_accessible) { 4406 CheckDerivedToBaseConversion( 4407 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4408 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4409 SourceRange(), DeclarationName(), nullptr); 4410 } 4411 4412 MarkFunctionReferenced(Location, Dtor); 4413 DiagnoseUseOfDecl(Dtor, Location); 4414 } 4415 } 4416 4417 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4418 if (!CDtorDecl) 4419 return; 4420 4421 if (CXXConstructorDecl *Constructor 4422 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4423 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4424 DiagnoseUninitializedFields(*this, Constructor); 4425 } 4426 } 4427 4428 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4429 unsigned DiagID, AbstractDiagSelID SelID) { 4430 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4431 unsigned DiagID; 4432 AbstractDiagSelID SelID; 4433 4434 public: 4435 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4436 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4437 4438 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4439 if (Suppressed) return; 4440 if (SelID == -1) 4441 S.Diag(Loc, DiagID) << T; 4442 else 4443 S.Diag(Loc, DiagID) << SelID << T; 4444 } 4445 } Diagnoser(DiagID, SelID); 4446 4447 return RequireNonAbstractType(Loc, T, Diagnoser); 4448 } 4449 4450 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4451 TypeDiagnoser &Diagnoser) { 4452 if (!getLangOpts().CPlusPlus) 4453 return false; 4454 4455 if (const ArrayType *AT = Context.getAsArrayType(T)) 4456 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4457 4458 if (const PointerType *PT = T->getAs<PointerType>()) { 4459 // Find the innermost pointer type. 4460 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4461 PT = T; 4462 4463 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4464 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4465 } 4466 4467 const RecordType *RT = T->getAs<RecordType>(); 4468 if (!RT) 4469 return false; 4470 4471 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4472 4473 // We can't answer whether something is abstract until it has a 4474 // definition. If it's currently being defined, we'll walk back 4475 // over all the declarations when we have a full definition. 4476 const CXXRecordDecl *Def = RD->getDefinition(); 4477 if (!Def || Def->isBeingDefined()) 4478 return false; 4479 4480 if (!RD->isAbstract()) 4481 return false; 4482 4483 Diagnoser.diagnose(*this, Loc, T); 4484 DiagnoseAbstractType(RD); 4485 4486 return true; 4487 } 4488 4489 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4490 // Check if we've already emitted the list of pure virtual functions 4491 // for this class. 4492 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4493 return; 4494 4495 // If the diagnostic is suppressed, don't emit the notes. We're only 4496 // going to emit them once, so try to attach them to a diagnostic we're 4497 // actually going to show. 4498 if (Diags.isLastDiagnosticIgnored()) 4499 return; 4500 4501 CXXFinalOverriderMap FinalOverriders; 4502 RD->getFinalOverriders(FinalOverriders); 4503 4504 // Keep a set of seen pure methods so we won't diagnose the same method 4505 // more than once. 4506 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4507 4508 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4509 MEnd = FinalOverriders.end(); 4510 M != MEnd; 4511 ++M) { 4512 for (OverridingMethods::iterator SO = M->second.begin(), 4513 SOEnd = M->second.end(); 4514 SO != SOEnd; ++SO) { 4515 // C++ [class.abstract]p4: 4516 // A class is abstract if it contains or inherits at least one 4517 // pure virtual function for which the final overrider is pure 4518 // virtual. 4519 4520 // 4521 if (SO->second.size() != 1) 4522 continue; 4523 4524 if (!SO->second.front().Method->isPure()) 4525 continue; 4526 4527 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4528 continue; 4529 4530 Diag(SO->second.front().Method->getLocation(), 4531 diag::note_pure_virtual_function) 4532 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4533 } 4534 } 4535 4536 if (!PureVirtualClassDiagSet) 4537 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4538 PureVirtualClassDiagSet->insert(RD); 4539 } 4540 4541 namespace { 4542 struct AbstractUsageInfo { 4543 Sema &S; 4544 CXXRecordDecl *Record; 4545 CanQualType AbstractType; 4546 bool Invalid; 4547 4548 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4549 : S(S), Record(Record), 4550 AbstractType(S.Context.getCanonicalType( 4551 S.Context.getTypeDeclType(Record))), 4552 Invalid(false) {} 4553 4554 void DiagnoseAbstractType() { 4555 if (Invalid) return; 4556 S.DiagnoseAbstractType(Record); 4557 Invalid = true; 4558 } 4559 4560 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4561 }; 4562 4563 struct CheckAbstractUsage { 4564 AbstractUsageInfo &Info; 4565 const NamedDecl *Ctx; 4566 4567 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4568 : Info(Info), Ctx(Ctx) {} 4569 4570 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4571 switch (TL.getTypeLocClass()) { 4572 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4573 #define TYPELOC(CLASS, PARENT) \ 4574 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4575 #include "clang/AST/TypeLocNodes.def" 4576 } 4577 } 4578 4579 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4580 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4581 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4582 if (!TL.getParam(I)) 4583 continue; 4584 4585 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4586 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4587 } 4588 } 4589 4590 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4591 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4592 } 4593 4594 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4595 // Visit the type parameters from a permissive context. 4596 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4597 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4598 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4599 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4600 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4601 // TODO: other template argument types? 4602 } 4603 } 4604 4605 // Visit pointee types from a permissive context. 4606 #define CheckPolymorphic(Type) \ 4607 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4608 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4609 } 4610 CheckPolymorphic(PointerTypeLoc) 4611 CheckPolymorphic(ReferenceTypeLoc) 4612 CheckPolymorphic(MemberPointerTypeLoc) 4613 CheckPolymorphic(BlockPointerTypeLoc) 4614 CheckPolymorphic(AtomicTypeLoc) 4615 4616 /// Handle all the types we haven't given a more specific 4617 /// implementation for above. 4618 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4619 // Every other kind of type that we haven't called out already 4620 // that has an inner type is either (1) sugar or (2) contains that 4621 // inner type in some way as a subobject. 4622 if (TypeLoc Next = TL.getNextTypeLoc()) 4623 return Visit(Next, Sel); 4624 4625 // If there's no inner type and we're in a permissive context, 4626 // don't diagnose. 4627 if (Sel == Sema::AbstractNone) return; 4628 4629 // Check whether the type matches the abstract type. 4630 QualType T = TL.getType(); 4631 if (T->isArrayType()) { 4632 Sel = Sema::AbstractArrayType; 4633 T = Info.S.Context.getBaseElementType(T); 4634 } 4635 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4636 if (CT != Info.AbstractType) return; 4637 4638 // It matched; do some magic. 4639 if (Sel == Sema::AbstractArrayType) { 4640 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4641 << T << TL.getSourceRange(); 4642 } else { 4643 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4644 << Sel << T << TL.getSourceRange(); 4645 } 4646 Info.DiagnoseAbstractType(); 4647 } 4648 }; 4649 4650 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4651 Sema::AbstractDiagSelID Sel) { 4652 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4653 } 4654 4655 } 4656 4657 /// Check for invalid uses of an abstract type in a method declaration. 4658 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4659 CXXMethodDecl *MD) { 4660 // No need to do the check on definitions, which require that 4661 // the return/param types be complete. 4662 if (MD->doesThisDeclarationHaveABody()) 4663 return; 4664 4665 // For safety's sake, just ignore it if we don't have type source 4666 // information. This should never happen for non-implicit methods, 4667 // but... 4668 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4669 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4670 } 4671 4672 /// Check for invalid uses of an abstract type within a class definition. 4673 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4674 CXXRecordDecl *RD) { 4675 for (auto *D : RD->decls()) { 4676 if (D->isImplicit()) continue; 4677 4678 // Methods and method templates. 4679 if (isa<CXXMethodDecl>(D)) { 4680 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4681 } else if (isa<FunctionTemplateDecl>(D)) { 4682 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4683 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4684 4685 // Fields and static variables. 4686 } else if (isa<FieldDecl>(D)) { 4687 FieldDecl *FD = cast<FieldDecl>(D); 4688 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4689 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4690 } else if (isa<VarDecl>(D)) { 4691 VarDecl *VD = cast<VarDecl>(D); 4692 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4693 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4694 4695 // Nested classes and class templates. 4696 } else if (isa<CXXRecordDecl>(D)) { 4697 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4698 } else if (isa<ClassTemplateDecl>(D)) { 4699 CheckAbstractClassUsage(Info, 4700 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4701 } 4702 } 4703 } 4704 4705 /// \brief Check class-level dllimport/dllexport attribute. 4706 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4707 Attr *ClassAttr = getDLLAttr(Class); 4708 4709 // MSVC inherits DLL attributes to partial class template specializations. 4710 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4711 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4712 if (Attr *TemplateAttr = 4713 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4714 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext())); 4715 A->setInherited(true); 4716 ClassAttr = A; 4717 } 4718 } 4719 } 4720 4721 if (!ClassAttr) 4722 return; 4723 4724 if (!Class->isExternallyVisible()) { 4725 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4726 << Class << ClassAttr; 4727 return; 4728 } 4729 4730 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4731 !ClassAttr->isInherited()) { 4732 // Diagnose dll attributes on members of class with dll attribute. 4733 for (Decl *Member : Class->decls()) { 4734 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4735 continue; 4736 InheritableAttr *MemberAttr = getDLLAttr(Member); 4737 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4738 continue; 4739 4740 S.Diag(MemberAttr->getLocation(), 4741 diag::err_attribute_dll_member_of_dll_class) 4742 << MemberAttr << ClassAttr; 4743 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4744 Member->setInvalidDecl(); 4745 } 4746 } 4747 4748 if (Class->getDescribedClassTemplate()) 4749 // Don't inherit dll attribute until the template is instantiated. 4750 return; 4751 4752 // The class is either imported or exported. 4753 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4754 const bool ClassImported = !ClassExported; 4755 4756 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4757 4758 // Don't dllexport explicit class template instantiation declarations. 4759 if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) { 4760 Class->dropAttr<DLLExportAttr>(); 4761 return; 4762 } 4763 4764 // Force declaration of implicit members so they can inherit the attribute. 4765 S.ForceDeclarationOfImplicitMembers(Class); 4766 4767 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4768 // seem to be true in practice? 4769 4770 for (Decl *Member : Class->decls()) { 4771 VarDecl *VD = dyn_cast<VarDecl>(Member); 4772 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4773 4774 // Only methods and static fields inherit the attributes. 4775 if (!VD && !MD) 4776 continue; 4777 4778 if (MD) { 4779 // Don't process deleted methods. 4780 if (MD->isDeleted()) 4781 continue; 4782 4783 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) { 4784 // Current MSVC versions don't export the move assignment operators, so 4785 // don't attempt to import them if we have a definition. 4786 continue; 4787 } 4788 4789 if (MD->isInlined() && 4790 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4791 // MinGW does not import or export inline methods. 4792 continue; 4793 } 4794 } 4795 4796 if (!getDLLAttr(Member)) { 4797 auto *NewAttr = 4798 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4799 NewAttr->setInherited(true); 4800 Member->addAttr(NewAttr); 4801 } 4802 4803 if (MD && ClassExported) { 4804 if (MD->isUserProvided()) { 4805 // Instantiate non-default class member functions ... 4806 4807 // .. except for certain kinds of template specializations. 4808 if (TSK == TSK_ExplicitInstantiationDeclaration) 4809 continue; 4810 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4811 continue; 4812 4813 S.MarkFunctionReferenced(Class->getLocation(), MD); 4814 4815 // The function will be passed to the consumer when its definition is 4816 // encountered. 4817 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4818 MD->isCopyAssignmentOperator() || 4819 MD->isMoveAssignmentOperator()) { 4820 // Synthesize and instantiate non-trivial implicit methods, explicitly 4821 // defaulted methods, and the copy and move assignment operators. The 4822 // latter are exported even if they are trivial, because the address of 4823 // an operator can be taken and should compare equal accross libraries. 4824 S.MarkFunctionReferenced(Class->getLocation(), MD); 4825 4826 // There is no later point when we will see the definition of this 4827 // function, so pass it to the consumer now. 4828 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 4829 } 4830 } 4831 } 4832 } 4833 4834 /// \brief Perform semantic checks on a class definition that has been 4835 /// completing, introducing implicitly-declared members, checking for 4836 /// abstract types, etc. 4837 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4838 if (!Record) 4839 return; 4840 4841 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4842 AbstractUsageInfo Info(*this, Record); 4843 CheckAbstractClassUsage(Info, Record); 4844 } 4845 4846 // If this is not an aggregate type and has no user-declared constructor, 4847 // complain about any non-static data members of reference or const scalar 4848 // type, since they will never get initializers. 4849 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4850 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4851 !Record->isLambda()) { 4852 bool Complained = false; 4853 for (const auto *F : Record->fields()) { 4854 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4855 continue; 4856 4857 if (F->getType()->isReferenceType() || 4858 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4859 if (!Complained) { 4860 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4861 << Record->getTagKind() << Record; 4862 Complained = true; 4863 } 4864 4865 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4866 << F->getType()->isReferenceType() 4867 << F->getDeclName(); 4868 } 4869 } 4870 } 4871 4872 if (Record->isDynamicClass() && !Record->isDependentType()) 4873 DynamicClasses.push_back(Record); 4874 4875 if (Record->getIdentifier()) { 4876 // C++ [class.mem]p13: 4877 // If T is the name of a class, then each of the following shall have a 4878 // name different from T: 4879 // - every member of every anonymous union that is a member of class T. 4880 // 4881 // C++ [class.mem]p14: 4882 // In addition, if class T has a user-declared constructor (12.1), every 4883 // non-static data member of class T shall have a name different from T. 4884 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4885 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4886 ++I) { 4887 NamedDecl *D = *I; 4888 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4889 isa<IndirectFieldDecl>(D)) { 4890 Diag(D->getLocation(), diag::err_member_name_of_class) 4891 << D->getDeclName(); 4892 break; 4893 } 4894 } 4895 } 4896 4897 // Warn if the class has virtual methods but non-virtual public destructor. 4898 if (Record->isPolymorphic() && !Record->isDependentType()) { 4899 CXXDestructorDecl *dtor = Record->getDestructor(); 4900 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4901 !Record->hasAttr<FinalAttr>()) 4902 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4903 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4904 } 4905 4906 if (Record->isAbstract()) { 4907 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4908 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4909 << FA->isSpelledAsSealed(); 4910 DiagnoseAbstractType(Record); 4911 } 4912 } 4913 4914 bool HasMethodWithOverrideControl = false, 4915 HasOverridingMethodWithoutOverrideControl = false; 4916 if (!Record->isDependentType()) { 4917 for (auto *M : Record->methods()) { 4918 // See if a method overloads virtual methods in a base 4919 // class without overriding any. 4920 if (!M->isStatic()) 4921 DiagnoseHiddenVirtualMethods(M); 4922 if (M->hasAttr<OverrideAttr>()) 4923 HasMethodWithOverrideControl = true; 4924 else if (M->size_overridden_methods() > 0) 4925 HasOverridingMethodWithoutOverrideControl = true; 4926 // Check whether the explicitly-defaulted special members are valid. 4927 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4928 CheckExplicitlyDefaultedSpecialMember(M); 4929 4930 // For an explicitly defaulted or deleted special member, we defer 4931 // determining triviality until the class is complete. That time is now! 4932 if (!M->isImplicit() && !M->isUserProvided()) { 4933 CXXSpecialMember CSM = getSpecialMember(M); 4934 if (CSM != CXXInvalid) { 4935 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4936 4937 // Inform the class that we've finished declaring this member. 4938 Record->finishedDefaultedOrDeletedMember(M); 4939 } 4940 } 4941 } 4942 } 4943 4944 if (HasMethodWithOverrideControl && 4945 HasOverridingMethodWithoutOverrideControl) { 4946 // At least one method has the 'override' control declared. 4947 // Diagnose all other overridden methods which do not have 'override' specified on them. 4948 for (auto *M : Record->methods()) 4949 DiagnoseAbsenceOfOverrideControl(M); 4950 } 4951 4952 // ms_struct is a request to use the same ABI rules as MSVC. Check 4953 // whether this class uses any C++ features that are implemented 4954 // completely differently in MSVC, and if so, emit a diagnostic. 4955 // That diagnostic defaults to an error, but we allow projects to 4956 // map it down to a warning (or ignore it). It's a fairly common 4957 // practice among users of the ms_struct pragma to mass-annotate 4958 // headers, sweeping up a bunch of types that the project doesn't 4959 // really rely on MSVC-compatible layout for. We must therefore 4960 // support "ms_struct except for C++ stuff" as a secondary ABI. 4961 if (Record->isMsStruct(Context) && 4962 (Record->isPolymorphic() || Record->getNumBases())) { 4963 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4964 } 4965 4966 // Declare inheriting constructors. We do this eagerly here because: 4967 // - The standard requires an eager diagnostic for conflicting inheriting 4968 // constructors from different classes. 4969 // - The lazy declaration of the other implicit constructors is so as to not 4970 // waste space and performance on classes that are not meant to be 4971 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4972 // have inheriting constructors. 4973 DeclareInheritingConstructors(Record); 4974 4975 checkDLLAttribute(*this, Record); 4976 } 4977 4978 /// Look up the special member function that would be called by a special 4979 /// member function for a subobject of class type. 4980 /// 4981 /// \param Class The class type of the subobject. 4982 /// \param CSM The kind of special member function. 4983 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4984 /// \param ConstRHS True if this is a copy operation with a const object 4985 /// on its RHS, that is, if the argument to the outer special member 4986 /// function is 'const' and this is not a field marked 'mutable'. 4987 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4988 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4989 unsigned FieldQuals, bool ConstRHS) { 4990 unsigned LHSQuals = 0; 4991 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4992 LHSQuals = FieldQuals; 4993 4994 unsigned RHSQuals = FieldQuals; 4995 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4996 RHSQuals = 0; 4997 else if (ConstRHS) 4998 RHSQuals |= Qualifiers::Const; 4999 5000 return S.LookupSpecialMember(Class, CSM, 5001 RHSQuals & Qualifiers::Const, 5002 RHSQuals & Qualifiers::Volatile, 5003 false, 5004 LHSQuals & Qualifiers::Const, 5005 LHSQuals & Qualifiers::Volatile); 5006 } 5007 5008 /// Is the special member function which would be selected to perform the 5009 /// specified operation on the specified class type a constexpr constructor? 5010 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5011 Sema::CXXSpecialMember CSM, 5012 unsigned Quals, bool ConstRHS) { 5013 Sema::SpecialMemberOverloadResult *SMOR = 5014 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5015 if (!SMOR || !SMOR->getMethod()) 5016 // A constructor we wouldn't select can't be "involved in initializing" 5017 // anything. 5018 return true; 5019 return SMOR->getMethod()->isConstexpr(); 5020 } 5021 5022 /// Determine whether the specified special member function would be constexpr 5023 /// if it were implicitly defined. 5024 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5025 Sema::CXXSpecialMember CSM, 5026 bool ConstArg) { 5027 if (!S.getLangOpts().CPlusPlus11) 5028 return false; 5029 5030 // C++11 [dcl.constexpr]p4: 5031 // In the definition of a constexpr constructor [...] 5032 bool Ctor = true; 5033 switch (CSM) { 5034 case Sema::CXXDefaultConstructor: 5035 // Since default constructor lookup is essentially trivial (and cannot 5036 // involve, for instance, template instantiation), we compute whether a 5037 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5038 // 5039 // This is important for performance; we need to know whether the default 5040 // constructor is constexpr to determine whether the type is a literal type. 5041 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5042 5043 case Sema::CXXCopyConstructor: 5044 case Sema::CXXMoveConstructor: 5045 // For copy or move constructors, we need to perform overload resolution. 5046 break; 5047 5048 case Sema::CXXCopyAssignment: 5049 case Sema::CXXMoveAssignment: 5050 if (!S.getLangOpts().CPlusPlus14) 5051 return false; 5052 // In C++1y, we need to perform overload resolution. 5053 Ctor = false; 5054 break; 5055 5056 case Sema::CXXDestructor: 5057 case Sema::CXXInvalid: 5058 return false; 5059 } 5060 5061 // -- if the class is a non-empty union, or for each non-empty anonymous 5062 // union member of a non-union class, exactly one non-static data member 5063 // shall be initialized; [DR1359] 5064 // 5065 // If we squint, this is guaranteed, since exactly one non-static data member 5066 // will be initialized (if the constructor isn't deleted), we just don't know 5067 // which one. 5068 if (Ctor && ClassDecl->isUnion()) 5069 return true; 5070 5071 // -- the class shall not have any virtual base classes; 5072 if (Ctor && ClassDecl->getNumVBases()) 5073 return false; 5074 5075 // C++1y [class.copy]p26: 5076 // -- [the class] is a literal type, and 5077 if (!Ctor && !ClassDecl->isLiteral()) 5078 return false; 5079 5080 // -- every constructor involved in initializing [...] base class 5081 // sub-objects shall be a constexpr constructor; 5082 // -- the assignment operator selected to copy/move each direct base 5083 // class is a constexpr function, and 5084 for (const auto &B : ClassDecl->bases()) { 5085 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5086 if (!BaseType) continue; 5087 5088 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5089 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5090 return false; 5091 } 5092 5093 // -- every constructor involved in initializing non-static data members 5094 // [...] shall be a constexpr constructor; 5095 // -- every non-static data member and base class sub-object shall be 5096 // initialized 5097 // -- for each non-static data member of X that is of class type (or array 5098 // thereof), the assignment operator selected to copy/move that member is 5099 // a constexpr function 5100 for (const auto *F : ClassDecl->fields()) { 5101 if (F->isInvalidDecl()) 5102 continue; 5103 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5104 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5105 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5106 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5107 BaseType.getCVRQualifiers(), 5108 ConstArg && !F->isMutable())) 5109 return false; 5110 } 5111 } 5112 5113 // All OK, it's constexpr! 5114 return true; 5115 } 5116 5117 static Sema::ImplicitExceptionSpecification 5118 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5119 switch (S.getSpecialMember(MD)) { 5120 case Sema::CXXDefaultConstructor: 5121 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5122 case Sema::CXXCopyConstructor: 5123 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5124 case Sema::CXXCopyAssignment: 5125 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5126 case Sema::CXXMoveConstructor: 5127 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5128 case Sema::CXXMoveAssignment: 5129 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5130 case Sema::CXXDestructor: 5131 return S.ComputeDefaultedDtorExceptionSpec(MD); 5132 case Sema::CXXInvalid: 5133 break; 5134 } 5135 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5136 "only special members have implicit exception specs"); 5137 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5138 } 5139 5140 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5141 CXXMethodDecl *MD) { 5142 FunctionProtoType::ExtProtoInfo EPI; 5143 5144 // Build an exception specification pointing back at this member. 5145 EPI.ExceptionSpec.Type = EST_Unevaluated; 5146 EPI.ExceptionSpec.SourceDecl = MD; 5147 5148 // Set the calling convention to the default for C++ instance methods. 5149 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5150 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5151 /*IsCXXMethod=*/true)); 5152 return EPI; 5153 } 5154 5155 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5156 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5157 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5158 return; 5159 5160 // Evaluate the exception specification. 5161 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5162 5163 // Update the type of the special member to use it. 5164 UpdateExceptionSpec(MD, ESI); 5165 5166 // A user-provided destructor can be defined outside the class. When that 5167 // happens, be sure to update the exception specification on both 5168 // declarations. 5169 const FunctionProtoType *CanonicalFPT = 5170 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5171 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5172 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5173 } 5174 5175 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5176 CXXRecordDecl *RD = MD->getParent(); 5177 CXXSpecialMember CSM = getSpecialMember(MD); 5178 5179 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5180 "not an explicitly-defaulted special member"); 5181 5182 // Whether this was the first-declared instance of the constructor. 5183 // This affects whether we implicitly add an exception spec and constexpr. 5184 bool First = MD == MD->getCanonicalDecl(); 5185 5186 bool HadError = false; 5187 5188 // C++11 [dcl.fct.def.default]p1: 5189 // A function that is explicitly defaulted shall 5190 // -- be a special member function (checked elsewhere), 5191 // -- have the same type (except for ref-qualifiers, and except that a 5192 // copy operation can take a non-const reference) as an implicit 5193 // declaration, and 5194 // -- not have default arguments. 5195 unsigned ExpectedParams = 1; 5196 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5197 ExpectedParams = 0; 5198 if (MD->getNumParams() != ExpectedParams) { 5199 // This also checks for default arguments: a copy or move constructor with a 5200 // default argument is classified as a default constructor, and assignment 5201 // operations and destructors can't have default arguments. 5202 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5203 << CSM << MD->getSourceRange(); 5204 HadError = true; 5205 } else if (MD->isVariadic()) { 5206 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5207 << CSM << MD->getSourceRange(); 5208 HadError = true; 5209 } 5210 5211 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5212 5213 bool CanHaveConstParam = false; 5214 if (CSM == CXXCopyConstructor) 5215 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5216 else if (CSM == CXXCopyAssignment) 5217 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5218 5219 QualType ReturnType = Context.VoidTy; 5220 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5221 // Check for return type matching. 5222 ReturnType = Type->getReturnType(); 5223 QualType ExpectedReturnType = 5224 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5225 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5226 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5227 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5228 HadError = true; 5229 } 5230 5231 // A defaulted special member cannot have cv-qualifiers. 5232 if (Type->getTypeQuals()) { 5233 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5234 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5235 HadError = true; 5236 } 5237 } 5238 5239 // Check for parameter type matching. 5240 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5241 bool HasConstParam = false; 5242 if (ExpectedParams && ArgType->isReferenceType()) { 5243 // Argument must be reference to possibly-const T. 5244 QualType ReferentType = ArgType->getPointeeType(); 5245 HasConstParam = ReferentType.isConstQualified(); 5246 5247 if (ReferentType.isVolatileQualified()) { 5248 Diag(MD->getLocation(), 5249 diag::err_defaulted_special_member_volatile_param) << CSM; 5250 HadError = true; 5251 } 5252 5253 if (HasConstParam && !CanHaveConstParam) { 5254 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5255 Diag(MD->getLocation(), 5256 diag::err_defaulted_special_member_copy_const_param) 5257 << (CSM == CXXCopyAssignment); 5258 // FIXME: Explain why this special member can't be const. 5259 } else { 5260 Diag(MD->getLocation(), 5261 diag::err_defaulted_special_member_move_const_param) 5262 << (CSM == CXXMoveAssignment); 5263 } 5264 HadError = true; 5265 } 5266 } else if (ExpectedParams) { 5267 // A copy assignment operator can take its argument by value, but a 5268 // defaulted one cannot. 5269 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5270 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5271 HadError = true; 5272 } 5273 5274 // C++11 [dcl.fct.def.default]p2: 5275 // An explicitly-defaulted function may be declared constexpr only if it 5276 // would have been implicitly declared as constexpr, 5277 // Do not apply this rule to members of class templates, since core issue 1358 5278 // makes such functions always instantiate to constexpr functions. For 5279 // functions which cannot be constexpr (for non-constructors in C++11 and for 5280 // destructors in C++1y), this is checked elsewhere. 5281 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5282 HasConstParam); 5283 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5284 : isa<CXXConstructorDecl>(MD)) && 5285 MD->isConstexpr() && !Constexpr && 5286 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5287 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5288 // FIXME: Explain why the special member can't be constexpr. 5289 HadError = true; 5290 } 5291 5292 // and may have an explicit exception-specification only if it is compatible 5293 // with the exception-specification on the implicit declaration. 5294 if (Type->hasExceptionSpec()) { 5295 // Delay the check if this is the first declaration of the special member, 5296 // since we may not have parsed some necessary in-class initializers yet. 5297 if (First) { 5298 // If the exception specification needs to be instantiated, do so now, 5299 // before we clobber it with an EST_Unevaluated specification below. 5300 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5301 InstantiateExceptionSpec(MD->getLocStart(), MD); 5302 Type = MD->getType()->getAs<FunctionProtoType>(); 5303 } 5304 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5305 } else 5306 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5307 } 5308 5309 // If a function is explicitly defaulted on its first declaration, 5310 if (First) { 5311 // -- it is implicitly considered to be constexpr if the implicit 5312 // definition would be, 5313 MD->setConstexpr(Constexpr); 5314 5315 // -- it is implicitly considered to have the same exception-specification 5316 // as if it had been implicitly declared, 5317 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5318 EPI.ExceptionSpec.Type = EST_Unevaluated; 5319 EPI.ExceptionSpec.SourceDecl = MD; 5320 MD->setType(Context.getFunctionType(ReturnType, 5321 llvm::makeArrayRef(&ArgType, 5322 ExpectedParams), 5323 EPI)); 5324 } 5325 5326 if (ShouldDeleteSpecialMember(MD, CSM)) { 5327 if (First) { 5328 SetDeclDeleted(MD, MD->getLocation()); 5329 } else { 5330 // C++11 [dcl.fct.def.default]p4: 5331 // [For a] user-provided explicitly-defaulted function [...] if such a 5332 // function is implicitly defined as deleted, the program is ill-formed. 5333 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5334 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5335 HadError = true; 5336 } 5337 } 5338 5339 if (HadError) 5340 MD->setInvalidDecl(); 5341 } 5342 5343 /// Check whether the exception specification provided for an 5344 /// explicitly-defaulted special member matches the exception specification 5345 /// that would have been generated for an implicit special member, per 5346 /// C++11 [dcl.fct.def.default]p2. 5347 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5348 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5349 // If the exception specification was explicitly specified but hadn't been 5350 // parsed when the method was defaulted, grab it now. 5351 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5352 SpecifiedType = 5353 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5354 5355 // Compute the implicit exception specification. 5356 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5357 /*IsCXXMethod=*/true); 5358 FunctionProtoType::ExtProtoInfo EPI(CC); 5359 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5360 .getExceptionSpec(); 5361 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5362 Context.getFunctionType(Context.VoidTy, None, EPI)); 5363 5364 // Ensure that it matches. 5365 CheckEquivalentExceptionSpec( 5366 PDiag(diag::err_incorrect_defaulted_exception_spec) 5367 << getSpecialMember(MD), PDiag(), 5368 ImplicitType, SourceLocation(), 5369 SpecifiedType, MD->getLocation()); 5370 } 5371 5372 void Sema::CheckDelayedMemberExceptionSpecs() { 5373 decltype(DelayedExceptionSpecChecks) Checks; 5374 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 5375 5376 std::swap(Checks, DelayedExceptionSpecChecks); 5377 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5378 5379 // Perform any deferred checking of exception specifications for virtual 5380 // destructors. 5381 for (auto &Check : Checks) 5382 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 5383 5384 // Check that any explicitly-defaulted methods have exception specifications 5385 // compatible with their implicit exception specifications. 5386 for (auto &Spec : Specs) 5387 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 5388 } 5389 5390 namespace { 5391 struct SpecialMemberDeletionInfo { 5392 Sema &S; 5393 CXXMethodDecl *MD; 5394 Sema::CXXSpecialMember CSM; 5395 bool Diagnose; 5396 5397 // Properties of the special member, computed for convenience. 5398 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5399 SourceLocation Loc; 5400 5401 bool AllFieldsAreConst; 5402 5403 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5404 Sema::CXXSpecialMember CSM, bool Diagnose) 5405 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5406 IsConstructor(false), IsAssignment(false), IsMove(false), 5407 ConstArg(false), Loc(MD->getLocation()), 5408 AllFieldsAreConst(true) { 5409 switch (CSM) { 5410 case Sema::CXXDefaultConstructor: 5411 case Sema::CXXCopyConstructor: 5412 IsConstructor = true; 5413 break; 5414 case Sema::CXXMoveConstructor: 5415 IsConstructor = true; 5416 IsMove = true; 5417 break; 5418 case Sema::CXXCopyAssignment: 5419 IsAssignment = true; 5420 break; 5421 case Sema::CXXMoveAssignment: 5422 IsAssignment = true; 5423 IsMove = true; 5424 break; 5425 case Sema::CXXDestructor: 5426 break; 5427 case Sema::CXXInvalid: 5428 llvm_unreachable("invalid special member kind"); 5429 } 5430 5431 if (MD->getNumParams()) { 5432 if (const ReferenceType *RT = 5433 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5434 ConstArg = RT->getPointeeType().isConstQualified(); 5435 } 5436 } 5437 5438 bool inUnion() const { return MD->getParent()->isUnion(); } 5439 5440 /// Look up the corresponding special member in the given class. 5441 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5442 unsigned Quals, bool IsMutable) { 5443 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5444 ConstArg && !IsMutable); 5445 } 5446 5447 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5448 5449 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5450 bool shouldDeleteForField(FieldDecl *FD); 5451 bool shouldDeleteForAllConstMembers(); 5452 5453 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5454 unsigned Quals); 5455 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5456 Sema::SpecialMemberOverloadResult *SMOR, 5457 bool IsDtorCallInCtor); 5458 5459 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5460 }; 5461 } 5462 5463 /// Is the given special member inaccessible when used on the given 5464 /// sub-object. 5465 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5466 CXXMethodDecl *target) { 5467 /// If we're operating on a base class, the object type is the 5468 /// type of this special member. 5469 QualType objectTy; 5470 AccessSpecifier access = target->getAccess(); 5471 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5472 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5473 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5474 5475 // If we're operating on a field, the object type is the type of the field. 5476 } else { 5477 objectTy = S.Context.getTypeDeclType(target->getParent()); 5478 } 5479 5480 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5481 } 5482 5483 /// Check whether we should delete a special member due to the implicit 5484 /// definition containing a call to a special member of a subobject. 5485 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5486 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5487 bool IsDtorCallInCtor) { 5488 CXXMethodDecl *Decl = SMOR->getMethod(); 5489 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5490 5491 int DiagKind = -1; 5492 5493 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5494 DiagKind = !Decl ? 0 : 1; 5495 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5496 DiagKind = 2; 5497 else if (!isAccessible(Subobj, Decl)) 5498 DiagKind = 3; 5499 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5500 !Decl->isTrivial()) { 5501 // A member of a union must have a trivial corresponding special member. 5502 // As a weird special case, a destructor call from a union's constructor 5503 // must be accessible and non-deleted, but need not be trivial. Such a 5504 // destructor is never actually called, but is semantically checked as 5505 // if it were. 5506 DiagKind = 4; 5507 } 5508 5509 if (DiagKind == -1) 5510 return false; 5511 5512 if (Diagnose) { 5513 if (Field) { 5514 S.Diag(Field->getLocation(), 5515 diag::note_deleted_special_member_class_subobject) 5516 << CSM << MD->getParent() << /*IsField*/true 5517 << Field << DiagKind << IsDtorCallInCtor; 5518 } else { 5519 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5520 S.Diag(Base->getLocStart(), 5521 diag::note_deleted_special_member_class_subobject) 5522 << CSM << MD->getParent() << /*IsField*/false 5523 << Base->getType() << DiagKind << IsDtorCallInCtor; 5524 } 5525 5526 if (DiagKind == 1) 5527 S.NoteDeletedFunction(Decl); 5528 // FIXME: Explain inaccessibility if DiagKind == 3. 5529 } 5530 5531 return true; 5532 } 5533 5534 /// Check whether we should delete a special member function due to having a 5535 /// direct or virtual base class or non-static data member of class type M. 5536 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5537 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5538 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5539 bool IsMutable = Field && Field->isMutable(); 5540 5541 // C++11 [class.ctor]p5: 5542 // -- any direct or virtual base class, or non-static data member with no 5543 // brace-or-equal-initializer, has class type M (or array thereof) and 5544 // either M has no default constructor or overload resolution as applied 5545 // to M's default constructor results in an ambiguity or in a function 5546 // that is deleted or inaccessible 5547 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5548 // -- a direct or virtual base class B that cannot be copied/moved because 5549 // overload resolution, as applied to B's corresponding special member, 5550 // results in an ambiguity or a function that is deleted or inaccessible 5551 // from the defaulted special member 5552 // C++11 [class.dtor]p5: 5553 // -- any direct or virtual base class [...] has a type with a destructor 5554 // that is deleted or inaccessible 5555 if (!(CSM == Sema::CXXDefaultConstructor && 5556 Field && Field->hasInClassInitializer()) && 5557 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5558 false)) 5559 return true; 5560 5561 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5562 // -- any direct or virtual base class or non-static data member has a 5563 // type with a destructor that is deleted or inaccessible 5564 if (IsConstructor) { 5565 Sema::SpecialMemberOverloadResult *SMOR = 5566 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5567 false, false, false, false, false); 5568 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5569 return true; 5570 } 5571 5572 return false; 5573 } 5574 5575 /// Check whether we should delete a special member function due to the class 5576 /// having a particular direct or virtual base class. 5577 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5578 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5579 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5580 } 5581 5582 /// Check whether we should delete a special member function due to the class 5583 /// having a particular non-static data member. 5584 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5585 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5586 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5587 5588 if (CSM == Sema::CXXDefaultConstructor) { 5589 // For a default constructor, all references must be initialized in-class 5590 // and, if a union, it must have a non-const member. 5591 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5592 if (Diagnose) 5593 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5594 << MD->getParent() << FD << FieldType << /*Reference*/0; 5595 return true; 5596 } 5597 // C++11 [class.ctor]p5: any non-variant non-static data member of 5598 // const-qualified type (or array thereof) with no 5599 // brace-or-equal-initializer does not have a user-provided default 5600 // constructor. 5601 if (!inUnion() && FieldType.isConstQualified() && 5602 !FD->hasInClassInitializer() && 5603 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5604 if (Diagnose) 5605 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5606 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5607 return true; 5608 } 5609 5610 if (inUnion() && !FieldType.isConstQualified()) 5611 AllFieldsAreConst = false; 5612 } else if (CSM == Sema::CXXCopyConstructor) { 5613 // For a copy constructor, data members must not be of rvalue reference 5614 // type. 5615 if (FieldType->isRValueReferenceType()) { 5616 if (Diagnose) 5617 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5618 << MD->getParent() << FD << FieldType; 5619 return true; 5620 } 5621 } else if (IsAssignment) { 5622 // For an assignment operator, data members must not be of reference type. 5623 if (FieldType->isReferenceType()) { 5624 if (Diagnose) 5625 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5626 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5627 return true; 5628 } 5629 if (!FieldRecord && FieldType.isConstQualified()) { 5630 // C++11 [class.copy]p23: 5631 // -- a non-static data member of const non-class type (or array thereof) 5632 if (Diagnose) 5633 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5634 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5635 return true; 5636 } 5637 } 5638 5639 if (FieldRecord) { 5640 // Some additional restrictions exist on the variant members. 5641 if (!inUnion() && FieldRecord->isUnion() && 5642 FieldRecord->isAnonymousStructOrUnion()) { 5643 bool AllVariantFieldsAreConst = true; 5644 5645 // FIXME: Handle anonymous unions declared within anonymous unions. 5646 for (auto *UI : FieldRecord->fields()) { 5647 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5648 5649 if (!UnionFieldType.isConstQualified()) 5650 AllVariantFieldsAreConst = false; 5651 5652 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5653 if (UnionFieldRecord && 5654 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5655 UnionFieldType.getCVRQualifiers())) 5656 return true; 5657 } 5658 5659 // At least one member in each anonymous union must be non-const 5660 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5661 !FieldRecord->field_empty()) { 5662 if (Diagnose) 5663 S.Diag(FieldRecord->getLocation(), 5664 diag::note_deleted_default_ctor_all_const) 5665 << MD->getParent() << /*anonymous union*/1; 5666 return true; 5667 } 5668 5669 // Don't check the implicit member of the anonymous union type. 5670 // This is technically non-conformant, but sanity demands it. 5671 return false; 5672 } 5673 5674 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5675 FieldType.getCVRQualifiers())) 5676 return true; 5677 } 5678 5679 return false; 5680 } 5681 5682 /// C++11 [class.ctor] p5: 5683 /// A defaulted default constructor for a class X is defined as deleted if 5684 /// X is a union and all of its variant members are of const-qualified type. 5685 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5686 // This is a silly definition, because it gives an empty union a deleted 5687 // default constructor. Don't do that. 5688 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5689 !MD->getParent()->field_empty()) { 5690 if (Diagnose) 5691 S.Diag(MD->getParent()->getLocation(), 5692 diag::note_deleted_default_ctor_all_const) 5693 << MD->getParent() << /*not anonymous union*/0; 5694 return true; 5695 } 5696 return false; 5697 } 5698 5699 /// Determine whether a defaulted special member function should be defined as 5700 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5701 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5702 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5703 bool Diagnose) { 5704 if (MD->isInvalidDecl()) 5705 return false; 5706 CXXRecordDecl *RD = MD->getParent(); 5707 assert(!RD->isDependentType() && "do deletion after instantiation"); 5708 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5709 return false; 5710 5711 // C++11 [expr.lambda.prim]p19: 5712 // The closure type associated with a lambda-expression has a 5713 // deleted (8.4.3) default constructor and a deleted copy 5714 // assignment operator. 5715 if (RD->isLambda() && 5716 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5717 if (Diagnose) 5718 Diag(RD->getLocation(), diag::note_lambda_decl); 5719 return true; 5720 } 5721 5722 // For an anonymous struct or union, the copy and assignment special members 5723 // will never be used, so skip the check. For an anonymous union declared at 5724 // namespace scope, the constructor and destructor are used. 5725 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5726 RD->isAnonymousStructOrUnion()) 5727 return false; 5728 5729 // C++11 [class.copy]p7, p18: 5730 // If the class definition declares a move constructor or move assignment 5731 // operator, an implicitly declared copy constructor or copy assignment 5732 // operator is defined as deleted. 5733 if (MD->isImplicit() && 5734 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5735 CXXMethodDecl *UserDeclaredMove = nullptr; 5736 5737 // In Microsoft mode, a user-declared move only causes the deletion of the 5738 // corresponding copy operation, not both copy operations. 5739 if (RD->hasUserDeclaredMoveConstructor() && 5740 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5741 if (!Diagnose) return true; 5742 5743 // Find any user-declared move constructor. 5744 for (auto *I : RD->ctors()) { 5745 if (I->isMoveConstructor()) { 5746 UserDeclaredMove = I; 5747 break; 5748 } 5749 } 5750 assert(UserDeclaredMove); 5751 } else if (RD->hasUserDeclaredMoveAssignment() && 5752 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5753 if (!Diagnose) return true; 5754 5755 // Find any user-declared move assignment operator. 5756 for (auto *I : RD->methods()) { 5757 if (I->isMoveAssignmentOperator()) { 5758 UserDeclaredMove = I; 5759 break; 5760 } 5761 } 5762 assert(UserDeclaredMove); 5763 } 5764 5765 if (UserDeclaredMove) { 5766 Diag(UserDeclaredMove->getLocation(), 5767 diag::note_deleted_copy_user_declared_move) 5768 << (CSM == CXXCopyAssignment) << RD 5769 << UserDeclaredMove->isMoveAssignmentOperator(); 5770 return true; 5771 } 5772 } 5773 5774 // Do access control from the special member function 5775 ContextRAII MethodContext(*this, MD); 5776 5777 // C++11 [class.dtor]p5: 5778 // -- for a virtual destructor, lookup of the non-array deallocation function 5779 // results in an ambiguity or in a function that is deleted or inaccessible 5780 if (CSM == CXXDestructor && MD->isVirtual()) { 5781 FunctionDecl *OperatorDelete = nullptr; 5782 DeclarationName Name = 5783 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5784 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5785 OperatorDelete, false)) { 5786 if (Diagnose) 5787 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5788 return true; 5789 } 5790 } 5791 5792 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5793 5794 for (auto &BI : RD->bases()) 5795 if (!BI.isVirtual() && 5796 SMI.shouldDeleteForBase(&BI)) 5797 return true; 5798 5799 // Per DR1611, do not consider virtual bases of constructors of abstract 5800 // classes, since we are not going to construct them. 5801 if (!RD->isAbstract() || !SMI.IsConstructor) { 5802 for (auto &BI : RD->vbases()) 5803 if (SMI.shouldDeleteForBase(&BI)) 5804 return true; 5805 } 5806 5807 for (auto *FI : RD->fields()) 5808 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5809 SMI.shouldDeleteForField(FI)) 5810 return true; 5811 5812 if (SMI.shouldDeleteForAllConstMembers()) 5813 return true; 5814 5815 if (getLangOpts().CUDA) { 5816 // We should delete the special member in CUDA mode if target inference 5817 // failed. 5818 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5819 Diagnose); 5820 } 5821 5822 return false; 5823 } 5824 5825 /// Perform lookup for a special member of the specified kind, and determine 5826 /// whether it is trivial. If the triviality can be determined without the 5827 /// lookup, skip it. This is intended for use when determining whether a 5828 /// special member of a containing object is trivial, and thus does not ever 5829 /// perform overload resolution for default constructors. 5830 /// 5831 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5832 /// member that was most likely to be intended to be trivial, if any. 5833 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5834 Sema::CXXSpecialMember CSM, unsigned Quals, 5835 bool ConstRHS, CXXMethodDecl **Selected) { 5836 if (Selected) 5837 *Selected = nullptr; 5838 5839 switch (CSM) { 5840 case Sema::CXXInvalid: 5841 llvm_unreachable("not a special member"); 5842 5843 case Sema::CXXDefaultConstructor: 5844 // C++11 [class.ctor]p5: 5845 // A default constructor is trivial if: 5846 // - all the [direct subobjects] have trivial default constructors 5847 // 5848 // Note, no overload resolution is performed in this case. 5849 if (RD->hasTrivialDefaultConstructor()) 5850 return true; 5851 5852 if (Selected) { 5853 // If there's a default constructor which could have been trivial, dig it 5854 // out. Otherwise, if there's any user-provided default constructor, point 5855 // to that as an example of why there's not a trivial one. 5856 CXXConstructorDecl *DefCtor = nullptr; 5857 if (RD->needsImplicitDefaultConstructor()) 5858 S.DeclareImplicitDefaultConstructor(RD); 5859 for (auto *CI : RD->ctors()) { 5860 if (!CI->isDefaultConstructor()) 5861 continue; 5862 DefCtor = CI; 5863 if (!DefCtor->isUserProvided()) 5864 break; 5865 } 5866 5867 *Selected = DefCtor; 5868 } 5869 5870 return false; 5871 5872 case Sema::CXXDestructor: 5873 // C++11 [class.dtor]p5: 5874 // A destructor is trivial if: 5875 // - all the direct [subobjects] have trivial destructors 5876 if (RD->hasTrivialDestructor()) 5877 return true; 5878 5879 if (Selected) { 5880 if (RD->needsImplicitDestructor()) 5881 S.DeclareImplicitDestructor(RD); 5882 *Selected = RD->getDestructor(); 5883 } 5884 5885 return false; 5886 5887 case Sema::CXXCopyConstructor: 5888 // C++11 [class.copy]p12: 5889 // A copy constructor is trivial if: 5890 // - the constructor selected to copy each direct [subobject] is trivial 5891 if (RD->hasTrivialCopyConstructor()) { 5892 if (Quals == Qualifiers::Const) 5893 // We must either select the trivial copy constructor or reach an 5894 // ambiguity; no need to actually perform overload resolution. 5895 return true; 5896 } else if (!Selected) { 5897 return false; 5898 } 5899 // In C++98, we are not supposed to perform overload resolution here, but we 5900 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5901 // cases like B as having a non-trivial copy constructor: 5902 // struct A { template<typename T> A(T&); }; 5903 // struct B { mutable A a; }; 5904 goto NeedOverloadResolution; 5905 5906 case Sema::CXXCopyAssignment: 5907 // C++11 [class.copy]p25: 5908 // A copy assignment operator is trivial if: 5909 // - the assignment operator selected to copy each direct [subobject] is 5910 // trivial 5911 if (RD->hasTrivialCopyAssignment()) { 5912 if (Quals == Qualifiers::Const) 5913 return true; 5914 } else if (!Selected) { 5915 return false; 5916 } 5917 // In C++98, we are not supposed to perform overload resolution here, but we 5918 // treat that as a language defect. 5919 goto NeedOverloadResolution; 5920 5921 case Sema::CXXMoveConstructor: 5922 case Sema::CXXMoveAssignment: 5923 NeedOverloadResolution: 5924 Sema::SpecialMemberOverloadResult *SMOR = 5925 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5926 5927 // The standard doesn't describe how to behave if the lookup is ambiguous. 5928 // We treat it as not making the member non-trivial, just like the standard 5929 // mandates for the default constructor. This should rarely matter, because 5930 // the member will also be deleted. 5931 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5932 return true; 5933 5934 if (!SMOR->getMethod()) { 5935 assert(SMOR->getKind() == 5936 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5937 return false; 5938 } 5939 5940 // We deliberately don't check if we found a deleted special member. We're 5941 // not supposed to! 5942 if (Selected) 5943 *Selected = SMOR->getMethod(); 5944 return SMOR->getMethod()->isTrivial(); 5945 } 5946 5947 llvm_unreachable("unknown special method kind"); 5948 } 5949 5950 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5951 for (auto *CI : RD->ctors()) 5952 if (!CI->isImplicit()) 5953 return CI; 5954 5955 // Look for constructor templates. 5956 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5957 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5958 if (CXXConstructorDecl *CD = 5959 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5960 return CD; 5961 } 5962 5963 return nullptr; 5964 } 5965 5966 /// The kind of subobject we are checking for triviality. The values of this 5967 /// enumeration are used in diagnostics. 5968 enum TrivialSubobjectKind { 5969 /// The subobject is a base class. 5970 TSK_BaseClass, 5971 /// The subobject is a non-static data member. 5972 TSK_Field, 5973 /// The object is actually the complete object. 5974 TSK_CompleteObject 5975 }; 5976 5977 /// Check whether the special member selected for a given type would be trivial. 5978 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5979 QualType SubType, bool ConstRHS, 5980 Sema::CXXSpecialMember CSM, 5981 TrivialSubobjectKind Kind, 5982 bool Diagnose) { 5983 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5984 if (!SubRD) 5985 return true; 5986 5987 CXXMethodDecl *Selected; 5988 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5989 ConstRHS, Diagnose ? &Selected : nullptr)) 5990 return true; 5991 5992 if (Diagnose) { 5993 if (ConstRHS) 5994 SubType.addConst(); 5995 5996 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5997 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5998 << Kind << SubType.getUnqualifiedType(); 5999 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6000 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6001 } else if (!Selected) 6002 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6003 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6004 else if (Selected->isUserProvided()) { 6005 if (Kind == TSK_CompleteObject) 6006 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6007 << Kind << SubType.getUnqualifiedType() << CSM; 6008 else { 6009 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6010 << Kind << SubType.getUnqualifiedType() << CSM; 6011 S.Diag(Selected->getLocation(), diag::note_declared_at); 6012 } 6013 } else { 6014 if (Kind != TSK_CompleteObject) 6015 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6016 << Kind << SubType.getUnqualifiedType() << CSM; 6017 6018 // Explain why the defaulted or deleted special member isn't trivial. 6019 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6020 } 6021 } 6022 6023 return false; 6024 } 6025 6026 /// Check whether the members of a class type allow a special member to be 6027 /// trivial. 6028 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 6029 Sema::CXXSpecialMember CSM, 6030 bool ConstArg, bool Diagnose) { 6031 for (const auto *FI : RD->fields()) { 6032 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 6033 continue; 6034 6035 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 6036 6037 // Pretend anonymous struct or union members are members of this class. 6038 if (FI->isAnonymousStructOrUnion()) { 6039 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 6040 CSM, ConstArg, Diagnose)) 6041 return false; 6042 continue; 6043 } 6044 6045 // C++11 [class.ctor]p5: 6046 // A default constructor is trivial if [...] 6047 // -- no non-static data member of its class has a 6048 // brace-or-equal-initializer 6049 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 6050 if (Diagnose) 6051 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 6052 return false; 6053 } 6054 6055 // Objective C ARC 4.3.5: 6056 // [...] nontrivally ownership-qualified types are [...] not trivially 6057 // default constructible, copy constructible, move constructible, copy 6058 // assignable, move assignable, or destructible [...] 6059 if (S.getLangOpts().ObjCAutoRefCount && 6060 FieldType.hasNonTrivialObjCLifetime()) { 6061 if (Diagnose) 6062 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6063 << RD << FieldType.getObjCLifetime(); 6064 return false; 6065 } 6066 6067 bool ConstRHS = ConstArg && !FI->isMutable(); 6068 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6069 CSM, TSK_Field, Diagnose)) 6070 return false; 6071 } 6072 6073 return true; 6074 } 6075 6076 /// Diagnose why the specified class does not have a trivial special member of 6077 /// the given kind. 6078 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6079 QualType Ty = Context.getRecordType(RD); 6080 6081 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6082 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6083 TSK_CompleteObject, /*Diagnose*/true); 6084 } 6085 6086 /// Determine whether a defaulted or deleted special member function is trivial, 6087 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6088 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6089 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6090 bool Diagnose) { 6091 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6092 6093 CXXRecordDecl *RD = MD->getParent(); 6094 6095 bool ConstArg = false; 6096 6097 // C++11 [class.copy]p12, p25: [DR1593] 6098 // A [special member] is trivial if [...] its parameter-type-list is 6099 // equivalent to the parameter-type-list of an implicit declaration [...] 6100 switch (CSM) { 6101 case CXXDefaultConstructor: 6102 case CXXDestructor: 6103 // Trivial default constructors and destructors cannot have parameters. 6104 break; 6105 6106 case CXXCopyConstructor: 6107 case CXXCopyAssignment: { 6108 // Trivial copy operations always have const, non-volatile parameter types. 6109 ConstArg = true; 6110 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6111 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6112 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6113 if (Diagnose) 6114 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6115 << Param0->getSourceRange() << Param0->getType() 6116 << Context.getLValueReferenceType( 6117 Context.getRecordType(RD).withConst()); 6118 return false; 6119 } 6120 break; 6121 } 6122 6123 case CXXMoveConstructor: 6124 case CXXMoveAssignment: { 6125 // Trivial move operations always have non-cv-qualified parameters. 6126 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6127 const RValueReferenceType *RT = 6128 Param0->getType()->getAs<RValueReferenceType>(); 6129 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6130 if (Diagnose) 6131 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6132 << Param0->getSourceRange() << Param0->getType() 6133 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6134 return false; 6135 } 6136 break; 6137 } 6138 6139 case CXXInvalid: 6140 llvm_unreachable("not a special member"); 6141 } 6142 6143 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6144 if (Diagnose) 6145 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6146 diag::note_nontrivial_default_arg) 6147 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6148 return false; 6149 } 6150 if (MD->isVariadic()) { 6151 if (Diagnose) 6152 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6153 return false; 6154 } 6155 6156 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6157 // A copy/move [constructor or assignment operator] is trivial if 6158 // -- the [member] selected to copy/move each direct base class subobject 6159 // is trivial 6160 // 6161 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6162 // A [default constructor or destructor] is trivial if 6163 // -- all the direct base classes have trivial [default constructors or 6164 // destructors] 6165 for (const auto &BI : RD->bases()) 6166 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6167 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6168 return false; 6169 6170 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6171 // A copy/move [constructor or assignment operator] for a class X is 6172 // trivial if 6173 // -- for each non-static data member of X that is of class type (or array 6174 // thereof), the constructor selected to copy/move that member is 6175 // trivial 6176 // 6177 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6178 // A [default constructor or destructor] is trivial if 6179 // -- for all of the non-static data members of its class that are of class 6180 // type (or array thereof), each such class has a trivial [default 6181 // constructor or destructor] 6182 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6183 return false; 6184 6185 // C++11 [class.dtor]p5: 6186 // A destructor is trivial if [...] 6187 // -- the destructor is not virtual 6188 if (CSM == CXXDestructor && MD->isVirtual()) { 6189 if (Diagnose) 6190 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6191 return false; 6192 } 6193 6194 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6195 // A [special member] for class X is trivial if [...] 6196 // -- class X has no virtual functions and no virtual base classes 6197 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6198 if (!Diagnose) 6199 return false; 6200 6201 if (RD->getNumVBases()) { 6202 // Check for virtual bases. We already know that the corresponding 6203 // member in all bases is trivial, so vbases must all be direct. 6204 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6205 assert(BS.isVirtual()); 6206 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6207 return false; 6208 } 6209 6210 // Must have a virtual method. 6211 for (const auto *MI : RD->methods()) { 6212 if (MI->isVirtual()) { 6213 SourceLocation MLoc = MI->getLocStart(); 6214 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6215 return false; 6216 } 6217 } 6218 6219 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6220 } 6221 6222 // Looks like it's trivial! 6223 return true; 6224 } 6225 6226 /// \brief Data used with FindHiddenVirtualMethod 6227 namespace { 6228 struct FindHiddenVirtualMethodData { 6229 Sema *S; 6230 CXXMethodDecl *Method; 6231 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6232 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6233 }; 6234 } 6235 6236 /// \brief Check whether any most overriden method from MD in Methods 6237 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 6238 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6239 if (MD->size_overridden_methods() == 0) 6240 return Methods.count(MD->getCanonicalDecl()); 6241 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6242 E = MD->end_overridden_methods(); 6243 I != E; ++I) 6244 if (CheckMostOverridenMethods(*I, Methods)) 6245 return true; 6246 return false; 6247 } 6248 6249 /// \brief Member lookup function that determines whether a given C++ 6250 /// method overloads virtual methods in a base class without overriding any, 6251 /// to be used with CXXRecordDecl::lookupInBases(). 6252 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 6253 CXXBasePath &Path, 6254 void *UserData) { 6255 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6256 6257 FindHiddenVirtualMethodData &Data 6258 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 6259 6260 DeclarationName Name = Data.Method->getDeclName(); 6261 assert(Name.getNameKind() == DeclarationName::Identifier); 6262 6263 bool foundSameNameMethod = false; 6264 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6265 for (Path.Decls = BaseRecord->lookup(Name); 6266 !Path.Decls.empty(); 6267 Path.Decls = Path.Decls.slice(1)) { 6268 NamedDecl *D = Path.Decls.front(); 6269 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6270 MD = MD->getCanonicalDecl(); 6271 foundSameNameMethod = true; 6272 // Interested only in hidden virtual methods. 6273 if (!MD->isVirtual()) 6274 continue; 6275 // If the method we are checking overrides a method from its base 6276 // don't warn about the other overloaded methods. Clang deviates from GCC 6277 // by only diagnosing overloads of inherited virtual functions that do not 6278 // override any other virtual functions in the base. GCC's 6279 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6280 // function from a base class. These cases may be better served by a 6281 // warning (not specific to virtual functions) on call sites when the call 6282 // would select a different function from the base class, were it visible. 6283 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6284 if (!Data.S->IsOverload(Data.Method, MD, false)) 6285 return true; 6286 // Collect the overload only if its hidden. 6287 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 6288 overloadedMethods.push_back(MD); 6289 } 6290 } 6291 6292 if (foundSameNameMethod) 6293 Data.OverloadedMethods.append(overloadedMethods.begin(), 6294 overloadedMethods.end()); 6295 return foundSameNameMethod; 6296 } 6297 6298 /// \brief Add the most overriden methods from MD to Methods 6299 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6300 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6301 if (MD->size_overridden_methods() == 0) 6302 Methods.insert(MD->getCanonicalDecl()); 6303 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6304 E = MD->end_overridden_methods(); 6305 I != E; ++I) 6306 AddMostOverridenMethods(*I, Methods); 6307 } 6308 6309 /// \brief Check if a method overloads virtual methods in a base class without 6310 /// overriding any. 6311 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6312 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6313 if (!MD->getDeclName().isIdentifier()) 6314 return; 6315 6316 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6317 /*bool RecordPaths=*/false, 6318 /*bool DetectVirtual=*/false); 6319 FindHiddenVirtualMethodData Data; 6320 Data.Method = MD; 6321 Data.S = this; 6322 6323 // Keep the base methods that were overriden or introduced in the subclass 6324 // by 'using' in a set. A base method not in this set is hidden. 6325 CXXRecordDecl *DC = MD->getParent(); 6326 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6327 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6328 NamedDecl *ND = *I; 6329 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6330 ND = shad->getTargetDecl(); 6331 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6332 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6333 } 6334 6335 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6336 OverloadedMethods = Data.OverloadedMethods; 6337 } 6338 6339 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6340 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6341 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6342 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6343 PartialDiagnostic PD = PDiag( 6344 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6345 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6346 Diag(overloadedMD->getLocation(), PD); 6347 } 6348 } 6349 6350 /// \brief Diagnose methods which overload virtual methods in a base class 6351 /// without overriding any. 6352 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6353 if (MD->isInvalidDecl()) 6354 return; 6355 6356 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6357 return; 6358 6359 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6360 FindHiddenVirtualMethods(MD, OverloadedMethods); 6361 if (!OverloadedMethods.empty()) { 6362 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6363 << MD << (OverloadedMethods.size() > 1); 6364 6365 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6366 } 6367 } 6368 6369 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6370 Decl *TagDecl, 6371 SourceLocation LBrac, 6372 SourceLocation RBrac, 6373 AttributeList *AttrList) { 6374 if (!TagDecl) 6375 return; 6376 6377 AdjustDeclIfTemplate(TagDecl); 6378 6379 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6380 if (l->getKind() != AttributeList::AT_Visibility) 6381 continue; 6382 l->setInvalid(); 6383 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6384 l->getName(); 6385 } 6386 6387 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6388 // strict aliasing violation! 6389 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6390 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6391 6392 CheckCompletedCXXClass( 6393 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6394 } 6395 6396 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6397 /// special functions, such as the default constructor, copy 6398 /// constructor, or destructor, to the given C++ class (C++ 6399 /// [special]p1). This routine can only be executed just before the 6400 /// definition of the class is complete. 6401 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6402 if (!ClassDecl->hasUserDeclaredConstructor()) 6403 ++ASTContext::NumImplicitDefaultConstructors; 6404 6405 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6406 ++ASTContext::NumImplicitCopyConstructors; 6407 6408 // If the properties or semantics of the copy constructor couldn't be 6409 // determined while the class was being declared, force a declaration 6410 // of it now. 6411 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6412 DeclareImplicitCopyConstructor(ClassDecl); 6413 } 6414 6415 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6416 ++ASTContext::NumImplicitMoveConstructors; 6417 6418 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6419 DeclareImplicitMoveConstructor(ClassDecl); 6420 } 6421 6422 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6423 ++ASTContext::NumImplicitCopyAssignmentOperators; 6424 6425 // If we have a dynamic class, then the copy assignment operator may be 6426 // virtual, so we have to declare it immediately. This ensures that, e.g., 6427 // it shows up in the right place in the vtable and that we diagnose 6428 // problems with the implicit exception specification. 6429 if (ClassDecl->isDynamicClass() || 6430 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6431 DeclareImplicitCopyAssignment(ClassDecl); 6432 } 6433 6434 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6435 ++ASTContext::NumImplicitMoveAssignmentOperators; 6436 6437 // Likewise for the move assignment operator. 6438 if (ClassDecl->isDynamicClass() || 6439 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6440 DeclareImplicitMoveAssignment(ClassDecl); 6441 } 6442 6443 if (!ClassDecl->hasUserDeclaredDestructor()) { 6444 ++ASTContext::NumImplicitDestructors; 6445 6446 // If we have a dynamic class, then the destructor may be virtual, so we 6447 // have to declare the destructor immediately. This ensures that, e.g., it 6448 // shows up in the right place in the vtable and that we diagnose problems 6449 // with the implicit exception specification. 6450 if (ClassDecl->isDynamicClass() || 6451 ClassDecl->needsOverloadResolutionForDestructor()) 6452 DeclareImplicitDestructor(ClassDecl); 6453 } 6454 } 6455 6456 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6457 if (!D) 6458 return 0; 6459 6460 // The order of template parameters is not important here. All names 6461 // get added to the same scope. 6462 SmallVector<TemplateParameterList *, 4> ParameterLists; 6463 6464 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6465 D = TD->getTemplatedDecl(); 6466 6467 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6468 ParameterLists.push_back(PSD->getTemplateParameters()); 6469 6470 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6471 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6472 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6473 6474 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6475 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6476 ParameterLists.push_back(FTD->getTemplateParameters()); 6477 } 6478 } 6479 6480 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6481 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6482 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6483 6484 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6485 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6486 ParameterLists.push_back(CTD->getTemplateParameters()); 6487 } 6488 } 6489 6490 unsigned Count = 0; 6491 for (TemplateParameterList *Params : ParameterLists) { 6492 if (Params->size() > 0) 6493 // Ignore explicit specializations; they don't contribute to the template 6494 // depth. 6495 ++Count; 6496 for (NamedDecl *Param : *Params) { 6497 if (Param->getDeclName()) { 6498 S->AddDecl(Param); 6499 IdResolver.AddDecl(Param); 6500 } 6501 } 6502 } 6503 6504 return Count; 6505 } 6506 6507 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6508 if (!RecordD) return; 6509 AdjustDeclIfTemplate(RecordD); 6510 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6511 PushDeclContext(S, Record); 6512 } 6513 6514 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6515 if (!RecordD) return; 6516 PopDeclContext(); 6517 } 6518 6519 /// This is used to implement the constant expression evaluation part of the 6520 /// attribute enable_if extension. There is nothing in standard C++ which would 6521 /// require reentering parameters. 6522 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6523 if (!Param) 6524 return; 6525 6526 S->AddDecl(Param); 6527 if (Param->getDeclName()) 6528 IdResolver.AddDecl(Param); 6529 } 6530 6531 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6532 /// parsing a top-level (non-nested) C++ class, and we are now 6533 /// parsing those parts of the given Method declaration that could 6534 /// not be parsed earlier (C++ [class.mem]p2), such as default 6535 /// arguments. This action should enter the scope of the given 6536 /// Method declaration as if we had just parsed the qualified method 6537 /// name. However, it should not bring the parameters into scope; 6538 /// that will be performed by ActOnDelayedCXXMethodParameter. 6539 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6540 } 6541 6542 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6543 /// C++ method declaration. We're (re-)introducing the given 6544 /// function parameter into scope for use in parsing later parts of 6545 /// the method declaration. For example, we could see an 6546 /// ActOnParamDefaultArgument event for this parameter. 6547 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6548 if (!ParamD) 6549 return; 6550 6551 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6552 6553 // If this parameter has an unparsed default argument, clear it out 6554 // to make way for the parsed default argument. 6555 if (Param->hasUnparsedDefaultArg()) 6556 Param->setDefaultArg(nullptr); 6557 6558 S->AddDecl(Param); 6559 if (Param->getDeclName()) 6560 IdResolver.AddDecl(Param); 6561 } 6562 6563 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6564 /// processing the delayed method declaration for Method. The method 6565 /// declaration is now considered finished. There may be a separate 6566 /// ActOnStartOfFunctionDef action later (not necessarily 6567 /// immediately!) for this method, if it was also defined inside the 6568 /// class body. 6569 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6570 if (!MethodD) 6571 return; 6572 6573 AdjustDeclIfTemplate(MethodD); 6574 6575 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6576 6577 // Now that we have our default arguments, check the constructor 6578 // again. It could produce additional diagnostics or affect whether 6579 // the class has implicitly-declared destructors, among other 6580 // things. 6581 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6582 CheckConstructor(Constructor); 6583 6584 // Check the default arguments, which we may have added. 6585 if (!Method->isInvalidDecl()) 6586 CheckCXXDefaultArguments(Method); 6587 } 6588 6589 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6590 /// the well-formedness of the constructor declarator @p D with type @p 6591 /// R. If there are any errors in the declarator, this routine will 6592 /// emit diagnostics and set the invalid bit to true. In any case, the type 6593 /// will be updated to reflect a well-formed type for the constructor and 6594 /// returned. 6595 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6596 StorageClass &SC) { 6597 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6598 6599 // C++ [class.ctor]p3: 6600 // A constructor shall not be virtual (10.3) or static (9.4). A 6601 // constructor can be invoked for a const, volatile or const 6602 // volatile object. A constructor shall not be declared const, 6603 // volatile, or const volatile (9.3.2). 6604 if (isVirtual) { 6605 if (!D.isInvalidType()) 6606 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6607 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6608 << SourceRange(D.getIdentifierLoc()); 6609 D.setInvalidType(); 6610 } 6611 if (SC == SC_Static) { 6612 if (!D.isInvalidType()) 6613 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6614 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6615 << SourceRange(D.getIdentifierLoc()); 6616 D.setInvalidType(); 6617 SC = SC_None; 6618 } 6619 6620 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6621 diagnoseIgnoredQualifiers( 6622 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6623 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6624 D.getDeclSpec().getRestrictSpecLoc(), 6625 D.getDeclSpec().getAtomicSpecLoc()); 6626 D.setInvalidType(); 6627 } 6628 6629 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6630 if (FTI.TypeQuals != 0) { 6631 if (FTI.TypeQuals & Qualifiers::Const) 6632 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6633 << "const" << SourceRange(D.getIdentifierLoc()); 6634 if (FTI.TypeQuals & Qualifiers::Volatile) 6635 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6636 << "volatile" << SourceRange(D.getIdentifierLoc()); 6637 if (FTI.TypeQuals & Qualifiers::Restrict) 6638 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6639 << "restrict" << SourceRange(D.getIdentifierLoc()); 6640 D.setInvalidType(); 6641 } 6642 6643 // C++0x [class.ctor]p4: 6644 // A constructor shall not be declared with a ref-qualifier. 6645 if (FTI.hasRefQualifier()) { 6646 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6647 << FTI.RefQualifierIsLValueRef 6648 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6649 D.setInvalidType(); 6650 } 6651 6652 // Rebuild the function type "R" without any type qualifiers (in 6653 // case any of the errors above fired) and with "void" as the 6654 // return type, since constructors don't have return types. 6655 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6656 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6657 return R; 6658 6659 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6660 EPI.TypeQuals = 0; 6661 EPI.RefQualifier = RQ_None; 6662 6663 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6664 } 6665 6666 /// CheckConstructor - Checks a fully-formed constructor for 6667 /// well-formedness, issuing any diagnostics required. Returns true if 6668 /// the constructor declarator is invalid. 6669 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6670 CXXRecordDecl *ClassDecl 6671 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6672 if (!ClassDecl) 6673 return Constructor->setInvalidDecl(); 6674 6675 // C++ [class.copy]p3: 6676 // A declaration of a constructor for a class X is ill-formed if 6677 // its first parameter is of type (optionally cv-qualified) X and 6678 // either there are no other parameters or else all other 6679 // parameters have default arguments. 6680 if (!Constructor->isInvalidDecl() && 6681 ((Constructor->getNumParams() == 1) || 6682 (Constructor->getNumParams() > 1 && 6683 Constructor->getParamDecl(1)->hasDefaultArg())) && 6684 Constructor->getTemplateSpecializationKind() 6685 != TSK_ImplicitInstantiation) { 6686 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6687 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6688 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6689 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6690 const char *ConstRef 6691 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6692 : " const &"; 6693 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6694 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6695 6696 // FIXME: Rather that making the constructor invalid, we should endeavor 6697 // to fix the type. 6698 Constructor->setInvalidDecl(); 6699 } 6700 } 6701 } 6702 6703 /// CheckDestructor - Checks a fully-formed destructor definition for 6704 /// well-formedness, issuing any diagnostics required. Returns true 6705 /// on error. 6706 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6707 CXXRecordDecl *RD = Destructor->getParent(); 6708 6709 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6710 SourceLocation Loc; 6711 6712 if (!Destructor->isImplicit()) 6713 Loc = Destructor->getLocation(); 6714 else 6715 Loc = RD->getLocation(); 6716 6717 // If we have a virtual destructor, look up the deallocation function 6718 FunctionDecl *OperatorDelete = nullptr; 6719 DeclarationName Name = 6720 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6721 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6722 return true; 6723 // If there's no class-specific operator delete, look up the global 6724 // non-array delete. 6725 if (!OperatorDelete) 6726 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6727 6728 MarkFunctionReferenced(Loc, OperatorDelete); 6729 6730 Destructor->setOperatorDelete(OperatorDelete); 6731 } 6732 6733 return false; 6734 } 6735 6736 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6737 /// the well-formednes of the destructor declarator @p D with type @p 6738 /// R. If there are any errors in the declarator, this routine will 6739 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6740 /// will be updated to reflect a well-formed type for the destructor and 6741 /// returned. 6742 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6743 StorageClass& SC) { 6744 // C++ [class.dtor]p1: 6745 // [...] A typedef-name that names a class is a class-name 6746 // (7.1.3); however, a typedef-name that names a class shall not 6747 // be used as the identifier in the declarator for a destructor 6748 // declaration. 6749 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6750 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6751 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6752 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6753 else if (const TemplateSpecializationType *TST = 6754 DeclaratorType->getAs<TemplateSpecializationType>()) 6755 if (TST->isTypeAlias()) 6756 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6757 << DeclaratorType << 1; 6758 6759 // C++ [class.dtor]p2: 6760 // A destructor is used to destroy objects of its class type. A 6761 // destructor takes no parameters, and no return type can be 6762 // specified for it (not even void). The address of a destructor 6763 // shall not be taken. A destructor shall not be static. A 6764 // destructor can be invoked for a const, volatile or const 6765 // volatile object. A destructor shall not be declared const, 6766 // volatile or const volatile (9.3.2). 6767 if (SC == SC_Static) { 6768 if (!D.isInvalidType()) 6769 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6770 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6771 << SourceRange(D.getIdentifierLoc()) 6772 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6773 6774 SC = SC_None; 6775 } 6776 if (!D.isInvalidType()) { 6777 // Destructors don't have return types, but the parser will 6778 // happily parse something like: 6779 // 6780 // class X { 6781 // float ~X(); 6782 // }; 6783 // 6784 // The return type will be eliminated later. 6785 if (D.getDeclSpec().hasTypeSpecifier()) 6786 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6787 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6788 << SourceRange(D.getIdentifierLoc()); 6789 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6790 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6791 SourceLocation(), 6792 D.getDeclSpec().getConstSpecLoc(), 6793 D.getDeclSpec().getVolatileSpecLoc(), 6794 D.getDeclSpec().getRestrictSpecLoc(), 6795 D.getDeclSpec().getAtomicSpecLoc()); 6796 D.setInvalidType(); 6797 } 6798 } 6799 6800 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6801 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6802 if (FTI.TypeQuals & Qualifiers::Const) 6803 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6804 << "const" << SourceRange(D.getIdentifierLoc()); 6805 if (FTI.TypeQuals & Qualifiers::Volatile) 6806 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6807 << "volatile" << SourceRange(D.getIdentifierLoc()); 6808 if (FTI.TypeQuals & Qualifiers::Restrict) 6809 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6810 << "restrict" << SourceRange(D.getIdentifierLoc()); 6811 D.setInvalidType(); 6812 } 6813 6814 // C++0x [class.dtor]p2: 6815 // A destructor shall not be declared with a ref-qualifier. 6816 if (FTI.hasRefQualifier()) { 6817 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6818 << FTI.RefQualifierIsLValueRef 6819 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6820 D.setInvalidType(); 6821 } 6822 6823 // Make sure we don't have any parameters. 6824 if (FTIHasNonVoidParameters(FTI)) { 6825 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6826 6827 // Delete the parameters. 6828 FTI.freeParams(); 6829 D.setInvalidType(); 6830 } 6831 6832 // Make sure the destructor isn't variadic. 6833 if (FTI.isVariadic) { 6834 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6835 D.setInvalidType(); 6836 } 6837 6838 // Rebuild the function type "R" without any type qualifiers or 6839 // parameters (in case any of the errors above fired) and with 6840 // "void" as the return type, since destructors don't have return 6841 // types. 6842 if (!D.isInvalidType()) 6843 return R; 6844 6845 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6846 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6847 EPI.Variadic = false; 6848 EPI.TypeQuals = 0; 6849 EPI.RefQualifier = RQ_None; 6850 return Context.getFunctionType(Context.VoidTy, None, EPI); 6851 } 6852 6853 static void extendLeft(SourceRange &R, const SourceRange &Before) { 6854 if (Before.isInvalid()) 6855 return; 6856 R.setBegin(Before.getBegin()); 6857 if (R.getEnd().isInvalid()) 6858 R.setEnd(Before.getEnd()); 6859 } 6860 6861 static void extendRight(SourceRange &R, const SourceRange &After) { 6862 if (After.isInvalid()) 6863 return; 6864 if (R.getBegin().isInvalid()) 6865 R.setBegin(After.getBegin()); 6866 R.setEnd(After.getEnd()); 6867 } 6868 6869 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6870 /// well-formednes of the conversion function declarator @p D with 6871 /// type @p R. If there are any errors in the declarator, this routine 6872 /// will emit diagnostics and return true. Otherwise, it will return 6873 /// false. Either way, the type @p R will be updated to reflect a 6874 /// well-formed type for the conversion operator. 6875 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6876 StorageClass& SC) { 6877 // C++ [class.conv.fct]p1: 6878 // Neither parameter types nor return type can be specified. The 6879 // type of a conversion function (8.3.5) is "function taking no 6880 // parameter returning conversion-type-id." 6881 if (SC == SC_Static) { 6882 if (!D.isInvalidType()) 6883 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6884 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6885 << D.getName().getSourceRange(); 6886 D.setInvalidType(); 6887 SC = SC_None; 6888 } 6889 6890 TypeSourceInfo *ConvTSI = nullptr; 6891 QualType ConvType = 6892 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 6893 6894 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6895 // Conversion functions don't have return types, but the parser will 6896 // happily parse something like: 6897 // 6898 // class X { 6899 // float operator bool(); 6900 // }; 6901 // 6902 // The return type will be changed later anyway. 6903 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6904 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6905 << SourceRange(D.getIdentifierLoc()); 6906 D.setInvalidType(); 6907 } 6908 6909 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6910 6911 // Make sure we don't have any parameters. 6912 if (Proto->getNumParams() > 0) { 6913 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6914 6915 // Delete the parameters. 6916 D.getFunctionTypeInfo().freeParams(); 6917 D.setInvalidType(); 6918 } else if (Proto->isVariadic()) { 6919 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6920 D.setInvalidType(); 6921 } 6922 6923 // Diagnose "&operator bool()" and other such nonsense. This 6924 // is actually a gcc extension which we don't support. 6925 if (Proto->getReturnType() != ConvType) { 6926 bool NeedsTypedef = false; 6927 SourceRange Before, After; 6928 6929 // Walk the chunks and extract information on them for our diagnostic. 6930 bool PastFunctionChunk = false; 6931 for (auto &Chunk : D.type_objects()) { 6932 switch (Chunk.Kind) { 6933 case DeclaratorChunk::Function: 6934 if (!PastFunctionChunk) { 6935 if (Chunk.Fun.HasTrailingReturnType) { 6936 TypeSourceInfo *TRT = nullptr; 6937 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 6938 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 6939 } 6940 PastFunctionChunk = true; 6941 break; 6942 } 6943 // Fall through. 6944 case DeclaratorChunk::Array: 6945 NeedsTypedef = true; 6946 extendRight(After, Chunk.getSourceRange()); 6947 break; 6948 6949 case DeclaratorChunk::Pointer: 6950 case DeclaratorChunk::BlockPointer: 6951 case DeclaratorChunk::Reference: 6952 case DeclaratorChunk::MemberPointer: 6953 extendLeft(Before, Chunk.getSourceRange()); 6954 break; 6955 6956 case DeclaratorChunk::Paren: 6957 extendLeft(Before, Chunk.Loc); 6958 extendRight(After, Chunk.EndLoc); 6959 break; 6960 } 6961 } 6962 6963 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 6964 After.isValid() ? After.getBegin() : 6965 D.getIdentifierLoc(); 6966 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 6967 DB << Before << After; 6968 6969 if (!NeedsTypedef) { 6970 DB << /*don't need a typedef*/0; 6971 6972 // If we can provide a correct fix-it hint, do so. 6973 if (After.isInvalid() && ConvTSI) { 6974 SourceLocation InsertLoc = 6975 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 6976 DB << FixItHint::CreateInsertion(InsertLoc, " ") 6977 << FixItHint::CreateInsertionFromRange( 6978 InsertLoc, CharSourceRange::getTokenRange(Before)) 6979 << FixItHint::CreateRemoval(Before); 6980 } 6981 } else if (!Proto->getReturnType()->isDependentType()) { 6982 DB << /*typedef*/1 << Proto->getReturnType(); 6983 } else if (getLangOpts().CPlusPlus11) { 6984 DB << /*alias template*/2 << Proto->getReturnType(); 6985 } else { 6986 DB << /*might not be fixable*/3; 6987 } 6988 6989 // Recover by incorporating the other type chunks into the result type. 6990 // Note, this does *not* change the name of the function. This is compatible 6991 // with the GCC extension: 6992 // struct S { &operator int(); } s; 6993 // int &r = s.operator int(); // ok in GCC 6994 // S::operator int&() {} // error in GCC, function name is 'operator int'. 6995 ConvType = Proto->getReturnType(); 6996 } 6997 6998 // C++ [class.conv.fct]p4: 6999 // The conversion-type-id shall not represent a function type nor 7000 // an array type. 7001 if (ConvType->isArrayType()) { 7002 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7003 ConvType = Context.getPointerType(ConvType); 7004 D.setInvalidType(); 7005 } else if (ConvType->isFunctionType()) { 7006 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7007 ConvType = Context.getPointerType(ConvType); 7008 D.setInvalidType(); 7009 } 7010 7011 // Rebuild the function type "R" without any parameters (in case any 7012 // of the errors above fired) and with the conversion type as the 7013 // return type. 7014 if (D.isInvalidType()) 7015 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7016 7017 // C++0x explicit conversion operators. 7018 if (D.getDeclSpec().isExplicitSpecified()) 7019 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7020 getLangOpts().CPlusPlus11 ? 7021 diag::warn_cxx98_compat_explicit_conversion_functions : 7022 diag::ext_explicit_conversion_functions) 7023 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 7024 } 7025 7026 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 7027 /// the declaration of the given C++ conversion function. This routine 7028 /// is responsible for recording the conversion function in the C++ 7029 /// class, if possible. 7030 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 7031 assert(Conversion && "Expected to receive a conversion function declaration"); 7032 7033 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 7034 7035 // Make sure we aren't redeclaring the conversion function. 7036 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 7037 7038 // C++ [class.conv.fct]p1: 7039 // [...] A conversion function is never used to convert a 7040 // (possibly cv-qualified) object to the (possibly cv-qualified) 7041 // same object type (or a reference to it), to a (possibly 7042 // cv-qualified) base class of that type (or a reference to it), 7043 // or to (possibly cv-qualified) void. 7044 // FIXME: Suppress this warning if the conversion function ends up being a 7045 // virtual function that overrides a virtual function in a base class. 7046 QualType ClassType 7047 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7048 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 7049 ConvType = ConvTypeRef->getPointeeType(); 7050 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 7051 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 7052 /* Suppress diagnostics for instantiations. */; 7053 else if (ConvType->isRecordType()) { 7054 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 7055 if (ConvType == ClassType) 7056 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 7057 << ClassType; 7058 else if (IsDerivedFrom(ClassType, ConvType)) 7059 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 7060 << ClassType << ConvType; 7061 } else if (ConvType->isVoidType()) { 7062 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 7063 << ClassType << ConvType; 7064 } 7065 7066 if (FunctionTemplateDecl *ConversionTemplate 7067 = Conversion->getDescribedFunctionTemplate()) 7068 return ConversionTemplate; 7069 7070 return Conversion; 7071 } 7072 7073 //===----------------------------------------------------------------------===// 7074 // Namespace Handling 7075 //===----------------------------------------------------------------------===// 7076 7077 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 7078 /// reopened. 7079 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 7080 SourceLocation Loc, 7081 IdentifierInfo *II, bool *IsInline, 7082 NamespaceDecl *PrevNS) { 7083 assert(*IsInline != PrevNS->isInline()); 7084 7085 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 7086 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 7087 // inline namespaces, with the intention of bringing names into namespace std. 7088 // 7089 // We support this just well enough to get that case working; this is not 7090 // sufficient to support reopening namespaces as inline in general. 7091 if (*IsInline && II && II->getName().startswith("__atomic") && 7092 S.getSourceManager().isInSystemHeader(Loc)) { 7093 // Mark all prior declarations of the namespace as inline. 7094 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 7095 NS = NS->getPreviousDecl()) 7096 NS->setInline(*IsInline); 7097 // Patch up the lookup table for the containing namespace. This isn't really 7098 // correct, but it's good enough for this particular case. 7099 for (auto *I : PrevNS->decls()) 7100 if (auto *ND = dyn_cast<NamedDecl>(I)) 7101 PrevNS->getParent()->makeDeclVisibleInContext(ND); 7102 return; 7103 } 7104 7105 if (PrevNS->isInline()) 7106 // The user probably just forgot the 'inline', so suggest that it 7107 // be added back. 7108 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 7109 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 7110 else 7111 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 7112 7113 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 7114 *IsInline = PrevNS->isInline(); 7115 } 7116 7117 /// ActOnStartNamespaceDef - This is called at the start of a namespace 7118 /// definition. 7119 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 7120 SourceLocation InlineLoc, 7121 SourceLocation NamespaceLoc, 7122 SourceLocation IdentLoc, 7123 IdentifierInfo *II, 7124 SourceLocation LBrace, 7125 AttributeList *AttrList) { 7126 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 7127 // For anonymous namespace, take the location of the left brace. 7128 SourceLocation Loc = II ? IdentLoc : LBrace; 7129 bool IsInline = InlineLoc.isValid(); 7130 bool IsInvalid = false; 7131 bool IsStd = false; 7132 bool AddToKnown = false; 7133 Scope *DeclRegionScope = NamespcScope->getParent(); 7134 7135 NamespaceDecl *PrevNS = nullptr; 7136 if (II) { 7137 // C++ [namespace.def]p2: 7138 // The identifier in an original-namespace-definition shall not 7139 // have been previously defined in the declarative region in 7140 // which the original-namespace-definition appears. The 7141 // identifier in an original-namespace-definition is the name of 7142 // the namespace. Subsequently in that declarative region, it is 7143 // treated as an original-namespace-name. 7144 // 7145 // Since namespace names are unique in their scope, and we don't 7146 // look through using directives, just look for any ordinary names. 7147 7148 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 7149 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 7150 Decl::IDNS_Namespace; 7151 NamedDecl *PrevDecl = nullptr; 7152 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 7153 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 7154 ++I) { 7155 if ((*I)->getIdentifierNamespace() & IDNS) { 7156 PrevDecl = *I; 7157 break; 7158 } 7159 } 7160 7161 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7162 7163 if (PrevNS) { 7164 // This is an extended namespace definition. 7165 if (IsInline != PrevNS->isInline()) 7166 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7167 &IsInline, PrevNS); 7168 } else if (PrevDecl) { 7169 // This is an invalid name redefinition. 7170 Diag(Loc, diag::err_redefinition_different_kind) 7171 << II; 7172 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7173 IsInvalid = true; 7174 // Continue on to push Namespc as current DeclContext and return it. 7175 } else if (II->isStr("std") && 7176 CurContext->getRedeclContext()->isTranslationUnit()) { 7177 // This is the first "real" definition of the namespace "std", so update 7178 // our cache of the "std" namespace to point at this definition. 7179 PrevNS = getStdNamespace(); 7180 IsStd = true; 7181 AddToKnown = !IsInline; 7182 } else { 7183 // We've seen this namespace for the first time. 7184 AddToKnown = !IsInline; 7185 } 7186 } else { 7187 // Anonymous namespaces. 7188 7189 // Determine whether the parent already has an anonymous namespace. 7190 DeclContext *Parent = CurContext->getRedeclContext(); 7191 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7192 PrevNS = TU->getAnonymousNamespace(); 7193 } else { 7194 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7195 PrevNS = ND->getAnonymousNamespace(); 7196 } 7197 7198 if (PrevNS && IsInline != PrevNS->isInline()) 7199 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7200 &IsInline, PrevNS); 7201 } 7202 7203 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7204 StartLoc, Loc, II, PrevNS); 7205 if (IsInvalid) 7206 Namespc->setInvalidDecl(); 7207 7208 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7209 7210 // FIXME: Should we be merging attributes? 7211 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7212 PushNamespaceVisibilityAttr(Attr, Loc); 7213 7214 if (IsStd) 7215 StdNamespace = Namespc; 7216 if (AddToKnown) 7217 KnownNamespaces[Namespc] = false; 7218 7219 if (II) { 7220 PushOnScopeChains(Namespc, DeclRegionScope); 7221 } else { 7222 // Link the anonymous namespace into its parent. 7223 DeclContext *Parent = CurContext->getRedeclContext(); 7224 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7225 TU->setAnonymousNamespace(Namespc); 7226 } else { 7227 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7228 } 7229 7230 CurContext->addDecl(Namespc); 7231 7232 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7233 // behaves as if it were replaced by 7234 // namespace unique { /* empty body */ } 7235 // using namespace unique; 7236 // namespace unique { namespace-body } 7237 // where all occurrences of 'unique' in a translation unit are 7238 // replaced by the same identifier and this identifier differs 7239 // from all other identifiers in the entire program. 7240 7241 // We just create the namespace with an empty name and then add an 7242 // implicit using declaration, just like the standard suggests. 7243 // 7244 // CodeGen enforces the "universally unique" aspect by giving all 7245 // declarations semantically contained within an anonymous 7246 // namespace internal linkage. 7247 7248 if (!PrevNS) { 7249 UsingDirectiveDecl* UD 7250 = UsingDirectiveDecl::Create(Context, Parent, 7251 /* 'using' */ LBrace, 7252 /* 'namespace' */ SourceLocation(), 7253 /* qualifier */ NestedNameSpecifierLoc(), 7254 /* identifier */ SourceLocation(), 7255 Namespc, 7256 /* Ancestor */ Parent); 7257 UD->setImplicit(); 7258 Parent->addDecl(UD); 7259 } 7260 } 7261 7262 ActOnDocumentableDecl(Namespc); 7263 7264 // Although we could have an invalid decl (i.e. the namespace name is a 7265 // redefinition), push it as current DeclContext and try to continue parsing. 7266 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7267 // for the namespace has the declarations that showed up in that particular 7268 // namespace definition. 7269 PushDeclContext(NamespcScope, Namespc); 7270 return Namespc; 7271 } 7272 7273 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7274 /// is a namespace alias, returns the namespace it points to. 7275 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7276 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7277 return AD->getNamespace(); 7278 return dyn_cast_or_null<NamespaceDecl>(D); 7279 } 7280 7281 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7282 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7283 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7284 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7285 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7286 Namespc->setRBraceLoc(RBrace); 7287 PopDeclContext(); 7288 if (Namespc->hasAttr<VisibilityAttr>()) 7289 PopPragmaVisibility(true, RBrace); 7290 } 7291 7292 CXXRecordDecl *Sema::getStdBadAlloc() const { 7293 return cast_or_null<CXXRecordDecl>( 7294 StdBadAlloc.get(Context.getExternalSource())); 7295 } 7296 7297 NamespaceDecl *Sema::getStdNamespace() const { 7298 return cast_or_null<NamespaceDecl>( 7299 StdNamespace.get(Context.getExternalSource())); 7300 } 7301 7302 /// \brief Retrieve the special "std" namespace, which may require us to 7303 /// implicitly define the namespace. 7304 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7305 if (!StdNamespace) { 7306 // The "std" namespace has not yet been defined, so build one implicitly. 7307 StdNamespace = NamespaceDecl::Create(Context, 7308 Context.getTranslationUnitDecl(), 7309 /*Inline=*/false, 7310 SourceLocation(), SourceLocation(), 7311 &PP.getIdentifierTable().get("std"), 7312 /*PrevDecl=*/nullptr); 7313 getStdNamespace()->setImplicit(true); 7314 } 7315 7316 return getStdNamespace(); 7317 } 7318 7319 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7320 assert(getLangOpts().CPlusPlus && 7321 "Looking for std::initializer_list outside of C++."); 7322 7323 // We're looking for implicit instantiations of 7324 // template <typename E> class std::initializer_list. 7325 7326 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7327 return false; 7328 7329 ClassTemplateDecl *Template = nullptr; 7330 const TemplateArgument *Arguments = nullptr; 7331 7332 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7333 7334 ClassTemplateSpecializationDecl *Specialization = 7335 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7336 if (!Specialization) 7337 return false; 7338 7339 Template = Specialization->getSpecializedTemplate(); 7340 Arguments = Specialization->getTemplateArgs().data(); 7341 } else if (const TemplateSpecializationType *TST = 7342 Ty->getAs<TemplateSpecializationType>()) { 7343 Template = dyn_cast_or_null<ClassTemplateDecl>( 7344 TST->getTemplateName().getAsTemplateDecl()); 7345 Arguments = TST->getArgs(); 7346 } 7347 if (!Template) 7348 return false; 7349 7350 if (!StdInitializerList) { 7351 // Haven't recognized std::initializer_list yet, maybe this is it. 7352 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7353 if (TemplateClass->getIdentifier() != 7354 &PP.getIdentifierTable().get("initializer_list") || 7355 !getStdNamespace()->InEnclosingNamespaceSetOf( 7356 TemplateClass->getDeclContext())) 7357 return false; 7358 // This is a template called std::initializer_list, but is it the right 7359 // template? 7360 TemplateParameterList *Params = Template->getTemplateParameters(); 7361 if (Params->getMinRequiredArguments() != 1) 7362 return false; 7363 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7364 return false; 7365 7366 // It's the right template. 7367 StdInitializerList = Template; 7368 } 7369 7370 if (Template != StdInitializerList) 7371 return false; 7372 7373 // This is an instance of std::initializer_list. Find the argument type. 7374 if (Element) 7375 *Element = Arguments[0].getAsType(); 7376 return true; 7377 } 7378 7379 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7380 NamespaceDecl *Std = S.getStdNamespace(); 7381 if (!Std) { 7382 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7383 return nullptr; 7384 } 7385 7386 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7387 Loc, Sema::LookupOrdinaryName); 7388 if (!S.LookupQualifiedName(Result, Std)) { 7389 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7390 return nullptr; 7391 } 7392 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7393 if (!Template) { 7394 Result.suppressDiagnostics(); 7395 // We found something weird. Complain about the first thing we found. 7396 NamedDecl *Found = *Result.begin(); 7397 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7398 return nullptr; 7399 } 7400 7401 // We found some template called std::initializer_list. Now verify that it's 7402 // correct. 7403 TemplateParameterList *Params = Template->getTemplateParameters(); 7404 if (Params->getMinRequiredArguments() != 1 || 7405 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7406 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7407 return nullptr; 7408 } 7409 7410 return Template; 7411 } 7412 7413 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7414 if (!StdInitializerList) { 7415 StdInitializerList = LookupStdInitializerList(*this, Loc); 7416 if (!StdInitializerList) 7417 return QualType(); 7418 } 7419 7420 TemplateArgumentListInfo Args(Loc, Loc); 7421 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7422 Context.getTrivialTypeSourceInfo(Element, 7423 Loc))); 7424 return Context.getCanonicalType( 7425 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7426 } 7427 7428 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7429 // C++ [dcl.init.list]p2: 7430 // A constructor is an initializer-list constructor if its first parameter 7431 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7432 // std::initializer_list<E> for some type E, and either there are no other 7433 // parameters or else all other parameters have default arguments. 7434 if (Ctor->getNumParams() < 1 || 7435 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7436 return false; 7437 7438 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7439 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7440 ArgType = RT->getPointeeType().getUnqualifiedType(); 7441 7442 return isStdInitializerList(ArgType, nullptr); 7443 } 7444 7445 /// \brief Determine whether a using statement is in a context where it will be 7446 /// apply in all contexts. 7447 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7448 switch (CurContext->getDeclKind()) { 7449 case Decl::TranslationUnit: 7450 return true; 7451 case Decl::LinkageSpec: 7452 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7453 default: 7454 return false; 7455 } 7456 } 7457 7458 namespace { 7459 7460 // Callback to only accept typo corrections that are namespaces. 7461 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7462 public: 7463 bool ValidateCandidate(const TypoCorrection &candidate) override { 7464 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7465 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7466 return false; 7467 } 7468 }; 7469 7470 } 7471 7472 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7473 CXXScopeSpec &SS, 7474 SourceLocation IdentLoc, 7475 IdentifierInfo *Ident) { 7476 R.clear(); 7477 if (TypoCorrection Corrected = 7478 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7479 llvm::make_unique<NamespaceValidatorCCC>(), 7480 Sema::CTK_ErrorRecovery)) { 7481 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7482 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7483 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7484 Ident->getName().equals(CorrectedStr); 7485 S.diagnoseTypo(Corrected, 7486 S.PDiag(diag::err_using_directive_member_suggest) 7487 << Ident << DC << DroppedSpecifier << SS.getRange(), 7488 S.PDiag(diag::note_namespace_defined_here)); 7489 } else { 7490 S.diagnoseTypo(Corrected, 7491 S.PDiag(diag::err_using_directive_suggest) << Ident, 7492 S.PDiag(diag::note_namespace_defined_here)); 7493 } 7494 R.addDecl(Corrected.getCorrectionDecl()); 7495 return true; 7496 } 7497 return false; 7498 } 7499 7500 Decl *Sema::ActOnUsingDirective(Scope *S, 7501 SourceLocation UsingLoc, 7502 SourceLocation NamespcLoc, 7503 CXXScopeSpec &SS, 7504 SourceLocation IdentLoc, 7505 IdentifierInfo *NamespcName, 7506 AttributeList *AttrList) { 7507 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7508 assert(NamespcName && "Invalid NamespcName."); 7509 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7510 7511 // This can only happen along a recovery path. 7512 while (S->getFlags() & Scope::TemplateParamScope) 7513 S = S->getParent(); 7514 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7515 7516 UsingDirectiveDecl *UDir = nullptr; 7517 NestedNameSpecifier *Qualifier = nullptr; 7518 if (SS.isSet()) 7519 Qualifier = SS.getScopeRep(); 7520 7521 // Lookup namespace name. 7522 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7523 LookupParsedName(R, S, &SS); 7524 if (R.isAmbiguous()) 7525 return nullptr; 7526 7527 if (R.empty()) { 7528 R.clear(); 7529 // Allow "using namespace std;" or "using namespace ::std;" even if 7530 // "std" hasn't been defined yet, for GCC compatibility. 7531 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7532 NamespcName->isStr("std")) { 7533 Diag(IdentLoc, diag::ext_using_undefined_std); 7534 R.addDecl(getOrCreateStdNamespace()); 7535 R.resolveKind(); 7536 } 7537 // Otherwise, attempt typo correction. 7538 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7539 } 7540 7541 if (!R.empty()) { 7542 NamedDecl *Named = R.getFoundDecl(); 7543 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7544 && "expected namespace decl"); 7545 7546 // The use of a nested name specifier may trigger deprecation warnings. 7547 DiagnoseUseOfDecl(Named, IdentLoc); 7548 7549 // C++ [namespace.udir]p1: 7550 // A using-directive specifies that the names in the nominated 7551 // namespace can be used in the scope in which the 7552 // using-directive appears after the using-directive. During 7553 // unqualified name lookup (3.4.1), the names appear as if they 7554 // were declared in the nearest enclosing namespace which 7555 // contains both the using-directive and the nominated 7556 // namespace. [Note: in this context, "contains" means "contains 7557 // directly or indirectly". ] 7558 7559 // Find enclosing context containing both using-directive and 7560 // nominated namespace. 7561 NamespaceDecl *NS = getNamespaceDecl(Named); 7562 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7563 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7564 CommonAncestor = CommonAncestor->getParent(); 7565 7566 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7567 SS.getWithLocInContext(Context), 7568 IdentLoc, Named, CommonAncestor); 7569 7570 if (IsUsingDirectiveInToplevelContext(CurContext) && 7571 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7572 Diag(IdentLoc, diag::warn_using_directive_in_header); 7573 } 7574 7575 PushUsingDirective(S, UDir); 7576 } else { 7577 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7578 } 7579 7580 if (UDir) 7581 ProcessDeclAttributeList(S, UDir, AttrList); 7582 7583 return UDir; 7584 } 7585 7586 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7587 // If the scope has an associated entity and the using directive is at 7588 // namespace or translation unit scope, add the UsingDirectiveDecl into 7589 // its lookup structure so qualified name lookup can find it. 7590 DeclContext *Ctx = S->getEntity(); 7591 if (Ctx && !Ctx->isFunctionOrMethod()) 7592 Ctx->addDecl(UDir); 7593 else 7594 // Otherwise, it is at block scope. The using-directives will affect lookup 7595 // only to the end of the scope. 7596 S->PushUsingDirective(UDir); 7597 } 7598 7599 7600 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7601 AccessSpecifier AS, 7602 bool HasUsingKeyword, 7603 SourceLocation UsingLoc, 7604 CXXScopeSpec &SS, 7605 UnqualifiedId &Name, 7606 AttributeList *AttrList, 7607 bool HasTypenameKeyword, 7608 SourceLocation TypenameLoc) { 7609 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7610 7611 switch (Name.getKind()) { 7612 case UnqualifiedId::IK_ImplicitSelfParam: 7613 case UnqualifiedId::IK_Identifier: 7614 case UnqualifiedId::IK_OperatorFunctionId: 7615 case UnqualifiedId::IK_LiteralOperatorId: 7616 case UnqualifiedId::IK_ConversionFunctionId: 7617 break; 7618 7619 case UnqualifiedId::IK_ConstructorName: 7620 case UnqualifiedId::IK_ConstructorTemplateId: 7621 // C++11 inheriting constructors. 7622 Diag(Name.getLocStart(), 7623 getLangOpts().CPlusPlus11 ? 7624 diag::warn_cxx98_compat_using_decl_constructor : 7625 diag::err_using_decl_constructor) 7626 << SS.getRange(); 7627 7628 if (getLangOpts().CPlusPlus11) break; 7629 7630 return nullptr; 7631 7632 case UnqualifiedId::IK_DestructorName: 7633 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7634 << SS.getRange(); 7635 return nullptr; 7636 7637 case UnqualifiedId::IK_TemplateId: 7638 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7639 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7640 return nullptr; 7641 } 7642 7643 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7644 DeclarationName TargetName = TargetNameInfo.getName(); 7645 if (!TargetName) 7646 return nullptr; 7647 7648 // Warn about access declarations. 7649 if (!HasUsingKeyword) { 7650 Diag(Name.getLocStart(), 7651 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7652 : diag::warn_access_decl_deprecated) 7653 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7654 } 7655 7656 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7657 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7658 return nullptr; 7659 7660 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7661 TargetNameInfo, AttrList, 7662 /* IsInstantiation */ false, 7663 HasTypenameKeyword, TypenameLoc); 7664 if (UD) 7665 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7666 7667 return UD; 7668 } 7669 7670 /// \brief Determine whether a using declaration considers the given 7671 /// declarations as "equivalent", e.g., if they are redeclarations of 7672 /// the same entity or are both typedefs of the same type. 7673 static bool 7674 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7675 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7676 return true; 7677 7678 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7679 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7680 return Context.hasSameType(TD1->getUnderlyingType(), 7681 TD2->getUnderlyingType()); 7682 7683 return false; 7684 } 7685 7686 7687 /// Determines whether to create a using shadow decl for a particular 7688 /// decl, given the set of decls existing prior to this using lookup. 7689 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7690 const LookupResult &Previous, 7691 UsingShadowDecl *&PrevShadow) { 7692 // Diagnose finding a decl which is not from a base class of the 7693 // current class. We do this now because there are cases where this 7694 // function will silently decide not to build a shadow decl, which 7695 // will pre-empt further diagnostics. 7696 // 7697 // We don't need to do this in C++0x because we do the check once on 7698 // the qualifier. 7699 // 7700 // FIXME: diagnose the following if we care enough: 7701 // struct A { int foo; }; 7702 // struct B : A { using A::foo; }; 7703 // template <class T> struct C : A {}; 7704 // template <class T> struct D : C<T> { using B::foo; } // <--- 7705 // This is invalid (during instantiation) in C++03 because B::foo 7706 // resolves to the using decl in B, which is not a base class of D<T>. 7707 // We can't diagnose it immediately because C<T> is an unknown 7708 // specialization. The UsingShadowDecl in D<T> then points directly 7709 // to A::foo, which will look well-formed when we instantiate. 7710 // The right solution is to not collapse the shadow-decl chain. 7711 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7712 DeclContext *OrigDC = Orig->getDeclContext(); 7713 7714 // Handle enums and anonymous structs. 7715 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7716 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7717 while (OrigRec->isAnonymousStructOrUnion()) 7718 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7719 7720 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7721 if (OrigDC == CurContext) { 7722 Diag(Using->getLocation(), 7723 diag::err_using_decl_nested_name_specifier_is_current_class) 7724 << Using->getQualifierLoc().getSourceRange(); 7725 Diag(Orig->getLocation(), diag::note_using_decl_target); 7726 return true; 7727 } 7728 7729 Diag(Using->getQualifierLoc().getBeginLoc(), 7730 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7731 << Using->getQualifier() 7732 << cast<CXXRecordDecl>(CurContext) 7733 << Using->getQualifierLoc().getSourceRange(); 7734 Diag(Orig->getLocation(), diag::note_using_decl_target); 7735 return true; 7736 } 7737 } 7738 7739 if (Previous.empty()) return false; 7740 7741 NamedDecl *Target = Orig; 7742 if (isa<UsingShadowDecl>(Target)) 7743 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7744 7745 // If the target happens to be one of the previous declarations, we 7746 // don't have a conflict. 7747 // 7748 // FIXME: but we might be increasing its access, in which case we 7749 // should redeclare it. 7750 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7751 bool FoundEquivalentDecl = false; 7752 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7753 I != E; ++I) { 7754 NamedDecl *D = (*I)->getUnderlyingDecl(); 7755 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7756 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7757 PrevShadow = Shadow; 7758 FoundEquivalentDecl = true; 7759 } 7760 7761 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7762 } 7763 7764 if (FoundEquivalentDecl) 7765 return false; 7766 7767 if (FunctionDecl *FD = Target->getAsFunction()) { 7768 NamedDecl *OldDecl = nullptr; 7769 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7770 /*IsForUsingDecl*/ true)) { 7771 case Ovl_Overload: 7772 return false; 7773 7774 case Ovl_NonFunction: 7775 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7776 break; 7777 7778 // We found a decl with the exact signature. 7779 case Ovl_Match: 7780 // If we're in a record, we want to hide the target, so we 7781 // return true (without a diagnostic) to tell the caller not to 7782 // build a shadow decl. 7783 if (CurContext->isRecord()) 7784 return true; 7785 7786 // If we're not in a record, this is an error. 7787 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7788 break; 7789 } 7790 7791 Diag(Target->getLocation(), diag::note_using_decl_target); 7792 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7793 return true; 7794 } 7795 7796 // Target is not a function. 7797 7798 if (isa<TagDecl>(Target)) { 7799 // No conflict between a tag and a non-tag. 7800 if (!Tag) return false; 7801 7802 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7803 Diag(Target->getLocation(), diag::note_using_decl_target); 7804 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7805 return true; 7806 } 7807 7808 // No conflict between a tag and a non-tag. 7809 if (!NonTag) return false; 7810 7811 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7812 Diag(Target->getLocation(), diag::note_using_decl_target); 7813 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7814 return true; 7815 } 7816 7817 /// Builds a shadow declaration corresponding to a 'using' declaration. 7818 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7819 UsingDecl *UD, 7820 NamedDecl *Orig, 7821 UsingShadowDecl *PrevDecl) { 7822 7823 // If we resolved to another shadow declaration, just coalesce them. 7824 NamedDecl *Target = Orig; 7825 if (isa<UsingShadowDecl>(Target)) { 7826 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7827 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7828 } 7829 7830 UsingShadowDecl *Shadow 7831 = UsingShadowDecl::Create(Context, CurContext, 7832 UD->getLocation(), UD, Target); 7833 UD->addShadowDecl(Shadow); 7834 7835 Shadow->setAccess(UD->getAccess()); 7836 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7837 Shadow->setInvalidDecl(); 7838 7839 Shadow->setPreviousDecl(PrevDecl); 7840 7841 if (S) 7842 PushOnScopeChains(Shadow, S); 7843 else 7844 CurContext->addDecl(Shadow); 7845 7846 7847 return Shadow; 7848 } 7849 7850 /// Hides a using shadow declaration. This is required by the current 7851 /// using-decl implementation when a resolvable using declaration in a 7852 /// class is followed by a declaration which would hide or override 7853 /// one or more of the using decl's targets; for example: 7854 /// 7855 /// struct Base { void foo(int); }; 7856 /// struct Derived : Base { 7857 /// using Base::foo; 7858 /// void foo(int); 7859 /// }; 7860 /// 7861 /// The governing language is C++03 [namespace.udecl]p12: 7862 /// 7863 /// When a using-declaration brings names from a base class into a 7864 /// derived class scope, member functions in the derived class 7865 /// override and/or hide member functions with the same name and 7866 /// parameter types in a base class (rather than conflicting). 7867 /// 7868 /// There are two ways to implement this: 7869 /// (1) optimistically create shadow decls when they're not hidden 7870 /// by existing declarations, or 7871 /// (2) don't create any shadow decls (or at least don't make them 7872 /// visible) until we've fully parsed/instantiated the class. 7873 /// The problem with (1) is that we might have to retroactively remove 7874 /// a shadow decl, which requires several O(n) operations because the 7875 /// decl structures are (very reasonably) not designed for removal. 7876 /// (2) avoids this but is very fiddly and phase-dependent. 7877 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7878 if (Shadow->getDeclName().getNameKind() == 7879 DeclarationName::CXXConversionFunctionName) 7880 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7881 7882 // Remove it from the DeclContext... 7883 Shadow->getDeclContext()->removeDecl(Shadow); 7884 7885 // ...and the scope, if applicable... 7886 if (S) { 7887 S->RemoveDecl(Shadow); 7888 IdResolver.RemoveDecl(Shadow); 7889 } 7890 7891 // ...and the using decl. 7892 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7893 7894 // TODO: complain somehow if Shadow was used. It shouldn't 7895 // be possible for this to happen, because...? 7896 } 7897 7898 /// Find the base specifier for a base class with the given type. 7899 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7900 QualType DesiredBase, 7901 bool &AnyDependentBases) { 7902 // Check whether the named type is a direct base class. 7903 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7904 for (auto &Base : Derived->bases()) { 7905 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7906 if (CanonicalDesiredBase == BaseType) 7907 return &Base; 7908 if (BaseType->isDependentType()) 7909 AnyDependentBases = true; 7910 } 7911 return nullptr; 7912 } 7913 7914 namespace { 7915 class UsingValidatorCCC : public CorrectionCandidateCallback { 7916 public: 7917 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7918 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7919 : HasTypenameKeyword(HasTypenameKeyword), 7920 IsInstantiation(IsInstantiation), OldNNS(NNS), 7921 RequireMemberOf(RequireMemberOf) {} 7922 7923 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7924 NamedDecl *ND = Candidate.getCorrectionDecl(); 7925 7926 // Keywords are not valid here. 7927 if (!ND || isa<NamespaceDecl>(ND)) 7928 return false; 7929 7930 // Completely unqualified names are invalid for a 'using' declaration. 7931 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7932 return false; 7933 7934 if (RequireMemberOf) { 7935 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7936 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7937 // No-one ever wants a using-declaration to name an injected-class-name 7938 // of a base class, unless they're declaring an inheriting constructor. 7939 ASTContext &Ctx = ND->getASTContext(); 7940 if (!Ctx.getLangOpts().CPlusPlus11) 7941 return false; 7942 QualType FoundType = Ctx.getRecordType(FoundRecord); 7943 7944 // Check that the injected-class-name is named as a member of its own 7945 // type; we don't want to suggest 'using Derived::Base;', since that 7946 // means something else. 7947 NestedNameSpecifier *Specifier = 7948 Candidate.WillReplaceSpecifier() 7949 ? Candidate.getCorrectionSpecifier() 7950 : OldNNS; 7951 if (!Specifier->getAsType() || 7952 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7953 return false; 7954 7955 // Check that this inheriting constructor declaration actually names a 7956 // direct base class of the current class. 7957 bool AnyDependentBases = false; 7958 if (!findDirectBaseWithType(RequireMemberOf, 7959 Ctx.getRecordType(FoundRecord), 7960 AnyDependentBases) && 7961 !AnyDependentBases) 7962 return false; 7963 } else { 7964 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7965 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7966 return false; 7967 7968 // FIXME: Check that the base class member is accessible? 7969 } 7970 } 7971 7972 if (isa<TypeDecl>(ND)) 7973 return HasTypenameKeyword || !IsInstantiation; 7974 7975 return !HasTypenameKeyword; 7976 } 7977 7978 private: 7979 bool HasTypenameKeyword; 7980 bool IsInstantiation; 7981 NestedNameSpecifier *OldNNS; 7982 CXXRecordDecl *RequireMemberOf; 7983 }; 7984 } // end anonymous namespace 7985 7986 /// Builds a using declaration. 7987 /// 7988 /// \param IsInstantiation - Whether this call arises from an 7989 /// instantiation of an unresolved using declaration. We treat 7990 /// the lookup differently for these declarations. 7991 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7992 SourceLocation UsingLoc, 7993 CXXScopeSpec &SS, 7994 DeclarationNameInfo NameInfo, 7995 AttributeList *AttrList, 7996 bool IsInstantiation, 7997 bool HasTypenameKeyword, 7998 SourceLocation TypenameLoc) { 7999 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8000 SourceLocation IdentLoc = NameInfo.getLoc(); 8001 assert(IdentLoc.isValid() && "Invalid TargetName location."); 8002 8003 // FIXME: We ignore attributes for now. 8004 8005 if (SS.isEmpty()) { 8006 Diag(IdentLoc, diag::err_using_requires_qualname); 8007 return nullptr; 8008 } 8009 8010 // Do the redeclaration lookup in the current scope. 8011 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 8012 ForRedeclaration); 8013 Previous.setHideTags(false); 8014 if (S) { 8015 LookupName(Previous, S); 8016 8017 // It is really dumb that we have to do this. 8018 LookupResult::Filter F = Previous.makeFilter(); 8019 while (F.hasNext()) { 8020 NamedDecl *D = F.next(); 8021 if (!isDeclInScope(D, CurContext, S)) 8022 F.erase(); 8023 // If we found a local extern declaration that's not ordinarily visible, 8024 // and this declaration is being added to a non-block scope, ignore it. 8025 // We're only checking for scope conflicts here, not also for violations 8026 // of the linkage rules. 8027 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 8028 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 8029 F.erase(); 8030 } 8031 F.done(); 8032 } else { 8033 assert(IsInstantiation && "no scope in non-instantiation"); 8034 assert(CurContext->isRecord() && "scope not record in instantiation"); 8035 LookupQualifiedName(Previous, CurContext); 8036 } 8037 8038 // Check for invalid redeclarations. 8039 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 8040 SS, IdentLoc, Previous)) 8041 return nullptr; 8042 8043 // Check for bad qualifiers. 8044 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 8045 return nullptr; 8046 8047 DeclContext *LookupContext = computeDeclContext(SS); 8048 NamedDecl *D; 8049 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 8050 if (!LookupContext) { 8051 if (HasTypenameKeyword) { 8052 // FIXME: not all declaration name kinds are legal here 8053 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 8054 UsingLoc, TypenameLoc, 8055 QualifierLoc, 8056 IdentLoc, NameInfo.getName()); 8057 } else { 8058 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 8059 QualifierLoc, NameInfo); 8060 } 8061 D->setAccess(AS); 8062 CurContext->addDecl(D); 8063 return D; 8064 } 8065 8066 auto Build = [&](bool Invalid) { 8067 UsingDecl *UD = 8068 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 8069 HasTypenameKeyword); 8070 UD->setAccess(AS); 8071 CurContext->addDecl(UD); 8072 UD->setInvalidDecl(Invalid); 8073 return UD; 8074 }; 8075 auto BuildInvalid = [&]{ return Build(true); }; 8076 auto BuildValid = [&]{ return Build(false); }; 8077 8078 if (RequireCompleteDeclContext(SS, LookupContext)) 8079 return BuildInvalid(); 8080 8081 // The normal rules do not apply to inheriting constructor declarations. 8082 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 8083 UsingDecl *UD = BuildValid(); 8084 CheckInheritingConstructorUsingDecl(UD); 8085 return UD; 8086 } 8087 8088 // Otherwise, look up the target name. 8089 8090 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8091 8092 // Unlike most lookups, we don't always want to hide tag 8093 // declarations: tag names are visible through the using declaration 8094 // even if hidden by ordinary names, *except* in a dependent context 8095 // where it's important for the sanity of two-phase lookup. 8096 if (!IsInstantiation) 8097 R.setHideTags(false); 8098 8099 // For the purposes of this lookup, we have a base object type 8100 // equal to that of the current context. 8101 if (CurContext->isRecord()) { 8102 R.setBaseObjectType( 8103 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 8104 } 8105 8106 LookupQualifiedName(R, LookupContext); 8107 8108 // Try to correct typos if possible. 8109 if (R.empty()) { 8110 if (TypoCorrection Corrected = CorrectTypo( 8111 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 8112 llvm::make_unique<UsingValidatorCCC>( 8113 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8114 dyn_cast<CXXRecordDecl>(CurContext)), 8115 CTK_ErrorRecovery)) { 8116 // We reject any correction for which ND would be NULL. 8117 NamedDecl *ND = Corrected.getCorrectionDecl(); 8118 8119 // We reject candidates where DroppedSpecifier == true, hence the 8120 // literal '0' below. 8121 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8122 << NameInfo.getName() << LookupContext << 0 8123 << SS.getRange()); 8124 8125 // If we corrected to an inheriting constructor, handle it as one. 8126 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8127 if (RD && RD->isInjectedClassName()) { 8128 // Fix up the information we'll use to build the using declaration. 8129 if (Corrected.WillReplaceSpecifier()) { 8130 NestedNameSpecifierLocBuilder Builder; 8131 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8132 QualifierLoc.getSourceRange()); 8133 QualifierLoc = Builder.getWithLocInContext(Context); 8134 } 8135 8136 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8137 Context.getCanonicalType(Context.getRecordType(RD)))); 8138 NameInfo.setNamedTypeInfo(nullptr); 8139 8140 // Build it and process it as an inheriting constructor. 8141 UsingDecl *UD = BuildValid(); 8142 CheckInheritingConstructorUsingDecl(UD); 8143 return UD; 8144 } 8145 8146 // FIXME: Pick up all the declarations if we found an overloaded function. 8147 R.setLookupName(Corrected.getCorrection()); 8148 R.addDecl(ND); 8149 } else { 8150 Diag(IdentLoc, diag::err_no_member) 8151 << NameInfo.getName() << LookupContext << SS.getRange(); 8152 return BuildInvalid(); 8153 } 8154 } 8155 8156 if (R.isAmbiguous()) 8157 return BuildInvalid(); 8158 8159 if (HasTypenameKeyword) { 8160 // If we asked for a typename and got a non-type decl, error out. 8161 if (!R.getAsSingle<TypeDecl>()) { 8162 Diag(IdentLoc, diag::err_using_typename_non_type); 8163 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8164 Diag((*I)->getUnderlyingDecl()->getLocation(), 8165 diag::note_using_decl_target); 8166 return BuildInvalid(); 8167 } 8168 } else { 8169 // If we asked for a non-typename and we got a type, error out, 8170 // but only if this is an instantiation of an unresolved using 8171 // decl. Otherwise just silently find the type name. 8172 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8173 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8174 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8175 return BuildInvalid(); 8176 } 8177 } 8178 8179 // C++0x N2914 [namespace.udecl]p6: 8180 // A using-declaration shall not name a namespace. 8181 if (R.getAsSingle<NamespaceDecl>()) { 8182 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8183 << SS.getRange(); 8184 return BuildInvalid(); 8185 } 8186 8187 UsingDecl *UD = BuildValid(); 8188 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8189 UsingShadowDecl *PrevDecl = nullptr; 8190 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8191 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8192 } 8193 8194 return UD; 8195 } 8196 8197 /// Additional checks for a using declaration referring to a constructor name. 8198 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8199 assert(!UD->hasTypename() && "expecting a constructor name"); 8200 8201 const Type *SourceType = UD->getQualifier()->getAsType(); 8202 assert(SourceType && 8203 "Using decl naming constructor doesn't have type in scope spec."); 8204 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8205 8206 // Check whether the named type is a direct base class. 8207 bool AnyDependentBases = false; 8208 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8209 AnyDependentBases); 8210 if (!Base && !AnyDependentBases) { 8211 Diag(UD->getUsingLoc(), 8212 diag::err_using_decl_constructor_not_in_direct_base) 8213 << UD->getNameInfo().getSourceRange() 8214 << QualType(SourceType, 0) << TargetClass; 8215 UD->setInvalidDecl(); 8216 return true; 8217 } 8218 8219 if (Base) 8220 Base->setInheritConstructors(); 8221 8222 return false; 8223 } 8224 8225 /// Checks that the given using declaration is not an invalid 8226 /// redeclaration. Note that this is checking only for the using decl 8227 /// itself, not for any ill-formedness among the UsingShadowDecls. 8228 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8229 bool HasTypenameKeyword, 8230 const CXXScopeSpec &SS, 8231 SourceLocation NameLoc, 8232 const LookupResult &Prev) { 8233 // C++03 [namespace.udecl]p8: 8234 // C++0x [namespace.udecl]p10: 8235 // A using-declaration is a declaration and can therefore be used 8236 // repeatedly where (and only where) multiple declarations are 8237 // allowed. 8238 // 8239 // That's in non-member contexts. 8240 if (!CurContext->getRedeclContext()->isRecord()) 8241 return false; 8242 8243 NestedNameSpecifier *Qual = SS.getScopeRep(); 8244 8245 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8246 NamedDecl *D = *I; 8247 8248 bool DTypename; 8249 NestedNameSpecifier *DQual; 8250 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8251 DTypename = UD->hasTypename(); 8252 DQual = UD->getQualifier(); 8253 } else if (UnresolvedUsingValueDecl *UD 8254 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8255 DTypename = false; 8256 DQual = UD->getQualifier(); 8257 } else if (UnresolvedUsingTypenameDecl *UD 8258 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8259 DTypename = true; 8260 DQual = UD->getQualifier(); 8261 } else continue; 8262 8263 // using decls differ if one says 'typename' and the other doesn't. 8264 // FIXME: non-dependent using decls? 8265 if (HasTypenameKeyword != DTypename) continue; 8266 8267 // using decls differ if they name different scopes (but note that 8268 // template instantiation can cause this check to trigger when it 8269 // didn't before instantiation). 8270 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8271 Context.getCanonicalNestedNameSpecifier(DQual)) 8272 continue; 8273 8274 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8275 Diag(D->getLocation(), diag::note_using_decl) << 1; 8276 return true; 8277 } 8278 8279 return false; 8280 } 8281 8282 8283 /// Checks that the given nested-name qualifier used in a using decl 8284 /// in the current context is appropriately related to the current 8285 /// scope. If an error is found, diagnoses it and returns true. 8286 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8287 const CXXScopeSpec &SS, 8288 const DeclarationNameInfo &NameInfo, 8289 SourceLocation NameLoc) { 8290 DeclContext *NamedContext = computeDeclContext(SS); 8291 8292 if (!CurContext->isRecord()) { 8293 // C++03 [namespace.udecl]p3: 8294 // C++0x [namespace.udecl]p8: 8295 // A using-declaration for a class member shall be a member-declaration. 8296 8297 // If we weren't able to compute a valid scope, it must be a 8298 // dependent class scope. 8299 if (!NamedContext || NamedContext->isRecord()) { 8300 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext); 8301 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8302 RD = nullptr; 8303 8304 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8305 << SS.getRange(); 8306 8307 // If we have a complete, non-dependent source type, try to suggest a 8308 // way to get the same effect. 8309 if (!RD) 8310 return true; 8311 8312 // Find what this using-declaration was referring to. 8313 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8314 R.setHideTags(false); 8315 R.suppressDiagnostics(); 8316 LookupQualifiedName(R, RD); 8317 8318 if (R.getAsSingle<TypeDecl>()) { 8319 if (getLangOpts().CPlusPlus11) { 8320 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8321 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8322 << 0 // alias declaration 8323 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8324 NameInfo.getName().getAsString() + 8325 " = "); 8326 } else { 8327 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8328 SourceLocation InsertLoc = 8329 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8330 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8331 << 1 // typedef declaration 8332 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8333 << FixItHint::CreateInsertion( 8334 InsertLoc, " " + NameInfo.getName().getAsString()); 8335 } 8336 } else if (R.getAsSingle<VarDecl>()) { 8337 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8338 // repeating the type of the static data member here. 8339 FixItHint FixIt; 8340 if (getLangOpts().CPlusPlus11) { 8341 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8342 FixIt = FixItHint::CreateReplacement( 8343 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8344 } 8345 8346 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8347 << 2 // reference declaration 8348 << FixIt; 8349 } 8350 return true; 8351 } 8352 8353 // Otherwise, everything is known to be fine. 8354 return false; 8355 } 8356 8357 // The current scope is a record. 8358 8359 // If the named context is dependent, we can't decide much. 8360 if (!NamedContext) { 8361 // FIXME: in C++0x, we can diagnose if we can prove that the 8362 // nested-name-specifier does not refer to a base class, which is 8363 // still possible in some cases. 8364 8365 // Otherwise we have to conservatively report that things might be 8366 // okay. 8367 return false; 8368 } 8369 8370 if (!NamedContext->isRecord()) { 8371 // Ideally this would point at the last name in the specifier, 8372 // but we don't have that level of source info. 8373 Diag(SS.getRange().getBegin(), 8374 diag::err_using_decl_nested_name_specifier_is_not_class) 8375 << SS.getScopeRep() << SS.getRange(); 8376 return true; 8377 } 8378 8379 if (!NamedContext->isDependentContext() && 8380 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8381 return true; 8382 8383 if (getLangOpts().CPlusPlus11) { 8384 // C++0x [namespace.udecl]p3: 8385 // In a using-declaration used as a member-declaration, the 8386 // nested-name-specifier shall name a base class of the class 8387 // being defined. 8388 8389 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8390 cast<CXXRecordDecl>(NamedContext))) { 8391 if (CurContext == NamedContext) { 8392 Diag(NameLoc, 8393 diag::err_using_decl_nested_name_specifier_is_current_class) 8394 << SS.getRange(); 8395 return true; 8396 } 8397 8398 Diag(SS.getRange().getBegin(), 8399 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8400 << SS.getScopeRep() 8401 << cast<CXXRecordDecl>(CurContext) 8402 << SS.getRange(); 8403 return true; 8404 } 8405 8406 return false; 8407 } 8408 8409 // C++03 [namespace.udecl]p4: 8410 // A using-declaration used as a member-declaration shall refer 8411 // to a member of a base class of the class being defined [etc.]. 8412 8413 // Salient point: SS doesn't have to name a base class as long as 8414 // lookup only finds members from base classes. Therefore we can 8415 // diagnose here only if we can prove that that can't happen, 8416 // i.e. if the class hierarchies provably don't intersect. 8417 8418 // TODO: it would be nice if "definitely valid" results were cached 8419 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8420 // need to be repeated. 8421 8422 struct UserData { 8423 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8424 8425 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8426 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8427 Data->Bases.insert(Base); 8428 return true; 8429 } 8430 8431 bool hasDependentBases(const CXXRecordDecl *Class) { 8432 return !Class->forallBases(collect, this); 8433 } 8434 8435 /// Returns true if the base is dependent or is one of the 8436 /// accumulated base classes. 8437 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8438 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8439 return !Data->Bases.count(Base); 8440 } 8441 8442 bool mightShareBases(const CXXRecordDecl *Class) { 8443 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8444 } 8445 }; 8446 8447 UserData Data; 8448 8449 // Returns false if we find a dependent base. 8450 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8451 return false; 8452 8453 // Returns false if the class has a dependent base or if it or one 8454 // of its bases is present in the base set of the current context. 8455 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8456 return false; 8457 8458 Diag(SS.getRange().getBegin(), 8459 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8460 << SS.getScopeRep() 8461 << cast<CXXRecordDecl>(CurContext) 8462 << SS.getRange(); 8463 8464 return true; 8465 } 8466 8467 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8468 AccessSpecifier AS, 8469 MultiTemplateParamsArg TemplateParamLists, 8470 SourceLocation UsingLoc, 8471 UnqualifiedId &Name, 8472 AttributeList *AttrList, 8473 TypeResult Type) { 8474 // Skip up to the relevant declaration scope. 8475 while (S->getFlags() & Scope::TemplateParamScope) 8476 S = S->getParent(); 8477 assert((S->getFlags() & Scope::DeclScope) && 8478 "got alias-declaration outside of declaration scope"); 8479 8480 if (Type.isInvalid()) 8481 return nullptr; 8482 8483 bool Invalid = false; 8484 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8485 TypeSourceInfo *TInfo = nullptr; 8486 GetTypeFromParser(Type.get(), &TInfo); 8487 8488 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8489 return nullptr; 8490 8491 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8492 UPPC_DeclarationType)) { 8493 Invalid = true; 8494 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8495 TInfo->getTypeLoc().getBeginLoc()); 8496 } 8497 8498 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8499 LookupName(Previous, S); 8500 8501 // Warn about shadowing the name of a template parameter. 8502 if (Previous.isSingleResult() && 8503 Previous.getFoundDecl()->isTemplateParameter()) { 8504 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8505 Previous.clear(); 8506 } 8507 8508 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8509 "name in alias declaration must be an identifier"); 8510 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8511 Name.StartLocation, 8512 Name.Identifier, TInfo); 8513 8514 NewTD->setAccess(AS); 8515 8516 if (Invalid) 8517 NewTD->setInvalidDecl(); 8518 8519 ProcessDeclAttributeList(S, NewTD, AttrList); 8520 8521 CheckTypedefForVariablyModifiedType(S, NewTD); 8522 Invalid |= NewTD->isInvalidDecl(); 8523 8524 bool Redeclaration = false; 8525 8526 NamedDecl *NewND; 8527 if (TemplateParamLists.size()) { 8528 TypeAliasTemplateDecl *OldDecl = nullptr; 8529 TemplateParameterList *OldTemplateParams = nullptr; 8530 8531 if (TemplateParamLists.size() != 1) { 8532 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8533 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8534 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8535 } 8536 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8537 8538 // Only consider previous declarations in the same scope. 8539 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8540 /*ExplicitInstantiationOrSpecialization*/false); 8541 if (!Previous.empty()) { 8542 Redeclaration = true; 8543 8544 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8545 if (!OldDecl && !Invalid) { 8546 Diag(UsingLoc, diag::err_redefinition_different_kind) 8547 << Name.Identifier; 8548 8549 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8550 if (OldD->getLocation().isValid()) 8551 Diag(OldD->getLocation(), diag::note_previous_definition); 8552 8553 Invalid = true; 8554 } 8555 8556 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8557 if (TemplateParameterListsAreEqual(TemplateParams, 8558 OldDecl->getTemplateParameters(), 8559 /*Complain=*/true, 8560 TPL_TemplateMatch)) 8561 OldTemplateParams = OldDecl->getTemplateParameters(); 8562 else 8563 Invalid = true; 8564 8565 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8566 if (!Invalid && 8567 !Context.hasSameType(OldTD->getUnderlyingType(), 8568 NewTD->getUnderlyingType())) { 8569 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8570 // but we can't reasonably accept it. 8571 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8572 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8573 if (OldTD->getLocation().isValid()) 8574 Diag(OldTD->getLocation(), diag::note_previous_definition); 8575 Invalid = true; 8576 } 8577 } 8578 } 8579 8580 // Merge any previous default template arguments into our parameters, 8581 // and check the parameter list. 8582 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8583 TPC_TypeAliasTemplate)) 8584 return nullptr; 8585 8586 TypeAliasTemplateDecl *NewDecl = 8587 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8588 Name.Identifier, TemplateParams, 8589 NewTD); 8590 NewTD->setDescribedAliasTemplate(NewDecl); 8591 8592 NewDecl->setAccess(AS); 8593 8594 if (Invalid) 8595 NewDecl->setInvalidDecl(); 8596 else if (OldDecl) 8597 NewDecl->setPreviousDecl(OldDecl); 8598 8599 NewND = NewDecl; 8600 } else { 8601 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8602 NewND = NewTD; 8603 } 8604 8605 if (!Redeclaration) 8606 PushOnScopeChains(NewND, S); 8607 8608 ActOnDocumentableDecl(NewND); 8609 return NewND; 8610 } 8611 8612 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8613 SourceLocation AliasLoc, 8614 IdentifierInfo *Alias, CXXScopeSpec &SS, 8615 SourceLocation IdentLoc, 8616 IdentifierInfo *Ident) { 8617 8618 // Lookup the namespace name. 8619 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8620 LookupParsedName(R, S, &SS); 8621 8622 if (R.isAmbiguous()) 8623 return nullptr; 8624 8625 if (R.empty()) { 8626 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8627 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8628 return nullptr; 8629 } 8630 } 8631 assert(!R.isAmbiguous() && !R.empty()); 8632 8633 // Check if we have a previous declaration with the same name. 8634 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8635 ForRedeclaration); 8636 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8637 PrevDecl = nullptr; 8638 8639 NamedDecl *ND = R.getFoundDecl(); 8640 8641 if (PrevDecl) { 8642 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8643 // We already have an alias with the same name that points to the same 8644 // namespace; check that it matches. 8645 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8646 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8647 << Alias; 8648 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8649 << AD->getNamespace(); 8650 return nullptr; 8651 } 8652 } else { 8653 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8654 ? diag::err_redefinition 8655 : diag::err_redefinition_different_kind; 8656 Diag(AliasLoc, DiagID) << Alias; 8657 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8658 return nullptr; 8659 } 8660 } 8661 8662 // The use of a nested name specifier may trigger deprecation warnings. 8663 DiagnoseUseOfDecl(ND, IdentLoc); 8664 8665 NamespaceAliasDecl *AliasDecl = 8666 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8667 Alias, SS.getWithLocInContext(Context), 8668 IdentLoc, ND); 8669 if (PrevDecl) 8670 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8671 8672 PushOnScopeChains(AliasDecl, S); 8673 return AliasDecl; 8674 } 8675 8676 Sema::ImplicitExceptionSpecification 8677 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8678 CXXMethodDecl *MD) { 8679 CXXRecordDecl *ClassDecl = MD->getParent(); 8680 8681 // C++ [except.spec]p14: 8682 // An implicitly declared special member function (Clause 12) shall have an 8683 // exception-specification. [...] 8684 ImplicitExceptionSpecification ExceptSpec(*this); 8685 if (ClassDecl->isInvalidDecl()) 8686 return ExceptSpec; 8687 8688 // Direct base-class constructors. 8689 for (const auto &B : ClassDecl->bases()) { 8690 if (B.isVirtual()) // Handled below. 8691 continue; 8692 8693 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8694 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8695 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8696 // If this is a deleted function, add it anyway. This might be conformant 8697 // with the standard. This might not. I'm not sure. It might not matter. 8698 if (Constructor) 8699 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8700 } 8701 } 8702 8703 // Virtual base-class constructors. 8704 for (const auto &B : ClassDecl->vbases()) { 8705 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8706 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8707 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8708 // If this is a deleted function, add it anyway. This might be conformant 8709 // with the standard. This might not. I'm not sure. It might not matter. 8710 if (Constructor) 8711 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8712 } 8713 } 8714 8715 // Field constructors. 8716 for (const auto *F : ClassDecl->fields()) { 8717 if (F->hasInClassInitializer()) { 8718 if (Expr *E = F->getInClassInitializer()) 8719 ExceptSpec.CalledExpr(E); 8720 } else if (const RecordType *RecordTy 8721 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8722 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8723 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8724 // If this is a deleted function, add it anyway. This might be conformant 8725 // with the standard. This might not. I'm not sure. It might not matter. 8726 // In particular, the problem is that this function never gets called. It 8727 // might just be ill-formed because this function attempts to refer to 8728 // a deleted function here. 8729 if (Constructor) 8730 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8731 } 8732 } 8733 8734 return ExceptSpec; 8735 } 8736 8737 Sema::ImplicitExceptionSpecification 8738 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8739 CXXRecordDecl *ClassDecl = CD->getParent(); 8740 8741 // C++ [except.spec]p14: 8742 // An inheriting constructor [...] shall have an exception-specification. [...] 8743 ImplicitExceptionSpecification ExceptSpec(*this); 8744 if (ClassDecl->isInvalidDecl()) 8745 return ExceptSpec; 8746 8747 // Inherited constructor. 8748 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8749 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8750 // FIXME: Copying or moving the parameters could add extra exceptions to the 8751 // set, as could the default arguments for the inherited constructor. This 8752 // will be addressed when we implement the resolution of core issue 1351. 8753 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8754 8755 // Direct base-class constructors. 8756 for (const auto &B : ClassDecl->bases()) { 8757 if (B.isVirtual()) // Handled below. 8758 continue; 8759 8760 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8761 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8762 if (BaseClassDecl == InheritedDecl) 8763 continue; 8764 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8765 if (Constructor) 8766 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8767 } 8768 } 8769 8770 // Virtual base-class constructors. 8771 for (const auto &B : ClassDecl->vbases()) { 8772 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8773 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8774 if (BaseClassDecl == InheritedDecl) 8775 continue; 8776 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8777 if (Constructor) 8778 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8779 } 8780 } 8781 8782 // Field constructors. 8783 for (const auto *F : ClassDecl->fields()) { 8784 if (F->hasInClassInitializer()) { 8785 if (Expr *E = F->getInClassInitializer()) 8786 ExceptSpec.CalledExpr(E); 8787 } else if (const RecordType *RecordTy 8788 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8789 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8790 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8791 if (Constructor) 8792 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8793 } 8794 } 8795 8796 return ExceptSpec; 8797 } 8798 8799 namespace { 8800 /// RAII object to register a special member as being currently declared. 8801 struct DeclaringSpecialMember { 8802 Sema &S; 8803 Sema::SpecialMemberDecl D; 8804 bool WasAlreadyBeingDeclared; 8805 8806 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8807 : S(S), D(RD, CSM) { 8808 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8809 if (WasAlreadyBeingDeclared) 8810 // This almost never happens, but if it does, ensure that our cache 8811 // doesn't contain a stale result. 8812 S.SpecialMemberCache.clear(); 8813 8814 // FIXME: Register a note to be produced if we encounter an error while 8815 // declaring the special member. 8816 } 8817 ~DeclaringSpecialMember() { 8818 if (!WasAlreadyBeingDeclared) 8819 S.SpecialMembersBeingDeclared.erase(D); 8820 } 8821 8822 /// \brief Are we already trying to declare this special member? 8823 bool isAlreadyBeingDeclared() const { 8824 return WasAlreadyBeingDeclared; 8825 } 8826 }; 8827 } 8828 8829 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8830 CXXRecordDecl *ClassDecl) { 8831 // C++ [class.ctor]p5: 8832 // A default constructor for a class X is a constructor of class X 8833 // that can be called without an argument. If there is no 8834 // user-declared constructor for class X, a default constructor is 8835 // implicitly declared. An implicitly-declared default constructor 8836 // is an inline public member of its class. 8837 assert(ClassDecl->needsImplicitDefaultConstructor() && 8838 "Should not build implicit default constructor!"); 8839 8840 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8841 if (DSM.isAlreadyBeingDeclared()) 8842 return nullptr; 8843 8844 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8845 CXXDefaultConstructor, 8846 false); 8847 8848 // Create the actual constructor declaration. 8849 CanQualType ClassType 8850 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8851 SourceLocation ClassLoc = ClassDecl->getLocation(); 8852 DeclarationName Name 8853 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8854 DeclarationNameInfo NameInfo(Name, ClassLoc); 8855 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8856 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8857 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8858 /*isImplicitlyDeclared=*/true, Constexpr); 8859 DefaultCon->setAccess(AS_public); 8860 DefaultCon->setDefaulted(); 8861 8862 if (getLangOpts().CUDA) { 8863 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8864 DefaultCon, 8865 /* ConstRHS */ false, 8866 /* Diagnose */ false); 8867 } 8868 8869 // Build an exception specification pointing back at this constructor. 8870 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8871 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8872 8873 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8874 // constructors is easy to compute. 8875 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8876 8877 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8878 SetDeclDeleted(DefaultCon, ClassLoc); 8879 8880 // Note that we have declared this constructor. 8881 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8882 8883 if (Scope *S = getScopeForContext(ClassDecl)) 8884 PushOnScopeChains(DefaultCon, S, false); 8885 ClassDecl->addDecl(DefaultCon); 8886 8887 return DefaultCon; 8888 } 8889 8890 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8891 CXXConstructorDecl *Constructor) { 8892 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8893 !Constructor->doesThisDeclarationHaveABody() && 8894 !Constructor->isDeleted()) && 8895 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8896 8897 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8898 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8899 8900 SynthesizedFunctionScope Scope(*this, Constructor); 8901 DiagnosticErrorTrap Trap(Diags); 8902 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8903 Trap.hasErrorOccurred()) { 8904 Diag(CurrentLocation, diag::note_member_synthesized_at) 8905 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8906 Constructor->setInvalidDecl(); 8907 return; 8908 } 8909 8910 // The exception specification is needed because we are defining the 8911 // function. 8912 ResolveExceptionSpec(CurrentLocation, 8913 Constructor->getType()->castAs<FunctionProtoType>()); 8914 8915 SourceLocation Loc = Constructor->getLocEnd().isValid() 8916 ? Constructor->getLocEnd() 8917 : Constructor->getLocation(); 8918 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8919 8920 Constructor->markUsed(Context); 8921 MarkVTableUsed(CurrentLocation, ClassDecl); 8922 8923 if (ASTMutationListener *L = getASTMutationListener()) { 8924 L->CompletedImplicitDefinition(Constructor); 8925 } 8926 8927 DiagnoseUninitializedFields(*this, Constructor); 8928 } 8929 8930 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8931 // Perform any delayed checks on exception specifications. 8932 CheckDelayedMemberExceptionSpecs(); 8933 } 8934 8935 namespace { 8936 /// Information on inheriting constructors to declare. 8937 class InheritingConstructorInfo { 8938 public: 8939 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8940 : SemaRef(SemaRef), Derived(Derived) { 8941 // Mark the constructors that we already have in the derived class. 8942 // 8943 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8944 // unless there is a user-declared constructor with the same signature in 8945 // the class where the using-declaration appears. 8946 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8947 } 8948 8949 void inheritAll(CXXRecordDecl *RD) { 8950 visitAll(RD, &InheritingConstructorInfo::inherit); 8951 } 8952 8953 private: 8954 /// Information about an inheriting constructor. 8955 struct InheritingConstructor { 8956 InheritingConstructor() 8957 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8958 8959 /// If \c true, a constructor with this signature is already declared 8960 /// in the derived class. 8961 bool DeclaredInDerived; 8962 8963 /// The constructor which is inherited. 8964 const CXXConstructorDecl *BaseCtor; 8965 8966 /// The derived constructor we declared. 8967 CXXConstructorDecl *DerivedCtor; 8968 }; 8969 8970 /// Inheriting constructors with a given canonical type. There can be at 8971 /// most one such non-template constructor, and any number of templated 8972 /// constructors. 8973 struct InheritingConstructorsForType { 8974 InheritingConstructor NonTemplate; 8975 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8976 Templates; 8977 8978 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8979 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8980 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8981 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8982 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8983 false, S.TPL_TemplateMatch)) 8984 return Templates[I].second; 8985 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8986 return Templates.back().second; 8987 } 8988 8989 return NonTemplate; 8990 } 8991 }; 8992 8993 /// Get or create the inheriting constructor record for a constructor. 8994 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8995 QualType CtorType) { 8996 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8997 .getEntry(SemaRef, Ctor); 8998 } 8999 9000 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 9001 9002 /// Process all constructors for a class. 9003 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 9004 for (const auto *Ctor : RD->ctors()) 9005 (this->*Callback)(Ctor); 9006 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9007 I(RD->decls_begin()), E(RD->decls_end()); 9008 I != E; ++I) { 9009 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 9010 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 9011 (this->*Callback)(CD); 9012 } 9013 } 9014 9015 /// Note that a constructor (or constructor template) was declared in Derived. 9016 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 9017 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 9018 } 9019 9020 /// Inherit a single constructor. 9021 void inherit(const CXXConstructorDecl *Ctor) { 9022 const FunctionProtoType *CtorType = 9023 Ctor->getType()->castAs<FunctionProtoType>(); 9024 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 9025 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 9026 9027 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 9028 9029 // Core issue (no number yet): the ellipsis is always discarded. 9030 if (EPI.Variadic) { 9031 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 9032 SemaRef.Diag(Ctor->getLocation(), 9033 diag::note_using_decl_constructor_ellipsis); 9034 EPI.Variadic = false; 9035 } 9036 9037 // Declare a constructor for each number of parameters. 9038 // 9039 // C++11 [class.inhctor]p1: 9040 // The candidate set of inherited constructors from the class X named in 9041 // the using-declaration consists of [... modulo defects ...] for each 9042 // constructor or constructor template of X, the set of constructors or 9043 // constructor templates that results from omitting any ellipsis parameter 9044 // specification and successively omitting parameters with a default 9045 // argument from the end of the parameter-type-list 9046 unsigned MinParams = minParamsToInherit(Ctor); 9047 unsigned Params = Ctor->getNumParams(); 9048 if (Params >= MinParams) { 9049 do 9050 declareCtor(UsingLoc, Ctor, 9051 SemaRef.Context.getFunctionType( 9052 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 9053 while (Params > MinParams && 9054 Ctor->getParamDecl(--Params)->hasDefaultArg()); 9055 } 9056 } 9057 9058 /// Find the using-declaration which specified that we should inherit the 9059 /// constructors of \p Base. 9060 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 9061 // No fancy lookup required; just look for the base constructor name 9062 // directly within the derived class. 9063 ASTContext &Context = SemaRef.Context; 9064 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9065 Context.getCanonicalType(Context.getRecordType(Base))); 9066 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 9067 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 9068 } 9069 9070 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 9071 // C++11 [class.inhctor]p3: 9072 // [F]or each constructor template in the candidate set of inherited 9073 // constructors, a constructor template is implicitly declared 9074 if (Ctor->getDescribedFunctionTemplate()) 9075 return 0; 9076 9077 // For each non-template constructor in the candidate set of inherited 9078 // constructors other than a constructor having no parameters or a 9079 // copy/move constructor having a single parameter, a constructor is 9080 // implicitly declared [...] 9081 if (Ctor->getNumParams() == 0) 9082 return 1; 9083 if (Ctor->isCopyOrMoveConstructor()) 9084 return 2; 9085 9086 // Per discussion on core reflector, never inherit a constructor which 9087 // would become a default, copy, or move constructor of Derived either. 9088 const ParmVarDecl *PD = Ctor->getParamDecl(0); 9089 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 9090 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 9091 } 9092 9093 /// Declare a single inheriting constructor, inheriting the specified 9094 /// constructor, with the given type. 9095 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 9096 QualType DerivedType) { 9097 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 9098 9099 // C++11 [class.inhctor]p3: 9100 // ... a constructor is implicitly declared with the same constructor 9101 // characteristics unless there is a user-declared constructor with 9102 // the same signature in the class where the using-declaration appears 9103 if (Entry.DeclaredInDerived) 9104 return; 9105 9106 // C++11 [class.inhctor]p7: 9107 // If two using-declarations declare inheriting constructors with the 9108 // same signature, the program is ill-formed 9109 if (Entry.DerivedCtor) { 9110 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 9111 // Only diagnose this once per constructor. 9112 if (Entry.DerivedCtor->isInvalidDecl()) 9113 return; 9114 Entry.DerivedCtor->setInvalidDecl(); 9115 9116 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9117 SemaRef.Diag(BaseCtor->getLocation(), 9118 diag::note_using_decl_constructor_conflict_current_ctor); 9119 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9120 diag::note_using_decl_constructor_conflict_previous_ctor); 9121 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9122 diag::note_using_decl_constructor_conflict_previous_using); 9123 } else { 9124 // Core issue (no number): if the same inheriting constructor is 9125 // produced by multiple base class constructors from the same base 9126 // class, the inheriting constructor is defined as deleted. 9127 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9128 } 9129 9130 return; 9131 } 9132 9133 ASTContext &Context = SemaRef.Context; 9134 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9135 Context.getCanonicalType(Context.getRecordType(Derived))); 9136 DeclarationNameInfo NameInfo(Name, UsingLoc); 9137 9138 TemplateParameterList *TemplateParams = nullptr; 9139 if (const FunctionTemplateDecl *FTD = 9140 BaseCtor->getDescribedFunctionTemplate()) { 9141 TemplateParams = FTD->getTemplateParameters(); 9142 // We're reusing template parameters from a different DeclContext. This 9143 // is questionable at best, but works out because the template depth in 9144 // both places is guaranteed to be 0. 9145 // FIXME: Rebuild the template parameters in the new context, and 9146 // transform the function type to refer to them. 9147 } 9148 9149 // Build type source info pointing at the using-declaration. This is 9150 // required by template instantiation. 9151 TypeSourceInfo *TInfo = 9152 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9153 FunctionProtoTypeLoc ProtoLoc = 9154 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9155 9156 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9157 Context, Derived, UsingLoc, NameInfo, DerivedType, 9158 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9159 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9160 9161 // Build an unevaluated exception specification for this constructor. 9162 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9163 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9164 EPI.ExceptionSpec.Type = EST_Unevaluated; 9165 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9166 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9167 FPT->getParamTypes(), EPI)); 9168 9169 // Build the parameter declarations. 9170 SmallVector<ParmVarDecl *, 16> ParamDecls; 9171 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9172 TypeSourceInfo *TInfo = 9173 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9174 ParmVarDecl *PD = ParmVarDecl::Create( 9175 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9176 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9177 PD->setScopeInfo(0, I); 9178 PD->setImplicit(); 9179 ParamDecls.push_back(PD); 9180 ProtoLoc.setParam(I, PD); 9181 } 9182 9183 // Set up the new constructor. 9184 DerivedCtor->setAccess(BaseCtor->getAccess()); 9185 DerivedCtor->setParams(ParamDecls); 9186 DerivedCtor->setInheritedConstructor(BaseCtor); 9187 if (BaseCtor->isDeleted()) 9188 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9189 9190 // If this is a constructor template, build the template declaration. 9191 if (TemplateParams) { 9192 FunctionTemplateDecl *DerivedTemplate = 9193 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9194 TemplateParams, DerivedCtor); 9195 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9196 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9197 Derived->addDecl(DerivedTemplate); 9198 } else { 9199 Derived->addDecl(DerivedCtor); 9200 } 9201 9202 Entry.BaseCtor = BaseCtor; 9203 Entry.DerivedCtor = DerivedCtor; 9204 } 9205 9206 Sema &SemaRef; 9207 CXXRecordDecl *Derived; 9208 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9209 MapType Map; 9210 }; 9211 } 9212 9213 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9214 // Defer declaring the inheriting constructors until the class is 9215 // instantiated. 9216 if (ClassDecl->isDependentContext()) 9217 return; 9218 9219 // Find base classes from which we might inherit constructors. 9220 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9221 for (const auto &BaseIt : ClassDecl->bases()) 9222 if (BaseIt.getInheritConstructors()) 9223 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9224 9225 // Go no further if we're not inheriting any constructors. 9226 if (InheritedBases.empty()) 9227 return; 9228 9229 // Declare the inherited constructors. 9230 InheritingConstructorInfo ICI(*this, ClassDecl); 9231 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9232 ICI.inheritAll(InheritedBases[I]); 9233 } 9234 9235 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9236 CXXConstructorDecl *Constructor) { 9237 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9238 assert(Constructor->getInheritedConstructor() && 9239 !Constructor->doesThisDeclarationHaveABody() && 9240 !Constructor->isDeleted()); 9241 9242 SynthesizedFunctionScope Scope(*this, Constructor); 9243 DiagnosticErrorTrap Trap(Diags); 9244 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9245 Trap.hasErrorOccurred()) { 9246 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9247 << Context.getTagDeclType(ClassDecl); 9248 Constructor->setInvalidDecl(); 9249 return; 9250 } 9251 9252 SourceLocation Loc = Constructor->getLocation(); 9253 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9254 9255 Constructor->markUsed(Context); 9256 MarkVTableUsed(CurrentLocation, ClassDecl); 9257 9258 if (ASTMutationListener *L = getASTMutationListener()) { 9259 L->CompletedImplicitDefinition(Constructor); 9260 } 9261 } 9262 9263 9264 Sema::ImplicitExceptionSpecification 9265 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9266 CXXRecordDecl *ClassDecl = MD->getParent(); 9267 9268 // C++ [except.spec]p14: 9269 // An implicitly declared special member function (Clause 12) shall have 9270 // an exception-specification. 9271 ImplicitExceptionSpecification ExceptSpec(*this); 9272 if (ClassDecl->isInvalidDecl()) 9273 return ExceptSpec; 9274 9275 // Direct base-class destructors. 9276 for (const auto &B : ClassDecl->bases()) { 9277 if (B.isVirtual()) // Handled below. 9278 continue; 9279 9280 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9281 ExceptSpec.CalledDecl(B.getLocStart(), 9282 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9283 } 9284 9285 // Virtual base-class destructors. 9286 for (const auto &B : ClassDecl->vbases()) { 9287 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9288 ExceptSpec.CalledDecl(B.getLocStart(), 9289 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9290 } 9291 9292 // Field destructors. 9293 for (const auto *F : ClassDecl->fields()) { 9294 if (const RecordType *RecordTy 9295 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9296 ExceptSpec.CalledDecl(F->getLocation(), 9297 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9298 } 9299 9300 return ExceptSpec; 9301 } 9302 9303 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9304 // C++ [class.dtor]p2: 9305 // If a class has no user-declared destructor, a destructor is 9306 // declared implicitly. An implicitly-declared destructor is an 9307 // inline public member of its class. 9308 assert(ClassDecl->needsImplicitDestructor()); 9309 9310 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9311 if (DSM.isAlreadyBeingDeclared()) 9312 return nullptr; 9313 9314 // Create the actual destructor declaration. 9315 CanQualType ClassType 9316 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9317 SourceLocation ClassLoc = ClassDecl->getLocation(); 9318 DeclarationName Name 9319 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9320 DeclarationNameInfo NameInfo(Name, ClassLoc); 9321 CXXDestructorDecl *Destructor 9322 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9323 QualType(), nullptr, /*isInline=*/true, 9324 /*isImplicitlyDeclared=*/true); 9325 Destructor->setAccess(AS_public); 9326 Destructor->setDefaulted(); 9327 9328 if (getLangOpts().CUDA) { 9329 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9330 Destructor, 9331 /* ConstRHS */ false, 9332 /* Diagnose */ false); 9333 } 9334 9335 // Build an exception specification pointing back at this destructor. 9336 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9337 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9338 9339 AddOverriddenMethods(ClassDecl, Destructor); 9340 9341 // We don't need to use SpecialMemberIsTrivial here; triviality for 9342 // destructors is easy to compute. 9343 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9344 9345 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9346 SetDeclDeleted(Destructor, ClassLoc); 9347 9348 // Note that we have declared this destructor. 9349 ++ASTContext::NumImplicitDestructorsDeclared; 9350 9351 // Introduce this destructor into its scope. 9352 if (Scope *S = getScopeForContext(ClassDecl)) 9353 PushOnScopeChains(Destructor, S, false); 9354 ClassDecl->addDecl(Destructor); 9355 9356 return Destructor; 9357 } 9358 9359 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9360 CXXDestructorDecl *Destructor) { 9361 assert((Destructor->isDefaulted() && 9362 !Destructor->doesThisDeclarationHaveABody() && 9363 !Destructor->isDeleted()) && 9364 "DefineImplicitDestructor - call it for implicit default dtor"); 9365 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9366 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9367 9368 if (Destructor->isInvalidDecl()) 9369 return; 9370 9371 SynthesizedFunctionScope Scope(*this, Destructor); 9372 9373 DiagnosticErrorTrap Trap(Diags); 9374 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9375 Destructor->getParent()); 9376 9377 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9378 Diag(CurrentLocation, diag::note_member_synthesized_at) 9379 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9380 9381 Destructor->setInvalidDecl(); 9382 return; 9383 } 9384 9385 // The exception specification is needed because we are defining the 9386 // function. 9387 ResolveExceptionSpec(CurrentLocation, 9388 Destructor->getType()->castAs<FunctionProtoType>()); 9389 9390 SourceLocation Loc = Destructor->getLocEnd().isValid() 9391 ? Destructor->getLocEnd() 9392 : Destructor->getLocation(); 9393 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9394 Destructor->markUsed(Context); 9395 MarkVTableUsed(CurrentLocation, ClassDecl); 9396 9397 if (ASTMutationListener *L = getASTMutationListener()) { 9398 L->CompletedImplicitDefinition(Destructor); 9399 } 9400 } 9401 9402 /// \brief Perform any semantic analysis which needs to be delayed until all 9403 /// pending class member declarations have been parsed. 9404 void Sema::ActOnFinishCXXMemberDecls() { 9405 // If the context is an invalid C++ class, just suppress these checks. 9406 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9407 if (Record->isInvalidDecl()) { 9408 DelayedDefaultedMemberExceptionSpecs.clear(); 9409 DelayedExceptionSpecChecks.clear(); 9410 return; 9411 } 9412 } 9413 } 9414 9415 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9416 CXXDestructorDecl *Destructor) { 9417 assert(getLangOpts().CPlusPlus11 && 9418 "adjusting dtor exception specs was introduced in c++11"); 9419 9420 // C++11 [class.dtor]p3: 9421 // A declaration of a destructor that does not have an exception- 9422 // specification is implicitly considered to have the same exception- 9423 // specification as an implicit declaration. 9424 const FunctionProtoType *DtorType = Destructor->getType()-> 9425 getAs<FunctionProtoType>(); 9426 if (DtorType->hasExceptionSpec()) 9427 return; 9428 9429 // Replace the destructor's type, building off the existing one. Fortunately, 9430 // the only thing of interest in the destructor type is its extended info. 9431 // The return and arguments are fixed. 9432 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9433 EPI.ExceptionSpec.Type = EST_Unevaluated; 9434 EPI.ExceptionSpec.SourceDecl = Destructor; 9435 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9436 9437 // FIXME: If the destructor has a body that could throw, and the newly created 9438 // spec doesn't allow exceptions, we should emit a warning, because this 9439 // change in behavior can break conforming C++03 programs at runtime. 9440 // However, we don't have a body or an exception specification yet, so it 9441 // needs to be done somewhere else. 9442 } 9443 9444 namespace { 9445 /// \brief An abstract base class for all helper classes used in building the 9446 // copy/move operators. These classes serve as factory functions and help us 9447 // avoid using the same Expr* in the AST twice. 9448 class ExprBuilder { 9449 ExprBuilder(const ExprBuilder&) = delete; 9450 ExprBuilder &operator=(const ExprBuilder&) = delete; 9451 9452 protected: 9453 static Expr *assertNotNull(Expr *E) { 9454 assert(E && "Expression construction must not fail."); 9455 return E; 9456 } 9457 9458 public: 9459 ExprBuilder() {} 9460 virtual ~ExprBuilder() {} 9461 9462 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9463 }; 9464 9465 class RefBuilder: public ExprBuilder { 9466 VarDecl *Var; 9467 QualType VarType; 9468 9469 public: 9470 Expr *build(Sema &S, SourceLocation Loc) const override { 9471 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9472 } 9473 9474 RefBuilder(VarDecl *Var, QualType VarType) 9475 : Var(Var), VarType(VarType) {} 9476 }; 9477 9478 class ThisBuilder: public ExprBuilder { 9479 public: 9480 Expr *build(Sema &S, SourceLocation Loc) const override { 9481 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9482 } 9483 }; 9484 9485 class CastBuilder: public ExprBuilder { 9486 const ExprBuilder &Builder; 9487 QualType Type; 9488 ExprValueKind Kind; 9489 const CXXCastPath &Path; 9490 9491 public: 9492 Expr *build(Sema &S, SourceLocation Loc) const override { 9493 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9494 CK_UncheckedDerivedToBase, Kind, 9495 &Path).get()); 9496 } 9497 9498 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9499 const CXXCastPath &Path) 9500 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9501 }; 9502 9503 class DerefBuilder: public ExprBuilder { 9504 const ExprBuilder &Builder; 9505 9506 public: 9507 Expr *build(Sema &S, SourceLocation Loc) const override { 9508 return assertNotNull( 9509 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9510 } 9511 9512 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9513 }; 9514 9515 class MemberBuilder: public ExprBuilder { 9516 const ExprBuilder &Builder; 9517 QualType Type; 9518 CXXScopeSpec SS; 9519 bool IsArrow; 9520 LookupResult &MemberLookup; 9521 9522 public: 9523 Expr *build(Sema &S, SourceLocation Loc) const override { 9524 return assertNotNull(S.BuildMemberReferenceExpr( 9525 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9526 nullptr, MemberLookup, nullptr).get()); 9527 } 9528 9529 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9530 LookupResult &MemberLookup) 9531 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9532 MemberLookup(MemberLookup) {} 9533 }; 9534 9535 class MoveCastBuilder: public ExprBuilder { 9536 const ExprBuilder &Builder; 9537 9538 public: 9539 Expr *build(Sema &S, SourceLocation Loc) const override { 9540 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9541 } 9542 9543 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9544 }; 9545 9546 class LvalueConvBuilder: public ExprBuilder { 9547 const ExprBuilder &Builder; 9548 9549 public: 9550 Expr *build(Sema &S, SourceLocation Loc) const override { 9551 return assertNotNull( 9552 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9553 } 9554 9555 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9556 }; 9557 9558 class SubscriptBuilder: public ExprBuilder { 9559 const ExprBuilder &Base; 9560 const ExprBuilder &Index; 9561 9562 public: 9563 Expr *build(Sema &S, SourceLocation Loc) const override { 9564 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9565 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9566 } 9567 9568 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9569 : Base(Base), Index(Index) {} 9570 }; 9571 9572 } // end anonymous namespace 9573 9574 /// When generating a defaulted copy or move assignment operator, if a field 9575 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9576 /// do so. This optimization only applies for arrays of scalars, and for arrays 9577 /// of class type where the selected copy/move-assignment operator is trivial. 9578 static StmtResult 9579 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9580 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9581 // Compute the size of the memory buffer to be copied. 9582 QualType SizeType = S.Context.getSizeType(); 9583 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9584 S.Context.getTypeSizeInChars(T).getQuantity()); 9585 9586 // Take the address of the field references for "from" and "to". We 9587 // directly construct UnaryOperators here because semantic analysis 9588 // does not permit us to take the address of an xvalue. 9589 Expr *From = FromB.build(S, Loc); 9590 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9591 S.Context.getPointerType(From->getType()), 9592 VK_RValue, OK_Ordinary, Loc); 9593 Expr *To = ToB.build(S, Loc); 9594 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9595 S.Context.getPointerType(To->getType()), 9596 VK_RValue, OK_Ordinary, Loc); 9597 9598 const Type *E = T->getBaseElementTypeUnsafe(); 9599 bool NeedsCollectableMemCpy = 9600 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9601 9602 // Create a reference to the __builtin_objc_memmove_collectable function 9603 StringRef MemCpyName = NeedsCollectableMemCpy ? 9604 "__builtin_objc_memmove_collectable" : 9605 "__builtin_memcpy"; 9606 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9607 Sema::LookupOrdinaryName); 9608 S.LookupName(R, S.TUScope, true); 9609 9610 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9611 if (!MemCpy) 9612 // Something went horribly wrong earlier, and we will have complained 9613 // about it. 9614 return StmtError(); 9615 9616 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9617 VK_RValue, Loc, nullptr); 9618 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9619 9620 Expr *CallArgs[] = { 9621 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9622 }; 9623 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9624 Loc, CallArgs, Loc); 9625 9626 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9627 return Call.getAs<Stmt>(); 9628 } 9629 9630 /// \brief Builds a statement that copies/moves the given entity from \p From to 9631 /// \c To. 9632 /// 9633 /// This routine is used to copy/move the members of a class with an 9634 /// implicitly-declared copy/move assignment operator. When the entities being 9635 /// copied are arrays, this routine builds for loops to copy them. 9636 /// 9637 /// \param S The Sema object used for type-checking. 9638 /// 9639 /// \param Loc The location where the implicit copy/move is being generated. 9640 /// 9641 /// \param T The type of the expressions being copied/moved. Both expressions 9642 /// must have this type. 9643 /// 9644 /// \param To The expression we are copying/moving to. 9645 /// 9646 /// \param From The expression we are copying/moving from. 9647 /// 9648 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9649 /// Otherwise, it's a non-static member subobject. 9650 /// 9651 /// \param Copying Whether we're copying or moving. 9652 /// 9653 /// \param Depth Internal parameter recording the depth of the recursion. 9654 /// 9655 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9656 /// if a memcpy should be used instead. 9657 static StmtResult 9658 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9659 const ExprBuilder &To, const ExprBuilder &From, 9660 bool CopyingBaseSubobject, bool Copying, 9661 unsigned Depth = 0) { 9662 // C++11 [class.copy]p28: 9663 // Each subobject is assigned in the manner appropriate to its type: 9664 // 9665 // - if the subobject is of class type, as if by a call to operator= with 9666 // the subobject as the object expression and the corresponding 9667 // subobject of x as a single function argument (as if by explicit 9668 // qualification; that is, ignoring any possible virtual overriding 9669 // functions in more derived classes); 9670 // 9671 // C++03 [class.copy]p13: 9672 // - if the subobject is of class type, the copy assignment operator for 9673 // the class is used (as if by explicit qualification; that is, 9674 // ignoring any possible virtual overriding functions in more derived 9675 // classes); 9676 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9677 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9678 9679 // Look for operator=. 9680 DeclarationName Name 9681 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9682 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9683 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9684 9685 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9686 // operator. 9687 if (!S.getLangOpts().CPlusPlus11) { 9688 LookupResult::Filter F = OpLookup.makeFilter(); 9689 while (F.hasNext()) { 9690 NamedDecl *D = F.next(); 9691 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9692 if (Method->isCopyAssignmentOperator() || 9693 (!Copying && Method->isMoveAssignmentOperator())) 9694 continue; 9695 9696 F.erase(); 9697 } 9698 F.done(); 9699 } 9700 9701 // Suppress the protected check (C++ [class.protected]) for each of the 9702 // assignment operators we found. This strange dance is required when 9703 // we're assigning via a base classes's copy-assignment operator. To 9704 // ensure that we're getting the right base class subobject (without 9705 // ambiguities), we need to cast "this" to that subobject type; to 9706 // ensure that we don't go through the virtual call mechanism, we need 9707 // to qualify the operator= name with the base class (see below). However, 9708 // this means that if the base class has a protected copy assignment 9709 // operator, the protected member access check will fail. So, we 9710 // rewrite "protected" access to "public" access in this case, since we 9711 // know by construction that we're calling from a derived class. 9712 if (CopyingBaseSubobject) { 9713 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9714 L != LEnd; ++L) { 9715 if (L.getAccess() == AS_protected) 9716 L.setAccess(AS_public); 9717 } 9718 } 9719 9720 // Create the nested-name-specifier that will be used to qualify the 9721 // reference to operator=; this is required to suppress the virtual 9722 // call mechanism. 9723 CXXScopeSpec SS; 9724 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9725 SS.MakeTrivial(S.Context, 9726 NestedNameSpecifier::Create(S.Context, nullptr, false, 9727 CanonicalT), 9728 Loc); 9729 9730 // Create the reference to operator=. 9731 ExprResult OpEqualRef 9732 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9733 SS, /*TemplateKWLoc=*/SourceLocation(), 9734 /*FirstQualifierInScope=*/nullptr, 9735 OpLookup, 9736 /*TemplateArgs=*/nullptr, 9737 /*SuppressQualifierCheck=*/true); 9738 if (OpEqualRef.isInvalid()) 9739 return StmtError(); 9740 9741 // Build the call to the assignment operator. 9742 9743 Expr *FromInst = From.build(S, Loc); 9744 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9745 OpEqualRef.getAs<Expr>(), 9746 Loc, FromInst, Loc); 9747 if (Call.isInvalid()) 9748 return StmtError(); 9749 9750 // If we built a call to a trivial 'operator=' while copying an array, 9751 // bail out. We'll replace the whole shebang with a memcpy. 9752 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9753 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9754 return StmtResult((Stmt*)nullptr); 9755 9756 // Convert to an expression-statement, and clean up any produced 9757 // temporaries. 9758 return S.ActOnExprStmt(Call); 9759 } 9760 9761 // - if the subobject is of scalar type, the built-in assignment 9762 // operator is used. 9763 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9764 if (!ArrayTy) { 9765 ExprResult Assignment = S.CreateBuiltinBinOp( 9766 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9767 if (Assignment.isInvalid()) 9768 return StmtError(); 9769 return S.ActOnExprStmt(Assignment); 9770 } 9771 9772 // - if the subobject is an array, each element is assigned, in the 9773 // manner appropriate to the element type; 9774 9775 // Construct a loop over the array bounds, e.g., 9776 // 9777 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9778 // 9779 // that will copy each of the array elements. 9780 QualType SizeType = S.Context.getSizeType(); 9781 9782 // Create the iteration variable. 9783 IdentifierInfo *IterationVarName = nullptr; 9784 { 9785 SmallString<8> Str; 9786 llvm::raw_svector_ostream OS(Str); 9787 OS << "__i" << Depth; 9788 IterationVarName = &S.Context.Idents.get(OS.str()); 9789 } 9790 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9791 IterationVarName, SizeType, 9792 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9793 SC_None); 9794 9795 // Initialize the iteration variable to zero. 9796 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9797 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9798 9799 // Creates a reference to the iteration variable. 9800 RefBuilder IterationVarRef(IterationVar, SizeType); 9801 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9802 9803 // Create the DeclStmt that holds the iteration variable. 9804 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9805 9806 // Subscript the "from" and "to" expressions with the iteration variable. 9807 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9808 MoveCastBuilder FromIndexMove(FromIndexCopy); 9809 const ExprBuilder *FromIndex; 9810 if (Copying) 9811 FromIndex = &FromIndexCopy; 9812 else 9813 FromIndex = &FromIndexMove; 9814 9815 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9816 9817 // Build the copy/move for an individual element of the array. 9818 StmtResult Copy = 9819 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9820 ToIndex, *FromIndex, CopyingBaseSubobject, 9821 Copying, Depth + 1); 9822 // Bail out if copying fails or if we determined that we should use memcpy. 9823 if (Copy.isInvalid() || !Copy.get()) 9824 return Copy; 9825 9826 // Create the comparison against the array bound. 9827 llvm::APInt Upper 9828 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9829 Expr *Comparison 9830 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9831 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9832 BO_NE, S.Context.BoolTy, 9833 VK_RValue, OK_Ordinary, Loc, false); 9834 9835 // Create the pre-increment of the iteration variable. 9836 Expr *Increment 9837 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9838 SizeType, VK_LValue, OK_Ordinary, Loc); 9839 9840 // Construct the loop that copies all elements of this array. 9841 return S.ActOnForStmt(Loc, Loc, InitStmt, 9842 S.MakeFullExpr(Comparison), 9843 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9844 Loc, Copy.get()); 9845 } 9846 9847 static StmtResult 9848 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9849 const ExprBuilder &To, const ExprBuilder &From, 9850 bool CopyingBaseSubobject, bool Copying) { 9851 // Maybe we should use a memcpy? 9852 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9853 T.isTriviallyCopyableType(S.Context)) 9854 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9855 9856 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9857 CopyingBaseSubobject, 9858 Copying, 0)); 9859 9860 // If we ended up picking a trivial assignment operator for an array of a 9861 // non-trivially-copyable class type, just emit a memcpy. 9862 if (!Result.isInvalid() && !Result.get()) 9863 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9864 9865 return Result; 9866 } 9867 9868 Sema::ImplicitExceptionSpecification 9869 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9870 CXXRecordDecl *ClassDecl = MD->getParent(); 9871 9872 ImplicitExceptionSpecification ExceptSpec(*this); 9873 if (ClassDecl->isInvalidDecl()) 9874 return ExceptSpec; 9875 9876 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9877 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9878 unsigned ArgQuals = 9879 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9880 9881 // C++ [except.spec]p14: 9882 // An implicitly declared special member function (Clause 12) shall have an 9883 // exception-specification. [...] 9884 9885 // It is unspecified whether or not an implicit copy assignment operator 9886 // attempts to deduplicate calls to assignment operators of virtual bases are 9887 // made. As such, this exception specification is effectively unspecified. 9888 // Based on a similar decision made for constness in C++0x, we're erring on 9889 // the side of assuming such calls to be made regardless of whether they 9890 // actually happen. 9891 for (const auto &Base : ClassDecl->bases()) { 9892 if (Base.isVirtual()) 9893 continue; 9894 9895 CXXRecordDecl *BaseClassDecl 9896 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9897 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9898 ArgQuals, false, 0)) 9899 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9900 } 9901 9902 for (const auto &Base : ClassDecl->vbases()) { 9903 CXXRecordDecl *BaseClassDecl 9904 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9905 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9906 ArgQuals, false, 0)) 9907 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9908 } 9909 9910 for (const auto *Field : ClassDecl->fields()) { 9911 QualType FieldType = Context.getBaseElementType(Field->getType()); 9912 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9913 if (CXXMethodDecl *CopyAssign = 9914 LookupCopyingAssignment(FieldClassDecl, 9915 ArgQuals | FieldType.getCVRQualifiers(), 9916 false, 0)) 9917 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9918 } 9919 } 9920 9921 return ExceptSpec; 9922 } 9923 9924 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9925 // Note: The following rules are largely analoguous to the copy 9926 // constructor rules. Note that virtual bases are not taken into account 9927 // for determining the argument type of the operator. Note also that 9928 // operators taking an object instead of a reference are allowed. 9929 assert(ClassDecl->needsImplicitCopyAssignment()); 9930 9931 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9932 if (DSM.isAlreadyBeingDeclared()) 9933 return nullptr; 9934 9935 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9936 QualType RetType = Context.getLValueReferenceType(ArgType); 9937 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9938 if (Const) 9939 ArgType = ArgType.withConst(); 9940 ArgType = Context.getLValueReferenceType(ArgType); 9941 9942 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9943 CXXCopyAssignment, 9944 Const); 9945 9946 // An implicitly-declared copy assignment operator is an inline public 9947 // member of its class. 9948 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9949 SourceLocation ClassLoc = ClassDecl->getLocation(); 9950 DeclarationNameInfo NameInfo(Name, ClassLoc); 9951 CXXMethodDecl *CopyAssignment = 9952 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9953 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9954 /*isInline=*/true, Constexpr, SourceLocation()); 9955 CopyAssignment->setAccess(AS_public); 9956 CopyAssignment->setDefaulted(); 9957 CopyAssignment->setImplicit(); 9958 9959 if (getLangOpts().CUDA) { 9960 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 9961 CopyAssignment, 9962 /* ConstRHS */ Const, 9963 /* Diagnose */ false); 9964 } 9965 9966 // Build an exception specification pointing back at this member. 9967 FunctionProtoType::ExtProtoInfo EPI = 9968 getImplicitMethodEPI(*this, CopyAssignment); 9969 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9970 9971 // Add the parameter to the operator. 9972 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9973 ClassLoc, ClassLoc, 9974 /*Id=*/nullptr, ArgType, 9975 /*TInfo=*/nullptr, SC_None, 9976 nullptr); 9977 CopyAssignment->setParams(FromParam); 9978 9979 AddOverriddenMethods(ClassDecl, CopyAssignment); 9980 9981 CopyAssignment->setTrivial( 9982 ClassDecl->needsOverloadResolutionForCopyAssignment() 9983 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9984 : ClassDecl->hasTrivialCopyAssignment()); 9985 9986 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9987 SetDeclDeleted(CopyAssignment, ClassLoc); 9988 9989 // Note that we have added this copy-assignment operator. 9990 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9991 9992 if (Scope *S = getScopeForContext(ClassDecl)) 9993 PushOnScopeChains(CopyAssignment, S, false); 9994 ClassDecl->addDecl(CopyAssignment); 9995 9996 return CopyAssignment; 9997 } 9998 9999 /// Diagnose an implicit copy operation for a class which is odr-used, but 10000 /// which is deprecated because the class has a user-declared copy constructor, 10001 /// copy assignment operator, or destructor. 10002 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 10003 SourceLocation UseLoc) { 10004 assert(CopyOp->isImplicit()); 10005 10006 CXXRecordDecl *RD = CopyOp->getParent(); 10007 CXXMethodDecl *UserDeclaredOperation = nullptr; 10008 10009 // In Microsoft mode, assignment operations don't affect constructors and 10010 // vice versa. 10011 if (RD->hasUserDeclaredDestructor()) { 10012 UserDeclaredOperation = RD->getDestructor(); 10013 } else if (!isa<CXXConstructorDecl>(CopyOp) && 10014 RD->hasUserDeclaredCopyConstructor() && 10015 !S.getLangOpts().MSVCCompat) { 10016 // Find any user-declared copy constructor. 10017 for (auto *I : RD->ctors()) { 10018 if (I->isCopyConstructor()) { 10019 UserDeclaredOperation = I; 10020 break; 10021 } 10022 } 10023 assert(UserDeclaredOperation); 10024 } else if (isa<CXXConstructorDecl>(CopyOp) && 10025 RD->hasUserDeclaredCopyAssignment() && 10026 !S.getLangOpts().MSVCCompat) { 10027 // Find any user-declared move assignment operator. 10028 for (auto *I : RD->methods()) { 10029 if (I->isCopyAssignmentOperator()) { 10030 UserDeclaredOperation = I; 10031 break; 10032 } 10033 } 10034 assert(UserDeclaredOperation); 10035 } 10036 10037 if (UserDeclaredOperation) { 10038 S.Diag(UserDeclaredOperation->getLocation(), 10039 diag::warn_deprecated_copy_operation) 10040 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 10041 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 10042 S.Diag(UseLoc, diag::note_member_synthesized_at) 10043 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 10044 : Sema::CXXCopyAssignment) 10045 << RD; 10046 } 10047 } 10048 10049 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 10050 CXXMethodDecl *CopyAssignOperator) { 10051 assert((CopyAssignOperator->isDefaulted() && 10052 CopyAssignOperator->isOverloadedOperator() && 10053 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 10054 !CopyAssignOperator->doesThisDeclarationHaveABody() && 10055 !CopyAssignOperator->isDeleted()) && 10056 "DefineImplicitCopyAssignment called for wrong function"); 10057 10058 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 10059 10060 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 10061 CopyAssignOperator->setInvalidDecl(); 10062 return; 10063 } 10064 10065 // C++11 [class.copy]p18: 10066 // The [definition of an implicitly declared copy assignment operator] is 10067 // deprecated if the class has a user-declared copy constructor or a 10068 // user-declared destructor. 10069 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 10070 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 10071 10072 CopyAssignOperator->markUsed(Context); 10073 10074 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 10075 DiagnosticErrorTrap Trap(Diags); 10076 10077 // C++0x [class.copy]p30: 10078 // The implicitly-defined or explicitly-defaulted copy assignment operator 10079 // for a non-union class X performs memberwise copy assignment of its 10080 // subobjects. The direct base classes of X are assigned first, in the 10081 // order of their declaration in the base-specifier-list, and then the 10082 // immediate non-static data members of X are assigned, in the order in 10083 // which they were declared in the class definition. 10084 10085 // The statements that form the synthesized function body. 10086 SmallVector<Stmt*, 8> Statements; 10087 10088 // The parameter for the "other" object, which we are copying from. 10089 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 10090 Qualifiers OtherQuals = Other->getType().getQualifiers(); 10091 QualType OtherRefType = Other->getType(); 10092 if (const LValueReferenceType *OtherRef 10093 = OtherRefType->getAs<LValueReferenceType>()) { 10094 OtherRefType = OtherRef->getPointeeType(); 10095 OtherQuals = OtherRefType.getQualifiers(); 10096 } 10097 10098 // Our location for everything implicitly-generated. 10099 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 10100 ? CopyAssignOperator->getLocEnd() 10101 : CopyAssignOperator->getLocation(); 10102 10103 // Builds a DeclRefExpr for the "other" object. 10104 RefBuilder OtherRef(Other, OtherRefType); 10105 10106 // Builds the "this" pointer. 10107 ThisBuilder This; 10108 10109 // Assign base classes. 10110 bool Invalid = false; 10111 for (auto &Base : ClassDecl->bases()) { 10112 // Form the assignment: 10113 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10114 QualType BaseType = Base.getType().getUnqualifiedType(); 10115 if (!BaseType->isRecordType()) { 10116 Invalid = true; 10117 continue; 10118 } 10119 10120 CXXCastPath BasePath; 10121 BasePath.push_back(&Base); 10122 10123 // Construct the "from" expression, which is an implicit cast to the 10124 // appropriately-qualified base type. 10125 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10126 VK_LValue, BasePath); 10127 10128 // Dereference "this". 10129 DerefBuilder DerefThis(This); 10130 CastBuilder To(DerefThis, 10131 Context.getCVRQualifiedType( 10132 BaseType, CopyAssignOperator->getTypeQualifiers()), 10133 VK_LValue, BasePath); 10134 10135 // Build the copy. 10136 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10137 To, From, 10138 /*CopyingBaseSubobject=*/true, 10139 /*Copying=*/true); 10140 if (Copy.isInvalid()) { 10141 Diag(CurrentLocation, diag::note_member_synthesized_at) 10142 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10143 CopyAssignOperator->setInvalidDecl(); 10144 return; 10145 } 10146 10147 // Success! Record the copy. 10148 Statements.push_back(Copy.getAs<Expr>()); 10149 } 10150 10151 // Assign non-static members. 10152 for (auto *Field : ClassDecl->fields()) { 10153 if (Field->isUnnamedBitfield()) 10154 continue; 10155 10156 if (Field->isInvalidDecl()) { 10157 Invalid = true; 10158 continue; 10159 } 10160 10161 // Check for members of reference type; we can't copy those. 10162 if (Field->getType()->isReferenceType()) { 10163 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10164 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10165 Diag(Field->getLocation(), diag::note_declared_at); 10166 Diag(CurrentLocation, diag::note_member_synthesized_at) 10167 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10168 Invalid = true; 10169 continue; 10170 } 10171 10172 // Check for members of const-qualified, non-class type. 10173 QualType BaseType = Context.getBaseElementType(Field->getType()); 10174 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10175 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10176 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10177 Diag(Field->getLocation(), diag::note_declared_at); 10178 Diag(CurrentLocation, diag::note_member_synthesized_at) 10179 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10180 Invalid = true; 10181 continue; 10182 } 10183 10184 // Suppress assigning zero-width bitfields. 10185 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10186 continue; 10187 10188 QualType FieldType = Field->getType().getNonReferenceType(); 10189 if (FieldType->isIncompleteArrayType()) { 10190 assert(ClassDecl->hasFlexibleArrayMember() && 10191 "Incomplete array type is not valid"); 10192 continue; 10193 } 10194 10195 // Build references to the field in the object we're copying from and to. 10196 CXXScopeSpec SS; // Intentionally empty 10197 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10198 LookupMemberName); 10199 MemberLookup.addDecl(Field); 10200 MemberLookup.resolveKind(); 10201 10202 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10203 10204 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10205 10206 // Build the copy of this field. 10207 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10208 To, From, 10209 /*CopyingBaseSubobject=*/false, 10210 /*Copying=*/true); 10211 if (Copy.isInvalid()) { 10212 Diag(CurrentLocation, diag::note_member_synthesized_at) 10213 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10214 CopyAssignOperator->setInvalidDecl(); 10215 return; 10216 } 10217 10218 // Success! Record the copy. 10219 Statements.push_back(Copy.getAs<Stmt>()); 10220 } 10221 10222 if (!Invalid) { 10223 // Add a "return *this;" 10224 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10225 10226 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10227 if (Return.isInvalid()) 10228 Invalid = true; 10229 else { 10230 Statements.push_back(Return.getAs<Stmt>()); 10231 10232 if (Trap.hasErrorOccurred()) { 10233 Diag(CurrentLocation, diag::note_member_synthesized_at) 10234 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10235 Invalid = true; 10236 } 10237 } 10238 } 10239 10240 // The exception specification is needed because we are defining the 10241 // function. 10242 ResolveExceptionSpec(CurrentLocation, 10243 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10244 10245 if (Invalid) { 10246 CopyAssignOperator->setInvalidDecl(); 10247 return; 10248 } 10249 10250 StmtResult Body; 10251 { 10252 CompoundScopeRAII CompoundScope(*this); 10253 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10254 /*isStmtExpr=*/false); 10255 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10256 } 10257 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10258 10259 if (ASTMutationListener *L = getASTMutationListener()) { 10260 L->CompletedImplicitDefinition(CopyAssignOperator); 10261 } 10262 } 10263 10264 Sema::ImplicitExceptionSpecification 10265 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10266 CXXRecordDecl *ClassDecl = MD->getParent(); 10267 10268 ImplicitExceptionSpecification ExceptSpec(*this); 10269 if (ClassDecl->isInvalidDecl()) 10270 return ExceptSpec; 10271 10272 // C++0x [except.spec]p14: 10273 // An implicitly declared special member function (Clause 12) shall have an 10274 // exception-specification. [...] 10275 10276 // It is unspecified whether or not an implicit move assignment operator 10277 // attempts to deduplicate calls to assignment operators of virtual bases are 10278 // made. As such, this exception specification is effectively unspecified. 10279 // Based on a similar decision made for constness in C++0x, we're erring on 10280 // the side of assuming such calls to be made regardless of whether they 10281 // actually happen. 10282 // Note that a move constructor is not implicitly declared when there are 10283 // virtual bases, but it can still be user-declared and explicitly defaulted. 10284 for (const auto &Base : ClassDecl->bases()) { 10285 if (Base.isVirtual()) 10286 continue; 10287 10288 CXXRecordDecl *BaseClassDecl 10289 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10290 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10291 0, false, 0)) 10292 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10293 } 10294 10295 for (const auto &Base : ClassDecl->vbases()) { 10296 CXXRecordDecl *BaseClassDecl 10297 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10298 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10299 0, false, 0)) 10300 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10301 } 10302 10303 for (const auto *Field : ClassDecl->fields()) { 10304 QualType FieldType = Context.getBaseElementType(Field->getType()); 10305 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10306 if (CXXMethodDecl *MoveAssign = 10307 LookupMovingAssignment(FieldClassDecl, 10308 FieldType.getCVRQualifiers(), 10309 false, 0)) 10310 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10311 } 10312 } 10313 10314 return ExceptSpec; 10315 } 10316 10317 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10318 assert(ClassDecl->needsImplicitMoveAssignment()); 10319 10320 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10321 if (DSM.isAlreadyBeingDeclared()) 10322 return nullptr; 10323 10324 // Note: The following rules are largely analoguous to the move 10325 // constructor rules. 10326 10327 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10328 QualType RetType = Context.getLValueReferenceType(ArgType); 10329 ArgType = Context.getRValueReferenceType(ArgType); 10330 10331 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10332 CXXMoveAssignment, 10333 false); 10334 10335 // An implicitly-declared move assignment operator is an inline public 10336 // member of its class. 10337 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10338 SourceLocation ClassLoc = ClassDecl->getLocation(); 10339 DeclarationNameInfo NameInfo(Name, ClassLoc); 10340 CXXMethodDecl *MoveAssignment = 10341 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10342 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10343 /*isInline=*/true, Constexpr, SourceLocation()); 10344 MoveAssignment->setAccess(AS_public); 10345 MoveAssignment->setDefaulted(); 10346 MoveAssignment->setImplicit(); 10347 10348 if (getLangOpts().CUDA) { 10349 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10350 MoveAssignment, 10351 /* ConstRHS */ false, 10352 /* Diagnose */ false); 10353 } 10354 10355 // Build an exception specification pointing back at this member. 10356 FunctionProtoType::ExtProtoInfo EPI = 10357 getImplicitMethodEPI(*this, MoveAssignment); 10358 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10359 10360 // Add the parameter to the operator. 10361 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10362 ClassLoc, ClassLoc, 10363 /*Id=*/nullptr, ArgType, 10364 /*TInfo=*/nullptr, SC_None, 10365 nullptr); 10366 MoveAssignment->setParams(FromParam); 10367 10368 AddOverriddenMethods(ClassDecl, MoveAssignment); 10369 10370 MoveAssignment->setTrivial( 10371 ClassDecl->needsOverloadResolutionForMoveAssignment() 10372 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10373 : ClassDecl->hasTrivialMoveAssignment()); 10374 10375 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10376 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10377 SetDeclDeleted(MoveAssignment, ClassLoc); 10378 } 10379 10380 // Note that we have added this copy-assignment operator. 10381 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10382 10383 if (Scope *S = getScopeForContext(ClassDecl)) 10384 PushOnScopeChains(MoveAssignment, S, false); 10385 ClassDecl->addDecl(MoveAssignment); 10386 10387 return MoveAssignment; 10388 } 10389 10390 /// Check if we're implicitly defining a move assignment operator for a class 10391 /// with virtual bases. Such a move assignment might move-assign the virtual 10392 /// base multiple times. 10393 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10394 SourceLocation CurrentLocation) { 10395 assert(!Class->isDependentContext() && "should not define dependent move"); 10396 10397 // Only a virtual base could get implicitly move-assigned multiple times. 10398 // Only a non-trivial move assignment can observe this. We only want to 10399 // diagnose if we implicitly define an assignment operator that assigns 10400 // two base classes, both of which move-assign the same virtual base. 10401 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10402 Class->getNumBases() < 2) 10403 return; 10404 10405 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10406 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10407 VBaseMap VBases; 10408 10409 for (auto &BI : Class->bases()) { 10410 Worklist.push_back(&BI); 10411 while (!Worklist.empty()) { 10412 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10413 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10414 10415 // If the base has no non-trivial move assignment operators, 10416 // we don't care about moves from it. 10417 if (!Base->hasNonTrivialMoveAssignment()) 10418 continue; 10419 10420 // If there's nothing virtual here, skip it. 10421 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10422 continue; 10423 10424 // If we're not actually going to call a move assignment for this base, 10425 // or the selected move assignment is trivial, skip it. 10426 Sema::SpecialMemberOverloadResult *SMOR = 10427 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10428 /*ConstArg*/false, /*VolatileArg*/false, 10429 /*RValueThis*/true, /*ConstThis*/false, 10430 /*VolatileThis*/false); 10431 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10432 !SMOR->getMethod()->isMoveAssignmentOperator()) 10433 continue; 10434 10435 if (BaseSpec->isVirtual()) { 10436 // We're going to move-assign this virtual base, and its move 10437 // assignment operator is not trivial. If this can happen for 10438 // multiple distinct direct bases of Class, diagnose it. (If it 10439 // only happens in one base, we'll diagnose it when synthesizing 10440 // that base class's move assignment operator.) 10441 CXXBaseSpecifier *&Existing = 10442 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10443 .first->second; 10444 if (Existing && Existing != &BI) { 10445 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10446 << Class << Base; 10447 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10448 << (Base->getCanonicalDecl() == 10449 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10450 << Base << Existing->getType() << Existing->getSourceRange(); 10451 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10452 << (Base->getCanonicalDecl() == 10453 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10454 << Base << BI.getType() << BaseSpec->getSourceRange(); 10455 10456 // Only diagnose each vbase once. 10457 Existing = nullptr; 10458 } 10459 } else { 10460 // Only walk over bases that have defaulted move assignment operators. 10461 // We assume that any user-provided move assignment operator handles 10462 // the multiple-moves-of-vbase case itself somehow. 10463 if (!SMOR->getMethod()->isDefaulted()) 10464 continue; 10465 10466 // We're going to move the base classes of Base. Add them to the list. 10467 for (auto &BI : Base->bases()) 10468 Worklist.push_back(&BI); 10469 } 10470 } 10471 } 10472 } 10473 10474 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10475 CXXMethodDecl *MoveAssignOperator) { 10476 assert((MoveAssignOperator->isDefaulted() && 10477 MoveAssignOperator->isOverloadedOperator() && 10478 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10479 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10480 !MoveAssignOperator->isDeleted()) && 10481 "DefineImplicitMoveAssignment called for wrong function"); 10482 10483 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10484 10485 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10486 MoveAssignOperator->setInvalidDecl(); 10487 return; 10488 } 10489 10490 MoveAssignOperator->markUsed(Context); 10491 10492 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10493 DiagnosticErrorTrap Trap(Diags); 10494 10495 // C++0x [class.copy]p28: 10496 // The implicitly-defined or move assignment operator for a non-union class 10497 // X performs memberwise move assignment of its subobjects. The direct base 10498 // classes of X are assigned first, in the order of their declaration in the 10499 // base-specifier-list, and then the immediate non-static data members of X 10500 // are assigned, in the order in which they were declared in the class 10501 // definition. 10502 10503 // Issue a warning if our implicit move assignment operator will move 10504 // from a virtual base more than once. 10505 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10506 10507 // The statements that form the synthesized function body. 10508 SmallVector<Stmt*, 8> Statements; 10509 10510 // The parameter for the "other" object, which we are move from. 10511 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10512 QualType OtherRefType = Other->getType()-> 10513 getAs<RValueReferenceType>()->getPointeeType(); 10514 assert(!OtherRefType.getQualifiers() && 10515 "Bad argument type of defaulted move assignment"); 10516 10517 // Our location for everything implicitly-generated. 10518 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10519 ? MoveAssignOperator->getLocEnd() 10520 : MoveAssignOperator->getLocation(); 10521 10522 // Builds a reference to the "other" object. 10523 RefBuilder OtherRef(Other, OtherRefType); 10524 // Cast to rvalue. 10525 MoveCastBuilder MoveOther(OtherRef); 10526 10527 // Builds the "this" pointer. 10528 ThisBuilder This; 10529 10530 // Assign base classes. 10531 bool Invalid = false; 10532 for (auto &Base : ClassDecl->bases()) { 10533 // C++11 [class.copy]p28: 10534 // It is unspecified whether subobjects representing virtual base classes 10535 // are assigned more than once by the implicitly-defined copy assignment 10536 // operator. 10537 // FIXME: Do not assign to a vbase that will be assigned by some other base 10538 // class. For a move-assignment, this can result in the vbase being moved 10539 // multiple times. 10540 10541 // Form the assignment: 10542 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10543 QualType BaseType = Base.getType().getUnqualifiedType(); 10544 if (!BaseType->isRecordType()) { 10545 Invalid = true; 10546 continue; 10547 } 10548 10549 CXXCastPath BasePath; 10550 BasePath.push_back(&Base); 10551 10552 // Construct the "from" expression, which is an implicit cast to the 10553 // appropriately-qualified base type. 10554 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10555 10556 // Dereference "this". 10557 DerefBuilder DerefThis(This); 10558 10559 // Implicitly cast "this" to the appropriately-qualified base type. 10560 CastBuilder To(DerefThis, 10561 Context.getCVRQualifiedType( 10562 BaseType, MoveAssignOperator->getTypeQualifiers()), 10563 VK_LValue, BasePath); 10564 10565 // Build the move. 10566 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10567 To, From, 10568 /*CopyingBaseSubobject=*/true, 10569 /*Copying=*/false); 10570 if (Move.isInvalid()) { 10571 Diag(CurrentLocation, diag::note_member_synthesized_at) 10572 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10573 MoveAssignOperator->setInvalidDecl(); 10574 return; 10575 } 10576 10577 // Success! Record the move. 10578 Statements.push_back(Move.getAs<Expr>()); 10579 } 10580 10581 // Assign non-static members. 10582 for (auto *Field : ClassDecl->fields()) { 10583 if (Field->isUnnamedBitfield()) 10584 continue; 10585 10586 if (Field->isInvalidDecl()) { 10587 Invalid = true; 10588 continue; 10589 } 10590 10591 // Check for members of reference type; we can't move those. 10592 if (Field->getType()->isReferenceType()) { 10593 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10594 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10595 Diag(Field->getLocation(), diag::note_declared_at); 10596 Diag(CurrentLocation, diag::note_member_synthesized_at) 10597 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10598 Invalid = true; 10599 continue; 10600 } 10601 10602 // Check for members of const-qualified, non-class type. 10603 QualType BaseType = Context.getBaseElementType(Field->getType()); 10604 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10605 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10606 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10607 Diag(Field->getLocation(), diag::note_declared_at); 10608 Diag(CurrentLocation, diag::note_member_synthesized_at) 10609 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10610 Invalid = true; 10611 continue; 10612 } 10613 10614 // Suppress assigning zero-width bitfields. 10615 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10616 continue; 10617 10618 QualType FieldType = Field->getType().getNonReferenceType(); 10619 if (FieldType->isIncompleteArrayType()) { 10620 assert(ClassDecl->hasFlexibleArrayMember() && 10621 "Incomplete array type is not valid"); 10622 continue; 10623 } 10624 10625 // Build references to the field in the object we're copying from and to. 10626 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10627 LookupMemberName); 10628 MemberLookup.addDecl(Field); 10629 MemberLookup.resolveKind(); 10630 MemberBuilder From(MoveOther, OtherRefType, 10631 /*IsArrow=*/false, MemberLookup); 10632 MemberBuilder To(This, getCurrentThisType(), 10633 /*IsArrow=*/true, MemberLookup); 10634 10635 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10636 "Member reference with rvalue base must be rvalue except for reference " 10637 "members, which aren't allowed for move assignment."); 10638 10639 // Build the move of this field. 10640 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10641 To, From, 10642 /*CopyingBaseSubobject=*/false, 10643 /*Copying=*/false); 10644 if (Move.isInvalid()) { 10645 Diag(CurrentLocation, diag::note_member_synthesized_at) 10646 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10647 MoveAssignOperator->setInvalidDecl(); 10648 return; 10649 } 10650 10651 // Success! Record the copy. 10652 Statements.push_back(Move.getAs<Stmt>()); 10653 } 10654 10655 if (!Invalid) { 10656 // Add a "return *this;" 10657 ExprResult ThisObj = 10658 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10659 10660 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10661 if (Return.isInvalid()) 10662 Invalid = true; 10663 else { 10664 Statements.push_back(Return.getAs<Stmt>()); 10665 10666 if (Trap.hasErrorOccurred()) { 10667 Diag(CurrentLocation, diag::note_member_synthesized_at) 10668 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10669 Invalid = true; 10670 } 10671 } 10672 } 10673 10674 // The exception specification is needed because we are defining the 10675 // function. 10676 ResolveExceptionSpec(CurrentLocation, 10677 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10678 10679 if (Invalid) { 10680 MoveAssignOperator->setInvalidDecl(); 10681 return; 10682 } 10683 10684 StmtResult Body; 10685 { 10686 CompoundScopeRAII CompoundScope(*this); 10687 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10688 /*isStmtExpr=*/false); 10689 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10690 } 10691 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10692 10693 if (ASTMutationListener *L = getASTMutationListener()) { 10694 L->CompletedImplicitDefinition(MoveAssignOperator); 10695 } 10696 } 10697 10698 Sema::ImplicitExceptionSpecification 10699 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10700 CXXRecordDecl *ClassDecl = MD->getParent(); 10701 10702 ImplicitExceptionSpecification ExceptSpec(*this); 10703 if (ClassDecl->isInvalidDecl()) 10704 return ExceptSpec; 10705 10706 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10707 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10708 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10709 10710 // C++ [except.spec]p14: 10711 // An implicitly declared special member function (Clause 12) shall have an 10712 // exception-specification. [...] 10713 for (const auto &Base : ClassDecl->bases()) { 10714 // Virtual bases are handled below. 10715 if (Base.isVirtual()) 10716 continue; 10717 10718 CXXRecordDecl *BaseClassDecl 10719 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10720 if (CXXConstructorDecl *CopyConstructor = 10721 LookupCopyingConstructor(BaseClassDecl, Quals)) 10722 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10723 } 10724 for (const auto &Base : ClassDecl->vbases()) { 10725 CXXRecordDecl *BaseClassDecl 10726 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10727 if (CXXConstructorDecl *CopyConstructor = 10728 LookupCopyingConstructor(BaseClassDecl, Quals)) 10729 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10730 } 10731 for (const auto *Field : ClassDecl->fields()) { 10732 QualType FieldType = Context.getBaseElementType(Field->getType()); 10733 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10734 if (CXXConstructorDecl *CopyConstructor = 10735 LookupCopyingConstructor(FieldClassDecl, 10736 Quals | FieldType.getCVRQualifiers())) 10737 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10738 } 10739 } 10740 10741 return ExceptSpec; 10742 } 10743 10744 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10745 CXXRecordDecl *ClassDecl) { 10746 // C++ [class.copy]p4: 10747 // If the class definition does not explicitly declare a copy 10748 // constructor, one is declared implicitly. 10749 assert(ClassDecl->needsImplicitCopyConstructor()); 10750 10751 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10752 if (DSM.isAlreadyBeingDeclared()) 10753 return nullptr; 10754 10755 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10756 QualType ArgType = ClassType; 10757 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10758 if (Const) 10759 ArgType = ArgType.withConst(); 10760 ArgType = Context.getLValueReferenceType(ArgType); 10761 10762 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10763 CXXCopyConstructor, 10764 Const); 10765 10766 DeclarationName Name 10767 = Context.DeclarationNames.getCXXConstructorName( 10768 Context.getCanonicalType(ClassType)); 10769 SourceLocation ClassLoc = ClassDecl->getLocation(); 10770 DeclarationNameInfo NameInfo(Name, ClassLoc); 10771 10772 // An implicitly-declared copy constructor is an inline public 10773 // member of its class. 10774 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10775 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10776 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10777 Constexpr); 10778 CopyConstructor->setAccess(AS_public); 10779 CopyConstructor->setDefaulted(); 10780 10781 if (getLangOpts().CUDA) { 10782 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10783 CopyConstructor, 10784 /* ConstRHS */ Const, 10785 /* Diagnose */ false); 10786 } 10787 10788 // Build an exception specification pointing back at this member. 10789 FunctionProtoType::ExtProtoInfo EPI = 10790 getImplicitMethodEPI(*this, CopyConstructor); 10791 CopyConstructor->setType( 10792 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10793 10794 // Add the parameter to the constructor. 10795 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10796 ClassLoc, ClassLoc, 10797 /*IdentifierInfo=*/nullptr, 10798 ArgType, /*TInfo=*/nullptr, 10799 SC_None, nullptr); 10800 CopyConstructor->setParams(FromParam); 10801 10802 CopyConstructor->setTrivial( 10803 ClassDecl->needsOverloadResolutionForCopyConstructor() 10804 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10805 : ClassDecl->hasTrivialCopyConstructor()); 10806 10807 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10808 SetDeclDeleted(CopyConstructor, ClassLoc); 10809 10810 // Note that we have declared this constructor. 10811 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10812 10813 if (Scope *S = getScopeForContext(ClassDecl)) 10814 PushOnScopeChains(CopyConstructor, S, false); 10815 ClassDecl->addDecl(CopyConstructor); 10816 10817 return CopyConstructor; 10818 } 10819 10820 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10821 CXXConstructorDecl *CopyConstructor) { 10822 assert((CopyConstructor->isDefaulted() && 10823 CopyConstructor->isCopyConstructor() && 10824 !CopyConstructor->doesThisDeclarationHaveABody() && 10825 !CopyConstructor->isDeleted()) && 10826 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10827 10828 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10829 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10830 10831 // C++11 [class.copy]p7: 10832 // The [definition of an implicitly declared copy constructor] is 10833 // deprecated if the class has a user-declared copy assignment operator 10834 // or a user-declared destructor. 10835 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10836 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10837 10838 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10839 DiagnosticErrorTrap Trap(Diags); 10840 10841 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10842 Trap.hasErrorOccurred()) { 10843 Diag(CurrentLocation, diag::note_member_synthesized_at) 10844 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10845 CopyConstructor->setInvalidDecl(); 10846 } else { 10847 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10848 ? CopyConstructor->getLocEnd() 10849 : CopyConstructor->getLocation(); 10850 Sema::CompoundScopeRAII CompoundScope(*this); 10851 CopyConstructor->setBody( 10852 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10853 } 10854 10855 // The exception specification is needed because we are defining the 10856 // function. 10857 ResolveExceptionSpec(CurrentLocation, 10858 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10859 10860 CopyConstructor->markUsed(Context); 10861 MarkVTableUsed(CurrentLocation, ClassDecl); 10862 10863 if (ASTMutationListener *L = getASTMutationListener()) { 10864 L->CompletedImplicitDefinition(CopyConstructor); 10865 } 10866 } 10867 10868 Sema::ImplicitExceptionSpecification 10869 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10870 CXXRecordDecl *ClassDecl = MD->getParent(); 10871 10872 // C++ [except.spec]p14: 10873 // An implicitly declared special member function (Clause 12) shall have an 10874 // exception-specification. [...] 10875 ImplicitExceptionSpecification ExceptSpec(*this); 10876 if (ClassDecl->isInvalidDecl()) 10877 return ExceptSpec; 10878 10879 // Direct base-class constructors. 10880 for (const auto &B : ClassDecl->bases()) { 10881 if (B.isVirtual()) // Handled below. 10882 continue; 10883 10884 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10885 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10886 CXXConstructorDecl *Constructor = 10887 LookupMovingConstructor(BaseClassDecl, 0); 10888 // If this is a deleted function, add it anyway. This might be conformant 10889 // with the standard. This might not. I'm not sure. It might not matter. 10890 if (Constructor) 10891 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10892 } 10893 } 10894 10895 // Virtual base-class constructors. 10896 for (const auto &B : ClassDecl->vbases()) { 10897 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10898 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10899 CXXConstructorDecl *Constructor = 10900 LookupMovingConstructor(BaseClassDecl, 0); 10901 // If this is a deleted function, add it anyway. This might be conformant 10902 // with the standard. This might not. I'm not sure. It might not matter. 10903 if (Constructor) 10904 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10905 } 10906 } 10907 10908 // Field constructors. 10909 for (const auto *F : ClassDecl->fields()) { 10910 QualType FieldType = Context.getBaseElementType(F->getType()); 10911 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10912 CXXConstructorDecl *Constructor = 10913 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10914 // If this is a deleted function, add it anyway. This might be conformant 10915 // with the standard. This might not. I'm not sure. It might not matter. 10916 // In particular, the problem is that this function never gets called. It 10917 // might just be ill-formed because this function attempts to refer to 10918 // a deleted function here. 10919 if (Constructor) 10920 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10921 } 10922 } 10923 10924 return ExceptSpec; 10925 } 10926 10927 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10928 CXXRecordDecl *ClassDecl) { 10929 assert(ClassDecl->needsImplicitMoveConstructor()); 10930 10931 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10932 if (DSM.isAlreadyBeingDeclared()) 10933 return nullptr; 10934 10935 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10936 QualType ArgType = Context.getRValueReferenceType(ClassType); 10937 10938 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10939 CXXMoveConstructor, 10940 false); 10941 10942 DeclarationName Name 10943 = Context.DeclarationNames.getCXXConstructorName( 10944 Context.getCanonicalType(ClassType)); 10945 SourceLocation ClassLoc = ClassDecl->getLocation(); 10946 DeclarationNameInfo NameInfo(Name, ClassLoc); 10947 10948 // C++11 [class.copy]p11: 10949 // An implicitly-declared copy/move constructor is an inline public 10950 // member of its class. 10951 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10952 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10953 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10954 Constexpr); 10955 MoveConstructor->setAccess(AS_public); 10956 MoveConstructor->setDefaulted(); 10957 10958 if (getLangOpts().CUDA) { 10959 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 10960 MoveConstructor, 10961 /* ConstRHS */ false, 10962 /* Diagnose */ false); 10963 } 10964 10965 // Build an exception specification pointing back at this member. 10966 FunctionProtoType::ExtProtoInfo EPI = 10967 getImplicitMethodEPI(*this, MoveConstructor); 10968 MoveConstructor->setType( 10969 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10970 10971 // Add the parameter to the constructor. 10972 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10973 ClassLoc, ClassLoc, 10974 /*IdentifierInfo=*/nullptr, 10975 ArgType, /*TInfo=*/nullptr, 10976 SC_None, nullptr); 10977 MoveConstructor->setParams(FromParam); 10978 10979 MoveConstructor->setTrivial( 10980 ClassDecl->needsOverloadResolutionForMoveConstructor() 10981 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10982 : ClassDecl->hasTrivialMoveConstructor()); 10983 10984 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10985 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10986 SetDeclDeleted(MoveConstructor, ClassLoc); 10987 } 10988 10989 // Note that we have declared this constructor. 10990 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10991 10992 if (Scope *S = getScopeForContext(ClassDecl)) 10993 PushOnScopeChains(MoveConstructor, S, false); 10994 ClassDecl->addDecl(MoveConstructor); 10995 10996 return MoveConstructor; 10997 } 10998 10999 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 11000 CXXConstructorDecl *MoveConstructor) { 11001 assert((MoveConstructor->isDefaulted() && 11002 MoveConstructor->isMoveConstructor() && 11003 !MoveConstructor->doesThisDeclarationHaveABody() && 11004 !MoveConstructor->isDeleted()) && 11005 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 11006 11007 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 11008 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 11009 11010 SynthesizedFunctionScope Scope(*this, MoveConstructor); 11011 DiagnosticErrorTrap Trap(Diags); 11012 11013 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 11014 Trap.hasErrorOccurred()) { 11015 Diag(CurrentLocation, diag::note_member_synthesized_at) 11016 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 11017 MoveConstructor->setInvalidDecl(); 11018 } else { 11019 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 11020 ? MoveConstructor->getLocEnd() 11021 : MoveConstructor->getLocation(); 11022 Sema::CompoundScopeRAII CompoundScope(*this); 11023 MoveConstructor->setBody(ActOnCompoundStmt( 11024 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 11025 } 11026 11027 // The exception specification is needed because we are defining the 11028 // function. 11029 ResolveExceptionSpec(CurrentLocation, 11030 MoveConstructor->getType()->castAs<FunctionProtoType>()); 11031 11032 MoveConstructor->markUsed(Context); 11033 MarkVTableUsed(CurrentLocation, ClassDecl); 11034 11035 if (ASTMutationListener *L = getASTMutationListener()) { 11036 L->CompletedImplicitDefinition(MoveConstructor); 11037 } 11038 } 11039 11040 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 11041 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 11042 } 11043 11044 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 11045 SourceLocation CurrentLocation, 11046 CXXConversionDecl *Conv) { 11047 CXXRecordDecl *Lambda = Conv->getParent(); 11048 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 11049 // If we are defining a specialization of a conversion to function-ptr 11050 // cache the deduced template arguments for this specialization 11051 // so that we can use them to retrieve the corresponding call-operator 11052 // and static-invoker. 11053 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 11054 11055 // Retrieve the corresponding call-operator specialization. 11056 if (Lambda->isGenericLambda()) { 11057 assert(Conv->isFunctionTemplateSpecialization()); 11058 FunctionTemplateDecl *CallOpTemplate = 11059 CallOp->getDescribedFunctionTemplate(); 11060 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 11061 void *InsertPos = nullptr; 11062 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 11063 DeducedTemplateArgs->asArray(), 11064 InsertPos); 11065 assert(CallOpSpec && 11066 "Conversion operator must have a corresponding call operator"); 11067 CallOp = cast<CXXMethodDecl>(CallOpSpec); 11068 } 11069 // Mark the call operator referenced (and add to pending instantiations 11070 // if necessary). 11071 // For both the conversion and static-invoker template specializations 11072 // we construct their body's in this function, so no need to add them 11073 // to the PendingInstantiations. 11074 MarkFunctionReferenced(CurrentLocation, CallOp); 11075 11076 SynthesizedFunctionScope Scope(*this, Conv); 11077 DiagnosticErrorTrap Trap(Diags); 11078 11079 // Retrieve the static invoker... 11080 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 11081 // ... and get the corresponding specialization for a generic lambda. 11082 if (Lambda->isGenericLambda()) { 11083 assert(DeducedTemplateArgs && 11084 "Must have deduced template arguments from Conversion Operator"); 11085 FunctionTemplateDecl *InvokeTemplate = 11086 Invoker->getDescribedFunctionTemplate(); 11087 void *InsertPos = nullptr; 11088 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 11089 DeducedTemplateArgs->asArray(), 11090 InsertPos); 11091 assert(InvokeSpec && 11092 "Must have a corresponding static invoker specialization"); 11093 Invoker = cast<CXXMethodDecl>(InvokeSpec); 11094 } 11095 // Construct the body of the conversion function { return __invoke; }. 11096 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 11097 VK_LValue, Conv->getLocation()).get(); 11098 assert(FunctionRef && "Can't refer to __invoke function?"); 11099 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 11100 Conv->setBody(new (Context) CompoundStmt(Context, Return, 11101 Conv->getLocation(), 11102 Conv->getLocation())); 11103 11104 Conv->markUsed(Context); 11105 Conv->setReferenced(); 11106 11107 // Fill in the __invoke function with a dummy implementation. IR generation 11108 // will fill in the actual details. 11109 Invoker->markUsed(Context); 11110 Invoker->setReferenced(); 11111 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 11112 11113 if (ASTMutationListener *L = getASTMutationListener()) { 11114 L->CompletedImplicitDefinition(Conv); 11115 L->CompletedImplicitDefinition(Invoker); 11116 } 11117 } 11118 11119 11120 11121 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11122 SourceLocation CurrentLocation, 11123 CXXConversionDecl *Conv) 11124 { 11125 assert(!Conv->getParent()->isGenericLambda()); 11126 11127 Conv->markUsed(Context); 11128 11129 SynthesizedFunctionScope Scope(*this, Conv); 11130 DiagnosticErrorTrap Trap(Diags); 11131 11132 // Copy-initialize the lambda object as needed to capture it. 11133 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11134 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11135 11136 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11137 Conv->getLocation(), 11138 Conv, DerefThis); 11139 11140 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11141 // behavior. Note that only the general conversion function does this 11142 // (since it's unusable otherwise); in the case where we inline the 11143 // block literal, it has block literal lifetime semantics. 11144 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11145 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11146 CK_CopyAndAutoreleaseBlockObject, 11147 BuildBlock.get(), nullptr, VK_RValue); 11148 11149 if (BuildBlock.isInvalid()) { 11150 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11151 Conv->setInvalidDecl(); 11152 return; 11153 } 11154 11155 // Create the return statement that returns the block from the conversion 11156 // function. 11157 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11158 if (Return.isInvalid()) { 11159 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11160 Conv->setInvalidDecl(); 11161 return; 11162 } 11163 11164 // Set the body of the conversion function. 11165 Stmt *ReturnS = Return.get(); 11166 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11167 Conv->getLocation(), 11168 Conv->getLocation())); 11169 11170 // We're done; notify the mutation listener, if any. 11171 if (ASTMutationListener *L = getASTMutationListener()) { 11172 L->CompletedImplicitDefinition(Conv); 11173 } 11174 } 11175 11176 /// \brief Determine whether the given list arguments contains exactly one 11177 /// "real" (non-default) argument. 11178 static bool hasOneRealArgument(MultiExprArg Args) { 11179 switch (Args.size()) { 11180 case 0: 11181 return false; 11182 11183 default: 11184 if (!Args[1]->isDefaultArgument()) 11185 return false; 11186 11187 // fall through 11188 case 1: 11189 return !Args[0]->isDefaultArgument(); 11190 } 11191 11192 return false; 11193 } 11194 11195 ExprResult 11196 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11197 CXXConstructorDecl *Constructor, 11198 MultiExprArg ExprArgs, 11199 bool HadMultipleCandidates, 11200 bool IsListInitialization, 11201 bool IsStdInitListInitialization, 11202 bool RequiresZeroInit, 11203 unsigned ConstructKind, 11204 SourceRange ParenRange) { 11205 bool Elidable = false; 11206 11207 // C++0x [class.copy]p34: 11208 // When certain criteria are met, an implementation is allowed to 11209 // omit the copy/move construction of a class object, even if the 11210 // copy/move constructor and/or destructor for the object have 11211 // side effects. [...] 11212 // - when a temporary class object that has not been bound to a 11213 // reference (12.2) would be copied/moved to a class object 11214 // with the same cv-unqualified type, the copy/move operation 11215 // can be omitted by constructing the temporary object 11216 // directly into the target of the omitted copy/move 11217 if (ConstructKind == CXXConstructExpr::CK_Complete && 11218 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11219 Expr *SubExpr = ExprArgs[0]; 11220 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11221 } 11222 11223 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11224 Elidable, ExprArgs, HadMultipleCandidates, 11225 IsListInitialization, 11226 IsStdInitListInitialization, RequiresZeroInit, 11227 ConstructKind, ParenRange); 11228 } 11229 11230 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11231 /// including handling of its default argument expressions. 11232 ExprResult 11233 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11234 CXXConstructorDecl *Constructor, bool Elidable, 11235 MultiExprArg ExprArgs, 11236 bool HadMultipleCandidates, 11237 bool IsListInitialization, 11238 bool IsStdInitListInitialization, 11239 bool RequiresZeroInit, 11240 unsigned ConstructKind, 11241 SourceRange ParenRange) { 11242 MarkFunctionReferenced(ConstructLoc, Constructor); 11243 return CXXConstructExpr::Create( 11244 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11245 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11246 RequiresZeroInit, 11247 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11248 ParenRange); 11249 } 11250 11251 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11252 assert(Field->hasInClassInitializer()); 11253 11254 // If we already have the in-class initializer nothing needs to be done. 11255 if (Field->getInClassInitializer()) 11256 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11257 11258 // Maybe we haven't instantiated the in-class initializer. Go check the 11259 // pattern FieldDecl to see if it has one. 11260 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11261 11262 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11263 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11264 DeclContext::lookup_result Lookup = 11265 ClassPattern->lookup(Field->getDeclName()); 11266 assert(Lookup.size() == 1); 11267 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11268 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11269 getTemplateInstantiationArgs(Field))) 11270 return ExprError(); 11271 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11272 } 11273 11274 // DR1351: 11275 // If the brace-or-equal-initializer of a non-static data member 11276 // invokes a defaulted default constructor of its class or of an 11277 // enclosing class in a potentially evaluated subexpression, the 11278 // program is ill-formed. 11279 // 11280 // This resolution is unworkable: the exception specification of the 11281 // default constructor can be needed in an unevaluated context, in 11282 // particular, in the operand of a noexcept-expression, and we can be 11283 // unable to compute an exception specification for an enclosed class. 11284 // 11285 // Any attempt to resolve the exception specification of a defaulted default 11286 // constructor before the initializer is lexically complete will ultimately 11287 // come here at which point we can diagnose it. 11288 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11289 if (OutermostClass == ParentRD) { 11290 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11291 << ParentRD << Field; 11292 } else { 11293 Diag(Field->getLocEnd(), 11294 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11295 << ParentRD << OutermostClass << Field; 11296 } 11297 11298 return ExprError(); 11299 } 11300 11301 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11302 if (VD->isInvalidDecl()) return; 11303 11304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11305 if (ClassDecl->isInvalidDecl()) return; 11306 if (ClassDecl->hasIrrelevantDestructor()) return; 11307 if (ClassDecl->isDependentContext()) return; 11308 11309 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11310 MarkFunctionReferenced(VD->getLocation(), Destructor); 11311 CheckDestructorAccess(VD->getLocation(), Destructor, 11312 PDiag(diag::err_access_dtor_var) 11313 << VD->getDeclName() 11314 << VD->getType()); 11315 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11316 11317 if (Destructor->isTrivial()) return; 11318 if (!VD->hasGlobalStorage()) return; 11319 11320 // Emit warning for non-trivial dtor in global scope (a real global, 11321 // class-static, function-static). 11322 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11323 11324 // TODO: this should be re-enabled for static locals by !CXAAtExit 11325 if (!VD->isStaticLocal()) 11326 Diag(VD->getLocation(), diag::warn_global_destructor); 11327 } 11328 11329 /// \brief Given a constructor and the set of arguments provided for the 11330 /// constructor, convert the arguments and add any required default arguments 11331 /// to form a proper call to this constructor. 11332 /// 11333 /// \returns true if an error occurred, false otherwise. 11334 bool 11335 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11336 MultiExprArg ArgsPtr, 11337 SourceLocation Loc, 11338 SmallVectorImpl<Expr*> &ConvertedArgs, 11339 bool AllowExplicit, 11340 bool IsListInitialization) { 11341 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11342 unsigned NumArgs = ArgsPtr.size(); 11343 Expr **Args = ArgsPtr.data(); 11344 11345 const FunctionProtoType *Proto 11346 = Constructor->getType()->getAs<FunctionProtoType>(); 11347 assert(Proto && "Constructor without a prototype?"); 11348 unsigned NumParams = Proto->getNumParams(); 11349 11350 // If too few arguments are available, we'll fill in the rest with defaults. 11351 if (NumArgs < NumParams) 11352 ConvertedArgs.reserve(NumParams); 11353 else 11354 ConvertedArgs.reserve(NumArgs); 11355 11356 VariadicCallType CallType = 11357 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11358 SmallVector<Expr *, 8> AllArgs; 11359 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11360 Proto, 0, 11361 llvm::makeArrayRef(Args, NumArgs), 11362 AllArgs, 11363 CallType, AllowExplicit, 11364 IsListInitialization); 11365 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11366 11367 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11368 11369 CheckConstructorCall(Constructor, 11370 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11371 Proto, Loc); 11372 11373 return Invalid; 11374 } 11375 11376 static inline bool 11377 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11378 const FunctionDecl *FnDecl) { 11379 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11380 if (isa<NamespaceDecl>(DC)) { 11381 return SemaRef.Diag(FnDecl->getLocation(), 11382 diag::err_operator_new_delete_declared_in_namespace) 11383 << FnDecl->getDeclName(); 11384 } 11385 11386 if (isa<TranslationUnitDecl>(DC) && 11387 FnDecl->getStorageClass() == SC_Static) { 11388 return SemaRef.Diag(FnDecl->getLocation(), 11389 diag::err_operator_new_delete_declared_static) 11390 << FnDecl->getDeclName(); 11391 } 11392 11393 return false; 11394 } 11395 11396 static inline bool 11397 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11398 CanQualType ExpectedResultType, 11399 CanQualType ExpectedFirstParamType, 11400 unsigned DependentParamTypeDiag, 11401 unsigned InvalidParamTypeDiag) { 11402 QualType ResultType = 11403 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11404 11405 // Check that the result type is not dependent. 11406 if (ResultType->isDependentType()) 11407 return SemaRef.Diag(FnDecl->getLocation(), 11408 diag::err_operator_new_delete_dependent_result_type) 11409 << FnDecl->getDeclName() << ExpectedResultType; 11410 11411 // Check that the result type is what we expect. 11412 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11413 return SemaRef.Diag(FnDecl->getLocation(), 11414 diag::err_operator_new_delete_invalid_result_type) 11415 << FnDecl->getDeclName() << ExpectedResultType; 11416 11417 // A function template must have at least 2 parameters. 11418 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11419 return SemaRef.Diag(FnDecl->getLocation(), 11420 diag::err_operator_new_delete_template_too_few_parameters) 11421 << FnDecl->getDeclName(); 11422 11423 // The function decl must have at least 1 parameter. 11424 if (FnDecl->getNumParams() == 0) 11425 return SemaRef.Diag(FnDecl->getLocation(), 11426 diag::err_operator_new_delete_too_few_parameters) 11427 << FnDecl->getDeclName(); 11428 11429 // Check the first parameter type is not dependent. 11430 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11431 if (FirstParamType->isDependentType()) 11432 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11433 << FnDecl->getDeclName() << ExpectedFirstParamType; 11434 11435 // Check that the first parameter type is what we expect. 11436 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11437 ExpectedFirstParamType) 11438 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11439 << FnDecl->getDeclName() << ExpectedFirstParamType; 11440 11441 return false; 11442 } 11443 11444 static bool 11445 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11446 // C++ [basic.stc.dynamic.allocation]p1: 11447 // A program is ill-formed if an allocation function is declared in a 11448 // namespace scope other than global scope or declared static in global 11449 // scope. 11450 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11451 return true; 11452 11453 CanQualType SizeTy = 11454 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11455 11456 // C++ [basic.stc.dynamic.allocation]p1: 11457 // The return type shall be void*. The first parameter shall have type 11458 // std::size_t. 11459 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11460 SizeTy, 11461 diag::err_operator_new_dependent_param_type, 11462 diag::err_operator_new_param_type)) 11463 return true; 11464 11465 // C++ [basic.stc.dynamic.allocation]p1: 11466 // The first parameter shall not have an associated default argument. 11467 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11468 return SemaRef.Diag(FnDecl->getLocation(), 11469 diag::err_operator_new_default_arg) 11470 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11471 11472 return false; 11473 } 11474 11475 static bool 11476 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11477 // C++ [basic.stc.dynamic.deallocation]p1: 11478 // A program is ill-formed if deallocation functions are declared in a 11479 // namespace scope other than global scope or declared static in global 11480 // scope. 11481 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11482 return true; 11483 11484 // C++ [basic.stc.dynamic.deallocation]p2: 11485 // Each deallocation function shall return void and its first parameter 11486 // shall be void*. 11487 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11488 SemaRef.Context.VoidPtrTy, 11489 diag::err_operator_delete_dependent_param_type, 11490 diag::err_operator_delete_param_type)) 11491 return true; 11492 11493 return false; 11494 } 11495 11496 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11497 /// of this overloaded operator is well-formed. If so, returns false; 11498 /// otherwise, emits appropriate diagnostics and returns true. 11499 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11500 assert(FnDecl && FnDecl->isOverloadedOperator() && 11501 "Expected an overloaded operator declaration"); 11502 11503 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11504 11505 // C++ [over.oper]p5: 11506 // The allocation and deallocation functions, operator new, 11507 // operator new[], operator delete and operator delete[], are 11508 // described completely in 3.7.3. The attributes and restrictions 11509 // found in the rest of this subclause do not apply to them unless 11510 // explicitly stated in 3.7.3. 11511 if (Op == OO_Delete || Op == OO_Array_Delete) 11512 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11513 11514 if (Op == OO_New || Op == OO_Array_New) 11515 return CheckOperatorNewDeclaration(*this, FnDecl); 11516 11517 // C++ [over.oper]p6: 11518 // An operator function shall either be a non-static member 11519 // function or be a non-member function and have at least one 11520 // parameter whose type is a class, a reference to a class, an 11521 // enumeration, or a reference to an enumeration. 11522 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11523 if (MethodDecl->isStatic()) 11524 return Diag(FnDecl->getLocation(), 11525 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11526 } else { 11527 bool ClassOrEnumParam = false; 11528 for (auto Param : FnDecl->params()) { 11529 QualType ParamType = Param->getType().getNonReferenceType(); 11530 if (ParamType->isDependentType() || ParamType->isRecordType() || 11531 ParamType->isEnumeralType()) { 11532 ClassOrEnumParam = true; 11533 break; 11534 } 11535 } 11536 11537 if (!ClassOrEnumParam) 11538 return Diag(FnDecl->getLocation(), 11539 diag::err_operator_overload_needs_class_or_enum) 11540 << FnDecl->getDeclName(); 11541 } 11542 11543 // C++ [over.oper]p8: 11544 // An operator function cannot have default arguments (8.3.6), 11545 // except where explicitly stated below. 11546 // 11547 // Only the function-call operator allows default arguments 11548 // (C++ [over.call]p1). 11549 if (Op != OO_Call) { 11550 for (auto Param : FnDecl->params()) { 11551 if (Param->hasDefaultArg()) 11552 return Diag(Param->getLocation(), 11553 diag::err_operator_overload_default_arg) 11554 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11555 } 11556 } 11557 11558 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11559 { false, false, false } 11560 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11561 , { Unary, Binary, MemberOnly } 11562 #include "clang/Basic/OperatorKinds.def" 11563 }; 11564 11565 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11566 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11567 bool MustBeMemberOperator = OperatorUses[Op][2]; 11568 11569 // C++ [over.oper]p8: 11570 // [...] Operator functions cannot have more or fewer parameters 11571 // than the number required for the corresponding operator, as 11572 // described in the rest of this subclause. 11573 unsigned NumParams = FnDecl->getNumParams() 11574 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11575 if (Op != OO_Call && 11576 ((NumParams == 1 && !CanBeUnaryOperator) || 11577 (NumParams == 2 && !CanBeBinaryOperator) || 11578 (NumParams < 1) || (NumParams > 2))) { 11579 // We have the wrong number of parameters. 11580 unsigned ErrorKind; 11581 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11582 ErrorKind = 2; // 2 -> unary or binary. 11583 } else if (CanBeUnaryOperator) { 11584 ErrorKind = 0; // 0 -> unary 11585 } else { 11586 assert(CanBeBinaryOperator && 11587 "All non-call overloaded operators are unary or binary!"); 11588 ErrorKind = 1; // 1 -> binary 11589 } 11590 11591 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11592 << FnDecl->getDeclName() << NumParams << ErrorKind; 11593 } 11594 11595 // Overloaded operators other than operator() cannot be variadic. 11596 if (Op != OO_Call && 11597 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11598 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11599 << FnDecl->getDeclName(); 11600 } 11601 11602 // Some operators must be non-static member functions. 11603 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11604 return Diag(FnDecl->getLocation(), 11605 diag::err_operator_overload_must_be_member) 11606 << FnDecl->getDeclName(); 11607 } 11608 11609 // C++ [over.inc]p1: 11610 // The user-defined function called operator++ implements the 11611 // prefix and postfix ++ operator. If this function is a member 11612 // function with no parameters, or a non-member function with one 11613 // parameter of class or enumeration type, it defines the prefix 11614 // increment operator ++ for objects of that type. If the function 11615 // is a member function with one parameter (which shall be of type 11616 // int) or a non-member function with two parameters (the second 11617 // of which shall be of type int), it defines the postfix 11618 // increment operator ++ for objects of that type. 11619 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11620 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11621 QualType ParamType = LastParam->getType(); 11622 11623 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11624 !ParamType->isDependentType()) 11625 return Diag(LastParam->getLocation(), 11626 diag::err_operator_overload_post_incdec_must_be_int) 11627 << LastParam->getType() << (Op == OO_MinusMinus); 11628 } 11629 11630 return false; 11631 } 11632 11633 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11634 /// of this literal operator function is well-formed. If so, returns 11635 /// false; otherwise, emits appropriate diagnostics and returns true. 11636 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11637 if (isa<CXXMethodDecl>(FnDecl)) { 11638 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11639 << FnDecl->getDeclName(); 11640 return true; 11641 } 11642 11643 if (FnDecl->isExternC()) { 11644 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11645 return true; 11646 } 11647 11648 bool Valid = false; 11649 11650 // This might be the definition of a literal operator template. 11651 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11652 // This might be a specialization of a literal operator template. 11653 if (!TpDecl) 11654 TpDecl = FnDecl->getPrimaryTemplate(); 11655 11656 // template <char...> type operator "" name() and 11657 // template <class T, T...> type operator "" name() are the only valid 11658 // template signatures, and the only valid signatures with no parameters. 11659 if (TpDecl) { 11660 if (FnDecl->param_size() == 0) { 11661 // Must have one or two template parameters 11662 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11663 if (Params->size() == 1) { 11664 NonTypeTemplateParmDecl *PmDecl = 11665 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11666 11667 // The template parameter must be a char parameter pack. 11668 if (PmDecl && PmDecl->isTemplateParameterPack() && 11669 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11670 Valid = true; 11671 } else if (Params->size() == 2) { 11672 TemplateTypeParmDecl *PmType = 11673 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11674 NonTypeTemplateParmDecl *PmArgs = 11675 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11676 11677 // The second template parameter must be a parameter pack with the 11678 // first template parameter as its type. 11679 if (PmType && PmArgs && 11680 !PmType->isTemplateParameterPack() && 11681 PmArgs->isTemplateParameterPack()) { 11682 const TemplateTypeParmType *TArgs = 11683 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11684 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11685 TArgs->getIndex() == PmType->getIndex()) { 11686 Valid = true; 11687 if (ActiveTemplateInstantiations.empty()) 11688 Diag(FnDecl->getLocation(), 11689 diag::ext_string_literal_operator_template); 11690 } 11691 } 11692 } 11693 } 11694 } else if (FnDecl->param_size()) { 11695 // Check the first parameter 11696 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11697 11698 QualType T = (*Param)->getType().getUnqualifiedType(); 11699 11700 // unsigned long long int, long double, and any character type are allowed 11701 // as the only parameters. 11702 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11703 Context.hasSameType(T, Context.LongDoubleTy) || 11704 Context.hasSameType(T, Context.CharTy) || 11705 Context.hasSameType(T, Context.WideCharTy) || 11706 Context.hasSameType(T, Context.Char16Ty) || 11707 Context.hasSameType(T, Context.Char32Ty)) { 11708 if (++Param == FnDecl->param_end()) 11709 Valid = true; 11710 goto FinishedParams; 11711 } 11712 11713 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11714 const PointerType *PT = T->getAs<PointerType>(); 11715 if (!PT) 11716 goto FinishedParams; 11717 T = PT->getPointeeType(); 11718 if (!T.isConstQualified() || T.isVolatileQualified()) 11719 goto FinishedParams; 11720 T = T.getUnqualifiedType(); 11721 11722 // Move on to the second parameter; 11723 ++Param; 11724 11725 // If there is no second parameter, the first must be a const char * 11726 if (Param == FnDecl->param_end()) { 11727 if (Context.hasSameType(T, Context.CharTy)) 11728 Valid = true; 11729 goto FinishedParams; 11730 } 11731 11732 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11733 // are allowed as the first parameter to a two-parameter function 11734 if (!(Context.hasSameType(T, Context.CharTy) || 11735 Context.hasSameType(T, Context.WideCharTy) || 11736 Context.hasSameType(T, Context.Char16Ty) || 11737 Context.hasSameType(T, Context.Char32Ty))) 11738 goto FinishedParams; 11739 11740 // The second and final parameter must be an std::size_t 11741 T = (*Param)->getType().getUnqualifiedType(); 11742 if (Context.hasSameType(T, Context.getSizeType()) && 11743 ++Param == FnDecl->param_end()) 11744 Valid = true; 11745 } 11746 11747 // FIXME: This diagnostic is absolutely terrible. 11748 FinishedParams: 11749 if (!Valid) { 11750 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11751 << FnDecl->getDeclName(); 11752 return true; 11753 } 11754 11755 // A parameter-declaration-clause containing a default argument is not 11756 // equivalent to any of the permitted forms. 11757 for (auto Param : FnDecl->params()) { 11758 if (Param->hasDefaultArg()) { 11759 Diag(Param->getDefaultArgRange().getBegin(), 11760 diag::err_literal_operator_default_argument) 11761 << Param->getDefaultArgRange(); 11762 break; 11763 } 11764 } 11765 11766 StringRef LiteralName 11767 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11768 if (LiteralName[0] != '_') { 11769 // C++11 [usrlit.suffix]p1: 11770 // Literal suffix identifiers that do not start with an underscore 11771 // are reserved for future standardization. 11772 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11773 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11774 } 11775 11776 return false; 11777 } 11778 11779 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11780 /// linkage specification, including the language and (if present) 11781 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11782 /// language string literal. LBraceLoc, if valid, provides the location of 11783 /// the '{' brace. Otherwise, this linkage specification does not 11784 /// have any braces. 11785 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11786 Expr *LangStr, 11787 SourceLocation LBraceLoc) { 11788 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11789 if (!Lit->isAscii()) { 11790 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11791 << LangStr->getSourceRange(); 11792 return nullptr; 11793 } 11794 11795 StringRef Lang = Lit->getString(); 11796 LinkageSpecDecl::LanguageIDs Language; 11797 if (Lang == "C") 11798 Language = LinkageSpecDecl::lang_c; 11799 else if (Lang == "C++") 11800 Language = LinkageSpecDecl::lang_cxx; 11801 else { 11802 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11803 << LangStr->getSourceRange(); 11804 return nullptr; 11805 } 11806 11807 // FIXME: Add all the various semantics of linkage specifications 11808 11809 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11810 LangStr->getExprLoc(), Language, 11811 LBraceLoc.isValid()); 11812 CurContext->addDecl(D); 11813 PushDeclContext(S, D); 11814 return D; 11815 } 11816 11817 /// ActOnFinishLinkageSpecification - Complete the definition of 11818 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11819 /// valid, it's the position of the closing '}' brace in a linkage 11820 /// specification that uses braces. 11821 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11822 Decl *LinkageSpec, 11823 SourceLocation RBraceLoc) { 11824 if (RBraceLoc.isValid()) { 11825 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11826 LSDecl->setRBraceLoc(RBraceLoc); 11827 } 11828 PopDeclContext(); 11829 return LinkageSpec; 11830 } 11831 11832 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11833 AttributeList *AttrList, 11834 SourceLocation SemiLoc) { 11835 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11836 // Attribute declarations appertain to empty declaration so we handle 11837 // them here. 11838 if (AttrList) 11839 ProcessDeclAttributeList(S, ED, AttrList); 11840 11841 CurContext->addDecl(ED); 11842 return ED; 11843 } 11844 11845 /// \brief Perform semantic analysis for the variable declaration that 11846 /// occurs within a C++ catch clause, returning the newly-created 11847 /// variable. 11848 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11849 TypeSourceInfo *TInfo, 11850 SourceLocation StartLoc, 11851 SourceLocation Loc, 11852 IdentifierInfo *Name) { 11853 bool Invalid = false; 11854 QualType ExDeclType = TInfo->getType(); 11855 11856 // Arrays and functions decay. 11857 if (ExDeclType->isArrayType()) 11858 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11859 else if (ExDeclType->isFunctionType()) 11860 ExDeclType = Context.getPointerType(ExDeclType); 11861 11862 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11863 // The exception-declaration shall not denote a pointer or reference to an 11864 // incomplete type, other than [cv] void*. 11865 // N2844 forbids rvalue references. 11866 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11867 Diag(Loc, diag::err_catch_rvalue_ref); 11868 Invalid = true; 11869 } 11870 11871 QualType BaseType = ExDeclType; 11872 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11873 unsigned DK = diag::err_catch_incomplete; 11874 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11875 BaseType = Ptr->getPointeeType(); 11876 Mode = 1; 11877 DK = diag::err_catch_incomplete_ptr; 11878 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11879 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11880 BaseType = Ref->getPointeeType(); 11881 Mode = 2; 11882 DK = diag::err_catch_incomplete_ref; 11883 } 11884 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11885 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11886 Invalid = true; 11887 11888 if (!Invalid && !ExDeclType->isDependentType() && 11889 RequireNonAbstractType(Loc, ExDeclType, 11890 diag::err_abstract_type_in_decl, 11891 AbstractVariableType)) 11892 Invalid = true; 11893 11894 // Only the non-fragile NeXT runtime currently supports C++ catches 11895 // of ObjC types, and no runtime supports catching ObjC types by value. 11896 if (!Invalid && getLangOpts().ObjC1) { 11897 QualType T = ExDeclType; 11898 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11899 T = RT->getPointeeType(); 11900 11901 if (T->isObjCObjectType()) { 11902 Diag(Loc, diag::err_objc_object_catch); 11903 Invalid = true; 11904 } else if (T->isObjCObjectPointerType()) { 11905 // FIXME: should this be a test for macosx-fragile specifically? 11906 if (getLangOpts().ObjCRuntime.isFragile()) 11907 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11908 } 11909 } 11910 11911 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11912 ExDeclType, TInfo, SC_None); 11913 ExDecl->setExceptionVariable(true); 11914 11915 // In ARC, infer 'retaining' for variables of retainable type. 11916 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11917 Invalid = true; 11918 11919 if (!Invalid && !ExDeclType->isDependentType()) { 11920 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11921 // Insulate this from anything else we might currently be parsing. 11922 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11923 11924 // C++ [except.handle]p16: 11925 // The object declared in an exception-declaration or, if the 11926 // exception-declaration does not specify a name, a temporary (12.2) is 11927 // copy-initialized (8.5) from the exception object. [...] 11928 // The object is destroyed when the handler exits, after the destruction 11929 // of any automatic objects initialized within the handler. 11930 // 11931 // We just pretend to initialize the object with itself, then make sure 11932 // it can be destroyed later. 11933 QualType initType = ExDeclType; 11934 11935 InitializedEntity entity = 11936 InitializedEntity::InitializeVariable(ExDecl); 11937 InitializationKind initKind = 11938 InitializationKind::CreateCopy(Loc, SourceLocation()); 11939 11940 Expr *opaqueValue = 11941 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11942 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11943 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11944 if (result.isInvalid()) 11945 Invalid = true; 11946 else { 11947 // If the constructor used was non-trivial, set this as the 11948 // "initializer". 11949 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11950 if (!construct->getConstructor()->isTrivial()) { 11951 Expr *init = MaybeCreateExprWithCleanups(construct); 11952 ExDecl->setInit(init); 11953 } 11954 11955 // And make sure it's destructable. 11956 FinalizeVarWithDestructor(ExDecl, recordType); 11957 } 11958 } 11959 } 11960 11961 if (Invalid) 11962 ExDecl->setInvalidDecl(); 11963 11964 return ExDecl; 11965 } 11966 11967 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11968 /// handler. 11969 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11970 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11971 bool Invalid = D.isInvalidType(); 11972 11973 // Check for unexpanded parameter packs. 11974 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11975 UPPC_ExceptionType)) { 11976 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11977 D.getIdentifierLoc()); 11978 Invalid = true; 11979 } 11980 11981 IdentifierInfo *II = D.getIdentifier(); 11982 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11983 LookupOrdinaryName, 11984 ForRedeclaration)) { 11985 // The scope should be freshly made just for us. There is just no way 11986 // it contains any previous declaration, except for function parameters in 11987 // a function-try-block's catch statement. 11988 assert(!S->isDeclScope(PrevDecl)); 11989 if (isDeclInScope(PrevDecl, CurContext, S)) { 11990 Diag(D.getIdentifierLoc(), diag::err_redefinition) 11991 << D.getIdentifier(); 11992 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11993 Invalid = true; 11994 } else if (PrevDecl->isTemplateParameter()) 11995 // Maybe we will complain about the shadowed template parameter. 11996 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11997 } 11998 11999 if (D.getCXXScopeSpec().isSet() && !Invalid) { 12000 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 12001 << D.getCXXScopeSpec().getRange(); 12002 Invalid = true; 12003 } 12004 12005 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 12006 D.getLocStart(), 12007 D.getIdentifierLoc(), 12008 D.getIdentifier()); 12009 if (Invalid) 12010 ExDecl->setInvalidDecl(); 12011 12012 // Add the exception declaration into this scope. 12013 if (II) 12014 PushOnScopeChains(ExDecl, S); 12015 else 12016 CurContext->addDecl(ExDecl); 12017 12018 ProcessDeclAttributes(S, ExDecl, D); 12019 return ExDecl; 12020 } 12021 12022 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12023 Expr *AssertExpr, 12024 Expr *AssertMessageExpr, 12025 SourceLocation RParenLoc) { 12026 StringLiteral *AssertMessage = 12027 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 12028 12029 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 12030 return nullptr; 12031 12032 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 12033 AssertMessage, RParenLoc, false); 12034 } 12035 12036 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12037 Expr *AssertExpr, 12038 StringLiteral *AssertMessage, 12039 SourceLocation RParenLoc, 12040 bool Failed) { 12041 assert(AssertExpr != nullptr && "Expected non-null condition"); 12042 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 12043 !Failed) { 12044 // In a static_assert-declaration, the constant-expression shall be a 12045 // constant expression that can be contextually converted to bool. 12046 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 12047 if (Converted.isInvalid()) 12048 Failed = true; 12049 12050 llvm::APSInt Cond; 12051 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 12052 diag::err_static_assert_expression_is_not_constant, 12053 /*AllowFold=*/false).isInvalid()) 12054 Failed = true; 12055 12056 if (!Failed && !Cond) { 12057 SmallString<256> MsgBuffer; 12058 llvm::raw_svector_ostream Msg(MsgBuffer); 12059 if (AssertMessage) 12060 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 12061 Diag(StaticAssertLoc, diag::err_static_assert_failed) 12062 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 12063 Failed = true; 12064 } 12065 } 12066 12067 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 12068 AssertExpr, AssertMessage, RParenLoc, 12069 Failed); 12070 12071 CurContext->addDecl(Decl); 12072 return Decl; 12073 } 12074 12075 /// \brief Perform semantic analysis of the given friend type declaration. 12076 /// 12077 /// \returns A friend declaration that. 12078 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 12079 SourceLocation FriendLoc, 12080 TypeSourceInfo *TSInfo) { 12081 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 12082 12083 QualType T = TSInfo->getType(); 12084 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 12085 12086 // C++03 [class.friend]p2: 12087 // An elaborated-type-specifier shall be used in a friend declaration 12088 // for a class.* 12089 // 12090 // * The class-key of the elaborated-type-specifier is required. 12091 if (!ActiveTemplateInstantiations.empty()) { 12092 // Do not complain about the form of friend template types during 12093 // template instantiation; we will already have complained when the 12094 // template was declared. 12095 } else { 12096 if (!T->isElaboratedTypeSpecifier()) { 12097 // If we evaluated the type to a record type, suggest putting 12098 // a tag in front. 12099 if (const RecordType *RT = T->getAs<RecordType>()) { 12100 RecordDecl *RD = RT->getDecl(); 12101 12102 SmallString<16> InsertionText(" "); 12103 InsertionText += RD->getKindName(); 12104 12105 Diag(TypeRange.getBegin(), 12106 getLangOpts().CPlusPlus11 ? 12107 diag::warn_cxx98_compat_unelaborated_friend_type : 12108 diag::ext_unelaborated_friend_type) 12109 << (unsigned) RD->getTagKind() 12110 << T 12111 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 12112 InsertionText); 12113 } else { 12114 Diag(FriendLoc, 12115 getLangOpts().CPlusPlus11 ? 12116 diag::warn_cxx98_compat_nonclass_type_friend : 12117 diag::ext_nonclass_type_friend) 12118 << T 12119 << TypeRange; 12120 } 12121 } else if (T->getAs<EnumType>()) { 12122 Diag(FriendLoc, 12123 getLangOpts().CPlusPlus11 ? 12124 diag::warn_cxx98_compat_enum_friend : 12125 diag::ext_enum_friend) 12126 << T 12127 << TypeRange; 12128 } 12129 12130 // C++11 [class.friend]p3: 12131 // A friend declaration that does not declare a function shall have one 12132 // of the following forms: 12133 // friend elaborated-type-specifier ; 12134 // friend simple-type-specifier ; 12135 // friend typename-specifier ; 12136 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12137 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12138 } 12139 12140 // If the type specifier in a friend declaration designates a (possibly 12141 // cv-qualified) class type, that class is declared as a friend; otherwise, 12142 // the friend declaration is ignored. 12143 return FriendDecl::Create(Context, CurContext, 12144 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12145 FriendLoc); 12146 } 12147 12148 /// Handle a friend tag declaration where the scope specifier was 12149 /// templated. 12150 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12151 unsigned TagSpec, SourceLocation TagLoc, 12152 CXXScopeSpec &SS, 12153 IdentifierInfo *Name, 12154 SourceLocation NameLoc, 12155 AttributeList *Attr, 12156 MultiTemplateParamsArg TempParamLists) { 12157 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12158 12159 bool isExplicitSpecialization = false; 12160 bool Invalid = false; 12161 12162 if (TemplateParameterList *TemplateParams = 12163 MatchTemplateParametersToScopeSpecifier( 12164 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12165 isExplicitSpecialization, Invalid)) { 12166 if (TemplateParams->size() > 0) { 12167 // This is a declaration of a class template. 12168 if (Invalid) 12169 return nullptr; 12170 12171 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12172 NameLoc, Attr, TemplateParams, AS_public, 12173 /*ModulePrivateLoc=*/SourceLocation(), 12174 FriendLoc, TempParamLists.size() - 1, 12175 TempParamLists.data()).get(); 12176 } else { 12177 // The "template<>" header is extraneous. 12178 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12179 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12180 isExplicitSpecialization = true; 12181 } 12182 } 12183 12184 if (Invalid) return nullptr; 12185 12186 bool isAllExplicitSpecializations = true; 12187 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12188 if (TempParamLists[I]->size()) { 12189 isAllExplicitSpecializations = false; 12190 break; 12191 } 12192 } 12193 12194 // FIXME: don't ignore attributes. 12195 12196 // If it's explicit specializations all the way down, just forget 12197 // about the template header and build an appropriate non-templated 12198 // friend. TODO: for source fidelity, remember the headers. 12199 if (isAllExplicitSpecializations) { 12200 if (SS.isEmpty()) { 12201 bool Owned = false; 12202 bool IsDependent = false; 12203 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12204 Attr, AS_public, 12205 /*ModulePrivateLoc=*/SourceLocation(), 12206 MultiTemplateParamsArg(), Owned, IsDependent, 12207 /*ScopedEnumKWLoc=*/SourceLocation(), 12208 /*ScopedEnumUsesClassTag=*/false, 12209 /*UnderlyingType=*/TypeResult(), 12210 /*IsTypeSpecifier=*/false); 12211 } 12212 12213 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12214 ElaboratedTypeKeyword Keyword 12215 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12216 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12217 *Name, NameLoc); 12218 if (T.isNull()) 12219 return nullptr; 12220 12221 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12222 if (isa<DependentNameType>(T)) { 12223 DependentNameTypeLoc TL = 12224 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12225 TL.setElaboratedKeywordLoc(TagLoc); 12226 TL.setQualifierLoc(QualifierLoc); 12227 TL.setNameLoc(NameLoc); 12228 } else { 12229 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12230 TL.setElaboratedKeywordLoc(TagLoc); 12231 TL.setQualifierLoc(QualifierLoc); 12232 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12233 } 12234 12235 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12236 TSI, FriendLoc, TempParamLists); 12237 Friend->setAccess(AS_public); 12238 CurContext->addDecl(Friend); 12239 return Friend; 12240 } 12241 12242 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12243 12244 12245 12246 // Handle the case of a templated-scope friend class. e.g. 12247 // template <class T> class A<T>::B; 12248 // FIXME: we don't support these right now. 12249 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12250 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12251 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12252 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12253 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12254 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12255 TL.setElaboratedKeywordLoc(TagLoc); 12256 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12257 TL.setNameLoc(NameLoc); 12258 12259 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12260 TSI, FriendLoc, TempParamLists); 12261 Friend->setAccess(AS_public); 12262 Friend->setUnsupportedFriend(true); 12263 CurContext->addDecl(Friend); 12264 return Friend; 12265 } 12266 12267 12268 /// Handle a friend type declaration. This works in tandem with 12269 /// ActOnTag. 12270 /// 12271 /// Notes on friend class templates: 12272 /// 12273 /// We generally treat friend class declarations as if they were 12274 /// declaring a class. So, for example, the elaborated type specifier 12275 /// in a friend declaration is required to obey the restrictions of a 12276 /// class-head (i.e. no typedefs in the scope chain), template 12277 /// parameters are required to match up with simple template-ids, &c. 12278 /// However, unlike when declaring a template specialization, it's 12279 /// okay to refer to a template specialization without an empty 12280 /// template parameter declaration, e.g. 12281 /// friend class A<T>::B<unsigned>; 12282 /// We permit this as a special case; if there are any template 12283 /// parameters present at all, require proper matching, i.e. 12284 /// template <> template \<class T> friend class A<int>::B; 12285 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12286 MultiTemplateParamsArg TempParams) { 12287 SourceLocation Loc = DS.getLocStart(); 12288 12289 assert(DS.isFriendSpecified()); 12290 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12291 12292 // Try to convert the decl specifier to a type. This works for 12293 // friend templates because ActOnTag never produces a ClassTemplateDecl 12294 // for a TUK_Friend. 12295 Declarator TheDeclarator(DS, Declarator::MemberContext); 12296 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12297 QualType T = TSI->getType(); 12298 if (TheDeclarator.isInvalidType()) 12299 return nullptr; 12300 12301 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12302 return nullptr; 12303 12304 // This is definitely an error in C++98. It's probably meant to 12305 // be forbidden in C++0x, too, but the specification is just 12306 // poorly written. 12307 // 12308 // The problem is with declarations like the following: 12309 // template <T> friend A<T>::foo; 12310 // where deciding whether a class C is a friend or not now hinges 12311 // on whether there exists an instantiation of A that causes 12312 // 'foo' to equal C. There are restrictions on class-heads 12313 // (which we declare (by fiat) elaborated friend declarations to 12314 // be) that makes this tractable. 12315 // 12316 // FIXME: handle "template <> friend class A<T>;", which 12317 // is possibly well-formed? Who even knows? 12318 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12319 Diag(Loc, diag::err_tagless_friend_type_template) 12320 << DS.getSourceRange(); 12321 return nullptr; 12322 } 12323 12324 // C++98 [class.friend]p1: A friend of a class is a function 12325 // or class that is not a member of the class . . . 12326 // This is fixed in DR77, which just barely didn't make the C++03 12327 // deadline. It's also a very silly restriction that seriously 12328 // affects inner classes and which nobody else seems to implement; 12329 // thus we never diagnose it, not even in -pedantic. 12330 // 12331 // But note that we could warn about it: it's always useless to 12332 // friend one of your own members (it's not, however, worthless to 12333 // friend a member of an arbitrary specialization of your template). 12334 12335 Decl *D; 12336 if (unsigned NumTempParamLists = TempParams.size()) 12337 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12338 NumTempParamLists, 12339 TempParams.data(), 12340 TSI, 12341 DS.getFriendSpecLoc()); 12342 else 12343 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12344 12345 if (!D) 12346 return nullptr; 12347 12348 D->setAccess(AS_public); 12349 CurContext->addDecl(D); 12350 12351 return D; 12352 } 12353 12354 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12355 MultiTemplateParamsArg TemplateParams) { 12356 const DeclSpec &DS = D.getDeclSpec(); 12357 12358 assert(DS.isFriendSpecified()); 12359 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12360 12361 SourceLocation Loc = D.getIdentifierLoc(); 12362 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12363 12364 // C++ [class.friend]p1 12365 // A friend of a class is a function or class.... 12366 // Note that this sees through typedefs, which is intended. 12367 // It *doesn't* see through dependent types, which is correct 12368 // according to [temp.arg.type]p3: 12369 // If a declaration acquires a function type through a 12370 // type dependent on a template-parameter and this causes 12371 // a declaration that does not use the syntactic form of a 12372 // function declarator to have a function type, the program 12373 // is ill-formed. 12374 if (!TInfo->getType()->isFunctionType()) { 12375 Diag(Loc, diag::err_unexpected_friend); 12376 12377 // It might be worthwhile to try to recover by creating an 12378 // appropriate declaration. 12379 return nullptr; 12380 } 12381 12382 // C++ [namespace.memdef]p3 12383 // - If a friend declaration in a non-local class first declares a 12384 // class or function, the friend class or function is a member 12385 // of the innermost enclosing namespace. 12386 // - The name of the friend is not found by simple name lookup 12387 // until a matching declaration is provided in that namespace 12388 // scope (either before or after the class declaration granting 12389 // friendship). 12390 // - If a friend function is called, its name may be found by the 12391 // name lookup that considers functions from namespaces and 12392 // classes associated with the types of the function arguments. 12393 // - When looking for a prior declaration of a class or a function 12394 // declared as a friend, scopes outside the innermost enclosing 12395 // namespace scope are not considered. 12396 12397 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12398 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12399 DeclarationName Name = NameInfo.getName(); 12400 assert(Name); 12401 12402 // Check for unexpanded parameter packs. 12403 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12404 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12405 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12406 return nullptr; 12407 12408 // The context we found the declaration in, or in which we should 12409 // create the declaration. 12410 DeclContext *DC; 12411 Scope *DCScope = S; 12412 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12413 ForRedeclaration); 12414 12415 // There are five cases here. 12416 // - There's no scope specifier and we're in a local class. Only look 12417 // for functions declared in the immediately-enclosing block scope. 12418 // We recover from invalid scope qualifiers as if they just weren't there. 12419 FunctionDecl *FunctionContainingLocalClass = nullptr; 12420 if ((SS.isInvalid() || !SS.isSet()) && 12421 (FunctionContainingLocalClass = 12422 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12423 // C++11 [class.friend]p11: 12424 // If a friend declaration appears in a local class and the name 12425 // specified is an unqualified name, a prior declaration is 12426 // looked up without considering scopes that are outside the 12427 // innermost enclosing non-class scope. For a friend function 12428 // declaration, if there is no prior declaration, the program is 12429 // ill-formed. 12430 12431 // Find the innermost enclosing non-class scope. This is the block 12432 // scope containing the local class definition (or for a nested class, 12433 // the outer local class). 12434 DCScope = S->getFnParent(); 12435 12436 // Look up the function name in the scope. 12437 Previous.clear(LookupLocalFriendName); 12438 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12439 12440 if (!Previous.empty()) { 12441 // All possible previous declarations must have the same context: 12442 // either they were declared at block scope or they are members of 12443 // one of the enclosing local classes. 12444 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12445 } else { 12446 // This is ill-formed, but provide the context that we would have 12447 // declared the function in, if we were permitted to, for error recovery. 12448 DC = FunctionContainingLocalClass; 12449 } 12450 adjustContextForLocalExternDecl(DC); 12451 12452 // C++ [class.friend]p6: 12453 // A function can be defined in a friend declaration of a class if and 12454 // only if the class is a non-local class (9.8), the function name is 12455 // unqualified, and the function has namespace scope. 12456 if (D.isFunctionDefinition()) { 12457 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12458 } 12459 12460 // - There's no scope specifier, in which case we just go to the 12461 // appropriate scope and look for a function or function template 12462 // there as appropriate. 12463 } else if (SS.isInvalid() || !SS.isSet()) { 12464 // C++11 [namespace.memdef]p3: 12465 // If the name in a friend declaration is neither qualified nor 12466 // a template-id and the declaration is a function or an 12467 // elaborated-type-specifier, the lookup to determine whether 12468 // the entity has been previously declared shall not consider 12469 // any scopes outside the innermost enclosing namespace. 12470 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12471 12472 // Find the appropriate context according to the above. 12473 DC = CurContext; 12474 12475 // Skip class contexts. If someone can cite chapter and verse 12476 // for this behavior, that would be nice --- it's what GCC and 12477 // EDG do, and it seems like a reasonable intent, but the spec 12478 // really only says that checks for unqualified existing 12479 // declarations should stop at the nearest enclosing namespace, 12480 // not that they should only consider the nearest enclosing 12481 // namespace. 12482 while (DC->isRecord()) 12483 DC = DC->getParent(); 12484 12485 DeclContext *LookupDC = DC; 12486 while (LookupDC->isTransparentContext()) 12487 LookupDC = LookupDC->getParent(); 12488 12489 while (true) { 12490 LookupQualifiedName(Previous, LookupDC); 12491 12492 if (!Previous.empty()) { 12493 DC = LookupDC; 12494 break; 12495 } 12496 12497 if (isTemplateId) { 12498 if (isa<TranslationUnitDecl>(LookupDC)) break; 12499 } else { 12500 if (LookupDC->isFileContext()) break; 12501 } 12502 LookupDC = LookupDC->getParent(); 12503 } 12504 12505 DCScope = getScopeForDeclContext(S, DC); 12506 12507 // - There's a non-dependent scope specifier, in which case we 12508 // compute it and do a previous lookup there for a function 12509 // or function template. 12510 } else if (!SS.getScopeRep()->isDependent()) { 12511 DC = computeDeclContext(SS); 12512 if (!DC) return nullptr; 12513 12514 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12515 12516 LookupQualifiedName(Previous, DC); 12517 12518 // Ignore things found implicitly in the wrong scope. 12519 // TODO: better diagnostics for this case. Suggesting the right 12520 // qualified scope would be nice... 12521 LookupResult::Filter F = Previous.makeFilter(); 12522 while (F.hasNext()) { 12523 NamedDecl *D = F.next(); 12524 if (!DC->InEnclosingNamespaceSetOf( 12525 D->getDeclContext()->getRedeclContext())) 12526 F.erase(); 12527 } 12528 F.done(); 12529 12530 if (Previous.empty()) { 12531 D.setInvalidType(); 12532 Diag(Loc, diag::err_qualified_friend_not_found) 12533 << Name << TInfo->getType(); 12534 return nullptr; 12535 } 12536 12537 // C++ [class.friend]p1: A friend of a class is a function or 12538 // class that is not a member of the class . . . 12539 if (DC->Equals(CurContext)) 12540 Diag(DS.getFriendSpecLoc(), 12541 getLangOpts().CPlusPlus11 ? 12542 diag::warn_cxx98_compat_friend_is_member : 12543 diag::err_friend_is_member); 12544 12545 if (D.isFunctionDefinition()) { 12546 // C++ [class.friend]p6: 12547 // A function can be defined in a friend declaration of a class if and 12548 // only if the class is a non-local class (9.8), the function name is 12549 // unqualified, and the function has namespace scope. 12550 SemaDiagnosticBuilder DB 12551 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12552 12553 DB << SS.getScopeRep(); 12554 if (DC->isFileContext()) 12555 DB << FixItHint::CreateRemoval(SS.getRange()); 12556 SS.clear(); 12557 } 12558 12559 // - There's a scope specifier that does not match any template 12560 // parameter lists, in which case we use some arbitrary context, 12561 // create a method or method template, and wait for instantiation. 12562 // - There's a scope specifier that does match some template 12563 // parameter lists, which we don't handle right now. 12564 } else { 12565 if (D.isFunctionDefinition()) { 12566 // C++ [class.friend]p6: 12567 // A function can be defined in a friend declaration of a class if and 12568 // only if the class is a non-local class (9.8), the function name is 12569 // unqualified, and the function has namespace scope. 12570 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12571 << SS.getScopeRep(); 12572 } 12573 12574 DC = CurContext; 12575 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12576 } 12577 12578 if (!DC->isRecord()) { 12579 // This implies that it has to be an operator or function. 12580 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12581 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12582 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12583 Diag(Loc, diag::err_introducing_special_friend) << 12584 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12585 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12586 return nullptr; 12587 } 12588 } 12589 12590 // FIXME: This is an egregious hack to cope with cases where the scope stack 12591 // does not contain the declaration context, i.e., in an out-of-line 12592 // definition of a class. 12593 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12594 if (!DCScope) { 12595 FakeDCScope.setEntity(DC); 12596 DCScope = &FakeDCScope; 12597 } 12598 12599 bool AddToScope = true; 12600 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12601 TemplateParams, AddToScope); 12602 if (!ND) return nullptr; 12603 12604 assert(ND->getLexicalDeclContext() == CurContext); 12605 12606 // If we performed typo correction, we might have added a scope specifier 12607 // and changed the decl context. 12608 DC = ND->getDeclContext(); 12609 12610 // Add the function declaration to the appropriate lookup tables, 12611 // adjusting the redeclarations list as necessary. We don't 12612 // want to do this yet if the friending class is dependent. 12613 // 12614 // Also update the scope-based lookup if the target context's 12615 // lookup context is in lexical scope. 12616 if (!CurContext->isDependentContext()) { 12617 DC = DC->getRedeclContext(); 12618 DC->makeDeclVisibleInContext(ND); 12619 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12620 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12621 } 12622 12623 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12624 D.getIdentifierLoc(), ND, 12625 DS.getFriendSpecLoc()); 12626 FrD->setAccess(AS_public); 12627 CurContext->addDecl(FrD); 12628 12629 if (ND->isInvalidDecl()) { 12630 FrD->setInvalidDecl(); 12631 } else { 12632 if (DC->isRecord()) CheckFriendAccess(ND); 12633 12634 FunctionDecl *FD; 12635 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12636 FD = FTD->getTemplatedDecl(); 12637 else 12638 FD = cast<FunctionDecl>(ND); 12639 12640 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12641 // default argument expression, that declaration shall be a definition 12642 // and shall be the only declaration of the function or function 12643 // template in the translation unit. 12644 if (functionDeclHasDefaultArgument(FD)) { 12645 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12646 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12647 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12648 } else if (!D.isFunctionDefinition()) 12649 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12650 } 12651 12652 // Mark templated-scope function declarations as unsupported. 12653 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12654 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12655 << SS.getScopeRep() << SS.getRange() 12656 << cast<CXXRecordDecl>(CurContext); 12657 FrD->setUnsupportedFriend(true); 12658 } 12659 } 12660 12661 return ND; 12662 } 12663 12664 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12665 AdjustDeclIfTemplate(Dcl); 12666 12667 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12668 if (!Fn) { 12669 Diag(DelLoc, diag::err_deleted_non_function); 12670 return; 12671 } 12672 12673 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12674 // Don't consider the implicit declaration we generate for explicit 12675 // specializations. FIXME: Do not generate these implicit declarations. 12676 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12677 Prev->getPreviousDecl()) && 12678 !Prev->isDefined()) { 12679 Diag(DelLoc, diag::err_deleted_decl_not_first); 12680 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12681 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12682 : diag::note_previous_declaration); 12683 } 12684 // If the declaration wasn't the first, we delete the function anyway for 12685 // recovery. 12686 Fn = Fn->getCanonicalDecl(); 12687 } 12688 12689 // dllimport/dllexport cannot be deleted. 12690 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12691 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12692 Fn->setInvalidDecl(); 12693 } 12694 12695 if (Fn->isDeleted()) 12696 return; 12697 12698 // See if we're deleting a function which is already known to override a 12699 // non-deleted virtual function. 12700 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12701 bool IssuedDiagnostic = false; 12702 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12703 E = MD->end_overridden_methods(); 12704 I != E; ++I) { 12705 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12706 if (!IssuedDiagnostic) { 12707 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12708 IssuedDiagnostic = true; 12709 } 12710 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12711 } 12712 } 12713 } 12714 12715 // C++11 [basic.start.main]p3: 12716 // A program that defines main as deleted [...] is ill-formed. 12717 if (Fn->isMain()) 12718 Diag(DelLoc, diag::err_deleted_main); 12719 12720 Fn->setDeletedAsWritten(); 12721 } 12722 12723 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12724 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12725 12726 if (MD) { 12727 if (MD->getParent()->isDependentType()) { 12728 MD->setDefaulted(); 12729 MD->setExplicitlyDefaulted(); 12730 return; 12731 } 12732 12733 CXXSpecialMember Member = getSpecialMember(MD); 12734 if (Member == CXXInvalid) { 12735 if (!MD->isInvalidDecl()) 12736 Diag(DefaultLoc, diag::err_default_special_members); 12737 return; 12738 } 12739 12740 MD->setDefaulted(); 12741 MD->setExplicitlyDefaulted(); 12742 12743 // If this definition appears within the record, do the checking when 12744 // the record is complete. 12745 const FunctionDecl *Primary = MD; 12746 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12747 // Find the uninstantiated declaration that actually had the '= default' 12748 // on it. 12749 Pattern->isDefined(Primary); 12750 12751 // If the method was defaulted on its first declaration, we will have 12752 // already performed the checking in CheckCompletedCXXClass. Such a 12753 // declaration doesn't trigger an implicit definition. 12754 if (Primary == Primary->getCanonicalDecl()) 12755 return; 12756 12757 CheckExplicitlyDefaultedSpecialMember(MD); 12758 12759 if (MD->isInvalidDecl()) 12760 return; 12761 12762 switch (Member) { 12763 case CXXDefaultConstructor: 12764 DefineImplicitDefaultConstructor(DefaultLoc, 12765 cast<CXXConstructorDecl>(MD)); 12766 break; 12767 case CXXCopyConstructor: 12768 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12769 break; 12770 case CXXCopyAssignment: 12771 DefineImplicitCopyAssignment(DefaultLoc, MD); 12772 break; 12773 case CXXDestructor: 12774 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12775 break; 12776 case CXXMoveConstructor: 12777 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12778 break; 12779 case CXXMoveAssignment: 12780 DefineImplicitMoveAssignment(DefaultLoc, MD); 12781 break; 12782 case CXXInvalid: 12783 llvm_unreachable("Invalid special member."); 12784 } 12785 } else { 12786 Diag(DefaultLoc, diag::err_default_special_members); 12787 } 12788 } 12789 12790 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12791 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12792 Stmt *SubStmt = *CI; 12793 if (!SubStmt) 12794 continue; 12795 if (isa<ReturnStmt>(SubStmt)) 12796 Self.Diag(SubStmt->getLocStart(), 12797 diag::err_return_in_constructor_handler); 12798 if (!isa<Expr>(SubStmt)) 12799 SearchForReturnInStmt(Self, SubStmt); 12800 } 12801 } 12802 12803 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12804 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12805 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12806 SearchForReturnInStmt(*this, Handler); 12807 } 12808 } 12809 12810 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12811 const CXXMethodDecl *Old) { 12812 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12813 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12814 12815 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12816 12817 // If the calling conventions match, everything is fine 12818 if (NewCC == OldCC) 12819 return false; 12820 12821 // If the calling conventions mismatch because the new function is static, 12822 // suppress the calling convention mismatch error; the error about static 12823 // function override (err_static_overrides_virtual from 12824 // Sema::CheckFunctionDeclaration) is more clear. 12825 if (New->getStorageClass() == SC_Static) 12826 return false; 12827 12828 Diag(New->getLocation(), 12829 diag::err_conflicting_overriding_cc_attributes) 12830 << New->getDeclName() << New->getType() << Old->getType(); 12831 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12832 return true; 12833 } 12834 12835 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12836 const CXXMethodDecl *Old) { 12837 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12838 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12839 12840 if (Context.hasSameType(NewTy, OldTy) || 12841 NewTy->isDependentType() || OldTy->isDependentType()) 12842 return false; 12843 12844 // Check if the return types are covariant 12845 QualType NewClassTy, OldClassTy; 12846 12847 /// Both types must be pointers or references to classes. 12848 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12849 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12850 NewClassTy = NewPT->getPointeeType(); 12851 OldClassTy = OldPT->getPointeeType(); 12852 } 12853 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12854 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12855 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12856 NewClassTy = NewRT->getPointeeType(); 12857 OldClassTy = OldRT->getPointeeType(); 12858 } 12859 } 12860 } 12861 12862 // The return types aren't either both pointers or references to a class type. 12863 if (NewClassTy.isNull()) { 12864 Diag(New->getLocation(), 12865 diag::err_different_return_type_for_overriding_virtual_function) 12866 << New->getDeclName() << NewTy << OldTy 12867 << New->getReturnTypeSourceRange(); 12868 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12869 << Old->getReturnTypeSourceRange(); 12870 12871 return true; 12872 } 12873 12874 // C++ [class.virtual]p6: 12875 // If the return type of D::f differs from the return type of B::f, the 12876 // class type in the return type of D::f shall be complete at the point of 12877 // declaration of D::f or shall be the class type D. 12878 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12879 if (!RT->isBeingDefined() && 12880 RequireCompleteType(New->getLocation(), NewClassTy, 12881 diag::err_covariant_return_incomplete, 12882 New->getDeclName())) 12883 return true; 12884 } 12885 12886 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12887 // Check if the new class derives from the old class. 12888 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12889 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12890 << New->getDeclName() << NewTy << OldTy 12891 << New->getReturnTypeSourceRange(); 12892 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12893 << Old->getReturnTypeSourceRange(); 12894 return true; 12895 } 12896 12897 // Check if we the conversion from derived to base is valid. 12898 if (CheckDerivedToBaseConversion( 12899 NewClassTy, OldClassTy, 12900 diag::err_covariant_return_inaccessible_base, 12901 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12902 New->getLocation(), New->getReturnTypeSourceRange(), 12903 New->getDeclName(), nullptr)) { 12904 // FIXME: this note won't trigger for delayed access control 12905 // diagnostics, and it's impossible to get an undelayed error 12906 // here from access control during the original parse because 12907 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12908 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12909 << Old->getReturnTypeSourceRange(); 12910 return true; 12911 } 12912 } 12913 12914 // The qualifiers of the return types must be the same. 12915 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12916 Diag(New->getLocation(), 12917 diag::err_covariant_return_type_different_qualifications) 12918 << New->getDeclName() << NewTy << OldTy 12919 << New->getReturnTypeSourceRange(); 12920 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12921 << Old->getReturnTypeSourceRange(); 12922 return true; 12923 }; 12924 12925 12926 // The new class type must have the same or less qualifiers as the old type. 12927 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12928 Diag(New->getLocation(), 12929 diag::err_covariant_return_type_class_type_more_qualified) 12930 << New->getDeclName() << NewTy << OldTy 12931 << New->getReturnTypeSourceRange(); 12932 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12933 << Old->getReturnTypeSourceRange(); 12934 return true; 12935 }; 12936 12937 return false; 12938 } 12939 12940 /// \brief Mark the given method pure. 12941 /// 12942 /// \param Method the method to be marked pure. 12943 /// 12944 /// \param InitRange the source range that covers the "0" initializer. 12945 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12946 SourceLocation EndLoc = InitRange.getEnd(); 12947 if (EndLoc.isValid()) 12948 Method->setRangeEnd(EndLoc); 12949 12950 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12951 Method->setPure(); 12952 return false; 12953 } 12954 12955 if (!Method->isInvalidDecl()) 12956 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12957 << Method->getDeclName() << InitRange; 12958 return true; 12959 } 12960 12961 /// \brief Determine whether the given declaration is a static data member. 12962 static bool isStaticDataMember(const Decl *D) { 12963 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12964 return Var->isStaticDataMember(); 12965 12966 return false; 12967 } 12968 12969 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12970 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12971 /// is a fresh scope pushed for just this purpose. 12972 /// 12973 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12974 /// static data member of class X, names should be looked up in the scope of 12975 /// class X. 12976 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12977 // If there is no declaration, there was an error parsing it. 12978 if (!D || D->isInvalidDecl()) 12979 return; 12980 12981 // We will always have a nested name specifier here, but this declaration 12982 // might not be out of line if the specifier names the current namespace: 12983 // extern int n; 12984 // int ::n = 0; 12985 if (D->isOutOfLine()) 12986 EnterDeclaratorContext(S, D->getDeclContext()); 12987 12988 // If we are parsing the initializer for a static data member, push a 12989 // new expression evaluation context that is associated with this static 12990 // data member. 12991 if (isStaticDataMember(D)) 12992 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12993 } 12994 12995 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12996 /// initializer for the out-of-line declaration 'D'. 12997 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12998 // If there is no declaration, there was an error parsing it. 12999 if (!D || D->isInvalidDecl()) 13000 return; 13001 13002 if (isStaticDataMember(D)) 13003 PopExpressionEvaluationContext(); 13004 13005 if (D->isOutOfLine()) 13006 ExitDeclaratorContext(S); 13007 } 13008 13009 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 13010 /// C++ if/switch/while/for statement. 13011 /// e.g: "if (int x = f()) {...}" 13012 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 13013 // C++ 6.4p2: 13014 // The declarator shall not specify a function or an array. 13015 // The type-specifier-seq shall not contain typedef and shall not declare a 13016 // new class or enumeration. 13017 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 13018 "Parser allowed 'typedef' as storage class of condition decl."); 13019 13020 Decl *Dcl = ActOnDeclarator(S, D); 13021 if (!Dcl) 13022 return true; 13023 13024 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 13025 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 13026 << D.getSourceRange(); 13027 return true; 13028 } 13029 13030 return Dcl; 13031 } 13032 13033 void Sema::LoadExternalVTableUses() { 13034 if (!ExternalSource) 13035 return; 13036 13037 SmallVector<ExternalVTableUse, 4> VTables; 13038 ExternalSource->ReadUsedVTables(VTables); 13039 SmallVector<VTableUse, 4> NewUses; 13040 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 13041 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 13042 = VTablesUsed.find(VTables[I].Record); 13043 // Even if a definition wasn't required before, it may be required now. 13044 if (Pos != VTablesUsed.end()) { 13045 if (!Pos->second && VTables[I].DefinitionRequired) 13046 Pos->second = true; 13047 continue; 13048 } 13049 13050 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 13051 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 13052 } 13053 13054 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 13055 } 13056 13057 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 13058 bool DefinitionRequired) { 13059 // Ignore any vtable uses in unevaluated operands or for classes that do 13060 // not have a vtable. 13061 if (!Class->isDynamicClass() || Class->isDependentContext() || 13062 CurContext->isDependentContext() || isUnevaluatedContext()) 13063 return; 13064 13065 // Try to insert this class into the map. 13066 LoadExternalVTableUses(); 13067 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13068 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 13069 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 13070 if (!Pos.second) { 13071 // If we already had an entry, check to see if we are promoting this vtable 13072 // to require a definition. If so, we need to reappend to the VTableUses 13073 // list, since we may have already processed the first entry. 13074 if (DefinitionRequired && !Pos.first->second) { 13075 Pos.first->second = true; 13076 } else { 13077 // Otherwise, we can early exit. 13078 return; 13079 } 13080 } else { 13081 // The Microsoft ABI requires that we perform the destructor body 13082 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 13083 // the deleting destructor is emitted with the vtable, not with the 13084 // destructor definition as in the Itanium ABI. 13085 // If it has a definition, we do the check at that point instead. 13086 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13087 Class->hasUserDeclaredDestructor() && 13088 !Class->getDestructor()->isDefined() && 13089 !Class->getDestructor()->isDeleted()) { 13090 CXXDestructorDecl *DD = Class->getDestructor(); 13091 ContextRAII SavedContext(*this, DD); 13092 CheckDestructor(DD); 13093 } 13094 } 13095 13096 // Local classes need to have their virtual members marked 13097 // immediately. For all other classes, we mark their virtual members 13098 // at the end of the translation unit. 13099 if (Class->isLocalClass()) 13100 MarkVirtualMembersReferenced(Loc, Class); 13101 else 13102 VTableUses.push_back(std::make_pair(Class, Loc)); 13103 } 13104 13105 bool Sema::DefineUsedVTables() { 13106 LoadExternalVTableUses(); 13107 if (VTableUses.empty()) 13108 return false; 13109 13110 // Note: The VTableUses vector could grow as a result of marking 13111 // the members of a class as "used", so we check the size each 13112 // time through the loop and prefer indices (which are stable) to 13113 // iterators (which are not). 13114 bool DefinedAnything = false; 13115 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13116 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13117 if (!Class) 13118 continue; 13119 13120 SourceLocation Loc = VTableUses[I].second; 13121 13122 bool DefineVTable = true; 13123 13124 // If this class has a key function, but that key function is 13125 // defined in another translation unit, we don't need to emit the 13126 // vtable even though we're using it. 13127 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13128 if (KeyFunction && !KeyFunction->hasBody()) { 13129 // The key function is in another translation unit. 13130 DefineVTable = false; 13131 TemplateSpecializationKind TSK = 13132 KeyFunction->getTemplateSpecializationKind(); 13133 assert(TSK != TSK_ExplicitInstantiationDefinition && 13134 TSK != TSK_ImplicitInstantiation && 13135 "Instantiations don't have key functions"); 13136 (void)TSK; 13137 } else if (!KeyFunction) { 13138 // If we have a class with no key function that is the subject 13139 // of an explicit instantiation declaration, suppress the 13140 // vtable; it will live with the explicit instantiation 13141 // definition. 13142 bool IsExplicitInstantiationDeclaration 13143 = Class->getTemplateSpecializationKind() 13144 == TSK_ExplicitInstantiationDeclaration; 13145 for (auto R : Class->redecls()) { 13146 TemplateSpecializationKind TSK 13147 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13148 if (TSK == TSK_ExplicitInstantiationDeclaration) 13149 IsExplicitInstantiationDeclaration = true; 13150 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13151 IsExplicitInstantiationDeclaration = false; 13152 break; 13153 } 13154 } 13155 13156 if (IsExplicitInstantiationDeclaration) 13157 DefineVTable = false; 13158 } 13159 13160 // The exception specifications for all virtual members may be needed even 13161 // if we are not providing an authoritative form of the vtable in this TU. 13162 // We may choose to emit it available_externally anyway. 13163 if (!DefineVTable) { 13164 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13165 continue; 13166 } 13167 13168 // Mark all of the virtual members of this class as referenced, so 13169 // that we can build a vtable. Then, tell the AST consumer that a 13170 // vtable for this class is required. 13171 DefinedAnything = true; 13172 MarkVirtualMembersReferenced(Loc, Class); 13173 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13174 if (VTablesUsed[Canonical]) 13175 Consumer.HandleVTable(Class); 13176 13177 // Optionally warn if we're emitting a weak vtable. 13178 if (Class->isExternallyVisible() && 13179 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13180 const FunctionDecl *KeyFunctionDef = nullptr; 13181 if (!KeyFunction || 13182 (KeyFunction->hasBody(KeyFunctionDef) && 13183 KeyFunctionDef->isInlined())) 13184 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13185 TSK_ExplicitInstantiationDefinition 13186 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13187 << Class; 13188 } 13189 } 13190 VTableUses.clear(); 13191 13192 return DefinedAnything; 13193 } 13194 13195 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13196 const CXXRecordDecl *RD) { 13197 for (const auto *I : RD->methods()) 13198 if (I->isVirtual() && !I->isPure()) 13199 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13200 } 13201 13202 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13203 const CXXRecordDecl *RD) { 13204 // Mark all functions which will appear in RD's vtable as used. 13205 CXXFinalOverriderMap FinalOverriders; 13206 RD->getFinalOverriders(FinalOverriders); 13207 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13208 E = FinalOverriders.end(); 13209 I != E; ++I) { 13210 for (OverridingMethods::const_iterator OI = I->second.begin(), 13211 OE = I->second.end(); 13212 OI != OE; ++OI) { 13213 assert(OI->second.size() > 0 && "no final overrider"); 13214 CXXMethodDecl *Overrider = OI->second.front().Method; 13215 13216 // C++ [basic.def.odr]p2: 13217 // [...] A virtual member function is used if it is not pure. [...] 13218 if (!Overrider->isPure()) 13219 MarkFunctionReferenced(Loc, Overrider); 13220 } 13221 } 13222 13223 // Only classes that have virtual bases need a VTT. 13224 if (RD->getNumVBases() == 0) 13225 return; 13226 13227 for (const auto &I : RD->bases()) { 13228 const CXXRecordDecl *Base = 13229 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13230 if (Base->getNumVBases() == 0) 13231 continue; 13232 MarkVirtualMembersReferenced(Loc, Base); 13233 } 13234 } 13235 13236 /// SetIvarInitializers - This routine builds initialization ASTs for the 13237 /// Objective-C implementation whose ivars need be initialized. 13238 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13239 if (!getLangOpts().CPlusPlus) 13240 return; 13241 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13242 SmallVector<ObjCIvarDecl*, 8> ivars; 13243 CollectIvarsToConstructOrDestruct(OID, ivars); 13244 if (ivars.empty()) 13245 return; 13246 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13247 for (unsigned i = 0; i < ivars.size(); i++) { 13248 FieldDecl *Field = ivars[i]; 13249 if (Field->isInvalidDecl()) 13250 continue; 13251 13252 CXXCtorInitializer *Member; 13253 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13254 InitializationKind InitKind = 13255 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13256 13257 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13258 ExprResult MemberInit = 13259 InitSeq.Perform(*this, InitEntity, InitKind, None); 13260 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13261 // Note, MemberInit could actually come back empty if no initialization 13262 // is required (e.g., because it would call a trivial default constructor) 13263 if (!MemberInit.get() || MemberInit.isInvalid()) 13264 continue; 13265 13266 Member = 13267 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13268 SourceLocation(), 13269 MemberInit.getAs<Expr>(), 13270 SourceLocation()); 13271 AllToInit.push_back(Member); 13272 13273 // Be sure that the destructor is accessible and is marked as referenced. 13274 if (const RecordType *RecordTy = 13275 Context.getBaseElementType(Field->getType()) 13276 ->getAs<RecordType>()) { 13277 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13278 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13279 MarkFunctionReferenced(Field->getLocation(), Destructor); 13280 CheckDestructorAccess(Field->getLocation(), Destructor, 13281 PDiag(diag::err_access_dtor_ivar) 13282 << Context.getBaseElementType(Field->getType())); 13283 } 13284 } 13285 } 13286 ObjCImplementation->setIvarInitializers(Context, 13287 AllToInit.data(), AllToInit.size()); 13288 } 13289 } 13290 13291 static 13292 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13293 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13294 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13295 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13296 Sema &S) { 13297 if (Ctor->isInvalidDecl()) 13298 return; 13299 13300 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13301 13302 // Target may not be determinable yet, for instance if this is a dependent 13303 // call in an uninstantiated template. 13304 if (Target) { 13305 const FunctionDecl *FNTarget = nullptr; 13306 (void)Target->hasBody(FNTarget); 13307 Target = const_cast<CXXConstructorDecl*>( 13308 cast_or_null<CXXConstructorDecl>(FNTarget)); 13309 } 13310 13311 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13312 // Avoid dereferencing a null pointer here. 13313 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13314 13315 if (!Current.insert(Canonical).second) 13316 return; 13317 13318 // We know that beyond here, we aren't chaining into a cycle. 13319 if (!Target || !Target->isDelegatingConstructor() || 13320 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13321 Valid.insert(Current.begin(), Current.end()); 13322 Current.clear(); 13323 // We've hit a cycle. 13324 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13325 Current.count(TCanonical)) { 13326 // If we haven't diagnosed this cycle yet, do so now. 13327 if (!Invalid.count(TCanonical)) { 13328 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13329 diag::warn_delegating_ctor_cycle) 13330 << Ctor; 13331 13332 // Don't add a note for a function delegating directly to itself. 13333 if (TCanonical != Canonical) 13334 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13335 13336 CXXConstructorDecl *C = Target; 13337 while (C->getCanonicalDecl() != Canonical) { 13338 const FunctionDecl *FNTarget = nullptr; 13339 (void)C->getTargetConstructor()->hasBody(FNTarget); 13340 assert(FNTarget && "Ctor cycle through bodiless function"); 13341 13342 C = const_cast<CXXConstructorDecl*>( 13343 cast<CXXConstructorDecl>(FNTarget)); 13344 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13345 } 13346 } 13347 13348 Invalid.insert(Current.begin(), Current.end()); 13349 Current.clear(); 13350 } else { 13351 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13352 } 13353 } 13354 13355 13356 void Sema::CheckDelegatingCtorCycles() { 13357 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13358 13359 for (DelegatingCtorDeclsType::iterator 13360 I = DelegatingCtorDecls.begin(ExternalSource), 13361 E = DelegatingCtorDecls.end(); 13362 I != E; ++I) 13363 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13364 13365 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13366 CE = Invalid.end(); 13367 CI != CE; ++CI) 13368 (*CI)->setInvalidDecl(); 13369 } 13370 13371 namespace { 13372 /// \brief AST visitor that finds references to the 'this' expression. 13373 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13374 Sema &S; 13375 13376 public: 13377 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13378 13379 bool VisitCXXThisExpr(CXXThisExpr *E) { 13380 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13381 << E->isImplicit(); 13382 return false; 13383 } 13384 }; 13385 } 13386 13387 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13388 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13389 if (!TSInfo) 13390 return false; 13391 13392 TypeLoc TL = TSInfo->getTypeLoc(); 13393 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13394 if (!ProtoTL) 13395 return false; 13396 13397 // C++11 [expr.prim.general]p3: 13398 // [The expression this] shall not appear before the optional 13399 // cv-qualifier-seq and it shall not appear within the declaration of a 13400 // static member function (although its type and value category are defined 13401 // within a static member function as they are within a non-static member 13402 // function). [ Note: this is because declaration matching does not occur 13403 // until the complete declarator is known. - end note ] 13404 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13405 FindCXXThisExpr Finder(*this); 13406 13407 // If the return type came after the cv-qualifier-seq, check it now. 13408 if (Proto->hasTrailingReturn() && 13409 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13410 return true; 13411 13412 // Check the exception specification. 13413 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13414 return true; 13415 13416 return checkThisInStaticMemberFunctionAttributes(Method); 13417 } 13418 13419 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13420 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13421 if (!TSInfo) 13422 return false; 13423 13424 TypeLoc TL = TSInfo->getTypeLoc(); 13425 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13426 if (!ProtoTL) 13427 return false; 13428 13429 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13430 FindCXXThisExpr Finder(*this); 13431 13432 switch (Proto->getExceptionSpecType()) { 13433 case EST_Unparsed: 13434 case EST_Uninstantiated: 13435 case EST_Unevaluated: 13436 case EST_BasicNoexcept: 13437 case EST_DynamicNone: 13438 case EST_MSAny: 13439 case EST_None: 13440 break; 13441 13442 case EST_ComputedNoexcept: 13443 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13444 return true; 13445 13446 case EST_Dynamic: 13447 for (const auto &E : Proto->exceptions()) { 13448 if (!Finder.TraverseType(E)) 13449 return true; 13450 } 13451 break; 13452 } 13453 13454 return false; 13455 } 13456 13457 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13458 FindCXXThisExpr Finder(*this); 13459 13460 // Check attributes. 13461 for (const auto *A : Method->attrs()) { 13462 // FIXME: This should be emitted by tblgen. 13463 Expr *Arg = nullptr; 13464 ArrayRef<Expr *> Args; 13465 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13466 Arg = G->getArg(); 13467 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13468 Arg = G->getArg(); 13469 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13470 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13471 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13472 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13473 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13474 Arg = ETLF->getSuccessValue(); 13475 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13476 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13477 Arg = STLF->getSuccessValue(); 13478 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13479 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13480 Arg = LR->getArg(); 13481 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13482 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13483 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13484 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13485 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13486 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13487 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13488 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13489 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13490 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13491 13492 if (Arg && !Finder.TraverseStmt(Arg)) 13493 return true; 13494 13495 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13496 if (!Finder.TraverseStmt(Args[I])) 13497 return true; 13498 } 13499 } 13500 13501 return false; 13502 } 13503 13504 void Sema::checkExceptionSpecification( 13505 bool IsTopLevel, ExceptionSpecificationType EST, 13506 ArrayRef<ParsedType> DynamicExceptions, 13507 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13508 SmallVectorImpl<QualType> &Exceptions, 13509 FunctionProtoType::ExceptionSpecInfo &ESI) { 13510 Exceptions.clear(); 13511 ESI.Type = EST; 13512 if (EST == EST_Dynamic) { 13513 Exceptions.reserve(DynamicExceptions.size()); 13514 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13515 // FIXME: Preserve type source info. 13516 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13517 13518 if (IsTopLevel) { 13519 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13520 collectUnexpandedParameterPacks(ET, Unexpanded); 13521 if (!Unexpanded.empty()) { 13522 DiagnoseUnexpandedParameterPacks( 13523 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13524 Unexpanded); 13525 continue; 13526 } 13527 } 13528 13529 // Check that the type is valid for an exception spec, and 13530 // drop it if not. 13531 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13532 Exceptions.push_back(ET); 13533 } 13534 ESI.Exceptions = Exceptions; 13535 return; 13536 } 13537 13538 if (EST == EST_ComputedNoexcept) { 13539 // If an error occurred, there's no expression here. 13540 if (NoexceptExpr) { 13541 assert((NoexceptExpr->isTypeDependent() || 13542 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13543 Context.BoolTy) && 13544 "Parser should have made sure that the expression is boolean"); 13545 if (IsTopLevel && NoexceptExpr && 13546 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13547 ESI.Type = EST_BasicNoexcept; 13548 return; 13549 } 13550 13551 if (!NoexceptExpr->isValueDependent()) 13552 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13553 diag::err_noexcept_needs_constant_expression, 13554 /*AllowFold*/ false).get(); 13555 ESI.NoexceptExpr = NoexceptExpr; 13556 } 13557 return; 13558 } 13559 } 13560 13561 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13562 ExceptionSpecificationType EST, 13563 SourceRange SpecificationRange, 13564 ArrayRef<ParsedType> DynamicExceptions, 13565 ArrayRef<SourceRange> DynamicExceptionRanges, 13566 Expr *NoexceptExpr) { 13567 if (!MethodD) 13568 return; 13569 13570 // Dig out the method we're referring to. 13571 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13572 MethodD = FunTmpl->getTemplatedDecl(); 13573 13574 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13575 if (!Method) 13576 return; 13577 13578 // Check the exception specification. 13579 llvm::SmallVector<QualType, 4> Exceptions; 13580 FunctionProtoType::ExceptionSpecInfo ESI; 13581 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13582 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13583 ESI); 13584 13585 // Update the exception specification on the function type. 13586 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13587 13588 if (Method->isStatic()) 13589 checkThisInStaticMemberFunctionExceptionSpec(Method); 13590 13591 if (Method->isVirtual()) { 13592 // Check overrides, which we previously had to delay. 13593 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13594 OEnd = Method->end_overridden_methods(); 13595 O != OEnd; ++O) 13596 CheckOverridingFunctionExceptionSpec(Method, *O); 13597 } 13598 } 13599 13600 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13601 /// 13602 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13603 SourceLocation DeclStart, 13604 Declarator &D, Expr *BitWidth, 13605 InClassInitStyle InitStyle, 13606 AccessSpecifier AS, 13607 AttributeList *MSPropertyAttr) { 13608 IdentifierInfo *II = D.getIdentifier(); 13609 if (!II) { 13610 Diag(DeclStart, diag::err_anonymous_property); 13611 return nullptr; 13612 } 13613 SourceLocation Loc = D.getIdentifierLoc(); 13614 13615 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13616 QualType T = TInfo->getType(); 13617 if (getLangOpts().CPlusPlus) { 13618 CheckExtraCXXDefaultArguments(D); 13619 13620 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13621 UPPC_DataMemberType)) { 13622 D.setInvalidType(); 13623 T = Context.IntTy; 13624 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13625 } 13626 } 13627 13628 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13629 13630 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13631 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13632 diag::err_invalid_thread) 13633 << DeclSpec::getSpecifierName(TSCS); 13634 13635 // Check to see if this name was declared as a member previously 13636 NamedDecl *PrevDecl = nullptr; 13637 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13638 LookupName(Previous, S); 13639 switch (Previous.getResultKind()) { 13640 case LookupResult::Found: 13641 case LookupResult::FoundUnresolvedValue: 13642 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13643 break; 13644 13645 case LookupResult::FoundOverloaded: 13646 PrevDecl = Previous.getRepresentativeDecl(); 13647 break; 13648 13649 case LookupResult::NotFound: 13650 case LookupResult::NotFoundInCurrentInstantiation: 13651 case LookupResult::Ambiguous: 13652 break; 13653 } 13654 13655 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13656 // Maybe we will complain about the shadowed template parameter. 13657 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13658 // Just pretend that we didn't see the previous declaration. 13659 PrevDecl = nullptr; 13660 } 13661 13662 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13663 PrevDecl = nullptr; 13664 13665 SourceLocation TSSL = D.getLocStart(); 13666 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13667 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13668 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13669 ProcessDeclAttributes(TUScope, NewPD, D); 13670 NewPD->setAccess(AS); 13671 13672 if (NewPD->isInvalidDecl()) 13673 Record->setInvalidDecl(); 13674 13675 if (D.getDeclSpec().isModulePrivateSpecified()) 13676 NewPD->setModulePrivate(); 13677 13678 if (NewPD->isInvalidDecl() && PrevDecl) { 13679 // Don't introduce NewFD into scope; there's already something 13680 // with the same name in the same scope. 13681 } else if (II) { 13682 PushOnScopeChains(NewPD, S); 13683 } else 13684 Record->addDecl(NewPD); 13685 13686 return NewPD; 13687 } 13688