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 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 392 << SourceRange((*Toks)[1].getLocation(), 393 Toks->back().getLocation()); 394 delete Toks; 395 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 396 } else if (Param->getDefaultArg()) { 397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 398 << Param->getDefaultArg()->getSourceRange(); 399 Param->setDefaultArg(nullptr); 400 } 401 } 402 } else if (chunk.Kind != DeclaratorChunk::Paren) { 403 MightBeFunction = false; 404 } 405 } 406 } 407 408 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 409 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 410 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 411 if (!PVD->hasDefaultArg()) 412 return false; 413 if (!PVD->hasInheritedDefaultArg()) 414 return true; 415 } 416 return false; 417 } 418 419 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 420 /// function, once we already know that they have the same 421 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 422 /// error, false otherwise. 423 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 424 Scope *S) { 425 bool Invalid = false; 426 427 // C++ [dcl.fct.default]p4: 428 // For non-template functions, default arguments can be added in 429 // later declarations of a function in the same 430 // scope. Declarations in different scopes have completely 431 // distinct sets of default arguments. That is, declarations in 432 // inner scopes do not acquire default arguments from 433 // declarations in outer scopes, and vice versa. In a given 434 // function declaration, all parameters subsequent to a 435 // parameter with a default argument shall have default 436 // arguments supplied in this or previous declarations. A 437 // default argument shall not be redefined by a later 438 // declaration (not even to the same value). 439 // 440 // C++ [dcl.fct.default]p6: 441 // Except for member functions of class templates, the default arguments 442 // in a member function definition that appears outside of the class 443 // definition are added to the set of default arguments provided by the 444 // member function declaration in the class definition. 445 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 446 ParmVarDecl *OldParam = Old->getParamDecl(p); 447 ParmVarDecl *NewParam = New->getParamDecl(p); 448 449 bool OldParamHasDfl = OldParam->hasDefaultArg(); 450 bool NewParamHasDfl = NewParam->hasDefaultArg(); 451 452 // The declaration context corresponding to the scope is the semantic 453 // parent, unless this is a local function declaration, in which case 454 // it is that surrounding function. 455 DeclContext *ScopeDC = New->isLocalExternDecl() 456 ? New->getLexicalDeclContext() 457 : New->getDeclContext(); 458 if (S && !isDeclInScope(Old, ScopeDC, S) && 459 !New->getDeclContext()->isRecord()) 460 // Ignore default parameters of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 OldParamHasDfl = false; 464 if (New->isLocalExternDecl() != Old->isLocalExternDecl()) 465 // If only one of these is a local function declaration, then they are 466 // declared in different scopes, even though isDeclInScope may think 467 // they're in the same scope. (If both are local, the scope check is 468 // sufficent, and if neither is local, then they are in the same scope.) 469 OldParamHasDfl = false; 470 471 if (OldParamHasDfl && NewParamHasDfl) { 472 473 unsigned DiagDefaultParamID = 474 diag::err_param_default_argument_redefinition; 475 476 // MSVC accepts that default parameters be redefined for member functions 477 // of template class. The new default parameter's value is ignored. 478 Invalid = true; 479 if (getLangOpts().MicrosoftExt) { 480 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 481 if (MD && MD->getParent()->getDescribedClassTemplate()) { 482 // Merge the old default argument into the new parameter. 483 NewParam->setHasInheritedDefaultArg(); 484 if (OldParam->hasUninstantiatedDefaultArg()) 485 NewParam->setUninstantiatedDefaultArg( 486 OldParam->getUninstantiatedDefaultArg()); 487 else 488 NewParam->setDefaultArg(OldParam->getInit()); 489 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 490 Invalid = false; 491 } 492 } 493 494 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 495 // hint here. Alternatively, we could walk the type-source information 496 // for NewParam to find the last source location in the type... but it 497 // isn't worth the effort right now. This is the kind of test case that 498 // is hard to get right: 499 // int f(int); 500 // void g(int (*fp)(int) = f); 501 // void g(int (*fp)(int) = &f); 502 Diag(NewParam->getLocation(), DiagDefaultParamID) 503 << NewParam->getDefaultArgRange(); 504 505 // Look for the function declaration where the default argument was 506 // actually written, which may be a declaration prior to Old. 507 for (FunctionDecl *Older = Old->getPreviousDecl(); 508 Older; Older = Older->getPreviousDecl()) { 509 if (!Older->getParamDecl(p)->hasDefaultArg()) 510 break; 511 512 OldParam = Older->getParamDecl(p); 513 } 514 515 Diag(OldParam->getLocation(), diag::note_previous_definition) 516 << OldParam->getDefaultArgRange(); 517 } else if (OldParamHasDfl) { 518 // Merge the old default argument into the new parameter. 519 // It's important to use getInit() here; getDefaultArg() 520 // strips off any top-level ExprWithCleanups. 521 NewParam->setHasInheritedDefaultArg(); 522 if (OldParam->hasUninstantiatedDefaultArg()) 523 NewParam->setUninstantiatedDefaultArg( 524 OldParam->getUninstantiatedDefaultArg()); 525 else 526 NewParam->setDefaultArg(OldParam->getInit()); 527 } else if (NewParamHasDfl) { 528 if (New->getDescribedFunctionTemplate()) { 529 // Paragraph 4, quoted above, only applies to non-template functions. 530 Diag(NewParam->getLocation(), 531 diag::err_param_default_argument_template_redecl) 532 << NewParam->getDefaultArgRange(); 533 Diag(Old->getLocation(), diag::note_template_prev_declaration) 534 << false; 535 } else if (New->getTemplateSpecializationKind() 536 != TSK_ImplicitInstantiation && 537 New->getTemplateSpecializationKind() != TSK_Undeclared) { 538 // C++ [temp.expr.spec]p21: 539 // Default function arguments shall not be specified in a declaration 540 // or a definition for one of the following explicit specializations: 541 // - the explicit specialization of a function template; 542 // - the explicit specialization of a member function template; 543 // - the explicit specialization of a member function of a class 544 // template where the class template specialization to which the 545 // member function specialization belongs is implicitly 546 // instantiated. 547 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 548 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 549 << New->getDeclName() 550 << NewParam->getDefaultArgRange(); 551 } else if (New->getDeclContext()->isDependentContext()) { 552 // C++ [dcl.fct.default]p6 (DR217): 553 // Default arguments for a member function of a class template shall 554 // be specified on the initial declaration of the member function 555 // within the class template. 556 // 557 // Reading the tea leaves a bit in DR217 and its reference to DR205 558 // leads me to the conclusion that one cannot add default function 559 // arguments for an out-of-line definition of a member function of a 560 // dependent type. 561 int WhichKind = 2; 562 if (CXXRecordDecl *Record 563 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 564 if (Record->getDescribedClassTemplate()) 565 WhichKind = 0; 566 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 567 WhichKind = 1; 568 else 569 WhichKind = 2; 570 } 571 572 Diag(NewParam->getLocation(), 573 diag::err_param_default_argument_member_template_redecl) 574 << WhichKind 575 << NewParam->getDefaultArgRange(); 576 } 577 } 578 } 579 580 // DR1344: If a default argument is added outside a class definition and that 581 // default argument makes the function a special member function, the program 582 // is ill-formed. This can only happen for constructors. 583 if (isa<CXXConstructorDecl>(New) && 584 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 585 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 586 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 587 if (NewSM != OldSM) { 588 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 589 assert(NewParam->hasDefaultArg()); 590 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 591 << NewParam->getDefaultArgRange() << NewSM; 592 Diag(Old->getLocation(), diag::note_previous_declaration); 593 } 594 } 595 596 const FunctionDecl *Def; 597 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 598 // template has a constexpr specifier then all its declarations shall 599 // contain the constexpr specifier. 600 if (New->isConstexpr() != Old->isConstexpr()) { 601 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 602 << New << New->isConstexpr(); 603 Diag(Old->getLocation(), diag::note_previous_declaration); 604 Invalid = true; 605 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 606 // C++11 [dcl.fcn.spec]p4: 607 // If the definition of a function appears in a translation unit before its 608 // first declaration as inline, the program is ill-formed. 609 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 610 Diag(Def->getLocation(), diag::note_previous_definition); 611 Invalid = true; 612 } 613 614 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 615 // argument expression, that declaration shall be a definition and shall be 616 // the only declaration of the function or function template in the 617 // translation unit. 618 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 619 functionDeclHasDefaultArgument(Old)) { 620 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 621 Diag(Old->getLocation(), diag::note_previous_declaration); 622 Invalid = true; 623 } 624 625 if (CheckEquivalentExceptionSpec(Old, New)) 626 Invalid = true; 627 628 return Invalid; 629 } 630 631 /// \brief Merge the exception specifications of two variable declarations. 632 /// 633 /// This is called when there's a redeclaration of a VarDecl. The function 634 /// checks if the redeclaration might have an exception specification and 635 /// validates compatibility and merges the specs if necessary. 636 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 637 // Shortcut if exceptions are disabled. 638 if (!getLangOpts().CXXExceptions) 639 return; 640 641 assert(Context.hasSameType(New->getType(), Old->getType()) && 642 "Should only be called if types are otherwise the same."); 643 644 QualType NewType = New->getType(); 645 QualType OldType = Old->getType(); 646 647 // We're only interested in pointers and references to functions, as well 648 // as pointers to member functions. 649 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 650 NewType = R->getPointeeType(); 651 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 652 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 653 NewType = P->getPointeeType(); 654 OldType = OldType->getAs<PointerType>()->getPointeeType(); 655 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 656 NewType = M->getPointeeType(); 657 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 658 } 659 660 if (!NewType->isFunctionProtoType()) 661 return; 662 663 // There's lots of special cases for functions. For function pointers, system 664 // libraries are hopefully not as broken so that we don't need these 665 // workarounds. 666 if (CheckEquivalentExceptionSpec( 667 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 668 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 669 New->setInvalidDecl(); 670 } 671 } 672 673 /// CheckCXXDefaultArguments - Verify that the default arguments for a 674 /// function declaration are well-formed according to C++ 675 /// [dcl.fct.default]. 676 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 677 unsigned NumParams = FD->getNumParams(); 678 unsigned p; 679 680 // Find first parameter with a default argument 681 for (p = 0; p < NumParams; ++p) { 682 ParmVarDecl *Param = FD->getParamDecl(p); 683 if (Param->hasDefaultArg()) 684 break; 685 } 686 687 // C++ [dcl.fct.default]p4: 688 // In a given function declaration, all parameters 689 // subsequent to a parameter with a default argument shall 690 // have default arguments supplied in this or previous 691 // declarations. A default argument shall not be redefined 692 // by a later declaration (not even to the same value). 693 unsigned LastMissingDefaultArg = 0; 694 for (; p < NumParams; ++p) { 695 ParmVarDecl *Param = FD->getParamDecl(p); 696 if (!Param->hasDefaultArg()) { 697 if (Param->isInvalidDecl()) 698 /* We already complained about this parameter. */; 699 else if (Param->getIdentifier()) 700 Diag(Param->getLocation(), 701 diag::err_param_default_argument_missing_name) 702 << Param->getIdentifier(); 703 else 704 Diag(Param->getLocation(), 705 diag::err_param_default_argument_missing); 706 707 LastMissingDefaultArg = p; 708 } 709 } 710 711 if (LastMissingDefaultArg > 0) { 712 // Some default arguments were missing. Clear out all of the 713 // default arguments up to (and including) the last missing 714 // default argument, so that we leave the function parameters 715 // in a semantically valid state. 716 for (p = 0; p <= LastMissingDefaultArg; ++p) { 717 ParmVarDecl *Param = FD->getParamDecl(p); 718 if (Param->hasDefaultArg()) { 719 Param->setDefaultArg(nullptr); 720 } 721 } 722 } 723 } 724 725 // CheckConstexprParameterTypes - Check whether a function's parameter types 726 // are all literal types. If so, return true. If not, produce a suitable 727 // diagnostic and return false. 728 static bool CheckConstexprParameterTypes(Sema &SemaRef, 729 const FunctionDecl *FD) { 730 unsigned ArgIndex = 0; 731 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 732 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 733 e = FT->param_type_end(); 734 i != e; ++i, ++ArgIndex) { 735 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 736 SourceLocation ParamLoc = PD->getLocation(); 737 if (!(*i)->isDependentType() && 738 SemaRef.RequireLiteralType(ParamLoc, *i, 739 diag::err_constexpr_non_literal_param, 740 ArgIndex+1, PD->getSourceRange(), 741 isa<CXXConstructorDecl>(FD))) 742 return false; 743 } 744 return true; 745 } 746 747 /// \brief Get diagnostic %select index for tag kind for 748 /// record diagnostic message. 749 /// WARNING: Indexes apply to particular diagnostics only! 750 /// 751 /// \returns diagnostic %select index. 752 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 753 switch (Tag) { 754 case TTK_Struct: return 0; 755 case TTK_Interface: return 1; 756 case TTK_Class: return 2; 757 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 758 } 759 } 760 761 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 762 // the requirements of a constexpr function definition or a constexpr 763 // constructor definition. If so, return true. If not, produce appropriate 764 // diagnostics and return false. 765 // 766 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 767 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 768 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 769 if (MD && MD->isInstance()) { 770 // C++11 [dcl.constexpr]p4: 771 // The definition of a constexpr constructor shall satisfy the following 772 // constraints: 773 // - the class shall not have any virtual base classes; 774 const CXXRecordDecl *RD = MD->getParent(); 775 if (RD->getNumVBases()) { 776 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 777 << isa<CXXConstructorDecl>(NewFD) 778 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 779 for (const auto &I : RD->vbases()) 780 Diag(I.getLocStart(), 781 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 782 return false; 783 } 784 } 785 786 if (!isa<CXXConstructorDecl>(NewFD)) { 787 // C++11 [dcl.constexpr]p3: 788 // The definition of a constexpr function shall satisfy the following 789 // constraints: 790 // - it shall not be virtual; 791 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 792 if (Method && Method->isVirtual()) { 793 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 794 795 // If it's not obvious why this function is virtual, find an overridden 796 // function which uses the 'virtual' keyword. 797 const CXXMethodDecl *WrittenVirtual = Method; 798 while (!WrittenVirtual->isVirtualAsWritten()) 799 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 800 if (WrittenVirtual != Method) 801 Diag(WrittenVirtual->getLocation(), 802 diag::note_overridden_virtual_function); 803 return false; 804 } 805 806 // - its return type shall be a literal type; 807 QualType RT = NewFD->getReturnType(); 808 if (!RT->isDependentType() && 809 RequireLiteralType(NewFD->getLocation(), RT, 810 diag::err_constexpr_non_literal_return)) 811 return false; 812 } 813 814 // - each of its parameter types shall be a literal type; 815 if (!CheckConstexprParameterTypes(*this, NewFD)) 816 return false; 817 818 return true; 819 } 820 821 /// Check the given declaration statement is legal within a constexpr function 822 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 823 /// 824 /// \return true if the body is OK (maybe only as an extension), false if we 825 /// have diagnosed a problem. 826 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 827 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 828 // C++11 [dcl.constexpr]p3 and p4: 829 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 830 // contain only 831 for (const auto *DclIt : DS->decls()) { 832 switch (DclIt->getKind()) { 833 case Decl::StaticAssert: 834 case Decl::Using: 835 case Decl::UsingShadow: 836 case Decl::UsingDirective: 837 case Decl::UnresolvedUsingTypename: 838 case Decl::UnresolvedUsingValue: 839 // - static_assert-declarations 840 // - using-declarations, 841 // - using-directives, 842 continue; 843 844 case Decl::Typedef: 845 case Decl::TypeAlias: { 846 // - typedef declarations and alias-declarations that do not define 847 // classes or enumerations, 848 const auto *TN = cast<TypedefNameDecl>(DclIt); 849 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 850 // Don't allow variably-modified types in constexpr functions. 851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 853 << TL.getSourceRange() << TL.getType() 854 << isa<CXXConstructorDecl>(Dcl); 855 return false; 856 } 857 continue; 858 } 859 860 case Decl::Enum: 861 case Decl::CXXRecord: 862 // C++1y allows types to be defined, not just declared. 863 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 864 SemaRef.Diag(DS->getLocStart(), 865 SemaRef.getLangOpts().CPlusPlus14 866 ? diag::warn_cxx11_compat_constexpr_type_definition 867 : diag::ext_constexpr_type_definition) 868 << isa<CXXConstructorDecl>(Dcl); 869 continue; 870 871 case Decl::EnumConstant: 872 case Decl::IndirectField: 873 case Decl::ParmVar: 874 // These can only appear with other declarations which are banned in 875 // C++11 and permitted in C++1y, so ignore them. 876 continue; 877 878 case Decl::Var: { 879 // C++1y [dcl.constexpr]p3 allows anything except: 880 // a definition of a variable of non-literal type or of static or 881 // thread storage duration or for which no initialization is performed. 882 const auto *VD = cast<VarDecl>(DclIt); 883 if (VD->isThisDeclarationADefinition()) { 884 if (VD->isStaticLocal()) { 885 SemaRef.Diag(VD->getLocation(), 886 diag::err_constexpr_local_var_static) 887 << isa<CXXConstructorDecl>(Dcl) 888 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 889 return false; 890 } 891 if (!VD->getType()->isDependentType() && 892 SemaRef.RequireLiteralType( 893 VD->getLocation(), VD->getType(), 894 diag::err_constexpr_local_var_non_literal_type, 895 isa<CXXConstructorDecl>(Dcl))) 896 return false; 897 if (!VD->getType()->isDependentType() && 898 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 899 SemaRef.Diag(VD->getLocation(), 900 diag::err_constexpr_local_var_no_init) 901 << isa<CXXConstructorDecl>(Dcl); 902 return false; 903 } 904 } 905 SemaRef.Diag(VD->getLocation(), 906 SemaRef.getLangOpts().CPlusPlus14 907 ? diag::warn_cxx11_compat_constexpr_local_var 908 : diag::ext_constexpr_local_var) 909 << isa<CXXConstructorDecl>(Dcl); 910 continue; 911 } 912 913 case Decl::NamespaceAlias: 914 case Decl::Function: 915 // These are disallowed in C++11 and permitted in C++1y. Allow them 916 // everywhere as an extension. 917 if (!Cxx1yLoc.isValid()) 918 Cxx1yLoc = DS->getLocStart(); 919 continue; 920 921 default: 922 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 923 << isa<CXXConstructorDecl>(Dcl); 924 return false; 925 } 926 } 927 928 return true; 929 } 930 931 /// Check that the given field is initialized within a constexpr constructor. 932 /// 933 /// \param Dcl The constexpr constructor being checked. 934 /// \param Field The field being checked. This may be a member of an anonymous 935 /// struct or union nested within the class being checked. 936 /// \param Inits All declarations, including anonymous struct/union members and 937 /// indirect members, for which any initialization was provided. 938 /// \param Diagnosed Set to true if an error is produced. 939 static void CheckConstexprCtorInitializer(Sema &SemaRef, 940 const FunctionDecl *Dcl, 941 FieldDecl *Field, 942 llvm::SmallSet<Decl*, 16> &Inits, 943 bool &Diagnosed) { 944 if (Field->isInvalidDecl()) 945 return; 946 947 if (Field->isUnnamedBitfield()) 948 return; 949 950 // Anonymous unions with no variant members and empty anonymous structs do not 951 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 952 // indirect fields don't need initializing. 953 if (Field->isAnonymousStructOrUnion() && 954 (Field->getType()->isUnionType() 955 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 956 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 957 return; 958 959 if (!Inits.count(Field)) { 960 if (!Diagnosed) { 961 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 962 Diagnosed = true; 963 } 964 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 965 } else if (Field->isAnonymousStructOrUnion()) { 966 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 967 for (auto *I : RD->fields()) 968 // If an anonymous union contains an anonymous struct of which any member 969 // is initialized, all members must be initialized. 970 if (!RD->isUnion() || Inits.count(I)) 971 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 972 } 973 } 974 975 /// Check the provided statement is allowed in a constexpr function 976 /// definition. 977 static bool 978 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 979 SmallVectorImpl<SourceLocation> &ReturnStmts, 980 SourceLocation &Cxx1yLoc) { 981 // - its function-body shall be [...] a compound-statement that contains only 982 switch (S->getStmtClass()) { 983 case Stmt::NullStmtClass: 984 // - null statements, 985 return true; 986 987 case Stmt::DeclStmtClass: 988 // - static_assert-declarations 989 // - using-declarations, 990 // - using-directives, 991 // - typedef declarations and alias-declarations that do not define 992 // classes or enumerations, 993 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 994 return false; 995 return true; 996 997 case Stmt::ReturnStmtClass: 998 // - and exactly one return statement; 999 if (isa<CXXConstructorDecl>(Dcl)) { 1000 // C++1y allows return statements in constexpr constructors. 1001 if (!Cxx1yLoc.isValid()) 1002 Cxx1yLoc = S->getLocStart(); 1003 return true; 1004 } 1005 1006 ReturnStmts.push_back(S->getLocStart()); 1007 return true; 1008 1009 case Stmt::CompoundStmtClass: { 1010 // C++1y allows compound-statements. 1011 if (!Cxx1yLoc.isValid()) 1012 Cxx1yLoc = S->getLocStart(); 1013 1014 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1015 for (auto *BodyIt : CompStmt->body()) { 1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1017 Cxx1yLoc)) 1018 return false; 1019 } 1020 return true; 1021 } 1022 1023 case Stmt::AttributedStmtClass: 1024 if (!Cxx1yLoc.isValid()) 1025 Cxx1yLoc = S->getLocStart(); 1026 return true; 1027 1028 case Stmt::IfStmtClass: { 1029 // C++1y allows if-statements. 1030 if (!Cxx1yLoc.isValid()) 1031 Cxx1yLoc = S->getLocStart(); 1032 1033 IfStmt *If = cast<IfStmt>(S); 1034 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1035 Cxx1yLoc)) 1036 return false; 1037 if (If->getElse() && 1038 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1039 Cxx1yLoc)) 1040 return false; 1041 return true; 1042 } 1043 1044 case Stmt::WhileStmtClass: 1045 case Stmt::DoStmtClass: 1046 case Stmt::ForStmtClass: 1047 case Stmt::CXXForRangeStmtClass: 1048 case Stmt::ContinueStmtClass: 1049 // C++1y allows all of these. We don't allow them as extensions in C++11, 1050 // because they don't make sense without variable mutation. 1051 if (!SemaRef.getLangOpts().CPlusPlus14) 1052 break; 1053 if (!Cxx1yLoc.isValid()) 1054 Cxx1yLoc = S->getLocStart(); 1055 for (Stmt::child_range Children = S->children(); Children; ++Children) 1056 if (*Children && 1057 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1058 Cxx1yLoc)) 1059 return false; 1060 return true; 1061 1062 case Stmt::SwitchStmtClass: 1063 case Stmt::CaseStmtClass: 1064 case Stmt::DefaultStmtClass: 1065 case Stmt::BreakStmtClass: 1066 // C++1y allows switch-statements, and since they don't need variable 1067 // mutation, we can reasonably allow them in C++11 as an extension. 1068 if (!Cxx1yLoc.isValid()) 1069 Cxx1yLoc = S->getLocStart(); 1070 for (Stmt::child_range Children = S->children(); Children; ++Children) 1071 if (*Children && 1072 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1073 Cxx1yLoc)) 1074 return false; 1075 return true; 1076 1077 default: 1078 if (!isa<Expr>(S)) 1079 break; 1080 1081 // C++1y allows expression-statements. 1082 if (!Cxx1yLoc.isValid()) 1083 Cxx1yLoc = S->getLocStart(); 1084 return true; 1085 } 1086 1087 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1088 << isa<CXXConstructorDecl>(Dcl); 1089 return false; 1090 } 1091 1092 /// Check the body for the given constexpr function declaration only contains 1093 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1094 /// 1095 /// \return true if the body is OK, false if we have diagnosed a problem. 1096 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1097 if (isa<CXXTryStmt>(Body)) { 1098 // C++11 [dcl.constexpr]p3: 1099 // The definition of a constexpr function shall satisfy the following 1100 // constraints: [...] 1101 // - its function-body shall be = delete, = default, or a 1102 // compound-statement 1103 // 1104 // C++11 [dcl.constexpr]p4: 1105 // In the definition of a constexpr constructor, [...] 1106 // - its function-body shall not be a function-try-block; 1107 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1108 << isa<CXXConstructorDecl>(Dcl); 1109 return false; 1110 } 1111 1112 SmallVector<SourceLocation, 4> ReturnStmts; 1113 1114 // - its function-body shall be [...] a compound-statement that contains only 1115 // [... list of cases ...] 1116 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1117 SourceLocation Cxx1yLoc; 1118 for (auto *BodyIt : CompBody->body()) { 1119 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1120 return false; 1121 } 1122 1123 if (Cxx1yLoc.isValid()) 1124 Diag(Cxx1yLoc, 1125 getLangOpts().CPlusPlus14 1126 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1127 : diag::ext_constexpr_body_invalid_stmt) 1128 << isa<CXXConstructorDecl>(Dcl); 1129 1130 if (const CXXConstructorDecl *Constructor 1131 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1132 const CXXRecordDecl *RD = Constructor->getParent(); 1133 // DR1359: 1134 // - every non-variant non-static data member and base class sub-object 1135 // shall be initialized; 1136 // DR1460: 1137 // - if the class is a union having variant members, exactly one of them 1138 // shall be initialized; 1139 if (RD->isUnion()) { 1140 if (Constructor->getNumCtorInitializers() == 0 && 1141 RD->hasVariantMembers()) { 1142 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1143 return false; 1144 } 1145 } else if (!Constructor->isDependentContext() && 1146 !Constructor->isDelegatingConstructor()) { 1147 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1148 1149 // Skip detailed checking if we have enough initializers, and we would 1150 // allow at most one initializer per member. 1151 bool AnyAnonStructUnionMembers = false; 1152 unsigned Fields = 0; 1153 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1154 E = RD->field_end(); I != E; ++I, ++Fields) { 1155 if (I->isAnonymousStructOrUnion()) { 1156 AnyAnonStructUnionMembers = true; 1157 break; 1158 } 1159 } 1160 // DR1460: 1161 // - if the class is a union-like class, but is not a union, for each of 1162 // its anonymous union members having variant members, exactly one of 1163 // them shall be initialized; 1164 if (AnyAnonStructUnionMembers || 1165 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1166 // Check initialization of non-static data members. Base classes are 1167 // always initialized so do not need to be checked. Dependent bases 1168 // might not have initializers in the member initializer list. 1169 llvm::SmallSet<Decl*, 16> Inits; 1170 for (const auto *I: Constructor->inits()) { 1171 if (FieldDecl *FD = I->getMember()) 1172 Inits.insert(FD); 1173 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1174 Inits.insert(ID->chain_begin(), ID->chain_end()); 1175 } 1176 1177 bool Diagnosed = false; 1178 for (auto *I : RD->fields()) 1179 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1180 if (Diagnosed) 1181 return false; 1182 } 1183 } 1184 } else { 1185 if (ReturnStmts.empty()) { 1186 // C++1y doesn't require constexpr functions to contain a 'return' 1187 // statement. We still do, unless the return type might be void, because 1188 // otherwise if there's no return statement, the function cannot 1189 // be used in a core constant expression. 1190 bool OK = getLangOpts().CPlusPlus14 && 1191 (Dcl->getReturnType()->isVoidType() || 1192 Dcl->getReturnType()->isDependentType()); 1193 Diag(Dcl->getLocation(), 1194 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1195 : diag::err_constexpr_body_no_return); 1196 return OK; 1197 } 1198 if (ReturnStmts.size() > 1) { 1199 Diag(ReturnStmts.back(), 1200 getLangOpts().CPlusPlus14 1201 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1202 : diag::ext_constexpr_body_multiple_return); 1203 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1204 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1205 } 1206 } 1207 1208 // C++11 [dcl.constexpr]p5: 1209 // if no function argument values exist such that the function invocation 1210 // substitution would produce a constant expression, the program is 1211 // ill-formed; no diagnostic required. 1212 // C++11 [dcl.constexpr]p3: 1213 // - every constructor call and implicit conversion used in initializing the 1214 // return value shall be one of those allowed in a constant expression. 1215 // C++11 [dcl.constexpr]p4: 1216 // - every constructor involved in initializing non-static data members and 1217 // base class sub-objects shall be a constexpr constructor. 1218 SmallVector<PartialDiagnosticAt, 8> Diags; 1219 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1220 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1221 << isa<CXXConstructorDecl>(Dcl); 1222 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1223 Diag(Diags[I].first, Diags[I].second); 1224 // Don't return false here: we allow this for compatibility in 1225 // system headers. 1226 } 1227 1228 return true; 1229 } 1230 1231 /// isCurrentClassName - Determine whether the identifier II is the 1232 /// name of the class type currently being defined. In the case of 1233 /// nested classes, this will only return true if II is the name of 1234 /// the innermost class. 1235 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1236 const CXXScopeSpec *SS) { 1237 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1238 1239 CXXRecordDecl *CurDecl; 1240 if (SS && SS->isSet() && !SS->isInvalid()) { 1241 DeclContext *DC = computeDeclContext(*SS, true); 1242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1243 } else 1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1245 1246 if (CurDecl && CurDecl->getIdentifier()) 1247 return &II == CurDecl->getIdentifier(); 1248 return false; 1249 } 1250 1251 /// \brief Determine whether the identifier II is a typo for the name of 1252 /// the class type currently being defined. If so, update it to the identifier 1253 /// that should have been used. 1254 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1255 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1256 1257 if (!getLangOpts().SpellChecking) 1258 return false; 1259 1260 CXXRecordDecl *CurDecl; 1261 if (SS && SS->isSet() && !SS->isInvalid()) { 1262 DeclContext *DC = computeDeclContext(*SS, true); 1263 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1264 } else 1265 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1266 1267 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1268 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1269 < II->getLength()) { 1270 II = CurDecl->getIdentifier(); 1271 return true; 1272 } 1273 1274 return false; 1275 } 1276 1277 /// \brief Determine whether the given class is a base class of the given 1278 /// class, including looking at dependent bases. 1279 static bool findCircularInheritance(const CXXRecordDecl *Class, 1280 const CXXRecordDecl *Current) { 1281 SmallVector<const CXXRecordDecl*, 8> Queue; 1282 1283 Class = Class->getCanonicalDecl(); 1284 while (true) { 1285 for (const auto &I : Current->bases()) { 1286 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1287 if (!Base) 1288 continue; 1289 1290 Base = Base->getDefinition(); 1291 if (!Base) 1292 continue; 1293 1294 if (Base->getCanonicalDecl() == Class) 1295 return true; 1296 1297 Queue.push_back(Base); 1298 } 1299 1300 if (Queue.empty()) 1301 return false; 1302 1303 Current = Queue.pop_back_val(); 1304 } 1305 1306 return false; 1307 } 1308 1309 /// \brief Perform propagation of DLL attributes from a derived class to a 1310 /// templated base class for MS compatibility. 1311 static void propagateDLLAttrToBaseClassTemplate( 1312 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1313 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1314 if (getDLLAttr( 1315 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1316 // If the base class template has a DLL attribute, don't try to change it. 1317 return; 1318 } 1319 1320 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1321 // If the base class is not already specialized, we can do the propagation. 1322 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1323 NewAttr->setInherited(true); 1324 BaseTemplateSpec->addAttr(NewAttr); 1325 return; 1326 } 1327 1328 bool DifferentAttribute = false; 1329 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1330 if (!SpecializationAttr->isInherited()) { 1331 // The template has previously been specialized or instantiated with an 1332 // explicit attribute. We should not try to change it. 1333 return; 1334 } 1335 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1336 // The specialization already has the right attribute. 1337 return; 1338 } 1339 DifferentAttribute = true; 1340 } 1341 1342 // The template was previously instantiated or explicitly specialized without 1343 // a dll attribute, or the template was previously instantiated with a 1344 // different inherited attribute. It's too late for us to change the 1345 // attribute, so warn that this is unsupported. 1346 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1347 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1348 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1349 if (BaseTemplateSpec->isExplicitSpecialization()) { 1350 S.Diag(BaseTemplateSpec->getLocation(), 1351 diag::note_template_class_explicit_specialization_was_here) 1352 << BaseTemplateSpec; 1353 } else { 1354 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1355 diag::note_template_class_instantiation_was_here) 1356 << BaseTemplateSpec; 1357 } 1358 } 1359 1360 /// \brief Check the validity of a C++ base class specifier. 1361 /// 1362 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1363 /// and returns NULL otherwise. 1364 CXXBaseSpecifier * 1365 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1366 SourceRange SpecifierRange, 1367 bool Virtual, AccessSpecifier Access, 1368 TypeSourceInfo *TInfo, 1369 SourceLocation EllipsisLoc) { 1370 QualType BaseType = TInfo->getType(); 1371 1372 // C++ [class.union]p1: 1373 // A union shall not have base classes. 1374 if (Class->isUnion()) { 1375 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1376 << SpecifierRange; 1377 return nullptr; 1378 } 1379 1380 if (EllipsisLoc.isValid() && 1381 !TInfo->getType()->containsUnexpandedParameterPack()) { 1382 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1383 << TInfo->getTypeLoc().getSourceRange(); 1384 EllipsisLoc = SourceLocation(); 1385 } 1386 1387 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1388 1389 if (BaseType->isDependentType()) { 1390 // Make sure that we don't have circular inheritance among our dependent 1391 // bases. For non-dependent bases, the check for completeness below handles 1392 // this. 1393 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1394 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1395 ((BaseDecl = BaseDecl->getDefinition()) && 1396 findCircularInheritance(Class, BaseDecl))) { 1397 Diag(BaseLoc, diag::err_circular_inheritance) 1398 << BaseType << Context.getTypeDeclType(Class); 1399 1400 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1401 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1402 << BaseType; 1403 1404 return nullptr; 1405 } 1406 } 1407 1408 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1409 Class->getTagKind() == TTK_Class, 1410 Access, TInfo, EllipsisLoc); 1411 } 1412 1413 // Base specifiers must be record types. 1414 if (!BaseType->isRecordType()) { 1415 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1416 return nullptr; 1417 } 1418 1419 // C++ [class.union]p1: 1420 // A union shall not be used as a base class. 1421 if (BaseType->isUnionType()) { 1422 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1423 return nullptr; 1424 } 1425 1426 // For the MS ABI, propagate DLL attributes to base class templates. 1427 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1428 if (Attr *ClassAttr = getDLLAttr(Class)) { 1429 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1430 BaseType->getAsCXXRecordDecl())) { 1431 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1432 BaseTemplate, BaseLoc); 1433 } 1434 } 1435 } 1436 1437 // C++ [class.derived]p2: 1438 // The class-name in a base-specifier shall not be an incompletely 1439 // defined class. 1440 if (RequireCompleteType(BaseLoc, BaseType, 1441 diag::err_incomplete_base_class, SpecifierRange)) { 1442 Class->setInvalidDecl(); 1443 return nullptr; 1444 } 1445 1446 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1447 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1448 assert(BaseDecl && "Record type has no declaration"); 1449 BaseDecl = BaseDecl->getDefinition(); 1450 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1451 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1452 assert(CXXBaseDecl && "Base type is not a C++ type"); 1453 1454 // A class which contains a flexible array member is not suitable for use as a 1455 // base class: 1456 // - If the layout determines that a base comes before another base, 1457 // the flexible array member would index into the subsequent base. 1458 // - If the layout determines that base comes before the derived class, 1459 // the flexible array member would index into the derived class. 1460 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1461 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1462 << CXXBaseDecl->getDeclName(); 1463 return nullptr; 1464 } 1465 1466 // C++ [class]p3: 1467 // If a class is marked final and it appears as a base-type-specifier in 1468 // base-clause, the program is ill-formed. 1469 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1470 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1471 << CXXBaseDecl->getDeclName() 1472 << FA->isSpelledAsSealed(); 1473 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1474 << CXXBaseDecl->getDeclName() << FA->getRange(); 1475 return nullptr; 1476 } 1477 1478 if (BaseDecl->isInvalidDecl()) 1479 Class->setInvalidDecl(); 1480 1481 // Create the base specifier. 1482 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1483 Class->getTagKind() == TTK_Class, 1484 Access, TInfo, EllipsisLoc); 1485 } 1486 1487 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1488 /// one entry in the base class list of a class specifier, for 1489 /// example: 1490 /// class foo : public bar, virtual private baz { 1491 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1492 BaseResult 1493 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1494 ParsedAttributes &Attributes, 1495 bool Virtual, AccessSpecifier Access, 1496 ParsedType basetype, SourceLocation BaseLoc, 1497 SourceLocation EllipsisLoc) { 1498 if (!classdecl) 1499 return true; 1500 1501 AdjustDeclIfTemplate(classdecl); 1502 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1503 if (!Class) 1504 return true; 1505 1506 // We haven't yet attached the base specifiers. 1507 Class->setIsParsingBaseSpecifiers(); 1508 1509 // We do not support any C++11 attributes on base-specifiers yet. 1510 // Diagnose any attributes we see. 1511 if (!Attributes.empty()) { 1512 for (AttributeList *Attr = Attributes.getList(); Attr; 1513 Attr = Attr->getNext()) { 1514 if (Attr->isInvalid() || 1515 Attr->getKind() == AttributeList::IgnoredAttribute) 1516 continue; 1517 Diag(Attr->getLoc(), 1518 Attr->getKind() == AttributeList::UnknownAttribute 1519 ? diag::warn_unknown_attribute_ignored 1520 : diag::err_base_specifier_attribute) 1521 << Attr->getName(); 1522 } 1523 } 1524 1525 TypeSourceInfo *TInfo = nullptr; 1526 GetTypeFromParser(basetype, &TInfo); 1527 1528 if (EllipsisLoc.isInvalid() && 1529 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1530 UPPC_BaseType)) 1531 return true; 1532 1533 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1534 Virtual, Access, TInfo, 1535 EllipsisLoc)) 1536 return BaseSpec; 1537 else 1538 Class->setInvalidDecl(); 1539 1540 return true; 1541 } 1542 1543 /// \brief Performs the actual work of attaching the given base class 1544 /// specifiers to a C++ class. 1545 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1546 unsigned NumBases) { 1547 if (NumBases == 0) 1548 return false; 1549 1550 // Used to keep track of which base types we have already seen, so 1551 // that we can properly diagnose redundant direct base types. Note 1552 // that the key is always the unqualified canonical type of the base 1553 // class. 1554 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1555 1556 // Copy non-redundant base specifiers into permanent storage. 1557 unsigned NumGoodBases = 0; 1558 bool Invalid = false; 1559 for (unsigned idx = 0; idx < NumBases; ++idx) { 1560 QualType NewBaseType 1561 = Context.getCanonicalType(Bases[idx]->getType()); 1562 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1563 1564 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1565 if (KnownBase) { 1566 // C++ [class.mi]p3: 1567 // A class shall not be specified as a direct base class of a 1568 // derived class more than once. 1569 Diag(Bases[idx]->getLocStart(), 1570 diag::err_duplicate_base_class) 1571 << KnownBase->getType() 1572 << Bases[idx]->getSourceRange(); 1573 1574 // Delete the duplicate base class specifier; we're going to 1575 // overwrite its pointer later. 1576 Context.Deallocate(Bases[idx]); 1577 1578 Invalid = true; 1579 } else { 1580 // Okay, add this new base class. 1581 KnownBase = Bases[idx]; 1582 Bases[NumGoodBases++] = Bases[idx]; 1583 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1584 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1585 if (Class->isInterface() && 1586 (!RD->isInterface() || 1587 KnownBase->getAccessSpecifier() != AS_public)) { 1588 // The Microsoft extension __interface does not permit bases that 1589 // are not themselves public interfaces. 1590 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1591 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1592 << RD->getSourceRange(); 1593 Invalid = true; 1594 } 1595 if (RD->hasAttr<WeakAttr>()) 1596 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1597 } 1598 } 1599 } 1600 1601 // Attach the remaining base class specifiers to the derived class. 1602 Class->setBases(Bases, NumGoodBases); 1603 1604 // Delete the remaining (good) base class specifiers, since their 1605 // data has been copied into the CXXRecordDecl. 1606 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1607 Context.Deallocate(Bases[idx]); 1608 1609 return Invalid; 1610 } 1611 1612 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1613 /// class, after checking whether there are any duplicate base 1614 /// classes. 1615 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1616 unsigned NumBases) { 1617 if (!ClassDecl || !Bases || !NumBases) 1618 return; 1619 1620 AdjustDeclIfTemplate(ClassDecl); 1621 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1622 } 1623 1624 /// \brief Determine whether the type \p Derived is a C++ class that is 1625 /// derived from the type \p Base. 1626 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1627 if (!getLangOpts().CPlusPlus) 1628 return false; 1629 1630 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1631 if (!DerivedRD) 1632 return false; 1633 1634 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1635 if (!BaseRD) 1636 return false; 1637 1638 // If either the base or the derived type is invalid, don't try to 1639 // check whether one is derived from the other. 1640 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1641 return false; 1642 1643 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1644 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1645 } 1646 1647 /// \brief Determine whether the type \p Derived is a C++ class that is 1648 /// derived from the type \p Base. 1649 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1650 if (!getLangOpts().CPlusPlus) 1651 return false; 1652 1653 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1654 if (!DerivedRD) 1655 return false; 1656 1657 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1658 if (!BaseRD) 1659 return false; 1660 1661 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1662 } 1663 1664 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1665 CXXCastPath &BasePathArray) { 1666 assert(BasePathArray.empty() && "Base path array must be empty!"); 1667 assert(Paths.isRecordingPaths() && "Must record paths!"); 1668 1669 const CXXBasePath &Path = Paths.front(); 1670 1671 // We first go backward and check if we have a virtual base. 1672 // FIXME: It would be better if CXXBasePath had the base specifier for 1673 // the nearest virtual base. 1674 unsigned Start = 0; 1675 for (unsigned I = Path.size(); I != 0; --I) { 1676 if (Path[I - 1].Base->isVirtual()) { 1677 Start = I - 1; 1678 break; 1679 } 1680 } 1681 1682 // Now add all bases. 1683 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1684 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1685 } 1686 1687 /// \brief Determine whether the given base path includes a virtual 1688 /// base class. 1689 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1690 for (CXXCastPath::const_iterator B = BasePath.begin(), 1691 BEnd = BasePath.end(); 1692 B != BEnd; ++B) 1693 if ((*B)->isVirtual()) 1694 return true; 1695 1696 return false; 1697 } 1698 1699 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1700 /// conversion (where Derived and Base are class types) is 1701 /// well-formed, meaning that the conversion is unambiguous (and 1702 /// that all of the base classes are accessible). Returns true 1703 /// and emits a diagnostic if the code is ill-formed, returns false 1704 /// otherwise. Loc is the location where this routine should point to 1705 /// if there is an error, and Range is the source range to highlight 1706 /// if there is an error. 1707 bool 1708 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1709 unsigned InaccessibleBaseID, 1710 unsigned AmbigiousBaseConvID, 1711 SourceLocation Loc, SourceRange Range, 1712 DeclarationName Name, 1713 CXXCastPath *BasePath) { 1714 // First, determine whether the path from Derived to Base is 1715 // ambiguous. This is slightly more expensive than checking whether 1716 // the Derived to Base conversion exists, because here we need to 1717 // explore multiple paths to determine if there is an ambiguity. 1718 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1719 /*DetectVirtual=*/false); 1720 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1721 assert(DerivationOkay && 1722 "Can only be used with a derived-to-base conversion"); 1723 (void)DerivationOkay; 1724 1725 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1726 if (InaccessibleBaseID) { 1727 // Check that the base class can be accessed. 1728 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1729 InaccessibleBaseID)) { 1730 case AR_inaccessible: 1731 return true; 1732 case AR_accessible: 1733 case AR_dependent: 1734 case AR_delayed: 1735 break; 1736 } 1737 } 1738 1739 // Build a base path if necessary. 1740 if (BasePath) 1741 BuildBasePathArray(Paths, *BasePath); 1742 return false; 1743 } 1744 1745 if (AmbigiousBaseConvID) { 1746 // We know that the derived-to-base conversion is ambiguous, and 1747 // we're going to produce a diagnostic. Perform the derived-to-base 1748 // search just one more time to compute all of the possible paths so 1749 // that we can print them out. This is more expensive than any of 1750 // the previous derived-to-base checks we've done, but at this point 1751 // performance isn't as much of an issue. 1752 Paths.clear(); 1753 Paths.setRecordingPaths(true); 1754 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1755 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1756 (void)StillOkay; 1757 1758 // Build up a textual representation of the ambiguous paths, e.g., 1759 // D -> B -> A, that will be used to illustrate the ambiguous 1760 // conversions in the diagnostic. We only print one of the paths 1761 // to each base class subobject. 1762 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1763 1764 Diag(Loc, AmbigiousBaseConvID) 1765 << Derived << Base << PathDisplayStr << Range << Name; 1766 } 1767 return true; 1768 } 1769 1770 bool 1771 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1772 SourceLocation Loc, SourceRange Range, 1773 CXXCastPath *BasePath, 1774 bool IgnoreAccess) { 1775 return CheckDerivedToBaseConversion(Derived, Base, 1776 IgnoreAccess ? 0 1777 : diag::err_upcast_to_inaccessible_base, 1778 diag::err_ambiguous_derived_to_base_conv, 1779 Loc, Range, DeclarationName(), 1780 BasePath); 1781 } 1782 1783 1784 /// @brief Builds a string representing ambiguous paths from a 1785 /// specific derived class to different subobjects of the same base 1786 /// class. 1787 /// 1788 /// This function builds a string that can be used in error messages 1789 /// to show the different paths that one can take through the 1790 /// inheritance hierarchy to go from the derived class to different 1791 /// subobjects of a base class. The result looks something like this: 1792 /// @code 1793 /// struct D -> struct B -> struct A 1794 /// struct D -> struct C -> struct A 1795 /// @endcode 1796 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1797 std::string PathDisplayStr; 1798 std::set<unsigned> DisplayedPaths; 1799 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1800 Path != Paths.end(); ++Path) { 1801 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1802 // We haven't displayed a path to this particular base 1803 // class subobject yet. 1804 PathDisplayStr += "\n "; 1805 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1806 for (CXXBasePath::const_iterator Element = Path->begin(); 1807 Element != Path->end(); ++Element) 1808 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1809 } 1810 } 1811 1812 return PathDisplayStr; 1813 } 1814 1815 //===----------------------------------------------------------------------===// 1816 // C++ class member Handling 1817 //===----------------------------------------------------------------------===// 1818 1819 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1820 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1821 SourceLocation ASLoc, 1822 SourceLocation ColonLoc, 1823 AttributeList *Attrs) { 1824 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1825 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1826 ASLoc, ColonLoc); 1827 CurContext->addHiddenDecl(ASDecl); 1828 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1829 } 1830 1831 /// CheckOverrideControl - Check C++11 override control semantics. 1832 void Sema::CheckOverrideControl(NamedDecl *D) { 1833 if (D->isInvalidDecl()) 1834 return; 1835 1836 // We only care about "override" and "final" declarations. 1837 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1838 return; 1839 1840 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1841 1842 // We can't check dependent instance methods. 1843 if (MD && MD->isInstance() && 1844 (MD->getParent()->hasAnyDependentBases() || 1845 MD->getType()->isDependentType())) 1846 return; 1847 1848 if (MD && !MD->isVirtual()) { 1849 // If we have a non-virtual method, check if if hides a virtual method. 1850 // (In that case, it's most likely the method has the wrong type.) 1851 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1852 FindHiddenVirtualMethods(MD, OverloadedMethods); 1853 1854 if (!OverloadedMethods.empty()) { 1855 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1856 Diag(OA->getLocation(), 1857 diag::override_keyword_hides_virtual_member_function) 1858 << "override" << (OverloadedMethods.size() > 1); 1859 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1860 Diag(FA->getLocation(), 1861 diag::override_keyword_hides_virtual_member_function) 1862 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1863 << (OverloadedMethods.size() > 1); 1864 } 1865 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1866 MD->setInvalidDecl(); 1867 return; 1868 } 1869 // Fall through into the general case diagnostic. 1870 // FIXME: We might want to attempt typo correction here. 1871 } 1872 1873 if (!MD || !MD->isVirtual()) { 1874 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1875 Diag(OA->getLocation(), 1876 diag::override_keyword_only_allowed_on_virtual_member_functions) 1877 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1878 D->dropAttr<OverrideAttr>(); 1879 } 1880 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1881 Diag(FA->getLocation(), 1882 diag::override_keyword_only_allowed_on_virtual_member_functions) 1883 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1884 << FixItHint::CreateRemoval(FA->getLocation()); 1885 D->dropAttr<FinalAttr>(); 1886 } 1887 return; 1888 } 1889 1890 // C++11 [class.virtual]p5: 1891 // If a function is marked with the virt-specifier override and 1892 // does not override a member function of a base class, the program is 1893 // ill-formed. 1894 bool HasOverriddenMethods = 1895 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1896 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1897 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1898 << MD->getDeclName(); 1899 } 1900 1901 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1902 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1903 return; 1904 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1905 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1906 isa<CXXDestructorDecl>(MD)) 1907 return; 1908 1909 SourceLocation Loc = MD->getLocation(); 1910 SourceLocation SpellingLoc = Loc; 1911 if (getSourceManager().isMacroArgExpansion(Loc)) 1912 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1913 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1914 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1915 return; 1916 1917 if (MD->size_overridden_methods() > 0) { 1918 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 1919 << MD->getDeclName(); 1920 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 1921 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 1922 } 1923 } 1924 1925 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1926 /// function overrides a virtual member function marked 'final', according to 1927 /// C++11 [class.virtual]p4. 1928 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1929 const CXXMethodDecl *Old) { 1930 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1931 if (!FA) 1932 return false; 1933 1934 Diag(New->getLocation(), diag::err_final_function_overridden) 1935 << New->getDeclName() 1936 << FA->isSpelledAsSealed(); 1937 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1938 return true; 1939 } 1940 1941 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1942 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1943 // FIXME: Destruction of ObjC lifetime types has side-effects. 1944 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1945 return !RD->isCompleteDefinition() || 1946 !RD->hasTrivialDefaultConstructor() || 1947 !RD->hasTrivialDestructor(); 1948 return false; 1949 } 1950 1951 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1952 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1953 if (it->isDeclspecPropertyAttribute()) 1954 return it; 1955 return nullptr; 1956 } 1957 1958 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1959 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1960 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1961 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1962 /// present (but parsing it has been deferred). 1963 NamedDecl * 1964 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1965 MultiTemplateParamsArg TemplateParameterLists, 1966 Expr *BW, const VirtSpecifiers &VS, 1967 InClassInitStyle InitStyle) { 1968 const DeclSpec &DS = D.getDeclSpec(); 1969 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1970 DeclarationName Name = NameInfo.getName(); 1971 SourceLocation Loc = NameInfo.getLoc(); 1972 1973 // For anonymous bitfields, the location should point to the type. 1974 if (Loc.isInvalid()) 1975 Loc = D.getLocStart(); 1976 1977 Expr *BitWidth = static_cast<Expr*>(BW); 1978 1979 assert(isa<CXXRecordDecl>(CurContext)); 1980 assert(!DS.isFriendSpecified()); 1981 1982 bool isFunc = D.isDeclarationOfFunction(); 1983 1984 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1985 // The Microsoft extension __interface only permits public member functions 1986 // and prohibits constructors, destructors, operators, non-public member 1987 // functions, static methods and data members. 1988 unsigned InvalidDecl; 1989 bool ShowDeclName = true; 1990 if (!isFunc) 1991 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1992 else if (AS != AS_public) 1993 InvalidDecl = 2; 1994 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1995 InvalidDecl = 3; 1996 else switch (Name.getNameKind()) { 1997 case DeclarationName::CXXConstructorName: 1998 InvalidDecl = 4; 1999 ShowDeclName = false; 2000 break; 2001 2002 case DeclarationName::CXXDestructorName: 2003 InvalidDecl = 5; 2004 ShowDeclName = false; 2005 break; 2006 2007 case DeclarationName::CXXOperatorName: 2008 case DeclarationName::CXXConversionFunctionName: 2009 InvalidDecl = 6; 2010 break; 2011 2012 default: 2013 InvalidDecl = 0; 2014 break; 2015 } 2016 2017 if (InvalidDecl) { 2018 if (ShowDeclName) 2019 Diag(Loc, diag::err_invalid_member_in_interface) 2020 << (InvalidDecl-1) << Name; 2021 else 2022 Diag(Loc, diag::err_invalid_member_in_interface) 2023 << (InvalidDecl-1) << ""; 2024 return nullptr; 2025 } 2026 } 2027 2028 // C++ 9.2p6: A member shall not be declared to have automatic storage 2029 // duration (auto, register) or with the extern storage-class-specifier. 2030 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2031 // data members and cannot be applied to names declared const or static, 2032 // and cannot be applied to reference members. 2033 switch (DS.getStorageClassSpec()) { 2034 case DeclSpec::SCS_unspecified: 2035 case DeclSpec::SCS_typedef: 2036 case DeclSpec::SCS_static: 2037 break; 2038 case DeclSpec::SCS_mutable: 2039 if (isFunc) { 2040 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2041 2042 // FIXME: It would be nicer if the keyword was ignored only for this 2043 // declarator. Otherwise we could get follow-up errors. 2044 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2045 } 2046 break; 2047 default: 2048 Diag(DS.getStorageClassSpecLoc(), 2049 diag::err_storageclass_invalid_for_member); 2050 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2051 break; 2052 } 2053 2054 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2055 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2056 !isFunc); 2057 2058 if (DS.isConstexprSpecified() && isInstField) { 2059 SemaDiagnosticBuilder B = 2060 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2061 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2062 if (InitStyle == ICIS_NoInit) { 2063 B << 0 << 0; 2064 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2065 B << FixItHint::CreateRemoval(ConstexprLoc); 2066 else { 2067 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2068 D.getMutableDeclSpec().ClearConstexprSpec(); 2069 const char *PrevSpec; 2070 unsigned DiagID; 2071 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2072 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2073 (void)Failed; 2074 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2075 } 2076 } else { 2077 B << 1; 2078 const char *PrevSpec; 2079 unsigned DiagID; 2080 if (D.getMutableDeclSpec().SetStorageClassSpec( 2081 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2082 Context.getPrintingPolicy())) { 2083 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2084 "This is the only DeclSpec that should fail to be applied"); 2085 B << 1; 2086 } else { 2087 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2088 isInstField = false; 2089 } 2090 } 2091 } 2092 2093 NamedDecl *Member; 2094 if (isInstField) { 2095 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2096 2097 // Data members must have identifiers for names. 2098 if (!Name.isIdentifier()) { 2099 Diag(Loc, diag::err_bad_variable_name) 2100 << Name; 2101 return nullptr; 2102 } 2103 2104 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2105 2106 // Member field could not be with "template" keyword. 2107 // So TemplateParameterLists should be empty in this case. 2108 if (TemplateParameterLists.size()) { 2109 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2110 if (TemplateParams->size()) { 2111 // There is no such thing as a member field template. 2112 Diag(D.getIdentifierLoc(), diag::err_template_member) 2113 << II 2114 << SourceRange(TemplateParams->getTemplateLoc(), 2115 TemplateParams->getRAngleLoc()); 2116 } else { 2117 // There is an extraneous 'template<>' for this member. 2118 Diag(TemplateParams->getTemplateLoc(), 2119 diag::err_template_member_noparams) 2120 << II 2121 << SourceRange(TemplateParams->getTemplateLoc(), 2122 TemplateParams->getRAngleLoc()); 2123 } 2124 return nullptr; 2125 } 2126 2127 if (SS.isSet() && !SS.isInvalid()) { 2128 // The user provided a superfluous scope specifier inside a class 2129 // definition: 2130 // 2131 // class X { 2132 // int X::member; 2133 // }; 2134 if (DeclContext *DC = computeDeclContext(SS, false)) 2135 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2136 else 2137 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2138 << Name << SS.getRange(); 2139 2140 SS.clear(); 2141 } 2142 2143 AttributeList *MSPropertyAttr = 2144 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2145 if (MSPropertyAttr) { 2146 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2147 BitWidth, InitStyle, AS, MSPropertyAttr); 2148 if (!Member) 2149 return nullptr; 2150 isInstField = false; 2151 } else { 2152 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2153 BitWidth, InitStyle, AS); 2154 assert(Member && "HandleField never returns null"); 2155 } 2156 } else { 2157 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2158 2159 Member = HandleDeclarator(S, D, TemplateParameterLists); 2160 if (!Member) 2161 return nullptr; 2162 2163 // Non-instance-fields can't have a bitfield. 2164 if (BitWidth) { 2165 if (Member->isInvalidDecl()) { 2166 // don't emit another diagnostic. 2167 } else if (isa<VarDecl>(Member)) { 2168 // C++ 9.6p3: A bit-field shall not be a static member. 2169 // "static member 'A' cannot be a bit-field" 2170 Diag(Loc, diag::err_static_not_bitfield) 2171 << Name << BitWidth->getSourceRange(); 2172 } else if (isa<TypedefDecl>(Member)) { 2173 // "typedef member 'x' cannot be a bit-field" 2174 Diag(Loc, diag::err_typedef_not_bitfield) 2175 << Name << BitWidth->getSourceRange(); 2176 } else { 2177 // A function typedef ("typedef int f(); f a;"). 2178 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2179 Diag(Loc, diag::err_not_integral_type_bitfield) 2180 << Name << cast<ValueDecl>(Member)->getType() 2181 << BitWidth->getSourceRange(); 2182 } 2183 2184 BitWidth = nullptr; 2185 Member->setInvalidDecl(); 2186 } 2187 2188 Member->setAccess(AS); 2189 2190 // If we have declared a member function template or static data member 2191 // template, set the access of the templated declaration as well. 2192 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2193 FunTmpl->getTemplatedDecl()->setAccess(AS); 2194 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2195 VarTmpl->getTemplatedDecl()->setAccess(AS); 2196 } 2197 2198 if (VS.isOverrideSpecified()) 2199 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2200 if (VS.isFinalSpecified()) 2201 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2202 VS.isFinalSpelledSealed())); 2203 2204 if (VS.getLastLocation().isValid()) { 2205 // Update the end location of a method that has a virt-specifiers. 2206 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2207 MD->setRangeEnd(VS.getLastLocation()); 2208 } 2209 2210 CheckOverrideControl(Member); 2211 2212 assert((Name || isInstField) && "No identifier for non-field ?"); 2213 2214 if (isInstField) { 2215 FieldDecl *FD = cast<FieldDecl>(Member); 2216 FieldCollector->Add(FD); 2217 2218 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2219 // Remember all explicit private FieldDecls that have a name, no side 2220 // effects and are not part of a dependent type declaration. 2221 if (!FD->isImplicit() && FD->getDeclName() && 2222 FD->getAccess() == AS_private && 2223 !FD->hasAttr<UnusedAttr>() && 2224 !FD->getParent()->isDependentContext() && 2225 !InitializationHasSideEffects(*FD)) 2226 UnusedPrivateFields.insert(FD); 2227 } 2228 } 2229 2230 return Member; 2231 } 2232 2233 namespace { 2234 class UninitializedFieldVisitor 2235 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2236 Sema &S; 2237 // List of Decls to generate a warning on. Also remove Decls that become 2238 // initialized. 2239 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2240 // List of base classes of the record. Classes are removed after their 2241 // initializers. 2242 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 2243 // Vector of decls to be removed from the Decl set prior to visiting the 2244 // nodes. These Decls may have been initialized in the prior initializer. 2245 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2246 // If non-null, add a note to the warning pointing back to the constructor. 2247 const CXXConstructorDecl *Constructor; 2248 // Variables to hold state when processing an initializer list. When 2249 // InitList is true, special case initialization of FieldDecls matching 2250 // InitListFieldDecl. 2251 bool InitList; 2252 FieldDecl *InitListFieldDecl; 2253 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2254 2255 public: 2256 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2257 UninitializedFieldVisitor(Sema &S, 2258 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 2259 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 2260 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 2261 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 2262 2263 // Returns true if the use of ME is not an uninitialized use. 2264 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2265 bool CheckReferenceOnly) { 2266 llvm::SmallVector<FieldDecl*, 4> Fields; 2267 bool ReferenceField = false; 2268 while (ME) { 2269 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2270 if (!FD) 2271 return false; 2272 Fields.push_back(FD); 2273 if (FD->getType()->isReferenceType()) 2274 ReferenceField = true; 2275 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2276 } 2277 2278 // Binding a reference to an unintialized field is not an 2279 // uninitialized use. 2280 if (CheckReferenceOnly && !ReferenceField) 2281 return true; 2282 2283 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2284 // Discard the first field since it is the field decl that is being 2285 // initialized. 2286 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2287 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2288 } 2289 2290 for (auto UsedIter = UsedFieldIndex.begin(), 2291 UsedEnd = UsedFieldIndex.end(), 2292 OrigIter = InitFieldIndex.begin(), 2293 OrigEnd = InitFieldIndex.end(); 2294 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2295 if (*UsedIter < *OrigIter) 2296 return true; 2297 if (*UsedIter > *OrigIter) 2298 break; 2299 } 2300 2301 return false; 2302 } 2303 2304 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2305 bool AddressOf) { 2306 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2307 return; 2308 2309 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2310 // or union. 2311 MemberExpr *FieldME = ME; 2312 2313 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2314 2315 Expr *Base = ME; 2316 while (MemberExpr *SubME = 2317 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 2318 2319 if (isa<VarDecl>(SubME->getMemberDecl())) 2320 return; 2321 2322 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2323 if (!FD->isAnonymousStructOrUnion()) 2324 FieldME = SubME; 2325 2326 if (!FieldME->getType().isPODType(S.Context)) 2327 AllPODFields = false; 2328 2329 Base = SubME->getBase(); 2330 } 2331 2332 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 2333 return; 2334 2335 if (AddressOf && AllPODFields) 2336 return; 2337 2338 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2339 2340 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 2341 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 2342 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 2343 } 2344 2345 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 2346 QualType T = BaseCast->getType(); 2347 if (T->isPointerType() && 2348 BaseClasses.count(T->getPointeeType())) { 2349 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 2350 << T->getPointeeType() << FoundVD; 2351 } 2352 } 2353 } 2354 2355 if (!Decls.count(FoundVD)) 2356 return; 2357 2358 const bool IsReference = FoundVD->getType()->isReferenceType(); 2359 2360 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2361 // Special checking for initializer lists. 2362 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2363 return; 2364 } 2365 } else { 2366 // Prevent double warnings on use of unbounded references. 2367 if (CheckReferenceOnly && !IsReference) 2368 return; 2369 } 2370 2371 unsigned diag = IsReference 2372 ? diag::warn_reference_field_is_uninit 2373 : diag::warn_field_is_uninit; 2374 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2375 if (Constructor) 2376 S.Diag(Constructor->getLocation(), 2377 diag::note_uninit_in_this_constructor) 2378 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2379 2380 } 2381 2382 void HandleValue(Expr *E, bool AddressOf) { 2383 E = E->IgnoreParens(); 2384 2385 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2386 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2387 AddressOf /*AddressOf*/); 2388 return; 2389 } 2390 2391 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2392 Visit(CO->getCond()); 2393 HandleValue(CO->getTrueExpr(), AddressOf); 2394 HandleValue(CO->getFalseExpr(), AddressOf); 2395 return; 2396 } 2397 2398 if (BinaryConditionalOperator *BCO = 2399 dyn_cast<BinaryConditionalOperator>(E)) { 2400 Visit(BCO->getCond()); 2401 HandleValue(BCO->getFalseExpr(), AddressOf); 2402 return; 2403 } 2404 2405 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2406 HandleValue(OVE->getSourceExpr(), AddressOf); 2407 return; 2408 } 2409 2410 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2411 switch (BO->getOpcode()) { 2412 default: 2413 break; 2414 case(BO_PtrMemD): 2415 case(BO_PtrMemI): 2416 HandleValue(BO->getLHS(), AddressOf); 2417 Visit(BO->getRHS()); 2418 return; 2419 case(BO_Comma): 2420 Visit(BO->getLHS()); 2421 HandleValue(BO->getRHS(), AddressOf); 2422 return; 2423 } 2424 } 2425 2426 Visit(E); 2427 } 2428 2429 void CheckInitListExpr(InitListExpr *ILE) { 2430 InitFieldIndex.push_back(0); 2431 for (auto Child : ILE->children()) { 2432 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2433 CheckInitListExpr(SubList); 2434 } else { 2435 Visit(Child); 2436 } 2437 ++InitFieldIndex.back(); 2438 } 2439 InitFieldIndex.pop_back(); 2440 } 2441 2442 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2443 FieldDecl *Field, const Type *BaseClass) { 2444 // Remove Decls that may have been initialized in the previous 2445 // initializer. 2446 for (ValueDecl* VD : DeclsToRemove) 2447 Decls.erase(VD); 2448 DeclsToRemove.clear(); 2449 2450 Constructor = FieldConstructor; 2451 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2452 2453 if (ILE && Field) { 2454 InitList = true; 2455 InitListFieldDecl = Field; 2456 InitFieldIndex.clear(); 2457 CheckInitListExpr(ILE); 2458 } else { 2459 InitList = false; 2460 Visit(E); 2461 } 2462 2463 if (Field) 2464 Decls.erase(Field); 2465 if (BaseClass) 2466 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 2467 } 2468 2469 void VisitMemberExpr(MemberExpr *ME) { 2470 // All uses of unbounded reference fields will warn. 2471 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2472 } 2473 2474 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2475 if (E->getCastKind() == CK_LValueToRValue) { 2476 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2477 return; 2478 } 2479 2480 Inherited::VisitImplicitCastExpr(E); 2481 } 2482 2483 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2484 if (E->getConstructor()->isCopyConstructor()) { 2485 Expr *ArgExpr = E->getArg(0); 2486 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2487 if (ILE->getNumInits() == 1) 2488 ArgExpr = ILE->getInit(0); 2489 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2490 if (ICE->getCastKind() == CK_NoOp) 2491 ArgExpr = ICE->getSubExpr(); 2492 HandleValue(ArgExpr, false /*AddressOf*/); 2493 return; 2494 } 2495 Inherited::VisitCXXConstructExpr(E); 2496 } 2497 2498 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2499 Expr *Callee = E->getCallee(); 2500 if (isa<MemberExpr>(Callee)) { 2501 HandleValue(Callee, false /*AddressOf*/); 2502 for (auto Arg : E->arguments()) 2503 Visit(Arg); 2504 return; 2505 } 2506 2507 Inherited::VisitCXXMemberCallExpr(E); 2508 } 2509 2510 void VisitCallExpr(CallExpr *E) { 2511 // Treat std::move as a use. 2512 if (E->getNumArgs() == 1) { 2513 if (FunctionDecl *FD = E->getDirectCallee()) { 2514 if (FD->isInStdNamespace() && FD->getIdentifier() && 2515 FD->getIdentifier()->isStr("move")) { 2516 HandleValue(E->getArg(0), false /*AddressOf*/); 2517 return; 2518 } 2519 } 2520 } 2521 2522 Inherited::VisitCallExpr(E); 2523 } 2524 2525 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2526 Expr *Callee = E->getCallee(); 2527 2528 if (isa<UnresolvedLookupExpr>(Callee)) 2529 return Inherited::VisitCXXOperatorCallExpr(E); 2530 2531 Visit(Callee); 2532 for (auto Arg : E->arguments()) 2533 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2534 } 2535 2536 void VisitBinaryOperator(BinaryOperator *E) { 2537 // If a field assignment is detected, remove the field from the 2538 // uninitiailized field set. 2539 if (E->getOpcode() == BO_Assign) 2540 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2541 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2542 if (!FD->getType()->isReferenceType()) 2543 DeclsToRemove.push_back(FD); 2544 2545 if (E->isCompoundAssignmentOp()) { 2546 HandleValue(E->getLHS(), false /*AddressOf*/); 2547 Visit(E->getRHS()); 2548 return; 2549 } 2550 2551 Inherited::VisitBinaryOperator(E); 2552 } 2553 2554 void VisitUnaryOperator(UnaryOperator *E) { 2555 if (E->isIncrementDecrementOp()) { 2556 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2557 return; 2558 } 2559 if (E->getOpcode() == UO_AddrOf) { 2560 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2561 HandleValue(ME->getBase(), true /*AddressOf*/); 2562 return; 2563 } 2564 } 2565 2566 Inherited::VisitUnaryOperator(E); 2567 } 2568 }; 2569 2570 // Diagnose value-uses of fields to initialize themselves, e.g. 2571 // foo(foo) 2572 // where foo is not also a parameter to the constructor. 2573 // Also diagnose across field uninitialized use such as 2574 // x(y), y(x) 2575 // TODO: implement -Wuninitialized and fold this into that framework. 2576 static void DiagnoseUninitializedFields( 2577 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2578 2579 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2580 Constructor->getLocation())) { 2581 return; 2582 } 2583 2584 if (Constructor->isInvalidDecl()) 2585 return; 2586 2587 const CXXRecordDecl *RD = Constructor->getParent(); 2588 2589 if (RD->getDescribedClassTemplate()) 2590 return; 2591 2592 // Holds fields that are uninitialized. 2593 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2594 2595 // At the beginning, all fields are uninitialized. 2596 for (auto *I : RD->decls()) { 2597 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2598 UninitializedFields.insert(FD); 2599 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2600 UninitializedFields.insert(IFD->getAnonField()); 2601 } 2602 } 2603 2604 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 2605 for (auto I : RD->bases()) 2606 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 2607 2608 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2609 return; 2610 2611 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2612 UninitializedFields, 2613 UninitializedBaseClasses); 2614 2615 for (const auto *FieldInit : Constructor->inits()) { 2616 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2617 break; 2618 2619 Expr *InitExpr = FieldInit->getInit(); 2620 if (!InitExpr) 2621 continue; 2622 2623 if (CXXDefaultInitExpr *Default = 2624 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2625 InitExpr = Default->getExpr(); 2626 if (!InitExpr) 2627 continue; 2628 // In class initializers will point to the constructor. 2629 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2630 FieldInit->getAnyMember(), 2631 FieldInit->getBaseClass()); 2632 } else { 2633 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2634 FieldInit->getAnyMember(), 2635 FieldInit->getBaseClass()); 2636 } 2637 } 2638 } 2639 } // namespace 2640 2641 /// \brief Enter a new C++ default initializer scope. After calling this, the 2642 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2643 /// parsing or instantiating the initializer failed. 2644 void Sema::ActOnStartCXXInClassMemberInitializer() { 2645 // Create a synthetic function scope to represent the call to the constructor 2646 // that notionally surrounds a use of this initializer. 2647 PushFunctionScope(); 2648 } 2649 2650 /// \brief This is invoked after parsing an in-class initializer for a 2651 /// non-static C++ class member, and after instantiating an in-class initializer 2652 /// in a class template. Such actions are deferred until the class is complete. 2653 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2654 SourceLocation InitLoc, 2655 Expr *InitExpr) { 2656 // Pop the notional constructor scope we created earlier. 2657 PopFunctionScopeInfo(nullptr, D); 2658 2659 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2660 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 2661 "must set init style when field is created"); 2662 2663 if (!InitExpr) { 2664 D->setInvalidDecl(); 2665 if (FD) 2666 FD->removeInClassInitializer(); 2667 return; 2668 } 2669 2670 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2671 FD->setInvalidDecl(); 2672 FD->removeInClassInitializer(); 2673 return; 2674 } 2675 2676 ExprResult Init = InitExpr; 2677 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2678 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2679 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2680 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2681 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2682 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2683 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2684 if (Init.isInvalid()) { 2685 FD->setInvalidDecl(); 2686 return; 2687 } 2688 } 2689 2690 // C++11 [class.base.init]p7: 2691 // The initialization of each base and member constitutes a 2692 // full-expression. 2693 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2694 if (Init.isInvalid()) { 2695 FD->setInvalidDecl(); 2696 return; 2697 } 2698 2699 InitExpr = Init.get(); 2700 2701 FD->setInClassInitializer(InitExpr); 2702 } 2703 2704 /// \brief Find the direct and/or virtual base specifiers that 2705 /// correspond to the given base type, for use in base initialization 2706 /// within a constructor. 2707 static bool FindBaseInitializer(Sema &SemaRef, 2708 CXXRecordDecl *ClassDecl, 2709 QualType BaseType, 2710 const CXXBaseSpecifier *&DirectBaseSpec, 2711 const CXXBaseSpecifier *&VirtualBaseSpec) { 2712 // First, check for a direct base class. 2713 DirectBaseSpec = nullptr; 2714 for (const auto &Base : ClassDecl->bases()) { 2715 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2716 // We found a direct base of this type. That's what we're 2717 // initializing. 2718 DirectBaseSpec = &Base; 2719 break; 2720 } 2721 } 2722 2723 // Check for a virtual base class. 2724 // FIXME: We might be able to short-circuit this if we know in advance that 2725 // there are no virtual bases. 2726 VirtualBaseSpec = nullptr; 2727 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2728 // We haven't found a base yet; search the class hierarchy for a 2729 // virtual base class. 2730 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2731 /*DetectVirtual=*/false); 2732 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2733 BaseType, Paths)) { 2734 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2735 Path != Paths.end(); ++Path) { 2736 if (Path->back().Base->isVirtual()) { 2737 VirtualBaseSpec = Path->back().Base; 2738 break; 2739 } 2740 } 2741 } 2742 } 2743 2744 return DirectBaseSpec || VirtualBaseSpec; 2745 } 2746 2747 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2748 MemInitResult 2749 Sema::ActOnMemInitializer(Decl *ConstructorD, 2750 Scope *S, 2751 CXXScopeSpec &SS, 2752 IdentifierInfo *MemberOrBase, 2753 ParsedType TemplateTypeTy, 2754 const DeclSpec &DS, 2755 SourceLocation IdLoc, 2756 Expr *InitList, 2757 SourceLocation EllipsisLoc) { 2758 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2759 DS, IdLoc, InitList, 2760 EllipsisLoc); 2761 } 2762 2763 /// \brief Handle a C++ member initializer using parentheses syntax. 2764 MemInitResult 2765 Sema::ActOnMemInitializer(Decl *ConstructorD, 2766 Scope *S, 2767 CXXScopeSpec &SS, 2768 IdentifierInfo *MemberOrBase, 2769 ParsedType TemplateTypeTy, 2770 const DeclSpec &DS, 2771 SourceLocation IdLoc, 2772 SourceLocation LParenLoc, 2773 ArrayRef<Expr *> Args, 2774 SourceLocation RParenLoc, 2775 SourceLocation EllipsisLoc) { 2776 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2777 Args, RParenLoc); 2778 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2779 DS, IdLoc, List, EllipsisLoc); 2780 } 2781 2782 namespace { 2783 2784 // Callback to only accept typo corrections that can be a valid C++ member 2785 // intializer: either a non-static field member or a base class. 2786 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2787 public: 2788 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2789 : ClassDecl(ClassDecl) {} 2790 2791 bool ValidateCandidate(const TypoCorrection &candidate) override { 2792 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2793 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2794 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2795 return isa<TypeDecl>(ND); 2796 } 2797 return false; 2798 } 2799 2800 private: 2801 CXXRecordDecl *ClassDecl; 2802 }; 2803 2804 } 2805 2806 /// \brief Handle a C++ member initializer. 2807 MemInitResult 2808 Sema::BuildMemInitializer(Decl *ConstructorD, 2809 Scope *S, 2810 CXXScopeSpec &SS, 2811 IdentifierInfo *MemberOrBase, 2812 ParsedType TemplateTypeTy, 2813 const DeclSpec &DS, 2814 SourceLocation IdLoc, 2815 Expr *Init, 2816 SourceLocation EllipsisLoc) { 2817 ExprResult Res = CorrectDelayedTyposInExpr(Init); 2818 if (!Res.isUsable()) 2819 return true; 2820 Init = Res.get(); 2821 2822 if (!ConstructorD) 2823 return true; 2824 2825 AdjustDeclIfTemplate(ConstructorD); 2826 2827 CXXConstructorDecl *Constructor 2828 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2829 if (!Constructor) { 2830 // The user wrote a constructor initializer on a function that is 2831 // not a C++ constructor. Ignore the error for now, because we may 2832 // have more member initializers coming; we'll diagnose it just 2833 // once in ActOnMemInitializers. 2834 return true; 2835 } 2836 2837 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2838 2839 // C++ [class.base.init]p2: 2840 // Names in a mem-initializer-id are looked up in the scope of the 2841 // constructor's class and, if not found in that scope, are looked 2842 // up in the scope containing the constructor's definition. 2843 // [Note: if the constructor's class contains a member with the 2844 // same name as a direct or virtual base class of the class, a 2845 // mem-initializer-id naming the member or base class and composed 2846 // of a single identifier refers to the class member. A 2847 // mem-initializer-id for the hidden base class may be specified 2848 // using a qualified name. ] 2849 if (!SS.getScopeRep() && !TemplateTypeTy) { 2850 // Look for a member, first. 2851 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2852 if (!Result.empty()) { 2853 ValueDecl *Member; 2854 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2855 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2856 if (EllipsisLoc.isValid()) 2857 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2858 << MemberOrBase 2859 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2860 2861 return BuildMemberInitializer(Member, Init, IdLoc); 2862 } 2863 } 2864 } 2865 // It didn't name a member, so see if it names a class. 2866 QualType BaseType; 2867 TypeSourceInfo *TInfo = nullptr; 2868 2869 if (TemplateTypeTy) { 2870 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2871 } else if (DS.getTypeSpecType() == TST_decltype) { 2872 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2873 } else { 2874 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2875 LookupParsedName(R, S, &SS); 2876 2877 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2878 if (!TyD) { 2879 if (R.isAmbiguous()) return true; 2880 2881 // We don't want access-control diagnostics here. 2882 R.suppressDiagnostics(); 2883 2884 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2885 bool NotUnknownSpecialization = false; 2886 DeclContext *DC = computeDeclContext(SS, false); 2887 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2888 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2889 2890 if (!NotUnknownSpecialization) { 2891 // When the scope specifier can refer to a member of an unknown 2892 // specialization, we take it as a type name. 2893 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2894 SS.getWithLocInContext(Context), 2895 *MemberOrBase, IdLoc); 2896 if (BaseType.isNull()) 2897 return true; 2898 2899 R.clear(); 2900 R.setLookupName(MemberOrBase); 2901 } 2902 } 2903 2904 // If no results were found, try to correct typos. 2905 TypoCorrection Corr; 2906 if (R.empty() && BaseType.isNull() && 2907 (Corr = CorrectTypo( 2908 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2909 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2910 CTK_ErrorRecovery, ClassDecl))) { 2911 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2912 // We have found a non-static data member with a similar 2913 // name to what was typed; complain and initialize that 2914 // member. 2915 diagnoseTypo(Corr, 2916 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2917 << MemberOrBase << true); 2918 return BuildMemberInitializer(Member, Init, IdLoc); 2919 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2920 const CXXBaseSpecifier *DirectBaseSpec; 2921 const CXXBaseSpecifier *VirtualBaseSpec; 2922 if (FindBaseInitializer(*this, ClassDecl, 2923 Context.getTypeDeclType(Type), 2924 DirectBaseSpec, VirtualBaseSpec)) { 2925 // We have found a direct or virtual base class with a 2926 // similar name to what was typed; complain and initialize 2927 // that base class. 2928 diagnoseTypo(Corr, 2929 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2930 << MemberOrBase << false, 2931 PDiag() /*Suppress note, we provide our own.*/); 2932 2933 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2934 : VirtualBaseSpec; 2935 Diag(BaseSpec->getLocStart(), 2936 diag::note_base_class_specified_here) 2937 << BaseSpec->getType() 2938 << BaseSpec->getSourceRange(); 2939 2940 TyD = Type; 2941 } 2942 } 2943 } 2944 2945 if (!TyD && BaseType.isNull()) { 2946 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2947 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2948 return true; 2949 } 2950 } 2951 2952 if (BaseType.isNull()) { 2953 BaseType = Context.getTypeDeclType(TyD); 2954 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 2955 if (SS.isSet()) 2956 // FIXME: preserve source range information 2957 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2958 BaseType); 2959 } 2960 } 2961 2962 if (!TInfo) 2963 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2964 2965 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2966 } 2967 2968 /// Checks a member initializer expression for cases where reference (or 2969 /// pointer) members are bound to by-value parameters (or their addresses). 2970 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2971 Expr *Init, 2972 SourceLocation IdLoc) { 2973 QualType MemberTy = Member->getType(); 2974 2975 // We only handle pointers and references currently. 2976 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2977 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2978 return; 2979 2980 const bool IsPointer = MemberTy->isPointerType(); 2981 if (IsPointer) { 2982 if (const UnaryOperator *Op 2983 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2984 // The only case we're worried about with pointers requires taking the 2985 // address. 2986 if (Op->getOpcode() != UO_AddrOf) 2987 return; 2988 2989 Init = Op->getSubExpr(); 2990 } else { 2991 // We only handle address-of expression initializers for pointers. 2992 return; 2993 } 2994 } 2995 2996 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2997 // We only warn when referring to a non-reference parameter declaration. 2998 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2999 if (!Parameter || Parameter->getType()->isReferenceType()) 3000 return; 3001 3002 S.Diag(Init->getExprLoc(), 3003 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3004 : diag::warn_bind_ref_member_to_parameter) 3005 << Member << Parameter << Init->getSourceRange(); 3006 } else { 3007 // Other initializers are fine. 3008 return; 3009 } 3010 3011 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3012 << (unsigned)IsPointer; 3013 } 3014 3015 MemInitResult 3016 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3017 SourceLocation IdLoc) { 3018 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3019 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3020 assert((DirectMember || IndirectMember) && 3021 "Member must be a FieldDecl or IndirectFieldDecl"); 3022 3023 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3024 return true; 3025 3026 if (Member->isInvalidDecl()) 3027 return true; 3028 3029 MultiExprArg Args; 3030 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3031 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3032 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3033 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3034 } else { 3035 // Template instantiation doesn't reconstruct ParenListExprs for us. 3036 Args = Init; 3037 } 3038 3039 SourceRange InitRange = Init->getSourceRange(); 3040 3041 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3042 // Can't check initialization for a member of dependent type or when 3043 // any of the arguments are type-dependent expressions. 3044 DiscardCleanupsInEvaluationContext(); 3045 } else { 3046 bool InitList = false; 3047 if (isa<InitListExpr>(Init)) { 3048 InitList = true; 3049 Args = Init; 3050 } 3051 3052 // Initialize the member. 3053 InitializedEntity MemberEntity = 3054 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3055 : InitializedEntity::InitializeMember(IndirectMember, 3056 nullptr); 3057 InitializationKind Kind = 3058 InitList ? InitializationKind::CreateDirectList(IdLoc) 3059 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3060 InitRange.getEnd()); 3061 3062 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3063 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3064 nullptr); 3065 if (MemberInit.isInvalid()) 3066 return true; 3067 3068 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3069 3070 // C++11 [class.base.init]p7: 3071 // The initialization of each base and member constitutes a 3072 // full-expression. 3073 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3074 if (MemberInit.isInvalid()) 3075 return true; 3076 3077 Init = MemberInit.get(); 3078 } 3079 3080 if (DirectMember) { 3081 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3082 InitRange.getBegin(), Init, 3083 InitRange.getEnd()); 3084 } else { 3085 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3086 InitRange.getBegin(), Init, 3087 InitRange.getEnd()); 3088 } 3089 } 3090 3091 MemInitResult 3092 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3093 CXXRecordDecl *ClassDecl) { 3094 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3095 if (!LangOpts.CPlusPlus11) 3096 return Diag(NameLoc, diag::err_delegating_ctor) 3097 << TInfo->getTypeLoc().getLocalSourceRange(); 3098 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3099 3100 bool InitList = true; 3101 MultiExprArg Args = Init; 3102 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3103 InitList = false; 3104 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3105 } 3106 3107 SourceRange InitRange = Init->getSourceRange(); 3108 // Initialize the object. 3109 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3110 QualType(ClassDecl->getTypeForDecl(), 0)); 3111 InitializationKind Kind = 3112 InitList ? InitializationKind::CreateDirectList(NameLoc) 3113 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3114 InitRange.getEnd()); 3115 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3116 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3117 Args, nullptr); 3118 if (DelegationInit.isInvalid()) 3119 return true; 3120 3121 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3122 "Delegating constructor with no target?"); 3123 3124 // C++11 [class.base.init]p7: 3125 // The initialization of each base and member constitutes a 3126 // full-expression. 3127 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3128 InitRange.getBegin()); 3129 if (DelegationInit.isInvalid()) 3130 return true; 3131 3132 // If we are in a dependent context, template instantiation will 3133 // perform this type-checking again. Just save the arguments that we 3134 // received in a ParenListExpr. 3135 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3136 // of the information that we have about the base 3137 // initializer. However, deconstructing the ASTs is a dicey process, 3138 // and this approach is far more likely to get the corner cases right. 3139 if (CurContext->isDependentContext()) 3140 DelegationInit = Init; 3141 3142 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3143 DelegationInit.getAs<Expr>(), 3144 InitRange.getEnd()); 3145 } 3146 3147 MemInitResult 3148 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3149 Expr *Init, CXXRecordDecl *ClassDecl, 3150 SourceLocation EllipsisLoc) { 3151 SourceLocation BaseLoc 3152 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3153 3154 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3155 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3156 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3157 3158 // C++ [class.base.init]p2: 3159 // [...] Unless the mem-initializer-id names a nonstatic data 3160 // member of the constructor's class or a direct or virtual base 3161 // of that class, the mem-initializer is ill-formed. A 3162 // mem-initializer-list can initialize a base class using any 3163 // name that denotes that base class type. 3164 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3165 3166 SourceRange InitRange = Init->getSourceRange(); 3167 if (EllipsisLoc.isValid()) { 3168 // This is a pack expansion. 3169 if (!BaseType->containsUnexpandedParameterPack()) { 3170 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3171 << SourceRange(BaseLoc, InitRange.getEnd()); 3172 3173 EllipsisLoc = SourceLocation(); 3174 } 3175 } else { 3176 // Check for any unexpanded parameter packs. 3177 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3178 return true; 3179 3180 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3181 return true; 3182 } 3183 3184 // Check for direct and virtual base classes. 3185 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3186 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3187 if (!Dependent) { 3188 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3189 BaseType)) 3190 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3191 3192 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3193 VirtualBaseSpec); 3194 3195 // C++ [base.class.init]p2: 3196 // Unless the mem-initializer-id names a nonstatic data member of the 3197 // constructor's class or a direct or virtual base of that class, the 3198 // mem-initializer is ill-formed. 3199 if (!DirectBaseSpec && !VirtualBaseSpec) { 3200 // If the class has any dependent bases, then it's possible that 3201 // one of those types will resolve to the same type as 3202 // BaseType. Therefore, just treat this as a dependent base 3203 // class initialization. FIXME: Should we try to check the 3204 // initialization anyway? It seems odd. 3205 if (ClassDecl->hasAnyDependentBases()) 3206 Dependent = true; 3207 else 3208 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3209 << BaseType << Context.getTypeDeclType(ClassDecl) 3210 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3211 } 3212 } 3213 3214 if (Dependent) { 3215 DiscardCleanupsInEvaluationContext(); 3216 3217 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3218 /*IsVirtual=*/false, 3219 InitRange.getBegin(), Init, 3220 InitRange.getEnd(), EllipsisLoc); 3221 } 3222 3223 // C++ [base.class.init]p2: 3224 // If a mem-initializer-id is ambiguous because it designates both 3225 // a direct non-virtual base class and an inherited virtual base 3226 // class, the mem-initializer is ill-formed. 3227 if (DirectBaseSpec && VirtualBaseSpec) 3228 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3229 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3230 3231 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3232 if (!BaseSpec) 3233 BaseSpec = VirtualBaseSpec; 3234 3235 // Initialize the base. 3236 bool InitList = true; 3237 MultiExprArg Args = Init; 3238 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3239 InitList = false; 3240 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3241 } 3242 3243 InitializedEntity BaseEntity = 3244 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3245 InitializationKind Kind = 3246 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3247 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3248 InitRange.getEnd()); 3249 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3250 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3251 if (BaseInit.isInvalid()) 3252 return true; 3253 3254 // C++11 [class.base.init]p7: 3255 // The initialization of each base and member constitutes a 3256 // full-expression. 3257 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3258 if (BaseInit.isInvalid()) 3259 return true; 3260 3261 // If we are in a dependent context, template instantiation will 3262 // perform this type-checking again. Just save the arguments that we 3263 // received in a ParenListExpr. 3264 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3265 // of the information that we have about the base 3266 // initializer. However, deconstructing the ASTs is a dicey process, 3267 // and this approach is far more likely to get the corner cases right. 3268 if (CurContext->isDependentContext()) 3269 BaseInit = Init; 3270 3271 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3272 BaseSpec->isVirtual(), 3273 InitRange.getBegin(), 3274 BaseInit.getAs<Expr>(), 3275 InitRange.getEnd(), EllipsisLoc); 3276 } 3277 3278 // Create a static_cast\<T&&>(expr). 3279 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3280 if (T.isNull()) T = E->getType(); 3281 QualType TargetType = SemaRef.BuildReferenceType( 3282 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3283 SourceLocation ExprLoc = E->getLocStart(); 3284 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3285 TargetType, ExprLoc); 3286 3287 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3288 SourceRange(ExprLoc, ExprLoc), 3289 E->getSourceRange()).get(); 3290 } 3291 3292 /// ImplicitInitializerKind - How an implicit base or member initializer should 3293 /// initialize its base or member. 3294 enum ImplicitInitializerKind { 3295 IIK_Default, 3296 IIK_Copy, 3297 IIK_Move, 3298 IIK_Inherit 3299 }; 3300 3301 static bool 3302 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3303 ImplicitInitializerKind ImplicitInitKind, 3304 CXXBaseSpecifier *BaseSpec, 3305 bool IsInheritedVirtualBase, 3306 CXXCtorInitializer *&CXXBaseInit) { 3307 InitializedEntity InitEntity 3308 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3309 IsInheritedVirtualBase); 3310 3311 ExprResult BaseInit; 3312 3313 switch (ImplicitInitKind) { 3314 case IIK_Inherit: { 3315 const CXXRecordDecl *Inherited = 3316 Constructor->getInheritedConstructor()->getParent(); 3317 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3318 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3319 // C++11 [class.inhctor]p8: 3320 // Each expression in the expression-list is of the form 3321 // static_cast<T&&>(p), where p is the name of the corresponding 3322 // constructor parameter and T is the declared type of p. 3323 SmallVector<Expr*, 16> Args; 3324 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3325 ParmVarDecl *PD = Constructor->getParamDecl(I); 3326 ExprResult ArgExpr = 3327 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3328 VK_LValue, SourceLocation()); 3329 if (ArgExpr.isInvalid()) 3330 return true; 3331 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3332 } 3333 3334 InitializationKind InitKind = InitializationKind::CreateDirect( 3335 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3336 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3337 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3338 break; 3339 } 3340 } 3341 // Fall through. 3342 case IIK_Default: { 3343 InitializationKind InitKind 3344 = InitializationKind::CreateDefault(Constructor->getLocation()); 3345 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3346 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3347 break; 3348 } 3349 3350 case IIK_Move: 3351 case IIK_Copy: { 3352 bool Moving = ImplicitInitKind == IIK_Move; 3353 ParmVarDecl *Param = Constructor->getParamDecl(0); 3354 QualType ParamType = Param->getType().getNonReferenceType(); 3355 3356 Expr *CopyCtorArg = 3357 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3358 SourceLocation(), Param, false, 3359 Constructor->getLocation(), ParamType, 3360 VK_LValue, nullptr); 3361 3362 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3363 3364 // Cast to the base class to avoid ambiguities. 3365 QualType ArgTy = 3366 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3367 ParamType.getQualifiers()); 3368 3369 if (Moving) { 3370 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3371 } 3372 3373 CXXCastPath BasePath; 3374 BasePath.push_back(BaseSpec); 3375 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3376 CK_UncheckedDerivedToBase, 3377 Moving ? VK_XValue : VK_LValue, 3378 &BasePath).get(); 3379 3380 InitializationKind InitKind 3381 = InitializationKind::CreateDirect(Constructor->getLocation(), 3382 SourceLocation(), SourceLocation()); 3383 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3384 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3385 break; 3386 } 3387 } 3388 3389 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3390 if (BaseInit.isInvalid()) 3391 return true; 3392 3393 CXXBaseInit = 3394 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3395 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3396 SourceLocation()), 3397 BaseSpec->isVirtual(), 3398 SourceLocation(), 3399 BaseInit.getAs<Expr>(), 3400 SourceLocation(), 3401 SourceLocation()); 3402 3403 return false; 3404 } 3405 3406 static bool RefersToRValueRef(Expr *MemRef) { 3407 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3408 return Referenced->getType()->isRValueReferenceType(); 3409 } 3410 3411 static bool 3412 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3413 ImplicitInitializerKind ImplicitInitKind, 3414 FieldDecl *Field, IndirectFieldDecl *Indirect, 3415 CXXCtorInitializer *&CXXMemberInit) { 3416 if (Field->isInvalidDecl()) 3417 return true; 3418 3419 SourceLocation Loc = Constructor->getLocation(); 3420 3421 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3422 bool Moving = ImplicitInitKind == IIK_Move; 3423 ParmVarDecl *Param = Constructor->getParamDecl(0); 3424 QualType ParamType = Param->getType().getNonReferenceType(); 3425 3426 // Suppress copying zero-width bitfields. 3427 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3428 return false; 3429 3430 Expr *MemberExprBase = 3431 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3432 SourceLocation(), Param, false, 3433 Loc, ParamType, VK_LValue, nullptr); 3434 3435 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3436 3437 if (Moving) { 3438 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3439 } 3440 3441 // Build a reference to this field within the parameter. 3442 CXXScopeSpec SS; 3443 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3444 Sema::LookupMemberName); 3445 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3446 : cast<ValueDecl>(Field), AS_public); 3447 MemberLookup.resolveKind(); 3448 ExprResult CtorArg 3449 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3450 ParamType, Loc, 3451 /*IsArrow=*/false, 3452 SS, 3453 /*TemplateKWLoc=*/SourceLocation(), 3454 /*FirstQualifierInScope=*/nullptr, 3455 MemberLookup, 3456 /*TemplateArgs=*/nullptr); 3457 if (CtorArg.isInvalid()) 3458 return true; 3459 3460 // C++11 [class.copy]p15: 3461 // - if a member m has rvalue reference type T&&, it is direct-initialized 3462 // with static_cast<T&&>(x.m); 3463 if (RefersToRValueRef(CtorArg.get())) { 3464 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3465 } 3466 3467 // When the field we are copying is an array, create index variables for 3468 // each dimension of the array. We use these index variables to subscript 3469 // the source array, and other clients (e.g., CodeGen) will perform the 3470 // necessary iteration with these index variables. 3471 SmallVector<VarDecl *, 4> IndexVariables; 3472 QualType BaseType = Field->getType(); 3473 QualType SizeType = SemaRef.Context.getSizeType(); 3474 bool InitializingArray = false; 3475 while (const ConstantArrayType *Array 3476 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3477 InitializingArray = true; 3478 // Create the iteration variable for this array index. 3479 IdentifierInfo *IterationVarName = nullptr; 3480 { 3481 SmallString<8> Str; 3482 llvm::raw_svector_ostream OS(Str); 3483 OS << "__i" << IndexVariables.size(); 3484 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3485 } 3486 VarDecl *IterationVar 3487 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3488 IterationVarName, SizeType, 3489 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3490 SC_None); 3491 IndexVariables.push_back(IterationVar); 3492 3493 // Create a reference to the iteration variable. 3494 ExprResult IterationVarRef 3495 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3496 assert(!IterationVarRef.isInvalid() && 3497 "Reference to invented variable cannot fail!"); 3498 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3499 assert(!IterationVarRef.isInvalid() && 3500 "Conversion of invented variable cannot fail!"); 3501 3502 // Subscript the array with this iteration variable. 3503 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3504 IterationVarRef.get(), 3505 Loc); 3506 if (CtorArg.isInvalid()) 3507 return true; 3508 3509 BaseType = Array->getElementType(); 3510 } 3511 3512 // The array subscript expression is an lvalue, which is wrong for moving. 3513 if (Moving && InitializingArray) 3514 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3515 3516 // Construct the entity that we will be initializing. For an array, this 3517 // will be first element in the array, which may require several levels 3518 // of array-subscript entities. 3519 SmallVector<InitializedEntity, 4> Entities; 3520 Entities.reserve(1 + IndexVariables.size()); 3521 if (Indirect) 3522 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3523 else 3524 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3525 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3526 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3527 0, 3528 Entities.back())); 3529 3530 // Direct-initialize to use the copy constructor. 3531 InitializationKind InitKind = 3532 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3533 3534 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3535 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3536 3537 ExprResult MemberInit 3538 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3539 MultiExprArg(&CtorArgE, 1)); 3540 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3541 if (MemberInit.isInvalid()) 3542 return true; 3543 3544 if (Indirect) { 3545 assert(IndexVariables.size() == 0 && 3546 "Indirect field improperly initialized"); 3547 CXXMemberInit 3548 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3549 Loc, Loc, 3550 MemberInit.getAs<Expr>(), 3551 Loc); 3552 } else 3553 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3554 Loc, MemberInit.getAs<Expr>(), 3555 Loc, 3556 IndexVariables.data(), 3557 IndexVariables.size()); 3558 return false; 3559 } 3560 3561 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3562 "Unhandled implicit init kind!"); 3563 3564 QualType FieldBaseElementType = 3565 SemaRef.Context.getBaseElementType(Field->getType()); 3566 3567 if (FieldBaseElementType->isRecordType()) { 3568 InitializedEntity InitEntity 3569 = Indirect? InitializedEntity::InitializeMember(Indirect) 3570 : InitializedEntity::InitializeMember(Field); 3571 InitializationKind InitKind = 3572 InitializationKind::CreateDefault(Loc); 3573 3574 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3575 ExprResult MemberInit = 3576 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3577 3578 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3579 if (MemberInit.isInvalid()) 3580 return true; 3581 3582 if (Indirect) 3583 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3584 Indirect, Loc, 3585 Loc, 3586 MemberInit.get(), 3587 Loc); 3588 else 3589 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3590 Field, Loc, Loc, 3591 MemberInit.get(), 3592 Loc); 3593 return false; 3594 } 3595 3596 if (!Field->getParent()->isUnion()) { 3597 if (FieldBaseElementType->isReferenceType()) { 3598 SemaRef.Diag(Constructor->getLocation(), 3599 diag::err_uninitialized_member_in_ctor) 3600 << (int)Constructor->isImplicit() 3601 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3602 << 0 << Field->getDeclName(); 3603 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3604 return true; 3605 } 3606 3607 if (FieldBaseElementType.isConstQualified()) { 3608 SemaRef.Diag(Constructor->getLocation(), 3609 diag::err_uninitialized_member_in_ctor) 3610 << (int)Constructor->isImplicit() 3611 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3612 << 1 << Field->getDeclName(); 3613 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3614 return true; 3615 } 3616 } 3617 3618 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3619 FieldBaseElementType->isObjCRetainableType() && 3620 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3621 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3622 // ARC: 3623 // Default-initialize Objective-C pointers to NULL. 3624 CXXMemberInit 3625 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3626 Loc, Loc, 3627 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3628 Loc); 3629 return false; 3630 } 3631 3632 // Nothing to initialize. 3633 CXXMemberInit = nullptr; 3634 return false; 3635 } 3636 3637 namespace { 3638 struct BaseAndFieldInfo { 3639 Sema &S; 3640 CXXConstructorDecl *Ctor; 3641 bool AnyErrorsInInits; 3642 ImplicitInitializerKind IIK; 3643 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3644 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3645 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3646 3647 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3648 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3649 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3650 if (Generated && Ctor->isCopyConstructor()) 3651 IIK = IIK_Copy; 3652 else if (Generated && Ctor->isMoveConstructor()) 3653 IIK = IIK_Move; 3654 else if (Ctor->getInheritedConstructor()) 3655 IIK = IIK_Inherit; 3656 else 3657 IIK = IIK_Default; 3658 } 3659 3660 bool isImplicitCopyOrMove() const { 3661 switch (IIK) { 3662 case IIK_Copy: 3663 case IIK_Move: 3664 return true; 3665 3666 case IIK_Default: 3667 case IIK_Inherit: 3668 return false; 3669 } 3670 3671 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3672 } 3673 3674 bool addFieldInitializer(CXXCtorInitializer *Init) { 3675 AllToInit.push_back(Init); 3676 3677 // Check whether this initializer makes the field "used". 3678 if (Init->getInit()->HasSideEffects(S.Context)) 3679 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3680 3681 return false; 3682 } 3683 3684 bool isInactiveUnionMember(FieldDecl *Field) { 3685 RecordDecl *Record = Field->getParent(); 3686 if (!Record->isUnion()) 3687 return false; 3688 3689 if (FieldDecl *Active = 3690 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3691 return Active != Field->getCanonicalDecl(); 3692 3693 // In an implicit copy or move constructor, ignore any in-class initializer. 3694 if (isImplicitCopyOrMove()) 3695 return true; 3696 3697 // If there's no explicit initialization, the field is active only if it 3698 // has an in-class initializer... 3699 if (Field->hasInClassInitializer()) 3700 return false; 3701 // ... or it's an anonymous struct or union whose class has an in-class 3702 // initializer. 3703 if (!Field->isAnonymousStructOrUnion()) 3704 return true; 3705 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3706 return !FieldRD->hasInClassInitializer(); 3707 } 3708 3709 /// \brief Determine whether the given field is, or is within, a union member 3710 /// that is inactive (because there was an initializer given for a different 3711 /// member of the union, or because the union was not initialized at all). 3712 bool isWithinInactiveUnionMember(FieldDecl *Field, 3713 IndirectFieldDecl *Indirect) { 3714 if (!Indirect) 3715 return isInactiveUnionMember(Field); 3716 3717 for (auto *C : Indirect->chain()) { 3718 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3719 if (Field && isInactiveUnionMember(Field)) 3720 return true; 3721 } 3722 return false; 3723 } 3724 }; 3725 } 3726 3727 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3728 /// array type. 3729 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3730 if (T->isIncompleteArrayType()) 3731 return true; 3732 3733 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3734 if (!ArrayT->getSize()) 3735 return true; 3736 3737 T = ArrayT->getElementType(); 3738 } 3739 3740 return false; 3741 } 3742 3743 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3744 FieldDecl *Field, 3745 IndirectFieldDecl *Indirect = nullptr) { 3746 if (Field->isInvalidDecl()) 3747 return false; 3748 3749 // Overwhelmingly common case: we have a direct initializer for this field. 3750 if (CXXCtorInitializer *Init = 3751 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3752 return Info.addFieldInitializer(Init); 3753 3754 // C++11 [class.base.init]p8: 3755 // if the entity is a non-static data member that has a 3756 // brace-or-equal-initializer and either 3757 // -- the constructor's class is a union and no other variant member of that 3758 // union is designated by a mem-initializer-id or 3759 // -- the constructor's class is not a union, and, if the entity is a member 3760 // of an anonymous union, no other member of that union is designated by 3761 // a mem-initializer-id, 3762 // the entity is initialized as specified in [dcl.init]. 3763 // 3764 // We also apply the same rules to handle anonymous structs within anonymous 3765 // unions. 3766 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3767 return false; 3768 3769 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3770 ExprResult DIE = 3771 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3772 if (DIE.isInvalid()) 3773 return true; 3774 CXXCtorInitializer *Init; 3775 if (Indirect) 3776 Init = new (SemaRef.Context) 3777 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3778 SourceLocation(), DIE.get(), SourceLocation()); 3779 else 3780 Init = new (SemaRef.Context) 3781 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3782 SourceLocation(), DIE.get(), SourceLocation()); 3783 return Info.addFieldInitializer(Init); 3784 } 3785 3786 // Don't initialize incomplete or zero-length arrays. 3787 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3788 return false; 3789 3790 // Don't try to build an implicit initializer if there were semantic 3791 // errors in any of the initializers (and therefore we might be 3792 // missing some that the user actually wrote). 3793 if (Info.AnyErrorsInInits) 3794 return false; 3795 3796 CXXCtorInitializer *Init = nullptr; 3797 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3798 Indirect, Init)) 3799 return true; 3800 3801 if (!Init) 3802 return false; 3803 3804 return Info.addFieldInitializer(Init); 3805 } 3806 3807 bool 3808 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3809 CXXCtorInitializer *Initializer) { 3810 assert(Initializer->isDelegatingInitializer()); 3811 Constructor->setNumCtorInitializers(1); 3812 CXXCtorInitializer **initializer = 3813 new (Context) CXXCtorInitializer*[1]; 3814 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3815 Constructor->setCtorInitializers(initializer); 3816 3817 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3818 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3819 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3820 } 3821 3822 DelegatingCtorDecls.push_back(Constructor); 3823 3824 DiagnoseUninitializedFields(*this, Constructor); 3825 3826 return false; 3827 } 3828 3829 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3830 ArrayRef<CXXCtorInitializer *> Initializers) { 3831 if (Constructor->isDependentContext()) { 3832 // Just store the initializers as written, they will be checked during 3833 // instantiation. 3834 if (!Initializers.empty()) { 3835 Constructor->setNumCtorInitializers(Initializers.size()); 3836 CXXCtorInitializer **baseOrMemberInitializers = 3837 new (Context) CXXCtorInitializer*[Initializers.size()]; 3838 memcpy(baseOrMemberInitializers, Initializers.data(), 3839 Initializers.size() * sizeof(CXXCtorInitializer*)); 3840 Constructor->setCtorInitializers(baseOrMemberInitializers); 3841 } 3842 3843 // Let template instantiation know whether we had errors. 3844 if (AnyErrors) 3845 Constructor->setInvalidDecl(); 3846 3847 return false; 3848 } 3849 3850 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3851 3852 // We need to build the initializer AST according to order of construction 3853 // and not what user specified in the Initializers list. 3854 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3855 if (!ClassDecl) 3856 return true; 3857 3858 bool HadError = false; 3859 3860 for (unsigned i = 0; i < Initializers.size(); i++) { 3861 CXXCtorInitializer *Member = Initializers[i]; 3862 3863 if (Member->isBaseInitializer()) 3864 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3865 else { 3866 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3867 3868 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3869 for (auto *C : F->chain()) { 3870 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3871 if (FD && FD->getParent()->isUnion()) 3872 Info.ActiveUnionMember.insert(std::make_pair( 3873 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3874 } 3875 } else if (FieldDecl *FD = Member->getMember()) { 3876 if (FD->getParent()->isUnion()) 3877 Info.ActiveUnionMember.insert(std::make_pair( 3878 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3879 } 3880 } 3881 } 3882 3883 // Keep track of the direct virtual bases. 3884 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3885 for (auto &I : ClassDecl->bases()) { 3886 if (I.isVirtual()) 3887 DirectVBases.insert(&I); 3888 } 3889 3890 // Push virtual bases before others. 3891 for (auto &VBase : ClassDecl->vbases()) { 3892 if (CXXCtorInitializer *Value 3893 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3894 // [class.base.init]p7, per DR257: 3895 // A mem-initializer where the mem-initializer-id names a virtual base 3896 // class is ignored during execution of a constructor of any class that 3897 // is not the most derived class. 3898 if (ClassDecl->isAbstract()) { 3899 // FIXME: Provide a fixit to remove the base specifier. This requires 3900 // tracking the location of the associated comma for a base specifier. 3901 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3902 << VBase.getType() << ClassDecl; 3903 DiagnoseAbstractType(ClassDecl); 3904 } 3905 3906 Info.AllToInit.push_back(Value); 3907 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3908 // [class.base.init]p8, per DR257: 3909 // If a given [...] base class is not named by a mem-initializer-id 3910 // [...] and the entity is not a virtual base class of an abstract 3911 // class, then [...] the entity is default-initialized. 3912 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3913 CXXCtorInitializer *CXXBaseInit; 3914 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3915 &VBase, IsInheritedVirtualBase, 3916 CXXBaseInit)) { 3917 HadError = true; 3918 continue; 3919 } 3920 3921 Info.AllToInit.push_back(CXXBaseInit); 3922 } 3923 } 3924 3925 // Non-virtual bases. 3926 for (auto &Base : ClassDecl->bases()) { 3927 // Virtuals are in the virtual base list and already constructed. 3928 if (Base.isVirtual()) 3929 continue; 3930 3931 if (CXXCtorInitializer *Value 3932 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3933 Info.AllToInit.push_back(Value); 3934 } else if (!AnyErrors) { 3935 CXXCtorInitializer *CXXBaseInit; 3936 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3937 &Base, /*IsInheritedVirtualBase=*/false, 3938 CXXBaseInit)) { 3939 HadError = true; 3940 continue; 3941 } 3942 3943 Info.AllToInit.push_back(CXXBaseInit); 3944 } 3945 } 3946 3947 // Fields. 3948 for (auto *Mem : ClassDecl->decls()) { 3949 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3950 // C++ [class.bit]p2: 3951 // A declaration for a bit-field that omits the identifier declares an 3952 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3953 // initialized. 3954 if (F->isUnnamedBitfield()) 3955 continue; 3956 3957 // If we're not generating the implicit copy/move constructor, then we'll 3958 // handle anonymous struct/union fields based on their individual 3959 // indirect fields. 3960 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3961 continue; 3962 3963 if (CollectFieldInitializer(*this, Info, F)) 3964 HadError = true; 3965 continue; 3966 } 3967 3968 // Beyond this point, we only consider default initialization. 3969 if (Info.isImplicitCopyOrMove()) 3970 continue; 3971 3972 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3973 if (F->getType()->isIncompleteArrayType()) { 3974 assert(ClassDecl->hasFlexibleArrayMember() && 3975 "Incomplete array type is not valid"); 3976 continue; 3977 } 3978 3979 // Initialize each field of an anonymous struct individually. 3980 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3981 HadError = true; 3982 3983 continue; 3984 } 3985 } 3986 3987 unsigned NumInitializers = Info.AllToInit.size(); 3988 if (NumInitializers > 0) { 3989 Constructor->setNumCtorInitializers(NumInitializers); 3990 CXXCtorInitializer **baseOrMemberInitializers = 3991 new (Context) CXXCtorInitializer*[NumInitializers]; 3992 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3993 NumInitializers * sizeof(CXXCtorInitializer*)); 3994 Constructor->setCtorInitializers(baseOrMemberInitializers); 3995 3996 // Constructors implicitly reference the base and member 3997 // destructors. 3998 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3999 Constructor->getParent()); 4000 } 4001 4002 return HadError; 4003 } 4004 4005 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4006 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4007 const RecordDecl *RD = RT->getDecl(); 4008 if (RD->isAnonymousStructOrUnion()) { 4009 for (auto *Field : RD->fields()) 4010 PopulateKeysForFields(Field, IdealInits); 4011 return; 4012 } 4013 } 4014 IdealInits.push_back(Field->getCanonicalDecl()); 4015 } 4016 4017 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4018 return Context.getCanonicalType(BaseType).getTypePtr(); 4019 } 4020 4021 static const void *GetKeyForMember(ASTContext &Context, 4022 CXXCtorInitializer *Member) { 4023 if (!Member->isAnyMemberInitializer()) 4024 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4025 4026 return Member->getAnyMember()->getCanonicalDecl(); 4027 } 4028 4029 static void DiagnoseBaseOrMemInitializerOrder( 4030 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4031 ArrayRef<CXXCtorInitializer *> Inits) { 4032 if (Constructor->getDeclContext()->isDependentContext()) 4033 return; 4034 4035 // Don't check initializers order unless the warning is enabled at the 4036 // location of at least one initializer. 4037 bool ShouldCheckOrder = false; 4038 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4039 CXXCtorInitializer *Init = Inits[InitIndex]; 4040 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4041 Init->getSourceLocation())) { 4042 ShouldCheckOrder = true; 4043 break; 4044 } 4045 } 4046 if (!ShouldCheckOrder) 4047 return; 4048 4049 // Build the list of bases and members in the order that they'll 4050 // actually be initialized. The explicit initializers should be in 4051 // this same order but may be missing things. 4052 SmallVector<const void*, 32> IdealInitKeys; 4053 4054 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4055 4056 // 1. Virtual bases. 4057 for (const auto &VBase : ClassDecl->vbases()) 4058 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4059 4060 // 2. Non-virtual bases. 4061 for (const auto &Base : ClassDecl->bases()) { 4062 if (Base.isVirtual()) 4063 continue; 4064 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4065 } 4066 4067 // 3. Direct fields. 4068 for (auto *Field : ClassDecl->fields()) { 4069 if (Field->isUnnamedBitfield()) 4070 continue; 4071 4072 PopulateKeysForFields(Field, IdealInitKeys); 4073 } 4074 4075 unsigned NumIdealInits = IdealInitKeys.size(); 4076 unsigned IdealIndex = 0; 4077 4078 CXXCtorInitializer *PrevInit = nullptr; 4079 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4080 CXXCtorInitializer *Init = Inits[InitIndex]; 4081 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4082 4083 // Scan forward to try to find this initializer in the idealized 4084 // initializers list. 4085 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4086 if (InitKey == IdealInitKeys[IdealIndex]) 4087 break; 4088 4089 // If we didn't find this initializer, it must be because we 4090 // scanned past it on a previous iteration. That can only 4091 // happen if we're out of order; emit a warning. 4092 if (IdealIndex == NumIdealInits && PrevInit) { 4093 Sema::SemaDiagnosticBuilder D = 4094 SemaRef.Diag(PrevInit->getSourceLocation(), 4095 diag::warn_initializer_out_of_order); 4096 4097 if (PrevInit->isAnyMemberInitializer()) 4098 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4099 else 4100 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4101 4102 if (Init->isAnyMemberInitializer()) 4103 D << 0 << Init->getAnyMember()->getDeclName(); 4104 else 4105 D << 1 << Init->getTypeSourceInfo()->getType(); 4106 4107 // Move back to the initializer's location in the ideal list. 4108 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4109 if (InitKey == IdealInitKeys[IdealIndex]) 4110 break; 4111 4112 assert(IdealIndex != NumIdealInits && 4113 "initializer not found in initializer list"); 4114 } 4115 4116 PrevInit = Init; 4117 } 4118 } 4119 4120 namespace { 4121 bool CheckRedundantInit(Sema &S, 4122 CXXCtorInitializer *Init, 4123 CXXCtorInitializer *&PrevInit) { 4124 if (!PrevInit) { 4125 PrevInit = Init; 4126 return false; 4127 } 4128 4129 if (FieldDecl *Field = Init->getAnyMember()) 4130 S.Diag(Init->getSourceLocation(), 4131 diag::err_multiple_mem_initialization) 4132 << Field->getDeclName() 4133 << Init->getSourceRange(); 4134 else { 4135 const Type *BaseClass = Init->getBaseClass(); 4136 assert(BaseClass && "neither field nor base"); 4137 S.Diag(Init->getSourceLocation(), 4138 diag::err_multiple_base_initialization) 4139 << QualType(BaseClass, 0) 4140 << Init->getSourceRange(); 4141 } 4142 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4143 << 0 << PrevInit->getSourceRange(); 4144 4145 return true; 4146 } 4147 4148 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4149 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4150 4151 bool CheckRedundantUnionInit(Sema &S, 4152 CXXCtorInitializer *Init, 4153 RedundantUnionMap &Unions) { 4154 FieldDecl *Field = Init->getAnyMember(); 4155 RecordDecl *Parent = Field->getParent(); 4156 NamedDecl *Child = Field; 4157 4158 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4159 if (Parent->isUnion()) { 4160 UnionEntry &En = Unions[Parent]; 4161 if (En.first && En.first != Child) { 4162 S.Diag(Init->getSourceLocation(), 4163 diag::err_multiple_mem_union_initialization) 4164 << Field->getDeclName() 4165 << Init->getSourceRange(); 4166 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4167 << 0 << En.second->getSourceRange(); 4168 return true; 4169 } 4170 if (!En.first) { 4171 En.first = Child; 4172 En.second = Init; 4173 } 4174 if (!Parent->isAnonymousStructOrUnion()) 4175 return false; 4176 } 4177 4178 Child = Parent; 4179 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4180 } 4181 4182 return false; 4183 } 4184 } 4185 4186 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4187 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4188 SourceLocation ColonLoc, 4189 ArrayRef<CXXCtorInitializer*> MemInits, 4190 bool AnyErrors) { 4191 if (!ConstructorDecl) 4192 return; 4193 4194 AdjustDeclIfTemplate(ConstructorDecl); 4195 4196 CXXConstructorDecl *Constructor 4197 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4198 4199 if (!Constructor) { 4200 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4201 return; 4202 } 4203 4204 // Mapping for the duplicate initializers check. 4205 // For member initializers, this is keyed with a FieldDecl*. 4206 // For base initializers, this is keyed with a Type*. 4207 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4208 4209 // Mapping for the inconsistent anonymous-union initializers check. 4210 RedundantUnionMap MemberUnions; 4211 4212 bool HadError = false; 4213 for (unsigned i = 0; i < MemInits.size(); i++) { 4214 CXXCtorInitializer *Init = MemInits[i]; 4215 4216 // Set the source order index. 4217 Init->setSourceOrder(i); 4218 4219 if (Init->isAnyMemberInitializer()) { 4220 const void *Key = GetKeyForMember(Context, Init); 4221 if (CheckRedundantInit(*this, Init, Members[Key]) || 4222 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4223 HadError = true; 4224 } else if (Init->isBaseInitializer()) { 4225 const void *Key = GetKeyForMember(Context, Init); 4226 if (CheckRedundantInit(*this, Init, Members[Key])) 4227 HadError = true; 4228 } else { 4229 assert(Init->isDelegatingInitializer()); 4230 // This must be the only initializer 4231 if (MemInits.size() != 1) { 4232 Diag(Init->getSourceLocation(), 4233 diag::err_delegating_initializer_alone) 4234 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4235 // We will treat this as being the only initializer. 4236 } 4237 SetDelegatingInitializer(Constructor, MemInits[i]); 4238 // Return immediately as the initializer is set. 4239 return; 4240 } 4241 } 4242 4243 if (HadError) 4244 return; 4245 4246 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4247 4248 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4249 4250 DiagnoseUninitializedFields(*this, Constructor); 4251 } 4252 4253 void 4254 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4255 CXXRecordDecl *ClassDecl) { 4256 // Ignore dependent contexts. Also ignore unions, since their members never 4257 // have destructors implicitly called. 4258 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4259 return; 4260 4261 // FIXME: all the access-control diagnostics are positioned on the 4262 // field/base declaration. That's probably good; that said, the 4263 // user might reasonably want to know why the destructor is being 4264 // emitted, and we currently don't say. 4265 4266 // Non-static data members. 4267 for (auto *Field : ClassDecl->fields()) { 4268 if (Field->isInvalidDecl()) 4269 continue; 4270 4271 // Don't destroy incomplete or zero-length arrays. 4272 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4273 continue; 4274 4275 QualType FieldType = Context.getBaseElementType(Field->getType()); 4276 4277 const RecordType* RT = FieldType->getAs<RecordType>(); 4278 if (!RT) 4279 continue; 4280 4281 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4282 if (FieldClassDecl->isInvalidDecl()) 4283 continue; 4284 if (FieldClassDecl->hasIrrelevantDestructor()) 4285 continue; 4286 // The destructor for an implicit anonymous union member is never invoked. 4287 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4288 continue; 4289 4290 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4291 assert(Dtor && "No dtor found for FieldClassDecl!"); 4292 CheckDestructorAccess(Field->getLocation(), Dtor, 4293 PDiag(diag::err_access_dtor_field) 4294 << Field->getDeclName() 4295 << FieldType); 4296 4297 MarkFunctionReferenced(Location, Dtor); 4298 DiagnoseUseOfDecl(Dtor, Location); 4299 } 4300 4301 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4302 4303 // Bases. 4304 for (const auto &Base : ClassDecl->bases()) { 4305 // Bases are always records in a well-formed non-dependent class. 4306 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4307 4308 // Remember direct virtual bases. 4309 if (Base.isVirtual()) 4310 DirectVirtualBases.insert(RT); 4311 4312 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4313 // If our base class is invalid, we probably can't get its dtor anyway. 4314 if (BaseClassDecl->isInvalidDecl()) 4315 continue; 4316 if (BaseClassDecl->hasIrrelevantDestructor()) 4317 continue; 4318 4319 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4320 assert(Dtor && "No dtor found for BaseClassDecl!"); 4321 4322 // FIXME: caret should be on the start of the class name 4323 CheckDestructorAccess(Base.getLocStart(), Dtor, 4324 PDiag(diag::err_access_dtor_base) 4325 << Base.getType() 4326 << Base.getSourceRange(), 4327 Context.getTypeDeclType(ClassDecl)); 4328 4329 MarkFunctionReferenced(Location, Dtor); 4330 DiagnoseUseOfDecl(Dtor, Location); 4331 } 4332 4333 // Virtual bases. 4334 for (const auto &VBase : ClassDecl->vbases()) { 4335 // Bases are always records in a well-formed non-dependent class. 4336 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4337 4338 // Ignore direct virtual bases. 4339 if (DirectVirtualBases.count(RT)) 4340 continue; 4341 4342 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4343 // If our base class is invalid, we probably can't get its dtor anyway. 4344 if (BaseClassDecl->isInvalidDecl()) 4345 continue; 4346 if (BaseClassDecl->hasIrrelevantDestructor()) 4347 continue; 4348 4349 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4350 assert(Dtor && "No dtor found for BaseClassDecl!"); 4351 if (CheckDestructorAccess( 4352 ClassDecl->getLocation(), Dtor, 4353 PDiag(diag::err_access_dtor_vbase) 4354 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4355 Context.getTypeDeclType(ClassDecl)) == 4356 AR_accessible) { 4357 CheckDerivedToBaseConversion( 4358 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4359 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4360 SourceRange(), DeclarationName(), nullptr); 4361 } 4362 4363 MarkFunctionReferenced(Location, Dtor); 4364 DiagnoseUseOfDecl(Dtor, Location); 4365 } 4366 } 4367 4368 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4369 if (!CDtorDecl) 4370 return; 4371 4372 if (CXXConstructorDecl *Constructor 4373 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4374 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4375 DiagnoseUninitializedFields(*this, Constructor); 4376 } 4377 } 4378 4379 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4380 unsigned DiagID, AbstractDiagSelID SelID) { 4381 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4382 unsigned DiagID; 4383 AbstractDiagSelID SelID; 4384 4385 public: 4386 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4387 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4388 4389 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4390 if (Suppressed) return; 4391 if (SelID == -1) 4392 S.Diag(Loc, DiagID) << T; 4393 else 4394 S.Diag(Loc, DiagID) << SelID << T; 4395 } 4396 } Diagnoser(DiagID, SelID); 4397 4398 return RequireNonAbstractType(Loc, T, Diagnoser); 4399 } 4400 4401 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4402 TypeDiagnoser &Diagnoser) { 4403 if (!getLangOpts().CPlusPlus) 4404 return false; 4405 4406 if (const ArrayType *AT = Context.getAsArrayType(T)) 4407 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4408 4409 if (const PointerType *PT = T->getAs<PointerType>()) { 4410 // Find the innermost pointer type. 4411 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4412 PT = T; 4413 4414 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4415 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4416 } 4417 4418 const RecordType *RT = T->getAs<RecordType>(); 4419 if (!RT) 4420 return false; 4421 4422 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4423 4424 // We can't answer whether something is abstract until it has a 4425 // definition. If it's currently being defined, we'll walk back 4426 // over all the declarations when we have a full definition. 4427 const CXXRecordDecl *Def = RD->getDefinition(); 4428 if (!Def || Def->isBeingDefined()) 4429 return false; 4430 4431 if (!RD->isAbstract()) 4432 return false; 4433 4434 Diagnoser.diagnose(*this, Loc, T); 4435 DiagnoseAbstractType(RD); 4436 4437 return true; 4438 } 4439 4440 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4441 // Check if we've already emitted the list of pure virtual functions 4442 // for this class. 4443 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4444 return; 4445 4446 // If the diagnostic is suppressed, don't emit the notes. We're only 4447 // going to emit them once, so try to attach them to a diagnostic we're 4448 // actually going to show. 4449 if (Diags.isLastDiagnosticIgnored()) 4450 return; 4451 4452 CXXFinalOverriderMap FinalOverriders; 4453 RD->getFinalOverriders(FinalOverriders); 4454 4455 // Keep a set of seen pure methods so we won't diagnose the same method 4456 // more than once. 4457 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4458 4459 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4460 MEnd = FinalOverriders.end(); 4461 M != MEnd; 4462 ++M) { 4463 for (OverridingMethods::iterator SO = M->second.begin(), 4464 SOEnd = M->second.end(); 4465 SO != SOEnd; ++SO) { 4466 // C++ [class.abstract]p4: 4467 // A class is abstract if it contains or inherits at least one 4468 // pure virtual function for which the final overrider is pure 4469 // virtual. 4470 4471 // 4472 if (SO->second.size() != 1) 4473 continue; 4474 4475 if (!SO->second.front().Method->isPure()) 4476 continue; 4477 4478 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4479 continue; 4480 4481 Diag(SO->second.front().Method->getLocation(), 4482 diag::note_pure_virtual_function) 4483 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4484 } 4485 } 4486 4487 if (!PureVirtualClassDiagSet) 4488 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4489 PureVirtualClassDiagSet->insert(RD); 4490 } 4491 4492 namespace { 4493 struct AbstractUsageInfo { 4494 Sema &S; 4495 CXXRecordDecl *Record; 4496 CanQualType AbstractType; 4497 bool Invalid; 4498 4499 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4500 : S(S), Record(Record), 4501 AbstractType(S.Context.getCanonicalType( 4502 S.Context.getTypeDeclType(Record))), 4503 Invalid(false) {} 4504 4505 void DiagnoseAbstractType() { 4506 if (Invalid) return; 4507 S.DiagnoseAbstractType(Record); 4508 Invalid = true; 4509 } 4510 4511 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4512 }; 4513 4514 struct CheckAbstractUsage { 4515 AbstractUsageInfo &Info; 4516 const NamedDecl *Ctx; 4517 4518 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4519 : Info(Info), Ctx(Ctx) {} 4520 4521 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4522 switch (TL.getTypeLocClass()) { 4523 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4524 #define TYPELOC(CLASS, PARENT) \ 4525 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4526 #include "clang/AST/TypeLocNodes.def" 4527 } 4528 } 4529 4530 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4531 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4532 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4533 if (!TL.getParam(I)) 4534 continue; 4535 4536 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4537 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4538 } 4539 } 4540 4541 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4542 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4543 } 4544 4545 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4546 // Visit the type parameters from a permissive context. 4547 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4548 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4549 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4550 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4551 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4552 // TODO: other template argument types? 4553 } 4554 } 4555 4556 // Visit pointee types from a permissive context. 4557 #define CheckPolymorphic(Type) \ 4558 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4559 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4560 } 4561 CheckPolymorphic(PointerTypeLoc) 4562 CheckPolymorphic(ReferenceTypeLoc) 4563 CheckPolymorphic(MemberPointerTypeLoc) 4564 CheckPolymorphic(BlockPointerTypeLoc) 4565 CheckPolymorphic(AtomicTypeLoc) 4566 4567 /// Handle all the types we haven't given a more specific 4568 /// implementation for above. 4569 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4570 // Every other kind of type that we haven't called out already 4571 // that has an inner type is either (1) sugar or (2) contains that 4572 // inner type in some way as a subobject. 4573 if (TypeLoc Next = TL.getNextTypeLoc()) 4574 return Visit(Next, Sel); 4575 4576 // If there's no inner type and we're in a permissive context, 4577 // don't diagnose. 4578 if (Sel == Sema::AbstractNone) return; 4579 4580 // Check whether the type matches the abstract type. 4581 QualType T = TL.getType(); 4582 if (T->isArrayType()) { 4583 Sel = Sema::AbstractArrayType; 4584 T = Info.S.Context.getBaseElementType(T); 4585 } 4586 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4587 if (CT != Info.AbstractType) return; 4588 4589 // It matched; do some magic. 4590 if (Sel == Sema::AbstractArrayType) { 4591 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4592 << T << TL.getSourceRange(); 4593 } else { 4594 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4595 << Sel << T << TL.getSourceRange(); 4596 } 4597 Info.DiagnoseAbstractType(); 4598 } 4599 }; 4600 4601 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4602 Sema::AbstractDiagSelID Sel) { 4603 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4604 } 4605 4606 } 4607 4608 /// Check for invalid uses of an abstract type in a method declaration. 4609 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4610 CXXMethodDecl *MD) { 4611 // No need to do the check on definitions, which require that 4612 // the return/param types be complete. 4613 if (MD->doesThisDeclarationHaveABody()) 4614 return; 4615 4616 // For safety's sake, just ignore it if we don't have type source 4617 // information. This should never happen for non-implicit methods, 4618 // but... 4619 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4620 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4621 } 4622 4623 /// Check for invalid uses of an abstract type within a class definition. 4624 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4625 CXXRecordDecl *RD) { 4626 for (auto *D : RD->decls()) { 4627 if (D->isImplicit()) continue; 4628 4629 // Methods and method templates. 4630 if (isa<CXXMethodDecl>(D)) { 4631 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4632 } else if (isa<FunctionTemplateDecl>(D)) { 4633 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4634 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4635 4636 // Fields and static variables. 4637 } else if (isa<FieldDecl>(D)) { 4638 FieldDecl *FD = cast<FieldDecl>(D); 4639 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4640 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4641 } else if (isa<VarDecl>(D)) { 4642 VarDecl *VD = cast<VarDecl>(D); 4643 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4644 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4645 4646 // Nested classes and class templates. 4647 } else if (isa<CXXRecordDecl>(D)) { 4648 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4649 } else if (isa<ClassTemplateDecl>(D)) { 4650 CheckAbstractClassUsage(Info, 4651 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4652 } 4653 } 4654 } 4655 4656 /// \brief Check class-level dllimport/dllexport attribute. 4657 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4658 Attr *ClassAttr = getDLLAttr(Class); 4659 4660 // MSVC inherits DLL attributes to partial class template specializations. 4661 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4662 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4663 if (Attr *TemplateAttr = 4664 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4665 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext())); 4666 A->setInherited(true); 4667 ClassAttr = A; 4668 } 4669 } 4670 } 4671 4672 if (!ClassAttr) 4673 return; 4674 4675 if (!Class->isExternallyVisible()) { 4676 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4677 << Class << ClassAttr; 4678 return; 4679 } 4680 4681 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4682 !ClassAttr->isInherited()) { 4683 // Diagnose dll attributes on members of class with dll attribute. 4684 for (Decl *Member : Class->decls()) { 4685 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4686 continue; 4687 InheritableAttr *MemberAttr = getDLLAttr(Member); 4688 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4689 continue; 4690 4691 S.Diag(MemberAttr->getLocation(), 4692 diag::err_attribute_dll_member_of_dll_class) 4693 << MemberAttr << ClassAttr; 4694 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4695 Member->setInvalidDecl(); 4696 } 4697 } 4698 4699 if (Class->getDescribedClassTemplate()) 4700 // Don't inherit dll attribute until the template is instantiated. 4701 return; 4702 4703 // The class is either imported or exported. 4704 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4705 const bool ClassImported = !ClassExported; 4706 4707 // Force declaration of implicit members so they can inherit the attribute. 4708 S.ForceDeclarationOfImplicitMembers(Class); 4709 4710 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4711 // seem to be true in practice? 4712 4713 TemplateSpecializationKind TSK = 4714 Class->getTemplateSpecializationKind(); 4715 4716 for (Decl *Member : Class->decls()) { 4717 VarDecl *VD = dyn_cast<VarDecl>(Member); 4718 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4719 4720 // Only methods and static fields inherit the attributes. 4721 if (!VD && !MD) 4722 continue; 4723 4724 if (MD) { 4725 // Don't process deleted methods. 4726 if (MD->isDeleted()) 4727 continue; 4728 4729 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) { 4730 // Current MSVC versions don't export the move assignment operators, so 4731 // don't attempt to import them if we have a definition. 4732 continue; 4733 } 4734 4735 if (MD->isInlined() && ClassImported && 4736 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4737 // MinGW does not import inline functions. 4738 continue; 4739 } 4740 } 4741 4742 if (!getDLLAttr(Member)) { 4743 auto *NewAttr = 4744 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4745 NewAttr->setInherited(true); 4746 Member->addAttr(NewAttr); 4747 } 4748 4749 if (MD && ClassExported) { 4750 if (MD->isUserProvided()) { 4751 // Instantiate non-default class member functions ... 4752 4753 // .. except for certain kinds of template specializations. 4754 if (TSK == TSK_ExplicitInstantiationDeclaration) 4755 continue; 4756 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4757 continue; 4758 4759 S.MarkFunctionReferenced(Class->getLocation(), MD); 4760 4761 // The function will be passed to the consumer when its definition is 4762 // encountered. 4763 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4764 MD->isCopyAssignmentOperator() || 4765 MD->isMoveAssignmentOperator()) { 4766 // Synthesize and instantiate non-trivial implicit methods, explicitly 4767 // defaulted methods, and the copy and move assignment operators. The 4768 // latter are exported even if they are trivial, because the address of 4769 // an operator can be taken and should compare equal accross libraries. 4770 S.MarkFunctionReferenced(Class->getLocation(), MD); 4771 4772 // There is no later point when we will see the definition of this 4773 // function, so pass it to the consumer now. 4774 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 4775 } 4776 } 4777 } 4778 } 4779 4780 /// \brief Perform semantic checks on a class definition that has been 4781 /// completing, introducing implicitly-declared members, checking for 4782 /// abstract types, etc. 4783 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4784 if (!Record) 4785 return; 4786 4787 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4788 AbstractUsageInfo Info(*this, Record); 4789 CheckAbstractClassUsage(Info, Record); 4790 } 4791 4792 // If this is not an aggregate type and has no user-declared constructor, 4793 // complain about any non-static data members of reference or const scalar 4794 // type, since they will never get initializers. 4795 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4796 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4797 !Record->isLambda()) { 4798 bool Complained = false; 4799 for (const auto *F : Record->fields()) { 4800 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4801 continue; 4802 4803 if (F->getType()->isReferenceType() || 4804 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4805 if (!Complained) { 4806 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4807 << Record->getTagKind() << Record; 4808 Complained = true; 4809 } 4810 4811 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4812 << F->getType()->isReferenceType() 4813 << F->getDeclName(); 4814 } 4815 } 4816 } 4817 4818 if (Record->isDynamicClass() && !Record->isDependentType()) 4819 DynamicClasses.push_back(Record); 4820 4821 if (Record->getIdentifier()) { 4822 // C++ [class.mem]p13: 4823 // If T is the name of a class, then each of the following shall have a 4824 // name different from T: 4825 // - every member of every anonymous union that is a member of class T. 4826 // 4827 // C++ [class.mem]p14: 4828 // In addition, if class T has a user-declared constructor (12.1), every 4829 // non-static data member of class T shall have a name different from T. 4830 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4831 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4832 ++I) { 4833 NamedDecl *D = *I; 4834 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4835 isa<IndirectFieldDecl>(D)) { 4836 Diag(D->getLocation(), diag::err_member_name_of_class) 4837 << D->getDeclName(); 4838 break; 4839 } 4840 } 4841 } 4842 4843 // Warn if the class has virtual methods but non-virtual public destructor. 4844 if (Record->isPolymorphic() && !Record->isDependentType()) { 4845 CXXDestructorDecl *dtor = Record->getDestructor(); 4846 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4847 !Record->hasAttr<FinalAttr>()) 4848 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4849 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4850 } 4851 4852 if (Record->isAbstract()) { 4853 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4854 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4855 << FA->isSpelledAsSealed(); 4856 DiagnoseAbstractType(Record); 4857 } 4858 } 4859 4860 bool HasMethodWithOverrideControl = false, 4861 HasOverridingMethodWithoutOverrideControl = false; 4862 if (!Record->isDependentType()) { 4863 for (auto *M : Record->methods()) { 4864 // See if a method overloads virtual methods in a base 4865 // class without overriding any. 4866 if (!M->isStatic()) 4867 DiagnoseHiddenVirtualMethods(M); 4868 if (M->hasAttr<OverrideAttr>()) 4869 HasMethodWithOverrideControl = true; 4870 else if (M->size_overridden_methods() > 0) 4871 HasOverridingMethodWithoutOverrideControl = true; 4872 // Check whether the explicitly-defaulted special members are valid. 4873 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4874 CheckExplicitlyDefaultedSpecialMember(M); 4875 4876 // For an explicitly defaulted or deleted special member, we defer 4877 // determining triviality until the class is complete. That time is now! 4878 if (!M->isImplicit() && !M->isUserProvided()) { 4879 CXXSpecialMember CSM = getSpecialMember(M); 4880 if (CSM != CXXInvalid) { 4881 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4882 4883 // Inform the class that we've finished declaring this member. 4884 Record->finishedDefaultedOrDeletedMember(M); 4885 } 4886 } 4887 } 4888 } 4889 4890 if (HasMethodWithOverrideControl && 4891 HasOverridingMethodWithoutOverrideControl) { 4892 // At least one method has the 'override' control declared. 4893 // Diagnose all other overridden methods which do not have 'override' specified on them. 4894 for (auto *M : Record->methods()) 4895 DiagnoseAbsenceOfOverrideControl(M); 4896 } 4897 4898 // ms_struct is a request to use the same ABI rules as MSVC. Check 4899 // whether this class uses any C++ features that are implemented 4900 // completely differently in MSVC, and if so, emit a diagnostic. 4901 // That diagnostic defaults to an error, but we allow projects to 4902 // map it down to a warning (or ignore it). It's a fairly common 4903 // practice among users of the ms_struct pragma to mass-annotate 4904 // headers, sweeping up a bunch of types that the project doesn't 4905 // really rely on MSVC-compatible layout for. We must therefore 4906 // support "ms_struct except for C++ stuff" as a secondary ABI. 4907 if (Record->isMsStruct(Context) && 4908 (Record->isPolymorphic() || Record->getNumBases())) { 4909 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4910 } 4911 4912 // Declare inheriting constructors. We do this eagerly here because: 4913 // - The standard requires an eager diagnostic for conflicting inheriting 4914 // constructors from different classes. 4915 // - The lazy declaration of the other implicit constructors is so as to not 4916 // waste space and performance on classes that are not meant to be 4917 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4918 // have inheriting constructors. 4919 DeclareInheritingConstructors(Record); 4920 4921 checkDLLAttribute(*this, Record); 4922 } 4923 4924 /// Look up the special member function that would be called by a special 4925 /// member function for a subobject of class type. 4926 /// 4927 /// \param Class The class type of the subobject. 4928 /// \param CSM The kind of special member function. 4929 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4930 /// \param ConstRHS True if this is a copy operation with a const object 4931 /// on its RHS, that is, if the argument to the outer special member 4932 /// function is 'const' and this is not a field marked 'mutable'. 4933 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4934 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4935 unsigned FieldQuals, bool ConstRHS) { 4936 unsigned LHSQuals = 0; 4937 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4938 LHSQuals = FieldQuals; 4939 4940 unsigned RHSQuals = FieldQuals; 4941 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4942 RHSQuals = 0; 4943 else if (ConstRHS) 4944 RHSQuals |= Qualifiers::Const; 4945 4946 return S.LookupSpecialMember(Class, CSM, 4947 RHSQuals & Qualifiers::Const, 4948 RHSQuals & Qualifiers::Volatile, 4949 false, 4950 LHSQuals & Qualifiers::Const, 4951 LHSQuals & Qualifiers::Volatile); 4952 } 4953 4954 /// Is the special member function which would be selected to perform the 4955 /// specified operation on the specified class type a constexpr constructor? 4956 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4957 Sema::CXXSpecialMember CSM, 4958 unsigned Quals, bool ConstRHS) { 4959 Sema::SpecialMemberOverloadResult *SMOR = 4960 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4961 if (!SMOR || !SMOR->getMethod()) 4962 // A constructor we wouldn't select can't be "involved in initializing" 4963 // anything. 4964 return true; 4965 return SMOR->getMethod()->isConstexpr(); 4966 } 4967 4968 /// Determine whether the specified special member function would be constexpr 4969 /// if it were implicitly defined. 4970 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4971 Sema::CXXSpecialMember CSM, 4972 bool ConstArg) { 4973 if (!S.getLangOpts().CPlusPlus11) 4974 return false; 4975 4976 // C++11 [dcl.constexpr]p4: 4977 // In the definition of a constexpr constructor [...] 4978 bool Ctor = true; 4979 switch (CSM) { 4980 case Sema::CXXDefaultConstructor: 4981 // Since default constructor lookup is essentially trivial (and cannot 4982 // involve, for instance, template instantiation), we compute whether a 4983 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4984 // 4985 // This is important for performance; we need to know whether the default 4986 // constructor is constexpr to determine whether the type is a literal type. 4987 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4988 4989 case Sema::CXXCopyConstructor: 4990 case Sema::CXXMoveConstructor: 4991 // For copy or move constructors, we need to perform overload resolution. 4992 break; 4993 4994 case Sema::CXXCopyAssignment: 4995 case Sema::CXXMoveAssignment: 4996 if (!S.getLangOpts().CPlusPlus14) 4997 return false; 4998 // In C++1y, we need to perform overload resolution. 4999 Ctor = false; 5000 break; 5001 5002 case Sema::CXXDestructor: 5003 case Sema::CXXInvalid: 5004 return false; 5005 } 5006 5007 // -- if the class is a non-empty union, or for each non-empty anonymous 5008 // union member of a non-union class, exactly one non-static data member 5009 // shall be initialized; [DR1359] 5010 // 5011 // If we squint, this is guaranteed, since exactly one non-static data member 5012 // will be initialized (if the constructor isn't deleted), we just don't know 5013 // which one. 5014 if (Ctor && ClassDecl->isUnion()) 5015 return true; 5016 5017 // -- the class shall not have any virtual base classes; 5018 if (Ctor && ClassDecl->getNumVBases()) 5019 return false; 5020 5021 // C++1y [class.copy]p26: 5022 // -- [the class] is a literal type, and 5023 if (!Ctor && !ClassDecl->isLiteral()) 5024 return false; 5025 5026 // -- every constructor involved in initializing [...] base class 5027 // sub-objects shall be a constexpr constructor; 5028 // -- the assignment operator selected to copy/move each direct base 5029 // class is a constexpr function, and 5030 for (const auto &B : ClassDecl->bases()) { 5031 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5032 if (!BaseType) continue; 5033 5034 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5035 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5036 return false; 5037 } 5038 5039 // -- every constructor involved in initializing non-static data members 5040 // [...] shall be a constexpr constructor; 5041 // -- every non-static data member and base class sub-object shall be 5042 // initialized 5043 // -- for each non-static data member of X that is of class type (or array 5044 // thereof), the assignment operator selected to copy/move that member is 5045 // a constexpr function 5046 for (const auto *F : ClassDecl->fields()) { 5047 if (F->isInvalidDecl()) 5048 continue; 5049 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5050 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5051 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5052 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5053 BaseType.getCVRQualifiers(), 5054 ConstArg && !F->isMutable())) 5055 return false; 5056 } 5057 } 5058 5059 // All OK, it's constexpr! 5060 return true; 5061 } 5062 5063 static Sema::ImplicitExceptionSpecification 5064 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5065 switch (S.getSpecialMember(MD)) { 5066 case Sema::CXXDefaultConstructor: 5067 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5068 case Sema::CXXCopyConstructor: 5069 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5070 case Sema::CXXCopyAssignment: 5071 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5072 case Sema::CXXMoveConstructor: 5073 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5074 case Sema::CXXMoveAssignment: 5075 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5076 case Sema::CXXDestructor: 5077 return S.ComputeDefaultedDtorExceptionSpec(MD); 5078 case Sema::CXXInvalid: 5079 break; 5080 } 5081 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5082 "only special members have implicit exception specs"); 5083 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5084 } 5085 5086 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5087 CXXMethodDecl *MD) { 5088 FunctionProtoType::ExtProtoInfo EPI; 5089 5090 // Build an exception specification pointing back at this member. 5091 EPI.ExceptionSpec.Type = EST_Unevaluated; 5092 EPI.ExceptionSpec.SourceDecl = MD; 5093 5094 // Set the calling convention to the default for C++ instance methods. 5095 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5096 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5097 /*IsCXXMethod=*/true)); 5098 return EPI; 5099 } 5100 5101 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5102 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5103 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5104 return; 5105 5106 // Evaluate the exception specification. 5107 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5108 5109 // Update the type of the special member to use it. 5110 UpdateExceptionSpec(MD, ESI); 5111 5112 // A user-provided destructor can be defined outside the class. When that 5113 // happens, be sure to update the exception specification on both 5114 // declarations. 5115 const FunctionProtoType *CanonicalFPT = 5116 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5117 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5118 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5119 } 5120 5121 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5122 CXXRecordDecl *RD = MD->getParent(); 5123 CXXSpecialMember CSM = getSpecialMember(MD); 5124 5125 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5126 "not an explicitly-defaulted special member"); 5127 5128 // Whether this was the first-declared instance of the constructor. 5129 // This affects whether we implicitly add an exception spec and constexpr. 5130 bool First = MD == MD->getCanonicalDecl(); 5131 5132 bool HadError = false; 5133 5134 // C++11 [dcl.fct.def.default]p1: 5135 // A function that is explicitly defaulted shall 5136 // -- be a special member function (checked elsewhere), 5137 // -- have the same type (except for ref-qualifiers, and except that a 5138 // copy operation can take a non-const reference) as an implicit 5139 // declaration, and 5140 // -- not have default arguments. 5141 unsigned ExpectedParams = 1; 5142 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5143 ExpectedParams = 0; 5144 if (MD->getNumParams() != ExpectedParams) { 5145 // This also checks for default arguments: a copy or move constructor with a 5146 // default argument is classified as a default constructor, and assignment 5147 // operations and destructors can't have default arguments. 5148 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5149 << CSM << MD->getSourceRange(); 5150 HadError = true; 5151 } else if (MD->isVariadic()) { 5152 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5153 << CSM << MD->getSourceRange(); 5154 HadError = true; 5155 } 5156 5157 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5158 5159 bool CanHaveConstParam = false; 5160 if (CSM == CXXCopyConstructor) 5161 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5162 else if (CSM == CXXCopyAssignment) 5163 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5164 5165 QualType ReturnType = Context.VoidTy; 5166 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5167 // Check for return type matching. 5168 ReturnType = Type->getReturnType(); 5169 QualType ExpectedReturnType = 5170 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5171 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5172 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5173 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5174 HadError = true; 5175 } 5176 5177 // A defaulted special member cannot have cv-qualifiers. 5178 if (Type->getTypeQuals()) { 5179 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5180 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5181 HadError = true; 5182 } 5183 } 5184 5185 // Check for parameter type matching. 5186 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5187 bool HasConstParam = false; 5188 if (ExpectedParams && ArgType->isReferenceType()) { 5189 // Argument must be reference to possibly-const T. 5190 QualType ReferentType = ArgType->getPointeeType(); 5191 HasConstParam = ReferentType.isConstQualified(); 5192 5193 if (ReferentType.isVolatileQualified()) { 5194 Diag(MD->getLocation(), 5195 diag::err_defaulted_special_member_volatile_param) << CSM; 5196 HadError = true; 5197 } 5198 5199 if (HasConstParam && !CanHaveConstParam) { 5200 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5201 Diag(MD->getLocation(), 5202 diag::err_defaulted_special_member_copy_const_param) 5203 << (CSM == CXXCopyAssignment); 5204 // FIXME: Explain why this special member can't be const. 5205 } else { 5206 Diag(MD->getLocation(), 5207 diag::err_defaulted_special_member_move_const_param) 5208 << (CSM == CXXMoveAssignment); 5209 } 5210 HadError = true; 5211 } 5212 } else if (ExpectedParams) { 5213 // A copy assignment operator can take its argument by value, but a 5214 // defaulted one cannot. 5215 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5216 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5217 HadError = true; 5218 } 5219 5220 // C++11 [dcl.fct.def.default]p2: 5221 // An explicitly-defaulted function may be declared constexpr only if it 5222 // would have been implicitly declared as constexpr, 5223 // Do not apply this rule to members of class templates, since core issue 1358 5224 // makes such functions always instantiate to constexpr functions. For 5225 // functions which cannot be constexpr (for non-constructors in C++11 and for 5226 // destructors in C++1y), this is checked elsewhere. 5227 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5228 HasConstParam); 5229 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5230 : isa<CXXConstructorDecl>(MD)) && 5231 MD->isConstexpr() && !Constexpr && 5232 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5233 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5234 // FIXME: Explain why the special member can't be constexpr. 5235 HadError = true; 5236 } 5237 5238 // and may have an explicit exception-specification only if it is compatible 5239 // with the exception-specification on the implicit declaration. 5240 if (Type->hasExceptionSpec()) { 5241 // Delay the check if this is the first declaration of the special member, 5242 // since we may not have parsed some necessary in-class initializers yet. 5243 if (First) { 5244 // If the exception specification needs to be instantiated, do so now, 5245 // before we clobber it with an EST_Unevaluated specification below. 5246 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5247 InstantiateExceptionSpec(MD->getLocStart(), MD); 5248 Type = MD->getType()->getAs<FunctionProtoType>(); 5249 } 5250 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5251 } else 5252 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5253 } 5254 5255 // If a function is explicitly defaulted on its first declaration, 5256 if (First) { 5257 // -- it is implicitly considered to be constexpr if the implicit 5258 // definition would be, 5259 MD->setConstexpr(Constexpr); 5260 5261 // -- it is implicitly considered to have the same exception-specification 5262 // as if it had been implicitly declared, 5263 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5264 EPI.ExceptionSpec.Type = EST_Unevaluated; 5265 EPI.ExceptionSpec.SourceDecl = MD; 5266 MD->setType(Context.getFunctionType(ReturnType, 5267 llvm::makeArrayRef(&ArgType, 5268 ExpectedParams), 5269 EPI)); 5270 } 5271 5272 if (ShouldDeleteSpecialMember(MD, CSM)) { 5273 if (First) { 5274 SetDeclDeleted(MD, MD->getLocation()); 5275 } else { 5276 // C++11 [dcl.fct.def.default]p4: 5277 // [For a] user-provided explicitly-defaulted function [...] if such a 5278 // function is implicitly defined as deleted, the program is ill-formed. 5279 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5280 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5281 HadError = true; 5282 } 5283 } 5284 5285 if (HadError) 5286 MD->setInvalidDecl(); 5287 } 5288 5289 /// Check whether the exception specification provided for an 5290 /// explicitly-defaulted special member matches the exception specification 5291 /// that would have been generated for an implicit special member, per 5292 /// C++11 [dcl.fct.def.default]p2. 5293 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5294 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5295 // If the exception specification was explicitly specified but hadn't been 5296 // parsed when the method was defaulted, grab it now. 5297 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5298 SpecifiedType = 5299 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5300 5301 // Compute the implicit exception specification. 5302 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5303 /*IsCXXMethod=*/true); 5304 FunctionProtoType::ExtProtoInfo EPI(CC); 5305 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5306 .getExceptionSpec(); 5307 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5308 Context.getFunctionType(Context.VoidTy, None, EPI)); 5309 5310 // Ensure that it matches. 5311 CheckEquivalentExceptionSpec( 5312 PDiag(diag::err_incorrect_defaulted_exception_spec) 5313 << getSpecialMember(MD), PDiag(), 5314 ImplicitType, SourceLocation(), 5315 SpecifiedType, MD->getLocation()); 5316 } 5317 5318 void Sema::CheckDelayedMemberExceptionSpecs() { 5319 decltype(DelayedExceptionSpecChecks) Checks; 5320 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 5321 5322 std::swap(Checks, DelayedExceptionSpecChecks); 5323 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5324 5325 // Perform any deferred checking of exception specifications for virtual 5326 // destructors. 5327 for (auto &Check : Checks) 5328 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 5329 5330 // Check that any explicitly-defaulted methods have exception specifications 5331 // compatible with their implicit exception specifications. 5332 for (auto &Spec : Specs) 5333 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 5334 } 5335 5336 namespace { 5337 struct SpecialMemberDeletionInfo { 5338 Sema &S; 5339 CXXMethodDecl *MD; 5340 Sema::CXXSpecialMember CSM; 5341 bool Diagnose; 5342 5343 // Properties of the special member, computed for convenience. 5344 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5345 SourceLocation Loc; 5346 5347 bool AllFieldsAreConst; 5348 5349 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5350 Sema::CXXSpecialMember CSM, bool Diagnose) 5351 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5352 IsConstructor(false), IsAssignment(false), IsMove(false), 5353 ConstArg(false), Loc(MD->getLocation()), 5354 AllFieldsAreConst(true) { 5355 switch (CSM) { 5356 case Sema::CXXDefaultConstructor: 5357 case Sema::CXXCopyConstructor: 5358 IsConstructor = true; 5359 break; 5360 case Sema::CXXMoveConstructor: 5361 IsConstructor = true; 5362 IsMove = true; 5363 break; 5364 case Sema::CXXCopyAssignment: 5365 IsAssignment = true; 5366 break; 5367 case Sema::CXXMoveAssignment: 5368 IsAssignment = true; 5369 IsMove = true; 5370 break; 5371 case Sema::CXXDestructor: 5372 break; 5373 case Sema::CXXInvalid: 5374 llvm_unreachable("invalid special member kind"); 5375 } 5376 5377 if (MD->getNumParams()) { 5378 if (const ReferenceType *RT = 5379 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5380 ConstArg = RT->getPointeeType().isConstQualified(); 5381 } 5382 } 5383 5384 bool inUnion() const { return MD->getParent()->isUnion(); } 5385 5386 /// Look up the corresponding special member in the given class. 5387 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5388 unsigned Quals, bool IsMutable) { 5389 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5390 ConstArg && !IsMutable); 5391 } 5392 5393 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5394 5395 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5396 bool shouldDeleteForField(FieldDecl *FD); 5397 bool shouldDeleteForAllConstMembers(); 5398 5399 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5400 unsigned Quals); 5401 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5402 Sema::SpecialMemberOverloadResult *SMOR, 5403 bool IsDtorCallInCtor); 5404 5405 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5406 }; 5407 } 5408 5409 /// Is the given special member inaccessible when used on the given 5410 /// sub-object. 5411 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5412 CXXMethodDecl *target) { 5413 /// If we're operating on a base class, the object type is the 5414 /// type of this special member. 5415 QualType objectTy; 5416 AccessSpecifier access = target->getAccess(); 5417 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5418 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5419 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5420 5421 // If we're operating on a field, the object type is the type of the field. 5422 } else { 5423 objectTy = S.Context.getTypeDeclType(target->getParent()); 5424 } 5425 5426 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5427 } 5428 5429 /// Check whether we should delete a special member due to the implicit 5430 /// definition containing a call to a special member of a subobject. 5431 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5432 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5433 bool IsDtorCallInCtor) { 5434 CXXMethodDecl *Decl = SMOR->getMethod(); 5435 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5436 5437 int DiagKind = -1; 5438 5439 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5440 DiagKind = !Decl ? 0 : 1; 5441 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5442 DiagKind = 2; 5443 else if (!isAccessible(Subobj, Decl)) 5444 DiagKind = 3; 5445 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5446 !Decl->isTrivial()) { 5447 // A member of a union must have a trivial corresponding special member. 5448 // As a weird special case, a destructor call from a union's constructor 5449 // must be accessible and non-deleted, but need not be trivial. Such a 5450 // destructor is never actually called, but is semantically checked as 5451 // if it were. 5452 DiagKind = 4; 5453 } 5454 5455 if (DiagKind == -1) 5456 return false; 5457 5458 if (Diagnose) { 5459 if (Field) { 5460 S.Diag(Field->getLocation(), 5461 diag::note_deleted_special_member_class_subobject) 5462 << CSM << MD->getParent() << /*IsField*/true 5463 << Field << DiagKind << IsDtorCallInCtor; 5464 } else { 5465 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5466 S.Diag(Base->getLocStart(), 5467 diag::note_deleted_special_member_class_subobject) 5468 << CSM << MD->getParent() << /*IsField*/false 5469 << Base->getType() << DiagKind << IsDtorCallInCtor; 5470 } 5471 5472 if (DiagKind == 1) 5473 S.NoteDeletedFunction(Decl); 5474 // FIXME: Explain inaccessibility if DiagKind == 3. 5475 } 5476 5477 return true; 5478 } 5479 5480 /// Check whether we should delete a special member function due to having a 5481 /// direct or virtual base class or non-static data member of class type M. 5482 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5483 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5484 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5485 bool IsMutable = Field && Field->isMutable(); 5486 5487 // C++11 [class.ctor]p5: 5488 // -- any direct or virtual base class, or non-static data member with no 5489 // brace-or-equal-initializer, has class type M (or array thereof) and 5490 // either M has no default constructor or overload resolution as applied 5491 // to M's default constructor results in an ambiguity or in a function 5492 // that is deleted or inaccessible 5493 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5494 // -- a direct or virtual base class B that cannot be copied/moved because 5495 // overload resolution, as applied to B's corresponding special member, 5496 // results in an ambiguity or a function that is deleted or inaccessible 5497 // from the defaulted special member 5498 // C++11 [class.dtor]p5: 5499 // -- any direct or virtual base class [...] has a type with a destructor 5500 // that is deleted or inaccessible 5501 if (!(CSM == Sema::CXXDefaultConstructor && 5502 Field && Field->hasInClassInitializer()) && 5503 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5504 false)) 5505 return true; 5506 5507 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5508 // -- any direct or virtual base class or non-static data member has a 5509 // type with a destructor that is deleted or inaccessible 5510 if (IsConstructor) { 5511 Sema::SpecialMemberOverloadResult *SMOR = 5512 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5513 false, false, false, false, false); 5514 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5515 return true; 5516 } 5517 5518 return false; 5519 } 5520 5521 /// Check whether we should delete a special member function due to the class 5522 /// having a particular direct or virtual base class. 5523 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5524 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5525 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5526 } 5527 5528 /// Check whether we should delete a special member function due to the class 5529 /// having a particular non-static data member. 5530 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5531 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5532 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5533 5534 if (CSM == Sema::CXXDefaultConstructor) { 5535 // For a default constructor, all references must be initialized in-class 5536 // and, if a union, it must have a non-const member. 5537 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5538 if (Diagnose) 5539 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5540 << MD->getParent() << FD << FieldType << /*Reference*/0; 5541 return true; 5542 } 5543 // C++11 [class.ctor]p5: any non-variant non-static data member of 5544 // const-qualified type (or array thereof) with no 5545 // brace-or-equal-initializer does not have a user-provided default 5546 // constructor. 5547 if (!inUnion() && FieldType.isConstQualified() && 5548 !FD->hasInClassInitializer() && 5549 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5550 if (Diagnose) 5551 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5552 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5553 return true; 5554 } 5555 5556 if (inUnion() && !FieldType.isConstQualified()) 5557 AllFieldsAreConst = false; 5558 } else if (CSM == Sema::CXXCopyConstructor) { 5559 // For a copy constructor, data members must not be of rvalue reference 5560 // type. 5561 if (FieldType->isRValueReferenceType()) { 5562 if (Diagnose) 5563 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5564 << MD->getParent() << FD << FieldType; 5565 return true; 5566 } 5567 } else if (IsAssignment) { 5568 // For an assignment operator, data members must not be of reference type. 5569 if (FieldType->isReferenceType()) { 5570 if (Diagnose) 5571 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5572 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5573 return true; 5574 } 5575 if (!FieldRecord && FieldType.isConstQualified()) { 5576 // C++11 [class.copy]p23: 5577 // -- a non-static data member of const non-class type (or array thereof) 5578 if (Diagnose) 5579 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5580 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5581 return true; 5582 } 5583 } 5584 5585 if (FieldRecord) { 5586 // Some additional restrictions exist on the variant members. 5587 if (!inUnion() && FieldRecord->isUnion() && 5588 FieldRecord->isAnonymousStructOrUnion()) { 5589 bool AllVariantFieldsAreConst = true; 5590 5591 // FIXME: Handle anonymous unions declared within anonymous unions. 5592 for (auto *UI : FieldRecord->fields()) { 5593 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5594 5595 if (!UnionFieldType.isConstQualified()) 5596 AllVariantFieldsAreConst = false; 5597 5598 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5599 if (UnionFieldRecord && 5600 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5601 UnionFieldType.getCVRQualifiers())) 5602 return true; 5603 } 5604 5605 // At least one member in each anonymous union must be non-const 5606 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5607 !FieldRecord->field_empty()) { 5608 if (Diagnose) 5609 S.Diag(FieldRecord->getLocation(), 5610 diag::note_deleted_default_ctor_all_const) 5611 << MD->getParent() << /*anonymous union*/1; 5612 return true; 5613 } 5614 5615 // Don't check the implicit member of the anonymous union type. 5616 // This is technically non-conformant, but sanity demands it. 5617 return false; 5618 } 5619 5620 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5621 FieldType.getCVRQualifiers())) 5622 return true; 5623 } 5624 5625 return false; 5626 } 5627 5628 /// C++11 [class.ctor] p5: 5629 /// A defaulted default constructor for a class X is defined as deleted if 5630 /// X is a union and all of its variant members are of const-qualified type. 5631 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5632 // This is a silly definition, because it gives an empty union a deleted 5633 // default constructor. Don't do that. 5634 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5635 !MD->getParent()->field_empty()) { 5636 if (Diagnose) 5637 S.Diag(MD->getParent()->getLocation(), 5638 diag::note_deleted_default_ctor_all_const) 5639 << MD->getParent() << /*not anonymous union*/0; 5640 return true; 5641 } 5642 return false; 5643 } 5644 5645 /// Determine whether a defaulted special member function should be defined as 5646 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5647 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5648 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5649 bool Diagnose) { 5650 if (MD->isInvalidDecl()) 5651 return false; 5652 CXXRecordDecl *RD = MD->getParent(); 5653 assert(!RD->isDependentType() && "do deletion after instantiation"); 5654 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5655 return false; 5656 5657 // C++11 [expr.lambda.prim]p19: 5658 // The closure type associated with a lambda-expression has a 5659 // deleted (8.4.3) default constructor and a deleted copy 5660 // assignment operator. 5661 if (RD->isLambda() && 5662 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5663 if (Diagnose) 5664 Diag(RD->getLocation(), diag::note_lambda_decl); 5665 return true; 5666 } 5667 5668 // For an anonymous struct or union, the copy and assignment special members 5669 // will never be used, so skip the check. For an anonymous union declared at 5670 // namespace scope, the constructor and destructor are used. 5671 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5672 RD->isAnonymousStructOrUnion()) 5673 return false; 5674 5675 // C++11 [class.copy]p7, p18: 5676 // If the class definition declares a move constructor or move assignment 5677 // operator, an implicitly declared copy constructor or copy assignment 5678 // operator is defined as deleted. 5679 if (MD->isImplicit() && 5680 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5681 CXXMethodDecl *UserDeclaredMove = nullptr; 5682 5683 // In Microsoft mode, a user-declared move only causes the deletion of the 5684 // corresponding copy operation, not both copy operations. 5685 if (RD->hasUserDeclaredMoveConstructor() && 5686 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5687 if (!Diagnose) return true; 5688 5689 // Find any user-declared move constructor. 5690 for (auto *I : RD->ctors()) { 5691 if (I->isMoveConstructor()) { 5692 UserDeclaredMove = I; 5693 break; 5694 } 5695 } 5696 assert(UserDeclaredMove); 5697 } else if (RD->hasUserDeclaredMoveAssignment() && 5698 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5699 if (!Diagnose) return true; 5700 5701 // Find any user-declared move assignment operator. 5702 for (auto *I : RD->methods()) { 5703 if (I->isMoveAssignmentOperator()) { 5704 UserDeclaredMove = I; 5705 break; 5706 } 5707 } 5708 assert(UserDeclaredMove); 5709 } 5710 5711 if (UserDeclaredMove) { 5712 Diag(UserDeclaredMove->getLocation(), 5713 diag::note_deleted_copy_user_declared_move) 5714 << (CSM == CXXCopyAssignment) << RD 5715 << UserDeclaredMove->isMoveAssignmentOperator(); 5716 return true; 5717 } 5718 } 5719 5720 // Do access control from the special member function 5721 ContextRAII MethodContext(*this, MD); 5722 5723 // C++11 [class.dtor]p5: 5724 // -- for a virtual destructor, lookup of the non-array deallocation function 5725 // results in an ambiguity or in a function that is deleted or inaccessible 5726 if (CSM == CXXDestructor && MD->isVirtual()) { 5727 FunctionDecl *OperatorDelete = nullptr; 5728 DeclarationName Name = 5729 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5730 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5731 OperatorDelete, false)) { 5732 if (Diagnose) 5733 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5734 return true; 5735 } 5736 } 5737 5738 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5739 5740 for (auto &BI : RD->bases()) 5741 if (!BI.isVirtual() && 5742 SMI.shouldDeleteForBase(&BI)) 5743 return true; 5744 5745 // Per DR1611, do not consider virtual bases of constructors of abstract 5746 // classes, since we are not going to construct them. 5747 if (!RD->isAbstract() || !SMI.IsConstructor) { 5748 for (auto &BI : RD->vbases()) 5749 if (SMI.shouldDeleteForBase(&BI)) 5750 return true; 5751 } 5752 5753 for (auto *FI : RD->fields()) 5754 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5755 SMI.shouldDeleteForField(FI)) 5756 return true; 5757 5758 if (SMI.shouldDeleteForAllConstMembers()) 5759 return true; 5760 5761 if (getLangOpts().CUDA) { 5762 // We should delete the special member in CUDA mode if target inference 5763 // failed. 5764 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5765 Diagnose); 5766 } 5767 5768 return false; 5769 } 5770 5771 /// Perform lookup for a special member of the specified kind, and determine 5772 /// whether it is trivial. If the triviality can be determined without the 5773 /// lookup, skip it. This is intended for use when determining whether a 5774 /// special member of a containing object is trivial, and thus does not ever 5775 /// perform overload resolution for default constructors. 5776 /// 5777 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5778 /// member that was most likely to be intended to be trivial, if any. 5779 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5780 Sema::CXXSpecialMember CSM, unsigned Quals, 5781 bool ConstRHS, CXXMethodDecl **Selected) { 5782 if (Selected) 5783 *Selected = nullptr; 5784 5785 switch (CSM) { 5786 case Sema::CXXInvalid: 5787 llvm_unreachable("not a special member"); 5788 5789 case Sema::CXXDefaultConstructor: 5790 // C++11 [class.ctor]p5: 5791 // A default constructor is trivial if: 5792 // - all the [direct subobjects] have trivial default constructors 5793 // 5794 // Note, no overload resolution is performed in this case. 5795 if (RD->hasTrivialDefaultConstructor()) 5796 return true; 5797 5798 if (Selected) { 5799 // If there's a default constructor which could have been trivial, dig it 5800 // out. Otherwise, if there's any user-provided default constructor, point 5801 // to that as an example of why there's not a trivial one. 5802 CXXConstructorDecl *DefCtor = nullptr; 5803 if (RD->needsImplicitDefaultConstructor()) 5804 S.DeclareImplicitDefaultConstructor(RD); 5805 for (auto *CI : RD->ctors()) { 5806 if (!CI->isDefaultConstructor()) 5807 continue; 5808 DefCtor = CI; 5809 if (!DefCtor->isUserProvided()) 5810 break; 5811 } 5812 5813 *Selected = DefCtor; 5814 } 5815 5816 return false; 5817 5818 case Sema::CXXDestructor: 5819 // C++11 [class.dtor]p5: 5820 // A destructor is trivial if: 5821 // - all the direct [subobjects] have trivial destructors 5822 if (RD->hasTrivialDestructor()) 5823 return true; 5824 5825 if (Selected) { 5826 if (RD->needsImplicitDestructor()) 5827 S.DeclareImplicitDestructor(RD); 5828 *Selected = RD->getDestructor(); 5829 } 5830 5831 return false; 5832 5833 case Sema::CXXCopyConstructor: 5834 // C++11 [class.copy]p12: 5835 // A copy constructor is trivial if: 5836 // - the constructor selected to copy each direct [subobject] is trivial 5837 if (RD->hasTrivialCopyConstructor()) { 5838 if (Quals == Qualifiers::Const) 5839 // We must either select the trivial copy constructor or reach an 5840 // ambiguity; no need to actually perform overload resolution. 5841 return true; 5842 } else if (!Selected) { 5843 return false; 5844 } 5845 // In C++98, we are not supposed to perform overload resolution here, but we 5846 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5847 // cases like B as having a non-trivial copy constructor: 5848 // struct A { template<typename T> A(T&); }; 5849 // struct B { mutable A a; }; 5850 goto NeedOverloadResolution; 5851 5852 case Sema::CXXCopyAssignment: 5853 // C++11 [class.copy]p25: 5854 // A copy assignment operator is trivial if: 5855 // - the assignment operator selected to copy each direct [subobject] is 5856 // trivial 5857 if (RD->hasTrivialCopyAssignment()) { 5858 if (Quals == Qualifiers::Const) 5859 return true; 5860 } else if (!Selected) { 5861 return false; 5862 } 5863 // In C++98, we are not supposed to perform overload resolution here, but we 5864 // treat that as a language defect. 5865 goto NeedOverloadResolution; 5866 5867 case Sema::CXXMoveConstructor: 5868 case Sema::CXXMoveAssignment: 5869 NeedOverloadResolution: 5870 Sema::SpecialMemberOverloadResult *SMOR = 5871 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5872 5873 // The standard doesn't describe how to behave if the lookup is ambiguous. 5874 // We treat it as not making the member non-trivial, just like the standard 5875 // mandates for the default constructor. This should rarely matter, because 5876 // the member will also be deleted. 5877 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5878 return true; 5879 5880 if (!SMOR->getMethod()) { 5881 assert(SMOR->getKind() == 5882 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5883 return false; 5884 } 5885 5886 // We deliberately don't check if we found a deleted special member. We're 5887 // not supposed to! 5888 if (Selected) 5889 *Selected = SMOR->getMethod(); 5890 return SMOR->getMethod()->isTrivial(); 5891 } 5892 5893 llvm_unreachable("unknown special method kind"); 5894 } 5895 5896 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5897 for (auto *CI : RD->ctors()) 5898 if (!CI->isImplicit()) 5899 return CI; 5900 5901 // Look for constructor templates. 5902 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5903 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5904 if (CXXConstructorDecl *CD = 5905 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5906 return CD; 5907 } 5908 5909 return nullptr; 5910 } 5911 5912 /// The kind of subobject we are checking for triviality. The values of this 5913 /// enumeration are used in diagnostics. 5914 enum TrivialSubobjectKind { 5915 /// The subobject is a base class. 5916 TSK_BaseClass, 5917 /// The subobject is a non-static data member. 5918 TSK_Field, 5919 /// The object is actually the complete object. 5920 TSK_CompleteObject 5921 }; 5922 5923 /// Check whether the special member selected for a given type would be trivial. 5924 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5925 QualType SubType, bool ConstRHS, 5926 Sema::CXXSpecialMember CSM, 5927 TrivialSubobjectKind Kind, 5928 bool Diagnose) { 5929 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5930 if (!SubRD) 5931 return true; 5932 5933 CXXMethodDecl *Selected; 5934 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5935 ConstRHS, Diagnose ? &Selected : nullptr)) 5936 return true; 5937 5938 if (Diagnose) { 5939 if (ConstRHS) 5940 SubType.addConst(); 5941 5942 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5943 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5944 << Kind << SubType.getUnqualifiedType(); 5945 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5946 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5947 } else if (!Selected) 5948 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5949 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5950 else if (Selected->isUserProvided()) { 5951 if (Kind == TSK_CompleteObject) 5952 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5953 << Kind << SubType.getUnqualifiedType() << CSM; 5954 else { 5955 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5956 << Kind << SubType.getUnqualifiedType() << CSM; 5957 S.Diag(Selected->getLocation(), diag::note_declared_at); 5958 } 5959 } else { 5960 if (Kind != TSK_CompleteObject) 5961 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5962 << Kind << SubType.getUnqualifiedType() << CSM; 5963 5964 // Explain why the defaulted or deleted special member isn't trivial. 5965 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5966 } 5967 } 5968 5969 return false; 5970 } 5971 5972 /// Check whether the members of a class type allow a special member to be 5973 /// trivial. 5974 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5975 Sema::CXXSpecialMember CSM, 5976 bool ConstArg, bool Diagnose) { 5977 for (const auto *FI : RD->fields()) { 5978 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5979 continue; 5980 5981 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5982 5983 // Pretend anonymous struct or union members are members of this class. 5984 if (FI->isAnonymousStructOrUnion()) { 5985 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5986 CSM, ConstArg, Diagnose)) 5987 return false; 5988 continue; 5989 } 5990 5991 // C++11 [class.ctor]p5: 5992 // A default constructor is trivial if [...] 5993 // -- no non-static data member of its class has a 5994 // brace-or-equal-initializer 5995 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5996 if (Diagnose) 5997 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5998 return false; 5999 } 6000 6001 // Objective C ARC 4.3.5: 6002 // [...] nontrivally ownership-qualified types are [...] not trivially 6003 // default constructible, copy constructible, move constructible, copy 6004 // assignable, move assignable, or destructible [...] 6005 if (S.getLangOpts().ObjCAutoRefCount && 6006 FieldType.hasNonTrivialObjCLifetime()) { 6007 if (Diagnose) 6008 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6009 << RD << FieldType.getObjCLifetime(); 6010 return false; 6011 } 6012 6013 bool ConstRHS = ConstArg && !FI->isMutable(); 6014 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6015 CSM, TSK_Field, Diagnose)) 6016 return false; 6017 } 6018 6019 return true; 6020 } 6021 6022 /// Diagnose why the specified class does not have a trivial special member of 6023 /// the given kind. 6024 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6025 QualType Ty = Context.getRecordType(RD); 6026 6027 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6028 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6029 TSK_CompleteObject, /*Diagnose*/true); 6030 } 6031 6032 /// Determine whether a defaulted or deleted special member function is trivial, 6033 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6034 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6035 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6036 bool Diagnose) { 6037 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6038 6039 CXXRecordDecl *RD = MD->getParent(); 6040 6041 bool ConstArg = false; 6042 6043 // C++11 [class.copy]p12, p25: [DR1593] 6044 // A [special member] is trivial if [...] its parameter-type-list is 6045 // equivalent to the parameter-type-list of an implicit declaration [...] 6046 switch (CSM) { 6047 case CXXDefaultConstructor: 6048 case CXXDestructor: 6049 // Trivial default constructors and destructors cannot have parameters. 6050 break; 6051 6052 case CXXCopyConstructor: 6053 case CXXCopyAssignment: { 6054 // Trivial copy operations always have const, non-volatile parameter types. 6055 ConstArg = true; 6056 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6057 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6058 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6059 if (Diagnose) 6060 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6061 << Param0->getSourceRange() << Param0->getType() 6062 << Context.getLValueReferenceType( 6063 Context.getRecordType(RD).withConst()); 6064 return false; 6065 } 6066 break; 6067 } 6068 6069 case CXXMoveConstructor: 6070 case CXXMoveAssignment: { 6071 // Trivial move operations always have non-cv-qualified parameters. 6072 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6073 const RValueReferenceType *RT = 6074 Param0->getType()->getAs<RValueReferenceType>(); 6075 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6076 if (Diagnose) 6077 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6078 << Param0->getSourceRange() << Param0->getType() 6079 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6080 return false; 6081 } 6082 break; 6083 } 6084 6085 case CXXInvalid: 6086 llvm_unreachable("not a special member"); 6087 } 6088 6089 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6090 if (Diagnose) 6091 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6092 diag::note_nontrivial_default_arg) 6093 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6094 return false; 6095 } 6096 if (MD->isVariadic()) { 6097 if (Diagnose) 6098 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6099 return false; 6100 } 6101 6102 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6103 // A copy/move [constructor or assignment operator] is trivial if 6104 // -- the [member] selected to copy/move each direct base class subobject 6105 // is trivial 6106 // 6107 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6108 // A [default constructor or destructor] is trivial if 6109 // -- all the direct base classes have trivial [default constructors or 6110 // destructors] 6111 for (const auto &BI : RD->bases()) 6112 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6113 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6114 return false; 6115 6116 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6117 // A copy/move [constructor or assignment operator] for a class X is 6118 // trivial if 6119 // -- for each non-static data member of X that is of class type (or array 6120 // thereof), the constructor selected to copy/move that member is 6121 // trivial 6122 // 6123 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6124 // A [default constructor or destructor] is trivial if 6125 // -- for all of the non-static data members of its class that are of class 6126 // type (or array thereof), each such class has a trivial [default 6127 // constructor or destructor] 6128 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6129 return false; 6130 6131 // C++11 [class.dtor]p5: 6132 // A destructor is trivial if [...] 6133 // -- the destructor is not virtual 6134 if (CSM == CXXDestructor && MD->isVirtual()) { 6135 if (Diagnose) 6136 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6137 return false; 6138 } 6139 6140 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6141 // A [special member] for class X is trivial if [...] 6142 // -- class X has no virtual functions and no virtual base classes 6143 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6144 if (!Diagnose) 6145 return false; 6146 6147 if (RD->getNumVBases()) { 6148 // Check for virtual bases. We already know that the corresponding 6149 // member in all bases is trivial, so vbases must all be direct. 6150 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6151 assert(BS.isVirtual()); 6152 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6153 return false; 6154 } 6155 6156 // Must have a virtual method. 6157 for (const auto *MI : RD->methods()) { 6158 if (MI->isVirtual()) { 6159 SourceLocation MLoc = MI->getLocStart(); 6160 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6161 return false; 6162 } 6163 } 6164 6165 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6166 } 6167 6168 // Looks like it's trivial! 6169 return true; 6170 } 6171 6172 /// \brief Data used with FindHiddenVirtualMethod 6173 namespace { 6174 struct FindHiddenVirtualMethodData { 6175 Sema *S; 6176 CXXMethodDecl *Method; 6177 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6178 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6179 }; 6180 } 6181 6182 /// \brief Check whether any most overriden method from MD in Methods 6183 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 6184 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6185 if (MD->size_overridden_methods() == 0) 6186 return Methods.count(MD->getCanonicalDecl()); 6187 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6188 E = MD->end_overridden_methods(); 6189 I != E; ++I) 6190 if (CheckMostOverridenMethods(*I, Methods)) 6191 return true; 6192 return false; 6193 } 6194 6195 /// \brief Member lookup function that determines whether a given C++ 6196 /// method overloads virtual methods in a base class without overriding any, 6197 /// to be used with CXXRecordDecl::lookupInBases(). 6198 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 6199 CXXBasePath &Path, 6200 void *UserData) { 6201 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6202 6203 FindHiddenVirtualMethodData &Data 6204 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 6205 6206 DeclarationName Name = Data.Method->getDeclName(); 6207 assert(Name.getNameKind() == DeclarationName::Identifier); 6208 6209 bool foundSameNameMethod = false; 6210 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6211 for (Path.Decls = BaseRecord->lookup(Name); 6212 !Path.Decls.empty(); 6213 Path.Decls = Path.Decls.slice(1)) { 6214 NamedDecl *D = Path.Decls.front(); 6215 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6216 MD = MD->getCanonicalDecl(); 6217 foundSameNameMethod = true; 6218 // Interested only in hidden virtual methods. 6219 if (!MD->isVirtual()) 6220 continue; 6221 // If the method we are checking overrides a method from its base 6222 // don't warn about the other overloaded methods. Clang deviates from GCC 6223 // by only diagnosing overloads of inherited virtual functions that do not 6224 // override any other virtual functions in the base. GCC's 6225 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6226 // function from a base class. These cases may be better served by a 6227 // warning (not specific to virtual functions) on call sites when the call 6228 // would select a different function from the base class, were it visible. 6229 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6230 if (!Data.S->IsOverload(Data.Method, MD, false)) 6231 return true; 6232 // Collect the overload only if its hidden. 6233 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 6234 overloadedMethods.push_back(MD); 6235 } 6236 } 6237 6238 if (foundSameNameMethod) 6239 Data.OverloadedMethods.append(overloadedMethods.begin(), 6240 overloadedMethods.end()); 6241 return foundSameNameMethod; 6242 } 6243 6244 /// \brief Add the most overriden methods from MD to Methods 6245 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6246 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6247 if (MD->size_overridden_methods() == 0) 6248 Methods.insert(MD->getCanonicalDecl()); 6249 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6250 E = MD->end_overridden_methods(); 6251 I != E; ++I) 6252 AddMostOverridenMethods(*I, Methods); 6253 } 6254 6255 /// \brief Check if a method overloads virtual methods in a base class without 6256 /// overriding any. 6257 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6258 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6259 if (!MD->getDeclName().isIdentifier()) 6260 return; 6261 6262 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6263 /*bool RecordPaths=*/false, 6264 /*bool DetectVirtual=*/false); 6265 FindHiddenVirtualMethodData Data; 6266 Data.Method = MD; 6267 Data.S = this; 6268 6269 // Keep the base methods that were overriden or introduced in the subclass 6270 // by 'using' in a set. A base method not in this set is hidden. 6271 CXXRecordDecl *DC = MD->getParent(); 6272 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6273 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6274 NamedDecl *ND = *I; 6275 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6276 ND = shad->getTargetDecl(); 6277 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6278 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6279 } 6280 6281 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6282 OverloadedMethods = Data.OverloadedMethods; 6283 } 6284 6285 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6286 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6287 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6288 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6289 PartialDiagnostic PD = PDiag( 6290 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6291 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6292 Diag(overloadedMD->getLocation(), PD); 6293 } 6294 } 6295 6296 /// \brief Diagnose methods which overload virtual methods in a base class 6297 /// without overriding any. 6298 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6299 if (MD->isInvalidDecl()) 6300 return; 6301 6302 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6303 return; 6304 6305 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6306 FindHiddenVirtualMethods(MD, OverloadedMethods); 6307 if (!OverloadedMethods.empty()) { 6308 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6309 << MD << (OverloadedMethods.size() > 1); 6310 6311 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6312 } 6313 } 6314 6315 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6316 Decl *TagDecl, 6317 SourceLocation LBrac, 6318 SourceLocation RBrac, 6319 AttributeList *AttrList) { 6320 if (!TagDecl) 6321 return; 6322 6323 AdjustDeclIfTemplate(TagDecl); 6324 6325 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6326 if (l->getKind() != AttributeList::AT_Visibility) 6327 continue; 6328 l->setInvalid(); 6329 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6330 l->getName(); 6331 } 6332 6333 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6334 // strict aliasing violation! 6335 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6336 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6337 6338 CheckCompletedCXXClass( 6339 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6340 } 6341 6342 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6343 /// special functions, such as the default constructor, copy 6344 /// constructor, or destructor, to the given C++ class (C++ 6345 /// [special]p1). This routine can only be executed just before the 6346 /// definition of the class is complete. 6347 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6348 if (!ClassDecl->hasUserDeclaredConstructor()) 6349 ++ASTContext::NumImplicitDefaultConstructors; 6350 6351 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6352 ++ASTContext::NumImplicitCopyConstructors; 6353 6354 // If the properties or semantics of the copy constructor couldn't be 6355 // determined while the class was being declared, force a declaration 6356 // of it now. 6357 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6358 DeclareImplicitCopyConstructor(ClassDecl); 6359 } 6360 6361 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6362 ++ASTContext::NumImplicitMoveConstructors; 6363 6364 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6365 DeclareImplicitMoveConstructor(ClassDecl); 6366 } 6367 6368 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6369 ++ASTContext::NumImplicitCopyAssignmentOperators; 6370 6371 // If we have a dynamic class, then the copy assignment operator may be 6372 // virtual, so we have to declare it immediately. This ensures that, e.g., 6373 // it shows up in the right place in the vtable and that we diagnose 6374 // problems with the implicit exception specification. 6375 if (ClassDecl->isDynamicClass() || 6376 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6377 DeclareImplicitCopyAssignment(ClassDecl); 6378 } 6379 6380 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6381 ++ASTContext::NumImplicitMoveAssignmentOperators; 6382 6383 // Likewise for the move assignment operator. 6384 if (ClassDecl->isDynamicClass() || 6385 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6386 DeclareImplicitMoveAssignment(ClassDecl); 6387 } 6388 6389 if (!ClassDecl->hasUserDeclaredDestructor()) { 6390 ++ASTContext::NumImplicitDestructors; 6391 6392 // If we have a dynamic class, then the destructor may be virtual, so we 6393 // have to declare the destructor immediately. This ensures that, e.g., it 6394 // shows up in the right place in the vtable and that we diagnose problems 6395 // with the implicit exception specification. 6396 if (ClassDecl->isDynamicClass() || 6397 ClassDecl->needsOverloadResolutionForDestructor()) 6398 DeclareImplicitDestructor(ClassDecl); 6399 } 6400 } 6401 6402 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6403 if (!D) 6404 return 0; 6405 6406 // The order of template parameters is not important here. All names 6407 // get added to the same scope. 6408 SmallVector<TemplateParameterList *, 4> ParameterLists; 6409 6410 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6411 D = TD->getTemplatedDecl(); 6412 6413 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6414 ParameterLists.push_back(PSD->getTemplateParameters()); 6415 6416 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6417 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6418 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6419 6420 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6421 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6422 ParameterLists.push_back(FTD->getTemplateParameters()); 6423 } 6424 } 6425 6426 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6427 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6428 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6429 6430 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6431 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6432 ParameterLists.push_back(CTD->getTemplateParameters()); 6433 } 6434 } 6435 6436 unsigned Count = 0; 6437 for (TemplateParameterList *Params : ParameterLists) { 6438 if (Params->size() > 0) 6439 // Ignore explicit specializations; they don't contribute to the template 6440 // depth. 6441 ++Count; 6442 for (NamedDecl *Param : *Params) { 6443 if (Param->getDeclName()) { 6444 S->AddDecl(Param); 6445 IdResolver.AddDecl(Param); 6446 } 6447 } 6448 } 6449 6450 return Count; 6451 } 6452 6453 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6454 if (!RecordD) return; 6455 AdjustDeclIfTemplate(RecordD); 6456 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6457 PushDeclContext(S, Record); 6458 } 6459 6460 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6461 if (!RecordD) return; 6462 PopDeclContext(); 6463 } 6464 6465 /// This is used to implement the constant expression evaluation part of the 6466 /// attribute enable_if extension. There is nothing in standard C++ which would 6467 /// require reentering parameters. 6468 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6469 if (!Param) 6470 return; 6471 6472 S->AddDecl(Param); 6473 if (Param->getDeclName()) 6474 IdResolver.AddDecl(Param); 6475 } 6476 6477 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6478 /// parsing a top-level (non-nested) C++ class, and we are now 6479 /// parsing those parts of the given Method declaration that could 6480 /// not be parsed earlier (C++ [class.mem]p2), such as default 6481 /// arguments. This action should enter the scope of the given 6482 /// Method declaration as if we had just parsed the qualified method 6483 /// name. However, it should not bring the parameters into scope; 6484 /// that will be performed by ActOnDelayedCXXMethodParameter. 6485 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6486 } 6487 6488 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6489 /// C++ method declaration. We're (re-)introducing the given 6490 /// function parameter into scope for use in parsing later parts of 6491 /// the method declaration. For example, we could see an 6492 /// ActOnParamDefaultArgument event for this parameter. 6493 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6494 if (!ParamD) 6495 return; 6496 6497 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6498 6499 // If this parameter has an unparsed default argument, clear it out 6500 // to make way for the parsed default argument. 6501 if (Param->hasUnparsedDefaultArg()) 6502 Param->setDefaultArg(nullptr); 6503 6504 S->AddDecl(Param); 6505 if (Param->getDeclName()) 6506 IdResolver.AddDecl(Param); 6507 } 6508 6509 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6510 /// processing the delayed method declaration for Method. The method 6511 /// declaration is now considered finished. There may be a separate 6512 /// ActOnStartOfFunctionDef action later (not necessarily 6513 /// immediately!) for this method, if it was also defined inside the 6514 /// class body. 6515 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6516 if (!MethodD) 6517 return; 6518 6519 AdjustDeclIfTemplate(MethodD); 6520 6521 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6522 6523 // Now that we have our default arguments, check the constructor 6524 // again. It could produce additional diagnostics or affect whether 6525 // the class has implicitly-declared destructors, among other 6526 // things. 6527 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6528 CheckConstructor(Constructor); 6529 6530 // Check the default arguments, which we may have added. 6531 if (!Method->isInvalidDecl()) 6532 CheckCXXDefaultArguments(Method); 6533 } 6534 6535 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6536 /// the well-formedness of the constructor declarator @p D with type @p 6537 /// R. If there are any errors in the declarator, this routine will 6538 /// emit diagnostics and set the invalid bit to true. In any case, the type 6539 /// will be updated to reflect a well-formed type for the constructor and 6540 /// returned. 6541 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6542 StorageClass &SC) { 6543 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6544 6545 // C++ [class.ctor]p3: 6546 // A constructor shall not be virtual (10.3) or static (9.4). A 6547 // constructor can be invoked for a const, volatile or const 6548 // volatile object. A constructor shall not be declared const, 6549 // volatile, or const volatile (9.3.2). 6550 if (isVirtual) { 6551 if (!D.isInvalidType()) 6552 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6553 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6554 << SourceRange(D.getIdentifierLoc()); 6555 D.setInvalidType(); 6556 } 6557 if (SC == SC_Static) { 6558 if (!D.isInvalidType()) 6559 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6560 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6561 << SourceRange(D.getIdentifierLoc()); 6562 D.setInvalidType(); 6563 SC = SC_None; 6564 } 6565 6566 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6567 diagnoseIgnoredQualifiers( 6568 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6569 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6570 D.getDeclSpec().getRestrictSpecLoc(), 6571 D.getDeclSpec().getAtomicSpecLoc()); 6572 D.setInvalidType(); 6573 } 6574 6575 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6576 if (FTI.TypeQuals != 0) { 6577 if (FTI.TypeQuals & Qualifiers::Const) 6578 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6579 << "const" << SourceRange(D.getIdentifierLoc()); 6580 if (FTI.TypeQuals & Qualifiers::Volatile) 6581 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6582 << "volatile" << SourceRange(D.getIdentifierLoc()); 6583 if (FTI.TypeQuals & Qualifiers::Restrict) 6584 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6585 << "restrict" << SourceRange(D.getIdentifierLoc()); 6586 D.setInvalidType(); 6587 } 6588 6589 // C++0x [class.ctor]p4: 6590 // A constructor shall not be declared with a ref-qualifier. 6591 if (FTI.hasRefQualifier()) { 6592 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6593 << FTI.RefQualifierIsLValueRef 6594 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6595 D.setInvalidType(); 6596 } 6597 6598 // Rebuild the function type "R" without any type qualifiers (in 6599 // case any of the errors above fired) and with "void" as the 6600 // return type, since constructors don't have return types. 6601 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6602 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6603 return R; 6604 6605 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6606 EPI.TypeQuals = 0; 6607 EPI.RefQualifier = RQ_None; 6608 6609 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6610 } 6611 6612 /// CheckConstructor - Checks a fully-formed constructor for 6613 /// well-formedness, issuing any diagnostics required. Returns true if 6614 /// the constructor declarator is invalid. 6615 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6616 CXXRecordDecl *ClassDecl 6617 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6618 if (!ClassDecl) 6619 return Constructor->setInvalidDecl(); 6620 6621 // C++ [class.copy]p3: 6622 // A declaration of a constructor for a class X is ill-formed if 6623 // its first parameter is of type (optionally cv-qualified) X and 6624 // either there are no other parameters or else all other 6625 // parameters have default arguments. 6626 if (!Constructor->isInvalidDecl() && 6627 ((Constructor->getNumParams() == 1) || 6628 (Constructor->getNumParams() > 1 && 6629 Constructor->getParamDecl(1)->hasDefaultArg())) && 6630 Constructor->getTemplateSpecializationKind() 6631 != TSK_ImplicitInstantiation) { 6632 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6633 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6634 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6635 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6636 const char *ConstRef 6637 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6638 : " const &"; 6639 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6640 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6641 6642 // FIXME: Rather that making the constructor invalid, we should endeavor 6643 // to fix the type. 6644 Constructor->setInvalidDecl(); 6645 } 6646 } 6647 } 6648 6649 /// CheckDestructor - Checks a fully-formed destructor definition for 6650 /// well-formedness, issuing any diagnostics required. Returns true 6651 /// on error. 6652 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6653 CXXRecordDecl *RD = Destructor->getParent(); 6654 6655 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6656 SourceLocation Loc; 6657 6658 if (!Destructor->isImplicit()) 6659 Loc = Destructor->getLocation(); 6660 else 6661 Loc = RD->getLocation(); 6662 6663 // If we have a virtual destructor, look up the deallocation function 6664 FunctionDecl *OperatorDelete = nullptr; 6665 DeclarationName Name = 6666 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6667 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6668 return true; 6669 // If there's no class-specific operator delete, look up the global 6670 // non-array delete. 6671 if (!OperatorDelete) 6672 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6673 6674 MarkFunctionReferenced(Loc, OperatorDelete); 6675 6676 Destructor->setOperatorDelete(OperatorDelete); 6677 } 6678 6679 return false; 6680 } 6681 6682 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6683 /// the well-formednes of the destructor declarator @p D with type @p 6684 /// R. If there are any errors in the declarator, this routine will 6685 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6686 /// will be updated to reflect a well-formed type for the destructor and 6687 /// returned. 6688 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6689 StorageClass& SC) { 6690 // C++ [class.dtor]p1: 6691 // [...] A typedef-name that names a class is a class-name 6692 // (7.1.3); however, a typedef-name that names a class shall not 6693 // be used as the identifier in the declarator for a destructor 6694 // declaration. 6695 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6696 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6697 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6698 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6699 else if (const TemplateSpecializationType *TST = 6700 DeclaratorType->getAs<TemplateSpecializationType>()) 6701 if (TST->isTypeAlias()) 6702 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6703 << DeclaratorType << 1; 6704 6705 // C++ [class.dtor]p2: 6706 // A destructor is used to destroy objects of its class type. A 6707 // destructor takes no parameters, and no return type can be 6708 // specified for it (not even void). The address of a destructor 6709 // shall not be taken. A destructor shall not be static. A 6710 // destructor can be invoked for a const, volatile or const 6711 // volatile object. A destructor shall not be declared const, 6712 // volatile or const volatile (9.3.2). 6713 if (SC == SC_Static) { 6714 if (!D.isInvalidType()) 6715 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6716 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6717 << SourceRange(D.getIdentifierLoc()) 6718 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6719 6720 SC = SC_None; 6721 } 6722 if (!D.isInvalidType()) { 6723 // Destructors don't have return types, but the parser will 6724 // happily parse something like: 6725 // 6726 // class X { 6727 // float ~X(); 6728 // }; 6729 // 6730 // The return type will be eliminated later. 6731 if (D.getDeclSpec().hasTypeSpecifier()) 6732 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6733 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6734 << SourceRange(D.getIdentifierLoc()); 6735 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6736 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6737 SourceLocation(), 6738 D.getDeclSpec().getConstSpecLoc(), 6739 D.getDeclSpec().getVolatileSpecLoc(), 6740 D.getDeclSpec().getRestrictSpecLoc(), 6741 D.getDeclSpec().getAtomicSpecLoc()); 6742 D.setInvalidType(); 6743 } 6744 } 6745 6746 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6747 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6748 if (FTI.TypeQuals & Qualifiers::Const) 6749 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6750 << "const" << SourceRange(D.getIdentifierLoc()); 6751 if (FTI.TypeQuals & Qualifiers::Volatile) 6752 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6753 << "volatile" << SourceRange(D.getIdentifierLoc()); 6754 if (FTI.TypeQuals & Qualifiers::Restrict) 6755 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6756 << "restrict" << SourceRange(D.getIdentifierLoc()); 6757 D.setInvalidType(); 6758 } 6759 6760 // C++0x [class.dtor]p2: 6761 // A destructor shall not be declared with a ref-qualifier. 6762 if (FTI.hasRefQualifier()) { 6763 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6764 << FTI.RefQualifierIsLValueRef 6765 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6766 D.setInvalidType(); 6767 } 6768 6769 // Make sure we don't have any parameters. 6770 if (FTIHasNonVoidParameters(FTI)) { 6771 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6772 6773 // Delete the parameters. 6774 FTI.freeParams(); 6775 D.setInvalidType(); 6776 } 6777 6778 // Make sure the destructor isn't variadic. 6779 if (FTI.isVariadic) { 6780 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6781 D.setInvalidType(); 6782 } 6783 6784 // Rebuild the function type "R" without any type qualifiers or 6785 // parameters (in case any of the errors above fired) and with 6786 // "void" as the return type, since destructors don't have return 6787 // types. 6788 if (!D.isInvalidType()) 6789 return R; 6790 6791 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6792 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6793 EPI.Variadic = false; 6794 EPI.TypeQuals = 0; 6795 EPI.RefQualifier = RQ_None; 6796 return Context.getFunctionType(Context.VoidTy, None, EPI); 6797 } 6798 6799 static void extendLeft(SourceRange &R, const SourceRange &Before) { 6800 if (Before.isInvalid()) 6801 return; 6802 R.setBegin(Before.getBegin()); 6803 if (R.getEnd().isInvalid()) 6804 R.setEnd(Before.getEnd()); 6805 } 6806 6807 static void extendRight(SourceRange &R, const SourceRange &After) { 6808 if (After.isInvalid()) 6809 return; 6810 if (R.getBegin().isInvalid()) 6811 R.setBegin(After.getBegin()); 6812 R.setEnd(After.getEnd()); 6813 } 6814 6815 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6816 /// well-formednes of the conversion function declarator @p D with 6817 /// type @p R. If there are any errors in the declarator, this routine 6818 /// will emit diagnostics and return true. Otherwise, it will return 6819 /// false. Either way, the type @p R will be updated to reflect a 6820 /// well-formed type for the conversion operator. 6821 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6822 StorageClass& SC) { 6823 // C++ [class.conv.fct]p1: 6824 // Neither parameter types nor return type can be specified. The 6825 // type of a conversion function (8.3.5) is "function taking no 6826 // parameter returning conversion-type-id." 6827 if (SC == SC_Static) { 6828 if (!D.isInvalidType()) 6829 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6830 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6831 << D.getName().getSourceRange(); 6832 D.setInvalidType(); 6833 SC = SC_None; 6834 } 6835 6836 TypeSourceInfo *ConvTSI = nullptr; 6837 QualType ConvType = 6838 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 6839 6840 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6841 // Conversion functions don't have return types, but the parser will 6842 // happily parse something like: 6843 // 6844 // class X { 6845 // float operator bool(); 6846 // }; 6847 // 6848 // The return type will be changed later anyway. 6849 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6850 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6851 << SourceRange(D.getIdentifierLoc()); 6852 D.setInvalidType(); 6853 } 6854 6855 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6856 6857 // Make sure we don't have any parameters. 6858 if (Proto->getNumParams() > 0) { 6859 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6860 6861 // Delete the parameters. 6862 D.getFunctionTypeInfo().freeParams(); 6863 D.setInvalidType(); 6864 } else if (Proto->isVariadic()) { 6865 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6866 D.setInvalidType(); 6867 } 6868 6869 // Diagnose "&operator bool()" and other such nonsense. This 6870 // is actually a gcc extension which we don't support. 6871 if (Proto->getReturnType() != ConvType) { 6872 bool NeedsTypedef = false; 6873 SourceRange Before, After; 6874 6875 // Walk the chunks and extract information on them for our diagnostic. 6876 bool PastFunctionChunk = false; 6877 for (auto &Chunk : D.type_objects()) { 6878 switch (Chunk.Kind) { 6879 case DeclaratorChunk::Function: 6880 if (!PastFunctionChunk) { 6881 if (Chunk.Fun.HasTrailingReturnType) { 6882 TypeSourceInfo *TRT = nullptr; 6883 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 6884 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 6885 } 6886 PastFunctionChunk = true; 6887 break; 6888 } 6889 // Fall through. 6890 case DeclaratorChunk::Array: 6891 NeedsTypedef = true; 6892 extendRight(After, Chunk.getSourceRange()); 6893 break; 6894 6895 case DeclaratorChunk::Pointer: 6896 case DeclaratorChunk::BlockPointer: 6897 case DeclaratorChunk::Reference: 6898 case DeclaratorChunk::MemberPointer: 6899 extendLeft(Before, Chunk.getSourceRange()); 6900 break; 6901 6902 case DeclaratorChunk::Paren: 6903 extendLeft(Before, Chunk.Loc); 6904 extendRight(After, Chunk.EndLoc); 6905 break; 6906 } 6907 } 6908 6909 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 6910 After.isValid() ? After.getBegin() : 6911 D.getIdentifierLoc(); 6912 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 6913 DB << Before << After; 6914 6915 if (!NeedsTypedef) { 6916 DB << /*don't need a typedef*/0; 6917 6918 // If we can provide a correct fix-it hint, do so. 6919 if (After.isInvalid() && ConvTSI) { 6920 SourceLocation InsertLoc = 6921 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 6922 DB << FixItHint::CreateInsertion(InsertLoc, " ") 6923 << FixItHint::CreateInsertionFromRange( 6924 InsertLoc, CharSourceRange::getTokenRange(Before)) 6925 << FixItHint::CreateRemoval(Before); 6926 } 6927 } else if (!Proto->getReturnType()->isDependentType()) { 6928 DB << /*typedef*/1 << Proto->getReturnType(); 6929 } else if (getLangOpts().CPlusPlus11) { 6930 DB << /*alias template*/2 << Proto->getReturnType(); 6931 } else { 6932 DB << /*might not be fixable*/3; 6933 } 6934 6935 // Recover by incorporating the other type chunks into the result type. 6936 // Note, this does *not* change the name of the function. This is compatible 6937 // with the GCC extension: 6938 // struct S { &operator int(); } s; 6939 // int &r = s.operator int(); // ok in GCC 6940 // S::operator int&() {} // error in GCC, function name is 'operator int'. 6941 ConvType = Proto->getReturnType(); 6942 } 6943 6944 // C++ [class.conv.fct]p4: 6945 // The conversion-type-id shall not represent a function type nor 6946 // an array type. 6947 if (ConvType->isArrayType()) { 6948 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6949 ConvType = Context.getPointerType(ConvType); 6950 D.setInvalidType(); 6951 } else if (ConvType->isFunctionType()) { 6952 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6953 ConvType = Context.getPointerType(ConvType); 6954 D.setInvalidType(); 6955 } 6956 6957 // Rebuild the function type "R" without any parameters (in case any 6958 // of the errors above fired) and with the conversion type as the 6959 // return type. 6960 if (D.isInvalidType()) 6961 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6962 6963 // C++0x explicit conversion operators. 6964 if (D.getDeclSpec().isExplicitSpecified()) 6965 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6966 getLangOpts().CPlusPlus11 ? 6967 diag::warn_cxx98_compat_explicit_conversion_functions : 6968 diag::ext_explicit_conversion_functions) 6969 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6970 } 6971 6972 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6973 /// the declaration of the given C++ conversion function. This routine 6974 /// is responsible for recording the conversion function in the C++ 6975 /// class, if possible. 6976 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6977 assert(Conversion && "Expected to receive a conversion function declaration"); 6978 6979 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6980 6981 // Make sure we aren't redeclaring the conversion function. 6982 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6983 6984 // C++ [class.conv.fct]p1: 6985 // [...] A conversion function is never used to convert a 6986 // (possibly cv-qualified) object to the (possibly cv-qualified) 6987 // same object type (or a reference to it), to a (possibly 6988 // cv-qualified) base class of that type (or a reference to it), 6989 // or to (possibly cv-qualified) void. 6990 // FIXME: Suppress this warning if the conversion function ends up being a 6991 // virtual function that overrides a virtual function in a base class. 6992 QualType ClassType 6993 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6994 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6995 ConvType = ConvTypeRef->getPointeeType(); 6996 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6997 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6998 /* Suppress diagnostics for instantiations. */; 6999 else if (ConvType->isRecordType()) { 7000 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 7001 if (ConvType == ClassType) 7002 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 7003 << ClassType; 7004 else if (IsDerivedFrom(ClassType, ConvType)) 7005 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 7006 << ClassType << ConvType; 7007 } else if (ConvType->isVoidType()) { 7008 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 7009 << ClassType << ConvType; 7010 } 7011 7012 if (FunctionTemplateDecl *ConversionTemplate 7013 = Conversion->getDescribedFunctionTemplate()) 7014 return ConversionTemplate; 7015 7016 return Conversion; 7017 } 7018 7019 //===----------------------------------------------------------------------===// 7020 // Namespace Handling 7021 //===----------------------------------------------------------------------===// 7022 7023 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 7024 /// reopened. 7025 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 7026 SourceLocation Loc, 7027 IdentifierInfo *II, bool *IsInline, 7028 NamespaceDecl *PrevNS) { 7029 assert(*IsInline != PrevNS->isInline()); 7030 7031 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 7032 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 7033 // inline namespaces, with the intention of bringing names into namespace std. 7034 // 7035 // We support this just well enough to get that case working; this is not 7036 // sufficient to support reopening namespaces as inline in general. 7037 if (*IsInline && II && II->getName().startswith("__atomic") && 7038 S.getSourceManager().isInSystemHeader(Loc)) { 7039 // Mark all prior declarations of the namespace as inline. 7040 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 7041 NS = NS->getPreviousDecl()) 7042 NS->setInline(*IsInline); 7043 // Patch up the lookup table for the containing namespace. This isn't really 7044 // correct, but it's good enough for this particular case. 7045 for (auto *I : PrevNS->decls()) 7046 if (auto *ND = dyn_cast<NamedDecl>(I)) 7047 PrevNS->getParent()->makeDeclVisibleInContext(ND); 7048 return; 7049 } 7050 7051 if (PrevNS->isInline()) 7052 // The user probably just forgot the 'inline', so suggest that it 7053 // be added back. 7054 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 7055 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 7056 else 7057 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 7058 7059 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 7060 *IsInline = PrevNS->isInline(); 7061 } 7062 7063 /// ActOnStartNamespaceDef - This is called at the start of a namespace 7064 /// definition. 7065 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 7066 SourceLocation InlineLoc, 7067 SourceLocation NamespaceLoc, 7068 SourceLocation IdentLoc, 7069 IdentifierInfo *II, 7070 SourceLocation LBrace, 7071 AttributeList *AttrList) { 7072 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 7073 // For anonymous namespace, take the location of the left brace. 7074 SourceLocation Loc = II ? IdentLoc : LBrace; 7075 bool IsInline = InlineLoc.isValid(); 7076 bool IsInvalid = false; 7077 bool IsStd = false; 7078 bool AddToKnown = false; 7079 Scope *DeclRegionScope = NamespcScope->getParent(); 7080 7081 NamespaceDecl *PrevNS = nullptr; 7082 if (II) { 7083 // C++ [namespace.def]p2: 7084 // The identifier in an original-namespace-definition shall not 7085 // have been previously defined in the declarative region in 7086 // which the original-namespace-definition appears. The 7087 // identifier in an original-namespace-definition is the name of 7088 // the namespace. Subsequently in that declarative region, it is 7089 // treated as an original-namespace-name. 7090 // 7091 // Since namespace names are unique in their scope, and we don't 7092 // look through using directives, just look for any ordinary names. 7093 7094 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 7095 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 7096 Decl::IDNS_Namespace; 7097 NamedDecl *PrevDecl = nullptr; 7098 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 7099 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 7100 ++I) { 7101 if ((*I)->getIdentifierNamespace() & IDNS) { 7102 PrevDecl = *I; 7103 break; 7104 } 7105 } 7106 7107 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7108 7109 if (PrevNS) { 7110 // This is an extended namespace definition. 7111 if (IsInline != PrevNS->isInline()) 7112 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7113 &IsInline, PrevNS); 7114 } else if (PrevDecl) { 7115 // This is an invalid name redefinition. 7116 Diag(Loc, diag::err_redefinition_different_kind) 7117 << II; 7118 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7119 IsInvalid = true; 7120 // Continue on to push Namespc as current DeclContext and return it. 7121 } else if (II->isStr("std") && 7122 CurContext->getRedeclContext()->isTranslationUnit()) { 7123 // This is the first "real" definition of the namespace "std", so update 7124 // our cache of the "std" namespace to point at this definition. 7125 PrevNS = getStdNamespace(); 7126 IsStd = true; 7127 AddToKnown = !IsInline; 7128 } else { 7129 // We've seen this namespace for the first time. 7130 AddToKnown = !IsInline; 7131 } 7132 } else { 7133 // Anonymous namespaces. 7134 7135 // Determine whether the parent already has an anonymous namespace. 7136 DeclContext *Parent = CurContext->getRedeclContext(); 7137 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7138 PrevNS = TU->getAnonymousNamespace(); 7139 } else { 7140 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7141 PrevNS = ND->getAnonymousNamespace(); 7142 } 7143 7144 if (PrevNS && IsInline != PrevNS->isInline()) 7145 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7146 &IsInline, PrevNS); 7147 } 7148 7149 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7150 StartLoc, Loc, II, PrevNS); 7151 if (IsInvalid) 7152 Namespc->setInvalidDecl(); 7153 7154 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7155 7156 // FIXME: Should we be merging attributes? 7157 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7158 PushNamespaceVisibilityAttr(Attr, Loc); 7159 7160 if (IsStd) 7161 StdNamespace = Namespc; 7162 if (AddToKnown) 7163 KnownNamespaces[Namespc] = false; 7164 7165 if (II) { 7166 PushOnScopeChains(Namespc, DeclRegionScope); 7167 } else { 7168 // Link the anonymous namespace into its parent. 7169 DeclContext *Parent = CurContext->getRedeclContext(); 7170 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7171 TU->setAnonymousNamespace(Namespc); 7172 } else { 7173 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7174 } 7175 7176 CurContext->addDecl(Namespc); 7177 7178 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7179 // behaves as if it were replaced by 7180 // namespace unique { /* empty body */ } 7181 // using namespace unique; 7182 // namespace unique { namespace-body } 7183 // where all occurrences of 'unique' in a translation unit are 7184 // replaced by the same identifier and this identifier differs 7185 // from all other identifiers in the entire program. 7186 7187 // We just create the namespace with an empty name and then add an 7188 // implicit using declaration, just like the standard suggests. 7189 // 7190 // CodeGen enforces the "universally unique" aspect by giving all 7191 // declarations semantically contained within an anonymous 7192 // namespace internal linkage. 7193 7194 if (!PrevNS) { 7195 UsingDirectiveDecl* UD 7196 = UsingDirectiveDecl::Create(Context, Parent, 7197 /* 'using' */ LBrace, 7198 /* 'namespace' */ SourceLocation(), 7199 /* qualifier */ NestedNameSpecifierLoc(), 7200 /* identifier */ SourceLocation(), 7201 Namespc, 7202 /* Ancestor */ Parent); 7203 UD->setImplicit(); 7204 Parent->addDecl(UD); 7205 } 7206 } 7207 7208 ActOnDocumentableDecl(Namespc); 7209 7210 // Although we could have an invalid decl (i.e. the namespace name is a 7211 // redefinition), push it as current DeclContext and try to continue parsing. 7212 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7213 // for the namespace has the declarations that showed up in that particular 7214 // namespace definition. 7215 PushDeclContext(NamespcScope, Namespc); 7216 return Namespc; 7217 } 7218 7219 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7220 /// is a namespace alias, returns the namespace it points to. 7221 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7222 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7223 return AD->getNamespace(); 7224 return dyn_cast_or_null<NamespaceDecl>(D); 7225 } 7226 7227 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7228 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7229 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7230 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7231 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7232 Namespc->setRBraceLoc(RBrace); 7233 PopDeclContext(); 7234 if (Namespc->hasAttr<VisibilityAttr>()) 7235 PopPragmaVisibility(true, RBrace); 7236 } 7237 7238 CXXRecordDecl *Sema::getStdBadAlloc() const { 7239 return cast_or_null<CXXRecordDecl>( 7240 StdBadAlloc.get(Context.getExternalSource())); 7241 } 7242 7243 NamespaceDecl *Sema::getStdNamespace() const { 7244 return cast_or_null<NamespaceDecl>( 7245 StdNamespace.get(Context.getExternalSource())); 7246 } 7247 7248 /// \brief Retrieve the special "std" namespace, which may require us to 7249 /// implicitly define the namespace. 7250 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7251 if (!StdNamespace) { 7252 // The "std" namespace has not yet been defined, so build one implicitly. 7253 StdNamespace = NamespaceDecl::Create(Context, 7254 Context.getTranslationUnitDecl(), 7255 /*Inline=*/false, 7256 SourceLocation(), SourceLocation(), 7257 &PP.getIdentifierTable().get("std"), 7258 /*PrevDecl=*/nullptr); 7259 getStdNamespace()->setImplicit(true); 7260 } 7261 7262 return getStdNamespace(); 7263 } 7264 7265 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7266 assert(getLangOpts().CPlusPlus && 7267 "Looking for std::initializer_list outside of C++."); 7268 7269 // We're looking for implicit instantiations of 7270 // template <typename E> class std::initializer_list. 7271 7272 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7273 return false; 7274 7275 ClassTemplateDecl *Template = nullptr; 7276 const TemplateArgument *Arguments = nullptr; 7277 7278 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7279 7280 ClassTemplateSpecializationDecl *Specialization = 7281 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7282 if (!Specialization) 7283 return false; 7284 7285 Template = Specialization->getSpecializedTemplate(); 7286 Arguments = Specialization->getTemplateArgs().data(); 7287 } else if (const TemplateSpecializationType *TST = 7288 Ty->getAs<TemplateSpecializationType>()) { 7289 Template = dyn_cast_or_null<ClassTemplateDecl>( 7290 TST->getTemplateName().getAsTemplateDecl()); 7291 Arguments = TST->getArgs(); 7292 } 7293 if (!Template) 7294 return false; 7295 7296 if (!StdInitializerList) { 7297 // Haven't recognized std::initializer_list yet, maybe this is it. 7298 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7299 if (TemplateClass->getIdentifier() != 7300 &PP.getIdentifierTable().get("initializer_list") || 7301 !getStdNamespace()->InEnclosingNamespaceSetOf( 7302 TemplateClass->getDeclContext())) 7303 return false; 7304 // This is a template called std::initializer_list, but is it the right 7305 // template? 7306 TemplateParameterList *Params = Template->getTemplateParameters(); 7307 if (Params->getMinRequiredArguments() != 1) 7308 return false; 7309 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7310 return false; 7311 7312 // It's the right template. 7313 StdInitializerList = Template; 7314 } 7315 7316 if (Template != StdInitializerList) 7317 return false; 7318 7319 // This is an instance of std::initializer_list. Find the argument type. 7320 if (Element) 7321 *Element = Arguments[0].getAsType(); 7322 return true; 7323 } 7324 7325 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7326 NamespaceDecl *Std = S.getStdNamespace(); 7327 if (!Std) { 7328 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7329 return nullptr; 7330 } 7331 7332 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7333 Loc, Sema::LookupOrdinaryName); 7334 if (!S.LookupQualifiedName(Result, Std)) { 7335 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7336 return nullptr; 7337 } 7338 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7339 if (!Template) { 7340 Result.suppressDiagnostics(); 7341 // We found something weird. Complain about the first thing we found. 7342 NamedDecl *Found = *Result.begin(); 7343 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7344 return nullptr; 7345 } 7346 7347 // We found some template called std::initializer_list. Now verify that it's 7348 // correct. 7349 TemplateParameterList *Params = Template->getTemplateParameters(); 7350 if (Params->getMinRequiredArguments() != 1 || 7351 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7352 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7353 return nullptr; 7354 } 7355 7356 return Template; 7357 } 7358 7359 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7360 if (!StdInitializerList) { 7361 StdInitializerList = LookupStdInitializerList(*this, Loc); 7362 if (!StdInitializerList) 7363 return QualType(); 7364 } 7365 7366 TemplateArgumentListInfo Args(Loc, Loc); 7367 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7368 Context.getTrivialTypeSourceInfo(Element, 7369 Loc))); 7370 return Context.getCanonicalType( 7371 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7372 } 7373 7374 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7375 // C++ [dcl.init.list]p2: 7376 // A constructor is an initializer-list constructor if its first parameter 7377 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7378 // std::initializer_list<E> for some type E, and either there are no other 7379 // parameters or else all other parameters have default arguments. 7380 if (Ctor->getNumParams() < 1 || 7381 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7382 return false; 7383 7384 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7385 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7386 ArgType = RT->getPointeeType().getUnqualifiedType(); 7387 7388 return isStdInitializerList(ArgType, nullptr); 7389 } 7390 7391 /// \brief Determine whether a using statement is in a context where it will be 7392 /// apply in all contexts. 7393 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7394 switch (CurContext->getDeclKind()) { 7395 case Decl::TranslationUnit: 7396 return true; 7397 case Decl::LinkageSpec: 7398 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7399 default: 7400 return false; 7401 } 7402 } 7403 7404 namespace { 7405 7406 // Callback to only accept typo corrections that are namespaces. 7407 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7408 public: 7409 bool ValidateCandidate(const TypoCorrection &candidate) override { 7410 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7411 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7412 return false; 7413 } 7414 }; 7415 7416 } 7417 7418 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7419 CXXScopeSpec &SS, 7420 SourceLocation IdentLoc, 7421 IdentifierInfo *Ident) { 7422 R.clear(); 7423 if (TypoCorrection Corrected = 7424 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7425 llvm::make_unique<NamespaceValidatorCCC>(), 7426 Sema::CTK_ErrorRecovery)) { 7427 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7428 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7429 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7430 Ident->getName().equals(CorrectedStr); 7431 S.diagnoseTypo(Corrected, 7432 S.PDiag(diag::err_using_directive_member_suggest) 7433 << Ident << DC << DroppedSpecifier << SS.getRange(), 7434 S.PDiag(diag::note_namespace_defined_here)); 7435 } else { 7436 S.diagnoseTypo(Corrected, 7437 S.PDiag(diag::err_using_directive_suggest) << Ident, 7438 S.PDiag(diag::note_namespace_defined_here)); 7439 } 7440 R.addDecl(Corrected.getCorrectionDecl()); 7441 return true; 7442 } 7443 return false; 7444 } 7445 7446 Decl *Sema::ActOnUsingDirective(Scope *S, 7447 SourceLocation UsingLoc, 7448 SourceLocation NamespcLoc, 7449 CXXScopeSpec &SS, 7450 SourceLocation IdentLoc, 7451 IdentifierInfo *NamespcName, 7452 AttributeList *AttrList) { 7453 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7454 assert(NamespcName && "Invalid NamespcName."); 7455 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7456 7457 // This can only happen along a recovery path. 7458 while (S->getFlags() & Scope::TemplateParamScope) 7459 S = S->getParent(); 7460 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7461 7462 UsingDirectiveDecl *UDir = nullptr; 7463 NestedNameSpecifier *Qualifier = nullptr; 7464 if (SS.isSet()) 7465 Qualifier = SS.getScopeRep(); 7466 7467 // Lookup namespace name. 7468 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7469 LookupParsedName(R, S, &SS); 7470 if (R.isAmbiguous()) 7471 return nullptr; 7472 7473 if (R.empty()) { 7474 R.clear(); 7475 // Allow "using namespace std;" or "using namespace ::std;" even if 7476 // "std" hasn't been defined yet, for GCC compatibility. 7477 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7478 NamespcName->isStr("std")) { 7479 Diag(IdentLoc, diag::ext_using_undefined_std); 7480 R.addDecl(getOrCreateStdNamespace()); 7481 R.resolveKind(); 7482 } 7483 // Otherwise, attempt typo correction. 7484 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7485 } 7486 7487 if (!R.empty()) { 7488 NamedDecl *Named = R.getFoundDecl(); 7489 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7490 && "expected namespace decl"); 7491 7492 // The use of a nested name specifier may trigger deprecation warnings. 7493 DiagnoseUseOfDecl(Named, IdentLoc); 7494 7495 // C++ [namespace.udir]p1: 7496 // A using-directive specifies that the names in the nominated 7497 // namespace can be used in the scope in which the 7498 // using-directive appears after the using-directive. During 7499 // unqualified name lookup (3.4.1), the names appear as if they 7500 // were declared in the nearest enclosing namespace which 7501 // contains both the using-directive and the nominated 7502 // namespace. [Note: in this context, "contains" means "contains 7503 // directly or indirectly". ] 7504 7505 // Find enclosing context containing both using-directive and 7506 // nominated namespace. 7507 NamespaceDecl *NS = getNamespaceDecl(Named); 7508 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7509 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7510 CommonAncestor = CommonAncestor->getParent(); 7511 7512 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7513 SS.getWithLocInContext(Context), 7514 IdentLoc, Named, CommonAncestor); 7515 7516 if (IsUsingDirectiveInToplevelContext(CurContext) && 7517 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7518 Diag(IdentLoc, diag::warn_using_directive_in_header); 7519 } 7520 7521 PushUsingDirective(S, UDir); 7522 } else { 7523 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7524 } 7525 7526 if (UDir) 7527 ProcessDeclAttributeList(S, UDir, AttrList); 7528 7529 return UDir; 7530 } 7531 7532 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7533 // If the scope has an associated entity and the using directive is at 7534 // namespace or translation unit scope, add the UsingDirectiveDecl into 7535 // its lookup structure so qualified name lookup can find it. 7536 DeclContext *Ctx = S->getEntity(); 7537 if (Ctx && !Ctx->isFunctionOrMethod()) 7538 Ctx->addDecl(UDir); 7539 else 7540 // Otherwise, it is at block scope. The using-directives will affect lookup 7541 // only to the end of the scope. 7542 S->PushUsingDirective(UDir); 7543 } 7544 7545 7546 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7547 AccessSpecifier AS, 7548 bool HasUsingKeyword, 7549 SourceLocation UsingLoc, 7550 CXXScopeSpec &SS, 7551 UnqualifiedId &Name, 7552 AttributeList *AttrList, 7553 bool HasTypenameKeyword, 7554 SourceLocation TypenameLoc) { 7555 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7556 7557 switch (Name.getKind()) { 7558 case UnqualifiedId::IK_ImplicitSelfParam: 7559 case UnqualifiedId::IK_Identifier: 7560 case UnqualifiedId::IK_OperatorFunctionId: 7561 case UnqualifiedId::IK_LiteralOperatorId: 7562 case UnqualifiedId::IK_ConversionFunctionId: 7563 break; 7564 7565 case UnqualifiedId::IK_ConstructorName: 7566 case UnqualifiedId::IK_ConstructorTemplateId: 7567 // C++11 inheriting constructors. 7568 Diag(Name.getLocStart(), 7569 getLangOpts().CPlusPlus11 ? 7570 diag::warn_cxx98_compat_using_decl_constructor : 7571 diag::err_using_decl_constructor) 7572 << SS.getRange(); 7573 7574 if (getLangOpts().CPlusPlus11) break; 7575 7576 return nullptr; 7577 7578 case UnqualifiedId::IK_DestructorName: 7579 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7580 << SS.getRange(); 7581 return nullptr; 7582 7583 case UnqualifiedId::IK_TemplateId: 7584 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7585 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7586 return nullptr; 7587 } 7588 7589 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7590 DeclarationName TargetName = TargetNameInfo.getName(); 7591 if (!TargetName) 7592 return nullptr; 7593 7594 // Warn about access declarations. 7595 if (!HasUsingKeyword) { 7596 Diag(Name.getLocStart(), 7597 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7598 : diag::warn_access_decl_deprecated) 7599 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7600 } 7601 7602 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7603 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7604 return nullptr; 7605 7606 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7607 TargetNameInfo, AttrList, 7608 /* IsInstantiation */ false, 7609 HasTypenameKeyword, TypenameLoc); 7610 if (UD) 7611 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7612 7613 return UD; 7614 } 7615 7616 /// \brief Determine whether a using declaration considers the given 7617 /// declarations as "equivalent", e.g., if they are redeclarations of 7618 /// the same entity or are both typedefs of the same type. 7619 static bool 7620 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7621 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7622 return true; 7623 7624 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7625 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7626 return Context.hasSameType(TD1->getUnderlyingType(), 7627 TD2->getUnderlyingType()); 7628 7629 return false; 7630 } 7631 7632 7633 /// Determines whether to create a using shadow decl for a particular 7634 /// decl, given the set of decls existing prior to this using lookup. 7635 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7636 const LookupResult &Previous, 7637 UsingShadowDecl *&PrevShadow) { 7638 // Diagnose finding a decl which is not from a base class of the 7639 // current class. We do this now because there are cases where this 7640 // function will silently decide not to build a shadow decl, which 7641 // will pre-empt further diagnostics. 7642 // 7643 // We don't need to do this in C++0x because we do the check once on 7644 // the qualifier. 7645 // 7646 // FIXME: diagnose the following if we care enough: 7647 // struct A { int foo; }; 7648 // struct B : A { using A::foo; }; 7649 // template <class T> struct C : A {}; 7650 // template <class T> struct D : C<T> { using B::foo; } // <--- 7651 // This is invalid (during instantiation) in C++03 because B::foo 7652 // resolves to the using decl in B, which is not a base class of D<T>. 7653 // We can't diagnose it immediately because C<T> is an unknown 7654 // specialization. The UsingShadowDecl in D<T> then points directly 7655 // to A::foo, which will look well-formed when we instantiate. 7656 // The right solution is to not collapse the shadow-decl chain. 7657 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7658 DeclContext *OrigDC = Orig->getDeclContext(); 7659 7660 // Handle enums and anonymous structs. 7661 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7662 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7663 while (OrigRec->isAnonymousStructOrUnion()) 7664 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7665 7666 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7667 if (OrigDC == CurContext) { 7668 Diag(Using->getLocation(), 7669 diag::err_using_decl_nested_name_specifier_is_current_class) 7670 << Using->getQualifierLoc().getSourceRange(); 7671 Diag(Orig->getLocation(), diag::note_using_decl_target); 7672 return true; 7673 } 7674 7675 Diag(Using->getQualifierLoc().getBeginLoc(), 7676 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7677 << Using->getQualifier() 7678 << cast<CXXRecordDecl>(CurContext) 7679 << Using->getQualifierLoc().getSourceRange(); 7680 Diag(Orig->getLocation(), diag::note_using_decl_target); 7681 return true; 7682 } 7683 } 7684 7685 if (Previous.empty()) return false; 7686 7687 NamedDecl *Target = Orig; 7688 if (isa<UsingShadowDecl>(Target)) 7689 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7690 7691 // If the target happens to be one of the previous declarations, we 7692 // don't have a conflict. 7693 // 7694 // FIXME: but we might be increasing its access, in which case we 7695 // should redeclare it. 7696 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7697 bool FoundEquivalentDecl = false; 7698 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7699 I != E; ++I) { 7700 NamedDecl *D = (*I)->getUnderlyingDecl(); 7701 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7702 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7703 PrevShadow = Shadow; 7704 FoundEquivalentDecl = true; 7705 } 7706 7707 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7708 } 7709 7710 if (FoundEquivalentDecl) 7711 return false; 7712 7713 if (FunctionDecl *FD = Target->getAsFunction()) { 7714 NamedDecl *OldDecl = nullptr; 7715 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7716 /*IsForUsingDecl*/ true)) { 7717 case Ovl_Overload: 7718 return false; 7719 7720 case Ovl_NonFunction: 7721 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7722 break; 7723 7724 // We found a decl with the exact signature. 7725 case Ovl_Match: 7726 // If we're in a record, we want to hide the target, so we 7727 // return true (without a diagnostic) to tell the caller not to 7728 // build a shadow decl. 7729 if (CurContext->isRecord()) 7730 return true; 7731 7732 // If we're not in a record, this is an error. 7733 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7734 break; 7735 } 7736 7737 Diag(Target->getLocation(), diag::note_using_decl_target); 7738 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7739 return true; 7740 } 7741 7742 // Target is not a function. 7743 7744 if (isa<TagDecl>(Target)) { 7745 // No conflict between a tag and a non-tag. 7746 if (!Tag) return false; 7747 7748 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7749 Diag(Target->getLocation(), diag::note_using_decl_target); 7750 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7751 return true; 7752 } 7753 7754 // No conflict between a tag and a non-tag. 7755 if (!NonTag) return false; 7756 7757 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7758 Diag(Target->getLocation(), diag::note_using_decl_target); 7759 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7760 return true; 7761 } 7762 7763 /// Builds a shadow declaration corresponding to a 'using' declaration. 7764 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7765 UsingDecl *UD, 7766 NamedDecl *Orig, 7767 UsingShadowDecl *PrevDecl) { 7768 7769 // If we resolved to another shadow declaration, just coalesce them. 7770 NamedDecl *Target = Orig; 7771 if (isa<UsingShadowDecl>(Target)) { 7772 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7773 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7774 } 7775 7776 UsingShadowDecl *Shadow 7777 = UsingShadowDecl::Create(Context, CurContext, 7778 UD->getLocation(), UD, Target); 7779 UD->addShadowDecl(Shadow); 7780 7781 Shadow->setAccess(UD->getAccess()); 7782 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7783 Shadow->setInvalidDecl(); 7784 7785 Shadow->setPreviousDecl(PrevDecl); 7786 7787 if (S) 7788 PushOnScopeChains(Shadow, S); 7789 else 7790 CurContext->addDecl(Shadow); 7791 7792 7793 return Shadow; 7794 } 7795 7796 /// Hides a using shadow declaration. This is required by the current 7797 /// using-decl implementation when a resolvable using declaration in a 7798 /// class is followed by a declaration which would hide or override 7799 /// one or more of the using decl's targets; for example: 7800 /// 7801 /// struct Base { void foo(int); }; 7802 /// struct Derived : Base { 7803 /// using Base::foo; 7804 /// void foo(int); 7805 /// }; 7806 /// 7807 /// The governing language is C++03 [namespace.udecl]p12: 7808 /// 7809 /// When a using-declaration brings names from a base class into a 7810 /// derived class scope, member functions in the derived class 7811 /// override and/or hide member functions with the same name and 7812 /// parameter types in a base class (rather than conflicting). 7813 /// 7814 /// There are two ways to implement this: 7815 /// (1) optimistically create shadow decls when they're not hidden 7816 /// by existing declarations, or 7817 /// (2) don't create any shadow decls (or at least don't make them 7818 /// visible) until we've fully parsed/instantiated the class. 7819 /// The problem with (1) is that we might have to retroactively remove 7820 /// a shadow decl, which requires several O(n) operations because the 7821 /// decl structures are (very reasonably) not designed for removal. 7822 /// (2) avoids this but is very fiddly and phase-dependent. 7823 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7824 if (Shadow->getDeclName().getNameKind() == 7825 DeclarationName::CXXConversionFunctionName) 7826 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7827 7828 // Remove it from the DeclContext... 7829 Shadow->getDeclContext()->removeDecl(Shadow); 7830 7831 // ...and the scope, if applicable... 7832 if (S) { 7833 S->RemoveDecl(Shadow); 7834 IdResolver.RemoveDecl(Shadow); 7835 } 7836 7837 // ...and the using decl. 7838 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7839 7840 // TODO: complain somehow if Shadow was used. It shouldn't 7841 // be possible for this to happen, because...? 7842 } 7843 7844 /// Find the base specifier for a base class with the given type. 7845 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7846 QualType DesiredBase, 7847 bool &AnyDependentBases) { 7848 // Check whether the named type is a direct base class. 7849 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7850 for (auto &Base : Derived->bases()) { 7851 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7852 if (CanonicalDesiredBase == BaseType) 7853 return &Base; 7854 if (BaseType->isDependentType()) 7855 AnyDependentBases = true; 7856 } 7857 return nullptr; 7858 } 7859 7860 namespace { 7861 class UsingValidatorCCC : public CorrectionCandidateCallback { 7862 public: 7863 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7864 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7865 : HasTypenameKeyword(HasTypenameKeyword), 7866 IsInstantiation(IsInstantiation), OldNNS(NNS), 7867 RequireMemberOf(RequireMemberOf) {} 7868 7869 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7870 NamedDecl *ND = Candidate.getCorrectionDecl(); 7871 7872 // Keywords are not valid here. 7873 if (!ND || isa<NamespaceDecl>(ND)) 7874 return false; 7875 7876 // Completely unqualified names are invalid for a 'using' declaration. 7877 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7878 return false; 7879 7880 if (RequireMemberOf) { 7881 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7882 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7883 // No-one ever wants a using-declaration to name an injected-class-name 7884 // of a base class, unless they're declaring an inheriting constructor. 7885 ASTContext &Ctx = ND->getASTContext(); 7886 if (!Ctx.getLangOpts().CPlusPlus11) 7887 return false; 7888 QualType FoundType = Ctx.getRecordType(FoundRecord); 7889 7890 // Check that the injected-class-name is named as a member of its own 7891 // type; we don't want to suggest 'using Derived::Base;', since that 7892 // means something else. 7893 NestedNameSpecifier *Specifier = 7894 Candidate.WillReplaceSpecifier() 7895 ? Candidate.getCorrectionSpecifier() 7896 : OldNNS; 7897 if (!Specifier->getAsType() || 7898 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7899 return false; 7900 7901 // Check that this inheriting constructor declaration actually names a 7902 // direct base class of the current class. 7903 bool AnyDependentBases = false; 7904 if (!findDirectBaseWithType(RequireMemberOf, 7905 Ctx.getRecordType(FoundRecord), 7906 AnyDependentBases) && 7907 !AnyDependentBases) 7908 return false; 7909 } else { 7910 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7911 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7912 return false; 7913 7914 // FIXME: Check that the base class member is accessible? 7915 } 7916 } 7917 7918 if (isa<TypeDecl>(ND)) 7919 return HasTypenameKeyword || !IsInstantiation; 7920 7921 return !HasTypenameKeyword; 7922 } 7923 7924 private: 7925 bool HasTypenameKeyword; 7926 bool IsInstantiation; 7927 NestedNameSpecifier *OldNNS; 7928 CXXRecordDecl *RequireMemberOf; 7929 }; 7930 } // end anonymous namespace 7931 7932 /// Builds a using declaration. 7933 /// 7934 /// \param IsInstantiation - Whether this call arises from an 7935 /// instantiation of an unresolved using declaration. We treat 7936 /// the lookup differently for these declarations. 7937 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7938 SourceLocation UsingLoc, 7939 CXXScopeSpec &SS, 7940 DeclarationNameInfo NameInfo, 7941 AttributeList *AttrList, 7942 bool IsInstantiation, 7943 bool HasTypenameKeyword, 7944 SourceLocation TypenameLoc) { 7945 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7946 SourceLocation IdentLoc = NameInfo.getLoc(); 7947 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7948 7949 // FIXME: We ignore attributes for now. 7950 7951 if (SS.isEmpty()) { 7952 Diag(IdentLoc, diag::err_using_requires_qualname); 7953 return nullptr; 7954 } 7955 7956 // Do the redeclaration lookup in the current scope. 7957 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7958 ForRedeclaration); 7959 Previous.setHideTags(false); 7960 if (S) { 7961 LookupName(Previous, S); 7962 7963 // It is really dumb that we have to do this. 7964 LookupResult::Filter F = Previous.makeFilter(); 7965 while (F.hasNext()) { 7966 NamedDecl *D = F.next(); 7967 if (!isDeclInScope(D, CurContext, S)) 7968 F.erase(); 7969 // If we found a local extern declaration that's not ordinarily visible, 7970 // and this declaration is being added to a non-block scope, ignore it. 7971 // We're only checking for scope conflicts here, not also for violations 7972 // of the linkage rules. 7973 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7974 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7975 F.erase(); 7976 } 7977 F.done(); 7978 } else { 7979 assert(IsInstantiation && "no scope in non-instantiation"); 7980 assert(CurContext->isRecord() && "scope not record in instantiation"); 7981 LookupQualifiedName(Previous, CurContext); 7982 } 7983 7984 // Check for invalid redeclarations. 7985 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7986 SS, IdentLoc, Previous)) 7987 return nullptr; 7988 7989 // Check for bad qualifiers. 7990 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7991 return nullptr; 7992 7993 DeclContext *LookupContext = computeDeclContext(SS); 7994 NamedDecl *D; 7995 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7996 if (!LookupContext) { 7997 if (HasTypenameKeyword) { 7998 // FIXME: not all declaration name kinds are legal here 7999 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 8000 UsingLoc, TypenameLoc, 8001 QualifierLoc, 8002 IdentLoc, NameInfo.getName()); 8003 } else { 8004 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 8005 QualifierLoc, NameInfo); 8006 } 8007 D->setAccess(AS); 8008 CurContext->addDecl(D); 8009 return D; 8010 } 8011 8012 auto Build = [&](bool Invalid) { 8013 UsingDecl *UD = 8014 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 8015 HasTypenameKeyword); 8016 UD->setAccess(AS); 8017 CurContext->addDecl(UD); 8018 UD->setInvalidDecl(Invalid); 8019 return UD; 8020 }; 8021 auto BuildInvalid = [&]{ return Build(true); }; 8022 auto BuildValid = [&]{ return Build(false); }; 8023 8024 if (RequireCompleteDeclContext(SS, LookupContext)) 8025 return BuildInvalid(); 8026 8027 // The normal rules do not apply to inheriting constructor declarations. 8028 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 8029 UsingDecl *UD = BuildValid(); 8030 CheckInheritingConstructorUsingDecl(UD); 8031 return UD; 8032 } 8033 8034 // Otherwise, look up the target name. 8035 8036 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8037 8038 // Unlike most lookups, we don't always want to hide tag 8039 // declarations: tag names are visible through the using declaration 8040 // even if hidden by ordinary names, *except* in a dependent context 8041 // where it's important for the sanity of two-phase lookup. 8042 if (!IsInstantiation) 8043 R.setHideTags(false); 8044 8045 // For the purposes of this lookup, we have a base object type 8046 // equal to that of the current context. 8047 if (CurContext->isRecord()) { 8048 R.setBaseObjectType( 8049 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 8050 } 8051 8052 LookupQualifiedName(R, LookupContext); 8053 8054 // Try to correct typos if possible. 8055 if (R.empty()) { 8056 if (TypoCorrection Corrected = CorrectTypo( 8057 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 8058 llvm::make_unique<UsingValidatorCCC>( 8059 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8060 dyn_cast<CXXRecordDecl>(CurContext)), 8061 CTK_ErrorRecovery)) { 8062 // We reject any correction for which ND would be NULL. 8063 NamedDecl *ND = Corrected.getCorrectionDecl(); 8064 8065 // We reject candidates where DroppedSpecifier == true, hence the 8066 // literal '0' below. 8067 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8068 << NameInfo.getName() << LookupContext << 0 8069 << SS.getRange()); 8070 8071 // If we corrected to an inheriting constructor, handle it as one. 8072 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8073 if (RD && RD->isInjectedClassName()) { 8074 // Fix up the information we'll use to build the using declaration. 8075 if (Corrected.WillReplaceSpecifier()) { 8076 NestedNameSpecifierLocBuilder Builder; 8077 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8078 QualifierLoc.getSourceRange()); 8079 QualifierLoc = Builder.getWithLocInContext(Context); 8080 } 8081 8082 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8083 Context.getCanonicalType(Context.getRecordType(RD)))); 8084 NameInfo.setNamedTypeInfo(nullptr); 8085 8086 // Build it and process it as an inheriting constructor. 8087 UsingDecl *UD = BuildValid(); 8088 CheckInheritingConstructorUsingDecl(UD); 8089 return UD; 8090 } 8091 8092 // FIXME: Pick up all the declarations if we found an overloaded function. 8093 R.setLookupName(Corrected.getCorrection()); 8094 R.addDecl(ND); 8095 } else { 8096 Diag(IdentLoc, diag::err_no_member) 8097 << NameInfo.getName() << LookupContext << SS.getRange(); 8098 return BuildInvalid(); 8099 } 8100 } 8101 8102 if (R.isAmbiguous()) 8103 return BuildInvalid(); 8104 8105 if (HasTypenameKeyword) { 8106 // If we asked for a typename and got a non-type decl, error out. 8107 if (!R.getAsSingle<TypeDecl>()) { 8108 Diag(IdentLoc, diag::err_using_typename_non_type); 8109 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8110 Diag((*I)->getUnderlyingDecl()->getLocation(), 8111 diag::note_using_decl_target); 8112 return BuildInvalid(); 8113 } 8114 } else { 8115 // If we asked for a non-typename and we got a type, error out, 8116 // but only if this is an instantiation of an unresolved using 8117 // decl. Otherwise just silently find the type name. 8118 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8119 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8120 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8121 return BuildInvalid(); 8122 } 8123 } 8124 8125 // C++0x N2914 [namespace.udecl]p6: 8126 // A using-declaration shall not name a namespace. 8127 if (R.getAsSingle<NamespaceDecl>()) { 8128 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8129 << SS.getRange(); 8130 return BuildInvalid(); 8131 } 8132 8133 UsingDecl *UD = BuildValid(); 8134 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8135 UsingShadowDecl *PrevDecl = nullptr; 8136 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8137 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8138 } 8139 8140 return UD; 8141 } 8142 8143 /// Additional checks for a using declaration referring to a constructor name. 8144 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8145 assert(!UD->hasTypename() && "expecting a constructor name"); 8146 8147 const Type *SourceType = UD->getQualifier()->getAsType(); 8148 assert(SourceType && 8149 "Using decl naming constructor doesn't have type in scope spec."); 8150 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8151 8152 // Check whether the named type is a direct base class. 8153 bool AnyDependentBases = false; 8154 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8155 AnyDependentBases); 8156 if (!Base && !AnyDependentBases) { 8157 Diag(UD->getUsingLoc(), 8158 diag::err_using_decl_constructor_not_in_direct_base) 8159 << UD->getNameInfo().getSourceRange() 8160 << QualType(SourceType, 0) << TargetClass; 8161 UD->setInvalidDecl(); 8162 return true; 8163 } 8164 8165 if (Base) 8166 Base->setInheritConstructors(); 8167 8168 return false; 8169 } 8170 8171 /// Checks that the given using declaration is not an invalid 8172 /// redeclaration. Note that this is checking only for the using decl 8173 /// itself, not for any ill-formedness among the UsingShadowDecls. 8174 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8175 bool HasTypenameKeyword, 8176 const CXXScopeSpec &SS, 8177 SourceLocation NameLoc, 8178 const LookupResult &Prev) { 8179 // C++03 [namespace.udecl]p8: 8180 // C++0x [namespace.udecl]p10: 8181 // A using-declaration is a declaration and can therefore be used 8182 // repeatedly where (and only where) multiple declarations are 8183 // allowed. 8184 // 8185 // That's in non-member contexts. 8186 if (!CurContext->getRedeclContext()->isRecord()) 8187 return false; 8188 8189 NestedNameSpecifier *Qual = SS.getScopeRep(); 8190 8191 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8192 NamedDecl *D = *I; 8193 8194 bool DTypename; 8195 NestedNameSpecifier *DQual; 8196 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8197 DTypename = UD->hasTypename(); 8198 DQual = UD->getQualifier(); 8199 } else if (UnresolvedUsingValueDecl *UD 8200 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8201 DTypename = false; 8202 DQual = UD->getQualifier(); 8203 } else if (UnresolvedUsingTypenameDecl *UD 8204 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8205 DTypename = true; 8206 DQual = UD->getQualifier(); 8207 } else continue; 8208 8209 // using decls differ if one says 'typename' and the other doesn't. 8210 // FIXME: non-dependent using decls? 8211 if (HasTypenameKeyword != DTypename) continue; 8212 8213 // using decls differ if they name different scopes (but note that 8214 // template instantiation can cause this check to trigger when it 8215 // didn't before instantiation). 8216 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8217 Context.getCanonicalNestedNameSpecifier(DQual)) 8218 continue; 8219 8220 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8221 Diag(D->getLocation(), diag::note_using_decl) << 1; 8222 return true; 8223 } 8224 8225 return false; 8226 } 8227 8228 8229 /// Checks that the given nested-name qualifier used in a using decl 8230 /// in the current context is appropriately related to the current 8231 /// scope. If an error is found, diagnoses it and returns true. 8232 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8233 const CXXScopeSpec &SS, 8234 const DeclarationNameInfo &NameInfo, 8235 SourceLocation NameLoc) { 8236 DeclContext *NamedContext = computeDeclContext(SS); 8237 8238 if (!CurContext->isRecord()) { 8239 // C++03 [namespace.udecl]p3: 8240 // C++0x [namespace.udecl]p8: 8241 // A using-declaration for a class member shall be a member-declaration. 8242 8243 // If we weren't able to compute a valid scope, it must be a 8244 // dependent class scope. 8245 if (!NamedContext || NamedContext->isRecord()) { 8246 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext); 8247 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8248 RD = nullptr; 8249 8250 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8251 << SS.getRange(); 8252 8253 // If we have a complete, non-dependent source type, try to suggest a 8254 // way to get the same effect. 8255 if (!RD) 8256 return true; 8257 8258 // Find what this using-declaration was referring to. 8259 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8260 R.setHideTags(false); 8261 R.suppressDiagnostics(); 8262 LookupQualifiedName(R, RD); 8263 8264 if (R.getAsSingle<TypeDecl>()) { 8265 if (getLangOpts().CPlusPlus11) { 8266 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8267 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8268 << 0 // alias declaration 8269 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8270 NameInfo.getName().getAsString() + 8271 " = "); 8272 } else { 8273 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8274 SourceLocation InsertLoc = 8275 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8276 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8277 << 1 // typedef declaration 8278 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8279 << FixItHint::CreateInsertion( 8280 InsertLoc, " " + NameInfo.getName().getAsString()); 8281 } 8282 } else if (R.getAsSingle<VarDecl>()) { 8283 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8284 // repeating the type of the static data member here. 8285 FixItHint FixIt; 8286 if (getLangOpts().CPlusPlus11) { 8287 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8288 FixIt = FixItHint::CreateReplacement( 8289 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8290 } 8291 8292 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8293 << 2 // reference declaration 8294 << FixIt; 8295 } 8296 return true; 8297 } 8298 8299 // Otherwise, everything is known to be fine. 8300 return false; 8301 } 8302 8303 // The current scope is a record. 8304 8305 // If the named context is dependent, we can't decide much. 8306 if (!NamedContext) { 8307 // FIXME: in C++0x, we can diagnose if we can prove that the 8308 // nested-name-specifier does not refer to a base class, which is 8309 // still possible in some cases. 8310 8311 // Otherwise we have to conservatively report that things might be 8312 // okay. 8313 return false; 8314 } 8315 8316 if (!NamedContext->isRecord()) { 8317 // Ideally this would point at the last name in the specifier, 8318 // but we don't have that level of source info. 8319 Diag(SS.getRange().getBegin(), 8320 diag::err_using_decl_nested_name_specifier_is_not_class) 8321 << SS.getScopeRep() << SS.getRange(); 8322 return true; 8323 } 8324 8325 if (!NamedContext->isDependentContext() && 8326 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8327 return true; 8328 8329 if (getLangOpts().CPlusPlus11) { 8330 // C++0x [namespace.udecl]p3: 8331 // In a using-declaration used as a member-declaration, the 8332 // nested-name-specifier shall name a base class of the class 8333 // being defined. 8334 8335 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8336 cast<CXXRecordDecl>(NamedContext))) { 8337 if (CurContext == NamedContext) { 8338 Diag(NameLoc, 8339 diag::err_using_decl_nested_name_specifier_is_current_class) 8340 << SS.getRange(); 8341 return true; 8342 } 8343 8344 Diag(SS.getRange().getBegin(), 8345 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8346 << SS.getScopeRep() 8347 << cast<CXXRecordDecl>(CurContext) 8348 << SS.getRange(); 8349 return true; 8350 } 8351 8352 return false; 8353 } 8354 8355 // C++03 [namespace.udecl]p4: 8356 // A using-declaration used as a member-declaration shall refer 8357 // to a member of a base class of the class being defined [etc.]. 8358 8359 // Salient point: SS doesn't have to name a base class as long as 8360 // lookup only finds members from base classes. Therefore we can 8361 // diagnose here only if we can prove that that can't happen, 8362 // i.e. if the class hierarchies provably don't intersect. 8363 8364 // TODO: it would be nice if "definitely valid" results were cached 8365 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8366 // need to be repeated. 8367 8368 struct UserData { 8369 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8370 8371 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8372 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8373 Data->Bases.insert(Base); 8374 return true; 8375 } 8376 8377 bool hasDependentBases(const CXXRecordDecl *Class) { 8378 return !Class->forallBases(collect, this); 8379 } 8380 8381 /// Returns true if the base is dependent or is one of the 8382 /// accumulated base classes. 8383 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8384 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8385 return !Data->Bases.count(Base); 8386 } 8387 8388 bool mightShareBases(const CXXRecordDecl *Class) { 8389 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8390 } 8391 }; 8392 8393 UserData Data; 8394 8395 // Returns false if we find a dependent base. 8396 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8397 return false; 8398 8399 // Returns false if the class has a dependent base or if it or one 8400 // of its bases is present in the base set of the current context. 8401 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8402 return false; 8403 8404 Diag(SS.getRange().getBegin(), 8405 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8406 << SS.getScopeRep() 8407 << cast<CXXRecordDecl>(CurContext) 8408 << SS.getRange(); 8409 8410 return true; 8411 } 8412 8413 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8414 AccessSpecifier AS, 8415 MultiTemplateParamsArg TemplateParamLists, 8416 SourceLocation UsingLoc, 8417 UnqualifiedId &Name, 8418 AttributeList *AttrList, 8419 TypeResult Type) { 8420 // Skip up to the relevant declaration scope. 8421 while (S->getFlags() & Scope::TemplateParamScope) 8422 S = S->getParent(); 8423 assert((S->getFlags() & Scope::DeclScope) && 8424 "got alias-declaration outside of declaration scope"); 8425 8426 if (Type.isInvalid()) 8427 return nullptr; 8428 8429 bool Invalid = false; 8430 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8431 TypeSourceInfo *TInfo = nullptr; 8432 GetTypeFromParser(Type.get(), &TInfo); 8433 8434 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8435 return nullptr; 8436 8437 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8438 UPPC_DeclarationType)) { 8439 Invalid = true; 8440 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8441 TInfo->getTypeLoc().getBeginLoc()); 8442 } 8443 8444 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8445 LookupName(Previous, S); 8446 8447 // Warn about shadowing the name of a template parameter. 8448 if (Previous.isSingleResult() && 8449 Previous.getFoundDecl()->isTemplateParameter()) { 8450 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8451 Previous.clear(); 8452 } 8453 8454 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8455 "name in alias declaration must be an identifier"); 8456 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8457 Name.StartLocation, 8458 Name.Identifier, TInfo); 8459 8460 NewTD->setAccess(AS); 8461 8462 if (Invalid) 8463 NewTD->setInvalidDecl(); 8464 8465 ProcessDeclAttributeList(S, NewTD, AttrList); 8466 8467 CheckTypedefForVariablyModifiedType(S, NewTD); 8468 Invalid |= NewTD->isInvalidDecl(); 8469 8470 bool Redeclaration = false; 8471 8472 NamedDecl *NewND; 8473 if (TemplateParamLists.size()) { 8474 TypeAliasTemplateDecl *OldDecl = nullptr; 8475 TemplateParameterList *OldTemplateParams = nullptr; 8476 8477 if (TemplateParamLists.size() != 1) { 8478 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8479 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8480 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8481 } 8482 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8483 8484 // Only consider previous declarations in the same scope. 8485 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8486 /*ExplicitInstantiationOrSpecialization*/false); 8487 if (!Previous.empty()) { 8488 Redeclaration = true; 8489 8490 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8491 if (!OldDecl && !Invalid) { 8492 Diag(UsingLoc, diag::err_redefinition_different_kind) 8493 << Name.Identifier; 8494 8495 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8496 if (OldD->getLocation().isValid()) 8497 Diag(OldD->getLocation(), diag::note_previous_definition); 8498 8499 Invalid = true; 8500 } 8501 8502 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8503 if (TemplateParameterListsAreEqual(TemplateParams, 8504 OldDecl->getTemplateParameters(), 8505 /*Complain=*/true, 8506 TPL_TemplateMatch)) 8507 OldTemplateParams = OldDecl->getTemplateParameters(); 8508 else 8509 Invalid = true; 8510 8511 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8512 if (!Invalid && 8513 !Context.hasSameType(OldTD->getUnderlyingType(), 8514 NewTD->getUnderlyingType())) { 8515 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8516 // but we can't reasonably accept it. 8517 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8518 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8519 if (OldTD->getLocation().isValid()) 8520 Diag(OldTD->getLocation(), diag::note_previous_definition); 8521 Invalid = true; 8522 } 8523 } 8524 } 8525 8526 // Merge any previous default template arguments into our parameters, 8527 // and check the parameter list. 8528 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8529 TPC_TypeAliasTemplate)) 8530 return nullptr; 8531 8532 TypeAliasTemplateDecl *NewDecl = 8533 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8534 Name.Identifier, TemplateParams, 8535 NewTD); 8536 NewTD->setDescribedAliasTemplate(NewDecl); 8537 8538 NewDecl->setAccess(AS); 8539 8540 if (Invalid) 8541 NewDecl->setInvalidDecl(); 8542 else if (OldDecl) 8543 NewDecl->setPreviousDecl(OldDecl); 8544 8545 NewND = NewDecl; 8546 } else { 8547 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8548 NewND = NewTD; 8549 } 8550 8551 if (!Redeclaration) 8552 PushOnScopeChains(NewND, S); 8553 8554 ActOnDocumentableDecl(NewND); 8555 return NewND; 8556 } 8557 8558 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8559 SourceLocation AliasLoc, 8560 IdentifierInfo *Alias, CXXScopeSpec &SS, 8561 SourceLocation IdentLoc, 8562 IdentifierInfo *Ident) { 8563 8564 // Lookup the namespace name. 8565 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8566 LookupParsedName(R, S, &SS); 8567 8568 if (R.isAmbiguous()) 8569 return nullptr; 8570 8571 if (R.empty()) { 8572 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8573 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8574 return nullptr; 8575 } 8576 } 8577 assert(!R.isAmbiguous() && !R.empty()); 8578 8579 // Check if we have a previous declaration with the same name. 8580 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8581 ForRedeclaration); 8582 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8583 PrevDecl = nullptr; 8584 8585 NamedDecl *ND = R.getFoundDecl(); 8586 8587 if (PrevDecl) { 8588 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8589 // We already have an alias with the same name that points to the same 8590 // namespace; check that it matches. 8591 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8592 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8593 << Alias; 8594 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8595 << AD->getNamespace(); 8596 return nullptr; 8597 } 8598 } else { 8599 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8600 ? diag::err_redefinition 8601 : diag::err_redefinition_different_kind; 8602 Diag(AliasLoc, DiagID) << Alias; 8603 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8604 return nullptr; 8605 } 8606 } 8607 8608 // The use of a nested name specifier may trigger deprecation warnings. 8609 DiagnoseUseOfDecl(ND, IdentLoc); 8610 8611 NamespaceAliasDecl *AliasDecl = 8612 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8613 Alias, SS.getWithLocInContext(Context), 8614 IdentLoc, ND); 8615 if (PrevDecl) 8616 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8617 8618 PushOnScopeChains(AliasDecl, S); 8619 return AliasDecl; 8620 } 8621 8622 Sema::ImplicitExceptionSpecification 8623 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8624 CXXMethodDecl *MD) { 8625 CXXRecordDecl *ClassDecl = MD->getParent(); 8626 8627 // C++ [except.spec]p14: 8628 // An implicitly declared special member function (Clause 12) shall have an 8629 // exception-specification. [...] 8630 ImplicitExceptionSpecification ExceptSpec(*this); 8631 if (ClassDecl->isInvalidDecl()) 8632 return ExceptSpec; 8633 8634 // Direct base-class constructors. 8635 for (const auto &B : ClassDecl->bases()) { 8636 if (B.isVirtual()) // Handled below. 8637 continue; 8638 8639 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8640 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8641 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8642 // If this is a deleted function, add it anyway. This might be conformant 8643 // with the standard. This might not. I'm not sure. It might not matter. 8644 if (Constructor) 8645 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8646 } 8647 } 8648 8649 // Virtual base-class constructors. 8650 for (const auto &B : ClassDecl->vbases()) { 8651 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8652 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8653 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8654 // If this is a deleted function, add it anyway. This might be conformant 8655 // with the standard. This might not. I'm not sure. It might not matter. 8656 if (Constructor) 8657 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8658 } 8659 } 8660 8661 // Field constructors. 8662 for (const auto *F : ClassDecl->fields()) { 8663 if (F->hasInClassInitializer()) { 8664 if (Expr *E = F->getInClassInitializer()) 8665 ExceptSpec.CalledExpr(E); 8666 } else if (const RecordType *RecordTy 8667 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8668 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8669 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8670 // If this is a deleted function, add it anyway. This might be conformant 8671 // with the standard. This might not. I'm not sure. It might not matter. 8672 // In particular, the problem is that this function never gets called. It 8673 // might just be ill-formed because this function attempts to refer to 8674 // a deleted function here. 8675 if (Constructor) 8676 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8677 } 8678 } 8679 8680 return ExceptSpec; 8681 } 8682 8683 Sema::ImplicitExceptionSpecification 8684 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8685 CXXRecordDecl *ClassDecl = CD->getParent(); 8686 8687 // C++ [except.spec]p14: 8688 // An inheriting constructor [...] shall have an exception-specification. [...] 8689 ImplicitExceptionSpecification ExceptSpec(*this); 8690 if (ClassDecl->isInvalidDecl()) 8691 return ExceptSpec; 8692 8693 // Inherited constructor. 8694 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8695 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8696 // FIXME: Copying or moving the parameters could add extra exceptions to the 8697 // set, as could the default arguments for the inherited constructor. This 8698 // will be addressed when we implement the resolution of core issue 1351. 8699 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8700 8701 // Direct base-class constructors. 8702 for (const auto &B : ClassDecl->bases()) { 8703 if (B.isVirtual()) // Handled below. 8704 continue; 8705 8706 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8707 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8708 if (BaseClassDecl == InheritedDecl) 8709 continue; 8710 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8711 if (Constructor) 8712 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8713 } 8714 } 8715 8716 // Virtual base-class constructors. 8717 for (const auto &B : ClassDecl->vbases()) { 8718 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8719 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8720 if (BaseClassDecl == InheritedDecl) 8721 continue; 8722 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8723 if (Constructor) 8724 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8725 } 8726 } 8727 8728 // Field constructors. 8729 for (const auto *F : ClassDecl->fields()) { 8730 if (F->hasInClassInitializer()) { 8731 if (Expr *E = F->getInClassInitializer()) 8732 ExceptSpec.CalledExpr(E); 8733 } else if (const RecordType *RecordTy 8734 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8735 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8736 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8737 if (Constructor) 8738 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8739 } 8740 } 8741 8742 return ExceptSpec; 8743 } 8744 8745 namespace { 8746 /// RAII object to register a special member as being currently declared. 8747 struct DeclaringSpecialMember { 8748 Sema &S; 8749 Sema::SpecialMemberDecl D; 8750 bool WasAlreadyBeingDeclared; 8751 8752 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8753 : S(S), D(RD, CSM) { 8754 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8755 if (WasAlreadyBeingDeclared) 8756 // This almost never happens, but if it does, ensure that our cache 8757 // doesn't contain a stale result. 8758 S.SpecialMemberCache.clear(); 8759 8760 // FIXME: Register a note to be produced if we encounter an error while 8761 // declaring the special member. 8762 } 8763 ~DeclaringSpecialMember() { 8764 if (!WasAlreadyBeingDeclared) 8765 S.SpecialMembersBeingDeclared.erase(D); 8766 } 8767 8768 /// \brief Are we already trying to declare this special member? 8769 bool isAlreadyBeingDeclared() const { 8770 return WasAlreadyBeingDeclared; 8771 } 8772 }; 8773 } 8774 8775 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8776 CXXRecordDecl *ClassDecl) { 8777 // C++ [class.ctor]p5: 8778 // A default constructor for a class X is a constructor of class X 8779 // that can be called without an argument. If there is no 8780 // user-declared constructor for class X, a default constructor is 8781 // implicitly declared. An implicitly-declared default constructor 8782 // is an inline public member of its class. 8783 assert(ClassDecl->needsImplicitDefaultConstructor() && 8784 "Should not build implicit default constructor!"); 8785 8786 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8787 if (DSM.isAlreadyBeingDeclared()) 8788 return nullptr; 8789 8790 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8791 CXXDefaultConstructor, 8792 false); 8793 8794 // Create the actual constructor declaration. 8795 CanQualType ClassType 8796 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8797 SourceLocation ClassLoc = ClassDecl->getLocation(); 8798 DeclarationName Name 8799 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8800 DeclarationNameInfo NameInfo(Name, ClassLoc); 8801 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8802 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8803 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8804 /*isImplicitlyDeclared=*/true, Constexpr); 8805 DefaultCon->setAccess(AS_public); 8806 DefaultCon->setDefaulted(); 8807 8808 if (getLangOpts().CUDA) { 8809 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8810 DefaultCon, 8811 /* ConstRHS */ false, 8812 /* Diagnose */ false); 8813 } 8814 8815 // Build an exception specification pointing back at this constructor. 8816 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8817 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8818 8819 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8820 // constructors is easy to compute. 8821 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8822 8823 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8824 SetDeclDeleted(DefaultCon, ClassLoc); 8825 8826 // Note that we have declared this constructor. 8827 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8828 8829 if (Scope *S = getScopeForContext(ClassDecl)) 8830 PushOnScopeChains(DefaultCon, S, false); 8831 ClassDecl->addDecl(DefaultCon); 8832 8833 return DefaultCon; 8834 } 8835 8836 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8837 CXXConstructorDecl *Constructor) { 8838 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8839 !Constructor->doesThisDeclarationHaveABody() && 8840 !Constructor->isDeleted()) && 8841 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8842 8843 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8844 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8845 8846 SynthesizedFunctionScope Scope(*this, Constructor); 8847 DiagnosticErrorTrap Trap(Diags); 8848 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8849 Trap.hasErrorOccurred()) { 8850 Diag(CurrentLocation, diag::note_member_synthesized_at) 8851 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8852 Constructor->setInvalidDecl(); 8853 return; 8854 } 8855 8856 // The exception specification is needed because we are defining the 8857 // function. 8858 ResolveExceptionSpec(CurrentLocation, 8859 Constructor->getType()->castAs<FunctionProtoType>()); 8860 8861 SourceLocation Loc = Constructor->getLocEnd().isValid() 8862 ? Constructor->getLocEnd() 8863 : Constructor->getLocation(); 8864 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8865 8866 Constructor->markUsed(Context); 8867 MarkVTableUsed(CurrentLocation, ClassDecl); 8868 8869 if (ASTMutationListener *L = getASTMutationListener()) { 8870 L->CompletedImplicitDefinition(Constructor); 8871 } 8872 8873 DiagnoseUninitializedFields(*this, Constructor); 8874 } 8875 8876 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8877 // Perform any delayed checks on exception specifications. 8878 CheckDelayedMemberExceptionSpecs(); 8879 } 8880 8881 namespace { 8882 /// Information on inheriting constructors to declare. 8883 class InheritingConstructorInfo { 8884 public: 8885 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8886 : SemaRef(SemaRef), Derived(Derived) { 8887 // Mark the constructors that we already have in the derived class. 8888 // 8889 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8890 // unless there is a user-declared constructor with the same signature in 8891 // the class where the using-declaration appears. 8892 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8893 } 8894 8895 void inheritAll(CXXRecordDecl *RD) { 8896 visitAll(RD, &InheritingConstructorInfo::inherit); 8897 } 8898 8899 private: 8900 /// Information about an inheriting constructor. 8901 struct InheritingConstructor { 8902 InheritingConstructor() 8903 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8904 8905 /// If \c true, a constructor with this signature is already declared 8906 /// in the derived class. 8907 bool DeclaredInDerived; 8908 8909 /// The constructor which is inherited. 8910 const CXXConstructorDecl *BaseCtor; 8911 8912 /// The derived constructor we declared. 8913 CXXConstructorDecl *DerivedCtor; 8914 }; 8915 8916 /// Inheriting constructors with a given canonical type. There can be at 8917 /// most one such non-template constructor, and any number of templated 8918 /// constructors. 8919 struct InheritingConstructorsForType { 8920 InheritingConstructor NonTemplate; 8921 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8922 Templates; 8923 8924 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8925 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8926 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8927 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8928 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8929 false, S.TPL_TemplateMatch)) 8930 return Templates[I].second; 8931 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8932 return Templates.back().second; 8933 } 8934 8935 return NonTemplate; 8936 } 8937 }; 8938 8939 /// Get or create the inheriting constructor record for a constructor. 8940 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8941 QualType CtorType) { 8942 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8943 .getEntry(SemaRef, Ctor); 8944 } 8945 8946 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8947 8948 /// Process all constructors for a class. 8949 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8950 for (const auto *Ctor : RD->ctors()) 8951 (this->*Callback)(Ctor); 8952 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8953 I(RD->decls_begin()), E(RD->decls_end()); 8954 I != E; ++I) { 8955 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8956 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8957 (this->*Callback)(CD); 8958 } 8959 } 8960 8961 /// Note that a constructor (or constructor template) was declared in Derived. 8962 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8963 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8964 } 8965 8966 /// Inherit a single constructor. 8967 void inherit(const CXXConstructorDecl *Ctor) { 8968 const FunctionProtoType *CtorType = 8969 Ctor->getType()->castAs<FunctionProtoType>(); 8970 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 8971 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8972 8973 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8974 8975 // Core issue (no number yet): the ellipsis is always discarded. 8976 if (EPI.Variadic) { 8977 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8978 SemaRef.Diag(Ctor->getLocation(), 8979 diag::note_using_decl_constructor_ellipsis); 8980 EPI.Variadic = false; 8981 } 8982 8983 // Declare a constructor for each number of parameters. 8984 // 8985 // C++11 [class.inhctor]p1: 8986 // The candidate set of inherited constructors from the class X named in 8987 // the using-declaration consists of [... modulo defects ...] for each 8988 // constructor or constructor template of X, the set of constructors or 8989 // constructor templates that results from omitting any ellipsis parameter 8990 // specification and successively omitting parameters with a default 8991 // argument from the end of the parameter-type-list 8992 unsigned MinParams = minParamsToInherit(Ctor); 8993 unsigned Params = Ctor->getNumParams(); 8994 if (Params >= MinParams) { 8995 do 8996 declareCtor(UsingLoc, Ctor, 8997 SemaRef.Context.getFunctionType( 8998 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8999 while (Params > MinParams && 9000 Ctor->getParamDecl(--Params)->hasDefaultArg()); 9001 } 9002 } 9003 9004 /// Find the using-declaration which specified that we should inherit the 9005 /// constructors of \p Base. 9006 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 9007 // No fancy lookup required; just look for the base constructor name 9008 // directly within the derived class. 9009 ASTContext &Context = SemaRef.Context; 9010 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9011 Context.getCanonicalType(Context.getRecordType(Base))); 9012 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 9013 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 9014 } 9015 9016 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 9017 // C++11 [class.inhctor]p3: 9018 // [F]or each constructor template in the candidate set of inherited 9019 // constructors, a constructor template is implicitly declared 9020 if (Ctor->getDescribedFunctionTemplate()) 9021 return 0; 9022 9023 // For each non-template constructor in the candidate set of inherited 9024 // constructors other than a constructor having no parameters or a 9025 // copy/move constructor having a single parameter, a constructor is 9026 // implicitly declared [...] 9027 if (Ctor->getNumParams() == 0) 9028 return 1; 9029 if (Ctor->isCopyOrMoveConstructor()) 9030 return 2; 9031 9032 // Per discussion on core reflector, never inherit a constructor which 9033 // would become a default, copy, or move constructor of Derived either. 9034 const ParmVarDecl *PD = Ctor->getParamDecl(0); 9035 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 9036 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 9037 } 9038 9039 /// Declare a single inheriting constructor, inheriting the specified 9040 /// constructor, with the given type. 9041 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 9042 QualType DerivedType) { 9043 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 9044 9045 // C++11 [class.inhctor]p3: 9046 // ... a constructor is implicitly declared with the same constructor 9047 // characteristics unless there is a user-declared constructor with 9048 // the same signature in the class where the using-declaration appears 9049 if (Entry.DeclaredInDerived) 9050 return; 9051 9052 // C++11 [class.inhctor]p7: 9053 // If two using-declarations declare inheriting constructors with the 9054 // same signature, the program is ill-formed 9055 if (Entry.DerivedCtor) { 9056 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 9057 // Only diagnose this once per constructor. 9058 if (Entry.DerivedCtor->isInvalidDecl()) 9059 return; 9060 Entry.DerivedCtor->setInvalidDecl(); 9061 9062 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9063 SemaRef.Diag(BaseCtor->getLocation(), 9064 diag::note_using_decl_constructor_conflict_current_ctor); 9065 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9066 diag::note_using_decl_constructor_conflict_previous_ctor); 9067 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9068 diag::note_using_decl_constructor_conflict_previous_using); 9069 } else { 9070 // Core issue (no number): if the same inheriting constructor is 9071 // produced by multiple base class constructors from the same base 9072 // class, the inheriting constructor is defined as deleted. 9073 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9074 } 9075 9076 return; 9077 } 9078 9079 ASTContext &Context = SemaRef.Context; 9080 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9081 Context.getCanonicalType(Context.getRecordType(Derived))); 9082 DeclarationNameInfo NameInfo(Name, UsingLoc); 9083 9084 TemplateParameterList *TemplateParams = nullptr; 9085 if (const FunctionTemplateDecl *FTD = 9086 BaseCtor->getDescribedFunctionTemplate()) { 9087 TemplateParams = FTD->getTemplateParameters(); 9088 // We're reusing template parameters from a different DeclContext. This 9089 // is questionable at best, but works out because the template depth in 9090 // both places is guaranteed to be 0. 9091 // FIXME: Rebuild the template parameters in the new context, and 9092 // transform the function type to refer to them. 9093 } 9094 9095 // Build type source info pointing at the using-declaration. This is 9096 // required by template instantiation. 9097 TypeSourceInfo *TInfo = 9098 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9099 FunctionProtoTypeLoc ProtoLoc = 9100 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9101 9102 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9103 Context, Derived, UsingLoc, NameInfo, DerivedType, 9104 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9105 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9106 9107 // Build an unevaluated exception specification for this constructor. 9108 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9109 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9110 EPI.ExceptionSpec.Type = EST_Unevaluated; 9111 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9112 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9113 FPT->getParamTypes(), EPI)); 9114 9115 // Build the parameter declarations. 9116 SmallVector<ParmVarDecl *, 16> ParamDecls; 9117 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9118 TypeSourceInfo *TInfo = 9119 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9120 ParmVarDecl *PD = ParmVarDecl::Create( 9121 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9122 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9123 PD->setScopeInfo(0, I); 9124 PD->setImplicit(); 9125 ParamDecls.push_back(PD); 9126 ProtoLoc.setParam(I, PD); 9127 } 9128 9129 // Set up the new constructor. 9130 DerivedCtor->setAccess(BaseCtor->getAccess()); 9131 DerivedCtor->setParams(ParamDecls); 9132 DerivedCtor->setInheritedConstructor(BaseCtor); 9133 if (BaseCtor->isDeleted()) 9134 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9135 9136 // If this is a constructor template, build the template declaration. 9137 if (TemplateParams) { 9138 FunctionTemplateDecl *DerivedTemplate = 9139 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9140 TemplateParams, DerivedCtor); 9141 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9142 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9143 Derived->addDecl(DerivedTemplate); 9144 } else { 9145 Derived->addDecl(DerivedCtor); 9146 } 9147 9148 Entry.BaseCtor = BaseCtor; 9149 Entry.DerivedCtor = DerivedCtor; 9150 } 9151 9152 Sema &SemaRef; 9153 CXXRecordDecl *Derived; 9154 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9155 MapType Map; 9156 }; 9157 } 9158 9159 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9160 // Defer declaring the inheriting constructors until the class is 9161 // instantiated. 9162 if (ClassDecl->isDependentContext()) 9163 return; 9164 9165 // Find base classes from which we might inherit constructors. 9166 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9167 for (const auto &BaseIt : ClassDecl->bases()) 9168 if (BaseIt.getInheritConstructors()) 9169 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9170 9171 // Go no further if we're not inheriting any constructors. 9172 if (InheritedBases.empty()) 9173 return; 9174 9175 // Declare the inherited constructors. 9176 InheritingConstructorInfo ICI(*this, ClassDecl); 9177 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9178 ICI.inheritAll(InheritedBases[I]); 9179 } 9180 9181 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9182 CXXConstructorDecl *Constructor) { 9183 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9184 assert(Constructor->getInheritedConstructor() && 9185 !Constructor->doesThisDeclarationHaveABody() && 9186 !Constructor->isDeleted()); 9187 9188 SynthesizedFunctionScope Scope(*this, Constructor); 9189 DiagnosticErrorTrap Trap(Diags); 9190 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9191 Trap.hasErrorOccurred()) { 9192 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9193 << Context.getTagDeclType(ClassDecl); 9194 Constructor->setInvalidDecl(); 9195 return; 9196 } 9197 9198 SourceLocation Loc = Constructor->getLocation(); 9199 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9200 9201 Constructor->markUsed(Context); 9202 MarkVTableUsed(CurrentLocation, ClassDecl); 9203 9204 if (ASTMutationListener *L = getASTMutationListener()) { 9205 L->CompletedImplicitDefinition(Constructor); 9206 } 9207 } 9208 9209 9210 Sema::ImplicitExceptionSpecification 9211 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9212 CXXRecordDecl *ClassDecl = MD->getParent(); 9213 9214 // C++ [except.spec]p14: 9215 // An implicitly declared special member function (Clause 12) shall have 9216 // an exception-specification. 9217 ImplicitExceptionSpecification ExceptSpec(*this); 9218 if (ClassDecl->isInvalidDecl()) 9219 return ExceptSpec; 9220 9221 // Direct base-class destructors. 9222 for (const auto &B : ClassDecl->bases()) { 9223 if (B.isVirtual()) // Handled below. 9224 continue; 9225 9226 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9227 ExceptSpec.CalledDecl(B.getLocStart(), 9228 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9229 } 9230 9231 // Virtual base-class destructors. 9232 for (const auto &B : ClassDecl->vbases()) { 9233 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9234 ExceptSpec.CalledDecl(B.getLocStart(), 9235 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9236 } 9237 9238 // Field destructors. 9239 for (const auto *F : ClassDecl->fields()) { 9240 if (const RecordType *RecordTy 9241 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9242 ExceptSpec.CalledDecl(F->getLocation(), 9243 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9244 } 9245 9246 return ExceptSpec; 9247 } 9248 9249 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9250 // C++ [class.dtor]p2: 9251 // If a class has no user-declared destructor, a destructor is 9252 // declared implicitly. An implicitly-declared destructor is an 9253 // inline public member of its class. 9254 assert(ClassDecl->needsImplicitDestructor()); 9255 9256 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9257 if (DSM.isAlreadyBeingDeclared()) 9258 return nullptr; 9259 9260 // Create the actual destructor declaration. 9261 CanQualType ClassType 9262 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9263 SourceLocation ClassLoc = ClassDecl->getLocation(); 9264 DeclarationName Name 9265 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9266 DeclarationNameInfo NameInfo(Name, ClassLoc); 9267 CXXDestructorDecl *Destructor 9268 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9269 QualType(), nullptr, /*isInline=*/true, 9270 /*isImplicitlyDeclared=*/true); 9271 Destructor->setAccess(AS_public); 9272 Destructor->setDefaulted(); 9273 9274 if (getLangOpts().CUDA) { 9275 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9276 Destructor, 9277 /* ConstRHS */ false, 9278 /* Diagnose */ false); 9279 } 9280 9281 // Build an exception specification pointing back at this destructor. 9282 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9283 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9284 9285 AddOverriddenMethods(ClassDecl, Destructor); 9286 9287 // We don't need to use SpecialMemberIsTrivial here; triviality for 9288 // destructors is easy to compute. 9289 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9290 9291 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9292 SetDeclDeleted(Destructor, ClassLoc); 9293 9294 // Note that we have declared this destructor. 9295 ++ASTContext::NumImplicitDestructorsDeclared; 9296 9297 // Introduce this destructor into its scope. 9298 if (Scope *S = getScopeForContext(ClassDecl)) 9299 PushOnScopeChains(Destructor, S, false); 9300 ClassDecl->addDecl(Destructor); 9301 9302 return Destructor; 9303 } 9304 9305 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9306 CXXDestructorDecl *Destructor) { 9307 assert((Destructor->isDefaulted() && 9308 !Destructor->doesThisDeclarationHaveABody() && 9309 !Destructor->isDeleted()) && 9310 "DefineImplicitDestructor - call it for implicit default dtor"); 9311 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9312 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9313 9314 if (Destructor->isInvalidDecl()) 9315 return; 9316 9317 SynthesizedFunctionScope Scope(*this, Destructor); 9318 9319 DiagnosticErrorTrap Trap(Diags); 9320 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9321 Destructor->getParent()); 9322 9323 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9324 Diag(CurrentLocation, diag::note_member_synthesized_at) 9325 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9326 9327 Destructor->setInvalidDecl(); 9328 return; 9329 } 9330 9331 // The exception specification is needed because we are defining the 9332 // function. 9333 ResolveExceptionSpec(CurrentLocation, 9334 Destructor->getType()->castAs<FunctionProtoType>()); 9335 9336 SourceLocation Loc = Destructor->getLocEnd().isValid() 9337 ? Destructor->getLocEnd() 9338 : Destructor->getLocation(); 9339 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9340 Destructor->markUsed(Context); 9341 MarkVTableUsed(CurrentLocation, ClassDecl); 9342 9343 if (ASTMutationListener *L = getASTMutationListener()) { 9344 L->CompletedImplicitDefinition(Destructor); 9345 } 9346 } 9347 9348 /// \brief Perform any semantic analysis which needs to be delayed until all 9349 /// pending class member declarations have been parsed. 9350 void Sema::ActOnFinishCXXMemberDecls() { 9351 // If the context is an invalid C++ class, just suppress these checks. 9352 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9353 if (Record->isInvalidDecl()) { 9354 DelayedDefaultedMemberExceptionSpecs.clear(); 9355 DelayedExceptionSpecChecks.clear(); 9356 return; 9357 } 9358 } 9359 } 9360 9361 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9362 CXXDestructorDecl *Destructor) { 9363 assert(getLangOpts().CPlusPlus11 && 9364 "adjusting dtor exception specs was introduced in c++11"); 9365 9366 // C++11 [class.dtor]p3: 9367 // A declaration of a destructor that does not have an exception- 9368 // specification is implicitly considered to have the same exception- 9369 // specification as an implicit declaration. 9370 const FunctionProtoType *DtorType = Destructor->getType()-> 9371 getAs<FunctionProtoType>(); 9372 if (DtorType->hasExceptionSpec()) 9373 return; 9374 9375 // Replace the destructor's type, building off the existing one. Fortunately, 9376 // the only thing of interest in the destructor type is its extended info. 9377 // The return and arguments are fixed. 9378 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9379 EPI.ExceptionSpec.Type = EST_Unevaluated; 9380 EPI.ExceptionSpec.SourceDecl = Destructor; 9381 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9382 9383 // FIXME: If the destructor has a body that could throw, and the newly created 9384 // spec doesn't allow exceptions, we should emit a warning, because this 9385 // change in behavior can break conforming C++03 programs at runtime. 9386 // However, we don't have a body or an exception specification yet, so it 9387 // needs to be done somewhere else. 9388 } 9389 9390 namespace { 9391 /// \brief An abstract base class for all helper classes used in building the 9392 // copy/move operators. These classes serve as factory functions and help us 9393 // avoid using the same Expr* in the AST twice. 9394 class ExprBuilder { 9395 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9396 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9397 9398 protected: 9399 static Expr *assertNotNull(Expr *E) { 9400 assert(E && "Expression construction must not fail."); 9401 return E; 9402 } 9403 9404 public: 9405 ExprBuilder() {} 9406 virtual ~ExprBuilder() {} 9407 9408 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9409 }; 9410 9411 class RefBuilder: public ExprBuilder { 9412 VarDecl *Var; 9413 QualType VarType; 9414 9415 public: 9416 Expr *build(Sema &S, SourceLocation Loc) const override { 9417 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9418 } 9419 9420 RefBuilder(VarDecl *Var, QualType VarType) 9421 : Var(Var), VarType(VarType) {} 9422 }; 9423 9424 class ThisBuilder: public ExprBuilder { 9425 public: 9426 Expr *build(Sema &S, SourceLocation Loc) const override { 9427 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9428 } 9429 }; 9430 9431 class CastBuilder: public ExprBuilder { 9432 const ExprBuilder &Builder; 9433 QualType Type; 9434 ExprValueKind Kind; 9435 const CXXCastPath &Path; 9436 9437 public: 9438 Expr *build(Sema &S, SourceLocation Loc) const override { 9439 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9440 CK_UncheckedDerivedToBase, Kind, 9441 &Path).get()); 9442 } 9443 9444 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9445 const CXXCastPath &Path) 9446 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9447 }; 9448 9449 class DerefBuilder: public ExprBuilder { 9450 const ExprBuilder &Builder; 9451 9452 public: 9453 Expr *build(Sema &S, SourceLocation Loc) const override { 9454 return assertNotNull( 9455 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9456 } 9457 9458 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9459 }; 9460 9461 class MemberBuilder: public ExprBuilder { 9462 const ExprBuilder &Builder; 9463 QualType Type; 9464 CXXScopeSpec SS; 9465 bool IsArrow; 9466 LookupResult &MemberLookup; 9467 9468 public: 9469 Expr *build(Sema &S, SourceLocation Loc) const override { 9470 return assertNotNull(S.BuildMemberReferenceExpr( 9471 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9472 nullptr, MemberLookup, nullptr).get()); 9473 } 9474 9475 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9476 LookupResult &MemberLookup) 9477 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9478 MemberLookup(MemberLookup) {} 9479 }; 9480 9481 class MoveCastBuilder: public ExprBuilder { 9482 const ExprBuilder &Builder; 9483 9484 public: 9485 Expr *build(Sema &S, SourceLocation Loc) const override { 9486 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9487 } 9488 9489 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9490 }; 9491 9492 class LvalueConvBuilder: public ExprBuilder { 9493 const ExprBuilder &Builder; 9494 9495 public: 9496 Expr *build(Sema &S, SourceLocation Loc) const override { 9497 return assertNotNull( 9498 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9499 } 9500 9501 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9502 }; 9503 9504 class SubscriptBuilder: public ExprBuilder { 9505 const ExprBuilder &Base; 9506 const ExprBuilder &Index; 9507 9508 public: 9509 Expr *build(Sema &S, SourceLocation Loc) const override { 9510 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9511 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9512 } 9513 9514 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9515 : Base(Base), Index(Index) {} 9516 }; 9517 9518 } // end anonymous namespace 9519 9520 /// When generating a defaulted copy or move assignment operator, if a field 9521 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9522 /// do so. This optimization only applies for arrays of scalars, and for arrays 9523 /// of class type where the selected copy/move-assignment operator is trivial. 9524 static StmtResult 9525 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9526 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9527 // Compute the size of the memory buffer to be copied. 9528 QualType SizeType = S.Context.getSizeType(); 9529 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9530 S.Context.getTypeSizeInChars(T).getQuantity()); 9531 9532 // Take the address of the field references for "from" and "to". We 9533 // directly construct UnaryOperators here because semantic analysis 9534 // does not permit us to take the address of an xvalue. 9535 Expr *From = FromB.build(S, Loc); 9536 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9537 S.Context.getPointerType(From->getType()), 9538 VK_RValue, OK_Ordinary, Loc); 9539 Expr *To = ToB.build(S, Loc); 9540 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9541 S.Context.getPointerType(To->getType()), 9542 VK_RValue, OK_Ordinary, Loc); 9543 9544 const Type *E = T->getBaseElementTypeUnsafe(); 9545 bool NeedsCollectableMemCpy = 9546 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9547 9548 // Create a reference to the __builtin_objc_memmove_collectable function 9549 StringRef MemCpyName = NeedsCollectableMemCpy ? 9550 "__builtin_objc_memmove_collectable" : 9551 "__builtin_memcpy"; 9552 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9553 Sema::LookupOrdinaryName); 9554 S.LookupName(R, S.TUScope, true); 9555 9556 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9557 if (!MemCpy) 9558 // Something went horribly wrong earlier, and we will have complained 9559 // about it. 9560 return StmtError(); 9561 9562 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9563 VK_RValue, Loc, nullptr); 9564 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9565 9566 Expr *CallArgs[] = { 9567 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9568 }; 9569 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9570 Loc, CallArgs, Loc); 9571 9572 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9573 return Call.getAs<Stmt>(); 9574 } 9575 9576 /// \brief Builds a statement that copies/moves the given entity from \p From to 9577 /// \c To. 9578 /// 9579 /// This routine is used to copy/move the members of a class with an 9580 /// implicitly-declared copy/move assignment operator. When the entities being 9581 /// copied are arrays, this routine builds for loops to copy them. 9582 /// 9583 /// \param S The Sema object used for type-checking. 9584 /// 9585 /// \param Loc The location where the implicit copy/move is being generated. 9586 /// 9587 /// \param T The type of the expressions being copied/moved. Both expressions 9588 /// must have this type. 9589 /// 9590 /// \param To The expression we are copying/moving to. 9591 /// 9592 /// \param From The expression we are copying/moving from. 9593 /// 9594 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9595 /// Otherwise, it's a non-static member subobject. 9596 /// 9597 /// \param Copying Whether we're copying or moving. 9598 /// 9599 /// \param Depth Internal parameter recording the depth of the recursion. 9600 /// 9601 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9602 /// if a memcpy should be used instead. 9603 static StmtResult 9604 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9605 const ExprBuilder &To, const ExprBuilder &From, 9606 bool CopyingBaseSubobject, bool Copying, 9607 unsigned Depth = 0) { 9608 // C++11 [class.copy]p28: 9609 // Each subobject is assigned in the manner appropriate to its type: 9610 // 9611 // - if the subobject is of class type, as if by a call to operator= with 9612 // the subobject as the object expression and the corresponding 9613 // subobject of x as a single function argument (as if by explicit 9614 // qualification; that is, ignoring any possible virtual overriding 9615 // functions in more derived classes); 9616 // 9617 // C++03 [class.copy]p13: 9618 // - if the subobject is of class type, the copy assignment operator for 9619 // the class is used (as if by explicit qualification; that is, 9620 // ignoring any possible virtual overriding functions in more derived 9621 // classes); 9622 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9623 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9624 9625 // Look for operator=. 9626 DeclarationName Name 9627 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9628 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9629 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9630 9631 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9632 // operator. 9633 if (!S.getLangOpts().CPlusPlus11) { 9634 LookupResult::Filter F = OpLookup.makeFilter(); 9635 while (F.hasNext()) { 9636 NamedDecl *D = F.next(); 9637 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9638 if (Method->isCopyAssignmentOperator() || 9639 (!Copying && Method->isMoveAssignmentOperator())) 9640 continue; 9641 9642 F.erase(); 9643 } 9644 F.done(); 9645 } 9646 9647 // Suppress the protected check (C++ [class.protected]) for each of the 9648 // assignment operators we found. This strange dance is required when 9649 // we're assigning via a base classes's copy-assignment operator. To 9650 // ensure that we're getting the right base class subobject (without 9651 // ambiguities), we need to cast "this" to that subobject type; to 9652 // ensure that we don't go through the virtual call mechanism, we need 9653 // to qualify the operator= name with the base class (see below). However, 9654 // this means that if the base class has a protected copy assignment 9655 // operator, the protected member access check will fail. So, we 9656 // rewrite "protected" access to "public" access in this case, since we 9657 // know by construction that we're calling from a derived class. 9658 if (CopyingBaseSubobject) { 9659 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9660 L != LEnd; ++L) { 9661 if (L.getAccess() == AS_protected) 9662 L.setAccess(AS_public); 9663 } 9664 } 9665 9666 // Create the nested-name-specifier that will be used to qualify the 9667 // reference to operator=; this is required to suppress the virtual 9668 // call mechanism. 9669 CXXScopeSpec SS; 9670 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9671 SS.MakeTrivial(S.Context, 9672 NestedNameSpecifier::Create(S.Context, nullptr, false, 9673 CanonicalT), 9674 Loc); 9675 9676 // Create the reference to operator=. 9677 ExprResult OpEqualRef 9678 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9679 SS, /*TemplateKWLoc=*/SourceLocation(), 9680 /*FirstQualifierInScope=*/nullptr, 9681 OpLookup, 9682 /*TemplateArgs=*/nullptr, 9683 /*SuppressQualifierCheck=*/true); 9684 if (OpEqualRef.isInvalid()) 9685 return StmtError(); 9686 9687 // Build the call to the assignment operator. 9688 9689 Expr *FromInst = From.build(S, Loc); 9690 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9691 OpEqualRef.getAs<Expr>(), 9692 Loc, FromInst, Loc); 9693 if (Call.isInvalid()) 9694 return StmtError(); 9695 9696 // If we built a call to a trivial 'operator=' while copying an array, 9697 // bail out. We'll replace the whole shebang with a memcpy. 9698 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9699 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9700 return StmtResult((Stmt*)nullptr); 9701 9702 // Convert to an expression-statement, and clean up any produced 9703 // temporaries. 9704 return S.ActOnExprStmt(Call); 9705 } 9706 9707 // - if the subobject is of scalar type, the built-in assignment 9708 // operator is used. 9709 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9710 if (!ArrayTy) { 9711 ExprResult Assignment = S.CreateBuiltinBinOp( 9712 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9713 if (Assignment.isInvalid()) 9714 return StmtError(); 9715 return S.ActOnExprStmt(Assignment); 9716 } 9717 9718 // - if the subobject is an array, each element is assigned, in the 9719 // manner appropriate to the element type; 9720 9721 // Construct a loop over the array bounds, e.g., 9722 // 9723 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9724 // 9725 // that will copy each of the array elements. 9726 QualType SizeType = S.Context.getSizeType(); 9727 9728 // Create the iteration variable. 9729 IdentifierInfo *IterationVarName = nullptr; 9730 { 9731 SmallString<8> Str; 9732 llvm::raw_svector_ostream OS(Str); 9733 OS << "__i" << Depth; 9734 IterationVarName = &S.Context.Idents.get(OS.str()); 9735 } 9736 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9737 IterationVarName, SizeType, 9738 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9739 SC_None); 9740 9741 // Initialize the iteration variable to zero. 9742 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9743 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9744 9745 // Creates a reference to the iteration variable. 9746 RefBuilder IterationVarRef(IterationVar, SizeType); 9747 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9748 9749 // Create the DeclStmt that holds the iteration variable. 9750 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9751 9752 // Subscript the "from" and "to" expressions with the iteration variable. 9753 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9754 MoveCastBuilder FromIndexMove(FromIndexCopy); 9755 const ExprBuilder *FromIndex; 9756 if (Copying) 9757 FromIndex = &FromIndexCopy; 9758 else 9759 FromIndex = &FromIndexMove; 9760 9761 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9762 9763 // Build the copy/move for an individual element of the array. 9764 StmtResult Copy = 9765 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9766 ToIndex, *FromIndex, CopyingBaseSubobject, 9767 Copying, Depth + 1); 9768 // Bail out if copying fails or if we determined that we should use memcpy. 9769 if (Copy.isInvalid() || !Copy.get()) 9770 return Copy; 9771 9772 // Create the comparison against the array bound. 9773 llvm::APInt Upper 9774 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9775 Expr *Comparison 9776 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9777 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9778 BO_NE, S.Context.BoolTy, 9779 VK_RValue, OK_Ordinary, Loc, false); 9780 9781 // Create the pre-increment of the iteration variable. 9782 Expr *Increment 9783 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9784 SizeType, VK_LValue, OK_Ordinary, Loc); 9785 9786 // Construct the loop that copies all elements of this array. 9787 return S.ActOnForStmt(Loc, Loc, InitStmt, 9788 S.MakeFullExpr(Comparison), 9789 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9790 Loc, Copy.get()); 9791 } 9792 9793 static StmtResult 9794 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9795 const ExprBuilder &To, const ExprBuilder &From, 9796 bool CopyingBaseSubobject, bool Copying) { 9797 // Maybe we should use a memcpy? 9798 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9799 T.isTriviallyCopyableType(S.Context)) 9800 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9801 9802 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9803 CopyingBaseSubobject, 9804 Copying, 0)); 9805 9806 // If we ended up picking a trivial assignment operator for an array of a 9807 // non-trivially-copyable class type, just emit a memcpy. 9808 if (!Result.isInvalid() && !Result.get()) 9809 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9810 9811 return Result; 9812 } 9813 9814 Sema::ImplicitExceptionSpecification 9815 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9816 CXXRecordDecl *ClassDecl = MD->getParent(); 9817 9818 ImplicitExceptionSpecification ExceptSpec(*this); 9819 if (ClassDecl->isInvalidDecl()) 9820 return ExceptSpec; 9821 9822 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9823 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9824 unsigned ArgQuals = 9825 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9826 9827 // C++ [except.spec]p14: 9828 // An implicitly declared special member function (Clause 12) shall have an 9829 // exception-specification. [...] 9830 9831 // It is unspecified whether or not an implicit copy assignment operator 9832 // attempts to deduplicate calls to assignment operators of virtual bases are 9833 // made. As such, this exception specification is effectively unspecified. 9834 // Based on a similar decision made for constness in C++0x, we're erring on 9835 // the side of assuming such calls to be made regardless of whether they 9836 // actually happen. 9837 for (const auto &Base : ClassDecl->bases()) { 9838 if (Base.isVirtual()) 9839 continue; 9840 9841 CXXRecordDecl *BaseClassDecl 9842 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9843 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9844 ArgQuals, false, 0)) 9845 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9846 } 9847 9848 for (const auto &Base : ClassDecl->vbases()) { 9849 CXXRecordDecl *BaseClassDecl 9850 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9851 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9852 ArgQuals, false, 0)) 9853 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9854 } 9855 9856 for (const auto *Field : ClassDecl->fields()) { 9857 QualType FieldType = Context.getBaseElementType(Field->getType()); 9858 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9859 if (CXXMethodDecl *CopyAssign = 9860 LookupCopyingAssignment(FieldClassDecl, 9861 ArgQuals | FieldType.getCVRQualifiers(), 9862 false, 0)) 9863 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9864 } 9865 } 9866 9867 return ExceptSpec; 9868 } 9869 9870 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9871 // Note: The following rules are largely analoguous to the copy 9872 // constructor rules. Note that virtual bases are not taken into account 9873 // for determining the argument type of the operator. Note also that 9874 // operators taking an object instead of a reference are allowed. 9875 assert(ClassDecl->needsImplicitCopyAssignment()); 9876 9877 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9878 if (DSM.isAlreadyBeingDeclared()) 9879 return nullptr; 9880 9881 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9882 QualType RetType = Context.getLValueReferenceType(ArgType); 9883 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9884 if (Const) 9885 ArgType = ArgType.withConst(); 9886 ArgType = Context.getLValueReferenceType(ArgType); 9887 9888 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9889 CXXCopyAssignment, 9890 Const); 9891 9892 // An implicitly-declared copy assignment operator is an inline public 9893 // member of its class. 9894 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9895 SourceLocation ClassLoc = ClassDecl->getLocation(); 9896 DeclarationNameInfo NameInfo(Name, ClassLoc); 9897 CXXMethodDecl *CopyAssignment = 9898 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9899 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9900 /*isInline=*/true, Constexpr, SourceLocation()); 9901 CopyAssignment->setAccess(AS_public); 9902 CopyAssignment->setDefaulted(); 9903 CopyAssignment->setImplicit(); 9904 9905 if (getLangOpts().CUDA) { 9906 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 9907 CopyAssignment, 9908 /* ConstRHS */ Const, 9909 /* Diagnose */ false); 9910 } 9911 9912 // Build an exception specification pointing back at this member. 9913 FunctionProtoType::ExtProtoInfo EPI = 9914 getImplicitMethodEPI(*this, CopyAssignment); 9915 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9916 9917 // Add the parameter to the operator. 9918 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9919 ClassLoc, ClassLoc, 9920 /*Id=*/nullptr, ArgType, 9921 /*TInfo=*/nullptr, SC_None, 9922 nullptr); 9923 CopyAssignment->setParams(FromParam); 9924 9925 AddOverriddenMethods(ClassDecl, CopyAssignment); 9926 9927 CopyAssignment->setTrivial( 9928 ClassDecl->needsOverloadResolutionForCopyAssignment() 9929 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9930 : ClassDecl->hasTrivialCopyAssignment()); 9931 9932 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9933 SetDeclDeleted(CopyAssignment, ClassLoc); 9934 9935 // Note that we have added this copy-assignment operator. 9936 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9937 9938 if (Scope *S = getScopeForContext(ClassDecl)) 9939 PushOnScopeChains(CopyAssignment, S, false); 9940 ClassDecl->addDecl(CopyAssignment); 9941 9942 return CopyAssignment; 9943 } 9944 9945 /// Diagnose an implicit copy operation for a class which is odr-used, but 9946 /// which is deprecated because the class has a user-declared copy constructor, 9947 /// copy assignment operator, or destructor. 9948 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9949 SourceLocation UseLoc) { 9950 assert(CopyOp->isImplicit()); 9951 9952 CXXRecordDecl *RD = CopyOp->getParent(); 9953 CXXMethodDecl *UserDeclaredOperation = nullptr; 9954 9955 // In Microsoft mode, assignment operations don't affect constructors and 9956 // vice versa. 9957 if (RD->hasUserDeclaredDestructor()) { 9958 UserDeclaredOperation = RD->getDestructor(); 9959 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9960 RD->hasUserDeclaredCopyConstructor() && 9961 !S.getLangOpts().MSVCCompat) { 9962 // Find any user-declared copy constructor. 9963 for (auto *I : RD->ctors()) { 9964 if (I->isCopyConstructor()) { 9965 UserDeclaredOperation = I; 9966 break; 9967 } 9968 } 9969 assert(UserDeclaredOperation); 9970 } else if (isa<CXXConstructorDecl>(CopyOp) && 9971 RD->hasUserDeclaredCopyAssignment() && 9972 !S.getLangOpts().MSVCCompat) { 9973 // Find any user-declared move assignment operator. 9974 for (auto *I : RD->methods()) { 9975 if (I->isCopyAssignmentOperator()) { 9976 UserDeclaredOperation = I; 9977 break; 9978 } 9979 } 9980 assert(UserDeclaredOperation); 9981 } 9982 9983 if (UserDeclaredOperation) { 9984 S.Diag(UserDeclaredOperation->getLocation(), 9985 diag::warn_deprecated_copy_operation) 9986 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9987 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9988 S.Diag(UseLoc, diag::note_member_synthesized_at) 9989 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9990 : Sema::CXXCopyAssignment) 9991 << RD; 9992 } 9993 } 9994 9995 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9996 CXXMethodDecl *CopyAssignOperator) { 9997 assert((CopyAssignOperator->isDefaulted() && 9998 CopyAssignOperator->isOverloadedOperator() && 9999 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 10000 !CopyAssignOperator->doesThisDeclarationHaveABody() && 10001 !CopyAssignOperator->isDeleted()) && 10002 "DefineImplicitCopyAssignment called for wrong function"); 10003 10004 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 10005 10006 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 10007 CopyAssignOperator->setInvalidDecl(); 10008 return; 10009 } 10010 10011 // C++11 [class.copy]p18: 10012 // The [definition of an implicitly declared copy assignment operator] is 10013 // deprecated if the class has a user-declared copy constructor or a 10014 // user-declared destructor. 10015 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 10016 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 10017 10018 CopyAssignOperator->markUsed(Context); 10019 10020 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 10021 DiagnosticErrorTrap Trap(Diags); 10022 10023 // C++0x [class.copy]p30: 10024 // The implicitly-defined or explicitly-defaulted copy assignment operator 10025 // for a non-union class X performs memberwise copy assignment of its 10026 // subobjects. The direct base classes of X are assigned first, in the 10027 // order of their declaration in the base-specifier-list, and then the 10028 // immediate non-static data members of X are assigned, in the order in 10029 // which they were declared in the class definition. 10030 10031 // The statements that form the synthesized function body. 10032 SmallVector<Stmt*, 8> Statements; 10033 10034 // The parameter for the "other" object, which we are copying from. 10035 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 10036 Qualifiers OtherQuals = Other->getType().getQualifiers(); 10037 QualType OtherRefType = Other->getType(); 10038 if (const LValueReferenceType *OtherRef 10039 = OtherRefType->getAs<LValueReferenceType>()) { 10040 OtherRefType = OtherRef->getPointeeType(); 10041 OtherQuals = OtherRefType.getQualifiers(); 10042 } 10043 10044 // Our location for everything implicitly-generated. 10045 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 10046 ? CopyAssignOperator->getLocEnd() 10047 : CopyAssignOperator->getLocation(); 10048 10049 // Builds a DeclRefExpr for the "other" object. 10050 RefBuilder OtherRef(Other, OtherRefType); 10051 10052 // Builds the "this" pointer. 10053 ThisBuilder This; 10054 10055 // Assign base classes. 10056 bool Invalid = false; 10057 for (auto &Base : ClassDecl->bases()) { 10058 // Form the assignment: 10059 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10060 QualType BaseType = Base.getType().getUnqualifiedType(); 10061 if (!BaseType->isRecordType()) { 10062 Invalid = true; 10063 continue; 10064 } 10065 10066 CXXCastPath BasePath; 10067 BasePath.push_back(&Base); 10068 10069 // Construct the "from" expression, which is an implicit cast to the 10070 // appropriately-qualified base type. 10071 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10072 VK_LValue, BasePath); 10073 10074 // Dereference "this". 10075 DerefBuilder DerefThis(This); 10076 CastBuilder To(DerefThis, 10077 Context.getCVRQualifiedType( 10078 BaseType, CopyAssignOperator->getTypeQualifiers()), 10079 VK_LValue, BasePath); 10080 10081 // Build the copy. 10082 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10083 To, From, 10084 /*CopyingBaseSubobject=*/true, 10085 /*Copying=*/true); 10086 if (Copy.isInvalid()) { 10087 Diag(CurrentLocation, diag::note_member_synthesized_at) 10088 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10089 CopyAssignOperator->setInvalidDecl(); 10090 return; 10091 } 10092 10093 // Success! Record the copy. 10094 Statements.push_back(Copy.getAs<Expr>()); 10095 } 10096 10097 // Assign non-static members. 10098 for (auto *Field : ClassDecl->fields()) { 10099 if (Field->isUnnamedBitfield()) 10100 continue; 10101 10102 if (Field->isInvalidDecl()) { 10103 Invalid = true; 10104 continue; 10105 } 10106 10107 // Check for members of reference type; we can't copy those. 10108 if (Field->getType()->isReferenceType()) { 10109 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10110 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10111 Diag(Field->getLocation(), diag::note_declared_at); 10112 Diag(CurrentLocation, diag::note_member_synthesized_at) 10113 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10114 Invalid = true; 10115 continue; 10116 } 10117 10118 // Check for members of const-qualified, non-class type. 10119 QualType BaseType = Context.getBaseElementType(Field->getType()); 10120 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10121 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10122 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10123 Diag(Field->getLocation(), diag::note_declared_at); 10124 Diag(CurrentLocation, diag::note_member_synthesized_at) 10125 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10126 Invalid = true; 10127 continue; 10128 } 10129 10130 // Suppress assigning zero-width bitfields. 10131 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10132 continue; 10133 10134 QualType FieldType = Field->getType().getNonReferenceType(); 10135 if (FieldType->isIncompleteArrayType()) { 10136 assert(ClassDecl->hasFlexibleArrayMember() && 10137 "Incomplete array type is not valid"); 10138 continue; 10139 } 10140 10141 // Build references to the field in the object we're copying from and to. 10142 CXXScopeSpec SS; // Intentionally empty 10143 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10144 LookupMemberName); 10145 MemberLookup.addDecl(Field); 10146 MemberLookup.resolveKind(); 10147 10148 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10149 10150 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10151 10152 // Build the copy of this field. 10153 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10154 To, From, 10155 /*CopyingBaseSubobject=*/false, 10156 /*Copying=*/true); 10157 if (Copy.isInvalid()) { 10158 Diag(CurrentLocation, diag::note_member_synthesized_at) 10159 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10160 CopyAssignOperator->setInvalidDecl(); 10161 return; 10162 } 10163 10164 // Success! Record the copy. 10165 Statements.push_back(Copy.getAs<Stmt>()); 10166 } 10167 10168 if (!Invalid) { 10169 // Add a "return *this;" 10170 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10171 10172 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10173 if (Return.isInvalid()) 10174 Invalid = true; 10175 else { 10176 Statements.push_back(Return.getAs<Stmt>()); 10177 10178 if (Trap.hasErrorOccurred()) { 10179 Diag(CurrentLocation, diag::note_member_synthesized_at) 10180 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10181 Invalid = true; 10182 } 10183 } 10184 } 10185 10186 // The exception specification is needed because we are defining the 10187 // function. 10188 ResolveExceptionSpec(CurrentLocation, 10189 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10190 10191 if (Invalid) { 10192 CopyAssignOperator->setInvalidDecl(); 10193 return; 10194 } 10195 10196 StmtResult Body; 10197 { 10198 CompoundScopeRAII CompoundScope(*this); 10199 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10200 /*isStmtExpr=*/false); 10201 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10202 } 10203 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10204 10205 if (ASTMutationListener *L = getASTMutationListener()) { 10206 L->CompletedImplicitDefinition(CopyAssignOperator); 10207 } 10208 } 10209 10210 Sema::ImplicitExceptionSpecification 10211 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10212 CXXRecordDecl *ClassDecl = MD->getParent(); 10213 10214 ImplicitExceptionSpecification ExceptSpec(*this); 10215 if (ClassDecl->isInvalidDecl()) 10216 return ExceptSpec; 10217 10218 // C++0x [except.spec]p14: 10219 // An implicitly declared special member function (Clause 12) shall have an 10220 // exception-specification. [...] 10221 10222 // It is unspecified whether or not an implicit move assignment operator 10223 // attempts to deduplicate calls to assignment operators of virtual bases are 10224 // made. As such, this exception specification is effectively unspecified. 10225 // Based on a similar decision made for constness in C++0x, we're erring on 10226 // the side of assuming such calls to be made regardless of whether they 10227 // actually happen. 10228 // Note that a move constructor is not implicitly declared when there are 10229 // virtual bases, but it can still be user-declared and explicitly defaulted. 10230 for (const auto &Base : ClassDecl->bases()) { 10231 if (Base.isVirtual()) 10232 continue; 10233 10234 CXXRecordDecl *BaseClassDecl 10235 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10236 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10237 0, false, 0)) 10238 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10239 } 10240 10241 for (const auto &Base : ClassDecl->vbases()) { 10242 CXXRecordDecl *BaseClassDecl 10243 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10244 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10245 0, false, 0)) 10246 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10247 } 10248 10249 for (const auto *Field : ClassDecl->fields()) { 10250 QualType FieldType = Context.getBaseElementType(Field->getType()); 10251 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10252 if (CXXMethodDecl *MoveAssign = 10253 LookupMovingAssignment(FieldClassDecl, 10254 FieldType.getCVRQualifiers(), 10255 false, 0)) 10256 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10257 } 10258 } 10259 10260 return ExceptSpec; 10261 } 10262 10263 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10264 assert(ClassDecl->needsImplicitMoveAssignment()); 10265 10266 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10267 if (DSM.isAlreadyBeingDeclared()) 10268 return nullptr; 10269 10270 // Note: The following rules are largely analoguous to the move 10271 // constructor rules. 10272 10273 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10274 QualType RetType = Context.getLValueReferenceType(ArgType); 10275 ArgType = Context.getRValueReferenceType(ArgType); 10276 10277 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10278 CXXMoveAssignment, 10279 false); 10280 10281 // An implicitly-declared move assignment operator is an inline public 10282 // member of its class. 10283 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10284 SourceLocation ClassLoc = ClassDecl->getLocation(); 10285 DeclarationNameInfo NameInfo(Name, ClassLoc); 10286 CXXMethodDecl *MoveAssignment = 10287 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10288 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10289 /*isInline=*/true, Constexpr, SourceLocation()); 10290 MoveAssignment->setAccess(AS_public); 10291 MoveAssignment->setDefaulted(); 10292 MoveAssignment->setImplicit(); 10293 10294 if (getLangOpts().CUDA) { 10295 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10296 MoveAssignment, 10297 /* ConstRHS */ false, 10298 /* Diagnose */ false); 10299 } 10300 10301 // Build an exception specification pointing back at this member. 10302 FunctionProtoType::ExtProtoInfo EPI = 10303 getImplicitMethodEPI(*this, MoveAssignment); 10304 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10305 10306 // Add the parameter to the operator. 10307 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10308 ClassLoc, ClassLoc, 10309 /*Id=*/nullptr, ArgType, 10310 /*TInfo=*/nullptr, SC_None, 10311 nullptr); 10312 MoveAssignment->setParams(FromParam); 10313 10314 AddOverriddenMethods(ClassDecl, MoveAssignment); 10315 10316 MoveAssignment->setTrivial( 10317 ClassDecl->needsOverloadResolutionForMoveAssignment() 10318 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10319 : ClassDecl->hasTrivialMoveAssignment()); 10320 10321 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10322 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10323 SetDeclDeleted(MoveAssignment, ClassLoc); 10324 } 10325 10326 // Note that we have added this copy-assignment operator. 10327 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10328 10329 if (Scope *S = getScopeForContext(ClassDecl)) 10330 PushOnScopeChains(MoveAssignment, S, false); 10331 ClassDecl->addDecl(MoveAssignment); 10332 10333 return MoveAssignment; 10334 } 10335 10336 /// Check if we're implicitly defining a move assignment operator for a class 10337 /// with virtual bases. Such a move assignment might move-assign the virtual 10338 /// base multiple times. 10339 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10340 SourceLocation CurrentLocation) { 10341 assert(!Class->isDependentContext() && "should not define dependent move"); 10342 10343 // Only a virtual base could get implicitly move-assigned multiple times. 10344 // Only a non-trivial move assignment can observe this. We only want to 10345 // diagnose if we implicitly define an assignment operator that assigns 10346 // two base classes, both of which move-assign the same virtual base. 10347 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10348 Class->getNumBases() < 2) 10349 return; 10350 10351 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10352 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10353 VBaseMap VBases; 10354 10355 for (auto &BI : Class->bases()) { 10356 Worklist.push_back(&BI); 10357 while (!Worklist.empty()) { 10358 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10359 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10360 10361 // If the base has no non-trivial move assignment operators, 10362 // we don't care about moves from it. 10363 if (!Base->hasNonTrivialMoveAssignment()) 10364 continue; 10365 10366 // If there's nothing virtual here, skip it. 10367 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10368 continue; 10369 10370 // If we're not actually going to call a move assignment for this base, 10371 // or the selected move assignment is trivial, skip it. 10372 Sema::SpecialMemberOverloadResult *SMOR = 10373 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10374 /*ConstArg*/false, /*VolatileArg*/false, 10375 /*RValueThis*/true, /*ConstThis*/false, 10376 /*VolatileThis*/false); 10377 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10378 !SMOR->getMethod()->isMoveAssignmentOperator()) 10379 continue; 10380 10381 if (BaseSpec->isVirtual()) { 10382 // We're going to move-assign this virtual base, and its move 10383 // assignment operator is not trivial. If this can happen for 10384 // multiple distinct direct bases of Class, diagnose it. (If it 10385 // only happens in one base, we'll diagnose it when synthesizing 10386 // that base class's move assignment operator.) 10387 CXXBaseSpecifier *&Existing = 10388 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10389 .first->second; 10390 if (Existing && Existing != &BI) { 10391 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10392 << Class << Base; 10393 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10394 << (Base->getCanonicalDecl() == 10395 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10396 << Base << Existing->getType() << Existing->getSourceRange(); 10397 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10398 << (Base->getCanonicalDecl() == 10399 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10400 << Base << BI.getType() << BaseSpec->getSourceRange(); 10401 10402 // Only diagnose each vbase once. 10403 Existing = nullptr; 10404 } 10405 } else { 10406 // Only walk over bases that have defaulted move assignment operators. 10407 // We assume that any user-provided move assignment operator handles 10408 // the multiple-moves-of-vbase case itself somehow. 10409 if (!SMOR->getMethod()->isDefaulted()) 10410 continue; 10411 10412 // We're going to move the base classes of Base. Add them to the list. 10413 for (auto &BI : Base->bases()) 10414 Worklist.push_back(&BI); 10415 } 10416 } 10417 } 10418 } 10419 10420 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10421 CXXMethodDecl *MoveAssignOperator) { 10422 assert((MoveAssignOperator->isDefaulted() && 10423 MoveAssignOperator->isOverloadedOperator() && 10424 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10425 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10426 !MoveAssignOperator->isDeleted()) && 10427 "DefineImplicitMoveAssignment called for wrong function"); 10428 10429 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10430 10431 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10432 MoveAssignOperator->setInvalidDecl(); 10433 return; 10434 } 10435 10436 MoveAssignOperator->markUsed(Context); 10437 10438 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10439 DiagnosticErrorTrap Trap(Diags); 10440 10441 // C++0x [class.copy]p28: 10442 // The implicitly-defined or move assignment operator for a non-union class 10443 // X performs memberwise move assignment of its subobjects. The direct base 10444 // classes of X are assigned first, in the order of their declaration in the 10445 // base-specifier-list, and then the immediate non-static data members of X 10446 // are assigned, in the order in which they were declared in the class 10447 // definition. 10448 10449 // Issue a warning if our implicit move assignment operator will move 10450 // from a virtual base more than once. 10451 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10452 10453 // The statements that form the synthesized function body. 10454 SmallVector<Stmt*, 8> Statements; 10455 10456 // The parameter for the "other" object, which we are move from. 10457 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10458 QualType OtherRefType = Other->getType()-> 10459 getAs<RValueReferenceType>()->getPointeeType(); 10460 assert(!OtherRefType.getQualifiers() && 10461 "Bad argument type of defaulted move assignment"); 10462 10463 // Our location for everything implicitly-generated. 10464 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10465 ? MoveAssignOperator->getLocEnd() 10466 : MoveAssignOperator->getLocation(); 10467 10468 // Builds a reference to the "other" object. 10469 RefBuilder OtherRef(Other, OtherRefType); 10470 // Cast to rvalue. 10471 MoveCastBuilder MoveOther(OtherRef); 10472 10473 // Builds the "this" pointer. 10474 ThisBuilder This; 10475 10476 // Assign base classes. 10477 bool Invalid = false; 10478 for (auto &Base : ClassDecl->bases()) { 10479 // C++11 [class.copy]p28: 10480 // It is unspecified whether subobjects representing virtual base classes 10481 // are assigned more than once by the implicitly-defined copy assignment 10482 // operator. 10483 // FIXME: Do not assign to a vbase that will be assigned by some other base 10484 // class. For a move-assignment, this can result in the vbase being moved 10485 // multiple times. 10486 10487 // Form the assignment: 10488 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10489 QualType BaseType = Base.getType().getUnqualifiedType(); 10490 if (!BaseType->isRecordType()) { 10491 Invalid = true; 10492 continue; 10493 } 10494 10495 CXXCastPath BasePath; 10496 BasePath.push_back(&Base); 10497 10498 // Construct the "from" expression, which is an implicit cast to the 10499 // appropriately-qualified base type. 10500 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10501 10502 // Dereference "this". 10503 DerefBuilder DerefThis(This); 10504 10505 // Implicitly cast "this" to the appropriately-qualified base type. 10506 CastBuilder To(DerefThis, 10507 Context.getCVRQualifiedType( 10508 BaseType, MoveAssignOperator->getTypeQualifiers()), 10509 VK_LValue, BasePath); 10510 10511 // Build the move. 10512 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10513 To, From, 10514 /*CopyingBaseSubobject=*/true, 10515 /*Copying=*/false); 10516 if (Move.isInvalid()) { 10517 Diag(CurrentLocation, diag::note_member_synthesized_at) 10518 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10519 MoveAssignOperator->setInvalidDecl(); 10520 return; 10521 } 10522 10523 // Success! Record the move. 10524 Statements.push_back(Move.getAs<Expr>()); 10525 } 10526 10527 // Assign non-static members. 10528 for (auto *Field : ClassDecl->fields()) { 10529 if (Field->isUnnamedBitfield()) 10530 continue; 10531 10532 if (Field->isInvalidDecl()) { 10533 Invalid = true; 10534 continue; 10535 } 10536 10537 // Check for members of reference type; we can't move those. 10538 if (Field->getType()->isReferenceType()) { 10539 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10540 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10541 Diag(Field->getLocation(), diag::note_declared_at); 10542 Diag(CurrentLocation, diag::note_member_synthesized_at) 10543 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10544 Invalid = true; 10545 continue; 10546 } 10547 10548 // Check for members of const-qualified, non-class type. 10549 QualType BaseType = Context.getBaseElementType(Field->getType()); 10550 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10551 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10552 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10553 Diag(Field->getLocation(), diag::note_declared_at); 10554 Diag(CurrentLocation, diag::note_member_synthesized_at) 10555 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10556 Invalid = true; 10557 continue; 10558 } 10559 10560 // Suppress assigning zero-width bitfields. 10561 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10562 continue; 10563 10564 QualType FieldType = Field->getType().getNonReferenceType(); 10565 if (FieldType->isIncompleteArrayType()) { 10566 assert(ClassDecl->hasFlexibleArrayMember() && 10567 "Incomplete array type is not valid"); 10568 continue; 10569 } 10570 10571 // Build references to the field in the object we're copying from and to. 10572 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10573 LookupMemberName); 10574 MemberLookup.addDecl(Field); 10575 MemberLookup.resolveKind(); 10576 MemberBuilder From(MoveOther, OtherRefType, 10577 /*IsArrow=*/false, MemberLookup); 10578 MemberBuilder To(This, getCurrentThisType(), 10579 /*IsArrow=*/true, MemberLookup); 10580 10581 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10582 "Member reference with rvalue base must be rvalue except for reference " 10583 "members, which aren't allowed for move assignment."); 10584 10585 // Build the move of this field. 10586 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10587 To, From, 10588 /*CopyingBaseSubobject=*/false, 10589 /*Copying=*/false); 10590 if (Move.isInvalid()) { 10591 Diag(CurrentLocation, diag::note_member_synthesized_at) 10592 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10593 MoveAssignOperator->setInvalidDecl(); 10594 return; 10595 } 10596 10597 // Success! Record the copy. 10598 Statements.push_back(Move.getAs<Stmt>()); 10599 } 10600 10601 if (!Invalid) { 10602 // Add a "return *this;" 10603 ExprResult ThisObj = 10604 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10605 10606 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10607 if (Return.isInvalid()) 10608 Invalid = true; 10609 else { 10610 Statements.push_back(Return.getAs<Stmt>()); 10611 10612 if (Trap.hasErrorOccurred()) { 10613 Diag(CurrentLocation, diag::note_member_synthesized_at) 10614 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10615 Invalid = true; 10616 } 10617 } 10618 } 10619 10620 // The exception specification is needed because we are defining the 10621 // function. 10622 ResolveExceptionSpec(CurrentLocation, 10623 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10624 10625 if (Invalid) { 10626 MoveAssignOperator->setInvalidDecl(); 10627 return; 10628 } 10629 10630 StmtResult Body; 10631 { 10632 CompoundScopeRAII CompoundScope(*this); 10633 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10634 /*isStmtExpr=*/false); 10635 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10636 } 10637 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10638 10639 if (ASTMutationListener *L = getASTMutationListener()) { 10640 L->CompletedImplicitDefinition(MoveAssignOperator); 10641 } 10642 } 10643 10644 Sema::ImplicitExceptionSpecification 10645 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10646 CXXRecordDecl *ClassDecl = MD->getParent(); 10647 10648 ImplicitExceptionSpecification ExceptSpec(*this); 10649 if (ClassDecl->isInvalidDecl()) 10650 return ExceptSpec; 10651 10652 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10653 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10654 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10655 10656 // C++ [except.spec]p14: 10657 // An implicitly declared special member function (Clause 12) shall have an 10658 // exception-specification. [...] 10659 for (const auto &Base : ClassDecl->bases()) { 10660 // Virtual bases are handled below. 10661 if (Base.isVirtual()) 10662 continue; 10663 10664 CXXRecordDecl *BaseClassDecl 10665 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10666 if (CXXConstructorDecl *CopyConstructor = 10667 LookupCopyingConstructor(BaseClassDecl, Quals)) 10668 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10669 } 10670 for (const auto &Base : ClassDecl->vbases()) { 10671 CXXRecordDecl *BaseClassDecl 10672 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10673 if (CXXConstructorDecl *CopyConstructor = 10674 LookupCopyingConstructor(BaseClassDecl, Quals)) 10675 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10676 } 10677 for (const auto *Field : ClassDecl->fields()) { 10678 QualType FieldType = Context.getBaseElementType(Field->getType()); 10679 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10680 if (CXXConstructorDecl *CopyConstructor = 10681 LookupCopyingConstructor(FieldClassDecl, 10682 Quals | FieldType.getCVRQualifiers())) 10683 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10684 } 10685 } 10686 10687 return ExceptSpec; 10688 } 10689 10690 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10691 CXXRecordDecl *ClassDecl) { 10692 // C++ [class.copy]p4: 10693 // If the class definition does not explicitly declare a copy 10694 // constructor, one is declared implicitly. 10695 assert(ClassDecl->needsImplicitCopyConstructor()); 10696 10697 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10698 if (DSM.isAlreadyBeingDeclared()) 10699 return nullptr; 10700 10701 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10702 QualType ArgType = ClassType; 10703 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10704 if (Const) 10705 ArgType = ArgType.withConst(); 10706 ArgType = Context.getLValueReferenceType(ArgType); 10707 10708 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10709 CXXCopyConstructor, 10710 Const); 10711 10712 DeclarationName Name 10713 = Context.DeclarationNames.getCXXConstructorName( 10714 Context.getCanonicalType(ClassType)); 10715 SourceLocation ClassLoc = ClassDecl->getLocation(); 10716 DeclarationNameInfo NameInfo(Name, ClassLoc); 10717 10718 // An implicitly-declared copy constructor is an inline public 10719 // member of its class. 10720 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10721 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10722 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10723 Constexpr); 10724 CopyConstructor->setAccess(AS_public); 10725 CopyConstructor->setDefaulted(); 10726 10727 if (getLangOpts().CUDA) { 10728 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10729 CopyConstructor, 10730 /* ConstRHS */ Const, 10731 /* Diagnose */ false); 10732 } 10733 10734 // Build an exception specification pointing back at this member. 10735 FunctionProtoType::ExtProtoInfo EPI = 10736 getImplicitMethodEPI(*this, CopyConstructor); 10737 CopyConstructor->setType( 10738 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10739 10740 // Add the parameter to the constructor. 10741 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10742 ClassLoc, ClassLoc, 10743 /*IdentifierInfo=*/nullptr, 10744 ArgType, /*TInfo=*/nullptr, 10745 SC_None, nullptr); 10746 CopyConstructor->setParams(FromParam); 10747 10748 CopyConstructor->setTrivial( 10749 ClassDecl->needsOverloadResolutionForCopyConstructor() 10750 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10751 : ClassDecl->hasTrivialCopyConstructor()); 10752 10753 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10754 SetDeclDeleted(CopyConstructor, ClassLoc); 10755 10756 // Note that we have declared this constructor. 10757 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10758 10759 if (Scope *S = getScopeForContext(ClassDecl)) 10760 PushOnScopeChains(CopyConstructor, S, false); 10761 ClassDecl->addDecl(CopyConstructor); 10762 10763 return CopyConstructor; 10764 } 10765 10766 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10767 CXXConstructorDecl *CopyConstructor) { 10768 assert((CopyConstructor->isDefaulted() && 10769 CopyConstructor->isCopyConstructor() && 10770 !CopyConstructor->doesThisDeclarationHaveABody() && 10771 !CopyConstructor->isDeleted()) && 10772 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10773 10774 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10775 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10776 10777 // C++11 [class.copy]p7: 10778 // The [definition of an implicitly declared copy constructor] is 10779 // deprecated if the class has a user-declared copy assignment operator 10780 // or a user-declared destructor. 10781 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10782 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10783 10784 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10785 DiagnosticErrorTrap Trap(Diags); 10786 10787 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10788 Trap.hasErrorOccurred()) { 10789 Diag(CurrentLocation, diag::note_member_synthesized_at) 10790 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10791 CopyConstructor->setInvalidDecl(); 10792 } else { 10793 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10794 ? CopyConstructor->getLocEnd() 10795 : CopyConstructor->getLocation(); 10796 Sema::CompoundScopeRAII CompoundScope(*this); 10797 CopyConstructor->setBody( 10798 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10799 } 10800 10801 // The exception specification is needed because we are defining the 10802 // function. 10803 ResolveExceptionSpec(CurrentLocation, 10804 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10805 10806 CopyConstructor->markUsed(Context); 10807 MarkVTableUsed(CurrentLocation, ClassDecl); 10808 10809 if (ASTMutationListener *L = getASTMutationListener()) { 10810 L->CompletedImplicitDefinition(CopyConstructor); 10811 } 10812 } 10813 10814 Sema::ImplicitExceptionSpecification 10815 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10816 CXXRecordDecl *ClassDecl = MD->getParent(); 10817 10818 // C++ [except.spec]p14: 10819 // An implicitly declared special member function (Clause 12) shall have an 10820 // exception-specification. [...] 10821 ImplicitExceptionSpecification ExceptSpec(*this); 10822 if (ClassDecl->isInvalidDecl()) 10823 return ExceptSpec; 10824 10825 // Direct base-class constructors. 10826 for (const auto &B : ClassDecl->bases()) { 10827 if (B.isVirtual()) // Handled below. 10828 continue; 10829 10830 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10831 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10832 CXXConstructorDecl *Constructor = 10833 LookupMovingConstructor(BaseClassDecl, 0); 10834 // If this is a deleted function, add it anyway. This might be conformant 10835 // with the standard. This might not. I'm not sure. It might not matter. 10836 if (Constructor) 10837 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10838 } 10839 } 10840 10841 // Virtual base-class constructors. 10842 for (const auto &B : ClassDecl->vbases()) { 10843 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10844 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10845 CXXConstructorDecl *Constructor = 10846 LookupMovingConstructor(BaseClassDecl, 0); 10847 // If this is a deleted function, add it anyway. This might be conformant 10848 // with the standard. This might not. I'm not sure. It might not matter. 10849 if (Constructor) 10850 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10851 } 10852 } 10853 10854 // Field constructors. 10855 for (const auto *F : ClassDecl->fields()) { 10856 QualType FieldType = Context.getBaseElementType(F->getType()); 10857 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10858 CXXConstructorDecl *Constructor = 10859 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10860 // If this is a deleted function, add it anyway. This might be conformant 10861 // with the standard. This might not. I'm not sure. It might not matter. 10862 // In particular, the problem is that this function never gets called. It 10863 // might just be ill-formed because this function attempts to refer to 10864 // a deleted function here. 10865 if (Constructor) 10866 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10867 } 10868 } 10869 10870 return ExceptSpec; 10871 } 10872 10873 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10874 CXXRecordDecl *ClassDecl) { 10875 assert(ClassDecl->needsImplicitMoveConstructor()); 10876 10877 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10878 if (DSM.isAlreadyBeingDeclared()) 10879 return nullptr; 10880 10881 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10882 QualType ArgType = Context.getRValueReferenceType(ClassType); 10883 10884 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10885 CXXMoveConstructor, 10886 false); 10887 10888 DeclarationName Name 10889 = Context.DeclarationNames.getCXXConstructorName( 10890 Context.getCanonicalType(ClassType)); 10891 SourceLocation ClassLoc = ClassDecl->getLocation(); 10892 DeclarationNameInfo NameInfo(Name, ClassLoc); 10893 10894 // C++11 [class.copy]p11: 10895 // An implicitly-declared copy/move constructor is an inline public 10896 // member of its class. 10897 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10898 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10899 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10900 Constexpr); 10901 MoveConstructor->setAccess(AS_public); 10902 MoveConstructor->setDefaulted(); 10903 10904 if (getLangOpts().CUDA) { 10905 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 10906 MoveConstructor, 10907 /* ConstRHS */ false, 10908 /* Diagnose */ false); 10909 } 10910 10911 // Build an exception specification pointing back at this member. 10912 FunctionProtoType::ExtProtoInfo EPI = 10913 getImplicitMethodEPI(*this, MoveConstructor); 10914 MoveConstructor->setType( 10915 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10916 10917 // Add the parameter to the constructor. 10918 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10919 ClassLoc, ClassLoc, 10920 /*IdentifierInfo=*/nullptr, 10921 ArgType, /*TInfo=*/nullptr, 10922 SC_None, nullptr); 10923 MoveConstructor->setParams(FromParam); 10924 10925 MoveConstructor->setTrivial( 10926 ClassDecl->needsOverloadResolutionForMoveConstructor() 10927 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10928 : ClassDecl->hasTrivialMoveConstructor()); 10929 10930 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10931 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10932 SetDeclDeleted(MoveConstructor, ClassLoc); 10933 } 10934 10935 // Note that we have declared this constructor. 10936 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10937 10938 if (Scope *S = getScopeForContext(ClassDecl)) 10939 PushOnScopeChains(MoveConstructor, S, false); 10940 ClassDecl->addDecl(MoveConstructor); 10941 10942 return MoveConstructor; 10943 } 10944 10945 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10946 CXXConstructorDecl *MoveConstructor) { 10947 assert((MoveConstructor->isDefaulted() && 10948 MoveConstructor->isMoveConstructor() && 10949 !MoveConstructor->doesThisDeclarationHaveABody() && 10950 !MoveConstructor->isDeleted()) && 10951 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10952 10953 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10954 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10955 10956 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10957 DiagnosticErrorTrap Trap(Diags); 10958 10959 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10960 Trap.hasErrorOccurred()) { 10961 Diag(CurrentLocation, diag::note_member_synthesized_at) 10962 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10963 MoveConstructor->setInvalidDecl(); 10964 } else { 10965 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 10966 ? MoveConstructor->getLocEnd() 10967 : MoveConstructor->getLocation(); 10968 Sema::CompoundScopeRAII CompoundScope(*this); 10969 MoveConstructor->setBody(ActOnCompoundStmt( 10970 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 10971 } 10972 10973 // The exception specification is needed because we are defining the 10974 // function. 10975 ResolveExceptionSpec(CurrentLocation, 10976 MoveConstructor->getType()->castAs<FunctionProtoType>()); 10977 10978 MoveConstructor->markUsed(Context); 10979 MarkVTableUsed(CurrentLocation, ClassDecl); 10980 10981 if (ASTMutationListener *L = getASTMutationListener()) { 10982 L->CompletedImplicitDefinition(MoveConstructor); 10983 } 10984 } 10985 10986 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10987 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10988 } 10989 10990 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10991 SourceLocation CurrentLocation, 10992 CXXConversionDecl *Conv) { 10993 CXXRecordDecl *Lambda = Conv->getParent(); 10994 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10995 // If we are defining a specialization of a conversion to function-ptr 10996 // cache the deduced template arguments for this specialization 10997 // so that we can use them to retrieve the corresponding call-operator 10998 // and static-invoker. 10999 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 11000 11001 // Retrieve the corresponding call-operator specialization. 11002 if (Lambda->isGenericLambda()) { 11003 assert(Conv->isFunctionTemplateSpecialization()); 11004 FunctionTemplateDecl *CallOpTemplate = 11005 CallOp->getDescribedFunctionTemplate(); 11006 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 11007 void *InsertPos = nullptr; 11008 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 11009 DeducedTemplateArgs->asArray(), 11010 InsertPos); 11011 assert(CallOpSpec && 11012 "Conversion operator must have a corresponding call operator"); 11013 CallOp = cast<CXXMethodDecl>(CallOpSpec); 11014 } 11015 // Mark the call operator referenced (and add to pending instantiations 11016 // if necessary). 11017 // For both the conversion and static-invoker template specializations 11018 // we construct their body's in this function, so no need to add them 11019 // to the PendingInstantiations. 11020 MarkFunctionReferenced(CurrentLocation, CallOp); 11021 11022 SynthesizedFunctionScope Scope(*this, Conv); 11023 DiagnosticErrorTrap Trap(Diags); 11024 11025 // Retrieve the static invoker... 11026 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 11027 // ... and get the corresponding specialization for a generic lambda. 11028 if (Lambda->isGenericLambda()) { 11029 assert(DeducedTemplateArgs && 11030 "Must have deduced template arguments from Conversion Operator"); 11031 FunctionTemplateDecl *InvokeTemplate = 11032 Invoker->getDescribedFunctionTemplate(); 11033 void *InsertPos = nullptr; 11034 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 11035 DeducedTemplateArgs->asArray(), 11036 InsertPos); 11037 assert(InvokeSpec && 11038 "Must have a corresponding static invoker specialization"); 11039 Invoker = cast<CXXMethodDecl>(InvokeSpec); 11040 } 11041 // Construct the body of the conversion function { return __invoke; }. 11042 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 11043 VK_LValue, Conv->getLocation()).get(); 11044 assert(FunctionRef && "Can't refer to __invoke function?"); 11045 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 11046 Conv->setBody(new (Context) CompoundStmt(Context, Return, 11047 Conv->getLocation(), 11048 Conv->getLocation())); 11049 11050 Conv->markUsed(Context); 11051 Conv->setReferenced(); 11052 11053 // Fill in the __invoke function with a dummy implementation. IR generation 11054 // will fill in the actual details. 11055 Invoker->markUsed(Context); 11056 Invoker->setReferenced(); 11057 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 11058 11059 if (ASTMutationListener *L = getASTMutationListener()) { 11060 L->CompletedImplicitDefinition(Conv); 11061 L->CompletedImplicitDefinition(Invoker); 11062 } 11063 } 11064 11065 11066 11067 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11068 SourceLocation CurrentLocation, 11069 CXXConversionDecl *Conv) 11070 { 11071 assert(!Conv->getParent()->isGenericLambda()); 11072 11073 Conv->markUsed(Context); 11074 11075 SynthesizedFunctionScope Scope(*this, Conv); 11076 DiagnosticErrorTrap Trap(Diags); 11077 11078 // Copy-initialize the lambda object as needed to capture it. 11079 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11080 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11081 11082 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11083 Conv->getLocation(), 11084 Conv, DerefThis); 11085 11086 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11087 // behavior. Note that only the general conversion function does this 11088 // (since it's unusable otherwise); in the case where we inline the 11089 // block literal, it has block literal lifetime semantics. 11090 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11091 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11092 CK_CopyAndAutoreleaseBlockObject, 11093 BuildBlock.get(), nullptr, VK_RValue); 11094 11095 if (BuildBlock.isInvalid()) { 11096 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11097 Conv->setInvalidDecl(); 11098 return; 11099 } 11100 11101 // Create the return statement that returns the block from the conversion 11102 // function. 11103 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11104 if (Return.isInvalid()) { 11105 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11106 Conv->setInvalidDecl(); 11107 return; 11108 } 11109 11110 // Set the body of the conversion function. 11111 Stmt *ReturnS = Return.get(); 11112 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11113 Conv->getLocation(), 11114 Conv->getLocation())); 11115 11116 // We're done; notify the mutation listener, if any. 11117 if (ASTMutationListener *L = getASTMutationListener()) { 11118 L->CompletedImplicitDefinition(Conv); 11119 } 11120 } 11121 11122 /// \brief Determine whether the given list arguments contains exactly one 11123 /// "real" (non-default) argument. 11124 static bool hasOneRealArgument(MultiExprArg Args) { 11125 switch (Args.size()) { 11126 case 0: 11127 return false; 11128 11129 default: 11130 if (!Args[1]->isDefaultArgument()) 11131 return false; 11132 11133 // fall through 11134 case 1: 11135 return !Args[0]->isDefaultArgument(); 11136 } 11137 11138 return false; 11139 } 11140 11141 ExprResult 11142 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11143 CXXConstructorDecl *Constructor, 11144 MultiExprArg ExprArgs, 11145 bool HadMultipleCandidates, 11146 bool IsListInitialization, 11147 bool IsStdInitListInitialization, 11148 bool RequiresZeroInit, 11149 unsigned ConstructKind, 11150 SourceRange ParenRange) { 11151 bool Elidable = false; 11152 11153 // C++0x [class.copy]p34: 11154 // When certain criteria are met, an implementation is allowed to 11155 // omit the copy/move construction of a class object, even if the 11156 // copy/move constructor and/or destructor for the object have 11157 // side effects. [...] 11158 // - when a temporary class object that has not been bound to a 11159 // reference (12.2) would be copied/moved to a class object 11160 // with the same cv-unqualified type, the copy/move operation 11161 // can be omitted by constructing the temporary object 11162 // directly into the target of the omitted copy/move 11163 if (ConstructKind == CXXConstructExpr::CK_Complete && 11164 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11165 Expr *SubExpr = ExprArgs[0]; 11166 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11167 } 11168 11169 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11170 Elidable, ExprArgs, HadMultipleCandidates, 11171 IsListInitialization, 11172 IsStdInitListInitialization, RequiresZeroInit, 11173 ConstructKind, ParenRange); 11174 } 11175 11176 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11177 /// including handling of its default argument expressions. 11178 ExprResult 11179 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11180 CXXConstructorDecl *Constructor, bool Elidable, 11181 MultiExprArg ExprArgs, 11182 bool HadMultipleCandidates, 11183 bool IsListInitialization, 11184 bool IsStdInitListInitialization, 11185 bool RequiresZeroInit, 11186 unsigned ConstructKind, 11187 SourceRange ParenRange) { 11188 MarkFunctionReferenced(ConstructLoc, Constructor); 11189 return CXXConstructExpr::Create( 11190 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11191 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11192 RequiresZeroInit, 11193 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11194 ParenRange); 11195 } 11196 11197 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11198 assert(Field->hasInClassInitializer()); 11199 11200 // If we already have the in-class initializer nothing needs to be done. 11201 if (Field->getInClassInitializer()) 11202 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11203 11204 // Maybe we haven't instantiated the in-class initializer. Go check the 11205 // pattern FieldDecl to see if it has one. 11206 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11207 11208 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11209 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11210 DeclContext::lookup_result Lookup = 11211 ClassPattern->lookup(Field->getDeclName()); 11212 assert(Lookup.size() == 1); 11213 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11214 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11215 getTemplateInstantiationArgs(Field))) 11216 return ExprError(); 11217 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11218 } 11219 11220 // DR1351: 11221 // If the brace-or-equal-initializer of a non-static data member 11222 // invokes a defaulted default constructor of its class or of an 11223 // enclosing class in a potentially evaluated subexpression, the 11224 // program is ill-formed. 11225 // 11226 // This resolution is unworkable: the exception specification of the 11227 // default constructor can be needed in an unevaluated context, in 11228 // particular, in the operand of a noexcept-expression, and we can be 11229 // unable to compute an exception specification for an enclosed class. 11230 // 11231 // Any attempt to resolve the exception specification of a defaulted default 11232 // constructor before the initializer is lexically complete will ultimately 11233 // come here at which point we can diagnose it. 11234 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11235 if (OutermostClass == ParentRD) { 11236 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11237 << ParentRD << Field; 11238 } else { 11239 Diag(Field->getLocEnd(), 11240 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11241 << ParentRD << OutermostClass << Field; 11242 } 11243 11244 return ExprError(); 11245 } 11246 11247 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11248 if (VD->isInvalidDecl()) return; 11249 11250 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11251 if (ClassDecl->isInvalidDecl()) return; 11252 if (ClassDecl->hasIrrelevantDestructor()) return; 11253 if (ClassDecl->isDependentContext()) return; 11254 11255 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11256 MarkFunctionReferenced(VD->getLocation(), Destructor); 11257 CheckDestructorAccess(VD->getLocation(), Destructor, 11258 PDiag(diag::err_access_dtor_var) 11259 << VD->getDeclName() 11260 << VD->getType()); 11261 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11262 11263 if (Destructor->isTrivial()) return; 11264 if (!VD->hasGlobalStorage()) return; 11265 11266 // Emit warning for non-trivial dtor in global scope (a real global, 11267 // class-static, function-static). 11268 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11269 11270 // TODO: this should be re-enabled for static locals by !CXAAtExit 11271 if (!VD->isStaticLocal()) 11272 Diag(VD->getLocation(), diag::warn_global_destructor); 11273 } 11274 11275 /// \brief Given a constructor and the set of arguments provided for the 11276 /// constructor, convert the arguments and add any required default arguments 11277 /// to form a proper call to this constructor. 11278 /// 11279 /// \returns true if an error occurred, false otherwise. 11280 bool 11281 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11282 MultiExprArg ArgsPtr, 11283 SourceLocation Loc, 11284 SmallVectorImpl<Expr*> &ConvertedArgs, 11285 bool AllowExplicit, 11286 bool IsListInitialization) { 11287 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11288 unsigned NumArgs = ArgsPtr.size(); 11289 Expr **Args = ArgsPtr.data(); 11290 11291 const FunctionProtoType *Proto 11292 = Constructor->getType()->getAs<FunctionProtoType>(); 11293 assert(Proto && "Constructor without a prototype?"); 11294 unsigned NumParams = Proto->getNumParams(); 11295 11296 // If too few arguments are available, we'll fill in the rest with defaults. 11297 if (NumArgs < NumParams) 11298 ConvertedArgs.reserve(NumParams); 11299 else 11300 ConvertedArgs.reserve(NumArgs); 11301 11302 VariadicCallType CallType = 11303 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11304 SmallVector<Expr *, 8> AllArgs; 11305 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11306 Proto, 0, 11307 llvm::makeArrayRef(Args, NumArgs), 11308 AllArgs, 11309 CallType, AllowExplicit, 11310 IsListInitialization); 11311 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11312 11313 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11314 11315 CheckConstructorCall(Constructor, 11316 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11317 Proto, Loc); 11318 11319 return Invalid; 11320 } 11321 11322 static inline bool 11323 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11324 const FunctionDecl *FnDecl) { 11325 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11326 if (isa<NamespaceDecl>(DC)) { 11327 return SemaRef.Diag(FnDecl->getLocation(), 11328 diag::err_operator_new_delete_declared_in_namespace) 11329 << FnDecl->getDeclName(); 11330 } 11331 11332 if (isa<TranslationUnitDecl>(DC) && 11333 FnDecl->getStorageClass() == SC_Static) { 11334 return SemaRef.Diag(FnDecl->getLocation(), 11335 diag::err_operator_new_delete_declared_static) 11336 << FnDecl->getDeclName(); 11337 } 11338 11339 return false; 11340 } 11341 11342 static inline bool 11343 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11344 CanQualType ExpectedResultType, 11345 CanQualType ExpectedFirstParamType, 11346 unsigned DependentParamTypeDiag, 11347 unsigned InvalidParamTypeDiag) { 11348 QualType ResultType = 11349 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11350 11351 // Check that the result type is not dependent. 11352 if (ResultType->isDependentType()) 11353 return SemaRef.Diag(FnDecl->getLocation(), 11354 diag::err_operator_new_delete_dependent_result_type) 11355 << FnDecl->getDeclName() << ExpectedResultType; 11356 11357 // Check that the result type is what we expect. 11358 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11359 return SemaRef.Diag(FnDecl->getLocation(), 11360 diag::err_operator_new_delete_invalid_result_type) 11361 << FnDecl->getDeclName() << ExpectedResultType; 11362 11363 // A function template must have at least 2 parameters. 11364 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11365 return SemaRef.Diag(FnDecl->getLocation(), 11366 diag::err_operator_new_delete_template_too_few_parameters) 11367 << FnDecl->getDeclName(); 11368 11369 // The function decl must have at least 1 parameter. 11370 if (FnDecl->getNumParams() == 0) 11371 return SemaRef.Diag(FnDecl->getLocation(), 11372 diag::err_operator_new_delete_too_few_parameters) 11373 << FnDecl->getDeclName(); 11374 11375 // Check the first parameter type is not dependent. 11376 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11377 if (FirstParamType->isDependentType()) 11378 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11379 << FnDecl->getDeclName() << ExpectedFirstParamType; 11380 11381 // Check that the first parameter type is what we expect. 11382 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11383 ExpectedFirstParamType) 11384 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11385 << FnDecl->getDeclName() << ExpectedFirstParamType; 11386 11387 return false; 11388 } 11389 11390 static bool 11391 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11392 // C++ [basic.stc.dynamic.allocation]p1: 11393 // A program is ill-formed if an allocation function is declared in a 11394 // namespace scope other than global scope or declared static in global 11395 // scope. 11396 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11397 return true; 11398 11399 CanQualType SizeTy = 11400 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11401 11402 // C++ [basic.stc.dynamic.allocation]p1: 11403 // The return type shall be void*. The first parameter shall have type 11404 // std::size_t. 11405 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11406 SizeTy, 11407 diag::err_operator_new_dependent_param_type, 11408 diag::err_operator_new_param_type)) 11409 return true; 11410 11411 // C++ [basic.stc.dynamic.allocation]p1: 11412 // The first parameter shall not have an associated default argument. 11413 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11414 return SemaRef.Diag(FnDecl->getLocation(), 11415 diag::err_operator_new_default_arg) 11416 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11417 11418 return false; 11419 } 11420 11421 static bool 11422 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11423 // C++ [basic.stc.dynamic.deallocation]p1: 11424 // A program is ill-formed if deallocation functions are declared in a 11425 // namespace scope other than global scope or declared static in global 11426 // scope. 11427 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11428 return true; 11429 11430 // C++ [basic.stc.dynamic.deallocation]p2: 11431 // Each deallocation function shall return void and its first parameter 11432 // shall be void*. 11433 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11434 SemaRef.Context.VoidPtrTy, 11435 diag::err_operator_delete_dependent_param_type, 11436 diag::err_operator_delete_param_type)) 11437 return true; 11438 11439 return false; 11440 } 11441 11442 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11443 /// of this overloaded operator is well-formed. If so, returns false; 11444 /// otherwise, emits appropriate diagnostics and returns true. 11445 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11446 assert(FnDecl && FnDecl->isOverloadedOperator() && 11447 "Expected an overloaded operator declaration"); 11448 11449 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11450 11451 // C++ [over.oper]p5: 11452 // The allocation and deallocation functions, operator new, 11453 // operator new[], operator delete and operator delete[], are 11454 // described completely in 3.7.3. The attributes and restrictions 11455 // found in the rest of this subclause do not apply to them unless 11456 // explicitly stated in 3.7.3. 11457 if (Op == OO_Delete || Op == OO_Array_Delete) 11458 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11459 11460 if (Op == OO_New || Op == OO_Array_New) 11461 return CheckOperatorNewDeclaration(*this, FnDecl); 11462 11463 // C++ [over.oper]p6: 11464 // An operator function shall either be a non-static member 11465 // function or be a non-member function and have at least one 11466 // parameter whose type is a class, a reference to a class, an 11467 // enumeration, or a reference to an enumeration. 11468 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11469 if (MethodDecl->isStatic()) 11470 return Diag(FnDecl->getLocation(), 11471 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11472 } else { 11473 bool ClassOrEnumParam = false; 11474 for (auto Param : FnDecl->params()) { 11475 QualType ParamType = Param->getType().getNonReferenceType(); 11476 if (ParamType->isDependentType() || ParamType->isRecordType() || 11477 ParamType->isEnumeralType()) { 11478 ClassOrEnumParam = true; 11479 break; 11480 } 11481 } 11482 11483 if (!ClassOrEnumParam) 11484 return Diag(FnDecl->getLocation(), 11485 diag::err_operator_overload_needs_class_or_enum) 11486 << FnDecl->getDeclName(); 11487 } 11488 11489 // C++ [over.oper]p8: 11490 // An operator function cannot have default arguments (8.3.6), 11491 // except where explicitly stated below. 11492 // 11493 // Only the function-call operator allows default arguments 11494 // (C++ [over.call]p1). 11495 if (Op != OO_Call) { 11496 for (auto Param : FnDecl->params()) { 11497 if (Param->hasDefaultArg()) 11498 return Diag(Param->getLocation(), 11499 diag::err_operator_overload_default_arg) 11500 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11501 } 11502 } 11503 11504 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11505 { false, false, false } 11506 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11507 , { Unary, Binary, MemberOnly } 11508 #include "clang/Basic/OperatorKinds.def" 11509 }; 11510 11511 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11512 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11513 bool MustBeMemberOperator = OperatorUses[Op][2]; 11514 11515 // C++ [over.oper]p8: 11516 // [...] Operator functions cannot have more or fewer parameters 11517 // than the number required for the corresponding operator, as 11518 // described in the rest of this subclause. 11519 unsigned NumParams = FnDecl->getNumParams() 11520 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11521 if (Op != OO_Call && 11522 ((NumParams == 1 && !CanBeUnaryOperator) || 11523 (NumParams == 2 && !CanBeBinaryOperator) || 11524 (NumParams < 1) || (NumParams > 2))) { 11525 // We have the wrong number of parameters. 11526 unsigned ErrorKind; 11527 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11528 ErrorKind = 2; // 2 -> unary or binary. 11529 } else if (CanBeUnaryOperator) { 11530 ErrorKind = 0; // 0 -> unary 11531 } else { 11532 assert(CanBeBinaryOperator && 11533 "All non-call overloaded operators are unary or binary!"); 11534 ErrorKind = 1; // 1 -> binary 11535 } 11536 11537 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11538 << FnDecl->getDeclName() << NumParams << ErrorKind; 11539 } 11540 11541 // Overloaded operators other than operator() cannot be variadic. 11542 if (Op != OO_Call && 11543 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11544 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11545 << FnDecl->getDeclName(); 11546 } 11547 11548 // Some operators must be non-static member functions. 11549 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11550 return Diag(FnDecl->getLocation(), 11551 diag::err_operator_overload_must_be_member) 11552 << FnDecl->getDeclName(); 11553 } 11554 11555 // C++ [over.inc]p1: 11556 // The user-defined function called operator++ implements the 11557 // prefix and postfix ++ operator. If this function is a member 11558 // function with no parameters, or a non-member function with one 11559 // parameter of class or enumeration type, it defines the prefix 11560 // increment operator ++ for objects of that type. If the function 11561 // is a member function with one parameter (which shall be of type 11562 // int) or a non-member function with two parameters (the second 11563 // of which shall be of type int), it defines the postfix 11564 // increment operator ++ for objects of that type. 11565 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11566 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11567 QualType ParamType = LastParam->getType(); 11568 11569 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11570 !ParamType->isDependentType()) 11571 return Diag(LastParam->getLocation(), 11572 diag::err_operator_overload_post_incdec_must_be_int) 11573 << LastParam->getType() << (Op == OO_MinusMinus); 11574 } 11575 11576 return false; 11577 } 11578 11579 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11580 /// of this literal operator function is well-formed. If so, returns 11581 /// false; otherwise, emits appropriate diagnostics and returns true. 11582 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11583 if (isa<CXXMethodDecl>(FnDecl)) { 11584 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11585 << FnDecl->getDeclName(); 11586 return true; 11587 } 11588 11589 if (FnDecl->isExternC()) { 11590 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11591 return true; 11592 } 11593 11594 bool Valid = false; 11595 11596 // This might be the definition of a literal operator template. 11597 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11598 // This might be a specialization of a literal operator template. 11599 if (!TpDecl) 11600 TpDecl = FnDecl->getPrimaryTemplate(); 11601 11602 // template <char...> type operator "" name() and 11603 // template <class T, T...> type operator "" name() are the only valid 11604 // template signatures, and the only valid signatures with no parameters. 11605 if (TpDecl) { 11606 if (FnDecl->param_size() == 0) { 11607 // Must have one or two template parameters 11608 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11609 if (Params->size() == 1) { 11610 NonTypeTemplateParmDecl *PmDecl = 11611 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11612 11613 // The template parameter must be a char parameter pack. 11614 if (PmDecl && PmDecl->isTemplateParameterPack() && 11615 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11616 Valid = true; 11617 } else if (Params->size() == 2) { 11618 TemplateTypeParmDecl *PmType = 11619 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11620 NonTypeTemplateParmDecl *PmArgs = 11621 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11622 11623 // The second template parameter must be a parameter pack with the 11624 // first template parameter as its type. 11625 if (PmType && PmArgs && 11626 !PmType->isTemplateParameterPack() && 11627 PmArgs->isTemplateParameterPack()) { 11628 const TemplateTypeParmType *TArgs = 11629 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11630 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11631 TArgs->getIndex() == PmType->getIndex()) { 11632 Valid = true; 11633 if (ActiveTemplateInstantiations.empty()) 11634 Diag(FnDecl->getLocation(), 11635 diag::ext_string_literal_operator_template); 11636 } 11637 } 11638 } 11639 } 11640 } else if (FnDecl->param_size()) { 11641 // Check the first parameter 11642 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11643 11644 QualType T = (*Param)->getType().getUnqualifiedType(); 11645 11646 // unsigned long long int, long double, and any character type are allowed 11647 // as the only parameters. 11648 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11649 Context.hasSameType(T, Context.LongDoubleTy) || 11650 Context.hasSameType(T, Context.CharTy) || 11651 Context.hasSameType(T, Context.WideCharTy) || 11652 Context.hasSameType(T, Context.Char16Ty) || 11653 Context.hasSameType(T, Context.Char32Ty)) { 11654 if (++Param == FnDecl->param_end()) 11655 Valid = true; 11656 goto FinishedParams; 11657 } 11658 11659 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11660 const PointerType *PT = T->getAs<PointerType>(); 11661 if (!PT) 11662 goto FinishedParams; 11663 T = PT->getPointeeType(); 11664 if (!T.isConstQualified() || T.isVolatileQualified()) 11665 goto FinishedParams; 11666 T = T.getUnqualifiedType(); 11667 11668 // Move on to the second parameter; 11669 ++Param; 11670 11671 // If there is no second parameter, the first must be a const char * 11672 if (Param == FnDecl->param_end()) { 11673 if (Context.hasSameType(T, Context.CharTy)) 11674 Valid = true; 11675 goto FinishedParams; 11676 } 11677 11678 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11679 // are allowed as the first parameter to a two-parameter function 11680 if (!(Context.hasSameType(T, Context.CharTy) || 11681 Context.hasSameType(T, Context.WideCharTy) || 11682 Context.hasSameType(T, Context.Char16Ty) || 11683 Context.hasSameType(T, Context.Char32Ty))) 11684 goto FinishedParams; 11685 11686 // The second and final parameter must be an std::size_t 11687 T = (*Param)->getType().getUnqualifiedType(); 11688 if (Context.hasSameType(T, Context.getSizeType()) && 11689 ++Param == FnDecl->param_end()) 11690 Valid = true; 11691 } 11692 11693 // FIXME: This diagnostic is absolutely terrible. 11694 FinishedParams: 11695 if (!Valid) { 11696 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11697 << FnDecl->getDeclName(); 11698 return true; 11699 } 11700 11701 // A parameter-declaration-clause containing a default argument is not 11702 // equivalent to any of the permitted forms. 11703 for (auto Param : FnDecl->params()) { 11704 if (Param->hasDefaultArg()) { 11705 Diag(Param->getDefaultArgRange().getBegin(), 11706 diag::err_literal_operator_default_argument) 11707 << Param->getDefaultArgRange(); 11708 break; 11709 } 11710 } 11711 11712 StringRef LiteralName 11713 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11714 if (LiteralName[0] != '_') { 11715 // C++11 [usrlit.suffix]p1: 11716 // Literal suffix identifiers that do not start with an underscore 11717 // are reserved for future standardization. 11718 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11719 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11720 } 11721 11722 return false; 11723 } 11724 11725 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11726 /// linkage specification, including the language and (if present) 11727 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11728 /// language string literal. LBraceLoc, if valid, provides the location of 11729 /// the '{' brace. Otherwise, this linkage specification does not 11730 /// have any braces. 11731 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11732 Expr *LangStr, 11733 SourceLocation LBraceLoc) { 11734 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11735 if (!Lit->isAscii()) { 11736 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11737 << LangStr->getSourceRange(); 11738 return nullptr; 11739 } 11740 11741 StringRef Lang = Lit->getString(); 11742 LinkageSpecDecl::LanguageIDs Language; 11743 if (Lang == "C") 11744 Language = LinkageSpecDecl::lang_c; 11745 else if (Lang == "C++") 11746 Language = LinkageSpecDecl::lang_cxx; 11747 else { 11748 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11749 << LangStr->getSourceRange(); 11750 return nullptr; 11751 } 11752 11753 // FIXME: Add all the various semantics of linkage specifications 11754 11755 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11756 LangStr->getExprLoc(), Language, 11757 LBraceLoc.isValid()); 11758 CurContext->addDecl(D); 11759 PushDeclContext(S, D); 11760 return D; 11761 } 11762 11763 /// ActOnFinishLinkageSpecification - Complete the definition of 11764 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11765 /// valid, it's the position of the closing '}' brace in a linkage 11766 /// specification that uses braces. 11767 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11768 Decl *LinkageSpec, 11769 SourceLocation RBraceLoc) { 11770 if (RBraceLoc.isValid()) { 11771 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11772 LSDecl->setRBraceLoc(RBraceLoc); 11773 } 11774 PopDeclContext(); 11775 return LinkageSpec; 11776 } 11777 11778 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11779 AttributeList *AttrList, 11780 SourceLocation SemiLoc) { 11781 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11782 // Attribute declarations appertain to empty declaration so we handle 11783 // them here. 11784 if (AttrList) 11785 ProcessDeclAttributeList(S, ED, AttrList); 11786 11787 CurContext->addDecl(ED); 11788 return ED; 11789 } 11790 11791 /// \brief Perform semantic analysis for the variable declaration that 11792 /// occurs within a C++ catch clause, returning the newly-created 11793 /// variable. 11794 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11795 TypeSourceInfo *TInfo, 11796 SourceLocation StartLoc, 11797 SourceLocation Loc, 11798 IdentifierInfo *Name) { 11799 bool Invalid = false; 11800 QualType ExDeclType = TInfo->getType(); 11801 11802 // Arrays and functions decay. 11803 if (ExDeclType->isArrayType()) 11804 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11805 else if (ExDeclType->isFunctionType()) 11806 ExDeclType = Context.getPointerType(ExDeclType); 11807 11808 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11809 // The exception-declaration shall not denote a pointer or reference to an 11810 // incomplete type, other than [cv] void*. 11811 // N2844 forbids rvalue references. 11812 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11813 Diag(Loc, diag::err_catch_rvalue_ref); 11814 Invalid = true; 11815 } 11816 11817 QualType BaseType = ExDeclType; 11818 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11819 unsigned DK = diag::err_catch_incomplete; 11820 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11821 BaseType = Ptr->getPointeeType(); 11822 Mode = 1; 11823 DK = diag::err_catch_incomplete_ptr; 11824 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11825 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11826 BaseType = Ref->getPointeeType(); 11827 Mode = 2; 11828 DK = diag::err_catch_incomplete_ref; 11829 } 11830 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11831 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11832 Invalid = true; 11833 11834 if (!Invalid && !ExDeclType->isDependentType() && 11835 RequireNonAbstractType(Loc, ExDeclType, 11836 diag::err_abstract_type_in_decl, 11837 AbstractVariableType)) 11838 Invalid = true; 11839 11840 // Only the non-fragile NeXT runtime currently supports C++ catches 11841 // of ObjC types, and no runtime supports catching ObjC types by value. 11842 if (!Invalid && getLangOpts().ObjC1) { 11843 QualType T = ExDeclType; 11844 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11845 T = RT->getPointeeType(); 11846 11847 if (T->isObjCObjectType()) { 11848 Diag(Loc, diag::err_objc_object_catch); 11849 Invalid = true; 11850 } else if (T->isObjCObjectPointerType()) { 11851 // FIXME: should this be a test for macosx-fragile specifically? 11852 if (getLangOpts().ObjCRuntime.isFragile()) 11853 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11854 } 11855 } 11856 11857 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11858 ExDeclType, TInfo, SC_None); 11859 ExDecl->setExceptionVariable(true); 11860 11861 // In ARC, infer 'retaining' for variables of retainable type. 11862 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11863 Invalid = true; 11864 11865 if (!Invalid && !ExDeclType->isDependentType()) { 11866 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11867 // Insulate this from anything else we might currently be parsing. 11868 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11869 11870 // C++ [except.handle]p16: 11871 // The object declared in an exception-declaration or, if the 11872 // exception-declaration does not specify a name, a temporary (12.2) is 11873 // copy-initialized (8.5) from the exception object. [...] 11874 // The object is destroyed when the handler exits, after the destruction 11875 // of any automatic objects initialized within the handler. 11876 // 11877 // We just pretend to initialize the object with itself, then make sure 11878 // it can be destroyed later. 11879 QualType initType = ExDeclType; 11880 11881 InitializedEntity entity = 11882 InitializedEntity::InitializeVariable(ExDecl); 11883 InitializationKind initKind = 11884 InitializationKind::CreateCopy(Loc, SourceLocation()); 11885 11886 Expr *opaqueValue = 11887 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11888 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11889 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11890 if (result.isInvalid()) 11891 Invalid = true; 11892 else { 11893 // If the constructor used was non-trivial, set this as the 11894 // "initializer". 11895 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11896 if (!construct->getConstructor()->isTrivial()) { 11897 Expr *init = MaybeCreateExprWithCleanups(construct); 11898 ExDecl->setInit(init); 11899 } 11900 11901 // And make sure it's destructable. 11902 FinalizeVarWithDestructor(ExDecl, recordType); 11903 } 11904 } 11905 } 11906 11907 if (Invalid) 11908 ExDecl->setInvalidDecl(); 11909 11910 return ExDecl; 11911 } 11912 11913 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11914 /// handler. 11915 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11916 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11917 bool Invalid = D.isInvalidType(); 11918 11919 // Check for unexpanded parameter packs. 11920 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11921 UPPC_ExceptionType)) { 11922 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11923 D.getIdentifierLoc()); 11924 Invalid = true; 11925 } 11926 11927 IdentifierInfo *II = D.getIdentifier(); 11928 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11929 LookupOrdinaryName, 11930 ForRedeclaration)) { 11931 // The scope should be freshly made just for us. There is just no way 11932 // it contains any previous declaration, except for function parameters in 11933 // a function-try-block's catch statement. 11934 assert(!S->isDeclScope(PrevDecl)); 11935 if (isDeclInScope(PrevDecl, CurContext, S)) { 11936 Diag(D.getIdentifierLoc(), diag::err_redefinition) 11937 << D.getIdentifier(); 11938 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11939 Invalid = true; 11940 } else if (PrevDecl->isTemplateParameter()) 11941 // Maybe we will complain about the shadowed template parameter. 11942 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11943 } 11944 11945 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11946 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11947 << D.getCXXScopeSpec().getRange(); 11948 Invalid = true; 11949 } 11950 11951 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11952 D.getLocStart(), 11953 D.getIdentifierLoc(), 11954 D.getIdentifier()); 11955 if (Invalid) 11956 ExDecl->setInvalidDecl(); 11957 11958 // Add the exception declaration into this scope. 11959 if (II) 11960 PushOnScopeChains(ExDecl, S); 11961 else 11962 CurContext->addDecl(ExDecl); 11963 11964 ProcessDeclAttributes(S, ExDecl, D); 11965 return ExDecl; 11966 } 11967 11968 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11969 Expr *AssertExpr, 11970 Expr *AssertMessageExpr, 11971 SourceLocation RParenLoc) { 11972 StringLiteral *AssertMessage = 11973 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 11974 11975 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11976 return nullptr; 11977 11978 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11979 AssertMessage, RParenLoc, false); 11980 } 11981 11982 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11983 Expr *AssertExpr, 11984 StringLiteral *AssertMessage, 11985 SourceLocation RParenLoc, 11986 bool Failed) { 11987 assert(AssertExpr != nullptr && "Expected non-null condition"); 11988 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11989 !Failed) { 11990 // In a static_assert-declaration, the constant-expression shall be a 11991 // constant expression that can be contextually converted to bool. 11992 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11993 if (Converted.isInvalid()) 11994 Failed = true; 11995 11996 llvm::APSInt Cond; 11997 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11998 diag::err_static_assert_expression_is_not_constant, 11999 /*AllowFold=*/false).isInvalid()) 12000 Failed = true; 12001 12002 if (!Failed && !Cond) { 12003 SmallString<256> MsgBuffer; 12004 llvm::raw_svector_ostream Msg(MsgBuffer); 12005 if (AssertMessage) 12006 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 12007 Diag(StaticAssertLoc, diag::err_static_assert_failed) 12008 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 12009 Failed = true; 12010 } 12011 } 12012 12013 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 12014 AssertExpr, AssertMessage, RParenLoc, 12015 Failed); 12016 12017 CurContext->addDecl(Decl); 12018 return Decl; 12019 } 12020 12021 /// \brief Perform semantic analysis of the given friend type declaration. 12022 /// 12023 /// \returns A friend declaration that. 12024 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 12025 SourceLocation FriendLoc, 12026 TypeSourceInfo *TSInfo) { 12027 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 12028 12029 QualType T = TSInfo->getType(); 12030 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 12031 12032 // C++03 [class.friend]p2: 12033 // An elaborated-type-specifier shall be used in a friend declaration 12034 // for a class.* 12035 // 12036 // * The class-key of the elaborated-type-specifier is required. 12037 if (!ActiveTemplateInstantiations.empty()) { 12038 // Do not complain about the form of friend template types during 12039 // template instantiation; we will already have complained when the 12040 // template was declared. 12041 } else { 12042 if (!T->isElaboratedTypeSpecifier()) { 12043 // If we evaluated the type to a record type, suggest putting 12044 // a tag in front. 12045 if (const RecordType *RT = T->getAs<RecordType>()) { 12046 RecordDecl *RD = RT->getDecl(); 12047 12048 SmallString<16> InsertionText(" "); 12049 InsertionText += RD->getKindName(); 12050 12051 Diag(TypeRange.getBegin(), 12052 getLangOpts().CPlusPlus11 ? 12053 diag::warn_cxx98_compat_unelaborated_friend_type : 12054 diag::ext_unelaborated_friend_type) 12055 << (unsigned) RD->getTagKind() 12056 << T 12057 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 12058 InsertionText); 12059 } else { 12060 Diag(FriendLoc, 12061 getLangOpts().CPlusPlus11 ? 12062 diag::warn_cxx98_compat_nonclass_type_friend : 12063 diag::ext_nonclass_type_friend) 12064 << T 12065 << TypeRange; 12066 } 12067 } else if (T->getAs<EnumType>()) { 12068 Diag(FriendLoc, 12069 getLangOpts().CPlusPlus11 ? 12070 diag::warn_cxx98_compat_enum_friend : 12071 diag::ext_enum_friend) 12072 << T 12073 << TypeRange; 12074 } 12075 12076 // C++11 [class.friend]p3: 12077 // A friend declaration that does not declare a function shall have one 12078 // of the following forms: 12079 // friend elaborated-type-specifier ; 12080 // friend simple-type-specifier ; 12081 // friend typename-specifier ; 12082 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12083 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12084 } 12085 12086 // If the type specifier in a friend declaration designates a (possibly 12087 // cv-qualified) class type, that class is declared as a friend; otherwise, 12088 // the friend declaration is ignored. 12089 return FriendDecl::Create(Context, CurContext, 12090 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12091 FriendLoc); 12092 } 12093 12094 /// Handle a friend tag declaration where the scope specifier was 12095 /// templated. 12096 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12097 unsigned TagSpec, SourceLocation TagLoc, 12098 CXXScopeSpec &SS, 12099 IdentifierInfo *Name, 12100 SourceLocation NameLoc, 12101 AttributeList *Attr, 12102 MultiTemplateParamsArg TempParamLists) { 12103 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12104 12105 bool isExplicitSpecialization = false; 12106 bool Invalid = false; 12107 12108 if (TemplateParameterList *TemplateParams = 12109 MatchTemplateParametersToScopeSpecifier( 12110 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12111 isExplicitSpecialization, Invalid)) { 12112 if (TemplateParams->size() > 0) { 12113 // This is a declaration of a class template. 12114 if (Invalid) 12115 return nullptr; 12116 12117 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12118 NameLoc, Attr, TemplateParams, AS_public, 12119 /*ModulePrivateLoc=*/SourceLocation(), 12120 FriendLoc, TempParamLists.size() - 1, 12121 TempParamLists.data()).get(); 12122 } else { 12123 // The "template<>" header is extraneous. 12124 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12125 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12126 isExplicitSpecialization = true; 12127 } 12128 } 12129 12130 if (Invalid) return nullptr; 12131 12132 bool isAllExplicitSpecializations = true; 12133 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12134 if (TempParamLists[I]->size()) { 12135 isAllExplicitSpecializations = false; 12136 break; 12137 } 12138 } 12139 12140 // FIXME: don't ignore attributes. 12141 12142 // If it's explicit specializations all the way down, just forget 12143 // about the template header and build an appropriate non-templated 12144 // friend. TODO: for source fidelity, remember the headers. 12145 if (isAllExplicitSpecializations) { 12146 if (SS.isEmpty()) { 12147 bool Owned = false; 12148 bool IsDependent = false; 12149 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12150 Attr, AS_public, 12151 /*ModulePrivateLoc=*/SourceLocation(), 12152 MultiTemplateParamsArg(), Owned, IsDependent, 12153 /*ScopedEnumKWLoc=*/SourceLocation(), 12154 /*ScopedEnumUsesClassTag=*/false, 12155 /*UnderlyingType=*/TypeResult(), 12156 /*IsTypeSpecifier=*/false); 12157 } 12158 12159 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12160 ElaboratedTypeKeyword Keyword 12161 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12162 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12163 *Name, NameLoc); 12164 if (T.isNull()) 12165 return nullptr; 12166 12167 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12168 if (isa<DependentNameType>(T)) { 12169 DependentNameTypeLoc TL = 12170 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12171 TL.setElaboratedKeywordLoc(TagLoc); 12172 TL.setQualifierLoc(QualifierLoc); 12173 TL.setNameLoc(NameLoc); 12174 } else { 12175 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12176 TL.setElaboratedKeywordLoc(TagLoc); 12177 TL.setQualifierLoc(QualifierLoc); 12178 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12179 } 12180 12181 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12182 TSI, FriendLoc, TempParamLists); 12183 Friend->setAccess(AS_public); 12184 CurContext->addDecl(Friend); 12185 return Friend; 12186 } 12187 12188 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12189 12190 12191 12192 // Handle the case of a templated-scope friend class. e.g. 12193 // template <class T> class A<T>::B; 12194 // FIXME: we don't support these right now. 12195 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12196 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12197 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12198 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12199 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12200 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12201 TL.setElaboratedKeywordLoc(TagLoc); 12202 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12203 TL.setNameLoc(NameLoc); 12204 12205 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12206 TSI, FriendLoc, TempParamLists); 12207 Friend->setAccess(AS_public); 12208 Friend->setUnsupportedFriend(true); 12209 CurContext->addDecl(Friend); 12210 return Friend; 12211 } 12212 12213 12214 /// Handle a friend type declaration. This works in tandem with 12215 /// ActOnTag. 12216 /// 12217 /// Notes on friend class templates: 12218 /// 12219 /// We generally treat friend class declarations as if they were 12220 /// declaring a class. So, for example, the elaborated type specifier 12221 /// in a friend declaration is required to obey the restrictions of a 12222 /// class-head (i.e. no typedefs in the scope chain), template 12223 /// parameters are required to match up with simple template-ids, &c. 12224 /// However, unlike when declaring a template specialization, it's 12225 /// okay to refer to a template specialization without an empty 12226 /// template parameter declaration, e.g. 12227 /// friend class A<T>::B<unsigned>; 12228 /// We permit this as a special case; if there are any template 12229 /// parameters present at all, require proper matching, i.e. 12230 /// template <> template \<class T> friend class A<int>::B; 12231 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12232 MultiTemplateParamsArg TempParams) { 12233 SourceLocation Loc = DS.getLocStart(); 12234 12235 assert(DS.isFriendSpecified()); 12236 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12237 12238 // Try to convert the decl specifier to a type. This works for 12239 // friend templates because ActOnTag never produces a ClassTemplateDecl 12240 // for a TUK_Friend. 12241 Declarator TheDeclarator(DS, Declarator::MemberContext); 12242 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12243 QualType T = TSI->getType(); 12244 if (TheDeclarator.isInvalidType()) 12245 return nullptr; 12246 12247 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12248 return nullptr; 12249 12250 // This is definitely an error in C++98. It's probably meant to 12251 // be forbidden in C++0x, too, but the specification is just 12252 // poorly written. 12253 // 12254 // The problem is with declarations like the following: 12255 // template <T> friend A<T>::foo; 12256 // where deciding whether a class C is a friend or not now hinges 12257 // on whether there exists an instantiation of A that causes 12258 // 'foo' to equal C. There are restrictions on class-heads 12259 // (which we declare (by fiat) elaborated friend declarations to 12260 // be) that makes this tractable. 12261 // 12262 // FIXME: handle "template <> friend class A<T>;", which 12263 // is possibly well-formed? Who even knows? 12264 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12265 Diag(Loc, diag::err_tagless_friend_type_template) 12266 << DS.getSourceRange(); 12267 return nullptr; 12268 } 12269 12270 // C++98 [class.friend]p1: A friend of a class is a function 12271 // or class that is not a member of the class . . . 12272 // This is fixed in DR77, which just barely didn't make the C++03 12273 // deadline. It's also a very silly restriction that seriously 12274 // affects inner classes and which nobody else seems to implement; 12275 // thus we never diagnose it, not even in -pedantic. 12276 // 12277 // But note that we could warn about it: it's always useless to 12278 // friend one of your own members (it's not, however, worthless to 12279 // friend a member of an arbitrary specialization of your template). 12280 12281 Decl *D; 12282 if (unsigned NumTempParamLists = TempParams.size()) 12283 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12284 NumTempParamLists, 12285 TempParams.data(), 12286 TSI, 12287 DS.getFriendSpecLoc()); 12288 else 12289 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12290 12291 if (!D) 12292 return nullptr; 12293 12294 D->setAccess(AS_public); 12295 CurContext->addDecl(D); 12296 12297 return D; 12298 } 12299 12300 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12301 MultiTemplateParamsArg TemplateParams) { 12302 const DeclSpec &DS = D.getDeclSpec(); 12303 12304 assert(DS.isFriendSpecified()); 12305 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12306 12307 SourceLocation Loc = D.getIdentifierLoc(); 12308 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12309 12310 // C++ [class.friend]p1 12311 // A friend of a class is a function or class.... 12312 // Note that this sees through typedefs, which is intended. 12313 // It *doesn't* see through dependent types, which is correct 12314 // according to [temp.arg.type]p3: 12315 // If a declaration acquires a function type through a 12316 // type dependent on a template-parameter and this causes 12317 // a declaration that does not use the syntactic form of a 12318 // function declarator to have a function type, the program 12319 // is ill-formed. 12320 if (!TInfo->getType()->isFunctionType()) { 12321 Diag(Loc, diag::err_unexpected_friend); 12322 12323 // It might be worthwhile to try to recover by creating an 12324 // appropriate declaration. 12325 return nullptr; 12326 } 12327 12328 // C++ [namespace.memdef]p3 12329 // - If a friend declaration in a non-local class first declares a 12330 // class or function, the friend class or function is a member 12331 // of the innermost enclosing namespace. 12332 // - The name of the friend is not found by simple name lookup 12333 // until a matching declaration is provided in that namespace 12334 // scope (either before or after the class declaration granting 12335 // friendship). 12336 // - If a friend function is called, its name may be found by the 12337 // name lookup that considers functions from namespaces and 12338 // classes associated with the types of the function arguments. 12339 // - When looking for a prior declaration of a class or a function 12340 // declared as a friend, scopes outside the innermost enclosing 12341 // namespace scope are not considered. 12342 12343 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12344 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12345 DeclarationName Name = NameInfo.getName(); 12346 assert(Name); 12347 12348 // Check for unexpanded parameter packs. 12349 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12350 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12351 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12352 return nullptr; 12353 12354 // The context we found the declaration in, or in which we should 12355 // create the declaration. 12356 DeclContext *DC; 12357 Scope *DCScope = S; 12358 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12359 ForRedeclaration); 12360 12361 // There are five cases here. 12362 // - There's no scope specifier and we're in a local class. Only look 12363 // for functions declared in the immediately-enclosing block scope. 12364 // We recover from invalid scope qualifiers as if they just weren't there. 12365 FunctionDecl *FunctionContainingLocalClass = nullptr; 12366 if ((SS.isInvalid() || !SS.isSet()) && 12367 (FunctionContainingLocalClass = 12368 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12369 // C++11 [class.friend]p11: 12370 // If a friend declaration appears in a local class and the name 12371 // specified is an unqualified name, a prior declaration is 12372 // looked up without considering scopes that are outside the 12373 // innermost enclosing non-class scope. For a friend function 12374 // declaration, if there is no prior declaration, the program is 12375 // ill-formed. 12376 12377 // Find the innermost enclosing non-class scope. This is the block 12378 // scope containing the local class definition (or for a nested class, 12379 // the outer local class). 12380 DCScope = S->getFnParent(); 12381 12382 // Look up the function name in the scope. 12383 Previous.clear(LookupLocalFriendName); 12384 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12385 12386 if (!Previous.empty()) { 12387 // All possible previous declarations must have the same context: 12388 // either they were declared at block scope or they are members of 12389 // one of the enclosing local classes. 12390 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12391 } else { 12392 // This is ill-formed, but provide the context that we would have 12393 // declared the function in, if we were permitted to, for error recovery. 12394 DC = FunctionContainingLocalClass; 12395 } 12396 adjustContextForLocalExternDecl(DC); 12397 12398 // C++ [class.friend]p6: 12399 // A function can be defined in a friend declaration of a class if and 12400 // only if the class is a non-local class (9.8), the function name is 12401 // unqualified, and the function has namespace scope. 12402 if (D.isFunctionDefinition()) { 12403 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12404 } 12405 12406 // - There's no scope specifier, in which case we just go to the 12407 // appropriate scope and look for a function or function template 12408 // there as appropriate. 12409 } else if (SS.isInvalid() || !SS.isSet()) { 12410 // C++11 [namespace.memdef]p3: 12411 // If the name in a friend declaration is neither qualified nor 12412 // a template-id and the declaration is a function or an 12413 // elaborated-type-specifier, the lookup to determine whether 12414 // the entity has been previously declared shall not consider 12415 // any scopes outside the innermost enclosing namespace. 12416 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12417 12418 // Find the appropriate context according to the above. 12419 DC = CurContext; 12420 12421 // Skip class contexts. If someone can cite chapter and verse 12422 // for this behavior, that would be nice --- it's what GCC and 12423 // EDG do, and it seems like a reasonable intent, but the spec 12424 // really only says that checks for unqualified existing 12425 // declarations should stop at the nearest enclosing namespace, 12426 // not that they should only consider the nearest enclosing 12427 // namespace. 12428 while (DC->isRecord()) 12429 DC = DC->getParent(); 12430 12431 DeclContext *LookupDC = DC; 12432 while (LookupDC->isTransparentContext()) 12433 LookupDC = LookupDC->getParent(); 12434 12435 while (true) { 12436 LookupQualifiedName(Previous, LookupDC); 12437 12438 if (!Previous.empty()) { 12439 DC = LookupDC; 12440 break; 12441 } 12442 12443 if (isTemplateId) { 12444 if (isa<TranslationUnitDecl>(LookupDC)) break; 12445 } else { 12446 if (LookupDC->isFileContext()) break; 12447 } 12448 LookupDC = LookupDC->getParent(); 12449 } 12450 12451 DCScope = getScopeForDeclContext(S, DC); 12452 12453 // - There's a non-dependent scope specifier, in which case we 12454 // compute it and do a previous lookup there for a function 12455 // or function template. 12456 } else if (!SS.getScopeRep()->isDependent()) { 12457 DC = computeDeclContext(SS); 12458 if (!DC) return nullptr; 12459 12460 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12461 12462 LookupQualifiedName(Previous, DC); 12463 12464 // Ignore things found implicitly in the wrong scope. 12465 // TODO: better diagnostics for this case. Suggesting the right 12466 // qualified scope would be nice... 12467 LookupResult::Filter F = Previous.makeFilter(); 12468 while (F.hasNext()) { 12469 NamedDecl *D = F.next(); 12470 if (!DC->InEnclosingNamespaceSetOf( 12471 D->getDeclContext()->getRedeclContext())) 12472 F.erase(); 12473 } 12474 F.done(); 12475 12476 if (Previous.empty()) { 12477 D.setInvalidType(); 12478 Diag(Loc, diag::err_qualified_friend_not_found) 12479 << Name << TInfo->getType(); 12480 return nullptr; 12481 } 12482 12483 // C++ [class.friend]p1: A friend of a class is a function or 12484 // class that is not a member of the class . . . 12485 if (DC->Equals(CurContext)) 12486 Diag(DS.getFriendSpecLoc(), 12487 getLangOpts().CPlusPlus11 ? 12488 diag::warn_cxx98_compat_friend_is_member : 12489 diag::err_friend_is_member); 12490 12491 if (D.isFunctionDefinition()) { 12492 // C++ [class.friend]p6: 12493 // A function can be defined in a friend declaration of a class if and 12494 // only if the class is a non-local class (9.8), the function name is 12495 // unqualified, and the function has namespace scope. 12496 SemaDiagnosticBuilder DB 12497 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12498 12499 DB << SS.getScopeRep(); 12500 if (DC->isFileContext()) 12501 DB << FixItHint::CreateRemoval(SS.getRange()); 12502 SS.clear(); 12503 } 12504 12505 // - There's a scope specifier that does not match any template 12506 // parameter lists, in which case we use some arbitrary context, 12507 // create a method or method template, and wait for instantiation. 12508 // - There's a scope specifier that does match some template 12509 // parameter lists, which we don't handle right now. 12510 } else { 12511 if (D.isFunctionDefinition()) { 12512 // C++ [class.friend]p6: 12513 // A function can be defined in a friend declaration of a class if and 12514 // only if the class is a non-local class (9.8), the function name is 12515 // unqualified, and the function has namespace scope. 12516 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12517 << SS.getScopeRep(); 12518 } 12519 12520 DC = CurContext; 12521 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12522 } 12523 12524 if (!DC->isRecord()) { 12525 // This implies that it has to be an operator or function. 12526 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12527 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12528 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12529 Diag(Loc, diag::err_introducing_special_friend) << 12530 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12531 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12532 return nullptr; 12533 } 12534 } 12535 12536 // FIXME: This is an egregious hack to cope with cases where the scope stack 12537 // does not contain the declaration context, i.e., in an out-of-line 12538 // definition of a class. 12539 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12540 if (!DCScope) { 12541 FakeDCScope.setEntity(DC); 12542 DCScope = &FakeDCScope; 12543 } 12544 12545 bool AddToScope = true; 12546 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12547 TemplateParams, AddToScope); 12548 if (!ND) return nullptr; 12549 12550 assert(ND->getLexicalDeclContext() == CurContext); 12551 12552 // If we performed typo correction, we might have added a scope specifier 12553 // and changed the decl context. 12554 DC = ND->getDeclContext(); 12555 12556 // Add the function declaration to the appropriate lookup tables, 12557 // adjusting the redeclarations list as necessary. We don't 12558 // want to do this yet if the friending class is dependent. 12559 // 12560 // Also update the scope-based lookup if the target context's 12561 // lookup context is in lexical scope. 12562 if (!CurContext->isDependentContext()) { 12563 DC = DC->getRedeclContext(); 12564 DC->makeDeclVisibleInContext(ND); 12565 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12566 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12567 } 12568 12569 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12570 D.getIdentifierLoc(), ND, 12571 DS.getFriendSpecLoc()); 12572 FrD->setAccess(AS_public); 12573 CurContext->addDecl(FrD); 12574 12575 if (ND->isInvalidDecl()) { 12576 FrD->setInvalidDecl(); 12577 } else { 12578 if (DC->isRecord()) CheckFriendAccess(ND); 12579 12580 FunctionDecl *FD; 12581 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12582 FD = FTD->getTemplatedDecl(); 12583 else 12584 FD = cast<FunctionDecl>(ND); 12585 12586 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12587 // default argument expression, that declaration shall be a definition 12588 // and shall be the only declaration of the function or function 12589 // template in the translation unit. 12590 if (functionDeclHasDefaultArgument(FD)) { 12591 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12592 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12593 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12594 } else if (!D.isFunctionDefinition()) 12595 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12596 } 12597 12598 // Mark templated-scope function declarations as unsupported. 12599 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12600 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12601 << SS.getScopeRep() << SS.getRange() 12602 << cast<CXXRecordDecl>(CurContext); 12603 FrD->setUnsupportedFriend(true); 12604 } 12605 } 12606 12607 return ND; 12608 } 12609 12610 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12611 AdjustDeclIfTemplate(Dcl); 12612 12613 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12614 if (!Fn) { 12615 Diag(DelLoc, diag::err_deleted_non_function); 12616 return; 12617 } 12618 12619 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12620 // Don't consider the implicit declaration we generate for explicit 12621 // specializations. FIXME: Do not generate these implicit declarations. 12622 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12623 Prev->getPreviousDecl()) && 12624 !Prev->isDefined()) { 12625 Diag(DelLoc, diag::err_deleted_decl_not_first); 12626 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12627 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12628 : diag::note_previous_declaration); 12629 } 12630 // If the declaration wasn't the first, we delete the function anyway for 12631 // recovery. 12632 Fn = Fn->getCanonicalDecl(); 12633 } 12634 12635 // dllimport/dllexport cannot be deleted. 12636 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12637 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12638 Fn->setInvalidDecl(); 12639 } 12640 12641 if (Fn->isDeleted()) 12642 return; 12643 12644 // See if we're deleting a function which is already known to override a 12645 // non-deleted virtual function. 12646 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12647 bool IssuedDiagnostic = false; 12648 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12649 E = MD->end_overridden_methods(); 12650 I != E; ++I) { 12651 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12652 if (!IssuedDiagnostic) { 12653 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12654 IssuedDiagnostic = true; 12655 } 12656 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12657 } 12658 } 12659 } 12660 12661 // C++11 [basic.start.main]p3: 12662 // A program that defines main as deleted [...] is ill-formed. 12663 if (Fn->isMain()) 12664 Diag(DelLoc, diag::err_deleted_main); 12665 12666 Fn->setDeletedAsWritten(); 12667 } 12668 12669 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12670 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12671 12672 if (MD) { 12673 if (MD->getParent()->isDependentType()) { 12674 MD->setDefaulted(); 12675 MD->setExplicitlyDefaulted(); 12676 return; 12677 } 12678 12679 CXXSpecialMember Member = getSpecialMember(MD); 12680 if (Member == CXXInvalid) { 12681 if (!MD->isInvalidDecl()) 12682 Diag(DefaultLoc, diag::err_default_special_members); 12683 return; 12684 } 12685 12686 MD->setDefaulted(); 12687 MD->setExplicitlyDefaulted(); 12688 12689 // If this definition appears within the record, do the checking when 12690 // the record is complete. 12691 const FunctionDecl *Primary = MD; 12692 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12693 // Find the uninstantiated declaration that actually had the '= default' 12694 // on it. 12695 Pattern->isDefined(Primary); 12696 12697 // If the method was defaulted on its first declaration, we will have 12698 // already performed the checking in CheckCompletedCXXClass. Such a 12699 // declaration doesn't trigger an implicit definition. 12700 if (Primary == Primary->getCanonicalDecl()) 12701 return; 12702 12703 CheckExplicitlyDefaultedSpecialMember(MD); 12704 12705 if (MD->isInvalidDecl()) 12706 return; 12707 12708 switch (Member) { 12709 case CXXDefaultConstructor: 12710 DefineImplicitDefaultConstructor(DefaultLoc, 12711 cast<CXXConstructorDecl>(MD)); 12712 break; 12713 case CXXCopyConstructor: 12714 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12715 break; 12716 case CXXCopyAssignment: 12717 DefineImplicitCopyAssignment(DefaultLoc, MD); 12718 break; 12719 case CXXDestructor: 12720 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12721 break; 12722 case CXXMoveConstructor: 12723 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12724 break; 12725 case CXXMoveAssignment: 12726 DefineImplicitMoveAssignment(DefaultLoc, MD); 12727 break; 12728 case CXXInvalid: 12729 llvm_unreachable("Invalid special member."); 12730 } 12731 } else { 12732 Diag(DefaultLoc, diag::err_default_special_members); 12733 } 12734 } 12735 12736 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12737 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12738 Stmt *SubStmt = *CI; 12739 if (!SubStmt) 12740 continue; 12741 if (isa<ReturnStmt>(SubStmt)) 12742 Self.Diag(SubStmt->getLocStart(), 12743 diag::err_return_in_constructor_handler); 12744 if (!isa<Expr>(SubStmt)) 12745 SearchForReturnInStmt(Self, SubStmt); 12746 } 12747 } 12748 12749 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12750 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12751 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12752 SearchForReturnInStmt(*this, Handler); 12753 } 12754 } 12755 12756 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12757 const CXXMethodDecl *Old) { 12758 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12759 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12760 12761 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12762 12763 // If the calling conventions match, everything is fine 12764 if (NewCC == OldCC) 12765 return false; 12766 12767 // If the calling conventions mismatch because the new function is static, 12768 // suppress the calling convention mismatch error; the error about static 12769 // function override (err_static_overrides_virtual from 12770 // Sema::CheckFunctionDeclaration) is more clear. 12771 if (New->getStorageClass() == SC_Static) 12772 return false; 12773 12774 Diag(New->getLocation(), 12775 diag::err_conflicting_overriding_cc_attributes) 12776 << New->getDeclName() << New->getType() << Old->getType(); 12777 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12778 return true; 12779 } 12780 12781 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12782 const CXXMethodDecl *Old) { 12783 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12784 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12785 12786 if (Context.hasSameType(NewTy, OldTy) || 12787 NewTy->isDependentType() || OldTy->isDependentType()) 12788 return false; 12789 12790 // Check if the return types are covariant 12791 QualType NewClassTy, OldClassTy; 12792 12793 /// Both types must be pointers or references to classes. 12794 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12795 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12796 NewClassTy = NewPT->getPointeeType(); 12797 OldClassTy = OldPT->getPointeeType(); 12798 } 12799 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12800 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12801 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12802 NewClassTy = NewRT->getPointeeType(); 12803 OldClassTy = OldRT->getPointeeType(); 12804 } 12805 } 12806 } 12807 12808 // The return types aren't either both pointers or references to a class type. 12809 if (NewClassTy.isNull()) { 12810 Diag(New->getLocation(), 12811 diag::err_different_return_type_for_overriding_virtual_function) 12812 << New->getDeclName() << NewTy << OldTy 12813 << New->getReturnTypeSourceRange(); 12814 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12815 << Old->getReturnTypeSourceRange(); 12816 12817 return true; 12818 } 12819 12820 // C++ [class.virtual]p6: 12821 // If the return type of D::f differs from the return type of B::f, the 12822 // class type in the return type of D::f shall be complete at the point of 12823 // declaration of D::f or shall be the class type D. 12824 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12825 if (!RT->isBeingDefined() && 12826 RequireCompleteType(New->getLocation(), NewClassTy, 12827 diag::err_covariant_return_incomplete, 12828 New->getDeclName())) 12829 return true; 12830 } 12831 12832 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12833 // Check if the new class derives from the old class. 12834 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12835 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12836 << New->getDeclName() << NewTy << OldTy 12837 << New->getReturnTypeSourceRange(); 12838 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12839 << Old->getReturnTypeSourceRange(); 12840 return true; 12841 } 12842 12843 // Check if we the conversion from derived to base is valid. 12844 if (CheckDerivedToBaseConversion( 12845 NewClassTy, OldClassTy, 12846 diag::err_covariant_return_inaccessible_base, 12847 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12848 New->getLocation(), New->getReturnTypeSourceRange(), 12849 New->getDeclName(), nullptr)) { 12850 // FIXME: this note won't trigger for delayed access control 12851 // diagnostics, and it's impossible to get an undelayed error 12852 // here from access control during the original parse because 12853 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12854 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12855 << Old->getReturnTypeSourceRange(); 12856 return true; 12857 } 12858 } 12859 12860 // The qualifiers of the return types must be the same. 12861 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12862 Diag(New->getLocation(), 12863 diag::err_covariant_return_type_different_qualifications) 12864 << New->getDeclName() << NewTy << OldTy 12865 << New->getReturnTypeSourceRange(); 12866 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12867 << Old->getReturnTypeSourceRange(); 12868 return true; 12869 }; 12870 12871 12872 // The new class type must have the same or less qualifiers as the old type. 12873 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12874 Diag(New->getLocation(), 12875 diag::err_covariant_return_type_class_type_more_qualified) 12876 << New->getDeclName() << NewTy << OldTy 12877 << New->getReturnTypeSourceRange(); 12878 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12879 << Old->getReturnTypeSourceRange(); 12880 return true; 12881 }; 12882 12883 return false; 12884 } 12885 12886 /// \brief Mark the given method pure. 12887 /// 12888 /// \param Method the method to be marked pure. 12889 /// 12890 /// \param InitRange the source range that covers the "0" initializer. 12891 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12892 SourceLocation EndLoc = InitRange.getEnd(); 12893 if (EndLoc.isValid()) 12894 Method->setRangeEnd(EndLoc); 12895 12896 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12897 Method->setPure(); 12898 return false; 12899 } 12900 12901 if (!Method->isInvalidDecl()) 12902 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12903 << Method->getDeclName() << InitRange; 12904 return true; 12905 } 12906 12907 /// \brief Determine whether the given declaration is a static data member. 12908 static bool isStaticDataMember(const Decl *D) { 12909 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12910 return Var->isStaticDataMember(); 12911 12912 return false; 12913 } 12914 12915 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12916 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12917 /// is a fresh scope pushed for just this purpose. 12918 /// 12919 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12920 /// static data member of class X, names should be looked up in the scope of 12921 /// class X. 12922 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12923 // If there is no declaration, there was an error parsing it. 12924 if (!D || D->isInvalidDecl()) 12925 return; 12926 12927 // We will always have a nested name specifier here, but this declaration 12928 // might not be out of line if the specifier names the current namespace: 12929 // extern int n; 12930 // int ::n = 0; 12931 if (D->isOutOfLine()) 12932 EnterDeclaratorContext(S, D->getDeclContext()); 12933 12934 // If we are parsing the initializer for a static data member, push a 12935 // new expression evaluation context that is associated with this static 12936 // data member. 12937 if (isStaticDataMember(D)) 12938 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12939 } 12940 12941 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12942 /// initializer for the out-of-line declaration 'D'. 12943 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12944 // If there is no declaration, there was an error parsing it. 12945 if (!D || D->isInvalidDecl()) 12946 return; 12947 12948 if (isStaticDataMember(D)) 12949 PopExpressionEvaluationContext(); 12950 12951 if (D->isOutOfLine()) 12952 ExitDeclaratorContext(S); 12953 } 12954 12955 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12956 /// C++ if/switch/while/for statement. 12957 /// e.g: "if (int x = f()) {...}" 12958 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12959 // C++ 6.4p2: 12960 // The declarator shall not specify a function or an array. 12961 // The type-specifier-seq shall not contain typedef and shall not declare a 12962 // new class or enumeration. 12963 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12964 "Parser allowed 'typedef' as storage class of condition decl."); 12965 12966 Decl *Dcl = ActOnDeclarator(S, D); 12967 if (!Dcl) 12968 return true; 12969 12970 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12971 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12972 << D.getSourceRange(); 12973 return true; 12974 } 12975 12976 return Dcl; 12977 } 12978 12979 void Sema::LoadExternalVTableUses() { 12980 if (!ExternalSource) 12981 return; 12982 12983 SmallVector<ExternalVTableUse, 4> VTables; 12984 ExternalSource->ReadUsedVTables(VTables); 12985 SmallVector<VTableUse, 4> NewUses; 12986 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12987 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12988 = VTablesUsed.find(VTables[I].Record); 12989 // Even if a definition wasn't required before, it may be required now. 12990 if (Pos != VTablesUsed.end()) { 12991 if (!Pos->second && VTables[I].DefinitionRequired) 12992 Pos->second = true; 12993 continue; 12994 } 12995 12996 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12997 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12998 } 12999 13000 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 13001 } 13002 13003 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 13004 bool DefinitionRequired) { 13005 // Ignore any vtable uses in unevaluated operands or for classes that do 13006 // not have a vtable. 13007 if (!Class->isDynamicClass() || Class->isDependentContext() || 13008 CurContext->isDependentContext() || isUnevaluatedContext()) 13009 return; 13010 13011 // Try to insert this class into the map. 13012 LoadExternalVTableUses(); 13013 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13014 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 13015 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 13016 if (!Pos.second) { 13017 // If we already had an entry, check to see if we are promoting this vtable 13018 // to required a definition. If so, we need to reappend to the VTableUses 13019 // list, since we may have already processed the first entry. 13020 if (DefinitionRequired && !Pos.first->second) { 13021 Pos.first->second = true; 13022 } else { 13023 // Otherwise, we can early exit. 13024 return; 13025 } 13026 } else { 13027 // The Microsoft ABI requires that we perform the destructor body 13028 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 13029 // the deleting destructor is emitted with the vtable, not with the 13030 // destructor definition as in the Itanium ABI. 13031 // If it has a definition, we do the check at that point instead. 13032 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13033 Class->hasUserDeclaredDestructor() && 13034 !Class->getDestructor()->isDefined() && 13035 !Class->getDestructor()->isDeleted()) { 13036 CXXDestructorDecl *DD = Class->getDestructor(); 13037 ContextRAII SavedContext(*this, DD); 13038 CheckDestructor(DD); 13039 } 13040 } 13041 13042 // Local classes need to have their virtual members marked 13043 // immediately. For all other classes, we mark their virtual members 13044 // at the end of the translation unit. 13045 if (Class->isLocalClass()) 13046 MarkVirtualMembersReferenced(Loc, Class); 13047 else 13048 VTableUses.push_back(std::make_pair(Class, Loc)); 13049 } 13050 13051 bool Sema::DefineUsedVTables() { 13052 LoadExternalVTableUses(); 13053 if (VTableUses.empty()) 13054 return false; 13055 13056 // Note: The VTableUses vector could grow as a result of marking 13057 // the members of a class as "used", so we check the size each 13058 // time through the loop and prefer indices (which are stable) to 13059 // iterators (which are not). 13060 bool DefinedAnything = false; 13061 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13062 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13063 if (!Class) 13064 continue; 13065 13066 SourceLocation Loc = VTableUses[I].second; 13067 13068 bool DefineVTable = true; 13069 13070 // If this class has a key function, but that key function is 13071 // defined in another translation unit, we don't need to emit the 13072 // vtable even though we're using it. 13073 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13074 if (KeyFunction && !KeyFunction->hasBody()) { 13075 // The key function is in another translation unit. 13076 DefineVTable = false; 13077 TemplateSpecializationKind TSK = 13078 KeyFunction->getTemplateSpecializationKind(); 13079 assert(TSK != TSK_ExplicitInstantiationDefinition && 13080 TSK != TSK_ImplicitInstantiation && 13081 "Instantiations don't have key functions"); 13082 (void)TSK; 13083 } else if (!KeyFunction) { 13084 // If we have a class with no key function that is the subject 13085 // of an explicit instantiation declaration, suppress the 13086 // vtable; it will live with the explicit instantiation 13087 // definition. 13088 bool IsExplicitInstantiationDeclaration 13089 = Class->getTemplateSpecializationKind() 13090 == TSK_ExplicitInstantiationDeclaration; 13091 for (auto R : Class->redecls()) { 13092 TemplateSpecializationKind TSK 13093 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13094 if (TSK == TSK_ExplicitInstantiationDeclaration) 13095 IsExplicitInstantiationDeclaration = true; 13096 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13097 IsExplicitInstantiationDeclaration = false; 13098 break; 13099 } 13100 } 13101 13102 if (IsExplicitInstantiationDeclaration) 13103 DefineVTable = false; 13104 } 13105 13106 // The exception specifications for all virtual members may be needed even 13107 // if we are not providing an authoritative form of the vtable in this TU. 13108 // We may choose to emit it available_externally anyway. 13109 if (!DefineVTable) { 13110 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13111 continue; 13112 } 13113 13114 // Mark all of the virtual members of this class as referenced, so 13115 // that we can build a vtable. Then, tell the AST consumer that a 13116 // vtable for this class is required. 13117 DefinedAnything = true; 13118 MarkVirtualMembersReferenced(Loc, Class); 13119 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13120 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 13121 13122 // Optionally warn if we're emitting a weak vtable. 13123 if (Class->isExternallyVisible() && 13124 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13125 const FunctionDecl *KeyFunctionDef = nullptr; 13126 if (!KeyFunction || 13127 (KeyFunction->hasBody(KeyFunctionDef) && 13128 KeyFunctionDef->isInlined())) 13129 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13130 TSK_ExplicitInstantiationDefinition 13131 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13132 << Class; 13133 } 13134 } 13135 VTableUses.clear(); 13136 13137 return DefinedAnything; 13138 } 13139 13140 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13141 const CXXRecordDecl *RD) { 13142 for (const auto *I : RD->methods()) 13143 if (I->isVirtual() && !I->isPure()) 13144 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13145 } 13146 13147 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13148 const CXXRecordDecl *RD) { 13149 // Mark all functions which will appear in RD's vtable as used. 13150 CXXFinalOverriderMap FinalOverriders; 13151 RD->getFinalOverriders(FinalOverriders); 13152 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13153 E = FinalOverriders.end(); 13154 I != E; ++I) { 13155 for (OverridingMethods::const_iterator OI = I->second.begin(), 13156 OE = I->second.end(); 13157 OI != OE; ++OI) { 13158 assert(OI->second.size() > 0 && "no final overrider"); 13159 CXXMethodDecl *Overrider = OI->second.front().Method; 13160 13161 // C++ [basic.def.odr]p2: 13162 // [...] A virtual member function is used if it is not pure. [...] 13163 if (!Overrider->isPure()) 13164 MarkFunctionReferenced(Loc, Overrider); 13165 } 13166 } 13167 13168 // Only classes that have virtual bases need a VTT. 13169 if (RD->getNumVBases() == 0) 13170 return; 13171 13172 for (const auto &I : RD->bases()) { 13173 const CXXRecordDecl *Base = 13174 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13175 if (Base->getNumVBases() == 0) 13176 continue; 13177 MarkVirtualMembersReferenced(Loc, Base); 13178 } 13179 } 13180 13181 /// SetIvarInitializers - This routine builds initialization ASTs for the 13182 /// Objective-C implementation whose ivars need be initialized. 13183 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13184 if (!getLangOpts().CPlusPlus) 13185 return; 13186 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13187 SmallVector<ObjCIvarDecl*, 8> ivars; 13188 CollectIvarsToConstructOrDestruct(OID, ivars); 13189 if (ivars.empty()) 13190 return; 13191 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13192 for (unsigned i = 0; i < ivars.size(); i++) { 13193 FieldDecl *Field = ivars[i]; 13194 if (Field->isInvalidDecl()) 13195 continue; 13196 13197 CXXCtorInitializer *Member; 13198 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13199 InitializationKind InitKind = 13200 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13201 13202 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13203 ExprResult MemberInit = 13204 InitSeq.Perform(*this, InitEntity, InitKind, None); 13205 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13206 // Note, MemberInit could actually come back empty if no initialization 13207 // is required (e.g., because it would call a trivial default constructor) 13208 if (!MemberInit.get() || MemberInit.isInvalid()) 13209 continue; 13210 13211 Member = 13212 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13213 SourceLocation(), 13214 MemberInit.getAs<Expr>(), 13215 SourceLocation()); 13216 AllToInit.push_back(Member); 13217 13218 // Be sure that the destructor is accessible and is marked as referenced. 13219 if (const RecordType *RecordTy = 13220 Context.getBaseElementType(Field->getType()) 13221 ->getAs<RecordType>()) { 13222 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13223 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13224 MarkFunctionReferenced(Field->getLocation(), Destructor); 13225 CheckDestructorAccess(Field->getLocation(), Destructor, 13226 PDiag(diag::err_access_dtor_ivar) 13227 << Context.getBaseElementType(Field->getType())); 13228 } 13229 } 13230 } 13231 ObjCImplementation->setIvarInitializers(Context, 13232 AllToInit.data(), AllToInit.size()); 13233 } 13234 } 13235 13236 static 13237 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13238 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13239 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13240 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13241 Sema &S) { 13242 if (Ctor->isInvalidDecl()) 13243 return; 13244 13245 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13246 13247 // Target may not be determinable yet, for instance if this is a dependent 13248 // call in an uninstantiated template. 13249 if (Target) { 13250 const FunctionDecl *FNTarget = nullptr; 13251 (void)Target->hasBody(FNTarget); 13252 Target = const_cast<CXXConstructorDecl*>( 13253 cast_or_null<CXXConstructorDecl>(FNTarget)); 13254 } 13255 13256 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13257 // Avoid dereferencing a null pointer here. 13258 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13259 13260 if (!Current.insert(Canonical).second) 13261 return; 13262 13263 // We know that beyond here, we aren't chaining into a cycle. 13264 if (!Target || !Target->isDelegatingConstructor() || 13265 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13266 Valid.insert(Current.begin(), Current.end()); 13267 Current.clear(); 13268 // We've hit a cycle. 13269 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13270 Current.count(TCanonical)) { 13271 // If we haven't diagnosed this cycle yet, do so now. 13272 if (!Invalid.count(TCanonical)) { 13273 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13274 diag::warn_delegating_ctor_cycle) 13275 << Ctor; 13276 13277 // Don't add a note for a function delegating directly to itself. 13278 if (TCanonical != Canonical) 13279 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13280 13281 CXXConstructorDecl *C = Target; 13282 while (C->getCanonicalDecl() != Canonical) { 13283 const FunctionDecl *FNTarget = nullptr; 13284 (void)C->getTargetConstructor()->hasBody(FNTarget); 13285 assert(FNTarget && "Ctor cycle through bodiless function"); 13286 13287 C = const_cast<CXXConstructorDecl*>( 13288 cast<CXXConstructorDecl>(FNTarget)); 13289 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13290 } 13291 } 13292 13293 Invalid.insert(Current.begin(), Current.end()); 13294 Current.clear(); 13295 } else { 13296 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13297 } 13298 } 13299 13300 13301 void Sema::CheckDelegatingCtorCycles() { 13302 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13303 13304 for (DelegatingCtorDeclsType::iterator 13305 I = DelegatingCtorDecls.begin(ExternalSource), 13306 E = DelegatingCtorDecls.end(); 13307 I != E; ++I) 13308 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13309 13310 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13311 CE = Invalid.end(); 13312 CI != CE; ++CI) 13313 (*CI)->setInvalidDecl(); 13314 } 13315 13316 namespace { 13317 /// \brief AST visitor that finds references to the 'this' expression. 13318 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13319 Sema &S; 13320 13321 public: 13322 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13323 13324 bool VisitCXXThisExpr(CXXThisExpr *E) { 13325 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13326 << E->isImplicit(); 13327 return false; 13328 } 13329 }; 13330 } 13331 13332 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13333 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13334 if (!TSInfo) 13335 return false; 13336 13337 TypeLoc TL = TSInfo->getTypeLoc(); 13338 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13339 if (!ProtoTL) 13340 return false; 13341 13342 // C++11 [expr.prim.general]p3: 13343 // [The expression this] shall not appear before the optional 13344 // cv-qualifier-seq and it shall not appear within the declaration of a 13345 // static member function (although its type and value category are defined 13346 // within a static member function as they are within a non-static member 13347 // function). [ Note: this is because declaration matching does not occur 13348 // until the complete declarator is known. - end note ] 13349 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13350 FindCXXThisExpr Finder(*this); 13351 13352 // If the return type came after the cv-qualifier-seq, check it now. 13353 if (Proto->hasTrailingReturn() && 13354 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13355 return true; 13356 13357 // Check the exception specification. 13358 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13359 return true; 13360 13361 return checkThisInStaticMemberFunctionAttributes(Method); 13362 } 13363 13364 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13365 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13366 if (!TSInfo) 13367 return false; 13368 13369 TypeLoc TL = TSInfo->getTypeLoc(); 13370 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13371 if (!ProtoTL) 13372 return false; 13373 13374 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13375 FindCXXThisExpr Finder(*this); 13376 13377 switch (Proto->getExceptionSpecType()) { 13378 case EST_Unparsed: 13379 case EST_Uninstantiated: 13380 case EST_Unevaluated: 13381 case EST_BasicNoexcept: 13382 case EST_DynamicNone: 13383 case EST_MSAny: 13384 case EST_None: 13385 break; 13386 13387 case EST_ComputedNoexcept: 13388 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13389 return true; 13390 13391 case EST_Dynamic: 13392 for (const auto &E : Proto->exceptions()) { 13393 if (!Finder.TraverseType(E)) 13394 return true; 13395 } 13396 break; 13397 } 13398 13399 return false; 13400 } 13401 13402 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13403 FindCXXThisExpr Finder(*this); 13404 13405 // Check attributes. 13406 for (const auto *A : Method->attrs()) { 13407 // FIXME: This should be emitted by tblgen. 13408 Expr *Arg = nullptr; 13409 ArrayRef<Expr *> Args; 13410 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13411 Arg = G->getArg(); 13412 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13413 Arg = G->getArg(); 13414 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13415 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13416 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13417 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13418 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13419 Arg = ETLF->getSuccessValue(); 13420 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13421 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13422 Arg = STLF->getSuccessValue(); 13423 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13424 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13425 Arg = LR->getArg(); 13426 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13427 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13428 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13429 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13430 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13431 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13432 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13433 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13434 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13435 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13436 13437 if (Arg && !Finder.TraverseStmt(Arg)) 13438 return true; 13439 13440 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13441 if (!Finder.TraverseStmt(Args[I])) 13442 return true; 13443 } 13444 } 13445 13446 return false; 13447 } 13448 13449 void Sema::checkExceptionSpecification( 13450 bool IsTopLevel, ExceptionSpecificationType EST, 13451 ArrayRef<ParsedType> DynamicExceptions, 13452 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13453 SmallVectorImpl<QualType> &Exceptions, 13454 FunctionProtoType::ExceptionSpecInfo &ESI) { 13455 Exceptions.clear(); 13456 ESI.Type = EST; 13457 if (EST == EST_Dynamic) { 13458 Exceptions.reserve(DynamicExceptions.size()); 13459 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13460 // FIXME: Preserve type source info. 13461 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13462 13463 if (IsTopLevel) { 13464 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13465 collectUnexpandedParameterPacks(ET, Unexpanded); 13466 if (!Unexpanded.empty()) { 13467 DiagnoseUnexpandedParameterPacks( 13468 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13469 Unexpanded); 13470 continue; 13471 } 13472 } 13473 13474 // Check that the type is valid for an exception spec, and 13475 // drop it if not. 13476 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13477 Exceptions.push_back(ET); 13478 } 13479 ESI.Exceptions = Exceptions; 13480 return; 13481 } 13482 13483 if (EST == EST_ComputedNoexcept) { 13484 // If an error occurred, there's no expression here. 13485 if (NoexceptExpr) { 13486 assert((NoexceptExpr->isTypeDependent() || 13487 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13488 Context.BoolTy) && 13489 "Parser should have made sure that the expression is boolean"); 13490 if (IsTopLevel && NoexceptExpr && 13491 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13492 ESI.Type = EST_BasicNoexcept; 13493 return; 13494 } 13495 13496 if (!NoexceptExpr->isValueDependent()) 13497 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13498 diag::err_noexcept_needs_constant_expression, 13499 /*AllowFold*/ false).get(); 13500 ESI.NoexceptExpr = NoexceptExpr; 13501 } 13502 return; 13503 } 13504 } 13505 13506 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13507 ExceptionSpecificationType EST, 13508 SourceRange SpecificationRange, 13509 ArrayRef<ParsedType> DynamicExceptions, 13510 ArrayRef<SourceRange> DynamicExceptionRanges, 13511 Expr *NoexceptExpr) { 13512 if (!MethodD) 13513 return; 13514 13515 // Dig out the method we're referring to. 13516 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13517 MethodD = FunTmpl->getTemplatedDecl(); 13518 13519 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13520 if (!Method) 13521 return; 13522 13523 // Check the exception specification. 13524 llvm::SmallVector<QualType, 4> Exceptions; 13525 FunctionProtoType::ExceptionSpecInfo ESI; 13526 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13527 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13528 ESI); 13529 13530 // Update the exception specification on the function type. 13531 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13532 13533 if (Method->isStatic()) 13534 checkThisInStaticMemberFunctionExceptionSpec(Method); 13535 13536 if (Method->isVirtual()) { 13537 // Check overrides, which we previously had to delay. 13538 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13539 OEnd = Method->end_overridden_methods(); 13540 O != OEnd; ++O) 13541 CheckOverridingFunctionExceptionSpec(Method, *O); 13542 } 13543 } 13544 13545 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13546 /// 13547 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13548 SourceLocation DeclStart, 13549 Declarator &D, Expr *BitWidth, 13550 InClassInitStyle InitStyle, 13551 AccessSpecifier AS, 13552 AttributeList *MSPropertyAttr) { 13553 IdentifierInfo *II = D.getIdentifier(); 13554 if (!II) { 13555 Diag(DeclStart, diag::err_anonymous_property); 13556 return nullptr; 13557 } 13558 SourceLocation Loc = D.getIdentifierLoc(); 13559 13560 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13561 QualType T = TInfo->getType(); 13562 if (getLangOpts().CPlusPlus) { 13563 CheckExtraCXXDefaultArguments(D); 13564 13565 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13566 UPPC_DataMemberType)) { 13567 D.setInvalidType(); 13568 T = Context.IntTy; 13569 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13570 } 13571 } 13572 13573 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13574 13575 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13576 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13577 diag::err_invalid_thread) 13578 << DeclSpec::getSpecifierName(TSCS); 13579 13580 // Check to see if this name was declared as a member previously 13581 NamedDecl *PrevDecl = nullptr; 13582 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13583 LookupName(Previous, S); 13584 switch (Previous.getResultKind()) { 13585 case LookupResult::Found: 13586 case LookupResult::FoundUnresolvedValue: 13587 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13588 break; 13589 13590 case LookupResult::FoundOverloaded: 13591 PrevDecl = Previous.getRepresentativeDecl(); 13592 break; 13593 13594 case LookupResult::NotFound: 13595 case LookupResult::NotFoundInCurrentInstantiation: 13596 case LookupResult::Ambiguous: 13597 break; 13598 } 13599 13600 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13601 // Maybe we will complain about the shadowed template parameter. 13602 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13603 // Just pretend that we didn't see the previous declaration. 13604 PrevDecl = nullptr; 13605 } 13606 13607 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13608 PrevDecl = nullptr; 13609 13610 SourceLocation TSSL = D.getLocStart(); 13611 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13612 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13613 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13614 ProcessDeclAttributes(TUScope, NewPD, D); 13615 NewPD->setAccess(AS); 13616 13617 if (NewPD->isInvalidDecl()) 13618 Record->setInvalidDecl(); 13619 13620 if (D.getDeclSpec().isModulePrivateSpecified()) 13621 NewPD->setModulePrivate(); 13622 13623 if (NewPD->isInvalidDecl() && PrevDecl) { 13624 // Don't introduce NewFD into scope; there's already something 13625 // with the same name in the same scope. 13626 } else if (II) { 13627 PushOnScopeChains(NewPD, S); 13628 } else 13629 Record->addDecl(NewPD); 13630 13631 return NewPD; 13632 } 13633