1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for C++ declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.getAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // Check that the default argument is well-formed 322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 323 if (DefaultArgChecker.Visit(DefaultArg)) { 324 Param->setInvalidDecl(); 325 return; 326 } 327 328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 329 } 330 331 /// ActOnParamUnparsedDefaultArgument - We've seen a default 332 /// argument for a function parameter, but we can't parse it yet 333 /// because we're inside a class definition. Note that this default 334 /// argument will be parsed later. 335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 336 SourceLocation EqualLoc, 337 SourceLocation ArgLoc) { 338 if (!param) 339 return; 340 341 ParmVarDecl *Param = cast<ParmVarDecl>(param); 342 Param->setUnparsedDefaultArg(); 343 UnparsedDefaultArgLocs[Param] = ArgLoc; 344 } 345 346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 347 /// the default argument for the parameter param failed. 348 void Sema::ActOnParamDefaultArgumentError(Decl *param, 349 SourceLocation EqualLoc) { 350 if (!param) 351 return; 352 353 ParmVarDecl *Param = cast<ParmVarDecl>(param); 354 Param->setInvalidDecl(); 355 UnparsedDefaultArgLocs.erase(Param); 356 Param->setDefaultArg(new(Context) 357 OpaqueValueExpr(EqualLoc, 358 Param->getType().getNonReferenceType(), 359 VK_RValue)); 360 } 361 362 /// CheckExtraCXXDefaultArguments - Check for any extra default 363 /// arguments in the declarator, which is not a function declaration 364 /// or definition and therefore is not permitted to have default 365 /// arguments. This routine should be invoked for every declarator 366 /// that is not a function declaration or definition. 367 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 368 // C++ [dcl.fct.default]p3 369 // A default argument expression shall be specified only in the 370 // parameter-declaration-clause of a function declaration or in a 371 // template-parameter (14.1). It shall not be specified for a 372 // parameter pack. If it is specified in a 373 // parameter-declaration-clause, it shall not occur within a 374 // declarator or abstract-declarator of a parameter-declaration. 375 bool MightBeFunction = D.isFunctionDeclarationContext(); 376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 377 DeclaratorChunk &chunk = D.getTypeObject(i); 378 if (chunk.Kind == DeclaratorChunk::Function) { 379 if (MightBeFunction) { 380 // This is a function declaration. It can have default arguments, but 381 // keep looking in case its return type is a function type with default 382 // arguments. 383 MightBeFunction = false; 384 continue; 385 } 386 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 387 ++argIdx) { 388 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 389 if (Param->hasUnparsedDefaultArg()) { 390 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 391 SourceRange SR; 392 if (Toks->size() > 1) 393 SR = SourceRange((*Toks)[1].getLocation(), 394 Toks->back().getLocation()); 395 else 396 SR = UnparsedDefaultArgLocs[Param]; 397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 398 << SR; 399 delete Toks; 400 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 401 } else if (Param->getDefaultArg()) { 402 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 403 << Param->getDefaultArg()->getSourceRange(); 404 Param->setDefaultArg(nullptr); 405 } 406 } 407 } else if (chunk.Kind != DeclaratorChunk::Paren) { 408 MightBeFunction = false; 409 } 410 } 411 } 412 413 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 414 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 415 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 416 if (!PVD->hasDefaultArg()) 417 return false; 418 if (!PVD->hasInheritedDefaultArg()) 419 return true; 420 } 421 return false; 422 } 423 424 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 425 /// function, once we already know that they have the same 426 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 427 /// error, false otherwise. 428 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 429 Scope *S) { 430 bool Invalid = false; 431 432 // C++ [dcl.fct.default]p4: 433 // For non-template functions, default arguments can be added in 434 // later declarations of a function in the same 435 // scope. Declarations in different scopes have completely 436 // distinct sets of default arguments. That is, declarations in 437 // inner scopes do not acquire default arguments from 438 // declarations in outer scopes, and vice versa. In a given 439 // function declaration, all parameters subsequent to a 440 // parameter with a default argument shall have default 441 // arguments supplied in this or previous declarations. A 442 // default argument shall not be redefined by a later 443 // declaration (not even to the same value). 444 // 445 // C++ [dcl.fct.default]p6: 446 // Except for member functions of class templates, the default arguments 447 // in a member function definition that appears outside of the class 448 // definition are added to the set of default arguments provided by the 449 // member function declaration in the class definition. 450 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 451 ParmVarDecl *OldParam = Old->getParamDecl(p); 452 ParmVarDecl *NewParam = New->getParamDecl(p); 453 454 bool OldParamHasDfl = OldParam->hasDefaultArg(); 455 bool NewParamHasDfl = NewParam->hasDefaultArg(); 456 457 // The declaration context corresponding to the scope is the semantic 458 // parent, unless this is a local function declaration, in which case 459 // it is that surrounding function. 460 DeclContext *ScopeDC = New->isLocalExternDecl() 461 ? New->getLexicalDeclContext() 462 : New->getDeclContext(); 463 if (S && !isDeclInScope(Old, ScopeDC, S) && 464 !New->getDeclContext()->isRecord()) 465 // Ignore default parameters of old decl if they are not in 466 // the same scope and this is not an out-of-line definition of 467 // a member function. 468 OldParamHasDfl = false; 469 if (New->isLocalExternDecl() != Old->isLocalExternDecl()) 470 // If only one of these is a local function declaration, then they are 471 // declared in different scopes, even though isDeclInScope may think 472 // they're in the same scope. (If both are local, the scope check is 473 // sufficent, and if neither is local, then they are in the same scope.) 474 OldParamHasDfl = false; 475 476 if (OldParamHasDfl && NewParamHasDfl) { 477 478 unsigned DiagDefaultParamID = 479 diag::err_param_default_argument_redefinition; 480 481 // MSVC accepts that default parameters be redefined for member functions 482 // of template class. The new default parameter's value is ignored. 483 Invalid = true; 484 if (getLangOpts().MicrosoftExt) { 485 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 486 if (MD && MD->getParent()->getDescribedClassTemplate()) { 487 // Merge the old default argument into the new parameter. 488 NewParam->setHasInheritedDefaultArg(); 489 if (OldParam->hasUninstantiatedDefaultArg()) 490 NewParam->setUninstantiatedDefaultArg( 491 OldParam->getUninstantiatedDefaultArg()); 492 else 493 NewParam->setDefaultArg(OldParam->getInit()); 494 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 495 Invalid = false; 496 } 497 } 498 499 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 500 // hint here. Alternatively, we could walk the type-source information 501 // for NewParam to find the last source location in the type... but it 502 // isn't worth the effort right now. This is the kind of test case that 503 // is hard to get right: 504 // int f(int); 505 // void g(int (*fp)(int) = f); 506 // void g(int (*fp)(int) = &f); 507 Diag(NewParam->getLocation(), DiagDefaultParamID) 508 << NewParam->getDefaultArgRange(); 509 510 // Look for the function declaration where the default argument was 511 // actually written, which may be a declaration prior to Old. 512 for (auto Older = Old; OldParam->hasInheritedDefaultArg();) { 513 Older = Older->getPreviousDecl(); 514 OldParam = Older->getParamDecl(p); 515 } 516 517 Diag(OldParam->getLocation(), diag::note_previous_definition) 518 << OldParam->getDefaultArgRange(); 519 } else if (OldParamHasDfl) { 520 // Merge the old default argument into the new parameter. 521 // It's important to use getInit() here; getDefaultArg() 522 // strips off any top-level ExprWithCleanups. 523 NewParam->setHasInheritedDefaultArg(); 524 if (OldParam->hasUnparsedDefaultArg()) 525 NewParam->setUnparsedDefaultArg(); 526 else if (OldParam->hasUninstantiatedDefaultArg()) 527 NewParam->setUninstantiatedDefaultArg( 528 OldParam->getUninstantiatedDefaultArg()); 529 else 530 NewParam->setDefaultArg(OldParam->getInit()); 531 } else if (NewParamHasDfl) { 532 if (New->getDescribedFunctionTemplate()) { 533 // Paragraph 4, quoted above, only applies to non-template functions. 534 Diag(NewParam->getLocation(), 535 diag::err_param_default_argument_template_redecl) 536 << NewParam->getDefaultArgRange(); 537 Diag(Old->getLocation(), diag::note_template_prev_declaration) 538 << false; 539 } else if (New->getTemplateSpecializationKind() 540 != TSK_ImplicitInstantiation && 541 New->getTemplateSpecializationKind() != TSK_Undeclared) { 542 // C++ [temp.expr.spec]p21: 543 // Default function arguments shall not be specified in a declaration 544 // or a definition for one of the following explicit specializations: 545 // - the explicit specialization of a function template; 546 // - the explicit specialization of a member function template; 547 // - the explicit specialization of a member function of a class 548 // template where the class template specialization to which the 549 // member function specialization belongs is implicitly 550 // instantiated. 551 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 552 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 553 << New->getDeclName() 554 << NewParam->getDefaultArgRange(); 555 } else if (New->getDeclContext()->isDependentContext()) { 556 // C++ [dcl.fct.default]p6 (DR217): 557 // Default arguments for a member function of a class template shall 558 // be specified on the initial declaration of the member function 559 // within the class template. 560 // 561 // Reading the tea leaves a bit in DR217 and its reference to DR205 562 // leads me to the conclusion that one cannot add default function 563 // arguments for an out-of-line definition of a member function of a 564 // dependent type. 565 int WhichKind = 2; 566 if (CXXRecordDecl *Record 567 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 568 if (Record->getDescribedClassTemplate()) 569 WhichKind = 0; 570 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 571 WhichKind = 1; 572 else 573 WhichKind = 2; 574 } 575 576 Diag(NewParam->getLocation(), 577 diag::err_param_default_argument_member_template_redecl) 578 << WhichKind 579 << NewParam->getDefaultArgRange(); 580 } 581 } 582 } 583 584 // DR1344: If a default argument is added outside a class definition and that 585 // default argument makes the function a special member function, the program 586 // is ill-formed. This can only happen for constructors. 587 if (isa<CXXConstructorDecl>(New) && 588 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 589 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 590 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 591 if (NewSM != OldSM) { 592 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 593 assert(NewParam->hasDefaultArg()); 594 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 595 << NewParam->getDefaultArgRange() << NewSM; 596 Diag(Old->getLocation(), diag::note_previous_declaration); 597 } 598 } 599 600 const FunctionDecl *Def; 601 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 602 // template has a constexpr specifier then all its declarations shall 603 // contain the constexpr specifier. 604 if (New->isConstexpr() != Old->isConstexpr()) { 605 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 606 << New << New->isConstexpr(); 607 Diag(Old->getLocation(), diag::note_previous_declaration); 608 Invalid = true; 609 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 610 // C++11 [dcl.fcn.spec]p4: 611 // If the definition of a function appears in a translation unit before its 612 // first declaration as inline, the program is ill-formed. 613 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 614 Diag(Def->getLocation(), diag::note_previous_definition); 615 Invalid = true; 616 } 617 618 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 619 // argument expression, that declaration shall be a definition and shall be 620 // the only declaration of the function or function template in the 621 // translation unit. 622 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 623 functionDeclHasDefaultArgument(Old)) { 624 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 625 Diag(Old->getLocation(), diag::note_previous_declaration); 626 Invalid = true; 627 } 628 629 if (CheckEquivalentExceptionSpec(Old, New)) 630 Invalid = true; 631 632 return Invalid; 633 } 634 635 /// \brief Merge the exception specifications of two variable declarations. 636 /// 637 /// This is called when there's a redeclaration of a VarDecl. The function 638 /// checks if the redeclaration might have an exception specification and 639 /// validates compatibility and merges the specs if necessary. 640 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 641 // Shortcut if exceptions are disabled. 642 if (!getLangOpts().CXXExceptions) 643 return; 644 645 assert(Context.hasSameType(New->getType(), Old->getType()) && 646 "Should only be called if types are otherwise the same."); 647 648 QualType NewType = New->getType(); 649 QualType OldType = Old->getType(); 650 651 // We're only interested in pointers and references to functions, as well 652 // as pointers to member functions. 653 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 654 NewType = R->getPointeeType(); 655 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 656 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 657 NewType = P->getPointeeType(); 658 OldType = OldType->getAs<PointerType>()->getPointeeType(); 659 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 660 NewType = M->getPointeeType(); 661 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 662 } 663 664 if (!NewType->isFunctionProtoType()) 665 return; 666 667 // There's lots of special cases for functions. For function pointers, system 668 // libraries are hopefully not as broken so that we don't need these 669 // workarounds. 670 if (CheckEquivalentExceptionSpec( 671 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 672 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 673 New->setInvalidDecl(); 674 } 675 } 676 677 /// CheckCXXDefaultArguments - Verify that the default arguments for a 678 /// function declaration are well-formed according to C++ 679 /// [dcl.fct.default]. 680 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 681 unsigned NumParams = FD->getNumParams(); 682 unsigned p; 683 684 // Find first parameter with a default argument 685 for (p = 0; p < NumParams; ++p) { 686 ParmVarDecl *Param = FD->getParamDecl(p); 687 if (Param->hasDefaultArg()) 688 break; 689 } 690 691 // C++ [dcl.fct.default]p4: 692 // In a given function declaration, all parameters 693 // subsequent to a parameter with a default argument shall 694 // have default arguments supplied in this or previous 695 // declarations. A default argument shall not be redefined 696 // by a later declaration (not even to the same value). 697 unsigned LastMissingDefaultArg = 0; 698 for (; p < NumParams; ++p) { 699 ParmVarDecl *Param = FD->getParamDecl(p); 700 if (!Param->hasDefaultArg()) { 701 if (Param->isInvalidDecl()) 702 /* We already complained about this parameter. */; 703 else if (Param->getIdentifier()) 704 Diag(Param->getLocation(), 705 diag::err_param_default_argument_missing_name) 706 << Param->getIdentifier(); 707 else 708 Diag(Param->getLocation(), 709 diag::err_param_default_argument_missing); 710 711 LastMissingDefaultArg = p; 712 } 713 } 714 715 if (LastMissingDefaultArg > 0) { 716 // Some default arguments were missing. Clear out all of the 717 // default arguments up to (and including) the last missing 718 // default argument, so that we leave the function parameters 719 // in a semantically valid state. 720 for (p = 0; p <= LastMissingDefaultArg; ++p) { 721 ParmVarDecl *Param = FD->getParamDecl(p); 722 if (Param->hasDefaultArg()) { 723 Param->setDefaultArg(nullptr); 724 } 725 } 726 } 727 } 728 729 // CheckConstexprParameterTypes - Check whether a function's parameter types 730 // are all literal types. If so, return true. If not, produce a suitable 731 // diagnostic and return false. 732 static bool CheckConstexprParameterTypes(Sema &SemaRef, 733 const FunctionDecl *FD) { 734 unsigned ArgIndex = 0; 735 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 736 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 737 e = FT->param_type_end(); 738 i != e; ++i, ++ArgIndex) { 739 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 740 SourceLocation ParamLoc = PD->getLocation(); 741 if (!(*i)->isDependentType() && 742 SemaRef.RequireLiteralType(ParamLoc, *i, 743 diag::err_constexpr_non_literal_param, 744 ArgIndex+1, PD->getSourceRange(), 745 isa<CXXConstructorDecl>(FD))) 746 return false; 747 } 748 return true; 749 } 750 751 /// \brief Get diagnostic %select index for tag kind for 752 /// record diagnostic message. 753 /// WARNING: Indexes apply to particular diagnostics only! 754 /// 755 /// \returns diagnostic %select index. 756 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 757 switch (Tag) { 758 case TTK_Struct: return 0; 759 case TTK_Interface: return 1; 760 case TTK_Class: return 2; 761 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 762 } 763 } 764 765 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 766 // the requirements of a constexpr function definition or a constexpr 767 // constructor definition. If so, return true. If not, produce appropriate 768 // diagnostics and return false. 769 // 770 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 771 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 772 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 773 if (MD && MD->isInstance()) { 774 // C++11 [dcl.constexpr]p4: 775 // The definition of a constexpr constructor shall satisfy the following 776 // constraints: 777 // - the class shall not have any virtual base classes; 778 const CXXRecordDecl *RD = MD->getParent(); 779 if (RD->getNumVBases()) { 780 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 781 << isa<CXXConstructorDecl>(NewFD) 782 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 783 for (const auto &I : RD->vbases()) 784 Diag(I.getLocStart(), 785 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 786 return false; 787 } 788 } 789 790 if (!isa<CXXConstructorDecl>(NewFD)) { 791 // C++11 [dcl.constexpr]p3: 792 // The definition of a constexpr function shall satisfy the following 793 // constraints: 794 // - it shall not be virtual; 795 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 796 if (Method && Method->isVirtual()) { 797 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 798 799 // If it's not obvious why this function is virtual, find an overridden 800 // function which uses the 'virtual' keyword. 801 const CXXMethodDecl *WrittenVirtual = Method; 802 while (!WrittenVirtual->isVirtualAsWritten()) 803 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 804 if (WrittenVirtual != Method) 805 Diag(WrittenVirtual->getLocation(), 806 diag::note_overridden_virtual_function); 807 return false; 808 } 809 810 // - its return type shall be a literal type; 811 QualType RT = NewFD->getReturnType(); 812 if (!RT->isDependentType() && 813 RequireLiteralType(NewFD->getLocation(), RT, 814 diag::err_constexpr_non_literal_return)) 815 return false; 816 } 817 818 // - each of its parameter types shall be a literal type; 819 if (!CheckConstexprParameterTypes(*this, NewFD)) 820 return false; 821 822 return true; 823 } 824 825 /// Check the given declaration statement is legal within a constexpr function 826 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 827 /// 828 /// \return true if the body is OK (maybe only as an extension), false if we 829 /// have diagnosed a problem. 830 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 831 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 832 // C++11 [dcl.constexpr]p3 and p4: 833 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 834 // contain only 835 for (const auto *DclIt : DS->decls()) { 836 switch (DclIt->getKind()) { 837 case Decl::StaticAssert: 838 case Decl::Using: 839 case Decl::UsingShadow: 840 case Decl::UsingDirective: 841 case Decl::UnresolvedUsingTypename: 842 case Decl::UnresolvedUsingValue: 843 // - static_assert-declarations 844 // - using-declarations, 845 // - using-directives, 846 continue; 847 848 case Decl::Typedef: 849 case Decl::TypeAlias: { 850 // - typedef declarations and alias-declarations that do not define 851 // classes or enumerations, 852 const auto *TN = cast<TypedefNameDecl>(DclIt); 853 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 854 // Don't allow variably-modified types in constexpr functions. 855 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 856 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 857 << TL.getSourceRange() << TL.getType() 858 << isa<CXXConstructorDecl>(Dcl); 859 return false; 860 } 861 continue; 862 } 863 864 case Decl::Enum: 865 case Decl::CXXRecord: 866 // C++1y allows types to be defined, not just declared. 867 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 868 SemaRef.Diag(DS->getLocStart(), 869 SemaRef.getLangOpts().CPlusPlus14 870 ? diag::warn_cxx11_compat_constexpr_type_definition 871 : diag::ext_constexpr_type_definition) 872 << isa<CXXConstructorDecl>(Dcl); 873 continue; 874 875 case Decl::EnumConstant: 876 case Decl::IndirectField: 877 case Decl::ParmVar: 878 // These can only appear with other declarations which are banned in 879 // C++11 and permitted in C++1y, so ignore them. 880 continue; 881 882 case Decl::Var: { 883 // C++1y [dcl.constexpr]p3 allows anything except: 884 // a definition of a variable of non-literal type or of static or 885 // thread storage duration or for which no initialization is performed. 886 const auto *VD = cast<VarDecl>(DclIt); 887 if (VD->isThisDeclarationADefinition()) { 888 if (VD->isStaticLocal()) { 889 SemaRef.Diag(VD->getLocation(), 890 diag::err_constexpr_local_var_static) 891 << isa<CXXConstructorDecl>(Dcl) 892 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 893 return false; 894 } 895 if (!VD->getType()->isDependentType() && 896 SemaRef.RequireLiteralType( 897 VD->getLocation(), VD->getType(), 898 diag::err_constexpr_local_var_non_literal_type, 899 isa<CXXConstructorDecl>(Dcl))) 900 return false; 901 if (!VD->getType()->isDependentType() && 902 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 903 SemaRef.Diag(VD->getLocation(), 904 diag::err_constexpr_local_var_no_init) 905 << isa<CXXConstructorDecl>(Dcl); 906 return false; 907 } 908 } 909 SemaRef.Diag(VD->getLocation(), 910 SemaRef.getLangOpts().CPlusPlus14 911 ? diag::warn_cxx11_compat_constexpr_local_var 912 : diag::ext_constexpr_local_var) 913 << isa<CXXConstructorDecl>(Dcl); 914 continue; 915 } 916 917 case Decl::NamespaceAlias: 918 case Decl::Function: 919 // These are disallowed in C++11 and permitted in C++1y. Allow them 920 // everywhere as an extension. 921 if (!Cxx1yLoc.isValid()) 922 Cxx1yLoc = DS->getLocStart(); 923 continue; 924 925 default: 926 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 927 << isa<CXXConstructorDecl>(Dcl); 928 return false; 929 } 930 } 931 932 return true; 933 } 934 935 /// Check that the given field is initialized within a constexpr constructor. 936 /// 937 /// \param Dcl The constexpr constructor being checked. 938 /// \param Field The field being checked. This may be a member of an anonymous 939 /// struct or union nested within the class being checked. 940 /// \param Inits All declarations, including anonymous struct/union members and 941 /// indirect members, for which any initialization was provided. 942 /// \param Diagnosed Set to true if an error is produced. 943 static void CheckConstexprCtorInitializer(Sema &SemaRef, 944 const FunctionDecl *Dcl, 945 FieldDecl *Field, 946 llvm::SmallSet<Decl*, 16> &Inits, 947 bool &Diagnosed) { 948 if (Field->isInvalidDecl()) 949 return; 950 951 if (Field->isUnnamedBitfield()) 952 return; 953 954 // Anonymous unions with no variant members and empty anonymous structs do not 955 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 956 // indirect fields don't need initializing. 957 if (Field->isAnonymousStructOrUnion() && 958 (Field->getType()->isUnionType() 959 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 960 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 961 return; 962 963 if (!Inits.count(Field)) { 964 if (!Diagnosed) { 965 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 966 Diagnosed = true; 967 } 968 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 969 } else if (Field->isAnonymousStructOrUnion()) { 970 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 971 for (auto *I : RD->fields()) 972 // If an anonymous union contains an anonymous struct of which any member 973 // is initialized, all members must be initialized. 974 if (!RD->isUnion() || Inits.count(I)) 975 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 976 } 977 } 978 979 /// Check the provided statement is allowed in a constexpr function 980 /// definition. 981 static bool 982 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 983 SmallVectorImpl<SourceLocation> &ReturnStmts, 984 SourceLocation &Cxx1yLoc) { 985 // - its function-body shall be [...] a compound-statement that contains only 986 switch (S->getStmtClass()) { 987 case Stmt::NullStmtClass: 988 // - null statements, 989 return true; 990 991 case Stmt::DeclStmtClass: 992 // - static_assert-declarations 993 // - using-declarations, 994 // - using-directives, 995 // - typedef declarations and alias-declarations that do not define 996 // classes or enumerations, 997 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 998 return false; 999 return true; 1000 1001 case Stmt::ReturnStmtClass: 1002 // - and exactly one return statement; 1003 if (isa<CXXConstructorDecl>(Dcl)) { 1004 // C++1y allows return statements in constexpr constructors. 1005 if (!Cxx1yLoc.isValid()) 1006 Cxx1yLoc = S->getLocStart(); 1007 return true; 1008 } 1009 1010 ReturnStmts.push_back(S->getLocStart()); 1011 return true; 1012 1013 case Stmt::CompoundStmtClass: { 1014 // C++1y allows compound-statements. 1015 if (!Cxx1yLoc.isValid()) 1016 Cxx1yLoc = S->getLocStart(); 1017 1018 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1019 for (auto *BodyIt : CompStmt->body()) { 1020 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1021 Cxx1yLoc)) 1022 return false; 1023 } 1024 return true; 1025 } 1026 1027 case Stmt::AttributedStmtClass: 1028 if (!Cxx1yLoc.isValid()) 1029 Cxx1yLoc = S->getLocStart(); 1030 return true; 1031 1032 case Stmt::IfStmtClass: { 1033 // C++1y allows if-statements. 1034 if (!Cxx1yLoc.isValid()) 1035 Cxx1yLoc = S->getLocStart(); 1036 1037 IfStmt *If = cast<IfStmt>(S); 1038 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1039 Cxx1yLoc)) 1040 return false; 1041 if (If->getElse() && 1042 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1043 Cxx1yLoc)) 1044 return false; 1045 return true; 1046 } 1047 1048 case Stmt::WhileStmtClass: 1049 case Stmt::DoStmtClass: 1050 case Stmt::ForStmtClass: 1051 case Stmt::CXXForRangeStmtClass: 1052 case Stmt::ContinueStmtClass: 1053 // C++1y allows all of these. We don't allow them as extensions in C++11, 1054 // because they don't make sense without variable mutation. 1055 if (!SemaRef.getLangOpts().CPlusPlus14) 1056 break; 1057 if (!Cxx1yLoc.isValid()) 1058 Cxx1yLoc = S->getLocStart(); 1059 for (Stmt::child_range Children = S->children(); Children; ++Children) 1060 if (*Children && 1061 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1062 Cxx1yLoc)) 1063 return false; 1064 return true; 1065 1066 case Stmt::SwitchStmtClass: 1067 case Stmt::CaseStmtClass: 1068 case Stmt::DefaultStmtClass: 1069 case Stmt::BreakStmtClass: 1070 // C++1y allows switch-statements, and since they don't need variable 1071 // mutation, we can reasonably allow them in C++11 as an extension. 1072 if (!Cxx1yLoc.isValid()) 1073 Cxx1yLoc = S->getLocStart(); 1074 for (Stmt::child_range Children = S->children(); Children; ++Children) 1075 if (*Children && 1076 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1077 Cxx1yLoc)) 1078 return false; 1079 return true; 1080 1081 default: 1082 if (!isa<Expr>(S)) 1083 break; 1084 1085 // C++1y allows expression-statements. 1086 if (!Cxx1yLoc.isValid()) 1087 Cxx1yLoc = S->getLocStart(); 1088 return true; 1089 } 1090 1091 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1092 << isa<CXXConstructorDecl>(Dcl); 1093 return false; 1094 } 1095 1096 /// Check the body for the given constexpr function declaration only contains 1097 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1098 /// 1099 /// \return true if the body is OK, false if we have diagnosed a problem. 1100 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1101 if (isa<CXXTryStmt>(Body)) { 1102 // C++11 [dcl.constexpr]p3: 1103 // The definition of a constexpr function shall satisfy the following 1104 // constraints: [...] 1105 // - its function-body shall be = delete, = default, or a 1106 // compound-statement 1107 // 1108 // C++11 [dcl.constexpr]p4: 1109 // In the definition of a constexpr constructor, [...] 1110 // - its function-body shall not be a function-try-block; 1111 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1112 << isa<CXXConstructorDecl>(Dcl); 1113 return false; 1114 } 1115 1116 SmallVector<SourceLocation, 4> ReturnStmts; 1117 1118 // - its function-body shall be [...] a compound-statement that contains only 1119 // [... list of cases ...] 1120 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1121 SourceLocation Cxx1yLoc; 1122 for (auto *BodyIt : CompBody->body()) { 1123 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1124 return false; 1125 } 1126 1127 if (Cxx1yLoc.isValid()) 1128 Diag(Cxx1yLoc, 1129 getLangOpts().CPlusPlus14 1130 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1131 : diag::ext_constexpr_body_invalid_stmt) 1132 << isa<CXXConstructorDecl>(Dcl); 1133 1134 if (const CXXConstructorDecl *Constructor 1135 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1136 const CXXRecordDecl *RD = Constructor->getParent(); 1137 // DR1359: 1138 // - every non-variant non-static data member and base class sub-object 1139 // shall be initialized; 1140 // DR1460: 1141 // - if the class is a union having variant members, exactly one of them 1142 // shall be initialized; 1143 if (RD->isUnion()) { 1144 if (Constructor->getNumCtorInitializers() == 0 && 1145 RD->hasVariantMembers()) { 1146 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1147 return false; 1148 } 1149 } else if (!Constructor->isDependentContext() && 1150 !Constructor->isDelegatingConstructor()) { 1151 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1152 1153 // Skip detailed checking if we have enough initializers, and we would 1154 // allow at most one initializer per member. 1155 bool AnyAnonStructUnionMembers = false; 1156 unsigned Fields = 0; 1157 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1158 E = RD->field_end(); I != E; ++I, ++Fields) { 1159 if (I->isAnonymousStructOrUnion()) { 1160 AnyAnonStructUnionMembers = true; 1161 break; 1162 } 1163 } 1164 // DR1460: 1165 // - if the class is a union-like class, but is not a union, for each of 1166 // its anonymous union members having variant members, exactly one of 1167 // them shall be initialized; 1168 if (AnyAnonStructUnionMembers || 1169 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1170 // Check initialization of non-static data members. Base classes are 1171 // always initialized so do not need to be checked. Dependent bases 1172 // might not have initializers in the member initializer list. 1173 llvm::SmallSet<Decl*, 16> Inits; 1174 for (const auto *I: Constructor->inits()) { 1175 if (FieldDecl *FD = I->getMember()) 1176 Inits.insert(FD); 1177 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1178 Inits.insert(ID->chain_begin(), ID->chain_end()); 1179 } 1180 1181 bool Diagnosed = false; 1182 for (auto *I : RD->fields()) 1183 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1184 if (Diagnosed) 1185 return false; 1186 } 1187 } 1188 } else { 1189 if (ReturnStmts.empty()) { 1190 // C++1y doesn't require constexpr functions to contain a 'return' 1191 // statement. We still do, unless the return type might be void, because 1192 // otherwise if there's no return statement, the function cannot 1193 // be used in a core constant expression. 1194 bool OK = getLangOpts().CPlusPlus14 && 1195 (Dcl->getReturnType()->isVoidType() || 1196 Dcl->getReturnType()->isDependentType()); 1197 Diag(Dcl->getLocation(), 1198 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1199 : diag::err_constexpr_body_no_return); 1200 return OK; 1201 } 1202 if (ReturnStmts.size() > 1) { 1203 Diag(ReturnStmts.back(), 1204 getLangOpts().CPlusPlus14 1205 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1206 : diag::ext_constexpr_body_multiple_return); 1207 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1208 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1209 } 1210 } 1211 1212 // C++11 [dcl.constexpr]p5: 1213 // if no function argument values exist such that the function invocation 1214 // substitution would produce a constant expression, the program is 1215 // ill-formed; no diagnostic required. 1216 // C++11 [dcl.constexpr]p3: 1217 // - every constructor call and implicit conversion used in initializing the 1218 // return value shall be one of those allowed in a constant expression. 1219 // C++11 [dcl.constexpr]p4: 1220 // - every constructor involved in initializing non-static data members and 1221 // base class sub-objects shall be a constexpr constructor. 1222 SmallVector<PartialDiagnosticAt, 8> Diags; 1223 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1224 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1225 << isa<CXXConstructorDecl>(Dcl); 1226 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1227 Diag(Diags[I].first, Diags[I].second); 1228 // Don't return false here: we allow this for compatibility in 1229 // system headers. 1230 } 1231 1232 return true; 1233 } 1234 1235 /// isCurrentClassName - Determine whether the identifier II is the 1236 /// name of the class type currently being defined. In the case of 1237 /// nested classes, this will only return true if II is the name of 1238 /// the innermost class. 1239 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1240 const CXXScopeSpec *SS) { 1241 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1242 1243 CXXRecordDecl *CurDecl; 1244 if (SS && SS->isSet() && !SS->isInvalid()) { 1245 DeclContext *DC = computeDeclContext(*SS, true); 1246 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1247 } else 1248 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1249 1250 if (CurDecl && CurDecl->getIdentifier()) 1251 return &II == CurDecl->getIdentifier(); 1252 return false; 1253 } 1254 1255 /// \brief Determine whether the identifier II is a typo for the name of 1256 /// the class type currently being defined. If so, update it to the identifier 1257 /// that should have been used. 1258 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1259 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1260 1261 if (!getLangOpts().SpellChecking) 1262 return false; 1263 1264 CXXRecordDecl *CurDecl; 1265 if (SS && SS->isSet() && !SS->isInvalid()) { 1266 DeclContext *DC = computeDeclContext(*SS, true); 1267 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1268 } else 1269 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1270 1271 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1272 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1273 < II->getLength()) { 1274 II = CurDecl->getIdentifier(); 1275 return true; 1276 } 1277 1278 return false; 1279 } 1280 1281 /// \brief Determine whether the given class is a base class of the given 1282 /// class, including looking at dependent bases. 1283 static bool findCircularInheritance(const CXXRecordDecl *Class, 1284 const CXXRecordDecl *Current) { 1285 SmallVector<const CXXRecordDecl*, 8> Queue; 1286 1287 Class = Class->getCanonicalDecl(); 1288 while (true) { 1289 for (const auto &I : Current->bases()) { 1290 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1291 if (!Base) 1292 continue; 1293 1294 Base = Base->getDefinition(); 1295 if (!Base) 1296 continue; 1297 1298 if (Base->getCanonicalDecl() == Class) 1299 return true; 1300 1301 Queue.push_back(Base); 1302 } 1303 1304 if (Queue.empty()) 1305 return false; 1306 1307 Current = Queue.pop_back_val(); 1308 } 1309 1310 return false; 1311 } 1312 1313 /// \brief Perform propagation of DLL attributes from a derived class to a 1314 /// templated base class for MS compatibility. 1315 static void propagateDLLAttrToBaseClassTemplate( 1316 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1317 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1318 if (getDLLAttr( 1319 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1320 // If the base class template has a DLL attribute, don't try to change it. 1321 return; 1322 } 1323 1324 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1325 // If the base class is not already specialized, we can do the propagation. 1326 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1327 NewAttr->setInherited(true); 1328 BaseTemplateSpec->addAttr(NewAttr); 1329 return; 1330 } 1331 1332 bool DifferentAttribute = false; 1333 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1334 if (!SpecializationAttr->isInherited()) { 1335 // The template has previously been specialized or instantiated with an 1336 // explicit attribute. We should not try to change it. 1337 return; 1338 } 1339 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1340 // The specialization already has the right attribute. 1341 return; 1342 } 1343 DifferentAttribute = true; 1344 } 1345 1346 // The template was previously instantiated or explicitly specialized without 1347 // a dll attribute, or the template was previously instantiated with a 1348 // different inherited attribute. It's too late for us to change the 1349 // attribute, so warn that this is unsupported. 1350 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1351 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1352 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1353 if (BaseTemplateSpec->isExplicitSpecialization()) { 1354 S.Diag(BaseTemplateSpec->getLocation(), 1355 diag::note_template_class_explicit_specialization_was_here) 1356 << BaseTemplateSpec; 1357 } else { 1358 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1359 diag::note_template_class_instantiation_was_here) 1360 << BaseTemplateSpec; 1361 } 1362 } 1363 1364 /// \brief Check the validity of a C++ base class specifier. 1365 /// 1366 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1367 /// and returns NULL otherwise. 1368 CXXBaseSpecifier * 1369 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1370 SourceRange SpecifierRange, 1371 bool Virtual, AccessSpecifier Access, 1372 TypeSourceInfo *TInfo, 1373 SourceLocation EllipsisLoc) { 1374 QualType BaseType = TInfo->getType(); 1375 1376 // C++ [class.union]p1: 1377 // A union shall not have base classes. 1378 if (Class->isUnion()) { 1379 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1380 << SpecifierRange; 1381 return nullptr; 1382 } 1383 1384 if (EllipsisLoc.isValid() && 1385 !TInfo->getType()->containsUnexpandedParameterPack()) { 1386 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1387 << TInfo->getTypeLoc().getSourceRange(); 1388 EllipsisLoc = SourceLocation(); 1389 } 1390 1391 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1392 1393 if (BaseType->isDependentType()) { 1394 // Make sure that we don't have circular inheritance among our dependent 1395 // bases. For non-dependent bases, the check for completeness below handles 1396 // this. 1397 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1398 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1399 ((BaseDecl = BaseDecl->getDefinition()) && 1400 findCircularInheritance(Class, BaseDecl))) { 1401 Diag(BaseLoc, diag::err_circular_inheritance) 1402 << BaseType << Context.getTypeDeclType(Class); 1403 1404 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1405 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1406 << BaseType; 1407 1408 return nullptr; 1409 } 1410 } 1411 1412 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1413 Class->getTagKind() == TTK_Class, 1414 Access, TInfo, EllipsisLoc); 1415 } 1416 1417 // Base specifiers must be record types. 1418 if (!BaseType->isRecordType()) { 1419 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1420 return nullptr; 1421 } 1422 1423 // C++ [class.union]p1: 1424 // A union shall not be used as a base class. 1425 if (BaseType->isUnionType()) { 1426 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1427 return nullptr; 1428 } 1429 1430 // For the MS ABI, propagate DLL attributes to base class templates. 1431 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1432 if (Attr *ClassAttr = getDLLAttr(Class)) { 1433 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1434 BaseType->getAsCXXRecordDecl())) { 1435 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1436 BaseTemplate, BaseLoc); 1437 } 1438 } 1439 } 1440 1441 // C++ [class.derived]p2: 1442 // The class-name in a base-specifier shall not be an incompletely 1443 // defined class. 1444 if (RequireCompleteType(BaseLoc, BaseType, 1445 diag::err_incomplete_base_class, SpecifierRange)) { 1446 Class->setInvalidDecl(); 1447 return nullptr; 1448 } 1449 1450 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1451 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1452 assert(BaseDecl && "Record type has no declaration"); 1453 BaseDecl = BaseDecl->getDefinition(); 1454 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1455 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1456 assert(CXXBaseDecl && "Base type is not a C++ type"); 1457 1458 // A class which contains a flexible array member is not suitable for use as a 1459 // base class: 1460 // - If the layout determines that a base comes before another base, 1461 // the flexible array member would index into the subsequent base. 1462 // - If the layout determines that base comes before the derived class, 1463 // the flexible array member would index into the derived class. 1464 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1465 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1466 << CXXBaseDecl->getDeclName(); 1467 return nullptr; 1468 } 1469 1470 // C++ [class]p3: 1471 // If a class is marked final and it appears as a base-type-specifier in 1472 // base-clause, the program is ill-formed. 1473 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1474 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1475 << CXXBaseDecl->getDeclName() 1476 << FA->isSpelledAsSealed(); 1477 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1478 << CXXBaseDecl->getDeclName() << FA->getRange(); 1479 return nullptr; 1480 } 1481 1482 if (BaseDecl->isInvalidDecl()) 1483 Class->setInvalidDecl(); 1484 1485 // Create the base specifier. 1486 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1487 Class->getTagKind() == TTK_Class, 1488 Access, TInfo, EllipsisLoc); 1489 } 1490 1491 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1492 /// one entry in the base class list of a class specifier, for 1493 /// example: 1494 /// class foo : public bar, virtual private baz { 1495 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1496 BaseResult 1497 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1498 ParsedAttributes &Attributes, 1499 bool Virtual, AccessSpecifier Access, 1500 ParsedType basetype, SourceLocation BaseLoc, 1501 SourceLocation EllipsisLoc) { 1502 if (!classdecl) 1503 return true; 1504 1505 AdjustDeclIfTemplate(classdecl); 1506 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1507 if (!Class) 1508 return true; 1509 1510 // We haven't yet attached the base specifiers. 1511 Class->setIsParsingBaseSpecifiers(); 1512 1513 // We do not support any C++11 attributes on base-specifiers yet. 1514 // Diagnose any attributes we see. 1515 if (!Attributes.empty()) { 1516 for (AttributeList *Attr = Attributes.getList(); Attr; 1517 Attr = Attr->getNext()) { 1518 if (Attr->isInvalid() || 1519 Attr->getKind() == AttributeList::IgnoredAttribute) 1520 continue; 1521 Diag(Attr->getLoc(), 1522 Attr->getKind() == AttributeList::UnknownAttribute 1523 ? diag::warn_unknown_attribute_ignored 1524 : diag::err_base_specifier_attribute) 1525 << Attr->getName(); 1526 } 1527 } 1528 1529 TypeSourceInfo *TInfo = nullptr; 1530 GetTypeFromParser(basetype, &TInfo); 1531 1532 if (EllipsisLoc.isInvalid() && 1533 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1534 UPPC_BaseType)) 1535 return true; 1536 1537 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1538 Virtual, Access, TInfo, 1539 EllipsisLoc)) 1540 return BaseSpec; 1541 else 1542 Class->setInvalidDecl(); 1543 1544 return true; 1545 } 1546 1547 /// Use small set to collect indirect bases. As this is only used 1548 /// locally, there's no need to abstract the small size parameter. 1549 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 1550 1551 /// \brief Recursively add the bases of Type. Don't add Type itself. 1552 static void 1553 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 1554 const QualType &Type) 1555 { 1556 // Even though the incoming type is a base, it might not be 1557 // a class -- it could be a template parm, for instance. 1558 if (auto Rec = Type->getAs<RecordType>()) { 1559 auto Decl = Rec->getAsCXXRecordDecl(); 1560 1561 // Iterate over its bases. 1562 for (const auto &BaseSpec : Decl->bases()) { 1563 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 1564 .getUnqualifiedType(); 1565 if (Set.insert(Base).second) 1566 // If we've not already seen it, recurse. 1567 NoteIndirectBases(Context, Set, Base); 1568 } 1569 } 1570 } 1571 1572 /// \brief Performs the actual work of attaching the given base class 1573 /// specifiers to a C++ class. 1574 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1575 unsigned NumBases) { 1576 if (NumBases == 0) 1577 return false; 1578 1579 // Used to keep track of which base types we have already seen, so 1580 // that we can properly diagnose redundant direct base types. Note 1581 // that the key is always the unqualified canonical type of the base 1582 // class. 1583 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1584 1585 // Used to track indirect bases so we can see if a direct base is 1586 // ambiguous. 1587 IndirectBaseSet IndirectBaseTypes; 1588 1589 // Copy non-redundant base specifiers into permanent storage. 1590 unsigned NumGoodBases = 0; 1591 bool Invalid = false; 1592 for (unsigned idx = 0; idx < NumBases; ++idx) { 1593 QualType NewBaseType 1594 = Context.getCanonicalType(Bases[idx]->getType()); 1595 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1596 1597 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1598 if (KnownBase) { 1599 // C++ [class.mi]p3: 1600 // A class shall not be specified as a direct base class of a 1601 // derived class more than once. 1602 Diag(Bases[idx]->getLocStart(), 1603 diag::err_duplicate_base_class) 1604 << KnownBase->getType() 1605 << Bases[idx]->getSourceRange(); 1606 1607 // Delete the duplicate base class specifier; we're going to 1608 // overwrite its pointer later. 1609 Context.Deallocate(Bases[idx]); 1610 1611 Invalid = true; 1612 } else { 1613 // Okay, add this new base class. 1614 KnownBase = Bases[idx]; 1615 Bases[NumGoodBases++] = Bases[idx]; 1616 1617 // Note this base's direct & indirect bases, if there could be ambiguity. 1618 if (NumBases > 1) 1619 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 1620 1621 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1622 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1623 if (Class->isInterface() && 1624 (!RD->isInterface() || 1625 KnownBase->getAccessSpecifier() != AS_public)) { 1626 // The Microsoft extension __interface does not permit bases that 1627 // are not themselves public interfaces. 1628 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1629 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1630 << RD->getSourceRange(); 1631 Invalid = true; 1632 } 1633 if (RD->hasAttr<WeakAttr>()) 1634 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1635 } 1636 } 1637 } 1638 1639 // Attach the remaining base class specifiers to the derived class. 1640 Class->setBases(Bases, NumGoodBases); 1641 1642 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 1643 // Check whether this direct base is inaccessible due to ambiguity. 1644 QualType BaseType = Bases[idx]->getType(); 1645 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 1646 .getUnqualifiedType(); 1647 1648 if (IndirectBaseTypes.count(CanonicalBase)) { 1649 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1650 /*DetectVirtual=*/true); 1651 bool found 1652 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 1653 assert(found); 1654 (void)found; 1655 1656 if (Paths.isAmbiguous(CanonicalBase)) 1657 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 1658 << BaseType << getAmbiguousPathsDisplayString(Paths) 1659 << Bases[idx]->getSourceRange(); 1660 else 1661 assert(Bases[idx]->isVirtual()); 1662 } 1663 1664 // Delete the base class specifier, since its data has been copied 1665 // into the CXXRecordDecl. 1666 Context.Deallocate(Bases[idx]); 1667 } 1668 1669 return Invalid; 1670 } 1671 1672 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1673 /// class, after checking whether there are any duplicate base 1674 /// classes. 1675 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1676 unsigned NumBases) { 1677 if (!ClassDecl || !Bases || !NumBases) 1678 return; 1679 1680 AdjustDeclIfTemplate(ClassDecl); 1681 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1682 } 1683 1684 /// \brief Determine whether the type \p Derived is a C++ class that is 1685 /// derived from the type \p Base. 1686 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1687 if (!getLangOpts().CPlusPlus) 1688 return false; 1689 1690 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1691 if (!DerivedRD) 1692 return false; 1693 1694 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1695 if (!BaseRD) 1696 return false; 1697 1698 // If either the base or the derived type is invalid, don't try to 1699 // check whether one is derived from the other. 1700 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1701 return false; 1702 1703 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1704 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1705 } 1706 1707 /// \brief Determine whether the type \p Derived is a C++ class that is 1708 /// derived from the type \p Base. 1709 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1710 if (!getLangOpts().CPlusPlus) 1711 return false; 1712 1713 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1714 if (!DerivedRD) 1715 return false; 1716 1717 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1718 if (!BaseRD) 1719 return false; 1720 1721 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1722 } 1723 1724 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1725 CXXCastPath &BasePathArray) { 1726 assert(BasePathArray.empty() && "Base path array must be empty!"); 1727 assert(Paths.isRecordingPaths() && "Must record paths!"); 1728 1729 const CXXBasePath &Path = Paths.front(); 1730 1731 // We first go backward and check if we have a virtual base. 1732 // FIXME: It would be better if CXXBasePath had the base specifier for 1733 // the nearest virtual base. 1734 unsigned Start = 0; 1735 for (unsigned I = Path.size(); I != 0; --I) { 1736 if (Path[I - 1].Base->isVirtual()) { 1737 Start = I - 1; 1738 break; 1739 } 1740 } 1741 1742 // Now add all bases. 1743 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1744 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1745 } 1746 1747 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1748 /// conversion (where Derived and Base are class types) is 1749 /// well-formed, meaning that the conversion is unambiguous (and 1750 /// that all of the base classes are accessible). Returns true 1751 /// and emits a diagnostic if the code is ill-formed, returns false 1752 /// otherwise. Loc is the location where this routine should point to 1753 /// if there is an error, and Range is the source range to highlight 1754 /// if there is an error. 1755 bool 1756 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1757 unsigned InaccessibleBaseID, 1758 unsigned AmbigiousBaseConvID, 1759 SourceLocation Loc, SourceRange Range, 1760 DeclarationName Name, 1761 CXXCastPath *BasePath) { 1762 // First, determine whether the path from Derived to Base is 1763 // ambiguous. This is slightly more expensive than checking whether 1764 // the Derived to Base conversion exists, because here we need to 1765 // explore multiple paths to determine if there is an ambiguity. 1766 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1767 /*DetectVirtual=*/false); 1768 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1769 assert(DerivationOkay && 1770 "Can only be used with a derived-to-base conversion"); 1771 (void)DerivationOkay; 1772 1773 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1774 if (InaccessibleBaseID) { 1775 // Check that the base class can be accessed. 1776 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1777 InaccessibleBaseID)) { 1778 case AR_inaccessible: 1779 return true; 1780 case AR_accessible: 1781 case AR_dependent: 1782 case AR_delayed: 1783 break; 1784 } 1785 } 1786 1787 // Build a base path if necessary. 1788 if (BasePath) 1789 BuildBasePathArray(Paths, *BasePath); 1790 return false; 1791 } 1792 1793 if (AmbigiousBaseConvID) { 1794 // We know that the derived-to-base conversion is ambiguous, and 1795 // we're going to produce a diagnostic. Perform the derived-to-base 1796 // search just one more time to compute all of the possible paths so 1797 // that we can print them out. This is more expensive than any of 1798 // the previous derived-to-base checks we've done, but at this point 1799 // performance isn't as much of an issue. 1800 Paths.clear(); 1801 Paths.setRecordingPaths(true); 1802 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1803 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1804 (void)StillOkay; 1805 1806 // Build up a textual representation of the ambiguous paths, e.g., 1807 // D -> B -> A, that will be used to illustrate the ambiguous 1808 // conversions in the diagnostic. We only print one of the paths 1809 // to each base class subobject. 1810 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1811 1812 Diag(Loc, AmbigiousBaseConvID) 1813 << Derived << Base << PathDisplayStr << Range << Name; 1814 } 1815 return true; 1816 } 1817 1818 bool 1819 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1820 SourceLocation Loc, SourceRange Range, 1821 CXXCastPath *BasePath, 1822 bool IgnoreAccess) { 1823 return CheckDerivedToBaseConversion(Derived, Base, 1824 IgnoreAccess ? 0 1825 : diag::err_upcast_to_inaccessible_base, 1826 diag::err_ambiguous_derived_to_base_conv, 1827 Loc, Range, DeclarationName(), 1828 BasePath); 1829 } 1830 1831 1832 /// @brief Builds a string representing ambiguous paths from a 1833 /// specific derived class to different subobjects of the same base 1834 /// class. 1835 /// 1836 /// This function builds a string that can be used in error messages 1837 /// to show the different paths that one can take through the 1838 /// inheritance hierarchy to go from the derived class to different 1839 /// subobjects of a base class. The result looks something like this: 1840 /// @code 1841 /// struct D -> struct B -> struct A 1842 /// struct D -> struct C -> struct A 1843 /// @endcode 1844 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1845 std::string PathDisplayStr; 1846 std::set<unsigned> DisplayedPaths; 1847 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1848 Path != Paths.end(); ++Path) { 1849 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1850 // We haven't displayed a path to this particular base 1851 // class subobject yet. 1852 PathDisplayStr += "\n "; 1853 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1854 for (CXXBasePath::const_iterator Element = Path->begin(); 1855 Element != Path->end(); ++Element) 1856 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1857 } 1858 } 1859 1860 return PathDisplayStr; 1861 } 1862 1863 //===----------------------------------------------------------------------===// 1864 // C++ class member Handling 1865 //===----------------------------------------------------------------------===// 1866 1867 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1868 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1869 SourceLocation ASLoc, 1870 SourceLocation ColonLoc, 1871 AttributeList *Attrs) { 1872 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1873 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1874 ASLoc, ColonLoc); 1875 CurContext->addHiddenDecl(ASDecl); 1876 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1877 } 1878 1879 /// CheckOverrideControl - Check C++11 override control semantics. 1880 void Sema::CheckOverrideControl(NamedDecl *D) { 1881 if (D->isInvalidDecl()) 1882 return; 1883 1884 // We only care about "override" and "final" declarations. 1885 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1886 return; 1887 1888 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1889 1890 // We can't check dependent instance methods. 1891 if (MD && MD->isInstance() && 1892 (MD->getParent()->hasAnyDependentBases() || 1893 MD->getType()->isDependentType())) 1894 return; 1895 1896 if (MD && !MD->isVirtual()) { 1897 // If we have a non-virtual method, check if if hides a virtual method. 1898 // (In that case, it's most likely the method has the wrong type.) 1899 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1900 FindHiddenVirtualMethods(MD, OverloadedMethods); 1901 1902 if (!OverloadedMethods.empty()) { 1903 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1904 Diag(OA->getLocation(), 1905 diag::override_keyword_hides_virtual_member_function) 1906 << "override" << (OverloadedMethods.size() > 1); 1907 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1908 Diag(FA->getLocation(), 1909 diag::override_keyword_hides_virtual_member_function) 1910 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1911 << (OverloadedMethods.size() > 1); 1912 } 1913 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1914 MD->setInvalidDecl(); 1915 return; 1916 } 1917 // Fall through into the general case diagnostic. 1918 // FIXME: We might want to attempt typo correction here. 1919 } 1920 1921 if (!MD || !MD->isVirtual()) { 1922 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1923 Diag(OA->getLocation(), 1924 diag::override_keyword_only_allowed_on_virtual_member_functions) 1925 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1926 D->dropAttr<OverrideAttr>(); 1927 } 1928 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1929 Diag(FA->getLocation(), 1930 diag::override_keyword_only_allowed_on_virtual_member_functions) 1931 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1932 << FixItHint::CreateRemoval(FA->getLocation()); 1933 D->dropAttr<FinalAttr>(); 1934 } 1935 return; 1936 } 1937 1938 // C++11 [class.virtual]p5: 1939 // If a function is marked with the virt-specifier override and 1940 // does not override a member function of a base class, the program is 1941 // ill-formed. 1942 bool HasOverriddenMethods = 1943 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1944 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1945 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1946 << MD->getDeclName(); 1947 } 1948 1949 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1950 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1951 return; 1952 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1953 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1954 isa<CXXDestructorDecl>(MD)) 1955 return; 1956 1957 SourceLocation Loc = MD->getLocation(); 1958 SourceLocation SpellingLoc = Loc; 1959 if (getSourceManager().isMacroArgExpansion(Loc)) 1960 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1961 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1962 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1963 return; 1964 1965 if (MD->size_overridden_methods() > 0) { 1966 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 1967 << MD->getDeclName(); 1968 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 1969 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 1970 } 1971 } 1972 1973 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1974 /// function overrides a virtual member function marked 'final', according to 1975 /// C++11 [class.virtual]p4. 1976 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1977 const CXXMethodDecl *Old) { 1978 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1979 if (!FA) 1980 return false; 1981 1982 Diag(New->getLocation(), diag::err_final_function_overridden) 1983 << New->getDeclName() 1984 << FA->isSpelledAsSealed(); 1985 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1986 return true; 1987 } 1988 1989 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1990 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1991 // FIXME: Destruction of ObjC lifetime types has side-effects. 1992 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1993 return !RD->isCompleteDefinition() || 1994 !RD->hasTrivialDefaultConstructor() || 1995 !RD->hasTrivialDestructor(); 1996 return false; 1997 } 1998 1999 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2000 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2001 if (it->isDeclspecPropertyAttribute()) 2002 return it; 2003 return nullptr; 2004 } 2005 2006 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2007 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2008 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2009 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2010 /// present (but parsing it has been deferred). 2011 NamedDecl * 2012 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2013 MultiTemplateParamsArg TemplateParameterLists, 2014 Expr *BW, const VirtSpecifiers &VS, 2015 InClassInitStyle InitStyle) { 2016 const DeclSpec &DS = D.getDeclSpec(); 2017 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2018 DeclarationName Name = NameInfo.getName(); 2019 SourceLocation Loc = NameInfo.getLoc(); 2020 2021 // For anonymous bitfields, the location should point to the type. 2022 if (Loc.isInvalid()) 2023 Loc = D.getLocStart(); 2024 2025 Expr *BitWidth = static_cast<Expr*>(BW); 2026 2027 assert(isa<CXXRecordDecl>(CurContext)); 2028 assert(!DS.isFriendSpecified()); 2029 2030 bool isFunc = D.isDeclarationOfFunction(); 2031 2032 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2033 // The Microsoft extension __interface only permits public member functions 2034 // and prohibits constructors, destructors, operators, non-public member 2035 // functions, static methods and data members. 2036 unsigned InvalidDecl; 2037 bool ShowDeclName = true; 2038 if (!isFunc) 2039 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2040 else if (AS != AS_public) 2041 InvalidDecl = 2; 2042 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2043 InvalidDecl = 3; 2044 else switch (Name.getNameKind()) { 2045 case DeclarationName::CXXConstructorName: 2046 InvalidDecl = 4; 2047 ShowDeclName = false; 2048 break; 2049 2050 case DeclarationName::CXXDestructorName: 2051 InvalidDecl = 5; 2052 ShowDeclName = false; 2053 break; 2054 2055 case DeclarationName::CXXOperatorName: 2056 case DeclarationName::CXXConversionFunctionName: 2057 InvalidDecl = 6; 2058 break; 2059 2060 default: 2061 InvalidDecl = 0; 2062 break; 2063 } 2064 2065 if (InvalidDecl) { 2066 if (ShowDeclName) 2067 Diag(Loc, diag::err_invalid_member_in_interface) 2068 << (InvalidDecl-1) << Name; 2069 else 2070 Diag(Loc, diag::err_invalid_member_in_interface) 2071 << (InvalidDecl-1) << ""; 2072 return nullptr; 2073 } 2074 } 2075 2076 // C++ 9.2p6: A member shall not be declared to have automatic storage 2077 // duration (auto, register) or with the extern storage-class-specifier. 2078 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2079 // data members and cannot be applied to names declared const or static, 2080 // and cannot be applied to reference members. 2081 switch (DS.getStorageClassSpec()) { 2082 case DeclSpec::SCS_unspecified: 2083 case DeclSpec::SCS_typedef: 2084 case DeclSpec::SCS_static: 2085 break; 2086 case DeclSpec::SCS_mutable: 2087 if (isFunc) { 2088 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2089 2090 // FIXME: It would be nicer if the keyword was ignored only for this 2091 // declarator. Otherwise we could get follow-up errors. 2092 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2093 } 2094 break; 2095 default: 2096 Diag(DS.getStorageClassSpecLoc(), 2097 diag::err_storageclass_invalid_for_member); 2098 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2099 break; 2100 } 2101 2102 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2103 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2104 !isFunc); 2105 2106 if (DS.isConstexprSpecified() && isInstField) { 2107 SemaDiagnosticBuilder B = 2108 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2109 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2110 if (InitStyle == ICIS_NoInit) { 2111 B << 0 << 0; 2112 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2113 B << FixItHint::CreateRemoval(ConstexprLoc); 2114 else { 2115 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2116 D.getMutableDeclSpec().ClearConstexprSpec(); 2117 const char *PrevSpec; 2118 unsigned DiagID; 2119 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2120 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2121 (void)Failed; 2122 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2123 } 2124 } else { 2125 B << 1; 2126 const char *PrevSpec; 2127 unsigned DiagID; 2128 if (D.getMutableDeclSpec().SetStorageClassSpec( 2129 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2130 Context.getPrintingPolicy())) { 2131 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2132 "This is the only DeclSpec that should fail to be applied"); 2133 B << 1; 2134 } else { 2135 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2136 isInstField = false; 2137 } 2138 } 2139 } 2140 2141 NamedDecl *Member; 2142 if (isInstField) { 2143 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2144 2145 // Data members must have identifiers for names. 2146 if (!Name.isIdentifier()) { 2147 Diag(Loc, diag::err_bad_variable_name) 2148 << Name; 2149 return nullptr; 2150 } 2151 2152 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2153 2154 // Member field could not be with "template" keyword. 2155 // So TemplateParameterLists should be empty in this case. 2156 if (TemplateParameterLists.size()) { 2157 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2158 if (TemplateParams->size()) { 2159 // There is no such thing as a member field template. 2160 Diag(D.getIdentifierLoc(), diag::err_template_member) 2161 << II 2162 << SourceRange(TemplateParams->getTemplateLoc(), 2163 TemplateParams->getRAngleLoc()); 2164 } else { 2165 // There is an extraneous 'template<>' for this member. 2166 Diag(TemplateParams->getTemplateLoc(), 2167 diag::err_template_member_noparams) 2168 << II 2169 << SourceRange(TemplateParams->getTemplateLoc(), 2170 TemplateParams->getRAngleLoc()); 2171 } 2172 return nullptr; 2173 } 2174 2175 if (SS.isSet() && !SS.isInvalid()) { 2176 // The user provided a superfluous scope specifier inside a class 2177 // definition: 2178 // 2179 // class X { 2180 // int X::member; 2181 // }; 2182 if (DeclContext *DC = computeDeclContext(SS, false)) 2183 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2184 else 2185 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2186 << Name << SS.getRange(); 2187 2188 SS.clear(); 2189 } 2190 2191 AttributeList *MSPropertyAttr = 2192 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2193 if (MSPropertyAttr) { 2194 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2195 BitWidth, InitStyle, AS, MSPropertyAttr); 2196 if (!Member) 2197 return nullptr; 2198 isInstField = false; 2199 } else { 2200 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2201 BitWidth, InitStyle, AS); 2202 assert(Member && "HandleField never returns null"); 2203 } 2204 } else { 2205 assert(InitStyle == ICIS_NoInit || 2206 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2207 2208 Member = HandleDeclarator(S, D, TemplateParameterLists); 2209 if (!Member) 2210 return nullptr; 2211 2212 // Non-instance-fields can't have a bitfield. 2213 if (BitWidth) { 2214 if (Member->isInvalidDecl()) { 2215 // don't emit another diagnostic. 2216 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 2217 // C++ 9.6p3: A bit-field shall not be a static member. 2218 // "static member 'A' cannot be a bit-field" 2219 Diag(Loc, diag::err_static_not_bitfield) 2220 << Name << BitWidth->getSourceRange(); 2221 } else if (isa<TypedefDecl>(Member)) { 2222 // "typedef member 'x' cannot be a bit-field" 2223 Diag(Loc, diag::err_typedef_not_bitfield) 2224 << Name << BitWidth->getSourceRange(); 2225 } else { 2226 // A function typedef ("typedef int f(); f a;"). 2227 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2228 Diag(Loc, diag::err_not_integral_type_bitfield) 2229 << Name << cast<ValueDecl>(Member)->getType() 2230 << BitWidth->getSourceRange(); 2231 } 2232 2233 BitWidth = nullptr; 2234 Member->setInvalidDecl(); 2235 } 2236 2237 Member->setAccess(AS); 2238 2239 // If we have declared a member function template or static data member 2240 // template, set the access of the templated declaration as well. 2241 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2242 FunTmpl->getTemplatedDecl()->setAccess(AS); 2243 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2244 VarTmpl->getTemplatedDecl()->setAccess(AS); 2245 } 2246 2247 if (VS.isOverrideSpecified()) 2248 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2249 if (VS.isFinalSpecified()) 2250 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2251 VS.isFinalSpelledSealed())); 2252 2253 if (VS.getLastLocation().isValid()) { 2254 // Update the end location of a method that has a virt-specifiers. 2255 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2256 MD->setRangeEnd(VS.getLastLocation()); 2257 } 2258 2259 CheckOverrideControl(Member); 2260 2261 assert((Name || isInstField) && "No identifier for non-field ?"); 2262 2263 if (isInstField) { 2264 FieldDecl *FD = cast<FieldDecl>(Member); 2265 FieldCollector->Add(FD); 2266 2267 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2268 // Remember all explicit private FieldDecls that have a name, no side 2269 // effects and are not part of a dependent type declaration. 2270 if (!FD->isImplicit() && FD->getDeclName() && 2271 FD->getAccess() == AS_private && 2272 !FD->hasAttr<UnusedAttr>() && 2273 !FD->getParent()->isDependentContext() && 2274 !InitializationHasSideEffects(*FD)) 2275 UnusedPrivateFields.insert(FD); 2276 } 2277 } 2278 2279 return Member; 2280 } 2281 2282 namespace { 2283 class UninitializedFieldVisitor 2284 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2285 Sema &S; 2286 // List of Decls to generate a warning on. Also remove Decls that become 2287 // initialized. 2288 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2289 // List of base classes of the record. Classes are removed after their 2290 // initializers. 2291 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 2292 // Vector of decls to be removed from the Decl set prior to visiting the 2293 // nodes. These Decls may have been initialized in the prior initializer. 2294 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2295 // If non-null, add a note to the warning pointing back to the constructor. 2296 const CXXConstructorDecl *Constructor; 2297 // Variables to hold state when processing an initializer list. When 2298 // InitList is true, special case initialization of FieldDecls matching 2299 // InitListFieldDecl. 2300 bool InitList; 2301 FieldDecl *InitListFieldDecl; 2302 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2303 2304 public: 2305 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2306 UninitializedFieldVisitor(Sema &S, 2307 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 2308 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 2309 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 2310 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 2311 2312 // Returns true if the use of ME is not an uninitialized use. 2313 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2314 bool CheckReferenceOnly) { 2315 llvm::SmallVector<FieldDecl*, 4> Fields; 2316 bool ReferenceField = false; 2317 while (ME) { 2318 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2319 if (!FD) 2320 return false; 2321 Fields.push_back(FD); 2322 if (FD->getType()->isReferenceType()) 2323 ReferenceField = true; 2324 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2325 } 2326 2327 // Binding a reference to an unintialized field is not an 2328 // uninitialized use. 2329 if (CheckReferenceOnly && !ReferenceField) 2330 return true; 2331 2332 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2333 // Discard the first field since it is the field decl that is being 2334 // initialized. 2335 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2336 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2337 } 2338 2339 for (auto UsedIter = UsedFieldIndex.begin(), 2340 UsedEnd = UsedFieldIndex.end(), 2341 OrigIter = InitFieldIndex.begin(), 2342 OrigEnd = InitFieldIndex.end(); 2343 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2344 if (*UsedIter < *OrigIter) 2345 return true; 2346 if (*UsedIter > *OrigIter) 2347 break; 2348 } 2349 2350 return false; 2351 } 2352 2353 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2354 bool AddressOf) { 2355 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2356 return; 2357 2358 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2359 // or union. 2360 MemberExpr *FieldME = ME; 2361 2362 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2363 2364 Expr *Base = ME; 2365 while (MemberExpr *SubME = 2366 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 2367 2368 if (isa<VarDecl>(SubME->getMemberDecl())) 2369 return; 2370 2371 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2372 if (!FD->isAnonymousStructOrUnion()) 2373 FieldME = SubME; 2374 2375 if (!FieldME->getType().isPODType(S.Context)) 2376 AllPODFields = false; 2377 2378 Base = SubME->getBase(); 2379 } 2380 2381 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 2382 return; 2383 2384 if (AddressOf && AllPODFields) 2385 return; 2386 2387 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2388 2389 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 2390 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 2391 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 2392 } 2393 2394 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 2395 QualType T = BaseCast->getType(); 2396 if (T->isPointerType() && 2397 BaseClasses.count(T->getPointeeType())) { 2398 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 2399 << T->getPointeeType() << FoundVD; 2400 } 2401 } 2402 } 2403 2404 if (!Decls.count(FoundVD)) 2405 return; 2406 2407 const bool IsReference = FoundVD->getType()->isReferenceType(); 2408 2409 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2410 // Special checking for initializer lists. 2411 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2412 return; 2413 } 2414 } else { 2415 // Prevent double warnings on use of unbounded references. 2416 if (CheckReferenceOnly && !IsReference) 2417 return; 2418 } 2419 2420 unsigned diag = IsReference 2421 ? diag::warn_reference_field_is_uninit 2422 : diag::warn_field_is_uninit; 2423 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2424 if (Constructor) 2425 S.Diag(Constructor->getLocation(), 2426 diag::note_uninit_in_this_constructor) 2427 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2428 2429 } 2430 2431 void HandleValue(Expr *E, bool AddressOf) { 2432 E = E->IgnoreParens(); 2433 2434 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2435 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2436 AddressOf /*AddressOf*/); 2437 return; 2438 } 2439 2440 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2441 Visit(CO->getCond()); 2442 HandleValue(CO->getTrueExpr(), AddressOf); 2443 HandleValue(CO->getFalseExpr(), AddressOf); 2444 return; 2445 } 2446 2447 if (BinaryConditionalOperator *BCO = 2448 dyn_cast<BinaryConditionalOperator>(E)) { 2449 Visit(BCO->getCond()); 2450 HandleValue(BCO->getFalseExpr(), AddressOf); 2451 return; 2452 } 2453 2454 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2455 HandleValue(OVE->getSourceExpr(), AddressOf); 2456 return; 2457 } 2458 2459 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2460 switch (BO->getOpcode()) { 2461 default: 2462 break; 2463 case(BO_PtrMemD): 2464 case(BO_PtrMemI): 2465 HandleValue(BO->getLHS(), AddressOf); 2466 Visit(BO->getRHS()); 2467 return; 2468 case(BO_Comma): 2469 Visit(BO->getLHS()); 2470 HandleValue(BO->getRHS(), AddressOf); 2471 return; 2472 } 2473 } 2474 2475 Visit(E); 2476 } 2477 2478 void CheckInitListExpr(InitListExpr *ILE) { 2479 InitFieldIndex.push_back(0); 2480 for (auto Child : ILE->children()) { 2481 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2482 CheckInitListExpr(SubList); 2483 } else { 2484 Visit(Child); 2485 } 2486 ++InitFieldIndex.back(); 2487 } 2488 InitFieldIndex.pop_back(); 2489 } 2490 2491 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2492 FieldDecl *Field, const Type *BaseClass) { 2493 // Remove Decls that may have been initialized in the previous 2494 // initializer. 2495 for (ValueDecl* VD : DeclsToRemove) 2496 Decls.erase(VD); 2497 DeclsToRemove.clear(); 2498 2499 Constructor = FieldConstructor; 2500 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2501 2502 if (ILE && Field) { 2503 InitList = true; 2504 InitListFieldDecl = Field; 2505 InitFieldIndex.clear(); 2506 CheckInitListExpr(ILE); 2507 } else { 2508 InitList = false; 2509 Visit(E); 2510 } 2511 2512 if (Field) 2513 Decls.erase(Field); 2514 if (BaseClass) 2515 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 2516 } 2517 2518 void VisitMemberExpr(MemberExpr *ME) { 2519 // All uses of unbounded reference fields will warn. 2520 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2521 } 2522 2523 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2524 if (E->getCastKind() == CK_LValueToRValue) { 2525 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2526 return; 2527 } 2528 2529 Inherited::VisitImplicitCastExpr(E); 2530 } 2531 2532 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2533 if (E->getConstructor()->isCopyConstructor()) { 2534 Expr *ArgExpr = E->getArg(0); 2535 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2536 if (ILE->getNumInits() == 1) 2537 ArgExpr = ILE->getInit(0); 2538 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2539 if (ICE->getCastKind() == CK_NoOp) 2540 ArgExpr = ICE->getSubExpr(); 2541 HandleValue(ArgExpr, false /*AddressOf*/); 2542 return; 2543 } 2544 Inherited::VisitCXXConstructExpr(E); 2545 } 2546 2547 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2548 Expr *Callee = E->getCallee(); 2549 if (isa<MemberExpr>(Callee)) { 2550 HandleValue(Callee, false /*AddressOf*/); 2551 for (auto Arg : E->arguments()) 2552 Visit(Arg); 2553 return; 2554 } 2555 2556 Inherited::VisitCXXMemberCallExpr(E); 2557 } 2558 2559 void VisitCallExpr(CallExpr *E) { 2560 // Treat std::move as a use. 2561 if (E->getNumArgs() == 1) { 2562 if (FunctionDecl *FD = E->getDirectCallee()) { 2563 if (FD->isInStdNamespace() && FD->getIdentifier() && 2564 FD->getIdentifier()->isStr("move")) { 2565 HandleValue(E->getArg(0), false /*AddressOf*/); 2566 return; 2567 } 2568 } 2569 } 2570 2571 Inherited::VisitCallExpr(E); 2572 } 2573 2574 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2575 Expr *Callee = E->getCallee(); 2576 2577 if (isa<UnresolvedLookupExpr>(Callee)) 2578 return Inherited::VisitCXXOperatorCallExpr(E); 2579 2580 Visit(Callee); 2581 for (auto Arg : E->arguments()) 2582 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2583 } 2584 2585 void VisitBinaryOperator(BinaryOperator *E) { 2586 // If a field assignment is detected, remove the field from the 2587 // uninitiailized field set. 2588 if (E->getOpcode() == BO_Assign) 2589 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2590 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2591 if (!FD->getType()->isReferenceType()) 2592 DeclsToRemove.push_back(FD); 2593 2594 if (E->isCompoundAssignmentOp()) { 2595 HandleValue(E->getLHS(), false /*AddressOf*/); 2596 Visit(E->getRHS()); 2597 return; 2598 } 2599 2600 Inherited::VisitBinaryOperator(E); 2601 } 2602 2603 void VisitUnaryOperator(UnaryOperator *E) { 2604 if (E->isIncrementDecrementOp()) { 2605 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2606 return; 2607 } 2608 if (E->getOpcode() == UO_AddrOf) { 2609 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2610 HandleValue(ME->getBase(), true /*AddressOf*/); 2611 return; 2612 } 2613 } 2614 2615 Inherited::VisitUnaryOperator(E); 2616 } 2617 }; 2618 2619 // Diagnose value-uses of fields to initialize themselves, e.g. 2620 // foo(foo) 2621 // where foo is not also a parameter to the constructor. 2622 // Also diagnose across field uninitialized use such as 2623 // x(y), y(x) 2624 // TODO: implement -Wuninitialized and fold this into that framework. 2625 static void DiagnoseUninitializedFields( 2626 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2627 2628 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2629 Constructor->getLocation())) { 2630 return; 2631 } 2632 2633 if (Constructor->isInvalidDecl()) 2634 return; 2635 2636 const CXXRecordDecl *RD = Constructor->getParent(); 2637 2638 if (RD->getDescribedClassTemplate()) 2639 return; 2640 2641 // Holds fields that are uninitialized. 2642 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2643 2644 // At the beginning, all fields are uninitialized. 2645 for (auto *I : RD->decls()) { 2646 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2647 UninitializedFields.insert(FD); 2648 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2649 UninitializedFields.insert(IFD->getAnonField()); 2650 } 2651 } 2652 2653 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 2654 for (auto I : RD->bases()) 2655 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 2656 2657 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2658 return; 2659 2660 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2661 UninitializedFields, 2662 UninitializedBaseClasses); 2663 2664 for (const auto *FieldInit : Constructor->inits()) { 2665 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2666 break; 2667 2668 Expr *InitExpr = FieldInit->getInit(); 2669 if (!InitExpr) 2670 continue; 2671 2672 if (CXXDefaultInitExpr *Default = 2673 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2674 InitExpr = Default->getExpr(); 2675 if (!InitExpr) 2676 continue; 2677 // In class initializers will point to the constructor. 2678 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2679 FieldInit->getAnyMember(), 2680 FieldInit->getBaseClass()); 2681 } else { 2682 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2683 FieldInit->getAnyMember(), 2684 FieldInit->getBaseClass()); 2685 } 2686 } 2687 } 2688 } // namespace 2689 2690 /// \brief Enter a new C++ default initializer scope. After calling this, the 2691 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2692 /// parsing or instantiating the initializer failed. 2693 void Sema::ActOnStartCXXInClassMemberInitializer() { 2694 // Create a synthetic function scope to represent the call to the constructor 2695 // that notionally surrounds a use of this initializer. 2696 PushFunctionScope(); 2697 } 2698 2699 /// \brief This is invoked after parsing an in-class initializer for a 2700 /// non-static C++ class member, and after instantiating an in-class initializer 2701 /// in a class template. Such actions are deferred until the class is complete. 2702 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2703 SourceLocation InitLoc, 2704 Expr *InitExpr) { 2705 // Pop the notional constructor scope we created earlier. 2706 PopFunctionScopeInfo(nullptr, D); 2707 2708 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2709 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 2710 "must set init style when field is created"); 2711 2712 if (!InitExpr) { 2713 D->setInvalidDecl(); 2714 if (FD) 2715 FD->removeInClassInitializer(); 2716 return; 2717 } 2718 2719 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2720 FD->setInvalidDecl(); 2721 FD->removeInClassInitializer(); 2722 return; 2723 } 2724 2725 ExprResult Init = InitExpr; 2726 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2727 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2728 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2729 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2730 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2731 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2732 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2733 if (Init.isInvalid()) { 2734 FD->setInvalidDecl(); 2735 return; 2736 } 2737 } 2738 2739 // C++11 [class.base.init]p7: 2740 // The initialization of each base and member constitutes a 2741 // full-expression. 2742 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2743 if (Init.isInvalid()) { 2744 FD->setInvalidDecl(); 2745 return; 2746 } 2747 2748 InitExpr = Init.get(); 2749 2750 FD->setInClassInitializer(InitExpr); 2751 } 2752 2753 /// \brief Find the direct and/or virtual base specifiers that 2754 /// correspond to the given base type, for use in base initialization 2755 /// within a constructor. 2756 static bool FindBaseInitializer(Sema &SemaRef, 2757 CXXRecordDecl *ClassDecl, 2758 QualType BaseType, 2759 const CXXBaseSpecifier *&DirectBaseSpec, 2760 const CXXBaseSpecifier *&VirtualBaseSpec) { 2761 // First, check for a direct base class. 2762 DirectBaseSpec = nullptr; 2763 for (const auto &Base : ClassDecl->bases()) { 2764 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2765 // We found a direct base of this type. That's what we're 2766 // initializing. 2767 DirectBaseSpec = &Base; 2768 break; 2769 } 2770 } 2771 2772 // Check for a virtual base class. 2773 // FIXME: We might be able to short-circuit this if we know in advance that 2774 // there are no virtual bases. 2775 VirtualBaseSpec = nullptr; 2776 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2777 // We haven't found a base yet; search the class hierarchy for a 2778 // virtual base class. 2779 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2780 /*DetectVirtual=*/false); 2781 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2782 BaseType, Paths)) { 2783 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2784 Path != Paths.end(); ++Path) { 2785 if (Path->back().Base->isVirtual()) { 2786 VirtualBaseSpec = Path->back().Base; 2787 break; 2788 } 2789 } 2790 } 2791 } 2792 2793 return DirectBaseSpec || VirtualBaseSpec; 2794 } 2795 2796 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2797 MemInitResult 2798 Sema::ActOnMemInitializer(Decl *ConstructorD, 2799 Scope *S, 2800 CXXScopeSpec &SS, 2801 IdentifierInfo *MemberOrBase, 2802 ParsedType TemplateTypeTy, 2803 const DeclSpec &DS, 2804 SourceLocation IdLoc, 2805 Expr *InitList, 2806 SourceLocation EllipsisLoc) { 2807 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2808 DS, IdLoc, InitList, 2809 EllipsisLoc); 2810 } 2811 2812 /// \brief Handle a C++ member initializer using parentheses syntax. 2813 MemInitResult 2814 Sema::ActOnMemInitializer(Decl *ConstructorD, 2815 Scope *S, 2816 CXXScopeSpec &SS, 2817 IdentifierInfo *MemberOrBase, 2818 ParsedType TemplateTypeTy, 2819 const DeclSpec &DS, 2820 SourceLocation IdLoc, 2821 SourceLocation LParenLoc, 2822 ArrayRef<Expr *> Args, 2823 SourceLocation RParenLoc, 2824 SourceLocation EllipsisLoc) { 2825 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2826 Args, RParenLoc); 2827 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2828 DS, IdLoc, List, EllipsisLoc); 2829 } 2830 2831 namespace { 2832 2833 // Callback to only accept typo corrections that can be a valid C++ member 2834 // intializer: either a non-static field member or a base class. 2835 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2836 public: 2837 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2838 : ClassDecl(ClassDecl) {} 2839 2840 bool ValidateCandidate(const TypoCorrection &candidate) override { 2841 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2842 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2843 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2844 return isa<TypeDecl>(ND); 2845 } 2846 return false; 2847 } 2848 2849 private: 2850 CXXRecordDecl *ClassDecl; 2851 }; 2852 2853 } 2854 2855 /// \brief Handle a C++ member initializer. 2856 MemInitResult 2857 Sema::BuildMemInitializer(Decl *ConstructorD, 2858 Scope *S, 2859 CXXScopeSpec &SS, 2860 IdentifierInfo *MemberOrBase, 2861 ParsedType TemplateTypeTy, 2862 const DeclSpec &DS, 2863 SourceLocation IdLoc, 2864 Expr *Init, 2865 SourceLocation EllipsisLoc) { 2866 ExprResult Res = CorrectDelayedTyposInExpr(Init); 2867 if (!Res.isUsable()) 2868 return true; 2869 Init = Res.get(); 2870 2871 if (!ConstructorD) 2872 return true; 2873 2874 AdjustDeclIfTemplate(ConstructorD); 2875 2876 CXXConstructorDecl *Constructor 2877 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2878 if (!Constructor) { 2879 // The user wrote a constructor initializer on a function that is 2880 // not a C++ constructor. Ignore the error for now, because we may 2881 // have more member initializers coming; we'll diagnose it just 2882 // once in ActOnMemInitializers. 2883 return true; 2884 } 2885 2886 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2887 2888 // C++ [class.base.init]p2: 2889 // Names in a mem-initializer-id are looked up in the scope of the 2890 // constructor's class and, if not found in that scope, are looked 2891 // up in the scope containing the constructor's definition. 2892 // [Note: if the constructor's class contains a member with the 2893 // same name as a direct or virtual base class of the class, a 2894 // mem-initializer-id naming the member or base class and composed 2895 // of a single identifier refers to the class member. A 2896 // mem-initializer-id for the hidden base class may be specified 2897 // using a qualified name. ] 2898 if (!SS.getScopeRep() && !TemplateTypeTy) { 2899 // Look for a member, first. 2900 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2901 if (!Result.empty()) { 2902 ValueDecl *Member; 2903 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2904 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2905 if (EllipsisLoc.isValid()) 2906 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2907 << MemberOrBase 2908 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2909 2910 return BuildMemberInitializer(Member, Init, IdLoc); 2911 } 2912 } 2913 } 2914 // It didn't name a member, so see if it names a class. 2915 QualType BaseType; 2916 TypeSourceInfo *TInfo = nullptr; 2917 2918 if (TemplateTypeTy) { 2919 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2920 } else if (DS.getTypeSpecType() == TST_decltype) { 2921 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2922 } else { 2923 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2924 LookupParsedName(R, S, &SS); 2925 2926 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2927 if (!TyD) { 2928 if (R.isAmbiguous()) return true; 2929 2930 // We don't want access-control diagnostics here. 2931 R.suppressDiagnostics(); 2932 2933 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2934 bool NotUnknownSpecialization = false; 2935 DeclContext *DC = computeDeclContext(SS, false); 2936 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2937 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2938 2939 if (!NotUnknownSpecialization) { 2940 // When the scope specifier can refer to a member of an unknown 2941 // specialization, we take it as a type name. 2942 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2943 SS.getWithLocInContext(Context), 2944 *MemberOrBase, IdLoc); 2945 if (BaseType.isNull()) 2946 return true; 2947 2948 R.clear(); 2949 R.setLookupName(MemberOrBase); 2950 } 2951 } 2952 2953 // If no results were found, try to correct typos. 2954 TypoCorrection Corr; 2955 if (R.empty() && BaseType.isNull() && 2956 (Corr = CorrectTypo( 2957 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2958 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2959 CTK_ErrorRecovery, ClassDecl))) { 2960 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2961 // We have found a non-static data member with a similar 2962 // name to what was typed; complain and initialize that 2963 // member. 2964 diagnoseTypo(Corr, 2965 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2966 << MemberOrBase << true); 2967 return BuildMemberInitializer(Member, Init, IdLoc); 2968 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2969 const CXXBaseSpecifier *DirectBaseSpec; 2970 const CXXBaseSpecifier *VirtualBaseSpec; 2971 if (FindBaseInitializer(*this, ClassDecl, 2972 Context.getTypeDeclType(Type), 2973 DirectBaseSpec, VirtualBaseSpec)) { 2974 // We have found a direct or virtual base class with a 2975 // similar name to what was typed; complain and initialize 2976 // that base class. 2977 diagnoseTypo(Corr, 2978 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2979 << MemberOrBase << false, 2980 PDiag() /*Suppress note, we provide our own.*/); 2981 2982 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2983 : VirtualBaseSpec; 2984 Diag(BaseSpec->getLocStart(), 2985 diag::note_base_class_specified_here) 2986 << BaseSpec->getType() 2987 << BaseSpec->getSourceRange(); 2988 2989 TyD = Type; 2990 } 2991 } 2992 } 2993 2994 if (!TyD && BaseType.isNull()) { 2995 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2996 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2997 return true; 2998 } 2999 } 3000 3001 if (BaseType.isNull()) { 3002 BaseType = Context.getTypeDeclType(TyD); 3003 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3004 if (SS.isSet()) 3005 // FIXME: preserve source range information 3006 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3007 BaseType); 3008 } 3009 } 3010 3011 if (!TInfo) 3012 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3013 3014 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3015 } 3016 3017 /// Checks a member initializer expression for cases where reference (or 3018 /// pointer) members are bound to by-value parameters (or their addresses). 3019 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3020 Expr *Init, 3021 SourceLocation IdLoc) { 3022 QualType MemberTy = Member->getType(); 3023 3024 // We only handle pointers and references currently. 3025 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3026 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3027 return; 3028 3029 const bool IsPointer = MemberTy->isPointerType(); 3030 if (IsPointer) { 3031 if (const UnaryOperator *Op 3032 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3033 // The only case we're worried about with pointers requires taking the 3034 // address. 3035 if (Op->getOpcode() != UO_AddrOf) 3036 return; 3037 3038 Init = Op->getSubExpr(); 3039 } else { 3040 // We only handle address-of expression initializers for pointers. 3041 return; 3042 } 3043 } 3044 3045 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3046 // We only warn when referring to a non-reference parameter declaration. 3047 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3048 if (!Parameter || Parameter->getType()->isReferenceType()) 3049 return; 3050 3051 S.Diag(Init->getExprLoc(), 3052 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3053 : diag::warn_bind_ref_member_to_parameter) 3054 << Member << Parameter << Init->getSourceRange(); 3055 } else { 3056 // Other initializers are fine. 3057 return; 3058 } 3059 3060 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3061 << (unsigned)IsPointer; 3062 } 3063 3064 MemInitResult 3065 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3066 SourceLocation IdLoc) { 3067 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3068 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3069 assert((DirectMember || IndirectMember) && 3070 "Member must be a FieldDecl or IndirectFieldDecl"); 3071 3072 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3073 return true; 3074 3075 if (Member->isInvalidDecl()) 3076 return true; 3077 3078 MultiExprArg Args; 3079 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3080 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3081 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3082 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3083 } else { 3084 // Template instantiation doesn't reconstruct ParenListExprs for us. 3085 Args = Init; 3086 } 3087 3088 SourceRange InitRange = Init->getSourceRange(); 3089 3090 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3091 // Can't check initialization for a member of dependent type or when 3092 // any of the arguments are type-dependent expressions. 3093 DiscardCleanupsInEvaluationContext(); 3094 } else { 3095 bool InitList = false; 3096 if (isa<InitListExpr>(Init)) { 3097 InitList = true; 3098 Args = Init; 3099 } 3100 3101 // Initialize the member. 3102 InitializedEntity MemberEntity = 3103 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3104 : InitializedEntity::InitializeMember(IndirectMember, 3105 nullptr); 3106 InitializationKind Kind = 3107 InitList ? InitializationKind::CreateDirectList(IdLoc) 3108 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3109 InitRange.getEnd()); 3110 3111 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3112 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3113 nullptr); 3114 if (MemberInit.isInvalid()) 3115 return true; 3116 3117 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3118 3119 // C++11 [class.base.init]p7: 3120 // The initialization of each base and member constitutes a 3121 // full-expression. 3122 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3123 if (MemberInit.isInvalid()) 3124 return true; 3125 3126 Init = MemberInit.get(); 3127 } 3128 3129 if (DirectMember) { 3130 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3131 InitRange.getBegin(), Init, 3132 InitRange.getEnd()); 3133 } else { 3134 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3135 InitRange.getBegin(), Init, 3136 InitRange.getEnd()); 3137 } 3138 } 3139 3140 MemInitResult 3141 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3142 CXXRecordDecl *ClassDecl) { 3143 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3144 if (!LangOpts.CPlusPlus11) 3145 return Diag(NameLoc, diag::err_delegating_ctor) 3146 << TInfo->getTypeLoc().getLocalSourceRange(); 3147 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3148 3149 bool InitList = true; 3150 MultiExprArg Args = Init; 3151 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3152 InitList = false; 3153 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3154 } 3155 3156 SourceRange InitRange = Init->getSourceRange(); 3157 // Initialize the object. 3158 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3159 QualType(ClassDecl->getTypeForDecl(), 0)); 3160 InitializationKind Kind = 3161 InitList ? InitializationKind::CreateDirectList(NameLoc) 3162 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3163 InitRange.getEnd()); 3164 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3165 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3166 Args, nullptr); 3167 if (DelegationInit.isInvalid()) 3168 return true; 3169 3170 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3171 "Delegating constructor with no target?"); 3172 3173 // C++11 [class.base.init]p7: 3174 // The initialization of each base and member constitutes a 3175 // full-expression. 3176 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3177 InitRange.getBegin()); 3178 if (DelegationInit.isInvalid()) 3179 return true; 3180 3181 // If we are in a dependent context, template instantiation will 3182 // perform this type-checking again. Just save the arguments that we 3183 // received in a ParenListExpr. 3184 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3185 // of the information that we have about the base 3186 // initializer. However, deconstructing the ASTs is a dicey process, 3187 // and this approach is far more likely to get the corner cases right. 3188 if (CurContext->isDependentContext()) 3189 DelegationInit = Init; 3190 3191 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3192 DelegationInit.getAs<Expr>(), 3193 InitRange.getEnd()); 3194 } 3195 3196 MemInitResult 3197 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3198 Expr *Init, CXXRecordDecl *ClassDecl, 3199 SourceLocation EllipsisLoc) { 3200 SourceLocation BaseLoc 3201 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3202 3203 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3204 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3205 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3206 3207 // C++ [class.base.init]p2: 3208 // [...] Unless the mem-initializer-id names a nonstatic data 3209 // member of the constructor's class or a direct or virtual base 3210 // of that class, the mem-initializer is ill-formed. A 3211 // mem-initializer-list can initialize a base class using any 3212 // name that denotes that base class type. 3213 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3214 3215 SourceRange InitRange = Init->getSourceRange(); 3216 if (EllipsisLoc.isValid()) { 3217 // This is a pack expansion. 3218 if (!BaseType->containsUnexpandedParameterPack()) { 3219 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3220 << SourceRange(BaseLoc, InitRange.getEnd()); 3221 3222 EllipsisLoc = SourceLocation(); 3223 } 3224 } else { 3225 // Check for any unexpanded parameter packs. 3226 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3227 return true; 3228 3229 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3230 return true; 3231 } 3232 3233 // Check for direct and virtual base classes. 3234 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3235 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3236 if (!Dependent) { 3237 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3238 BaseType)) 3239 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3240 3241 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3242 VirtualBaseSpec); 3243 3244 // C++ [base.class.init]p2: 3245 // Unless the mem-initializer-id names a nonstatic data member of the 3246 // constructor's class or a direct or virtual base of that class, the 3247 // mem-initializer is ill-formed. 3248 if (!DirectBaseSpec && !VirtualBaseSpec) { 3249 // If the class has any dependent bases, then it's possible that 3250 // one of those types will resolve to the same type as 3251 // BaseType. Therefore, just treat this as a dependent base 3252 // class initialization. FIXME: Should we try to check the 3253 // initialization anyway? It seems odd. 3254 if (ClassDecl->hasAnyDependentBases()) 3255 Dependent = true; 3256 else 3257 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3258 << BaseType << Context.getTypeDeclType(ClassDecl) 3259 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3260 } 3261 } 3262 3263 if (Dependent) { 3264 DiscardCleanupsInEvaluationContext(); 3265 3266 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3267 /*IsVirtual=*/false, 3268 InitRange.getBegin(), Init, 3269 InitRange.getEnd(), EllipsisLoc); 3270 } 3271 3272 // C++ [base.class.init]p2: 3273 // If a mem-initializer-id is ambiguous because it designates both 3274 // a direct non-virtual base class and an inherited virtual base 3275 // class, the mem-initializer is ill-formed. 3276 if (DirectBaseSpec && VirtualBaseSpec) 3277 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3278 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3279 3280 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3281 if (!BaseSpec) 3282 BaseSpec = VirtualBaseSpec; 3283 3284 // Initialize the base. 3285 bool InitList = true; 3286 MultiExprArg Args = Init; 3287 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3288 InitList = false; 3289 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3290 } 3291 3292 InitializedEntity BaseEntity = 3293 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3294 InitializationKind Kind = 3295 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3296 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3297 InitRange.getEnd()); 3298 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3299 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3300 if (BaseInit.isInvalid()) 3301 return true; 3302 3303 // C++11 [class.base.init]p7: 3304 // The initialization of each base and member constitutes a 3305 // full-expression. 3306 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3307 if (BaseInit.isInvalid()) 3308 return true; 3309 3310 // If we are in a dependent context, template instantiation will 3311 // perform this type-checking again. Just save the arguments that we 3312 // received in a ParenListExpr. 3313 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3314 // of the information that we have about the base 3315 // initializer. However, deconstructing the ASTs is a dicey process, 3316 // and this approach is far more likely to get the corner cases right. 3317 if (CurContext->isDependentContext()) 3318 BaseInit = Init; 3319 3320 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3321 BaseSpec->isVirtual(), 3322 InitRange.getBegin(), 3323 BaseInit.getAs<Expr>(), 3324 InitRange.getEnd(), EllipsisLoc); 3325 } 3326 3327 // Create a static_cast\<T&&>(expr). 3328 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3329 if (T.isNull()) T = E->getType(); 3330 QualType TargetType = SemaRef.BuildReferenceType( 3331 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3332 SourceLocation ExprLoc = E->getLocStart(); 3333 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3334 TargetType, ExprLoc); 3335 3336 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3337 SourceRange(ExprLoc, ExprLoc), 3338 E->getSourceRange()).get(); 3339 } 3340 3341 /// ImplicitInitializerKind - How an implicit base or member initializer should 3342 /// initialize its base or member. 3343 enum ImplicitInitializerKind { 3344 IIK_Default, 3345 IIK_Copy, 3346 IIK_Move, 3347 IIK_Inherit 3348 }; 3349 3350 static bool 3351 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3352 ImplicitInitializerKind ImplicitInitKind, 3353 CXXBaseSpecifier *BaseSpec, 3354 bool IsInheritedVirtualBase, 3355 CXXCtorInitializer *&CXXBaseInit) { 3356 InitializedEntity InitEntity 3357 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3358 IsInheritedVirtualBase); 3359 3360 ExprResult BaseInit; 3361 3362 switch (ImplicitInitKind) { 3363 case IIK_Inherit: { 3364 const CXXRecordDecl *Inherited = 3365 Constructor->getInheritedConstructor()->getParent(); 3366 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3367 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3368 // C++11 [class.inhctor]p8: 3369 // Each expression in the expression-list is of the form 3370 // static_cast<T&&>(p), where p is the name of the corresponding 3371 // constructor parameter and T is the declared type of p. 3372 SmallVector<Expr*, 16> Args; 3373 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3374 ParmVarDecl *PD = Constructor->getParamDecl(I); 3375 ExprResult ArgExpr = 3376 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3377 VK_LValue, SourceLocation()); 3378 if (ArgExpr.isInvalid()) 3379 return true; 3380 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3381 } 3382 3383 InitializationKind InitKind = InitializationKind::CreateDirect( 3384 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3385 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3386 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3387 break; 3388 } 3389 } 3390 // Fall through. 3391 case IIK_Default: { 3392 InitializationKind InitKind 3393 = InitializationKind::CreateDefault(Constructor->getLocation()); 3394 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3395 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3396 break; 3397 } 3398 3399 case IIK_Move: 3400 case IIK_Copy: { 3401 bool Moving = ImplicitInitKind == IIK_Move; 3402 ParmVarDecl *Param = Constructor->getParamDecl(0); 3403 QualType ParamType = Param->getType().getNonReferenceType(); 3404 3405 Expr *CopyCtorArg = 3406 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3407 SourceLocation(), Param, false, 3408 Constructor->getLocation(), ParamType, 3409 VK_LValue, nullptr); 3410 3411 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3412 3413 // Cast to the base class to avoid ambiguities. 3414 QualType ArgTy = 3415 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3416 ParamType.getQualifiers()); 3417 3418 if (Moving) { 3419 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3420 } 3421 3422 CXXCastPath BasePath; 3423 BasePath.push_back(BaseSpec); 3424 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3425 CK_UncheckedDerivedToBase, 3426 Moving ? VK_XValue : VK_LValue, 3427 &BasePath).get(); 3428 3429 InitializationKind InitKind 3430 = InitializationKind::CreateDirect(Constructor->getLocation(), 3431 SourceLocation(), SourceLocation()); 3432 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3433 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3434 break; 3435 } 3436 } 3437 3438 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3439 if (BaseInit.isInvalid()) 3440 return true; 3441 3442 CXXBaseInit = 3443 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3444 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3445 SourceLocation()), 3446 BaseSpec->isVirtual(), 3447 SourceLocation(), 3448 BaseInit.getAs<Expr>(), 3449 SourceLocation(), 3450 SourceLocation()); 3451 3452 return false; 3453 } 3454 3455 static bool RefersToRValueRef(Expr *MemRef) { 3456 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3457 return Referenced->getType()->isRValueReferenceType(); 3458 } 3459 3460 static bool 3461 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3462 ImplicitInitializerKind ImplicitInitKind, 3463 FieldDecl *Field, IndirectFieldDecl *Indirect, 3464 CXXCtorInitializer *&CXXMemberInit) { 3465 if (Field->isInvalidDecl()) 3466 return true; 3467 3468 SourceLocation Loc = Constructor->getLocation(); 3469 3470 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3471 bool Moving = ImplicitInitKind == IIK_Move; 3472 ParmVarDecl *Param = Constructor->getParamDecl(0); 3473 QualType ParamType = Param->getType().getNonReferenceType(); 3474 3475 // Suppress copying zero-width bitfields. 3476 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3477 return false; 3478 3479 Expr *MemberExprBase = 3480 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3481 SourceLocation(), Param, false, 3482 Loc, ParamType, VK_LValue, nullptr); 3483 3484 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3485 3486 if (Moving) { 3487 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3488 } 3489 3490 // Build a reference to this field within the parameter. 3491 CXXScopeSpec SS; 3492 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3493 Sema::LookupMemberName); 3494 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3495 : cast<ValueDecl>(Field), AS_public); 3496 MemberLookup.resolveKind(); 3497 ExprResult CtorArg 3498 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3499 ParamType, Loc, 3500 /*IsArrow=*/false, 3501 SS, 3502 /*TemplateKWLoc=*/SourceLocation(), 3503 /*FirstQualifierInScope=*/nullptr, 3504 MemberLookup, 3505 /*TemplateArgs=*/nullptr); 3506 if (CtorArg.isInvalid()) 3507 return true; 3508 3509 // C++11 [class.copy]p15: 3510 // - if a member m has rvalue reference type T&&, it is direct-initialized 3511 // with static_cast<T&&>(x.m); 3512 if (RefersToRValueRef(CtorArg.get())) { 3513 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3514 } 3515 3516 // When the field we are copying is an array, create index variables for 3517 // each dimension of the array. We use these index variables to subscript 3518 // the source array, and other clients (e.g., CodeGen) will perform the 3519 // necessary iteration with these index variables. 3520 SmallVector<VarDecl *, 4> IndexVariables; 3521 QualType BaseType = Field->getType(); 3522 QualType SizeType = SemaRef.Context.getSizeType(); 3523 bool InitializingArray = false; 3524 while (const ConstantArrayType *Array 3525 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3526 InitializingArray = true; 3527 // Create the iteration variable for this array index. 3528 IdentifierInfo *IterationVarName = nullptr; 3529 { 3530 SmallString<8> Str; 3531 llvm::raw_svector_ostream OS(Str); 3532 OS << "__i" << IndexVariables.size(); 3533 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3534 } 3535 VarDecl *IterationVar 3536 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3537 IterationVarName, SizeType, 3538 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3539 SC_None); 3540 IndexVariables.push_back(IterationVar); 3541 3542 // Create a reference to the iteration variable. 3543 ExprResult IterationVarRef 3544 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3545 assert(!IterationVarRef.isInvalid() && 3546 "Reference to invented variable cannot fail!"); 3547 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3548 assert(!IterationVarRef.isInvalid() && 3549 "Conversion of invented variable cannot fail!"); 3550 3551 // Subscript the array with this iteration variable. 3552 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3553 IterationVarRef.get(), 3554 Loc); 3555 if (CtorArg.isInvalid()) 3556 return true; 3557 3558 BaseType = Array->getElementType(); 3559 } 3560 3561 // The array subscript expression is an lvalue, which is wrong for moving. 3562 if (Moving && InitializingArray) 3563 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3564 3565 // Construct the entity that we will be initializing. For an array, this 3566 // will be first element in the array, which may require several levels 3567 // of array-subscript entities. 3568 SmallVector<InitializedEntity, 4> Entities; 3569 Entities.reserve(1 + IndexVariables.size()); 3570 if (Indirect) 3571 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3572 else 3573 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3574 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3575 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3576 0, 3577 Entities.back())); 3578 3579 // Direct-initialize to use the copy constructor. 3580 InitializationKind InitKind = 3581 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3582 3583 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3584 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 3585 CtorArgE); 3586 3587 ExprResult MemberInit 3588 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3589 MultiExprArg(&CtorArgE, 1)); 3590 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3591 if (MemberInit.isInvalid()) 3592 return true; 3593 3594 if (Indirect) { 3595 assert(IndexVariables.size() == 0 && 3596 "Indirect field improperly initialized"); 3597 CXXMemberInit 3598 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3599 Loc, Loc, 3600 MemberInit.getAs<Expr>(), 3601 Loc); 3602 } else 3603 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3604 Loc, MemberInit.getAs<Expr>(), 3605 Loc, 3606 IndexVariables.data(), 3607 IndexVariables.size()); 3608 return false; 3609 } 3610 3611 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3612 "Unhandled implicit init kind!"); 3613 3614 QualType FieldBaseElementType = 3615 SemaRef.Context.getBaseElementType(Field->getType()); 3616 3617 if (FieldBaseElementType->isRecordType()) { 3618 InitializedEntity InitEntity 3619 = Indirect? InitializedEntity::InitializeMember(Indirect) 3620 : InitializedEntity::InitializeMember(Field); 3621 InitializationKind InitKind = 3622 InitializationKind::CreateDefault(Loc); 3623 3624 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3625 ExprResult MemberInit = 3626 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3627 3628 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3629 if (MemberInit.isInvalid()) 3630 return true; 3631 3632 if (Indirect) 3633 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3634 Indirect, Loc, 3635 Loc, 3636 MemberInit.get(), 3637 Loc); 3638 else 3639 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3640 Field, Loc, Loc, 3641 MemberInit.get(), 3642 Loc); 3643 return false; 3644 } 3645 3646 if (!Field->getParent()->isUnion()) { 3647 if (FieldBaseElementType->isReferenceType()) { 3648 SemaRef.Diag(Constructor->getLocation(), 3649 diag::err_uninitialized_member_in_ctor) 3650 << (int)Constructor->isImplicit() 3651 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3652 << 0 << Field->getDeclName(); 3653 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3654 return true; 3655 } 3656 3657 if (FieldBaseElementType.isConstQualified()) { 3658 SemaRef.Diag(Constructor->getLocation(), 3659 diag::err_uninitialized_member_in_ctor) 3660 << (int)Constructor->isImplicit() 3661 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3662 << 1 << Field->getDeclName(); 3663 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3664 return true; 3665 } 3666 } 3667 3668 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3669 FieldBaseElementType->isObjCRetainableType() && 3670 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3671 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3672 // ARC: 3673 // Default-initialize Objective-C pointers to NULL. 3674 CXXMemberInit 3675 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3676 Loc, Loc, 3677 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3678 Loc); 3679 return false; 3680 } 3681 3682 // Nothing to initialize. 3683 CXXMemberInit = nullptr; 3684 return false; 3685 } 3686 3687 namespace { 3688 struct BaseAndFieldInfo { 3689 Sema &S; 3690 CXXConstructorDecl *Ctor; 3691 bool AnyErrorsInInits; 3692 ImplicitInitializerKind IIK; 3693 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3694 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3695 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3696 3697 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3698 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3699 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3700 if (Generated && Ctor->isCopyConstructor()) 3701 IIK = IIK_Copy; 3702 else if (Generated && Ctor->isMoveConstructor()) 3703 IIK = IIK_Move; 3704 else if (Ctor->getInheritedConstructor()) 3705 IIK = IIK_Inherit; 3706 else 3707 IIK = IIK_Default; 3708 } 3709 3710 bool isImplicitCopyOrMove() const { 3711 switch (IIK) { 3712 case IIK_Copy: 3713 case IIK_Move: 3714 return true; 3715 3716 case IIK_Default: 3717 case IIK_Inherit: 3718 return false; 3719 } 3720 3721 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3722 } 3723 3724 bool addFieldInitializer(CXXCtorInitializer *Init) { 3725 AllToInit.push_back(Init); 3726 3727 // Check whether this initializer makes the field "used". 3728 if (Init->getInit()->HasSideEffects(S.Context)) 3729 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3730 3731 return false; 3732 } 3733 3734 bool isInactiveUnionMember(FieldDecl *Field) { 3735 RecordDecl *Record = Field->getParent(); 3736 if (!Record->isUnion()) 3737 return false; 3738 3739 if (FieldDecl *Active = 3740 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3741 return Active != Field->getCanonicalDecl(); 3742 3743 // In an implicit copy or move constructor, ignore any in-class initializer. 3744 if (isImplicitCopyOrMove()) 3745 return true; 3746 3747 // If there's no explicit initialization, the field is active only if it 3748 // has an in-class initializer... 3749 if (Field->hasInClassInitializer()) 3750 return false; 3751 // ... or it's an anonymous struct or union whose class has an in-class 3752 // initializer. 3753 if (!Field->isAnonymousStructOrUnion()) 3754 return true; 3755 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3756 return !FieldRD->hasInClassInitializer(); 3757 } 3758 3759 /// \brief Determine whether the given field is, or is within, a union member 3760 /// that is inactive (because there was an initializer given for a different 3761 /// member of the union, or because the union was not initialized at all). 3762 bool isWithinInactiveUnionMember(FieldDecl *Field, 3763 IndirectFieldDecl *Indirect) { 3764 if (!Indirect) 3765 return isInactiveUnionMember(Field); 3766 3767 for (auto *C : Indirect->chain()) { 3768 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3769 if (Field && isInactiveUnionMember(Field)) 3770 return true; 3771 } 3772 return false; 3773 } 3774 }; 3775 } 3776 3777 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3778 /// array type. 3779 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3780 if (T->isIncompleteArrayType()) 3781 return true; 3782 3783 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3784 if (!ArrayT->getSize()) 3785 return true; 3786 3787 T = ArrayT->getElementType(); 3788 } 3789 3790 return false; 3791 } 3792 3793 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3794 FieldDecl *Field, 3795 IndirectFieldDecl *Indirect = nullptr) { 3796 if (Field->isInvalidDecl()) 3797 return false; 3798 3799 // Overwhelmingly common case: we have a direct initializer for this field. 3800 if (CXXCtorInitializer *Init = 3801 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3802 return Info.addFieldInitializer(Init); 3803 3804 // C++11 [class.base.init]p8: 3805 // if the entity is a non-static data member that has a 3806 // brace-or-equal-initializer and either 3807 // -- the constructor's class is a union and no other variant member of that 3808 // union is designated by a mem-initializer-id or 3809 // -- the constructor's class is not a union, and, if the entity is a member 3810 // of an anonymous union, no other member of that union is designated by 3811 // a mem-initializer-id, 3812 // the entity is initialized as specified in [dcl.init]. 3813 // 3814 // We also apply the same rules to handle anonymous structs within anonymous 3815 // unions. 3816 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3817 return false; 3818 3819 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3820 ExprResult DIE = 3821 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3822 if (DIE.isInvalid()) 3823 return true; 3824 CXXCtorInitializer *Init; 3825 if (Indirect) 3826 Init = new (SemaRef.Context) 3827 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3828 SourceLocation(), DIE.get(), SourceLocation()); 3829 else 3830 Init = new (SemaRef.Context) 3831 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3832 SourceLocation(), DIE.get(), SourceLocation()); 3833 return Info.addFieldInitializer(Init); 3834 } 3835 3836 // Don't initialize incomplete or zero-length arrays. 3837 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3838 return false; 3839 3840 // Don't try to build an implicit initializer if there were semantic 3841 // errors in any of the initializers (and therefore we might be 3842 // missing some that the user actually wrote). 3843 if (Info.AnyErrorsInInits) 3844 return false; 3845 3846 CXXCtorInitializer *Init = nullptr; 3847 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3848 Indirect, Init)) 3849 return true; 3850 3851 if (!Init) 3852 return false; 3853 3854 return Info.addFieldInitializer(Init); 3855 } 3856 3857 bool 3858 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3859 CXXCtorInitializer *Initializer) { 3860 assert(Initializer->isDelegatingInitializer()); 3861 Constructor->setNumCtorInitializers(1); 3862 CXXCtorInitializer **initializer = 3863 new (Context) CXXCtorInitializer*[1]; 3864 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3865 Constructor->setCtorInitializers(initializer); 3866 3867 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3868 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3869 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3870 } 3871 3872 DelegatingCtorDecls.push_back(Constructor); 3873 3874 DiagnoseUninitializedFields(*this, Constructor); 3875 3876 return false; 3877 } 3878 3879 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3880 ArrayRef<CXXCtorInitializer *> Initializers) { 3881 if (Constructor->isDependentContext()) { 3882 // Just store the initializers as written, they will be checked during 3883 // instantiation. 3884 if (!Initializers.empty()) { 3885 Constructor->setNumCtorInitializers(Initializers.size()); 3886 CXXCtorInitializer **baseOrMemberInitializers = 3887 new (Context) CXXCtorInitializer*[Initializers.size()]; 3888 memcpy(baseOrMemberInitializers, Initializers.data(), 3889 Initializers.size() * sizeof(CXXCtorInitializer*)); 3890 Constructor->setCtorInitializers(baseOrMemberInitializers); 3891 } 3892 3893 // Let template instantiation know whether we had errors. 3894 if (AnyErrors) 3895 Constructor->setInvalidDecl(); 3896 3897 return false; 3898 } 3899 3900 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3901 3902 // We need to build the initializer AST according to order of construction 3903 // and not what user specified in the Initializers list. 3904 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3905 if (!ClassDecl) 3906 return true; 3907 3908 bool HadError = false; 3909 3910 for (unsigned i = 0; i < Initializers.size(); i++) { 3911 CXXCtorInitializer *Member = Initializers[i]; 3912 3913 if (Member->isBaseInitializer()) 3914 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3915 else { 3916 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3917 3918 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3919 for (auto *C : F->chain()) { 3920 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3921 if (FD && FD->getParent()->isUnion()) 3922 Info.ActiveUnionMember.insert(std::make_pair( 3923 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3924 } 3925 } else if (FieldDecl *FD = Member->getMember()) { 3926 if (FD->getParent()->isUnion()) 3927 Info.ActiveUnionMember.insert(std::make_pair( 3928 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3929 } 3930 } 3931 } 3932 3933 // Keep track of the direct virtual bases. 3934 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3935 for (auto &I : ClassDecl->bases()) { 3936 if (I.isVirtual()) 3937 DirectVBases.insert(&I); 3938 } 3939 3940 // Push virtual bases before others. 3941 for (auto &VBase : ClassDecl->vbases()) { 3942 if (CXXCtorInitializer *Value 3943 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3944 // [class.base.init]p7, per DR257: 3945 // A mem-initializer where the mem-initializer-id names a virtual base 3946 // class is ignored during execution of a constructor of any class that 3947 // is not the most derived class. 3948 if (ClassDecl->isAbstract()) { 3949 // FIXME: Provide a fixit to remove the base specifier. This requires 3950 // tracking the location of the associated comma for a base specifier. 3951 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3952 << VBase.getType() << ClassDecl; 3953 DiagnoseAbstractType(ClassDecl); 3954 } 3955 3956 Info.AllToInit.push_back(Value); 3957 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3958 // [class.base.init]p8, per DR257: 3959 // If a given [...] base class is not named by a mem-initializer-id 3960 // [...] and the entity is not a virtual base class of an abstract 3961 // class, then [...] the entity is default-initialized. 3962 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3963 CXXCtorInitializer *CXXBaseInit; 3964 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3965 &VBase, IsInheritedVirtualBase, 3966 CXXBaseInit)) { 3967 HadError = true; 3968 continue; 3969 } 3970 3971 Info.AllToInit.push_back(CXXBaseInit); 3972 } 3973 } 3974 3975 // Non-virtual bases. 3976 for (auto &Base : ClassDecl->bases()) { 3977 // Virtuals are in the virtual base list and already constructed. 3978 if (Base.isVirtual()) 3979 continue; 3980 3981 if (CXXCtorInitializer *Value 3982 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3983 Info.AllToInit.push_back(Value); 3984 } else if (!AnyErrors) { 3985 CXXCtorInitializer *CXXBaseInit; 3986 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3987 &Base, /*IsInheritedVirtualBase=*/false, 3988 CXXBaseInit)) { 3989 HadError = true; 3990 continue; 3991 } 3992 3993 Info.AllToInit.push_back(CXXBaseInit); 3994 } 3995 } 3996 3997 // Fields. 3998 for (auto *Mem : ClassDecl->decls()) { 3999 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4000 // C++ [class.bit]p2: 4001 // A declaration for a bit-field that omits the identifier declares an 4002 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4003 // initialized. 4004 if (F->isUnnamedBitfield()) 4005 continue; 4006 4007 // If we're not generating the implicit copy/move constructor, then we'll 4008 // handle anonymous struct/union fields based on their individual 4009 // indirect fields. 4010 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4011 continue; 4012 4013 if (CollectFieldInitializer(*this, Info, F)) 4014 HadError = true; 4015 continue; 4016 } 4017 4018 // Beyond this point, we only consider default initialization. 4019 if (Info.isImplicitCopyOrMove()) 4020 continue; 4021 4022 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4023 if (F->getType()->isIncompleteArrayType()) { 4024 assert(ClassDecl->hasFlexibleArrayMember() && 4025 "Incomplete array type is not valid"); 4026 continue; 4027 } 4028 4029 // Initialize each field of an anonymous struct individually. 4030 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4031 HadError = true; 4032 4033 continue; 4034 } 4035 } 4036 4037 unsigned NumInitializers = Info.AllToInit.size(); 4038 if (NumInitializers > 0) { 4039 Constructor->setNumCtorInitializers(NumInitializers); 4040 CXXCtorInitializer **baseOrMemberInitializers = 4041 new (Context) CXXCtorInitializer*[NumInitializers]; 4042 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4043 NumInitializers * sizeof(CXXCtorInitializer*)); 4044 Constructor->setCtorInitializers(baseOrMemberInitializers); 4045 4046 // Constructors implicitly reference the base and member 4047 // destructors. 4048 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4049 Constructor->getParent()); 4050 } 4051 4052 return HadError; 4053 } 4054 4055 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4056 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4057 const RecordDecl *RD = RT->getDecl(); 4058 if (RD->isAnonymousStructOrUnion()) { 4059 for (auto *Field : RD->fields()) 4060 PopulateKeysForFields(Field, IdealInits); 4061 return; 4062 } 4063 } 4064 IdealInits.push_back(Field->getCanonicalDecl()); 4065 } 4066 4067 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4068 return Context.getCanonicalType(BaseType).getTypePtr(); 4069 } 4070 4071 static const void *GetKeyForMember(ASTContext &Context, 4072 CXXCtorInitializer *Member) { 4073 if (!Member->isAnyMemberInitializer()) 4074 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4075 4076 return Member->getAnyMember()->getCanonicalDecl(); 4077 } 4078 4079 static void DiagnoseBaseOrMemInitializerOrder( 4080 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4081 ArrayRef<CXXCtorInitializer *> Inits) { 4082 if (Constructor->getDeclContext()->isDependentContext()) 4083 return; 4084 4085 // Don't check initializers order unless the warning is enabled at the 4086 // location of at least one initializer. 4087 bool ShouldCheckOrder = false; 4088 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4089 CXXCtorInitializer *Init = Inits[InitIndex]; 4090 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4091 Init->getSourceLocation())) { 4092 ShouldCheckOrder = true; 4093 break; 4094 } 4095 } 4096 if (!ShouldCheckOrder) 4097 return; 4098 4099 // Build the list of bases and members in the order that they'll 4100 // actually be initialized. The explicit initializers should be in 4101 // this same order but may be missing things. 4102 SmallVector<const void*, 32> IdealInitKeys; 4103 4104 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4105 4106 // 1. Virtual bases. 4107 for (const auto &VBase : ClassDecl->vbases()) 4108 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4109 4110 // 2. Non-virtual bases. 4111 for (const auto &Base : ClassDecl->bases()) { 4112 if (Base.isVirtual()) 4113 continue; 4114 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4115 } 4116 4117 // 3. Direct fields. 4118 for (auto *Field : ClassDecl->fields()) { 4119 if (Field->isUnnamedBitfield()) 4120 continue; 4121 4122 PopulateKeysForFields(Field, IdealInitKeys); 4123 } 4124 4125 unsigned NumIdealInits = IdealInitKeys.size(); 4126 unsigned IdealIndex = 0; 4127 4128 CXXCtorInitializer *PrevInit = nullptr; 4129 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4130 CXXCtorInitializer *Init = Inits[InitIndex]; 4131 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4132 4133 // Scan forward to try to find this initializer in the idealized 4134 // initializers list. 4135 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4136 if (InitKey == IdealInitKeys[IdealIndex]) 4137 break; 4138 4139 // If we didn't find this initializer, it must be because we 4140 // scanned past it on a previous iteration. That can only 4141 // happen if we're out of order; emit a warning. 4142 if (IdealIndex == NumIdealInits && PrevInit) { 4143 Sema::SemaDiagnosticBuilder D = 4144 SemaRef.Diag(PrevInit->getSourceLocation(), 4145 diag::warn_initializer_out_of_order); 4146 4147 if (PrevInit->isAnyMemberInitializer()) 4148 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4149 else 4150 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4151 4152 if (Init->isAnyMemberInitializer()) 4153 D << 0 << Init->getAnyMember()->getDeclName(); 4154 else 4155 D << 1 << Init->getTypeSourceInfo()->getType(); 4156 4157 // Move back to the initializer's location in the ideal list. 4158 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4159 if (InitKey == IdealInitKeys[IdealIndex]) 4160 break; 4161 4162 assert(IdealIndex != NumIdealInits && 4163 "initializer not found in initializer list"); 4164 } 4165 4166 PrevInit = Init; 4167 } 4168 } 4169 4170 namespace { 4171 bool CheckRedundantInit(Sema &S, 4172 CXXCtorInitializer *Init, 4173 CXXCtorInitializer *&PrevInit) { 4174 if (!PrevInit) { 4175 PrevInit = Init; 4176 return false; 4177 } 4178 4179 if (FieldDecl *Field = Init->getAnyMember()) 4180 S.Diag(Init->getSourceLocation(), 4181 diag::err_multiple_mem_initialization) 4182 << Field->getDeclName() 4183 << Init->getSourceRange(); 4184 else { 4185 const Type *BaseClass = Init->getBaseClass(); 4186 assert(BaseClass && "neither field nor base"); 4187 S.Diag(Init->getSourceLocation(), 4188 diag::err_multiple_base_initialization) 4189 << QualType(BaseClass, 0) 4190 << Init->getSourceRange(); 4191 } 4192 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4193 << 0 << PrevInit->getSourceRange(); 4194 4195 return true; 4196 } 4197 4198 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4199 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4200 4201 bool CheckRedundantUnionInit(Sema &S, 4202 CXXCtorInitializer *Init, 4203 RedundantUnionMap &Unions) { 4204 FieldDecl *Field = Init->getAnyMember(); 4205 RecordDecl *Parent = Field->getParent(); 4206 NamedDecl *Child = Field; 4207 4208 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4209 if (Parent->isUnion()) { 4210 UnionEntry &En = Unions[Parent]; 4211 if (En.first && En.first != Child) { 4212 S.Diag(Init->getSourceLocation(), 4213 diag::err_multiple_mem_union_initialization) 4214 << Field->getDeclName() 4215 << Init->getSourceRange(); 4216 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4217 << 0 << En.second->getSourceRange(); 4218 return true; 4219 } 4220 if (!En.first) { 4221 En.first = Child; 4222 En.second = Init; 4223 } 4224 if (!Parent->isAnonymousStructOrUnion()) 4225 return false; 4226 } 4227 4228 Child = Parent; 4229 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4230 } 4231 4232 return false; 4233 } 4234 } 4235 4236 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4237 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4238 SourceLocation ColonLoc, 4239 ArrayRef<CXXCtorInitializer*> MemInits, 4240 bool AnyErrors) { 4241 if (!ConstructorDecl) 4242 return; 4243 4244 AdjustDeclIfTemplate(ConstructorDecl); 4245 4246 CXXConstructorDecl *Constructor 4247 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4248 4249 if (!Constructor) { 4250 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4251 return; 4252 } 4253 4254 // Mapping for the duplicate initializers check. 4255 // For member initializers, this is keyed with a FieldDecl*. 4256 // For base initializers, this is keyed with a Type*. 4257 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4258 4259 // Mapping for the inconsistent anonymous-union initializers check. 4260 RedundantUnionMap MemberUnions; 4261 4262 bool HadError = false; 4263 for (unsigned i = 0; i < MemInits.size(); i++) { 4264 CXXCtorInitializer *Init = MemInits[i]; 4265 4266 // Set the source order index. 4267 Init->setSourceOrder(i); 4268 4269 if (Init->isAnyMemberInitializer()) { 4270 const void *Key = GetKeyForMember(Context, Init); 4271 if (CheckRedundantInit(*this, Init, Members[Key]) || 4272 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4273 HadError = true; 4274 } else if (Init->isBaseInitializer()) { 4275 const void *Key = GetKeyForMember(Context, Init); 4276 if (CheckRedundantInit(*this, Init, Members[Key])) 4277 HadError = true; 4278 } else { 4279 assert(Init->isDelegatingInitializer()); 4280 // This must be the only initializer 4281 if (MemInits.size() != 1) { 4282 Diag(Init->getSourceLocation(), 4283 diag::err_delegating_initializer_alone) 4284 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4285 // We will treat this as being the only initializer. 4286 } 4287 SetDelegatingInitializer(Constructor, MemInits[i]); 4288 // Return immediately as the initializer is set. 4289 return; 4290 } 4291 } 4292 4293 if (HadError) 4294 return; 4295 4296 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4297 4298 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4299 4300 DiagnoseUninitializedFields(*this, Constructor); 4301 } 4302 4303 void 4304 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4305 CXXRecordDecl *ClassDecl) { 4306 // Ignore dependent contexts. Also ignore unions, since their members never 4307 // have destructors implicitly called. 4308 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4309 return; 4310 4311 // FIXME: all the access-control diagnostics are positioned on the 4312 // field/base declaration. That's probably good; that said, the 4313 // user might reasonably want to know why the destructor is being 4314 // emitted, and we currently don't say. 4315 4316 // Non-static data members. 4317 for (auto *Field : ClassDecl->fields()) { 4318 if (Field->isInvalidDecl()) 4319 continue; 4320 4321 // Don't destroy incomplete or zero-length arrays. 4322 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4323 continue; 4324 4325 QualType FieldType = Context.getBaseElementType(Field->getType()); 4326 4327 const RecordType* RT = FieldType->getAs<RecordType>(); 4328 if (!RT) 4329 continue; 4330 4331 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4332 if (FieldClassDecl->isInvalidDecl()) 4333 continue; 4334 if (FieldClassDecl->hasIrrelevantDestructor()) 4335 continue; 4336 // The destructor for an implicit anonymous union member is never invoked. 4337 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4338 continue; 4339 4340 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4341 assert(Dtor && "No dtor found for FieldClassDecl!"); 4342 CheckDestructorAccess(Field->getLocation(), Dtor, 4343 PDiag(diag::err_access_dtor_field) 4344 << Field->getDeclName() 4345 << FieldType); 4346 4347 MarkFunctionReferenced(Location, Dtor); 4348 DiagnoseUseOfDecl(Dtor, Location); 4349 } 4350 4351 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4352 4353 // Bases. 4354 for (const auto &Base : ClassDecl->bases()) { 4355 // Bases are always records in a well-formed non-dependent class. 4356 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4357 4358 // Remember direct virtual bases. 4359 if (Base.isVirtual()) 4360 DirectVirtualBases.insert(RT); 4361 4362 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4363 // If our base class is invalid, we probably can't get its dtor anyway. 4364 if (BaseClassDecl->isInvalidDecl()) 4365 continue; 4366 if (BaseClassDecl->hasIrrelevantDestructor()) 4367 continue; 4368 4369 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4370 assert(Dtor && "No dtor found for BaseClassDecl!"); 4371 4372 // FIXME: caret should be on the start of the class name 4373 CheckDestructorAccess(Base.getLocStart(), Dtor, 4374 PDiag(diag::err_access_dtor_base) 4375 << Base.getType() 4376 << Base.getSourceRange(), 4377 Context.getTypeDeclType(ClassDecl)); 4378 4379 MarkFunctionReferenced(Location, Dtor); 4380 DiagnoseUseOfDecl(Dtor, Location); 4381 } 4382 4383 // Virtual bases. 4384 for (const auto &VBase : ClassDecl->vbases()) { 4385 // Bases are always records in a well-formed non-dependent class. 4386 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4387 4388 // Ignore direct virtual bases. 4389 if (DirectVirtualBases.count(RT)) 4390 continue; 4391 4392 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4393 // If our base class is invalid, we probably can't get its dtor anyway. 4394 if (BaseClassDecl->isInvalidDecl()) 4395 continue; 4396 if (BaseClassDecl->hasIrrelevantDestructor()) 4397 continue; 4398 4399 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4400 assert(Dtor && "No dtor found for BaseClassDecl!"); 4401 if (CheckDestructorAccess( 4402 ClassDecl->getLocation(), Dtor, 4403 PDiag(diag::err_access_dtor_vbase) 4404 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4405 Context.getTypeDeclType(ClassDecl)) == 4406 AR_accessible) { 4407 CheckDerivedToBaseConversion( 4408 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4409 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4410 SourceRange(), DeclarationName(), nullptr); 4411 } 4412 4413 MarkFunctionReferenced(Location, Dtor); 4414 DiagnoseUseOfDecl(Dtor, Location); 4415 } 4416 } 4417 4418 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4419 if (!CDtorDecl) 4420 return; 4421 4422 if (CXXConstructorDecl *Constructor 4423 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4424 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4425 DiagnoseUninitializedFields(*this, Constructor); 4426 } 4427 } 4428 4429 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4430 unsigned DiagID, AbstractDiagSelID SelID) { 4431 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4432 unsigned DiagID; 4433 AbstractDiagSelID SelID; 4434 4435 public: 4436 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4437 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4438 4439 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4440 if (Suppressed) return; 4441 if (SelID == -1) 4442 S.Diag(Loc, DiagID) << T; 4443 else 4444 S.Diag(Loc, DiagID) << SelID << T; 4445 } 4446 } Diagnoser(DiagID, SelID); 4447 4448 return RequireNonAbstractType(Loc, T, Diagnoser); 4449 } 4450 4451 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4452 TypeDiagnoser &Diagnoser) { 4453 if (!getLangOpts().CPlusPlus) 4454 return false; 4455 4456 if (const ArrayType *AT = Context.getAsArrayType(T)) 4457 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4458 4459 if (const PointerType *PT = T->getAs<PointerType>()) { 4460 // Find the innermost pointer type. 4461 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4462 PT = T; 4463 4464 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4465 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4466 } 4467 4468 const RecordType *RT = T->getAs<RecordType>(); 4469 if (!RT) 4470 return false; 4471 4472 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4473 4474 // We can't answer whether something is abstract until it has a 4475 // definition. If it's currently being defined, we'll walk back 4476 // over all the declarations when we have a full definition. 4477 const CXXRecordDecl *Def = RD->getDefinition(); 4478 if (!Def || Def->isBeingDefined()) 4479 return false; 4480 4481 if (!RD->isAbstract()) 4482 return false; 4483 4484 Diagnoser.diagnose(*this, Loc, T); 4485 DiagnoseAbstractType(RD); 4486 4487 return true; 4488 } 4489 4490 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4491 // Check if we've already emitted the list of pure virtual functions 4492 // for this class. 4493 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4494 return; 4495 4496 // If the diagnostic is suppressed, don't emit the notes. We're only 4497 // going to emit them once, so try to attach them to a diagnostic we're 4498 // actually going to show. 4499 if (Diags.isLastDiagnosticIgnored()) 4500 return; 4501 4502 CXXFinalOverriderMap FinalOverriders; 4503 RD->getFinalOverriders(FinalOverriders); 4504 4505 // Keep a set of seen pure methods so we won't diagnose the same method 4506 // more than once. 4507 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4508 4509 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4510 MEnd = FinalOverriders.end(); 4511 M != MEnd; 4512 ++M) { 4513 for (OverridingMethods::iterator SO = M->second.begin(), 4514 SOEnd = M->second.end(); 4515 SO != SOEnd; ++SO) { 4516 // C++ [class.abstract]p4: 4517 // A class is abstract if it contains or inherits at least one 4518 // pure virtual function for which the final overrider is pure 4519 // virtual. 4520 4521 // 4522 if (SO->second.size() != 1) 4523 continue; 4524 4525 if (!SO->second.front().Method->isPure()) 4526 continue; 4527 4528 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4529 continue; 4530 4531 Diag(SO->second.front().Method->getLocation(), 4532 diag::note_pure_virtual_function) 4533 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4534 } 4535 } 4536 4537 if (!PureVirtualClassDiagSet) 4538 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4539 PureVirtualClassDiagSet->insert(RD); 4540 } 4541 4542 namespace { 4543 struct AbstractUsageInfo { 4544 Sema &S; 4545 CXXRecordDecl *Record; 4546 CanQualType AbstractType; 4547 bool Invalid; 4548 4549 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4550 : S(S), Record(Record), 4551 AbstractType(S.Context.getCanonicalType( 4552 S.Context.getTypeDeclType(Record))), 4553 Invalid(false) {} 4554 4555 void DiagnoseAbstractType() { 4556 if (Invalid) return; 4557 S.DiagnoseAbstractType(Record); 4558 Invalid = true; 4559 } 4560 4561 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4562 }; 4563 4564 struct CheckAbstractUsage { 4565 AbstractUsageInfo &Info; 4566 const NamedDecl *Ctx; 4567 4568 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4569 : Info(Info), Ctx(Ctx) {} 4570 4571 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4572 switch (TL.getTypeLocClass()) { 4573 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4574 #define TYPELOC(CLASS, PARENT) \ 4575 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4576 #include "clang/AST/TypeLocNodes.def" 4577 } 4578 } 4579 4580 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4581 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4582 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4583 if (!TL.getParam(I)) 4584 continue; 4585 4586 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4587 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4588 } 4589 } 4590 4591 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4592 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4593 } 4594 4595 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4596 // Visit the type parameters from a permissive context. 4597 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4598 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4599 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4600 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4601 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4602 // TODO: other template argument types? 4603 } 4604 } 4605 4606 // Visit pointee types from a permissive context. 4607 #define CheckPolymorphic(Type) \ 4608 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4609 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4610 } 4611 CheckPolymorphic(PointerTypeLoc) 4612 CheckPolymorphic(ReferenceTypeLoc) 4613 CheckPolymorphic(MemberPointerTypeLoc) 4614 CheckPolymorphic(BlockPointerTypeLoc) 4615 CheckPolymorphic(AtomicTypeLoc) 4616 4617 /// Handle all the types we haven't given a more specific 4618 /// implementation for above. 4619 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4620 // Every other kind of type that we haven't called out already 4621 // that has an inner type is either (1) sugar or (2) contains that 4622 // inner type in some way as a subobject. 4623 if (TypeLoc Next = TL.getNextTypeLoc()) 4624 return Visit(Next, Sel); 4625 4626 // If there's no inner type and we're in a permissive context, 4627 // don't diagnose. 4628 if (Sel == Sema::AbstractNone) return; 4629 4630 // Check whether the type matches the abstract type. 4631 QualType T = TL.getType(); 4632 if (T->isArrayType()) { 4633 Sel = Sema::AbstractArrayType; 4634 T = Info.S.Context.getBaseElementType(T); 4635 } 4636 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4637 if (CT != Info.AbstractType) return; 4638 4639 // It matched; do some magic. 4640 if (Sel == Sema::AbstractArrayType) { 4641 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4642 << T << TL.getSourceRange(); 4643 } else { 4644 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4645 << Sel << T << TL.getSourceRange(); 4646 } 4647 Info.DiagnoseAbstractType(); 4648 } 4649 }; 4650 4651 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4652 Sema::AbstractDiagSelID Sel) { 4653 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4654 } 4655 4656 } 4657 4658 /// Check for invalid uses of an abstract type in a method declaration. 4659 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4660 CXXMethodDecl *MD) { 4661 // No need to do the check on definitions, which require that 4662 // the return/param types be complete. 4663 if (MD->doesThisDeclarationHaveABody()) 4664 return; 4665 4666 // For safety's sake, just ignore it if we don't have type source 4667 // information. This should never happen for non-implicit methods, 4668 // but... 4669 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4670 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4671 } 4672 4673 /// Check for invalid uses of an abstract type within a class definition. 4674 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4675 CXXRecordDecl *RD) { 4676 for (auto *D : RD->decls()) { 4677 if (D->isImplicit()) continue; 4678 4679 // Methods and method templates. 4680 if (isa<CXXMethodDecl>(D)) { 4681 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4682 } else if (isa<FunctionTemplateDecl>(D)) { 4683 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4684 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4685 4686 // Fields and static variables. 4687 } else if (isa<FieldDecl>(D)) { 4688 FieldDecl *FD = cast<FieldDecl>(D); 4689 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4690 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4691 } else if (isa<VarDecl>(D)) { 4692 VarDecl *VD = cast<VarDecl>(D); 4693 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4694 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4695 4696 // Nested classes and class templates. 4697 } else if (isa<CXXRecordDecl>(D)) { 4698 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4699 } else if (isa<ClassTemplateDecl>(D)) { 4700 CheckAbstractClassUsage(Info, 4701 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4702 } 4703 } 4704 } 4705 4706 /// \brief Check class-level dllimport/dllexport attribute. 4707 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4708 Attr *ClassAttr = getDLLAttr(Class); 4709 4710 // MSVC inherits DLL attributes to partial class template specializations. 4711 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4712 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4713 if (Attr *TemplateAttr = 4714 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4715 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext())); 4716 A->setInherited(true); 4717 ClassAttr = A; 4718 } 4719 } 4720 } 4721 4722 if (!ClassAttr) 4723 return; 4724 4725 if (!Class->isExternallyVisible()) { 4726 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4727 << Class << ClassAttr; 4728 return; 4729 } 4730 4731 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4732 !ClassAttr->isInherited()) { 4733 // Diagnose dll attributes on members of class with dll attribute. 4734 for (Decl *Member : Class->decls()) { 4735 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4736 continue; 4737 InheritableAttr *MemberAttr = getDLLAttr(Member); 4738 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4739 continue; 4740 4741 S.Diag(MemberAttr->getLocation(), 4742 diag::err_attribute_dll_member_of_dll_class) 4743 << MemberAttr << ClassAttr; 4744 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4745 Member->setInvalidDecl(); 4746 } 4747 } 4748 4749 if (Class->getDescribedClassTemplate()) 4750 // Don't inherit dll attribute until the template is instantiated. 4751 return; 4752 4753 // The class is either imported or exported. 4754 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4755 const bool ClassImported = !ClassExported; 4756 4757 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 4758 4759 // Don't dllexport explicit class template instantiation declarations. 4760 if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) { 4761 Class->dropAttr<DLLExportAttr>(); 4762 return; 4763 } 4764 4765 // Force declaration of implicit members so they can inherit the attribute. 4766 S.ForceDeclarationOfImplicitMembers(Class); 4767 4768 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4769 // seem to be true in practice? 4770 4771 for (Decl *Member : Class->decls()) { 4772 VarDecl *VD = dyn_cast<VarDecl>(Member); 4773 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4774 4775 // Only methods and static fields inherit the attributes. 4776 if (!VD && !MD) 4777 continue; 4778 4779 if (MD) { 4780 // Don't process deleted methods. 4781 if (MD->isDeleted()) 4782 continue; 4783 4784 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) { 4785 // Current MSVC versions don't export the move assignment operators, so 4786 // don't attempt to import them if we have a definition. 4787 continue; 4788 } 4789 4790 if (MD->isInlined() && 4791 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4792 // MinGW does not import or export inline methods. 4793 continue; 4794 } 4795 } 4796 4797 if (!getDLLAttr(Member)) { 4798 auto *NewAttr = 4799 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4800 NewAttr->setInherited(true); 4801 Member->addAttr(NewAttr); 4802 } 4803 4804 if (MD && ClassExported) { 4805 if (MD->isUserProvided()) { 4806 // Instantiate non-default class member functions ... 4807 4808 // .. except for certain kinds of template specializations. 4809 if (TSK == TSK_ExplicitInstantiationDeclaration) 4810 continue; 4811 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4812 continue; 4813 4814 S.MarkFunctionReferenced(Class->getLocation(), MD); 4815 4816 // The function will be passed to the consumer when its definition is 4817 // encountered. 4818 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4819 MD->isCopyAssignmentOperator() || 4820 MD->isMoveAssignmentOperator()) { 4821 // Synthesize and instantiate non-trivial implicit methods, explicitly 4822 // defaulted methods, and the copy and move assignment operators. The 4823 // latter are exported even if they are trivial, because the address of 4824 // an operator can be taken and should compare equal accross libraries. 4825 DiagnosticErrorTrap Trap(S.Diags); 4826 S.MarkFunctionReferenced(Class->getLocation(), MD); 4827 if (Trap.hasErrorOccurred()) { 4828 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 4829 << Class->getName() << !S.getLangOpts().CPlusPlus11; 4830 break; 4831 } 4832 4833 // There is no later point when we will see the definition of this 4834 // function, so pass it to the consumer now. 4835 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 4836 } 4837 } 4838 } 4839 } 4840 4841 /// \brief Perform semantic checks on a class definition that has been 4842 /// completing, introducing implicitly-declared members, checking for 4843 /// abstract types, etc. 4844 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4845 if (!Record) 4846 return; 4847 4848 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4849 AbstractUsageInfo Info(*this, Record); 4850 CheckAbstractClassUsage(Info, Record); 4851 } 4852 4853 // If this is not an aggregate type and has no user-declared constructor, 4854 // complain about any non-static data members of reference or const scalar 4855 // type, since they will never get initializers. 4856 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4857 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4858 !Record->isLambda()) { 4859 bool Complained = false; 4860 for (const auto *F : Record->fields()) { 4861 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4862 continue; 4863 4864 if (F->getType()->isReferenceType() || 4865 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4866 if (!Complained) { 4867 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4868 << Record->getTagKind() << Record; 4869 Complained = true; 4870 } 4871 4872 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4873 << F->getType()->isReferenceType() 4874 << F->getDeclName(); 4875 } 4876 } 4877 } 4878 4879 if (Record->getIdentifier()) { 4880 // C++ [class.mem]p13: 4881 // If T is the name of a class, then each of the following shall have a 4882 // name different from T: 4883 // - every member of every anonymous union that is a member of class T. 4884 // 4885 // C++ [class.mem]p14: 4886 // In addition, if class T has a user-declared constructor (12.1), every 4887 // non-static data member of class T shall have a name different from T. 4888 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4889 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4890 ++I) { 4891 NamedDecl *D = *I; 4892 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4893 isa<IndirectFieldDecl>(D)) { 4894 Diag(D->getLocation(), diag::err_member_name_of_class) 4895 << D->getDeclName(); 4896 break; 4897 } 4898 } 4899 } 4900 4901 // Warn if the class has virtual methods but non-virtual public destructor. 4902 if (Record->isPolymorphic() && !Record->isDependentType()) { 4903 CXXDestructorDecl *dtor = Record->getDestructor(); 4904 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4905 !Record->hasAttr<FinalAttr>()) 4906 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4907 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4908 } 4909 4910 if (Record->isAbstract()) { 4911 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4912 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4913 << FA->isSpelledAsSealed(); 4914 DiagnoseAbstractType(Record); 4915 } 4916 } 4917 4918 bool HasMethodWithOverrideControl = false, 4919 HasOverridingMethodWithoutOverrideControl = false; 4920 if (!Record->isDependentType()) { 4921 for (auto *M : Record->methods()) { 4922 // See if a method overloads virtual methods in a base 4923 // class without overriding any. 4924 if (!M->isStatic()) 4925 DiagnoseHiddenVirtualMethods(M); 4926 if (M->hasAttr<OverrideAttr>()) 4927 HasMethodWithOverrideControl = true; 4928 else if (M->size_overridden_methods() > 0) 4929 HasOverridingMethodWithoutOverrideControl = true; 4930 // Check whether the explicitly-defaulted special members are valid. 4931 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4932 CheckExplicitlyDefaultedSpecialMember(M); 4933 4934 // For an explicitly defaulted or deleted special member, we defer 4935 // determining triviality until the class is complete. That time is now! 4936 if (!M->isImplicit() && !M->isUserProvided()) { 4937 CXXSpecialMember CSM = getSpecialMember(M); 4938 if (CSM != CXXInvalid) { 4939 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4940 4941 // Inform the class that we've finished declaring this member. 4942 Record->finishedDefaultedOrDeletedMember(M); 4943 } 4944 } 4945 } 4946 } 4947 4948 if (HasMethodWithOverrideControl && 4949 HasOverridingMethodWithoutOverrideControl) { 4950 // At least one method has the 'override' control declared. 4951 // Diagnose all other overridden methods which do not have 'override' specified on them. 4952 for (auto *M : Record->methods()) 4953 DiagnoseAbsenceOfOverrideControl(M); 4954 } 4955 4956 // ms_struct is a request to use the same ABI rules as MSVC. Check 4957 // whether this class uses any C++ features that are implemented 4958 // completely differently in MSVC, and if so, emit a diagnostic. 4959 // That diagnostic defaults to an error, but we allow projects to 4960 // map it down to a warning (or ignore it). It's a fairly common 4961 // practice among users of the ms_struct pragma to mass-annotate 4962 // headers, sweeping up a bunch of types that the project doesn't 4963 // really rely on MSVC-compatible layout for. We must therefore 4964 // support "ms_struct except for C++ stuff" as a secondary ABI. 4965 if (Record->isMsStruct(Context) && 4966 (Record->isPolymorphic() || Record->getNumBases())) { 4967 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4968 } 4969 4970 // Declare inheriting constructors. We do this eagerly here because: 4971 // - The standard requires an eager diagnostic for conflicting inheriting 4972 // constructors from different classes. 4973 // - The lazy declaration of the other implicit constructors is so as to not 4974 // waste space and performance on classes that are not meant to be 4975 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4976 // have inheriting constructors. 4977 DeclareInheritingConstructors(Record); 4978 4979 checkDLLAttribute(*this, Record); 4980 } 4981 4982 /// Look up the special member function that would be called by a special 4983 /// member function for a subobject of class type. 4984 /// 4985 /// \param Class The class type of the subobject. 4986 /// \param CSM The kind of special member function. 4987 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4988 /// \param ConstRHS True if this is a copy operation with a const object 4989 /// on its RHS, that is, if the argument to the outer special member 4990 /// function is 'const' and this is not a field marked 'mutable'. 4991 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4992 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4993 unsigned FieldQuals, bool ConstRHS) { 4994 unsigned LHSQuals = 0; 4995 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4996 LHSQuals = FieldQuals; 4997 4998 unsigned RHSQuals = FieldQuals; 4999 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5000 RHSQuals = 0; 5001 else if (ConstRHS) 5002 RHSQuals |= Qualifiers::Const; 5003 5004 return S.LookupSpecialMember(Class, CSM, 5005 RHSQuals & Qualifiers::Const, 5006 RHSQuals & Qualifiers::Volatile, 5007 false, 5008 LHSQuals & Qualifiers::Const, 5009 LHSQuals & Qualifiers::Volatile); 5010 } 5011 5012 /// Is the special member function which would be selected to perform the 5013 /// specified operation on the specified class type a constexpr constructor? 5014 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5015 Sema::CXXSpecialMember CSM, 5016 unsigned Quals, bool ConstRHS) { 5017 Sema::SpecialMemberOverloadResult *SMOR = 5018 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 5019 if (!SMOR || !SMOR->getMethod()) 5020 // A constructor we wouldn't select can't be "involved in initializing" 5021 // anything. 5022 return true; 5023 return SMOR->getMethod()->isConstexpr(); 5024 } 5025 5026 /// Determine whether the specified special member function would be constexpr 5027 /// if it were implicitly defined. 5028 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 5029 Sema::CXXSpecialMember CSM, 5030 bool ConstArg) { 5031 if (!S.getLangOpts().CPlusPlus11) 5032 return false; 5033 5034 // C++11 [dcl.constexpr]p4: 5035 // In the definition of a constexpr constructor [...] 5036 bool Ctor = true; 5037 switch (CSM) { 5038 case Sema::CXXDefaultConstructor: 5039 // Since default constructor lookup is essentially trivial (and cannot 5040 // involve, for instance, template instantiation), we compute whether a 5041 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5042 // 5043 // This is important for performance; we need to know whether the default 5044 // constructor is constexpr to determine whether the type is a literal type. 5045 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5046 5047 case Sema::CXXCopyConstructor: 5048 case Sema::CXXMoveConstructor: 5049 // For copy or move constructors, we need to perform overload resolution. 5050 break; 5051 5052 case Sema::CXXCopyAssignment: 5053 case Sema::CXXMoveAssignment: 5054 if (!S.getLangOpts().CPlusPlus14) 5055 return false; 5056 // In C++1y, we need to perform overload resolution. 5057 Ctor = false; 5058 break; 5059 5060 case Sema::CXXDestructor: 5061 case Sema::CXXInvalid: 5062 return false; 5063 } 5064 5065 // -- if the class is a non-empty union, or for each non-empty anonymous 5066 // union member of a non-union class, exactly one non-static data member 5067 // shall be initialized; [DR1359] 5068 // 5069 // If we squint, this is guaranteed, since exactly one non-static data member 5070 // will be initialized (if the constructor isn't deleted), we just don't know 5071 // which one. 5072 if (Ctor && ClassDecl->isUnion()) 5073 return true; 5074 5075 // -- the class shall not have any virtual base classes; 5076 if (Ctor && ClassDecl->getNumVBases()) 5077 return false; 5078 5079 // C++1y [class.copy]p26: 5080 // -- [the class] is a literal type, and 5081 if (!Ctor && !ClassDecl->isLiteral()) 5082 return false; 5083 5084 // -- every constructor involved in initializing [...] base class 5085 // sub-objects shall be a constexpr constructor; 5086 // -- the assignment operator selected to copy/move each direct base 5087 // class is a constexpr function, and 5088 for (const auto &B : ClassDecl->bases()) { 5089 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5090 if (!BaseType) continue; 5091 5092 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5093 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5094 return false; 5095 } 5096 5097 // -- every constructor involved in initializing non-static data members 5098 // [...] shall be a constexpr constructor; 5099 // -- every non-static data member and base class sub-object shall be 5100 // initialized 5101 // -- for each non-static data member of X that is of class type (or array 5102 // thereof), the assignment operator selected to copy/move that member is 5103 // a constexpr function 5104 for (const auto *F : ClassDecl->fields()) { 5105 if (F->isInvalidDecl()) 5106 continue; 5107 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5108 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5109 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5110 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5111 BaseType.getCVRQualifiers(), 5112 ConstArg && !F->isMutable())) 5113 return false; 5114 } 5115 } 5116 5117 // All OK, it's constexpr! 5118 return true; 5119 } 5120 5121 static Sema::ImplicitExceptionSpecification 5122 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5123 switch (S.getSpecialMember(MD)) { 5124 case Sema::CXXDefaultConstructor: 5125 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5126 case Sema::CXXCopyConstructor: 5127 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5128 case Sema::CXXCopyAssignment: 5129 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5130 case Sema::CXXMoveConstructor: 5131 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5132 case Sema::CXXMoveAssignment: 5133 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5134 case Sema::CXXDestructor: 5135 return S.ComputeDefaultedDtorExceptionSpec(MD); 5136 case Sema::CXXInvalid: 5137 break; 5138 } 5139 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5140 "only special members have implicit exception specs"); 5141 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5142 } 5143 5144 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5145 CXXMethodDecl *MD) { 5146 FunctionProtoType::ExtProtoInfo EPI; 5147 5148 // Build an exception specification pointing back at this member. 5149 EPI.ExceptionSpec.Type = EST_Unevaluated; 5150 EPI.ExceptionSpec.SourceDecl = MD; 5151 5152 // Set the calling convention to the default for C++ instance methods. 5153 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5154 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5155 /*IsCXXMethod=*/true)); 5156 return EPI; 5157 } 5158 5159 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5160 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5161 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5162 return; 5163 5164 // Evaluate the exception specification. 5165 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5166 5167 // Update the type of the special member to use it. 5168 UpdateExceptionSpec(MD, ESI); 5169 5170 // A user-provided destructor can be defined outside the class. When that 5171 // happens, be sure to update the exception specification on both 5172 // declarations. 5173 const FunctionProtoType *CanonicalFPT = 5174 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5175 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5176 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5177 } 5178 5179 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5180 CXXRecordDecl *RD = MD->getParent(); 5181 CXXSpecialMember CSM = getSpecialMember(MD); 5182 5183 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5184 "not an explicitly-defaulted special member"); 5185 5186 // Whether this was the first-declared instance of the constructor. 5187 // This affects whether we implicitly add an exception spec and constexpr. 5188 bool First = MD == MD->getCanonicalDecl(); 5189 5190 bool HadError = false; 5191 5192 // C++11 [dcl.fct.def.default]p1: 5193 // A function that is explicitly defaulted shall 5194 // -- be a special member function (checked elsewhere), 5195 // -- have the same type (except for ref-qualifiers, and except that a 5196 // copy operation can take a non-const reference) as an implicit 5197 // declaration, and 5198 // -- not have default arguments. 5199 unsigned ExpectedParams = 1; 5200 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5201 ExpectedParams = 0; 5202 if (MD->getNumParams() != ExpectedParams) { 5203 // This also checks for default arguments: a copy or move constructor with a 5204 // default argument is classified as a default constructor, and assignment 5205 // operations and destructors can't have default arguments. 5206 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5207 << CSM << MD->getSourceRange(); 5208 HadError = true; 5209 } else if (MD->isVariadic()) { 5210 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5211 << CSM << MD->getSourceRange(); 5212 HadError = true; 5213 } 5214 5215 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5216 5217 bool CanHaveConstParam = false; 5218 if (CSM == CXXCopyConstructor) 5219 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5220 else if (CSM == CXXCopyAssignment) 5221 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5222 5223 QualType ReturnType = Context.VoidTy; 5224 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5225 // Check for return type matching. 5226 ReturnType = Type->getReturnType(); 5227 QualType ExpectedReturnType = 5228 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5229 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5230 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5231 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5232 HadError = true; 5233 } 5234 5235 // A defaulted special member cannot have cv-qualifiers. 5236 if (Type->getTypeQuals()) { 5237 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5238 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5239 HadError = true; 5240 } 5241 } 5242 5243 // Check for parameter type matching. 5244 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5245 bool HasConstParam = false; 5246 if (ExpectedParams && ArgType->isReferenceType()) { 5247 // Argument must be reference to possibly-const T. 5248 QualType ReferentType = ArgType->getPointeeType(); 5249 HasConstParam = ReferentType.isConstQualified(); 5250 5251 if (ReferentType.isVolatileQualified()) { 5252 Diag(MD->getLocation(), 5253 diag::err_defaulted_special_member_volatile_param) << CSM; 5254 HadError = true; 5255 } 5256 5257 if (HasConstParam && !CanHaveConstParam) { 5258 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5259 Diag(MD->getLocation(), 5260 diag::err_defaulted_special_member_copy_const_param) 5261 << (CSM == CXXCopyAssignment); 5262 // FIXME: Explain why this special member can't be const. 5263 } else { 5264 Diag(MD->getLocation(), 5265 diag::err_defaulted_special_member_move_const_param) 5266 << (CSM == CXXMoveAssignment); 5267 } 5268 HadError = true; 5269 } 5270 } else if (ExpectedParams) { 5271 // A copy assignment operator can take its argument by value, but a 5272 // defaulted one cannot. 5273 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5274 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5275 HadError = true; 5276 } 5277 5278 // C++11 [dcl.fct.def.default]p2: 5279 // An explicitly-defaulted function may be declared constexpr only if it 5280 // would have been implicitly declared as constexpr, 5281 // Do not apply this rule to members of class templates, since core issue 1358 5282 // makes such functions always instantiate to constexpr functions. For 5283 // functions which cannot be constexpr (for non-constructors in C++11 and for 5284 // destructors in C++1y), this is checked elsewhere. 5285 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5286 HasConstParam); 5287 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5288 : isa<CXXConstructorDecl>(MD)) && 5289 MD->isConstexpr() && !Constexpr && 5290 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5291 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5292 // FIXME: Explain why the special member can't be constexpr. 5293 HadError = true; 5294 } 5295 5296 // and may have an explicit exception-specification only if it is compatible 5297 // with the exception-specification on the implicit declaration. 5298 if (Type->hasExceptionSpec()) { 5299 // Delay the check if this is the first declaration of the special member, 5300 // since we may not have parsed some necessary in-class initializers yet. 5301 if (First) { 5302 // If the exception specification needs to be instantiated, do so now, 5303 // before we clobber it with an EST_Unevaluated specification below. 5304 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5305 InstantiateExceptionSpec(MD->getLocStart(), MD); 5306 Type = MD->getType()->getAs<FunctionProtoType>(); 5307 } 5308 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5309 } else 5310 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5311 } 5312 5313 // If a function is explicitly defaulted on its first declaration, 5314 if (First) { 5315 // -- it is implicitly considered to be constexpr if the implicit 5316 // definition would be, 5317 MD->setConstexpr(Constexpr); 5318 5319 // -- it is implicitly considered to have the same exception-specification 5320 // as if it had been implicitly declared, 5321 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5322 EPI.ExceptionSpec.Type = EST_Unevaluated; 5323 EPI.ExceptionSpec.SourceDecl = MD; 5324 MD->setType(Context.getFunctionType(ReturnType, 5325 llvm::makeArrayRef(&ArgType, 5326 ExpectedParams), 5327 EPI)); 5328 } 5329 5330 if (ShouldDeleteSpecialMember(MD, CSM)) { 5331 if (First) { 5332 SetDeclDeleted(MD, MD->getLocation()); 5333 } else { 5334 // C++11 [dcl.fct.def.default]p4: 5335 // [For a] user-provided explicitly-defaulted function [...] if such a 5336 // function is implicitly defined as deleted, the program is ill-formed. 5337 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5338 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5339 HadError = true; 5340 } 5341 } 5342 5343 if (HadError) 5344 MD->setInvalidDecl(); 5345 } 5346 5347 /// Check whether the exception specification provided for an 5348 /// explicitly-defaulted special member matches the exception specification 5349 /// that would have been generated for an implicit special member, per 5350 /// C++11 [dcl.fct.def.default]p2. 5351 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5352 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5353 // If the exception specification was explicitly specified but hadn't been 5354 // parsed when the method was defaulted, grab it now. 5355 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5356 SpecifiedType = 5357 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5358 5359 // Compute the implicit exception specification. 5360 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5361 /*IsCXXMethod=*/true); 5362 FunctionProtoType::ExtProtoInfo EPI(CC); 5363 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5364 .getExceptionSpec(); 5365 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5366 Context.getFunctionType(Context.VoidTy, None, EPI)); 5367 5368 // Ensure that it matches. 5369 CheckEquivalentExceptionSpec( 5370 PDiag(diag::err_incorrect_defaulted_exception_spec) 5371 << getSpecialMember(MD), PDiag(), 5372 ImplicitType, SourceLocation(), 5373 SpecifiedType, MD->getLocation()); 5374 } 5375 5376 void Sema::CheckDelayedMemberExceptionSpecs() { 5377 decltype(DelayedExceptionSpecChecks) Checks; 5378 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 5379 5380 std::swap(Checks, DelayedExceptionSpecChecks); 5381 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5382 5383 // Perform any deferred checking of exception specifications for virtual 5384 // destructors. 5385 for (auto &Check : Checks) 5386 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 5387 5388 // Check that any explicitly-defaulted methods have exception specifications 5389 // compatible with their implicit exception specifications. 5390 for (auto &Spec : Specs) 5391 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 5392 } 5393 5394 namespace { 5395 struct SpecialMemberDeletionInfo { 5396 Sema &S; 5397 CXXMethodDecl *MD; 5398 Sema::CXXSpecialMember CSM; 5399 bool Diagnose; 5400 5401 // Properties of the special member, computed for convenience. 5402 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5403 SourceLocation Loc; 5404 5405 bool AllFieldsAreConst; 5406 5407 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5408 Sema::CXXSpecialMember CSM, bool Diagnose) 5409 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5410 IsConstructor(false), IsAssignment(false), IsMove(false), 5411 ConstArg(false), Loc(MD->getLocation()), 5412 AllFieldsAreConst(true) { 5413 switch (CSM) { 5414 case Sema::CXXDefaultConstructor: 5415 case Sema::CXXCopyConstructor: 5416 IsConstructor = true; 5417 break; 5418 case Sema::CXXMoveConstructor: 5419 IsConstructor = true; 5420 IsMove = true; 5421 break; 5422 case Sema::CXXCopyAssignment: 5423 IsAssignment = true; 5424 break; 5425 case Sema::CXXMoveAssignment: 5426 IsAssignment = true; 5427 IsMove = true; 5428 break; 5429 case Sema::CXXDestructor: 5430 break; 5431 case Sema::CXXInvalid: 5432 llvm_unreachable("invalid special member kind"); 5433 } 5434 5435 if (MD->getNumParams()) { 5436 if (const ReferenceType *RT = 5437 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5438 ConstArg = RT->getPointeeType().isConstQualified(); 5439 } 5440 } 5441 5442 bool inUnion() const { return MD->getParent()->isUnion(); } 5443 5444 /// Look up the corresponding special member in the given class. 5445 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5446 unsigned Quals, bool IsMutable) { 5447 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5448 ConstArg && !IsMutable); 5449 } 5450 5451 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5452 5453 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5454 bool shouldDeleteForField(FieldDecl *FD); 5455 bool shouldDeleteForAllConstMembers(); 5456 5457 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5458 unsigned Quals); 5459 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5460 Sema::SpecialMemberOverloadResult *SMOR, 5461 bool IsDtorCallInCtor); 5462 5463 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5464 }; 5465 } 5466 5467 /// Is the given special member inaccessible when used on the given 5468 /// sub-object. 5469 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5470 CXXMethodDecl *target) { 5471 /// If we're operating on a base class, the object type is the 5472 /// type of this special member. 5473 QualType objectTy; 5474 AccessSpecifier access = target->getAccess(); 5475 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5476 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5477 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5478 5479 // If we're operating on a field, the object type is the type of the field. 5480 } else { 5481 objectTy = S.Context.getTypeDeclType(target->getParent()); 5482 } 5483 5484 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5485 } 5486 5487 /// Check whether we should delete a special member due to the implicit 5488 /// definition containing a call to a special member of a subobject. 5489 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5490 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5491 bool IsDtorCallInCtor) { 5492 CXXMethodDecl *Decl = SMOR->getMethod(); 5493 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5494 5495 int DiagKind = -1; 5496 5497 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5498 DiagKind = !Decl ? 0 : 1; 5499 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5500 DiagKind = 2; 5501 else if (!isAccessible(Subobj, Decl)) 5502 DiagKind = 3; 5503 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5504 !Decl->isTrivial()) { 5505 // A member of a union must have a trivial corresponding special member. 5506 // As a weird special case, a destructor call from a union's constructor 5507 // must be accessible and non-deleted, but need not be trivial. Such a 5508 // destructor is never actually called, but is semantically checked as 5509 // if it were. 5510 DiagKind = 4; 5511 } 5512 5513 if (DiagKind == -1) 5514 return false; 5515 5516 if (Diagnose) { 5517 if (Field) { 5518 S.Diag(Field->getLocation(), 5519 diag::note_deleted_special_member_class_subobject) 5520 << CSM << MD->getParent() << /*IsField*/true 5521 << Field << DiagKind << IsDtorCallInCtor; 5522 } else { 5523 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5524 S.Diag(Base->getLocStart(), 5525 diag::note_deleted_special_member_class_subobject) 5526 << CSM << MD->getParent() << /*IsField*/false 5527 << Base->getType() << DiagKind << IsDtorCallInCtor; 5528 } 5529 5530 if (DiagKind == 1) 5531 S.NoteDeletedFunction(Decl); 5532 // FIXME: Explain inaccessibility if DiagKind == 3. 5533 } 5534 5535 return true; 5536 } 5537 5538 /// Check whether we should delete a special member function due to having a 5539 /// direct or virtual base class or non-static data member of class type M. 5540 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5541 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5542 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5543 bool IsMutable = Field && Field->isMutable(); 5544 5545 // C++11 [class.ctor]p5: 5546 // -- any direct or virtual base class, or non-static data member with no 5547 // brace-or-equal-initializer, has class type M (or array thereof) and 5548 // either M has no default constructor or overload resolution as applied 5549 // to M's default constructor results in an ambiguity or in a function 5550 // that is deleted or inaccessible 5551 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5552 // -- a direct or virtual base class B that cannot be copied/moved because 5553 // overload resolution, as applied to B's corresponding special member, 5554 // results in an ambiguity or a function that is deleted or inaccessible 5555 // from the defaulted special member 5556 // C++11 [class.dtor]p5: 5557 // -- any direct or virtual base class [...] has a type with a destructor 5558 // that is deleted or inaccessible 5559 if (!(CSM == Sema::CXXDefaultConstructor && 5560 Field && Field->hasInClassInitializer()) && 5561 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5562 false)) 5563 return true; 5564 5565 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5566 // -- any direct or virtual base class or non-static data member has a 5567 // type with a destructor that is deleted or inaccessible 5568 if (IsConstructor) { 5569 Sema::SpecialMemberOverloadResult *SMOR = 5570 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5571 false, false, false, false, false); 5572 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5573 return true; 5574 } 5575 5576 return false; 5577 } 5578 5579 /// Check whether we should delete a special member function due to the class 5580 /// having a particular direct or virtual base class. 5581 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5582 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5583 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5584 } 5585 5586 /// Check whether we should delete a special member function due to the class 5587 /// having a particular non-static data member. 5588 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5589 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5590 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5591 5592 if (CSM == Sema::CXXDefaultConstructor) { 5593 // For a default constructor, all references must be initialized in-class 5594 // and, if a union, it must have a non-const member. 5595 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5596 if (Diagnose) 5597 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5598 << MD->getParent() << FD << FieldType << /*Reference*/0; 5599 return true; 5600 } 5601 // C++11 [class.ctor]p5: any non-variant non-static data member of 5602 // const-qualified type (or array thereof) with no 5603 // brace-or-equal-initializer does not have a user-provided default 5604 // constructor. 5605 if (!inUnion() && FieldType.isConstQualified() && 5606 !FD->hasInClassInitializer() && 5607 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5608 if (Diagnose) 5609 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5610 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5611 return true; 5612 } 5613 5614 if (inUnion() && !FieldType.isConstQualified()) 5615 AllFieldsAreConst = false; 5616 } else if (CSM == Sema::CXXCopyConstructor) { 5617 // For a copy constructor, data members must not be of rvalue reference 5618 // type. 5619 if (FieldType->isRValueReferenceType()) { 5620 if (Diagnose) 5621 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5622 << MD->getParent() << FD << FieldType; 5623 return true; 5624 } 5625 } else if (IsAssignment) { 5626 // For an assignment operator, data members must not be of reference type. 5627 if (FieldType->isReferenceType()) { 5628 if (Diagnose) 5629 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5630 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5631 return true; 5632 } 5633 if (!FieldRecord && FieldType.isConstQualified()) { 5634 // C++11 [class.copy]p23: 5635 // -- a non-static data member of const non-class type (or array thereof) 5636 if (Diagnose) 5637 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5638 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5639 return true; 5640 } 5641 } 5642 5643 if (FieldRecord) { 5644 // Some additional restrictions exist on the variant members. 5645 if (!inUnion() && FieldRecord->isUnion() && 5646 FieldRecord->isAnonymousStructOrUnion()) { 5647 bool AllVariantFieldsAreConst = true; 5648 5649 // FIXME: Handle anonymous unions declared within anonymous unions. 5650 for (auto *UI : FieldRecord->fields()) { 5651 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5652 5653 if (!UnionFieldType.isConstQualified()) 5654 AllVariantFieldsAreConst = false; 5655 5656 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5657 if (UnionFieldRecord && 5658 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5659 UnionFieldType.getCVRQualifiers())) 5660 return true; 5661 } 5662 5663 // At least one member in each anonymous union must be non-const 5664 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5665 !FieldRecord->field_empty()) { 5666 if (Diagnose) 5667 S.Diag(FieldRecord->getLocation(), 5668 diag::note_deleted_default_ctor_all_const) 5669 << MD->getParent() << /*anonymous union*/1; 5670 return true; 5671 } 5672 5673 // Don't check the implicit member of the anonymous union type. 5674 // This is technically non-conformant, but sanity demands it. 5675 return false; 5676 } 5677 5678 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5679 FieldType.getCVRQualifiers())) 5680 return true; 5681 } 5682 5683 return false; 5684 } 5685 5686 /// C++11 [class.ctor] p5: 5687 /// A defaulted default constructor for a class X is defined as deleted if 5688 /// X is a union and all of its variant members are of const-qualified type. 5689 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5690 // This is a silly definition, because it gives an empty union a deleted 5691 // default constructor. Don't do that. 5692 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5693 !MD->getParent()->field_empty()) { 5694 if (Diagnose) 5695 S.Diag(MD->getParent()->getLocation(), 5696 diag::note_deleted_default_ctor_all_const) 5697 << MD->getParent() << /*not anonymous union*/0; 5698 return true; 5699 } 5700 return false; 5701 } 5702 5703 /// Determine whether a defaulted special member function should be defined as 5704 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5705 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5706 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5707 bool Diagnose) { 5708 if (MD->isInvalidDecl()) 5709 return false; 5710 CXXRecordDecl *RD = MD->getParent(); 5711 assert(!RD->isDependentType() && "do deletion after instantiation"); 5712 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5713 return false; 5714 5715 // C++11 [expr.lambda.prim]p19: 5716 // The closure type associated with a lambda-expression has a 5717 // deleted (8.4.3) default constructor and a deleted copy 5718 // assignment operator. 5719 if (RD->isLambda() && 5720 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5721 if (Diagnose) 5722 Diag(RD->getLocation(), diag::note_lambda_decl); 5723 return true; 5724 } 5725 5726 // For an anonymous struct or union, the copy and assignment special members 5727 // will never be used, so skip the check. For an anonymous union declared at 5728 // namespace scope, the constructor and destructor are used. 5729 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5730 RD->isAnonymousStructOrUnion()) 5731 return false; 5732 5733 // C++11 [class.copy]p7, p18: 5734 // If the class definition declares a move constructor or move assignment 5735 // operator, an implicitly declared copy constructor or copy assignment 5736 // operator is defined as deleted. 5737 if (MD->isImplicit() && 5738 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5739 CXXMethodDecl *UserDeclaredMove = nullptr; 5740 5741 // In Microsoft mode, a user-declared move only causes the deletion of the 5742 // corresponding copy operation, not both copy operations. 5743 if (RD->hasUserDeclaredMoveConstructor() && 5744 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5745 if (!Diagnose) return true; 5746 5747 // Find any user-declared move constructor. 5748 for (auto *I : RD->ctors()) { 5749 if (I->isMoveConstructor()) { 5750 UserDeclaredMove = I; 5751 break; 5752 } 5753 } 5754 assert(UserDeclaredMove); 5755 } else if (RD->hasUserDeclaredMoveAssignment() && 5756 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5757 if (!Diagnose) return true; 5758 5759 // Find any user-declared move assignment operator. 5760 for (auto *I : RD->methods()) { 5761 if (I->isMoveAssignmentOperator()) { 5762 UserDeclaredMove = I; 5763 break; 5764 } 5765 } 5766 assert(UserDeclaredMove); 5767 } 5768 5769 if (UserDeclaredMove) { 5770 Diag(UserDeclaredMove->getLocation(), 5771 diag::note_deleted_copy_user_declared_move) 5772 << (CSM == CXXCopyAssignment) << RD 5773 << UserDeclaredMove->isMoveAssignmentOperator(); 5774 return true; 5775 } 5776 } 5777 5778 // Do access control from the special member function 5779 ContextRAII MethodContext(*this, MD); 5780 5781 // C++11 [class.dtor]p5: 5782 // -- for a virtual destructor, lookup of the non-array deallocation function 5783 // results in an ambiguity or in a function that is deleted or inaccessible 5784 if (CSM == CXXDestructor && MD->isVirtual()) { 5785 FunctionDecl *OperatorDelete = nullptr; 5786 DeclarationName Name = 5787 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5788 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5789 OperatorDelete, false)) { 5790 if (Diagnose) 5791 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5792 return true; 5793 } 5794 } 5795 5796 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5797 5798 for (auto &BI : RD->bases()) 5799 if (!BI.isVirtual() && 5800 SMI.shouldDeleteForBase(&BI)) 5801 return true; 5802 5803 // Per DR1611, do not consider virtual bases of constructors of abstract 5804 // classes, since we are not going to construct them. 5805 if (!RD->isAbstract() || !SMI.IsConstructor) { 5806 for (auto &BI : RD->vbases()) 5807 if (SMI.shouldDeleteForBase(&BI)) 5808 return true; 5809 } 5810 5811 for (auto *FI : RD->fields()) 5812 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5813 SMI.shouldDeleteForField(FI)) 5814 return true; 5815 5816 if (SMI.shouldDeleteForAllConstMembers()) 5817 return true; 5818 5819 if (getLangOpts().CUDA) { 5820 // We should delete the special member in CUDA mode if target inference 5821 // failed. 5822 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5823 Diagnose); 5824 } 5825 5826 return false; 5827 } 5828 5829 /// Perform lookup for a special member of the specified kind, and determine 5830 /// whether it is trivial. If the triviality can be determined without the 5831 /// lookup, skip it. This is intended for use when determining whether a 5832 /// special member of a containing object is trivial, and thus does not ever 5833 /// perform overload resolution for default constructors. 5834 /// 5835 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5836 /// member that was most likely to be intended to be trivial, if any. 5837 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5838 Sema::CXXSpecialMember CSM, unsigned Quals, 5839 bool ConstRHS, CXXMethodDecl **Selected) { 5840 if (Selected) 5841 *Selected = nullptr; 5842 5843 switch (CSM) { 5844 case Sema::CXXInvalid: 5845 llvm_unreachable("not a special member"); 5846 5847 case Sema::CXXDefaultConstructor: 5848 // C++11 [class.ctor]p5: 5849 // A default constructor is trivial if: 5850 // - all the [direct subobjects] have trivial default constructors 5851 // 5852 // Note, no overload resolution is performed in this case. 5853 if (RD->hasTrivialDefaultConstructor()) 5854 return true; 5855 5856 if (Selected) { 5857 // If there's a default constructor which could have been trivial, dig it 5858 // out. Otherwise, if there's any user-provided default constructor, point 5859 // to that as an example of why there's not a trivial one. 5860 CXXConstructorDecl *DefCtor = nullptr; 5861 if (RD->needsImplicitDefaultConstructor()) 5862 S.DeclareImplicitDefaultConstructor(RD); 5863 for (auto *CI : RD->ctors()) { 5864 if (!CI->isDefaultConstructor()) 5865 continue; 5866 DefCtor = CI; 5867 if (!DefCtor->isUserProvided()) 5868 break; 5869 } 5870 5871 *Selected = DefCtor; 5872 } 5873 5874 return false; 5875 5876 case Sema::CXXDestructor: 5877 // C++11 [class.dtor]p5: 5878 // A destructor is trivial if: 5879 // - all the direct [subobjects] have trivial destructors 5880 if (RD->hasTrivialDestructor()) 5881 return true; 5882 5883 if (Selected) { 5884 if (RD->needsImplicitDestructor()) 5885 S.DeclareImplicitDestructor(RD); 5886 *Selected = RD->getDestructor(); 5887 } 5888 5889 return false; 5890 5891 case Sema::CXXCopyConstructor: 5892 // C++11 [class.copy]p12: 5893 // A copy constructor is trivial if: 5894 // - the constructor selected to copy each direct [subobject] is trivial 5895 if (RD->hasTrivialCopyConstructor()) { 5896 if (Quals == Qualifiers::Const) 5897 // We must either select the trivial copy constructor or reach an 5898 // ambiguity; no need to actually perform overload resolution. 5899 return true; 5900 } else if (!Selected) { 5901 return false; 5902 } 5903 // In C++98, we are not supposed to perform overload resolution here, but we 5904 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5905 // cases like B as having a non-trivial copy constructor: 5906 // struct A { template<typename T> A(T&); }; 5907 // struct B { mutable A a; }; 5908 goto NeedOverloadResolution; 5909 5910 case Sema::CXXCopyAssignment: 5911 // C++11 [class.copy]p25: 5912 // A copy assignment operator is trivial if: 5913 // - the assignment operator selected to copy each direct [subobject] is 5914 // trivial 5915 if (RD->hasTrivialCopyAssignment()) { 5916 if (Quals == Qualifiers::Const) 5917 return true; 5918 } else if (!Selected) { 5919 return false; 5920 } 5921 // In C++98, we are not supposed to perform overload resolution here, but we 5922 // treat that as a language defect. 5923 goto NeedOverloadResolution; 5924 5925 case Sema::CXXMoveConstructor: 5926 case Sema::CXXMoveAssignment: 5927 NeedOverloadResolution: 5928 Sema::SpecialMemberOverloadResult *SMOR = 5929 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5930 5931 // The standard doesn't describe how to behave if the lookup is ambiguous. 5932 // We treat it as not making the member non-trivial, just like the standard 5933 // mandates for the default constructor. This should rarely matter, because 5934 // the member will also be deleted. 5935 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5936 return true; 5937 5938 if (!SMOR->getMethod()) { 5939 assert(SMOR->getKind() == 5940 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5941 return false; 5942 } 5943 5944 // We deliberately don't check if we found a deleted special member. We're 5945 // not supposed to! 5946 if (Selected) 5947 *Selected = SMOR->getMethod(); 5948 return SMOR->getMethod()->isTrivial(); 5949 } 5950 5951 llvm_unreachable("unknown special method kind"); 5952 } 5953 5954 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5955 for (auto *CI : RD->ctors()) 5956 if (!CI->isImplicit()) 5957 return CI; 5958 5959 // Look for constructor templates. 5960 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5961 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5962 if (CXXConstructorDecl *CD = 5963 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5964 return CD; 5965 } 5966 5967 return nullptr; 5968 } 5969 5970 /// The kind of subobject we are checking for triviality. The values of this 5971 /// enumeration are used in diagnostics. 5972 enum TrivialSubobjectKind { 5973 /// The subobject is a base class. 5974 TSK_BaseClass, 5975 /// The subobject is a non-static data member. 5976 TSK_Field, 5977 /// The object is actually the complete object. 5978 TSK_CompleteObject 5979 }; 5980 5981 /// Check whether the special member selected for a given type would be trivial. 5982 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5983 QualType SubType, bool ConstRHS, 5984 Sema::CXXSpecialMember CSM, 5985 TrivialSubobjectKind Kind, 5986 bool Diagnose) { 5987 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5988 if (!SubRD) 5989 return true; 5990 5991 CXXMethodDecl *Selected; 5992 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5993 ConstRHS, Diagnose ? &Selected : nullptr)) 5994 return true; 5995 5996 if (Diagnose) { 5997 if (ConstRHS) 5998 SubType.addConst(); 5999 6000 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 6001 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 6002 << Kind << SubType.getUnqualifiedType(); 6003 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 6004 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 6005 } else if (!Selected) 6006 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 6007 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 6008 else if (Selected->isUserProvided()) { 6009 if (Kind == TSK_CompleteObject) 6010 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 6011 << Kind << SubType.getUnqualifiedType() << CSM; 6012 else { 6013 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 6014 << Kind << SubType.getUnqualifiedType() << CSM; 6015 S.Diag(Selected->getLocation(), diag::note_declared_at); 6016 } 6017 } else { 6018 if (Kind != TSK_CompleteObject) 6019 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 6020 << Kind << SubType.getUnqualifiedType() << CSM; 6021 6022 // Explain why the defaulted or deleted special member isn't trivial. 6023 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 6024 } 6025 } 6026 6027 return false; 6028 } 6029 6030 /// Check whether the members of a class type allow a special member to be 6031 /// trivial. 6032 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 6033 Sema::CXXSpecialMember CSM, 6034 bool ConstArg, bool Diagnose) { 6035 for (const auto *FI : RD->fields()) { 6036 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 6037 continue; 6038 6039 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 6040 6041 // Pretend anonymous struct or union members are members of this class. 6042 if (FI->isAnonymousStructOrUnion()) { 6043 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 6044 CSM, ConstArg, Diagnose)) 6045 return false; 6046 continue; 6047 } 6048 6049 // C++11 [class.ctor]p5: 6050 // A default constructor is trivial if [...] 6051 // -- no non-static data member of its class has a 6052 // brace-or-equal-initializer 6053 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 6054 if (Diagnose) 6055 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 6056 return false; 6057 } 6058 6059 // Objective C ARC 4.3.5: 6060 // [...] nontrivally ownership-qualified types are [...] not trivially 6061 // default constructible, copy constructible, move constructible, copy 6062 // assignable, move assignable, or destructible [...] 6063 if (S.getLangOpts().ObjCAutoRefCount && 6064 FieldType.hasNonTrivialObjCLifetime()) { 6065 if (Diagnose) 6066 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6067 << RD << FieldType.getObjCLifetime(); 6068 return false; 6069 } 6070 6071 bool ConstRHS = ConstArg && !FI->isMutable(); 6072 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6073 CSM, TSK_Field, Diagnose)) 6074 return false; 6075 } 6076 6077 return true; 6078 } 6079 6080 /// Diagnose why the specified class does not have a trivial special member of 6081 /// the given kind. 6082 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6083 QualType Ty = Context.getRecordType(RD); 6084 6085 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6086 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6087 TSK_CompleteObject, /*Diagnose*/true); 6088 } 6089 6090 /// Determine whether a defaulted or deleted special member function is trivial, 6091 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6092 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6093 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6094 bool Diagnose) { 6095 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6096 6097 CXXRecordDecl *RD = MD->getParent(); 6098 6099 bool ConstArg = false; 6100 6101 // C++11 [class.copy]p12, p25: [DR1593] 6102 // A [special member] is trivial if [...] its parameter-type-list is 6103 // equivalent to the parameter-type-list of an implicit declaration [...] 6104 switch (CSM) { 6105 case CXXDefaultConstructor: 6106 case CXXDestructor: 6107 // Trivial default constructors and destructors cannot have parameters. 6108 break; 6109 6110 case CXXCopyConstructor: 6111 case CXXCopyAssignment: { 6112 // Trivial copy operations always have const, non-volatile parameter types. 6113 ConstArg = true; 6114 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6115 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6116 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6117 if (Diagnose) 6118 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6119 << Param0->getSourceRange() << Param0->getType() 6120 << Context.getLValueReferenceType( 6121 Context.getRecordType(RD).withConst()); 6122 return false; 6123 } 6124 break; 6125 } 6126 6127 case CXXMoveConstructor: 6128 case CXXMoveAssignment: { 6129 // Trivial move operations always have non-cv-qualified parameters. 6130 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6131 const RValueReferenceType *RT = 6132 Param0->getType()->getAs<RValueReferenceType>(); 6133 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6134 if (Diagnose) 6135 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6136 << Param0->getSourceRange() << Param0->getType() 6137 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6138 return false; 6139 } 6140 break; 6141 } 6142 6143 case CXXInvalid: 6144 llvm_unreachable("not a special member"); 6145 } 6146 6147 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6148 if (Diagnose) 6149 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6150 diag::note_nontrivial_default_arg) 6151 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6152 return false; 6153 } 6154 if (MD->isVariadic()) { 6155 if (Diagnose) 6156 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6157 return false; 6158 } 6159 6160 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6161 // A copy/move [constructor or assignment operator] is trivial if 6162 // -- the [member] selected to copy/move each direct base class subobject 6163 // is trivial 6164 // 6165 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6166 // A [default constructor or destructor] is trivial if 6167 // -- all the direct base classes have trivial [default constructors or 6168 // destructors] 6169 for (const auto &BI : RD->bases()) 6170 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6171 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6172 return false; 6173 6174 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6175 // A copy/move [constructor or assignment operator] for a class X is 6176 // trivial if 6177 // -- for each non-static data member of X that is of class type (or array 6178 // thereof), the constructor selected to copy/move that member is 6179 // trivial 6180 // 6181 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6182 // A [default constructor or destructor] is trivial if 6183 // -- for all of the non-static data members of its class that are of class 6184 // type (or array thereof), each such class has a trivial [default 6185 // constructor or destructor] 6186 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6187 return false; 6188 6189 // C++11 [class.dtor]p5: 6190 // A destructor is trivial if [...] 6191 // -- the destructor is not virtual 6192 if (CSM == CXXDestructor && MD->isVirtual()) { 6193 if (Diagnose) 6194 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6195 return false; 6196 } 6197 6198 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6199 // A [special member] for class X is trivial if [...] 6200 // -- class X has no virtual functions and no virtual base classes 6201 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6202 if (!Diagnose) 6203 return false; 6204 6205 if (RD->getNumVBases()) { 6206 // Check for virtual bases. We already know that the corresponding 6207 // member in all bases is trivial, so vbases must all be direct. 6208 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6209 assert(BS.isVirtual()); 6210 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6211 return false; 6212 } 6213 6214 // Must have a virtual method. 6215 for (const auto *MI : RD->methods()) { 6216 if (MI->isVirtual()) { 6217 SourceLocation MLoc = MI->getLocStart(); 6218 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6219 return false; 6220 } 6221 } 6222 6223 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6224 } 6225 6226 // Looks like it's trivial! 6227 return true; 6228 } 6229 6230 /// \brief Data used with FindHiddenVirtualMethod 6231 namespace { 6232 struct FindHiddenVirtualMethodData { 6233 Sema *S; 6234 CXXMethodDecl *Method; 6235 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6236 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6237 }; 6238 } 6239 6240 /// \brief Check whether any most overriden method from MD in Methods 6241 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 6242 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6243 if (MD->size_overridden_methods() == 0) 6244 return Methods.count(MD->getCanonicalDecl()); 6245 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6246 E = MD->end_overridden_methods(); 6247 I != E; ++I) 6248 if (CheckMostOverridenMethods(*I, Methods)) 6249 return true; 6250 return false; 6251 } 6252 6253 /// \brief Member lookup function that determines whether a given C++ 6254 /// method overloads virtual methods in a base class without overriding any, 6255 /// to be used with CXXRecordDecl::lookupInBases(). 6256 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 6257 CXXBasePath &Path, 6258 void *UserData) { 6259 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6260 6261 FindHiddenVirtualMethodData &Data 6262 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 6263 6264 DeclarationName Name = Data.Method->getDeclName(); 6265 assert(Name.getNameKind() == DeclarationName::Identifier); 6266 6267 bool foundSameNameMethod = false; 6268 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6269 for (Path.Decls = BaseRecord->lookup(Name); 6270 !Path.Decls.empty(); 6271 Path.Decls = Path.Decls.slice(1)) { 6272 NamedDecl *D = Path.Decls.front(); 6273 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6274 MD = MD->getCanonicalDecl(); 6275 foundSameNameMethod = true; 6276 // Interested only in hidden virtual methods. 6277 if (!MD->isVirtual()) 6278 continue; 6279 // If the method we are checking overrides a method from its base 6280 // don't warn about the other overloaded methods. Clang deviates from GCC 6281 // by only diagnosing overloads of inherited virtual functions that do not 6282 // override any other virtual functions in the base. GCC's 6283 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6284 // function from a base class. These cases may be better served by a 6285 // warning (not specific to virtual functions) on call sites when the call 6286 // would select a different function from the base class, were it visible. 6287 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6288 if (!Data.S->IsOverload(Data.Method, MD, false)) 6289 return true; 6290 // Collect the overload only if its hidden. 6291 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 6292 overloadedMethods.push_back(MD); 6293 } 6294 } 6295 6296 if (foundSameNameMethod) 6297 Data.OverloadedMethods.append(overloadedMethods.begin(), 6298 overloadedMethods.end()); 6299 return foundSameNameMethod; 6300 } 6301 6302 /// \brief Add the most overriden methods from MD to Methods 6303 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6304 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6305 if (MD->size_overridden_methods() == 0) 6306 Methods.insert(MD->getCanonicalDecl()); 6307 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6308 E = MD->end_overridden_methods(); 6309 I != E; ++I) 6310 AddMostOverridenMethods(*I, Methods); 6311 } 6312 6313 /// \brief Check if a method overloads virtual methods in a base class without 6314 /// overriding any. 6315 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6316 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6317 if (!MD->getDeclName().isIdentifier()) 6318 return; 6319 6320 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6321 /*bool RecordPaths=*/false, 6322 /*bool DetectVirtual=*/false); 6323 FindHiddenVirtualMethodData Data; 6324 Data.Method = MD; 6325 Data.S = this; 6326 6327 // Keep the base methods that were overriden or introduced in the subclass 6328 // by 'using' in a set. A base method not in this set is hidden. 6329 CXXRecordDecl *DC = MD->getParent(); 6330 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6331 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6332 NamedDecl *ND = *I; 6333 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6334 ND = shad->getTargetDecl(); 6335 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6336 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6337 } 6338 6339 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6340 OverloadedMethods = Data.OverloadedMethods; 6341 } 6342 6343 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6344 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6345 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6346 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6347 PartialDiagnostic PD = PDiag( 6348 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6349 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6350 Diag(overloadedMD->getLocation(), PD); 6351 } 6352 } 6353 6354 /// \brief Diagnose methods which overload virtual methods in a base class 6355 /// without overriding any. 6356 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6357 if (MD->isInvalidDecl()) 6358 return; 6359 6360 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6361 return; 6362 6363 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6364 FindHiddenVirtualMethods(MD, OverloadedMethods); 6365 if (!OverloadedMethods.empty()) { 6366 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6367 << MD << (OverloadedMethods.size() > 1); 6368 6369 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6370 } 6371 } 6372 6373 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6374 Decl *TagDecl, 6375 SourceLocation LBrac, 6376 SourceLocation RBrac, 6377 AttributeList *AttrList) { 6378 if (!TagDecl) 6379 return; 6380 6381 AdjustDeclIfTemplate(TagDecl); 6382 6383 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6384 if (l->getKind() != AttributeList::AT_Visibility) 6385 continue; 6386 l->setInvalid(); 6387 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6388 l->getName(); 6389 } 6390 6391 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6392 // strict aliasing violation! 6393 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6394 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6395 6396 CheckCompletedCXXClass( 6397 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6398 } 6399 6400 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6401 /// special functions, such as the default constructor, copy 6402 /// constructor, or destructor, to the given C++ class (C++ 6403 /// [special]p1). This routine can only be executed just before the 6404 /// definition of the class is complete. 6405 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6406 if (!ClassDecl->hasUserDeclaredConstructor()) 6407 ++ASTContext::NumImplicitDefaultConstructors; 6408 6409 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6410 ++ASTContext::NumImplicitCopyConstructors; 6411 6412 // If the properties or semantics of the copy constructor couldn't be 6413 // determined while the class was being declared, force a declaration 6414 // of it now. 6415 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6416 DeclareImplicitCopyConstructor(ClassDecl); 6417 } 6418 6419 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6420 ++ASTContext::NumImplicitMoveConstructors; 6421 6422 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6423 DeclareImplicitMoveConstructor(ClassDecl); 6424 } 6425 6426 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6427 ++ASTContext::NumImplicitCopyAssignmentOperators; 6428 6429 // If we have a dynamic class, then the copy assignment operator may be 6430 // virtual, so we have to declare it immediately. This ensures that, e.g., 6431 // it shows up in the right place in the vtable and that we diagnose 6432 // problems with the implicit exception specification. 6433 if (ClassDecl->isDynamicClass() || 6434 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6435 DeclareImplicitCopyAssignment(ClassDecl); 6436 } 6437 6438 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6439 ++ASTContext::NumImplicitMoveAssignmentOperators; 6440 6441 // Likewise for the move assignment operator. 6442 if (ClassDecl->isDynamicClass() || 6443 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6444 DeclareImplicitMoveAssignment(ClassDecl); 6445 } 6446 6447 if (!ClassDecl->hasUserDeclaredDestructor()) { 6448 ++ASTContext::NumImplicitDestructors; 6449 6450 // If we have a dynamic class, then the destructor may be virtual, so we 6451 // have to declare the destructor immediately. This ensures that, e.g., it 6452 // shows up in the right place in the vtable and that we diagnose problems 6453 // with the implicit exception specification. 6454 if (ClassDecl->isDynamicClass() || 6455 ClassDecl->needsOverloadResolutionForDestructor()) 6456 DeclareImplicitDestructor(ClassDecl); 6457 } 6458 } 6459 6460 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6461 if (!D) 6462 return 0; 6463 6464 // The order of template parameters is not important here. All names 6465 // get added to the same scope. 6466 SmallVector<TemplateParameterList *, 4> ParameterLists; 6467 6468 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6469 D = TD->getTemplatedDecl(); 6470 6471 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6472 ParameterLists.push_back(PSD->getTemplateParameters()); 6473 6474 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6475 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6476 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6477 6478 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6479 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6480 ParameterLists.push_back(FTD->getTemplateParameters()); 6481 } 6482 } 6483 6484 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6485 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6486 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6487 6488 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6489 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6490 ParameterLists.push_back(CTD->getTemplateParameters()); 6491 } 6492 } 6493 6494 unsigned Count = 0; 6495 for (TemplateParameterList *Params : ParameterLists) { 6496 if (Params->size() > 0) 6497 // Ignore explicit specializations; they don't contribute to the template 6498 // depth. 6499 ++Count; 6500 for (NamedDecl *Param : *Params) { 6501 if (Param->getDeclName()) { 6502 S->AddDecl(Param); 6503 IdResolver.AddDecl(Param); 6504 } 6505 } 6506 } 6507 6508 return Count; 6509 } 6510 6511 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6512 if (!RecordD) return; 6513 AdjustDeclIfTemplate(RecordD); 6514 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6515 PushDeclContext(S, Record); 6516 } 6517 6518 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6519 if (!RecordD) return; 6520 PopDeclContext(); 6521 } 6522 6523 /// This is used to implement the constant expression evaluation part of the 6524 /// attribute enable_if extension. There is nothing in standard C++ which would 6525 /// require reentering parameters. 6526 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6527 if (!Param) 6528 return; 6529 6530 S->AddDecl(Param); 6531 if (Param->getDeclName()) 6532 IdResolver.AddDecl(Param); 6533 } 6534 6535 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6536 /// parsing a top-level (non-nested) C++ class, and we are now 6537 /// parsing those parts of the given Method declaration that could 6538 /// not be parsed earlier (C++ [class.mem]p2), such as default 6539 /// arguments. This action should enter the scope of the given 6540 /// Method declaration as if we had just parsed the qualified method 6541 /// name. However, it should not bring the parameters into scope; 6542 /// that will be performed by ActOnDelayedCXXMethodParameter. 6543 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6544 } 6545 6546 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6547 /// C++ method declaration. We're (re-)introducing the given 6548 /// function parameter into scope for use in parsing later parts of 6549 /// the method declaration. For example, we could see an 6550 /// ActOnParamDefaultArgument event for this parameter. 6551 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6552 if (!ParamD) 6553 return; 6554 6555 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6556 6557 // If this parameter has an unparsed default argument, clear it out 6558 // to make way for the parsed default argument. 6559 if (Param->hasUnparsedDefaultArg()) 6560 Param->setDefaultArg(nullptr); 6561 6562 S->AddDecl(Param); 6563 if (Param->getDeclName()) 6564 IdResolver.AddDecl(Param); 6565 } 6566 6567 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6568 /// processing the delayed method declaration for Method. The method 6569 /// declaration is now considered finished. There may be a separate 6570 /// ActOnStartOfFunctionDef action later (not necessarily 6571 /// immediately!) for this method, if it was also defined inside the 6572 /// class body. 6573 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6574 if (!MethodD) 6575 return; 6576 6577 AdjustDeclIfTemplate(MethodD); 6578 6579 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6580 6581 // Now that we have our default arguments, check the constructor 6582 // again. It could produce additional diagnostics or affect whether 6583 // the class has implicitly-declared destructors, among other 6584 // things. 6585 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6586 CheckConstructor(Constructor); 6587 6588 // Check the default arguments, which we may have added. 6589 if (!Method->isInvalidDecl()) 6590 CheckCXXDefaultArguments(Method); 6591 } 6592 6593 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6594 /// the well-formedness of the constructor declarator @p D with type @p 6595 /// R. If there are any errors in the declarator, this routine will 6596 /// emit diagnostics and set the invalid bit to true. In any case, the type 6597 /// will be updated to reflect a well-formed type for the constructor and 6598 /// returned. 6599 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6600 StorageClass &SC) { 6601 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6602 6603 // C++ [class.ctor]p3: 6604 // A constructor shall not be virtual (10.3) or static (9.4). A 6605 // constructor can be invoked for a const, volatile or const 6606 // volatile object. A constructor shall not be declared const, 6607 // volatile, or const volatile (9.3.2). 6608 if (isVirtual) { 6609 if (!D.isInvalidType()) 6610 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6611 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6612 << SourceRange(D.getIdentifierLoc()); 6613 D.setInvalidType(); 6614 } 6615 if (SC == SC_Static) { 6616 if (!D.isInvalidType()) 6617 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6618 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6619 << SourceRange(D.getIdentifierLoc()); 6620 D.setInvalidType(); 6621 SC = SC_None; 6622 } 6623 6624 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6625 diagnoseIgnoredQualifiers( 6626 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6627 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6628 D.getDeclSpec().getRestrictSpecLoc(), 6629 D.getDeclSpec().getAtomicSpecLoc()); 6630 D.setInvalidType(); 6631 } 6632 6633 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6634 if (FTI.TypeQuals != 0) { 6635 if (FTI.TypeQuals & Qualifiers::Const) 6636 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6637 << "const" << SourceRange(D.getIdentifierLoc()); 6638 if (FTI.TypeQuals & Qualifiers::Volatile) 6639 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6640 << "volatile" << SourceRange(D.getIdentifierLoc()); 6641 if (FTI.TypeQuals & Qualifiers::Restrict) 6642 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6643 << "restrict" << SourceRange(D.getIdentifierLoc()); 6644 D.setInvalidType(); 6645 } 6646 6647 // C++0x [class.ctor]p4: 6648 // A constructor shall not be declared with a ref-qualifier. 6649 if (FTI.hasRefQualifier()) { 6650 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6651 << FTI.RefQualifierIsLValueRef 6652 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6653 D.setInvalidType(); 6654 } 6655 6656 // Rebuild the function type "R" without any type qualifiers (in 6657 // case any of the errors above fired) and with "void" as the 6658 // return type, since constructors don't have return types. 6659 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6660 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6661 return R; 6662 6663 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6664 EPI.TypeQuals = 0; 6665 EPI.RefQualifier = RQ_None; 6666 6667 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6668 } 6669 6670 /// CheckConstructor - Checks a fully-formed constructor for 6671 /// well-formedness, issuing any diagnostics required. Returns true if 6672 /// the constructor declarator is invalid. 6673 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6674 CXXRecordDecl *ClassDecl 6675 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6676 if (!ClassDecl) 6677 return Constructor->setInvalidDecl(); 6678 6679 // C++ [class.copy]p3: 6680 // A declaration of a constructor for a class X is ill-formed if 6681 // its first parameter is of type (optionally cv-qualified) X and 6682 // either there are no other parameters or else all other 6683 // parameters have default arguments. 6684 if (!Constructor->isInvalidDecl() && 6685 ((Constructor->getNumParams() == 1) || 6686 (Constructor->getNumParams() > 1 && 6687 Constructor->getParamDecl(1)->hasDefaultArg())) && 6688 Constructor->getTemplateSpecializationKind() 6689 != TSK_ImplicitInstantiation) { 6690 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6691 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6692 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6693 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6694 const char *ConstRef 6695 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6696 : " const &"; 6697 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6698 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6699 6700 // FIXME: Rather that making the constructor invalid, we should endeavor 6701 // to fix the type. 6702 Constructor->setInvalidDecl(); 6703 } 6704 } 6705 } 6706 6707 /// CheckDestructor - Checks a fully-formed destructor definition for 6708 /// well-formedness, issuing any diagnostics required. Returns true 6709 /// on error. 6710 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6711 CXXRecordDecl *RD = Destructor->getParent(); 6712 6713 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6714 SourceLocation Loc; 6715 6716 if (!Destructor->isImplicit()) 6717 Loc = Destructor->getLocation(); 6718 else 6719 Loc = RD->getLocation(); 6720 6721 // If we have a virtual destructor, look up the deallocation function 6722 FunctionDecl *OperatorDelete = nullptr; 6723 DeclarationName Name = 6724 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6725 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6726 return true; 6727 // If there's no class-specific operator delete, look up the global 6728 // non-array delete. 6729 if (!OperatorDelete) 6730 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6731 6732 MarkFunctionReferenced(Loc, OperatorDelete); 6733 6734 Destructor->setOperatorDelete(OperatorDelete); 6735 } 6736 6737 return false; 6738 } 6739 6740 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6741 /// the well-formednes of the destructor declarator @p D with type @p 6742 /// R. If there are any errors in the declarator, this routine will 6743 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6744 /// will be updated to reflect a well-formed type for the destructor and 6745 /// returned. 6746 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6747 StorageClass& SC) { 6748 // C++ [class.dtor]p1: 6749 // [...] A typedef-name that names a class is a class-name 6750 // (7.1.3); however, a typedef-name that names a class shall not 6751 // be used as the identifier in the declarator for a destructor 6752 // declaration. 6753 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6754 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6755 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6756 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6757 else if (const TemplateSpecializationType *TST = 6758 DeclaratorType->getAs<TemplateSpecializationType>()) 6759 if (TST->isTypeAlias()) 6760 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6761 << DeclaratorType << 1; 6762 6763 // C++ [class.dtor]p2: 6764 // A destructor is used to destroy objects of its class type. A 6765 // destructor takes no parameters, and no return type can be 6766 // specified for it (not even void). The address of a destructor 6767 // shall not be taken. A destructor shall not be static. A 6768 // destructor can be invoked for a const, volatile or const 6769 // volatile object. A destructor shall not be declared const, 6770 // volatile or const volatile (9.3.2). 6771 if (SC == SC_Static) { 6772 if (!D.isInvalidType()) 6773 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6774 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6775 << SourceRange(D.getIdentifierLoc()) 6776 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6777 6778 SC = SC_None; 6779 } 6780 if (!D.isInvalidType()) { 6781 // Destructors don't have return types, but the parser will 6782 // happily parse something like: 6783 // 6784 // class X { 6785 // float ~X(); 6786 // }; 6787 // 6788 // The return type will be eliminated later. 6789 if (D.getDeclSpec().hasTypeSpecifier()) 6790 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6791 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6792 << SourceRange(D.getIdentifierLoc()); 6793 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6794 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6795 SourceLocation(), 6796 D.getDeclSpec().getConstSpecLoc(), 6797 D.getDeclSpec().getVolatileSpecLoc(), 6798 D.getDeclSpec().getRestrictSpecLoc(), 6799 D.getDeclSpec().getAtomicSpecLoc()); 6800 D.setInvalidType(); 6801 } 6802 } 6803 6804 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6805 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6806 if (FTI.TypeQuals & Qualifiers::Const) 6807 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6808 << "const" << SourceRange(D.getIdentifierLoc()); 6809 if (FTI.TypeQuals & Qualifiers::Volatile) 6810 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6811 << "volatile" << SourceRange(D.getIdentifierLoc()); 6812 if (FTI.TypeQuals & Qualifiers::Restrict) 6813 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6814 << "restrict" << SourceRange(D.getIdentifierLoc()); 6815 D.setInvalidType(); 6816 } 6817 6818 // C++0x [class.dtor]p2: 6819 // A destructor shall not be declared with a ref-qualifier. 6820 if (FTI.hasRefQualifier()) { 6821 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6822 << FTI.RefQualifierIsLValueRef 6823 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6824 D.setInvalidType(); 6825 } 6826 6827 // Make sure we don't have any parameters. 6828 if (FTIHasNonVoidParameters(FTI)) { 6829 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6830 6831 // Delete the parameters. 6832 FTI.freeParams(); 6833 D.setInvalidType(); 6834 } 6835 6836 // Make sure the destructor isn't variadic. 6837 if (FTI.isVariadic) { 6838 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6839 D.setInvalidType(); 6840 } 6841 6842 // Rebuild the function type "R" without any type qualifiers or 6843 // parameters (in case any of the errors above fired) and with 6844 // "void" as the return type, since destructors don't have return 6845 // types. 6846 if (!D.isInvalidType()) 6847 return R; 6848 6849 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6850 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6851 EPI.Variadic = false; 6852 EPI.TypeQuals = 0; 6853 EPI.RefQualifier = RQ_None; 6854 return Context.getFunctionType(Context.VoidTy, None, EPI); 6855 } 6856 6857 static void extendLeft(SourceRange &R, const SourceRange &Before) { 6858 if (Before.isInvalid()) 6859 return; 6860 R.setBegin(Before.getBegin()); 6861 if (R.getEnd().isInvalid()) 6862 R.setEnd(Before.getEnd()); 6863 } 6864 6865 static void extendRight(SourceRange &R, const SourceRange &After) { 6866 if (After.isInvalid()) 6867 return; 6868 if (R.getBegin().isInvalid()) 6869 R.setBegin(After.getBegin()); 6870 R.setEnd(After.getEnd()); 6871 } 6872 6873 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6874 /// well-formednes of the conversion function declarator @p D with 6875 /// type @p R. If there are any errors in the declarator, this routine 6876 /// will emit diagnostics and return true. Otherwise, it will return 6877 /// false. Either way, the type @p R will be updated to reflect a 6878 /// well-formed type for the conversion operator. 6879 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6880 StorageClass& SC) { 6881 // C++ [class.conv.fct]p1: 6882 // Neither parameter types nor return type can be specified. The 6883 // type of a conversion function (8.3.5) is "function taking no 6884 // parameter returning conversion-type-id." 6885 if (SC == SC_Static) { 6886 if (!D.isInvalidType()) 6887 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6888 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6889 << D.getName().getSourceRange(); 6890 D.setInvalidType(); 6891 SC = SC_None; 6892 } 6893 6894 TypeSourceInfo *ConvTSI = nullptr; 6895 QualType ConvType = 6896 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 6897 6898 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6899 // Conversion functions don't have return types, but the parser will 6900 // happily parse something like: 6901 // 6902 // class X { 6903 // float operator bool(); 6904 // }; 6905 // 6906 // The return type will be changed later anyway. 6907 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6908 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6909 << SourceRange(D.getIdentifierLoc()); 6910 D.setInvalidType(); 6911 } 6912 6913 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6914 6915 // Make sure we don't have any parameters. 6916 if (Proto->getNumParams() > 0) { 6917 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6918 6919 // Delete the parameters. 6920 D.getFunctionTypeInfo().freeParams(); 6921 D.setInvalidType(); 6922 } else if (Proto->isVariadic()) { 6923 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6924 D.setInvalidType(); 6925 } 6926 6927 // Diagnose "&operator bool()" and other such nonsense. This 6928 // is actually a gcc extension which we don't support. 6929 if (Proto->getReturnType() != ConvType) { 6930 bool NeedsTypedef = false; 6931 SourceRange Before, After; 6932 6933 // Walk the chunks and extract information on them for our diagnostic. 6934 bool PastFunctionChunk = false; 6935 for (auto &Chunk : D.type_objects()) { 6936 switch (Chunk.Kind) { 6937 case DeclaratorChunk::Function: 6938 if (!PastFunctionChunk) { 6939 if (Chunk.Fun.HasTrailingReturnType) { 6940 TypeSourceInfo *TRT = nullptr; 6941 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 6942 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 6943 } 6944 PastFunctionChunk = true; 6945 break; 6946 } 6947 // Fall through. 6948 case DeclaratorChunk::Array: 6949 NeedsTypedef = true; 6950 extendRight(After, Chunk.getSourceRange()); 6951 break; 6952 6953 case DeclaratorChunk::Pointer: 6954 case DeclaratorChunk::BlockPointer: 6955 case DeclaratorChunk::Reference: 6956 case DeclaratorChunk::MemberPointer: 6957 extendLeft(Before, Chunk.getSourceRange()); 6958 break; 6959 6960 case DeclaratorChunk::Paren: 6961 extendLeft(Before, Chunk.Loc); 6962 extendRight(After, Chunk.EndLoc); 6963 break; 6964 } 6965 } 6966 6967 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 6968 After.isValid() ? After.getBegin() : 6969 D.getIdentifierLoc(); 6970 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 6971 DB << Before << After; 6972 6973 if (!NeedsTypedef) { 6974 DB << /*don't need a typedef*/0; 6975 6976 // If we can provide a correct fix-it hint, do so. 6977 if (After.isInvalid() && ConvTSI) { 6978 SourceLocation InsertLoc = 6979 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 6980 DB << FixItHint::CreateInsertion(InsertLoc, " ") 6981 << FixItHint::CreateInsertionFromRange( 6982 InsertLoc, CharSourceRange::getTokenRange(Before)) 6983 << FixItHint::CreateRemoval(Before); 6984 } 6985 } else if (!Proto->getReturnType()->isDependentType()) { 6986 DB << /*typedef*/1 << Proto->getReturnType(); 6987 } else if (getLangOpts().CPlusPlus11) { 6988 DB << /*alias template*/2 << Proto->getReturnType(); 6989 } else { 6990 DB << /*might not be fixable*/3; 6991 } 6992 6993 // Recover by incorporating the other type chunks into the result type. 6994 // Note, this does *not* change the name of the function. This is compatible 6995 // with the GCC extension: 6996 // struct S { &operator int(); } s; 6997 // int &r = s.operator int(); // ok in GCC 6998 // S::operator int&() {} // error in GCC, function name is 'operator int'. 6999 ConvType = Proto->getReturnType(); 7000 } 7001 7002 // C++ [class.conv.fct]p4: 7003 // The conversion-type-id shall not represent a function type nor 7004 // an array type. 7005 if (ConvType->isArrayType()) { 7006 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 7007 ConvType = Context.getPointerType(ConvType); 7008 D.setInvalidType(); 7009 } else if (ConvType->isFunctionType()) { 7010 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 7011 ConvType = Context.getPointerType(ConvType); 7012 D.setInvalidType(); 7013 } 7014 7015 // Rebuild the function type "R" without any parameters (in case any 7016 // of the errors above fired) and with the conversion type as the 7017 // return type. 7018 if (D.isInvalidType()) 7019 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 7020 7021 // C++0x explicit conversion operators. 7022 if (D.getDeclSpec().isExplicitSpecified()) 7023 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7024 getLangOpts().CPlusPlus11 ? 7025 diag::warn_cxx98_compat_explicit_conversion_functions : 7026 diag::ext_explicit_conversion_functions) 7027 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 7028 } 7029 7030 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 7031 /// the declaration of the given C++ conversion function. This routine 7032 /// is responsible for recording the conversion function in the C++ 7033 /// class, if possible. 7034 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 7035 assert(Conversion && "Expected to receive a conversion function declaration"); 7036 7037 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 7038 7039 // Make sure we aren't redeclaring the conversion function. 7040 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 7041 7042 // C++ [class.conv.fct]p1: 7043 // [...] A conversion function is never used to convert a 7044 // (possibly cv-qualified) object to the (possibly cv-qualified) 7045 // same object type (or a reference to it), to a (possibly 7046 // cv-qualified) base class of that type (or a reference to it), 7047 // or to (possibly cv-qualified) void. 7048 // FIXME: Suppress this warning if the conversion function ends up being a 7049 // virtual function that overrides a virtual function in a base class. 7050 QualType ClassType 7051 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7052 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 7053 ConvType = ConvTypeRef->getPointeeType(); 7054 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 7055 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 7056 /* Suppress diagnostics for instantiations. */; 7057 else if (ConvType->isRecordType()) { 7058 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 7059 if (ConvType == ClassType) 7060 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 7061 << ClassType; 7062 else if (IsDerivedFrom(ClassType, ConvType)) 7063 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 7064 << ClassType << ConvType; 7065 } else if (ConvType->isVoidType()) { 7066 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 7067 << ClassType << ConvType; 7068 } 7069 7070 if (FunctionTemplateDecl *ConversionTemplate 7071 = Conversion->getDescribedFunctionTemplate()) 7072 return ConversionTemplate; 7073 7074 return Conversion; 7075 } 7076 7077 //===----------------------------------------------------------------------===// 7078 // Namespace Handling 7079 //===----------------------------------------------------------------------===// 7080 7081 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 7082 /// reopened. 7083 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 7084 SourceLocation Loc, 7085 IdentifierInfo *II, bool *IsInline, 7086 NamespaceDecl *PrevNS) { 7087 assert(*IsInline != PrevNS->isInline()); 7088 7089 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 7090 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 7091 // inline namespaces, with the intention of bringing names into namespace std. 7092 // 7093 // We support this just well enough to get that case working; this is not 7094 // sufficient to support reopening namespaces as inline in general. 7095 if (*IsInline && II && II->getName().startswith("__atomic") && 7096 S.getSourceManager().isInSystemHeader(Loc)) { 7097 // Mark all prior declarations of the namespace as inline. 7098 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 7099 NS = NS->getPreviousDecl()) 7100 NS->setInline(*IsInline); 7101 // Patch up the lookup table for the containing namespace. This isn't really 7102 // correct, but it's good enough for this particular case. 7103 for (auto *I : PrevNS->decls()) 7104 if (auto *ND = dyn_cast<NamedDecl>(I)) 7105 PrevNS->getParent()->makeDeclVisibleInContext(ND); 7106 return; 7107 } 7108 7109 if (PrevNS->isInline()) 7110 // The user probably just forgot the 'inline', so suggest that it 7111 // be added back. 7112 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 7113 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 7114 else 7115 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 7116 7117 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 7118 *IsInline = PrevNS->isInline(); 7119 } 7120 7121 /// ActOnStartNamespaceDef - This is called at the start of a namespace 7122 /// definition. 7123 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 7124 SourceLocation InlineLoc, 7125 SourceLocation NamespaceLoc, 7126 SourceLocation IdentLoc, 7127 IdentifierInfo *II, 7128 SourceLocation LBrace, 7129 AttributeList *AttrList) { 7130 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 7131 // For anonymous namespace, take the location of the left brace. 7132 SourceLocation Loc = II ? IdentLoc : LBrace; 7133 bool IsInline = InlineLoc.isValid(); 7134 bool IsInvalid = false; 7135 bool IsStd = false; 7136 bool AddToKnown = false; 7137 Scope *DeclRegionScope = NamespcScope->getParent(); 7138 7139 NamespaceDecl *PrevNS = nullptr; 7140 if (II) { 7141 // C++ [namespace.def]p2: 7142 // The identifier in an original-namespace-definition shall not 7143 // have been previously defined in the declarative region in 7144 // which the original-namespace-definition appears. The 7145 // identifier in an original-namespace-definition is the name of 7146 // the namespace. Subsequently in that declarative region, it is 7147 // treated as an original-namespace-name. 7148 // 7149 // Since namespace names are unique in their scope, and we don't 7150 // look through using directives, just look for any ordinary names. 7151 7152 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 7153 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 7154 Decl::IDNS_Namespace; 7155 NamedDecl *PrevDecl = nullptr; 7156 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 7157 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 7158 ++I) { 7159 if ((*I)->getIdentifierNamespace() & IDNS) { 7160 PrevDecl = *I; 7161 break; 7162 } 7163 } 7164 7165 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7166 7167 if (PrevNS) { 7168 // This is an extended namespace definition. 7169 if (IsInline != PrevNS->isInline()) 7170 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7171 &IsInline, PrevNS); 7172 } else if (PrevDecl) { 7173 // This is an invalid name redefinition. 7174 Diag(Loc, diag::err_redefinition_different_kind) 7175 << II; 7176 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7177 IsInvalid = true; 7178 // Continue on to push Namespc as current DeclContext and return it. 7179 } else if (II->isStr("std") && 7180 CurContext->getRedeclContext()->isTranslationUnit()) { 7181 // This is the first "real" definition of the namespace "std", so update 7182 // our cache of the "std" namespace to point at this definition. 7183 PrevNS = getStdNamespace(); 7184 IsStd = true; 7185 AddToKnown = !IsInline; 7186 } else { 7187 // We've seen this namespace for the first time. 7188 AddToKnown = !IsInline; 7189 } 7190 } else { 7191 // Anonymous namespaces. 7192 7193 // Determine whether the parent already has an anonymous namespace. 7194 DeclContext *Parent = CurContext->getRedeclContext(); 7195 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7196 PrevNS = TU->getAnonymousNamespace(); 7197 } else { 7198 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7199 PrevNS = ND->getAnonymousNamespace(); 7200 } 7201 7202 if (PrevNS && IsInline != PrevNS->isInline()) 7203 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7204 &IsInline, PrevNS); 7205 } 7206 7207 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7208 StartLoc, Loc, II, PrevNS); 7209 if (IsInvalid) 7210 Namespc->setInvalidDecl(); 7211 7212 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7213 7214 // FIXME: Should we be merging attributes? 7215 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7216 PushNamespaceVisibilityAttr(Attr, Loc); 7217 7218 if (IsStd) 7219 StdNamespace = Namespc; 7220 if (AddToKnown) 7221 KnownNamespaces[Namespc] = false; 7222 7223 if (II) { 7224 PushOnScopeChains(Namespc, DeclRegionScope); 7225 } else { 7226 // Link the anonymous namespace into its parent. 7227 DeclContext *Parent = CurContext->getRedeclContext(); 7228 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7229 TU->setAnonymousNamespace(Namespc); 7230 } else { 7231 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7232 } 7233 7234 CurContext->addDecl(Namespc); 7235 7236 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7237 // behaves as if it were replaced by 7238 // namespace unique { /* empty body */ } 7239 // using namespace unique; 7240 // namespace unique { namespace-body } 7241 // where all occurrences of 'unique' in a translation unit are 7242 // replaced by the same identifier and this identifier differs 7243 // from all other identifiers in the entire program. 7244 7245 // We just create the namespace with an empty name and then add an 7246 // implicit using declaration, just like the standard suggests. 7247 // 7248 // CodeGen enforces the "universally unique" aspect by giving all 7249 // declarations semantically contained within an anonymous 7250 // namespace internal linkage. 7251 7252 if (!PrevNS) { 7253 UsingDirectiveDecl* UD 7254 = UsingDirectiveDecl::Create(Context, Parent, 7255 /* 'using' */ LBrace, 7256 /* 'namespace' */ SourceLocation(), 7257 /* qualifier */ NestedNameSpecifierLoc(), 7258 /* identifier */ SourceLocation(), 7259 Namespc, 7260 /* Ancestor */ Parent); 7261 UD->setImplicit(); 7262 Parent->addDecl(UD); 7263 } 7264 } 7265 7266 ActOnDocumentableDecl(Namespc); 7267 7268 // Although we could have an invalid decl (i.e. the namespace name is a 7269 // redefinition), push it as current DeclContext and try to continue parsing. 7270 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7271 // for the namespace has the declarations that showed up in that particular 7272 // namespace definition. 7273 PushDeclContext(NamespcScope, Namespc); 7274 return Namespc; 7275 } 7276 7277 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7278 /// is a namespace alias, returns the namespace it points to. 7279 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7280 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7281 return AD->getNamespace(); 7282 return dyn_cast_or_null<NamespaceDecl>(D); 7283 } 7284 7285 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7286 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7287 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7288 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7289 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7290 Namespc->setRBraceLoc(RBrace); 7291 PopDeclContext(); 7292 if (Namespc->hasAttr<VisibilityAttr>()) 7293 PopPragmaVisibility(true, RBrace); 7294 } 7295 7296 CXXRecordDecl *Sema::getStdBadAlloc() const { 7297 return cast_or_null<CXXRecordDecl>( 7298 StdBadAlloc.get(Context.getExternalSource())); 7299 } 7300 7301 NamespaceDecl *Sema::getStdNamespace() const { 7302 return cast_or_null<NamespaceDecl>( 7303 StdNamespace.get(Context.getExternalSource())); 7304 } 7305 7306 /// \brief Retrieve the special "std" namespace, which may require us to 7307 /// implicitly define the namespace. 7308 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7309 if (!StdNamespace) { 7310 // The "std" namespace has not yet been defined, so build one implicitly. 7311 StdNamespace = NamespaceDecl::Create(Context, 7312 Context.getTranslationUnitDecl(), 7313 /*Inline=*/false, 7314 SourceLocation(), SourceLocation(), 7315 &PP.getIdentifierTable().get("std"), 7316 /*PrevDecl=*/nullptr); 7317 getStdNamespace()->setImplicit(true); 7318 } 7319 7320 return getStdNamespace(); 7321 } 7322 7323 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7324 assert(getLangOpts().CPlusPlus && 7325 "Looking for std::initializer_list outside of C++."); 7326 7327 // We're looking for implicit instantiations of 7328 // template <typename E> class std::initializer_list. 7329 7330 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7331 return false; 7332 7333 ClassTemplateDecl *Template = nullptr; 7334 const TemplateArgument *Arguments = nullptr; 7335 7336 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7337 7338 ClassTemplateSpecializationDecl *Specialization = 7339 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7340 if (!Specialization) 7341 return false; 7342 7343 Template = Specialization->getSpecializedTemplate(); 7344 Arguments = Specialization->getTemplateArgs().data(); 7345 } else if (const TemplateSpecializationType *TST = 7346 Ty->getAs<TemplateSpecializationType>()) { 7347 Template = dyn_cast_or_null<ClassTemplateDecl>( 7348 TST->getTemplateName().getAsTemplateDecl()); 7349 Arguments = TST->getArgs(); 7350 } 7351 if (!Template) 7352 return false; 7353 7354 if (!StdInitializerList) { 7355 // Haven't recognized std::initializer_list yet, maybe this is it. 7356 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7357 if (TemplateClass->getIdentifier() != 7358 &PP.getIdentifierTable().get("initializer_list") || 7359 !getStdNamespace()->InEnclosingNamespaceSetOf( 7360 TemplateClass->getDeclContext())) 7361 return false; 7362 // This is a template called std::initializer_list, but is it the right 7363 // template? 7364 TemplateParameterList *Params = Template->getTemplateParameters(); 7365 if (Params->getMinRequiredArguments() != 1) 7366 return false; 7367 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7368 return false; 7369 7370 // It's the right template. 7371 StdInitializerList = Template; 7372 } 7373 7374 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 7375 return false; 7376 7377 // This is an instance of std::initializer_list. Find the argument type. 7378 if (Element) 7379 *Element = Arguments[0].getAsType(); 7380 return true; 7381 } 7382 7383 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7384 NamespaceDecl *Std = S.getStdNamespace(); 7385 if (!Std) { 7386 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7387 return nullptr; 7388 } 7389 7390 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7391 Loc, Sema::LookupOrdinaryName); 7392 if (!S.LookupQualifiedName(Result, Std)) { 7393 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7394 return nullptr; 7395 } 7396 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7397 if (!Template) { 7398 Result.suppressDiagnostics(); 7399 // We found something weird. Complain about the first thing we found. 7400 NamedDecl *Found = *Result.begin(); 7401 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7402 return nullptr; 7403 } 7404 7405 // We found some template called std::initializer_list. Now verify that it's 7406 // correct. 7407 TemplateParameterList *Params = Template->getTemplateParameters(); 7408 if (Params->getMinRequiredArguments() != 1 || 7409 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7410 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7411 return nullptr; 7412 } 7413 7414 return Template; 7415 } 7416 7417 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7418 if (!StdInitializerList) { 7419 StdInitializerList = LookupStdInitializerList(*this, Loc); 7420 if (!StdInitializerList) 7421 return QualType(); 7422 } 7423 7424 TemplateArgumentListInfo Args(Loc, Loc); 7425 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7426 Context.getTrivialTypeSourceInfo(Element, 7427 Loc))); 7428 return Context.getCanonicalType( 7429 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7430 } 7431 7432 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7433 // C++ [dcl.init.list]p2: 7434 // A constructor is an initializer-list constructor if its first parameter 7435 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7436 // std::initializer_list<E> for some type E, and either there are no other 7437 // parameters or else all other parameters have default arguments. 7438 if (Ctor->getNumParams() < 1 || 7439 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7440 return false; 7441 7442 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7443 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7444 ArgType = RT->getPointeeType().getUnqualifiedType(); 7445 7446 return isStdInitializerList(ArgType, nullptr); 7447 } 7448 7449 /// \brief Determine whether a using statement is in a context where it will be 7450 /// apply in all contexts. 7451 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7452 switch (CurContext->getDeclKind()) { 7453 case Decl::TranslationUnit: 7454 return true; 7455 case Decl::LinkageSpec: 7456 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7457 default: 7458 return false; 7459 } 7460 } 7461 7462 namespace { 7463 7464 // Callback to only accept typo corrections that are namespaces. 7465 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7466 public: 7467 bool ValidateCandidate(const TypoCorrection &candidate) override { 7468 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7469 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7470 return false; 7471 } 7472 }; 7473 7474 } 7475 7476 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7477 CXXScopeSpec &SS, 7478 SourceLocation IdentLoc, 7479 IdentifierInfo *Ident) { 7480 R.clear(); 7481 if (TypoCorrection Corrected = 7482 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7483 llvm::make_unique<NamespaceValidatorCCC>(), 7484 Sema::CTK_ErrorRecovery)) { 7485 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7486 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7487 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7488 Ident->getName().equals(CorrectedStr); 7489 S.diagnoseTypo(Corrected, 7490 S.PDiag(diag::err_using_directive_member_suggest) 7491 << Ident << DC << DroppedSpecifier << SS.getRange(), 7492 S.PDiag(diag::note_namespace_defined_here)); 7493 } else { 7494 S.diagnoseTypo(Corrected, 7495 S.PDiag(diag::err_using_directive_suggest) << Ident, 7496 S.PDiag(diag::note_namespace_defined_here)); 7497 } 7498 R.addDecl(Corrected.getCorrectionDecl()); 7499 return true; 7500 } 7501 return false; 7502 } 7503 7504 Decl *Sema::ActOnUsingDirective(Scope *S, 7505 SourceLocation UsingLoc, 7506 SourceLocation NamespcLoc, 7507 CXXScopeSpec &SS, 7508 SourceLocation IdentLoc, 7509 IdentifierInfo *NamespcName, 7510 AttributeList *AttrList) { 7511 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7512 assert(NamespcName && "Invalid NamespcName."); 7513 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7514 7515 // This can only happen along a recovery path. 7516 while (S->getFlags() & Scope::TemplateParamScope) 7517 S = S->getParent(); 7518 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7519 7520 UsingDirectiveDecl *UDir = nullptr; 7521 NestedNameSpecifier *Qualifier = nullptr; 7522 if (SS.isSet()) 7523 Qualifier = SS.getScopeRep(); 7524 7525 // Lookup namespace name. 7526 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7527 LookupParsedName(R, S, &SS); 7528 if (R.isAmbiguous()) 7529 return nullptr; 7530 7531 if (R.empty()) { 7532 R.clear(); 7533 // Allow "using namespace std;" or "using namespace ::std;" even if 7534 // "std" hasn't been defined yet, for GCC compatibility. 7535 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7536 NamespcName->isStr("std")) { 7537 Diag(IdentLoc, diag::ext_using_undefined_std); 7538 R.addDecl(getOrCreateStdNamespace()); 7539 R.resolveKind(); 7540 } 7541 // Otherwise, attempt typo correction. 7542 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7543 } 7544 7545 if (!R.empty()) { 7546 NamedDecl *Named = R.getFoundDecl(); 7547 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7548 && "expected namespace decl"); 7549 7550 // The use of a nested name specifier may trigger deprecation warnings. 7551 DiagnoseUseOfDecl(Named, IdentLoc); 7552 7553 // C++ [namespace.udir]p1: 7554 // A using-directive specifies that the names in the nominated 7555 // namespace can be used in the scope in which the 7556 // using-directive appears after the using-directive. During 7557 // unqualified name lookup (3.4.1), the names appear as if they 7558 // were declared in the nearest enclosing namespace which 7559 // contains both the using-directive and the nominated 7560 // namespace. [Note: in this context, "contains" means "contains 7561 // directly or indirectly". ] 7562 7563 // Find enclosing context containing both using-directive and 7564 // nominated namespace. 7565 NamespaceDecl *NS = getNamespaceDecl(Named); 7566 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7567 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7568 CommonAncestor = CommonAncestor->getParent(); 7569 7570 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7571 SS.getWithLocInContext(Context), 7572 IdentLoc, Named, CommonAncestor); 7573 7574 if (IsUsingDirectiveInToplevelContext(CurContext) && 7575 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7576 Diag(IdentLoc, diag::warn_using_directive_in_header); 7577 } 7578 7579 PushUsingDirective(S, UDir); 7580 } else { 7581 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7582 } 7583 7584 if (UDir) 7585 ProcessDeclAttributeList(S, UDir, AttrList); 7586 7587 return UDir; 7588 } 7589 7590 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7591 // If the scope has an associated entity and the using directive is at 7592 // namespace or translation unit scope, add the UsingDirectiveDecl into 7593 // its lookup structure so qualified name lookup can find it. 7594 DeclContext *Ctx = S->getEntity(); 7595 if (Ctx && !Ctx->isFunctionOrMethod()) 7596 Ctx->addDecl(UDir); 7597 else 7598 // Otherwise, it is at block scope. The using-directives will affect lookup 7599 // only to the end of the scope. 7600 S->PushUsingDirective(UDir); 7601 } 7602 7603 7604 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7605 AccessSpecifier AS, 7606 bool HasUsingKeyword, 7607 SourceLocation UsingLoc, 7608 CXXScopeSpec &SS, 7609 UnqualifiedId &Name, 7610 AttributeList *AttrList, 7611 bool HasTypenameKeyword, 7612 SourceLocation TypenameLoc) { 7613 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7614 7615 switch (Name.getKind()) { 7616 case UnqualifiedId::IK_ImplicitSelfParam: 7617 case UnqualifiedId::IK_Identifier: 7618 case UnqualifiedId::IK_OperatorFunctionId: 7619 case UnqualifiedId::IK_LiteralOperatorId: 7620 case UnqualifiedId::IK_ConversionFunctionId: 7621 break; 7622 7623 case UnqualifiedId::IK_ConstructorName: 7624 case UnqualifiedId::IK_ConstructorTemplateId: 7625 // C++11 inheriting constructors. 7626 Diag(Name.getLocStart(), 7627 getLangOpts().CPlusPlus11 ? 7628 diag::warn_cxx98_compat_using_decl_constructor : 7629 diag::err_using_decl_constructor) 7630 << SS.getRange(); 7631 7632 if (getLangOpts().CPlusPlus11) break; 7633 7634 return nullptr; 7635 7636 case UnqualifiedId::IK_DestructorName: 7637 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7638 << SS.getRange(); 7639 return nullptr; 7640 7641 case UnqualifiedId::IK_TemplateId: 7642 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7643 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7644 return nullptr; 7645 } 7646 7647 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7648 DeclarationName TargetName = TargetNameInfo.getName(); 7649 if (!TargetName) 7650 return nullptr; 7651 7652 // Warn about access declarations. 7653 if (!HasUsingKeyword) { 7654 Diag(Name.getLocStart(), 7655 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7656 : diag::warn_access_decl_deprecated) 7657 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7658 } 7659 7660 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7661 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7662 return nullptr; 7663 7664 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7665 TargetNameInfo, AttrList, 7666 /* IsInstantiation */ false, 7667 HasTypenameKeyword, TypenameLoc); 7668 if (UD) 7669 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7670 7671 return UD; 7672 } 7673 7674 /// \brief Determine whether a using declaration considers the given 7675 /// declarations as "equivalent", e.g., if they are redeclarations of 7676 /// the same entity or are both typedefs of the same type. 7677 static bool 7678 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7679 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7680 return true; 7681 7682 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7683 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7684 return Context.hasSameType(TD1->getUnderlyingType(), 7685 TD2->getUnderlyingType()); 7686 7687 return false; 7688 } 7689 7690 7691 /// Determines whether to create a using shadow decl for a particular 7692 /// decl, given the set of decls existing prior to this using lookup. 7693 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7694 const LookupResult &Previous, 7695 UsingShadowDecl *&PrevShadow) { 7696 // Diagnose finding a decl which is not from a base class of the 7697 // current class. We do this now because there are cases where this 7698 // function will silently decide not to build a shadow decl, which 7699 // will pre-empt further diagnostics. 7700 // 7701 // We don't need to do this in C++0x because we do the check once on 7702 // the qualifier. 7703 // 7704 // FIXME: diagnose the following if we care enough: 7705 // struct A { int foo; }; 7706 // struct B : A { using A::foo; }; 7707 // template <class T> struct C : A {}; 7708 // template <class T> struct D : C<T> { using B::foo; } // <--- 7709 // This is invalid (during instantiation) in C++03 because B::foo 7710 // resolves to the using decl in B, which is not a base class of D<T>. 7711 // We can't diagnose it immediately because C<T> is an unknown 7712 // specialization. The UsingShadowDecl in D<T> then points directly 7713 // to A::foo, which will look well-formed when we instantiate. 7714 // The right solution is to not collapse the shadow-decl chain. 7715 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7716 DeclContext *OrigDC = Orig->getDeclContext(); 7717 7718 // Handle enums and anonymous structs. 7719 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7720 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7721 while (OrigRec->isAnonymousStructOrUnion()) 7722 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7723 7724 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7725 if (OrigDC == CurContext) { 7726 Diag(Using->getLocation(), 7727 diag::err_using_decl_nested_name_specifier_is_current_class) 7728 << Using->getQualifierLoc().getSourceRange(); 7729 Diag(Orig->getLocation(), diag::note_using_decl_target); 7730 return true; 7731 } 7732 7733 Diag(Using->getQualifierLoc().getBeginLoc(), 7734 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7735 << Using->getQualifier() 7736 << cast<CXXRecordDecl>(CurContext) 7737 << Using->getQualifierLoc().getSourceRange(); 7738 Diag(Orig->getLocation(), diag::note_using_decl_target); 7739 return true; 7740 } 7741 } 7742 7743 if (Previous.empty()) return false; 7744 7745 NamedDecl *Target = Orig; 7746 if (isa<UsingShadowDecl>(Target)) 7747 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7748 7749 // If the target happens to be one of the previous declarations, we 7750 // don't have a conflict. 7751 // 7752 // FIXME: but we might be increasing its access, in which case we 7753 // should redeclare it. 7754 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7755 bool FoundEquivalentDecl = false; 7756 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7757 I != E; ++I) { 7758 NamedDecl *D = (*I)->getUnderlyingDecl(); 7759 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7760 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7761 PrevShadow = Shadow; 7762 FoundEquivalentDecl = true; 7763 } 7764 7765 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7766 } 7767 7768 if (FoundEquivalentDecl) 7769 return false; 7770 7771 if (FunctionDecl *FD = Target->getAsFunction()) { 7772 NamedDecl *OldDecl = nullptr; 7773 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7774 /*IsForUsingDecl*/ true)) { 7775 case Ovl_Overload: 7776 return false; 7777 7778 case Ovl_NonFunction: 7779 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7780 break; 7781 7782 // We found a decl with the exact signature. 7783 case Ovl_Match: 7784 // If we're in a record, we want to hide the target, so we 7785 // return true (without a diagnostic) to tell the caller not to 7786 // build a shadow decl. 7787 if (CurContext->isRecord()) 7788 return true; 7789 7790 // If we're not in a record, this is an error. 7791 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7792 break; 7793 } 7794 7795 Diag(Target->getLocation(), diag::note_using_decl_target); 7796 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7797 return true; 7798 } 7799 7800 // Target is not a function. 7801 7802 if (isa<TagDecl>(Target)) { 7803 // No conflict between a tag and a non-tag. 7804 if (!Tag) return false; 7805 7806 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7807 Diag(Target->getLocation(), diag::note_using_decl_target); 7808 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7809 return true; 7810 } 7811 7812 // No conflict between a tag and a non-tag. 7813 if (!NonTag) return false; 7814 7815 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7816 Diag(Target->getLocation(), diag::note_using_decl_target); 7817 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7818 return true; 7819 } 7820 7821 /// Builds a shadow declaration corresponding to a 'using' declaration. 7822 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7823 UsingDecl *UD, 7824 NamedDecl *Orig, 7825 UsingShadowDecl *PrevDecl) { 7826 7827 // If we resolved to another shadow declaration, just coalesce them. 7828 NamedDecl *Target = Orig; 7829 if (isa<UsingShadowDecl>(Target)) { 7830 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7831 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7832 } 7833 7834 UsingShadowDecl *Shadow 7835 = UsingShadowDecl::Create(Context, CurContext, 7836 UD->getLocation(), UD, Target); 7837 UD->addShadowDecl(Shadow); 7838 7839 Shadow->setAccess(UD->getAccess()); 7840 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7841 Shadow->setInvalidDecl(); 7842 7843 Shadow->setPreviousDecl(PrevDecl); 7844 7845 if (S) 7846 PushOnScopeChains(Shadow, S); 7847 else 7848 CurContext->addDecl(Shadow); 7849 7850 7851 return Shadow; 7852 } 7853 7854 /// Hides a using shadow declaration. This is required by the current 7855 /// using-decl implementation when a resolvable using declaration in a 7856 /// class is followed by a declaration which would hide or override 7857 /// one or more of the using decl's targets; for example: 7858 /// 7859 /// struct Base { void foo(int); }; 7860 /// struct Derived : Base { 7861 /// using Base::foo; 7862 /// void foo(int); 7863 /// }; 7864 /// 7865 /// The governing language is C++03 [namespace.udecl]p12: 7866 /// 7867 /// When a using-declaration brings names from a base class into a 7868 /// derived class scope, member functions in the derived class 7869 /// override and/or hide member functions with the same name and 7870 /// parameter types in a base class (rather than conflicting). 7871 /// 7872 /// There are two ways to implement this: 7873 /// (1) optimistically create shadow decls when they're not hidden 7874 /// by existing declarations, or 7875 /// (2) don't create any shadow decls (or at least don't make them 7876 /// visible) until we've fully parsed/instantiated the class. 7877 /// The problem with (1) is that we might have to retroactively remove 7878 /// a shadow decl, which requires several O(n) operations because the 7879 /// decl structures are (very reasonably) not designed for removal. 7880 /// (2) avoids this but is very fiddly and phase-dependent. 7881 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7882 if (Shadow->getDeclName().getNameKind() == 7883 DeclarationName::CXXConversionFunctionName) 7884 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7885 7886 // Remove it from the DeclContext... 7887 Shadow->getDeclContext()->removeDecl(Shadow); 7888 7889 // ...and the scope, if applicable... 7890 if (S) { 7891 S->RemoveDecl(Shadow); 7892 IdResolver.RemoveDecl(Shadow); 7893 } 7894 7895 // ...and the using decl. 7896 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7897 7898 // TODO: complain somehow if Shadow was used. It shouldn't 7899 // be possible for this to happen, because...? 7900 } 7901 7902 /// Find the base specifier for a base class with the given type. 7903 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7904 QualType DesiredBase, 7905 bool &AnyDependentBases) { 7906 // Check whether the named type is a direct base class. 7907 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7908 for (auto &Base : Derived->bases()) { 7909 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7910 if (CanonicalDesiredBase == BaseType) 7911 return &Base; 7912 if (BaseType->isDependentType()) 7913 AnyDependentBases = true; 7914 } 7915 return nullptr; 7916 } 7917 7918 namespace { 7919 class UsingValidatorCCC : public CorrectionCandidateCallback { 7920 public: 7921 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7922 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7923 : HasTypenameKeyword(HasTypenameKeyword), 7924 IsInstantiation(IsInstantiation), OldNNS(NNS), 7925 RequireMemberOf(RequireMemberOf) {} 7926 7927 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7928 NamedDecl *ND = Candidate.getCorrectionDecl(); 7929 7930 // Keywords are not valid here. 7931 if (!ND || isa<NamespaceDecl>(ND)) 7932 return false; 7933 7934 // Completely unqualified names are invalid for a 'using' declaration. 7935 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7936 return false; 7937 7938 if (RequireMemberOf) { 7939 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7940 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7941 // No-one ever wants a using-declaration to name an injected-class-name 7942 // of a base class, unless they're declaring an inheriting constructor. 7943 ASTContext &Ctx = ND->getASTContext(); 7944 if (!Ctx.getLangOpts().CPlusPlus11) 7945 return false; 7946 QualType FoundType = Ctx.getRecordType(FoundRecord); 7947 7948 // Check that the injected-class-name is named as a member of its own 7949 // type; we don't want to suggest 'using Derived::Base;', since that 7950 // means something else. 7951 NestedNameSpecifier *Specifier = 7952 Candidate.WillReplaceSpecifier() 7953 ? Candidate.getCorrectionSpecifier() 7954 : OldNNS; 7955 if (!Specifier->getAsType() || 7956 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7957 return false; 7958 7959 // Check that this inheriting constructor declaration actually names a 7960 // direct base class of the current class. 7961 bool AnyDependentBases = false; 7962 if (!findDirectBaseWithType(RequireMemberOf, 7963 Ctx.getRecordType(FoundRecord), 7964 AnyDependentBases) && 7965 !AnyDependentBases) 7966 return false; 7967 } else { 7968 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7969 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7970 return false; 7971 7972 // FIXME: Check that the base class member is accessible? 7973 } 7974 } 7975 7976 if (isa<TypeDecl>(ND)) 7977 return HasTypenameKeyword || !IsInstantiation; 7978 7979 return !HasTypenameKeyword; 7980 } 7981 7982 private: 7983 bool HasTypenameKeyword; 7984 bool IsInstantiation; 7985 NestedNameSpecifier *OldNNS; 7986 CXXRecordDecl *RequireMemberOf; 7987 }; 7988 } // end anonymous namespace 7989 7990 /// Builds a using declaration. 7991 /// 7992 /// \param IsInstantiation - Whether this call arises from an 7993 /// instantiation of an unresolved using declaration. We treat 7994 /// the lookup differently for these declarations. 7995 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7996 SourceLocation UsingLoc, 7997 CXXScopeSpec &SS, 7998 DeclarationNameInfo NameInfo, 7999 AttributeList *AttrList, 8000 bool IsInstantiation, 8001 bool HasTypenameKeyword, 8002 SourceLocation TypenameLoc) { 8003 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8004 SourceLocation IdentLoc = NameInfo.getLoc(); 8005 assert(IdentLoc.isValid() && "Invalid TargetName location."); 8006 8007 // FIXME: We ignore attributes for now. 8008 8009 if (SS.isEmpty()) { 8010 Diag(IdentLoc, diag::err_using_requires_qualname); 8011 return nullptr; 8012 } 8013 8014 // Do the redeclaration lookup in the current scope. 8015 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 8016 ForRedeclaration); 8017 Previous.setHideTags(false); 8018 if (S) { 8019 LookupName(Previous, S); 8020 8021 // It is really dumb that we have to do this. 8022 LookupResult::Filter F = Previous.makeFilter(); 8023 while (F.hasNext()) { 8024 NamedDecl *D = F.next(); 8025 if (!isDeclInScope(D, CurContext, S)) 8026 F.erase(); 8027 // If we found a local extern declaration that's not ordinarily visible, 8028 // and this declaration is being added to a non-block scope, ignore it. 8029 // We're only checking for scope conflicts here, not also for violations 8030 // of the linkage rules. 8031 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 8032 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 8033 F.erase(); 8034 } 8035 F.done(); 8036 } else { 8037 assert(IsInstantiation && "no scope in non-instantiation"); 8038 assert(CurContext->isRecord() && "scope not record in instantiation"); 8039 LookupQualifiedName(Previous, CurContext); 8040 } 8041 8042 // Check for invalid redeclarations. 8043 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 8044 SS, IdentLoc, Previous)) 8045 return nullptr; 8046 8047 // Check for bad qualifiers. 8048 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 8049 return nullptr; 8050 8051 DeclContext *LookupContext = computeDeclContext(SS); 8052 NamedDecl *D; 8053 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 8054 if (!LookupContext) { 8055 if (HasTypenameKeyword) { 8056 // FIXME: not all declaration name kinds are legal here 8057 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 8058 UsingLoc, TypenameLoc, 8059 QualifierLoc, 8060 IdentLoc, NameInfo.getName()); 8061 } else { 8062 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 8063 QualifierLoc, NameInfo); 8064 } 8065 D->setAccess(AS); 8066 CurContext->addDecl(D); 8067 return D; 8068 } 8069 8070 auto Build = [&](bool Invalid) { 8071 UsingDecl *UD = 8072 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 8073 HasTypenameKeyword); 8074 UD->setAccess(AS); 8075 CurContext->addDecl(UD); 8076 UD->setInvalidDecl(Invalid); 8077 return UD; 8078 }; 8079 auto BuildInvalid = [&]{ return Build(true); }; 8080 auto BuildValid = [&]{ return Build(false); }; 8081 8082 if (RequireCompleteDeclContext(SS, LookupContext)) 8083 return BuildInvalid(); 8084 8085 // The normal rules do not apply to inheriting constructor declarations. 8086 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 8087 UsingDecl *UD = BuildValid(); 8088 CheckInheritingConstructorUsingDecl(UD); 8089 return UD; 8090 } 8091 8092 // Otherwise, look up the target name. 8093 8094 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8095 8096 // Unlike most lookups, we don't always want to hide tag 8097 // declarations: tag names are visible through the using declaration 8098 // even if hidden by ordinary names, *except* in a dependent context 8099 // where it's important for the sanity of two-phase lookup. 8100 if (!IsInstantiation) 8101 R.setHideTags(false); 8102 8103 // For the purposes of this lookup, we have a base object type 8104 // equal to that of the current context. 8105 if (CurContext->isRecord()) { 8106 R.setBaseObjectType( 8107 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 8108 } 8109 8110 LookupQualifiedName(R, LookupContext); 8111 8112 // Try to correct typos if possible. 8113 if (R.empty()) { 8114 if (TypoCorrection Corrected = CorrectTypo( 8115 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 8116 llvm::make_unique<UsingValidatorCCC>( 8117 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8118 dyn_cast<CXXRecordDecl>(CurContext)), 8119 CTK_ErrorRecovery)) { 8120 // We reject any correction for which ND would be NULL. 8121 NamedDecl *ND = Corrected.getCorrectionDecl(); 8122 8123 // We reject candidates where DroppedSpecifier == true, hence the 8124 // literal '0' below. 8125 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8126 << NameInfo.getName() << LookupContext << 0 8127 << SS.getRange()); 8128 8129 // If we corrected to an inheriting constructor, handle it as one. 8130 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8131 if (RD && RD->isInjectedClassName()) { 8132 // Fix up the information we'll use to build the using declaration. 8133 if (Corrected.WillReplaceSpecifier()) { 8134 NestedNameSpecifierLocBuilder Builder; 8135 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8136 QualifierLoc.getSourceRange()); 8137 QualifierLoc = Builder.getWithLocInContext(Context); 8138 } 8139 8140 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8141 Context.getCanonicalType(Context.getRecordType(RD)))); 8142 NameInfo.setNamedTypeInfo(nullptr); 8143 8144 // Build it and process it as an inheriting constructor. 8145 UsingDecl *UD = BuildValid(); 8146 CheckInheritingConstructorUsingDecl(UD); 8147 return UD; 8148 } 8149 8150 // FIXME: Pick up all the declarations if we found an overloaded function. 8151 R.setLookupName(Corrected.getCorrection()); 8152 R.addDecl(ND); 8153 } else { 8154 Diag(IdentLoc, diag::err_no_member) 8155 << NameInfo.getName() << LookupContext << SS.getRange(); 8156 return BuildInvalid(); 8157 } 8158 } 8159 8160 if (R.isAmbiguous()) 8161 return BuildInvalid(); 8162 8163 if (HasTypenameKeyword) { 8164 // If we asked for a typename and got a non-type decl, error out. 8165 if (!R.getAsSingle<TypeDecl>()) { 8166 Diag(IdentLoc, diag::err_using_typename_non_type); 8167 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8168 Diag((*I)->getUnderlyingDecl()->getLocation(), 8169 diag::note_using_decl_target); 8170 return BuildInvalid(); 8171 } 8172 } else { 8173 // If we asked for a non-typename and we got a type, error out, 8174 // but only if this is an instantiation of an unresolved using 8175 // decl. Otherwise just silently find the type name. 8176 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8177 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8178 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8179 return BuildInvalid(); 8180 } 8181 } 8182 8183 // C++0x N2914 [namespace.udecl]p6: 8184 // A using-declaration shall not name a namespace. 8185 if (R.getAsSingle<NamespaceDecl>()) { 8186 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8187 << SS.getRange(); 8188 return BuildInvalid(); 8189 } 8190 8191 UsingDecl *UD = BuildValid(); 8192 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8193 UsingShadowDecl *PrevDecl = nullptr; 8194 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8195 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8196 } 8197 8198 return UD; 8199 } 8200 8201 /// Additional checks for a using declaration referring to a constructor name. 8202 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8203 assert(!UD->hasTypename() && "expecting a constructor name"); 8204 8205 const Type *SourceType = UD->getQualifier()->getAsType(); 8206 assert(SourceType && 8207 "Using decl naming constructor doesn't have type in scope spec."); 8208 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8209 8210 // Check whether the named type is a direct base class. 8211 bool AnyDependentBases = false; 8212 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8213 AnyDependentBases); 8214 if (!Base && !AnyDependentBases) { 8215 Diag(UD->getUsingLoc(), 8216 diag::err_using_decl_constructor_not_in_direct_base) 8217 << UD->getNameInfo().getSourceRange() 8218 << QualType(SourceType, 0) << TargetClass; 8219 UD->setInvalidDecl(); 8220 return true; 8221 } 8222 8223 if (Base) 8224 Base->setInheritConstructors(); 8225 8226 return false; 8227 } 8228 8229 /// Checks that the given using declaration is not an invalid 8230 /// redeclaration. Note that this is checking only for the using decl 8231 /// itself, not for any ill-formedness among the UsingShadowDecls. 8232 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8233 bool HasTypenameKeyword, 8234 const CXXScopeSpec &SS, 8235 SourceLocation NameLoc, 8236 const LookupResult &Prev) { 8237 // C++03 [namespace.udecl]p8: 8238 // C++0x [namespace.udecl]p10: 8239 // A using-declaration is a declaration and can therefore be used 8240 // repeatedly where (and only where) multiple declarations are 8241 // allowed. 8242 // 8243 // That's in non-member contexts. 8244 if (!CurContext->getRedeclContext()->isRecord()) 8245 return false; 8246 8247 NestedNameSpecifier *Qual = SS.getScopeRep(); 8248 8249 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8250 NamedDecl *D = *I; 8251 8252 bool DTypename; 8253 NestedNameSpecifier *DQual; 8254 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8255 DTypename = UD->hasTypename(); 8256 DQual = UD->getQualifier(); 8257 } else if (UnresolvedUsingValueDecl *UD 8258 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8259 DTypename = false; 8260 DQual = UD->getQualifier(); 8261 } else if (UnresolvedUsingTypenameDecl *UD 8262 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8263 DTypename = true; 8264 DQual = UD->getQualifier(); 8265 } else continue; 8266 8267 // using decls differ if one says 'typename' and the other doesn't. 8268 // FIXME: non-dependent using decls? 8269 if (HasTypenameKeyword != DTypename) continue; 8270 8271 // using decls differ if they name different scopes (but note that 8272 // template instantiation can cause this check to trigger when it 8273 // didn't before instantiation). 8274 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8275 Context.getCanonicalNestedNameSpecifier(DQual)) 8276 continue; 8277 8278 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8279 Diag(D->getLocation(), diag::note_using_decl) << 1; 8280 return true; 8281 } 8282 8283 return false; 8284 } 8285 8286 8287 /// Checks that the given nested-name qualifier used in a using decl 8288 /// in the current context is appropriately related to the current 8289 /// scope. If an error is found, diagnoses it and returns true. 8290 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8291 const CXXScopeSpec &SS, 8292 const DeclarationNameInfo &NameInfo, 8293 SourceLocation NameLoc) { 8294 DeclContext *NamedContext = computeDeclContext(SS); 8295 8296 if (!CurContext->isRecord()) { 8297 // C++03 [namespace.udecl]p3: 8298 // C++0x [namespace.udecl]p8: 8299 // A using-declaration for a class member shall be a member-declaration. 8300 8301 // If we weren't able to compute a valid scope, it must be a 8302 // dependent class scope. 8303 if (!NamedContext || NamedContext->isRecord()) { 8304 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext); 8305 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8306 RD = nullptr; 8307 8308 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8309 << SS.getRange(); 8310 8311 // If we have a complete, non-dependent source type, try to suggest a 8312 // way to get the same effect. 8313 if (!RD) 8314 return true; 8315 8316 // Find what this using-declaration was referring to. 8317 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8318 R.setHideTags(false); 8319 R.suppressDiagnostics(); 8320 LookupQualifiedName(R, RD); 8321 8322 if (R.getAsSingle<TypeDecl>()) { 8323 if (getLangOpts().CPlusPlus11) { 8324 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8325 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8326 << 0 // alias declaration 8327 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8328 NameInfo.getName().getAsString() + 8329 " = "); 8330 } else { 8331 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8332 SourceLocation InsertLoc = 8333 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8334 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8335 << 1 // typedef declaration 8336 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8337 << FixItHint::CreateInsertion( 8338 InsertLoc, " " + NameInfo.getName().getAsString()); 8339 } 8340 } else if (R.getAsSingle<VarDecl>()) { 8341 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8342 // repeating the type of the static data member here. 8343 FixItHint FixIt; 8344 if (getLangOpts().CPlusPlus11) { 8345 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8346 FixIt = FixItHint::CreateReplacement( 8347 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8348 } 8349 8350 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8351 << 2 // reference declaration 8352 << FixIt; 8353 } 8354 return true; 8355 } 8356 8357 // Otherwise, everything is known to be fine. 8358 return false; 8359 } 8360 8361 // The current scope is a record. 8362 8363 // If the named context is dependent, we can't decide much. 8364 if (!NamedContext) { 8365 // FIXME: in C++0x, we can diagnose if we can prove that the 8366 // nested-name-specifier does not refer to a base class, which is 8367 // still possible in some cases. 8368 8369 // Otherwise we have to conservatively report that things might be 8370 // okay. 8371 return false; 8372 } 8373 8374 if (!NamedContext->isRecord()) { 8375 // Ideally this would point at the last name in the specifier, 8376 // but we don't have that level of source info. 8377 Diag(SS.getRange().getBegin(), 8378 diag::err_using_decl_nested_name_specifier_is_not_class) 8379 << SS.getScopeRep() << SS.getRange(); 8380 return true; 8381 } 8382 8383 if (!NamedContext->isDependentContext() && 8384 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8385 return true; 8386 8387 if (getLangOpts().CPlusPlus11) { 8388 // C++0x [namespace.udecl]p3: 8389 // In a using-declaration used as a member-declaration, the 8390 // nested-name-specifier shall name a base class of the class 8391 // being defined. 8392 8393 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8394 cast<CXXRecordDecl>(NamedContext))) { 8395 if (CurContext == NamedContext) { 8396 Diag(NameLoc, 8397 diag::err_using_decl_nested_name_specifier_is_current_class) 8398 << SS.getRange(); 8399 return true; 8400 } 8401 8402 Diag(SS.getRange().getBegin(), 8403 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8404 << SS.getScopeRep() 8405 << cast<CXXRecordDecl>(CurContext) 8406 << SS.getRange(); 8407 return true; 8408 } 8409 8410 return false; 8411 } 8412 8413 // C++03 [namespace.udecl]p4: 8414 // A using-declaration used as a member-declaration shall refer 8415 // to a member of a base class of the class being defined [etc.]. 8416 8417 // Salient point: SS doesn't have to name a base class as long as 8418 // lookup only finds members from base classes. Therefore we can 8419 // diagnose here only if we can prove that that can't happen, 8420 // i.e. if the class hierarchies provably don't intersect. 8421 8422 // TODO: it would be nice if "definitely valid" results were cached 8423 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8424 // need to be repeated. 8425 8426 struct UserData { 8427 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8428 8429 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8430 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8431 Data->Bases.insert(Base); 8432 return true; 8433 } 8434 8435 bool hasDependentBases(const CXXRecordDecl *Class) { 8436 return !Class->forallBases(collect, this); 8437 } 8438 8439 /// Returns true if the base is dependent or is one of the 8440 /// accumulated base classes. 8441 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8442 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8443 return !Data->Bases.count(Base); 8444 } 8445 8446 bool mightShareBases(const CXXRecordDecl *Class) { 8447 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8448 } 8449 }; 8450 8451 UserData Data; 8452 8453 // Returns false if we find a dependent base. 8454 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8455 return false; 8456 8457 // Returns false if the class has a dependent base or if it or one 8458 // of its bases is present in the base set of the current context. 8459 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8460 return false; 8461 8462 Diag(SS.getRange().getBegin(), 8463 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8464 << SS.getScopeRep() 8465 << cast<CXXRecordDecl>(CurContext) 8466 << SS.getRange(); 8467 8468 return true; 8469 } 8470 8471 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8472 AccessSpecifier AS, 8473 MultiTemplateParamsArg TemplateParamLists, 8474 SourceLocation UsingLoc, 8475 UnqualifiedId &Name, 8476 AttributeList *AttrList, 8477 TypeResult Type, 8478 Decl *DeclFromDeclSpec) { 8479 // Skip up to the relevant declaration scope. 8480 while (S->getFlags() & Scope::TemplateParamScope) 8481 S = S->getParent(); 8482 assert((S->getFlags() & Scope::DeclScope) && 8483 "got alias-declaration outside of declaration scope"); 8484 8485 if (Type.isInvalid()) 8486 return nullptr; 8487 8488 bool Invalid = false; 8489 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8490 TypeSourceInfo *TInfo = nullptr; 8491 GetTypeFromParser(Type.get(), &TInfo); 8492 8493 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8494 return nullptr; 8495 8496 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8497 UPPC_DeclarationType)) { 8498 Invalid = true; 8499 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8500 TInfo->getTypeLoc().getBeginLoc()); 8501 } 8502 8503 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8504 LookupName(Previous, S); 8505 8506 // Warn about shadowing the name of a template parameter. 8507 if (Previous.isSingleResult() && 8508 Previous.getFoundDecl()->isTemplateParameter()) { 8509 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8510 Previous.clear(); 8511 } 8512 8513 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8514 "name in alias declaration must be an identifier"); 8515 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8516 Name.StartLocation, 8517 Name.Identifier, TInfo); 8518 8519 NewTD->setAccess(AS); 8520 8521 if (Invalid) 8522 NewTD->setInvalidDecl(); 8523 8524 ProcessDeclAttributeList(S, NewTD, AttrList); 8525 8526 CheckTypedefForVariablyModifiedType(S, NewTD); 8527 Invalid |= NewTD->isInvalidDecl(); 8528 8529 bool Redeclaration = false; 8530 8531 NamedDecl *NewND; 8532 if (TemplateParamLists.size()) { 8533 TypeAliasTemplateDecl *OldDecl = nullptr; 8534 TemplateParameterList *OldTemplateParams = nullptr; 8535 8536 if (TemplateParamLists.size() != 1) { 8537 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8538 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8539 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8540 } 8541 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8542 8543 // Only consider previous declarations in the same scope. 8544 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8545 /*ExplicitInstantiationOrSpecialization*/false); 8546 if (!Previous.empty()) { 8547 Redeclaration = true; 8548 8549 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8550 if (!OldDecl && !Invalid) { 8551 Diag(UsingLoc, diag::err_redefinition_different_kind) 8552 << Name.Identifier; 8553 8554 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8555 if (OldD->getLocation().isValid()) 8556 Diag(OldD->getLocation(), diag::note_previous_definition); 8557 8558 Invalid = true; 8559 } 8560 8561 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8562 if (TemplateParameterListsAreEqual(TemplateParams, 8563 OldDecl->getTemplateParameters(), 8564 /*Complain=*/true, 8565 TPL_TemplateMatch)) 8566 OldTemplateParams = OldDecl->getTemplateParameters(); 8567 else 8568 Invalid = true; 8569 8570 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8571 if (!Invalid && 8572 !Context.hasSameType(OldTD->getUnderlyingType(), 8573 NewTD->getUnderlyingType())) { 8574 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8575 // but we can't reasonably accept it. 8576 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8577 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8578 if (OldTD->getLocation().isValid()) 8579 Diag(OldTD->getLocation(), diag::note_previous_definition); 8580 Invalid = true; 8581 } 8582 } 8583 } 8584 8585 // Merge any previous default template arguments into our parameters, 8586 // and check the parameter list. 8587 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8588 TPC_TypeAliasTemplate)) 8589 return nullptr; 8590 8591 TypeAliasTemplateDecl *NewDecl = 8592 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8593 Name.Identifier, TemplateParams, 8594 NewTD); 8595 NewTD->setDescribedAliasTemplate(NewDecl); 8596 8597 NewDecl->setAccess(AS); 8598 8599 if (Invalid) 8600 NewDecl->setInvalidDecl(); 8601 else if (OldDecl) 8602 NewDecl->setPreviousDecl(OldDecl); 8603 8604 NewND = NewDecl; 8605 } else { 8606 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 8607 setTagNameForLinkagePurposes(TD, NewTD); 8608 handleTagNumbering(TD, S); 8609 } 8610 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8611 NewND = NewTD; 8612 } 8613 8614 if (!Redeclaration) 8615 PushOnScopeChains(NewND, S); 8616 8617 ActOnDocumentableDecl(NewND); 8618 return NewND; 8619 } 8620 8621 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8622 SourceLocation AliasLoc, 8623 IdentifierInfo *Alias, CXXScopeSpec &SS, 8624 SourceLocation IdentLoc, 8625 IdentifierInfo *Ident) { 8626 8627 // Lookup the namespace name. 8628 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8629 LookupParsedName(R, S, &SS); 8630 8631 if (R.isAmbiguous()) 8632 return nullptr; 8633 8634 if (R.empty()) { 8635 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8636 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8637 return nullptr; 8638 } 8639 } 8640 assert(!R.isAmbiguous() && !R.empty()); 8641 8642 // Check if we have a previous declaration with the same name. 8643 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8644 ForRedeclaration); 8645 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8646 PrevDecl = nullptr; 8647 8648 NamedDecl *ND = R.getFoundDecl(); 8649 8650 if (PrevDecl) { 8651 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8652 // We already have an alias with the same name that points to the same 8653 // namespace; check that it matches. 8654 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8655 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8656 << Alias; 8657 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8658 << AD->getNamespace(); 8659 return nullptr; 8660 } 8661 } else { 8662 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8663 ? diag::err_redefinition 8664 : diag::err_redefinition_different_kind; 8665 Diag(AliasLoc, DiagID) << Alias; 8666 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8667 return nullptr; 8668 } 8669 } 8670 8671 // The use of a nested name specifier may trigger deprecation warnings. 8672 DiagnoseUseOfDecl(ND, IdentLoc); 8673 8674 NamespaceAliasDecl *AliasDecl = 8675 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8676 Alias, SS.getWithLocInContext(Context), 8677 IdentLoc, ND); 8678 if (PrevDecl) 8679 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8680 8681 PushOnScopeChains(AliasDecl, S); 8682 return AliasDecl; 8683 } 8684 8685 Sema::ImplicitExceptionSpecification 8686 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8687 CXXMethodDecl *MD) { 8688 CXXRecordDecl *ClassDecl = MD->getParent(); 8689 8690 // C++ [except.spec]p14: 8691 // An implicitly declared special member function (Clause 12) shall have an 8692 // exception-specification. [...] 8693 ImplicitExceptionSpecification ExceptSpec(*this); 8694 if (ClassDecl->isInvalidDecl()) 8695 return ExceptSpec; 8696 8697 // Direct base-class constructors. 8698 for (const auto &B : ClassDecl->bases()) { 8699 if (B.isVirtual()) // Handled below. 8700 continue; 8701 8702 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8703 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8704 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8705 // If this is a deleted function, add it anyway. This might be conformant 8706 // with the standard. This might not. I'm not sure. It might not matter. 8707 if (Constructor) 8708 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8709 } 8710 } 8711 8712 // Virtual base-class constructors. 8713 for (const auto &B : ClassDecl->vbases()) { 8714 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8715 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8716 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8717 // If this is a deleted function, add it anyway. This might be conformant 8718 // with the standard. This might not. I'm not sure. It might not matter. 8719 if (Constructor) 8720 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8721 } 8722 } 8723 8724 // Field constructors. 8725 for (const auto *F : ClassDecl->fields()) { 8726 if (F->hasInClassInitializer()) { 8727 if (Expr *E = F->getInClassInitializer()) 8728 ExceptSpec.CalledExpr(E); 8729 } else if (const RecordType *RecordTy 8730 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8731 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8732 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8733 // If this is a deleted function, add it anyway. This might be conformant 8734 // with the standard. This might not. I'm not sure. It might not matter. 8735 // In particular, the problem is that this function never gets called. It 8736 // might just be ill-formed because this function attempts to refer to 8737 // a deleted function here. 8738 if (Constructor) 8739 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8740 } 8741 } 8742 8743 return ExceptSpec; 8744 } 8745 8746 Sema::ImplicitExceptionSpecification 8747 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8748 CXXRecordDecl *ClassDecl = CD->getParent(); 8749 8750 // C++ [except.spec]p14: 8751 // An inheriting constructor [...] shall have an exception-specification. [...] 8752 ImplicitExceptionSpecification ExceptSpec(*this); 8753 if (ClassDecl->isInvalidDecl()) 8754 return ExceptSpec; 8755 8756 // Inherited constructor. 8757 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8758 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8759 // FIXME: Copying or moving the parameters could add extra exceptions to the 8760 // set, as could the default arguments for the inherited constructor. This 8761 // will be addressed when we implement the resolution of core issue 1351. 8762 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8763 8764 // Direct base-class constructors. 8765 for (const auto &B : ClassDecl->bases()) { 8766 if (B.isVirtual()) // Handled below. 8767 continue; 8768 8769 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8770 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8771 if (BaseClassDecl == InheritedDecl) 8772 continue; 8773 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8774 if (Constructor) 8775 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8776 } 8777 } 8778 8779 // Virtual base-class constructors. 8780 for (const auto &B : ClassDecl->vbases()) { 8781 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8782 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8783 if (BaseClassDecl == InheritedDecl) 8784 continue; 8785 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8786 if (Constructor) 8787 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8788 } 8789 } 8790 8791 // Field constructors. 8792 for (const auto *F : ClassDecl->fields()) { 8793 if (F->hasInClassInitializer()) { 8794 if (Expr *E = F->getInClassInitializer()) 8795 ExceptSpec.CalledExpr(E); 8796 } else if (const RecordType *RecordTy 8797 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8798 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8799 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8800 if (Constructor) 8801 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8802 } 8803 } 8804 8805 return ExceptSpec; 8806 } 8807 8808 namespace { 8809 /// RAII object to register a special member as being currently declared. 8810 struct DeclaringSpecialMember { 8811 Sema &S; 8812 Sema::SpecialMemberDecl D; 8813 bool WasAlreadyBeingDeclared; 8814 8815 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8816 : S(S), D(RD, CSM) { 8817 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8818 if (WasAlreadyBeingDeclared) 8819 // This almost never happens, but if it does, ensure that our cache 8820 // doesn't contain a stale result. 8821 S.SpecialMemberCache.clear(); 8822 8823 // FIXME: Register a note to be produced if we encounter an error while 8824 // declaring the special member. 8825 } 8826 ~DeclaringSpecialMember() { 8827 if (!WasAlreadyBeingDeclared) 8828 S.SpecialMembersBeingDeclared.erase(D); 8829 } 8830 8831 /// \brief Are we already trying to declare this special member? 8832 bool isAlreadyBeingDeclared() const { 8833 return WasAlreadyBeingDeclared; 8834 } 8835 }; 8836 } 8837 8838 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8839 CXXRecordDecl *ClassDecl) { 8840 // C++ [class.ctor]p5: 8841 // A default constructor for a class X is a constructor of class X 8842 // that can be called without an argument. If there is no 8843 // user-declared constructor for class X, a default constructor is 8844 // implicitly declared. An implicitly-declared default constructor 8845 // is an inline public member of its class. 8846 assert(ClassDecl->needsImplicitDefaultConstructor() && 8847 "Should not build implicit default constructor!"); 8848 8849 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8850 if (DSM.isAlreadyBeingDeclared()) 8851 return nullptr; 8852 8853 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8854 CXXDefaultConstructor, 8855 false); 8856 8857 // Create the actual constructor declaration. 8858 CanQualType ClassType 8859 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8860 SourceLocation ClassLoc = ClassDecl->getLocation(); 8861 DeclarationName Name 8862 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8863 DeclarationNameInfo NameInfo(Name, ClassLoc); 8864 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8865 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8866 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8867 /*isImplicitlyDeclared=*/true, Constexpr); 8868 DefaultCon->setAccess(AS_public); 8869 DefaultCon->setDefaulted(); 8870 8871 if (getLangOpts().CUDA) { 8872 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8873 DefaultCon, 8874 /* ConstRHS */ false, 8875 /* Diagnose */ false); 8876 } 8877 8878 // Build an exception specification pointing back at this constructor. 8879 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8880 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8881 8882 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8883 // constructors is easy to compute. 8884 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8885 8886 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8887 SetDeclDeleted(DefaultCon, ClassLoc); 8888 8889 // Note that we have declared this constructor. 8890 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8891 8892 if (Scope *S = getScopeForContext(ClassDecl)) 8893 PushOnScopeChains(DefaultCon, S, false); 8894 ClassDecl->addDecl(DefaultCon); 8895 8896 return DefaultCon; 8897 } 8898 8899 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8900 CXXConstructorDecl *Constructor) { 8901 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8902 !Constructor->doesThisDeclarationHaveABody() && 8903 !Constructor->isDeleted()) && 8904 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8905 8906 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8907 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8908 8909 SynthesizedFunctionScope Scope(*this, Constructor); 8910 DiagnosticErrorTrap Trap(Diags); 8911 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8912 Trap.hasErrorOccurred()) { 8913 Diag(CurrentLocation, diag::note_member_synthesized_at) 8914 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8915 Constructor->setInvalidDecl(); 8916 return; 8917 } 8918 8919 // The exception specification is needed because we are defining the 8920 // function. 8921 ResolveExceptionSpec(CurrentLocation, 8922 Constructor->getType()->castAs<FunctionProtoType>()); 8923 8924 SourceLocation Loc = Constructor->getLocEnd().isValid() 8925 ? Constructor->getLocEnd() 8926 : Constructor->getLocation(); 8927 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8928 8929 Constructor->markUsed(Context); 8930 MarkVTableUsed(CurrentLocation, ClassDecl); 8931 8932 if (ASTMutationListener *L = getASTMutationListener()) { 8933 L->CompletedImplicitDefinition(Constructor); 8934 } 8935 8936 DiagnoseUninitializedFields(*this, Constructor); 8937 } 8938 8939 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8940 // Perform any delayed checks on exception specifications. 8941 CheckDelayedMemberExceptionSpecs(); 8942 } 8943 8944 namespace { 8945 /// Information on inheriting constructors to declare. 8946 class InheritingConstructorInfo { 8947 public: 8948 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8949 : SemaRef(SemaRef), Derived(Derived) { 8950 // Mark the constructors that we already have in the derived class. 8951 // 8952 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8953 // unless there is a user-declared constructor with the same signature in 8954 // the class where the using-declaration appears. 8955 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8956 } 8957 8958 void inheritAll(CXXRecordDecl *RD) { 8959 visitAll(RD, &InheritingConstructorInfo::inherit); 8960 } 8961 8962 private: 8963 /// Information about an inheriting constructor. 8964 struct InheritingConstructor { 8965 InheritingConstructor() 8966 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8967 8968 /// If \c true, a constructor with this signature is already declared 8969 /// in the derived class. 8970 bool DeclaredInDerived; 8971 8972 /// The constructor which is inherited. 8973 const CXXConstructorDecl *BaseCtor; 8974 8975 /// The derived constructor we declared. 8976 CXXConstructorDecl *DerivedCtor; 8977 }; 8978 8979 /// Inheriting constructors with a given canonical type. There can be at 8980 /// most one such non-template constructor, and any number of templated 8981 /// constructors. 8982 struct InheritingConstructorsForType { 8983 InheritingConstructor NonTemplate; 8984 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8985 Templates; 8986 8987 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8988 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8989 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8990 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8991 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8992 false, S.TPL_TemplateMatch)) 8993 return Templates[I].second; 8994 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8995 return Templates.back().second; 8996 } 8997 8998 return NonTemplate; 8999 } 9000 }; 9001 9002 /// Get or create the inheriting constructor record for a constructor. 9003 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 9004 QualType CtorType) { 9005 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 9006 .getEntry(SemaRef, Ctor); 9007 } 9008 9009 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 9010 9011 /// Process all constructors for a class. 9012 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 9013 for (const auto *Ctor : RD->ctors()) 9014 (this->*Callback)(Ctor); 9015 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9016 I(RD->decls_begin()), E(RD->decls_end()); 9017 I != E; ++I) { 9018 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 9019 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 9020 (this->*Callback)(CD); 9021 } 9022 } 9023 9024 /// Note that a constructor (or constructor template) was declared in Derived. 9025 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 9026 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 9027 } 9028 9029 /// Inherit a single constructor. 9030 void inherit(const CXXConstructorDecl *Ctor) { 9031 const FunctionProtoType *CtorType = 9032 Ctor->getType()->castAs<FunctionProtoType>(); 9033 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 9034 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 9035 9036 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 9037 9038 // Core issue (no number yet): the ellipsis is always discarded. 9039 if (EPI.Variadic) { 9040 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 9041 SemaRef.Diag(Ctor->getLocation(), 9042 diag::note_using_decl_constructor_ellipsis); 9043 EPI.Variadic = false; 9044 } 9045 9046 // Declare a constructor for each number of parameters. 9047 // 9048 // C++11 [class.inhctor]p1: 9049 // The candidate set of inherited constructors from the class X named in 9050 // the using-declaration consists of [... modulo defects ...] for each 9051 // constructor or constructor template of X, the set of constructors or 9052 // constructor templates that results from omitting any ellipsis parameter 9053 // specification and successively omitting parameters with a default 9054 // argument from the end of the parameter-type-list 9055 unsigned MinParams = minParamsToInherit(Ctor); 9056 unsigned Params = Ctor->getNumParams(); 9057 if (Params >= MinParams) { 9058 do 9059 declareCtor(UsingLoc, Ctor, 9060 SemaRef.Context.getFunctionType( 9061 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 9062 while (Params > MinParams && 9063 Ctor->getParamDecl(--Params)->hasDefaultArg()); 9064 } 9065 } 9066 9067 /// Find the using-declaration which specified that we should inherit the 9068 /// constructors of \p Base. 9069 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 9070 // No fancy lookup required; just look for the base constructor name 9071 // directly within the derived class. 9072 ASTContext &Context = SemaRef.Context; 9073 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9074 Context.getCanonicalType(Context.getRecordType(Base))); 9075 DeclContext::lookup_result Decls = Derived->lookup(Name); 9076 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 9077 } 9078 9079 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 9080 // C++11 [class.inhctor]p3: 9081 // [F]or each constructor template in the candidate set of inherited 9082 // constructors, a constructor template is implicitly declared 9083 if (Ctor->getDescribedFunctionTemplate()) 9084 return 0; 9085 9086 // For each non-template constructor in the candidate set of inherited 9087 // constructors other than a constructor having no parameters or a 9088 // copy/move constructor having a single parameter, a constructor is 9089 // implicitly declared [...] 9090 if (Ctor->getNumParams() == 0) 9091 return 1; 9092 if (Ctor->isCopyOrMoveConstructor()) 9093 return 2; 9094 9095 // Per discussion on core reflector, never inherit a constructor which 9096 // would become a default, copy, or move constructor of Derived either. 9097 const ParmVarDecl *PD = Ctor->getParamDecl(0); 9098 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 9099 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 9100 } 9101 9102 /// Declare a single inheriting constructor, inheriting the specified 9103 /// constructor, with the given type. 9104 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 9105 QualType DerivedType) { 9106 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 9107 9108 // C++11 [class.inhctor]p3: 9109 // ... a constructor is implicitly declared with the same constructor 9110 // characteristics unless there is a user-declared constructor with 9111 // the same signature in the class where the using-declaration appears 9112 if (Entry.DeclaredInDerived) 9113 return; 9114 9115 // C++11 [class.inhctor]p7: 9116 // If two using-declarations declare inheriting constructors with the 9117 // same signature, the program is ill-formed 9118 if (Entry.DerivedCtor) { 9119 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 9120 // Only diagnose this once per constructor. 9121 if (Entry.DerivedCtor->isInvalidDecl()) 9122 return; 9123 Entry.DerivedCtor->setInvalidDecl(); 9124 9125 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9126 SemaRef.Diag(BaseCtor->getLocation(), 9127 diag::note_using_decl_constructor_conflict_current_ctor); 9128 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9129 diag::note_using_decl_constructor_conflict_previous_ctor); 9130 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9131 diag::note_using_decl_constructor_conflict_previous_using); 9132 } else { 9133 // Core issue (no number): if the same inheriting constructor is 9134 // produced by multiple base class constructors from the same base 9135 // class, the inheriting constructor is defined as deleted. 9136 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9137 } 9138 9139 return; 9140 } 9141 9142 ASTContext &Context = SemaRef.Context; 9143 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9144 Context.getCanonicalType(Context.getRecordType(Derived))); 9145 DeclarationNameInfo NameInfo(Name, UsingLoc); 9146 9147 TemplateParameterList *TemplateParams = nullptr; 9148 if (const FunctionTemplateDecl *FTD = 9149 BaseCtor->getDescribedFunctionTemplate()) { 9150 TemplateParams = FTD->getTemplateParameters(); 9151 // We're reusing template parameters from a different DeclContext. This 9152 // is questionable at best, but works out because the template depth in 9153 // both places is guaranteed to be 0. 9154 // FIXME: Rebuild the template parameters in the new context, and 9155 // transform the function type to refer to them. 9156 } 9157 9158 // Build type source info pointing at the using-declaration. This is 9159 // required by template instantiation. 9160 TypeSourceInfo *TInfo = 9161 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9162 FunctionProtoTypeLoc ProtoLoc = 9163 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9164 9165 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9166 Context, Derived, UsingLoc, NameInfo, DerivedType, 9167 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9168 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9169 9170 // Build an unevaluated exception specification for this constructor. 9171 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9172 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9173 EPI.ExceptionSpec.Type = EST_Unevaluated; 9174 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9175 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9176 FPT->getParamTypes(), EPI)); 9177 9178 // Build the parameter declarations. 9179 SmallVector<ParmVarDecl *, 16> ParamDecls; 9180 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9181 TypeSourceInfo *TInfo = 9182 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9183 ParmVarDecl *PD = ParmVarDecl::Create( 9184 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9185 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9186 PD->setScopeInfo(0, I); 9187 PD->setImplicit(); 9188 ParamDecls.push_back(PD); 9189 ProtoLoc.setParam(I, PD); 9190 } 9191 9192 // Set up the new constructor. 9193 DerivedCtor->setAccess(BaseCtor->getAccess()); 9194 DerivedCtor->setParams(ParamDecls); 9195 DerivedCtor->setInheritedConstructor(BaseCtor); 9196 if (BaseCtor->isDeleted()) 9197 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9198 9199 // If this is a constructor template, build the template declaration. 9200 if (TemplateParams) { 9201 FunctionTemplateDecl *DerivedTemplate = 9202 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9203 TemplateParams, DerivedCtor); 9204 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9205 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9206 Derived->addDecl(DerivedTemplate); 9207 } else { 9208 Derived->addDecl(DerivedCtor); 9209 } 9210 9211 Entry.BaseCtor = BaseCtor; 9212 Entry.DerivedCtor = DerivedCtor; 9213 } 9214 9215 Sema &SemaRef; 9216 CXXRecordDecl *Derived; 9217 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9218 MapType Map; 9219 }; 9220 } 9221 9222 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9223 // Defer declaring the inheriting constructors until the class is 9224 // instantiated. 9225 if (ClassDecl->isDependentContext()) 9226 return; 9227 9228 // Find base classes from which we might inherit constructors. 9229 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9230 for (const auto &BaseIt : ClassDecl->bases()) 9231 if (BaseIt.getInheritConstructors()) 9232 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9233 9234 // Go no further if we're not inheriting any constructors. 9235 if (InheritedBases.empty()) 9236 return; 9237 9238 // Declare the inherited constructors. 9239 InheritingConstructorInfo ICI(*this, ClassDecl); 9240 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9241 ICI.inheritAll(InheritedBases[I]); 9242 } 9243 9244 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9245 CXXConstructorDecl *Constructor) { 9246 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9247 assert(Constructor->getInheritedConstructor() && 9248 !Constructor->doesThisDeclarationHaveABody() && 9249 !Constructor->isDeleted()); 9250 9251 SynthesizedFunctionScope Scope(*this, Constructor); 9252 DiagnosticErrorTrap Trap(Diags); 9253 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9254 Trap.hasErrorOccurred()) { 9255 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9256 << Context.getTagDeclType(ClassDecl); 9257 Constructor->setInvalidDecl(); 9258 return; 9259 } 9260 9261 SourceLocation Loc = Constructor->getLocation(); 9262 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9263 9264 Constructor->markUsed(Context); 9265 MarkVTableUsed(CurrentLocation, ClassDecl); 9266 9267 if (ASTMutationListener *L = getASTMutationListener()) { 9268 L->CompletedImplicitDefinition(Constructor); 9269 } 9270 } 9271 9272 9273 Sema::ImplicitExceptionSpecification 9274 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9275 CXXRecordDecl *ClassDecl = MD->getParent(); 9276 9277 // C++ [except.spec]p14: 9278 // An implicitly declared special member function (Clause 12) shall have 9279 // an exception-specification. 9280 ImplicitExceptionSpecification ExceptSpec(*this); 9281 if (ClassDecl->isInvalidDecl()) 9282 return ExceptSpec; 9283 9284 // Direct base-class destructors. 9285 for (const auto &B : ClassDecl->bases()) { 9286 if (B.isVirtual()) // Handled below. 9287 continue; 9288 9289 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9290 ExceptSpec.CalledDecl(B.getLocStart(), 9291 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9292 } 9293 9294 // Virtual base-class destructors. 9295 for (const auto &B : ClassDecl->vbases()) { 9296 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9297 ExceptSpec.CalledDecl(B.getLocStart(), 9298 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9299 } 9300 9301 // Field destructors. 9302 for (const auto *F : ClassDecl->fields()) { 9303 if (const RecordType *RecordTy 9304 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9305 ExceptSpec.CalledDecl(F->getLocation(), 9306 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9307 } 9308 9309 return ExceptSpec; 9310 } 9311 9312 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9313 // C++ [class.dtor]p2: 9314 // If a class has no user-declared destructor, a destructor is 9315 // declared implicitly. An implicitly-declared destructor is an 9316 // inline public member of its class. 9317 assert(ClassDecl->needsImplicitDestructor()); 9318 9319 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9320 if (DSM.isAlreadyBeingDeclared()) 9321 return nullptr; 9322 9323 // Create the actual destructor declaration. 9324 CanQualType ClassType 9325 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9326 SourceLocation ClassLoc = ClassDecl->getLocation(); 9327 DeclarationName Name 9328 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9329 DeclarationNameInfo NameInfo(Name, ClassLoc); 9330 CXXDestructorDecl *Destructor 9331 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9332 QualType(), nullptr, /*isInline=*/true, 9333 /*isImplicitlyDeclared=*/true); 9334 Destructor->setAccess(AS_public); 9335 Destructor->setDefaulted(); 9336 9337 if (getLangOpts().CUDA) { 9338 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9339 Destructor, 9340 /* ConstRHS */ false, 9341 /* Diagnose */ false); 9342 } 9343 9344 // Build an exception specification pointing back at this destructor. 9345 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9346 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9347 9348 AddOverriddenMethods(ClassDecl, Destructor); 9349 9350 // We don't need to use SpecialMemberIsTrivial here; triviality for 9351 // destructors is easy to compute. 9352 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9353 9354 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9355 SetDeclDeleted(Destructor, ClassLoc); 9356 9357 // Note that we have declared this destructor. 9358 ++ASTContext::NumImplicitDestructorsDeclared; 9359 9360 // Introduce this destructor into its scope. 9361 if (Scope *S = getScopeForContext(ClassDecl)) 9362 PushOnScopeChains(Destructor, S, false); 9363 ClassDecl->addDecl(Destructor); 9364 9365 return Destructor; 9366 } 9367 9368 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9369 CXXDestructorDecl *Destructor) { 9370 assert((Destructor->isDefaulted() && 9371 !Destructor->doesThisDeclarationHaveABody() && 9372 !Destructor->isDeleted()) && 9373 "DefineImplicitDestructor - call it for implicit default dtor"); 9374 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9375 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9376 9377 if (Destructor->isInvalidDecl()) 9378 return; 9379 9380 SynthesizedFunctionScope Scope(*this, Destructor); 9381 9382 DiagnosticErrorTrap Trap(Diags); 9383 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9384 Destructor->getParent()); 9385 9386 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9387 Diag(CurrentLocation, diag::note_member_synthesized_at) 9388 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9389 9390 Destructor->setInvalidDecl(); 9391 return; 9392 } 9393 9394 // The exception specification is needed because we are defining the 9395 // function. 9396 ResolveExceptionSpec(CurrentLocation, 9397 Destructor->getType()->castAs<FunctionProtoType>()); 9398 9399 SourceLocation Loc = Destructor->getLocEnd().isValid() 9400 ? Destructor->getLocEnd() 9401 : Destructor->getLocation(); 9402 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9403 Destructor->markUsed(Context); 9404 MarkVTableUsed(CurrentLocation, ClassDecl); 9405 9406 if (ASTMutationListener *L = getASTMutationListener()) { 9407 L->CompletedImplicitDefinition(Destructor); 9408 } 9409 } 9410 9411 /// \brief Perform any semantic analysis which needs to be delayed until all 9412 /// pending class member declarations have been parsed. 9413 void Sema::ActOnFinishCXXMemberDecls() { 9414 // If the context is an invalid C++ class, just suppress these checks. 9415 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9416 if (Record->isInvalidDecl()) { 9417 DelayedDefaultedMemberExceptionSpecs.clear(); 9418 DelayedExceptionSpecChecks.clear(); 9419 return; 9420 } 9421 } 9422 } 9423 9424 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9425 CXXDestructorDecl *Destructor) { 9426 assert(getLangOpts().CPlusPlus11 && 9427 "adjusting dtor exception specs was introduced in c++11"); 9428 9429 // C++11 [class.dtor]p3: 9430 // A declaration of a destructor that does not have an exception- 9431 // specification is implicitly considered to have the same exception- 9432 // specification as an implicit declaration. 9433 const FunctionProtoType *DtorType = Destructor->getType()-> 9434 getAs<FunctionProtoType>(); 9435 if (DtorType->hasExceptionSpec()) 9436 return; 9437 9438 // Replace the destructor's type, building off the existing one. Fortunately, 9439 // the only thing of interest in the destructor type is its extended info. 9440 // The return and arguments are fixed. 9441 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9442 EPI.ExceptionSpec.Type = EST_Unevaluated; 9443 EPI.ExceptionSpec.SourceDecl = Destructor; 9444 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9445 9446 // FIXME: If the destructor has a body that could throw, and the newly created 9447 // spec doesn't allow exceptions, we should emit a warning, because this 9448 // change in behavior can break conforming C++03 programs at runtime. 9449 // However, we don't have a body or an exception specification yet, so it 9450 // needs to be done somewhere else. 9451 } 9452 9453 namespace { 9454 /// \brief An abstract base class for all helper classes used in building the 9455 // copy/move operators. These classes serve as factory functions and help us 9456 // avoid using the same Expr* in the AST twice. 9457 class ExprBuilder { 9458 ExprBuilder(const ExprBuilder&) = delete; 9459 ExprBuilder &operator=(const ExprBuilder&) = delete; 9460 9461 protected: 9462 static Expr *assertNotNull(Expr *E) { 9463 assert(E && "Expression construction must not fail."); 9464 return E; 9465 } 9466 9467 public: 9468 ExprBuilder() {} 9469 virtual ~ExprBuilder() {} 9470 9471 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9472 }; 9473 9474 class RefBuilder: public ExprBuilder { 9475 VarDecl *Var; 9476 QualType VarType; 9477 9478 public: 9479 Expr *build(Sema &S, SourceLocation Loc) const override { 9480 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9481 } 9482 9483 RefBuilder(VarDecl *Var, QualType VarType) 9484 : Var(Var), VarType(VarType) {} 9485 }; 9486 9487 class ThisBuilder: public ExprBuilder { 9488 public: 9489 Expr *build(Sema &S, SourceLocation Loc) const override { 9490 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9491 } 9492 }; 9493 9494 class CastBuilder: public ExprBuilder { 9495 const ExprBuilder &Builder; 9496 QualType Type; 9497 ExprValueKind Kind; 9498 const CXXCastPath &Path; 9499 9500 public: 9501 Expr *build(Sema &S, SourceLocation Loc) const override { 9502 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9503 CK_UncheckedDerivedToBase, Kind, 9504 &Path).get()); 9505 } 9506 9507 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9508 const CXXCastPath &Path) 9509 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9510 }; 9511 9512 class DerefBuilder: public ExprBuilder { 9513 const ExprBuilder &Builder; 9514 9515 public: 9516 Expr *build(Sema &S, SourceLocation Loc) const override { 9517 return assertNotNull( 9518 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9519 } 9520 9521 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9522 }; 9523 9524 class MemberBuilder: public ExprBuilder { 9525 const ExprBuilder &Builder; 9526 QualType Type; 9527 CXXScopeSpec SS; 9528 bool IsArrow; 9529 LookupResult &MemberLookup; 9530 9531 public: 9532 Expr *build(Sema &S, SourceLocation Loc) const override { 9533 return assertNotNull(S.BuildMemberReferenceExpr( 9534 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9535 nullptr, MemberLookup, nullptr).get()); 9536 } 9537 9538 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9539 LookupResult &MemberLookup) 9540 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9541 MemberLookup(MemberLookup) {} 9542 }; 9543 9544 class MoveCastBuilder: public ExprBuilder { 9545 const ExprBuilder &Builder; 9546 9547 public: 9548 Expr *build(Sema &S, SourceLocation Loc) const override { 9549 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9550 } 9551 9552 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9553 }; 9554 9555 class LvalueConvBuilder: public ExprBuilder { 9556 const ExprBuilder &Builder; 9557 9558 public: 9559 Expr *build(Sema &S, SourceLocation Loc) const override { 9560 return assertNotNull( 9561 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9562 } 9563 9564 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9565 }; 9566 9567 class SubscriptBuilder: public ExprBuilder { 9568 const ExprBuilder &Base; 9569 const ExprBuilder &Index; 9570 9571 public: 9572 Expr *build(Sema &S, SourceLocation Loc) const override { 9573 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9574 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9575 } 9576 9577 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9578 : Base(Base), Index(Index) {} 9579 }; 9580 9581 } // end anonymous namespace 9582 9583 /// When generating a defaulted copy or move assignment operator, if a field 9584 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9585 /// do so. This optimization only applies for arrays of scalars, and for arrays 9586 /// of class type where the selected copy/move-assignment operator is trivial. 9587 static StmtResult 9588 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9589 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9590 // Compute the size of the memory buffer to be copied. 9591 QualType SizeType = S.Context.getSizeType(); 9592 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9593 S.Context.getTypeSizeInChars(T).getQuantity()); 9594 9595 // Take the address of the field references for "from" and "to". We 9596 // directly construct UnaryOperators here because semantic analysis 9597 // does not permit us to take the address of an xvalue. 9598 Expr *From = FromB.build(S, Loc); 9599 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9600 S.Context.getPointerType(From->getType()), 9601 VK_RValue, OK_Ordinary, Loc); 9602 Expr *To = ToB.build(S, Loc); 9603 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9604 S.Context.getPointerType(To->getType()), 9605 VK_RValue, OK_Ordinary, Loc); 9606 9607 const Type *E = T->getBaseElementTypeUnsafe(); 9608 bool NeedsCollectableMemCpy = 9609 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9610 9611 // Create a reference to the __builtin_objc_memmove_collectable function 9612 StringRef MemCpyName = NeedsCollectableMemCpy ? 9613 "__builtin_objc_memmove_collectable" : 9614 "__builtin_memcpy"; 9615 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9616 Sema::LookupOrdinaryName); 9617 S.LookupName(R, S.TUScope, true); 9618 9619 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9620 if (!MemCpy) 9621 // Something went horribly wrong earlier, and we will have complained 9622 // about it. 9623 return StmtError(); 9624 9625 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9626 VK_RValue, Loc, nullptr); 9627 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9628 9629 Expr *CallArgs[] = { 9630 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9631 }; 9632 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9633 Loc, CallArgs, Loc); 9634 9635 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9636 return Call.getAs<Stmt>(); 9637 } 9638 9639 /// \brief Builds a statement that copies/moves the given entity from \p From to 9640 /// \c To. 9641 /// 9642 /// This routine is used to copy/move the members of a class with an 9643 /// implicitly-declared copy/move assignment operator. When the entities being 9644 /// copied are arrays, this routine builds for loops to copy them. 9645 /// 9646 /// \param S The Sema object used for type-checking. 9647 /// 9648 /// \param Loc The location where the implicit copy/move is being generated. 9649 /// 9650 /// \param T The type of the expressions being copied/moved. Both expressions 9651 /// must have this type. 9652 /// 9653 /// \param To The expression we are copying/moving to. 9654 /// 9655 /// \param From The expression we are copying/moving from. 9656 /// 9657 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9658 /// Otherwise, it's a non-static member subobject. 9659 /// 9660 /// \param Copying Whether we're copying or moving. 9661 /// 9662 /// \param Depth Internal parameter recording the depth of the recursion. 9663 /// 9664 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9665 /// if a memcpy should be used instead. 9666 static StmtResult 9667 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9668 const ExprBuilder &To, const ExprBuilder &From, 9669 bool CopyingBaseSubobject, bool Copying, 9670 unsigned Depth = 0) { 9671 // C++11 [class.copy]p28: 9672 // Each subobject is assigned in the manner appropriate to its type: 9673 // 9674 // - if the subobject is of class type, as if by a call to operator= with 9675 // the subobject as the object expression and the corresponding 9676 // subobject of x as a single function argument (as if by explicit 9677 // qualification; that is, ignoring any possible virtual overriding 9678 // functions in more derived classes); 9679 // 9680 // C++03 [class.copy]p13: 9681 // - if the subobject is of class type, the copy assignment operator for 9682 // the class is used (as if by explicit qualification; that is, 9683 // ignoring any possible virtual overriding functions in more derived 9684 // classes); 9685 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9686 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9687 9688 // Look for operator=. 9689 DeclarationName Name 9690 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9691 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9692 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9693 9694 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9695 // operator. 9696 if (!S.getLangOpts().CPlusPlus11) { 9697 LookupResult::Filter F = OpLookup.makeFilter(); 9698 while (F.hasNext()) { 9699 NamedDecl *D = F.next(); 9700 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9701 if (Method->isCopyAssignmentOperator() || 9702 (!Copying && Method->isMoveAssignmentOperator())) 9703 continue; 9704 9705 F.erase(); 9706 } 9707 F.done(); 9708 } 9709 9710 // Suppress the protected check (C++ [class.protected]) for each of the 9711 // assignment operators we found. This strange dance is required when 9712 // we're assigning via a base classes's copy-assignment operator. To 9713 // ensure that we're getting the right base class subobject (without 9714 // ambiguities), we need to cast "this" to that subobject type; to 9715 // ensure that we don't go through the virtual call mechanism, we need 9716 // to qualify the operator= name with the base class (see below). However, 9717 // this means that if the base class has a protected copy assignment 9718 // operator, the protected member access check will fail. So, we 9719 // rewrite "protected" access to "public" access in this case, since we 9720 // know by construction that we're calling from a derived class. 9721 if (CopyingBaseSubobject) { 9722 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9723 L != LEnd; ++L) { 9724 if (L.getAccess() == AS_protected) 9725 L.setAccess(AS_public); 9726 } 9727 } 9728 9729 // Create the nested-name-specifier that will be used to qualify the 9730 // reference to operator=; this is required to suppress the virtual 9731 // call mechanism. 9732 CXXScopeSpec SS; 9733 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9734 SS.MakeTrivial(S.Context, 9735 NestedNameSpecifier::Create(S.Context, nullptr, false, 9736 CanonicalT), 9737 Loc); 9738 9739 // Create the reference to operator=. 9740 ExprResult OpEqualRef 9741 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9742 SS, /*TemplateKWLoc=*/SourceLocation(), 9743 /*FirstQualifierInScope=*/nullptr, 9744 OpLookup, 9745 /*TemplateArgs=*/nullptr, 9746 /*SuppressQualifierCheck=*/true); 9747 if (OpEqualRef.isInvalid()) 9748 return StmtError(); 9749 9750 // Build the call to the assignment operator. 9751 9752 Expr *FromInst = From.build(S, Loc); 9753 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9754 OpEqualRef.getAs<Expr>(), 9755 Loc, FromInst, Loc); 9756 if (Call.isInvalid()) 9757 return StmtError(); 9758 9759 // If we built a call to a trivial 'operator=' while copying an array, 9760 // bail out. We'll replace the whole shebang with a memcpy. 9761 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9762 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9763 return StmtResult((Stmt*)nullptr); 9764 9765 // Convert to an expression-statement, and clean up any produced 9766 // temporaries. 9767 return S.ActOnExprStmt(Call); 9768 } 9769 9770 // - if the subobject is of scalar type, the built-in assignment 9771 // operator is used. 9772 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9773 if (!ArrayTy) { 9774 ExprResult Assignment = S.CreateBuiltinBinOp( 9775 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9776 if (Assignment.isInvalid()) 9777 return StmtError(); 9778 return S.ActOnExprStmt(Assignment); 9779 } 9780 9781 // - if the subobject is an array, each element is assigned, in the 9782 // manner appropriate to the element type; 9783 9784 // Construct a loop over the array bounds, e.g., 9785 // 9786 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9787 // 9788 // that will copy each of the array elements. 9789 QualType SizeType = S.Context.getSizeType(); 9790 9791 // Create the iteration variable. 9792 IdentifierInfo *IterationVarName = nullptr; 9793 { 9794 SmallString<8> Str; 9795 llvm::raw_svector_ostream OS(Str); 9796 OS << "__i" << Depth; 9797 IterationVarName = &S.Context.Idents.get(OS.str()); 9798 } 9799 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9800 IterationVarName, SizeType, 9801 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9802 SC_None); 9803 9804 // Initialize the iteration variable to zero. 9805 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9806 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9807 9808 // Creates a reference to the iteration variable. 9809 RefBuilder IterationVarRef(IterationVar, SizeType); 9810 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9811 9812 // Create the DeclStmt that holds the iteration variable. 9813 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9814 9815 // Subscript the "from" and "to" expressions with the iteration variable. 9816 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9817 MoveCastBuilder FromIndexMove(FromIndexCopy); 9818 const ExprBuilder *FromIndex; 9819 if (Copying) 9820 FromIndex = &FromIndexCopy; 9821 else 9822 FromIndex = &FromIndexMove; 9823 9824 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9825 9826 // Build the copy/move for an individual element of the array. 9827 StmtResult Copy = 9828 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9829 ToIndex, *FromIndex, CopyingBaseSubobject, 9830 Copying, Depth + 1); 9831 // Bail out if copying fails or if we determined that we should use memcpy. 9832 if (Copy.isInvalid() || !Copy.get()) 9833 return Copy; 9834 9835 // Create the comparison against the array bound. 9836 llvm::APInt Upper 9837 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9838 Expr *Comparison 9839 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9840 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9841 BO_NE, S.Context.BoolTy, 9842 VK_RValue, OK_Ordinary, Loc, false); 9843 9844 // Create the pre-increment of the iteration variable. 9845 Expr *Increment 9846 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9847 SizeType, VK_LValue, OK_Ordinary, Loc); 9848 9849 // Construct the loop that copies all elements of this array. 9850 return S.ActOnForStmt(Loc, Loc, InitStmt, 9851 S.MakeFullExpr(Comparison), 9852 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9853 Loc, Copy.get()); 9854 } 9855 9856 static StmtResult 9857 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9858 const ExprBuilder &To, const ExprBuilder &From, 9859 bool CopyingBaseSubobject, bool Copying) { 9860 // Maybe we should use a memcpy? 9861 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9862 T.isTriviallyCopyableType(S.Context)) 9863 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9864 9865 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9866 CopyingBaseSubobject, 9867 Copying, 0)); 9868 9869 // If we ended up picking a trivial assignment operator for an array of a 9870 // non-trivially-copyable class type, just emit a memcpy. 9871 if (!Result.isInvalid() && !Result.get()) 9872 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9873 9874 return Result; 9875 } 9876 9877 Sema::ImplicitExceptionSpecification 9878 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9879 CXXRecordDecl *ClassDecl = MD->getParent(); 9880 9881 ImplicitExceptionSpecification ExceptSpec(*this); 9882 if (ClassDecl->isInvalidDecl()) 9883 return ExceptSpec; 9884 9885 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9886 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9887 unsigned ArgQuals = 9888 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9889 9890 // C++ [except.spec]p14: 9891 // An implicitly declared special member function (Clause 12) shall have an 9892 // exception-specification. [...] 9893 9894 // It is unspecified whether or not an implicit copy assignment operator 9895 // attempts to deduplicate calls to assignment operators of virtual bases are 9896 // made. As such, this exception specification is effectively unspecified. 9897 // Based on a similar decision made for constness in C++0x, we're erring on 9898 // the side of assuming such calls to be made regardless of whether they 9899 // actually happen. 9900 for (const auto &Base : ClassDecl->bases()) { 9901 if (Base.isVirtual()) 9902 continue; 9903 9904 CXXRecordDecl *BaseClassDecl 9905 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9906 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9907 ArgQuals, false, 0)) 9908 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9909 } 9910 9911 for (const auto &Base : ClassDecl->vbases()) { 9912 CXXRecordDecl *BaseClassDecl 9913 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9914 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9915 ArgQuals, false, 0)) 9916 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9917 } 9918 9919 for (const auto *Field : ClassDecl->fields()) { 9920 QualType FieldType = Context.getBaseElementType(Field->getType()); 9921 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9922 if (CXXMethodDecl *CopyAssign = 9923 LookupCopyingAssignment(FieldClassDecl, 9924 ArgQuals | FieldType.getCVRQualifiers(), 9925 false, 0)) 9926 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9927 } 9928 } 9929 9930 return ExceptSpec; 9931 } 9932 9933 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9934 // Note: The following rules are largely analoguous to the copy 9935 // constructor rules. Note that virtual bases are not taken into account 9936 // for determining the argument type of the operator. Note also that 9937 // operators taking an object instead of a reference are allowed. 9938 assert(ClassDecl->needsImplicitCopyAssignment()); 9939 9940 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9941 if (DSM.isAlreadyBeingDeclared()) 9942 return nullptr; 9943 9944 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9945 QualType RetType = Context.getLValueReferenceType(ArgType); 9946 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9947 if (Const) 9948 ArgType = ArgType.withConst(); 9949 ArgType = Context.getLValueReferenceType(ArgType); 9950 9951 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9952 CXXCopyAssignment, 9953 Const); 9954 9955 // An implicitly-declared copy assignment operator is an inline public 9956 // member of its class. 9957 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9958 SourceLocation ClassLoc = ClassDecl->getLocation(); 9959 DeclarationNameInfo NameInfo(Name, ClassLoc); 9960 CXXMethodDecl *CopyAssignment = 9961 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9962 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9963 /*isInline=*/true, Constexpr, SourceLocation()); 9964 CopyAssignment->setAccess(AS_public); 9965 CopyAssignment->setDefaulted(); 9966 CopyAssignment->setImplicit(); 9967 9968 if (getLangOpts().CUDA) { 9969 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 9970 CopyAssignment, 9971 /* ConstRHS */ Const, 9972 /* Diagnose */ false); 9973 } 9974 9975 // Build an exception specification pointing back at this member. 9976 FunctionProtoType::ExtProtoInfo EPI = 9977 getImplicitMethodEPI(*this, CopyAssignment); 9978 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9979 9980 // Add the parameter to the operator. 9981 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9982 ClassLoc, ClassLoc, 9983 /*Id=*/nullptr, ArgType, 9984 /*TInfo=*/nullptr, SC_None, 9985 nullptr); 9986 CopyAssignment->setParams(FromParam); 9987 9988 AddOverriddenMethods(ClassDecl, CopyAssignment); 9989 9990 CopyAssignment->setTrivial( 9991 ClassDecl->needsOverloadResolutionForCopyAssignment() 9992 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9993 : ClassDecl->hasTrivialCopyAssignment()); 9994 9995 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9996 SetDeclDeleted(CopyAssignment, ClassLoc); 9997 9998 // Note that we have added this copy-assignment operator. 9999 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 10000 10001 if (Scope *S = getScopeForContext(ClassDecl)) 10002 PushOnScopeChains(CopyAssignment, S, false); 10003 ClassDecl->addDecl(CopyAssignment); 10004 10005 return CopyAssignment; 10006 } 10007 10008 /// Diagnose an implicit copy operation for a class which is odr-used, but 10009 /// which is deprecated because the class has a user-declared copy constructor, 10010 /// copy assignment operator, or destructor. 10011 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 10012 SourceLocation UseLoc) { 10013 assert(CopyOp->isImplicit()); 10014 10015 CXXRecordDecl *RD = CopyOp->getParent(); 10016 CXXMethodDecl *UserDeclaredOperation = nullptr; 10017 10018 // In Microsoft mode, assignment operations don't affect constructors and 10019 // vice versa. 10020 if (RD->hasUserDeclaredDestructor()) { 10021 UserDeclaredOperation = RD->getDestructor(); 10022 } else if (!isa<CXXConstructorDecl>(CopyOp) && 10023 RD->hasUserDeclaredCopyConstructor() && 10024 !S.getLangOpts().MSVCCompat) { 10025 // Find any user-declared copy constructor. 10026 for (auto *I : RD->ctors()) { 10027 if (I->isCopyConstructor()) { 10028 UserDeclaredOperation = I; 10029 break; 10030 } 10031 } 10032 assert(UserDeclaredOperation); 10033 } else if (isa<CXXConstructorDecl>(CopyOp) && 10034 RD->hasUserDeclaredCopyAssignment() && 10035 !S.getLangOpts().MSVCCompat) { 10036 // Find any user-declared move assignment operator. 10037 for (auto *I : RD->methods()) { 10038 if (I->isCopyAssignmentOperator()) { 10039 UserDeclaredOperation = I; 10040 break; 10041 } 10042 } 10043 assert(UserDeclaredOperation); 10044 } 10045 10046 if (UserDeclaredOperation) { 10047 S.Diag(UserDeclaredOperation->getLocation(), 10048 diag::warn_deprecated_copy_operation) 10049 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 10050 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 10051 S.Diag(UseLoc, diag::note_member_synthesized_at) 10052 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 10053 : Sema::CXXCopyAssignment) 10054 << RD; 10055 } 10056 } 10057 10058 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 10059 CXXMethodDecl *CopyAssignOperator) { 10060 assert((CopyAssignOperator->isDefaulted() && 10061 CopyAssignOperator->isOverloadedOperator() && 10062 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 10063 !CopyAssignOperator->doesThisDeclarationHaveABody() && 10064 !CopyAssignOperator->isDeleted()) && 10065 "DefineImplicitCopyAssignment called for wrong function"); 10066 10067 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 10068 10069 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 10070 CopyAssignOperator->setInvalidDecl(); 10071 return; 10072 } 10073 10074 // C++11 [class.copy]p18: 10075 // The [definition of an implicitly declared copy assignment operator] is 10076 // deprecated if the class has a user-declared copy constructor or a 10077 // user-declared destructor. 10078 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 10079 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 10080 10081 CopyAssignOperator->markUsed(Context); 10082 10083 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 10084 DiagnosticErrorTrap Trap(Diags); 10085 10086 // C++0x [class.copy]p30: 10087 // The implicitly-defined or explicitly-defaulted copy assignment operator 10088 // for a non-union class X performs memberwise copy assignment of its 10089 // subobjects. The direct base classes of X are assigned first, in the 10090 // order of their declaration in the base-specifier-list, and then the 10091 // immediate non-static data members of X are assigned, in the order in 10092 // which they were declared in the class definition. 10093 10094 // The statements that form the synthesized function body. 10095 SmallVector<Stmt*, 8> Statements; 10096 10097 // The parameter for the "other" object, which we are copying from. 10098 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 10099 Qualifiers OtherQuals = Other->getType().getQualifiers(); 10100 QualType OtherRefType = Other->getType(); 10101 if (const LValueReferenceType *OtherRef 10102 = OtherRefType->getAs<LValueReferenceType>()) { 10103 OtherRefType = OtherRef->getPointeeType(); 10104 OtherQuals = OtherRefType.getQualifiers(); 10105 } 10106 10107 // Our location for everything implicitly-generated. 10108 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 10109 ? CopyAssignOperator->getLocEnd() 10110 : CopyAssignOperator->getLocation(); 10111 10112 // Builds a DeclRefExpr for the "other" object. 10113 RefBuilder OtherRef(Other, OtherRefType); 10114 10115 // Builds the "this" pointer. 10116 ThisBuilder This; 10117 10118 // Assign base classes. 10119 bool Invalid = false; 10120 for (auto &Base : ClassDecl->bases()) { 10121 // Form the assignment: 10122 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10123 QualType BaseType = Base.getType().getUnqualifiedType(); 10124 if (!BaseType->isRecordType()) { 10125 Invalid = true; 10126 continue; 10127 } 10128 10129 CXXCastPath BasePath; 10130 BasePath.push_back(&Base); 10131 10132 // Construct the "from" expression, which is an implicit cast to the 10133 // appropriately-qualified base type. 10134 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10135 VK_LValue, BasePath); 10136 10137 // Dereference "this". 10138 DerefBuilder DerefThis(This); 10139 CastBuilder To(DerefThis, 10140 Context.getCVRQualifiedType( 10141 BaseType, CopyAssignOperator->getTypeQualifiers()), 10142 VK_LValue, BasePath); 10143 10144 // Build the copy. 10145 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10146 To, From, 10147 /*CopyingBaseSubobject=*/true, 10148 /*Copying=*/true); 10149 if (Copy.isInvalid()) { 10150 Diag(CurrentLocation, diag::note_member_synthesized_at) 10151 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10152 CopyAssignOperator->setInvalidDecl(); 10153 return; 10154 } 10155 10156 // Success! Record the copy. 10157 Statements.push_back(Copy.getAs<Expr>()); 10158 } 10159 10160 // Assign non-static members. 10161 for (auto *Field : ClassDecl->fields()) { 10162 if (Field->isUnnamedBitfield()) 10163 continue; 10164 10165 if (Field->isInvalidDecl()) { 10166 Invalid = true; 10167 continue; 10168 } 10169 10170 // Check for members of reference type; we can't copy those. 10171 if (Field->getType()->isReferenceType()) { 10172 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10173 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10174 Diag(Field->getLocation(), diag::note_declared_at); 10175 Diag(CurrentLocation, diag::note_member_synthesized_at) 10176 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10177 Invalid = true; 10178 continue; 10179 } 10180 10181 // Check for members of const-qualified, non-class type. 10182 QualType BaseType = Context.getBaseElementType(Field->getType()); 10183 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10184 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10185 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10186 Diag(Field->getLocation(), diag::note_declared_at); 10187 Diag(CurrentLocation, diag::note_member_synthesized_at) 10188 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10189 Invalid = true; 10190 continue; 10191 } 10192 10193 // Suppress assigning zero-width bitfields. 10194 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10195 continue; 10196 10197 QualType FieldType = Field->getType().getNonReferenceType(); 10198 if (FieldType->isIncompleteArrayType()) { 10199 assert(ClassDecl->hasFlexibleArrayMember() && 10200 "Incomplete array type is not valid"); 10201 continue; 10202 } 10203 10204 // Build references to the field in the object we're copying from and to. 10205 CXXScopeSpec SS; // Intentionally empty 10206 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10207 LookupMemberName); 10208 MemberLookup.addDecl(Field); 10209 MemberLookup.resolveKind(); 10210 10211 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10212 10213 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10214 10215 // Build the copy of this field. 10216 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10217 To, From, 10218 /*CopyingBaseSubobject=*/false, 10219 /*Copying=*/true); 10220 if (Copy.isInvalid()) { 10221 Diag(CurrentLocation, diag::note_member_synthesized_at) 10222 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10223 CopyAssignOperator->setInvalidDecl(); 10224 return; 10225 } 10226 10227 // Success! Record the copy. 10228 Statements.push_back(Copy.getAs<Stmt>()); 10229 } 10230 10231 if (!Invalid) { 10232 // Add a "return *this;" 10233 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10234 10235 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10236 if (Return.isInvalid()) 10237 Invalid = true; 10238 else { 10239 Statements.push_back(Return.getAs<Stmt>()); 10240 10241 if (Trap.hasErrorOccurred()) { 10242 Diag(CurrentLocation, diag::note_member_synthesized_at) 10243 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10244 Invalid = true; 10245 } 10246 } 10247 } 10248 10249 // The exception specification is needed because we are defining the 10250 // function. 10251 ResolveExceptionSpec(CurrentLocation, 10252 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10253 10254 if (Invalid) { 10255 CopyAssignOperator->setInvalidDecl(); 10256 return; 10257 } 10258 10259 StmtResult Body; 10260 { 10261 CompoundScopeRAII CompoundScope(*this); 10262 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10263 /*isStmtExpr=*/false); 10264 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10265 } 10266 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10267 10268 if (ASTMutationListener *L = getASTMutationListener()) { 10269 L->CompletedImplicitDefinition(CopyAssignOperator); 10270 } 10271 } 10272 10273 Sema::ImplicitExceptionSpecification 10274 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10275 CXXRecordDecl *ClassDecl = MD->getParent(); 10276 10277 ImplicitExceptionSpecification ExceptSpec(*this); 10278 if (ClassDecl->isInvalidDecl()) 10279 return ExceptSpec; 10280 10281 // C++0x [except.spec]p14: 10282 // An implicitly declared special member function (Clause 12) shall have an 10283 // exception-specification. [...] 10284 10285 // It is unspecified whether or not an implicit move assignment operator 10286 // attempts to deduplicate calls to assignment operators of virtual bases are 10287 // made. As such, this exception specification is effectively unspecified. 10288 // Based on a similar decision made for constness in C++0x, we're erring on 10289 // the side of assuming such calls to be made regardless of whether they 10290 // actually happen. 10291 // Note that a move constructor is not implicitly declared when there are 10292 // virtual bases, but it can still be user-declared and explicitly defaulted. 10293 for (const auto &Base : ClassDecl->bases()) { 10294 if (Base.isVirtual()) 10295 continue; 10296 10297 CXXRecordDecl *BaseClassDecl 10298 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10299 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10300 0, false, 0)) 10301 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10302 } 10303 10304 for (const auto &Base : ClassDecl->vbases()) { 10305 CXXRecordDecl *BaseClassDecl 10306 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10307 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10308 0, false, 0)) 10309 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10310 } 10311 10312 for (const auto *Field : ClassDecl->fields()) { 10313 QualType FieldType = Context.getBaseElementType(Field->getType()); 10314 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10315 if (CXXMethodDecl *MoveAssign = 10316 LookupMovingAssignment(FieldClassDecl, 10317 FieldType.getCVRQualifiers(), 10318 false, 0)) 10319 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10320 } 10321 } 10322 10323 return ExceptSpec; 10324 } 10325 10326 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10327 assert(ClassDecl->needsImplicitMoveAssignment()); 10328 10329 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10330 if (DSM.isAlreadyBeingDeclared()) 10331 return nullptr; 10332 10333 // Note: The following rules are largely analoguous to the move 10334 // constructor rules. 10335 10336 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10337 QualType RetType = Context.getLValueReferenceType(ArgType); 10338 ArgType = Context.getRValueReferenceType(ArgType); 10339 10340 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10341 CXXMoveAssignment, 10342 false); 10343 10344 // An implicitly-declared move assignment operator is an inline public 10345 // member of its class. 10346 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10347 SourceLocation ClassLoc = ClassDecl->getLocation(); 10348 DeclarationNameInfo NameInfo(Name, ClassLoc); 10349 CXXMethodDecl *MoveAssignment = 10350 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10351 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10352 /*isInline=*/true, Constexpr, SourceLocation()); 10353 MoveAssignment->setAccess(AS_public); 10354 MoveAssignment->setDefaulted(); 10355 MoveAssignment->setImplicit(); 10356 10357 if (getLangOpts().CUDA) { 10358 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10359 MoveAssignment, 10360 /* ConstRHS */ false, 10361 /* Diagnose */ false); 10362 } 10363 10364 // Build an exception specification pointing back at this member. 10365 FunctionProtoType::ExtProtoInfo EPI = 10366 getImplicitMethodEPI(*this, MoveAssignment); 10367 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10368 10369 // Add the parameter to the operator. 10370 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10371 ClassLoc, ClassLoc, 10372 /*Id=*/nullptr, ArgType, 10373 /*TInfo=*/nullptr, SC_None, 10374 nullptr); 10375 MoveAssignment->setParams(FromParam); 10376 10377 AddOverriddenMethods(ClassDecl, MoveAssignment); 10378 10379 MoveAssignment->setTrivial( 10380 ClassDecl->needsOverloadResolutionForMoveAssignment() 10381 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10382 : ClassDecl->hasTrivialMoveAssignment()); 10383 10384 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10385 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10386 SetDeclDeleted(MoveAssignment, ClassLoc); 10387 } 10388 10389 // Note that we have added this copy-assignment operator. 10390 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10391 10392 if (Scope *S = getScopeForContext(ClassDecl)) 10393 PushOnScopeChains(MoveAssignment, S, false); 10394 ClassDecl->addDecl(MoveAssignment); 10395 10396 return MoveAssignment; 10397 } 10398 10399 /// Check if we're implicitly defining a move assignment operator for a class 10400 /// with virtual bases. Such a move assignment might move-assign the virtual 10401 /// base multiple times. 10402 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10403 SourceLocation CurrentLocation) { 10404 assert(!Class->isDependentContext() && "should not define dependent move"); 10405 10406 // Only a virtual base could get implicitly move-assigned multiple times. 10407 // Only a non-trivial move assignment can observe this. We only want to 10408 // diagnose if we implicitly define an assignment operator that assigns 10409 // two base classes, both of which move-assign the same virtual base. 10410 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10411 Class->getNumBases() < 2) 10412 return; 10413 10414 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10415 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10416 VBaseMap VBases; 10417 10418 for (auto &BI : Class->bases()) { 10419 Worklist.push_back(&BI); 10420 while (!Worklist.empty()) { 10421 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10422 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10423 10424 // If the base has no non-trivial move assignment operators, 10425 // we don't care about moves from it. 10426 if (!Base->hasNonTrivialMoveAssignment()) 10427 continue; 10428 10429 // If there's nothing virtual here, skip it. 10430 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10431 continue; 10432 10433 // If we're not actually going to call a move assignment for this base, 10434 // or the selected move assignment is trivial, skip it. 10435 Sema::SpecialMemberOverloadResult *SMOR = 10436 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10437 /*ConstArg*/false, /*VolatileArg*/false, 10438 /*RValueThis*/true, /*ConstThis*/false, 10439 /*VolatileThis*/false); 10440 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10441 !SMOR->getMethod()->isMoveAssignmentOperator()) 10442 continue; 10443 10444 if (BaseSpec->isVirtual()) { 10445 // We're going to move-assign this virtual base, and its move 10446 // assignment operator is not trivial. If this can happen for 10447 // multiple distinct direct bases of Class, diagnose it. (If it 10448 // only happens in one base, we'll diagnose it when synthesizing 10449 // that base class's move assignment operator.) 10450 CXXBaseSpecifier *&Existing = 10451 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10452 .first->second; 10453 if (Existing && Existing != &BI) { 10454 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10455 << Class << Base; 10456 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10457 << (Base->getCanonicalDecl() == 10458 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10459 << Base << Existing->getType() << Existing->getSourceRange(); 10460 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10461 << (Base->getCanonicalDecl() == 10462 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10463 << Base << BI.getType() << BaseSpec->getSourceRange(); 10464 10465 // Only diagnose each vbase once. 10466 Existing = nullptr; 10467 } 10468 } else { 10469 // Only walk over bases that have defaulted move assignment operators. 10470 // We assume that any user-provided move assignment operator handles 10471 // the multiple-moves-of-vbase case itself somehow. 10472 if (!SMOR->getMethod()->isDefaulted()) 10473 continue; 10474 10475 // We're going to move the base classes of Base. Add them to the list. 10476 for (auto &BI : Base->bases()) 10477 Worklist.push_back(&BI); 10478 } 10479 } 10480 } 10481 } 10482 10483 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10484 CXXMethodDecl *MoveAssignOperator) { 10485 assert((MoveAssignOperator->isDefaulted() && 10486 MoveAssignOperator->isOverloadedOperator() && 10487 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10488 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10489 !MoveAssignOperator->isDeleted()) && 10490 "DefineImplicitMoveAssignment called for wrong function"); 10491 10492 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10493 10494 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10495 MoveAssignOperator->setInvalidDecl(); 10496 return; 10497 } 10498 10499 MoveAssignOperator->markUsed(Context); 10500 10501 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10502 DiagnosticErrorTrap Trap(Diags); 10503 10504 // C++0x [class.copy]p28: 10505 // The implicitly-defined or move assignment operator for a non-union class 10506 // X performs memberwise move assignment of its subobjects. The direct base 10507 // classes of X are assigned first, in the order of their declaration in the 10508 // base-specifier-list, and then the immediate non-static data members of X 10509 // are assigned, in the order in which they were declared in the class 10510 // definition. 10511 10512 // Issue a warning if our implicit move assignment operator will move 10513 // from a virtual base more than once. 10514 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10515 10516 // The statements that form the synthesized function body. 10517 SmallVector<Stmt*, 8> Statements; 10518 10519 // The parameter for the "other" object, which we are move from. 10520 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10521 QualType OtherRefType = Other->getType()-> 10522 getAs<RValueReferenceType>()->getPointeeType(); 10523 assert(!OtherRefType.getQualifiers() && 10524 "Bad argument type of defaulted move assignment"); 10525 10526 // Our location for everything implicitly-generated. 10527 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10528 ? MoveAssignOperator->getLocEnd() 10529 : MoveAssignOperator->getLocation(); 10530 10531 // Builds a reference to the "other" object. 10532 RefBuilder OtherRef(Other, OtherRefType); 10533 // Cast to rvalue. 10534 MoveCastBuilder MoveOther(OtherRef); 10535 10536 // Builds the "this" pointer. 10537 ThisBuilder This; 10538 10539 // Assign base classes. 10540 bool Invalid = false; 10541 for (auto &Base : ClassDecl->bases()) { 10542 // C++11 [class.copy]p28: 10543 // It is unspecified whether subobjects representing virtual base classes 10544 // are assigned more than once by the implicitly-defined copy assignment 10545 // operator. 10546 // FIXME: Do not assign to a vbase that will be assigned by some other base 10547 // class. For a move-assignment, this can result in the vbase being moved 10548 // multiple times. 10549 10550 // Form the assignment: 10551 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10552 QualType BaseType = Base.getType().getUnqualifiedType(); 10553 if (!BaseType->isRecordType()) { 10554 Invalid = true; 10555 continue; 10556 } 10557 10558 CXXCastPath BasePath; 10559 BasePath.push_back(&Base); 10560 10561 // Construct the "from" expression, which is an implicit cast to the 10562 // appropriately-qualified base type. 10563 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10564 10565 // Dereference "this". 10566 DerefBuilder DerefThis(This); 10567 10568 // Implicitly cast "this" to the appropriately-qualified base type. 10569 CastBuilder To(DerefThis, 10570 Context.getCVRQualifiedType( 10571 BaseType, MoveAssignOperator->getTypeQualifiers()), 10572 VK_LValue, BasePath); 10573 10574 // Build the move. 10575 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10576 To, From, 10577 /*CopyingBaseSubobject=*/true, 10578 /*Copying=*/false); 10579 if (Move.isInvalid()) { 10580 Diag(CurrentLocation, diag::note_member_synthesized_at) 10581 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10582 MoveAssignOperator->setInvalidDecl(); 10583 return; 10584 } 10585 10586 // Success! Record the move. 10587 Statements.push_back(Move.getAs<Expr>()); 10588 } 10589 10590 // Assign non-static members. 10591 for (auto *Field : ClassDecl->fields()) { 10592 if (Field->isUnnamedBitfield()) 10593 continue; 10594 10595 if (Field->isInvalidDecl()) { 10596 Invalid = true; 10597 continue; 10598 } 10599 10600 // Check for members of reference type; we can't move those. 10601 if (Field->getType()->isReferenceType()) { 10602 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10603 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10604 Diag(Field->getLocation(), diag::note_declared_at); 10605 Diag(CurrentLocation, diag::note_member_synthesized_at) 10606 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10607 Invalid = true; 10608 continue; 10609 } 10610 10611 // Check for members of const-qualified, non-class type. 10612 QualType BaseType = Context.getBaseElementType(Field->getType()); 10613 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10614 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10615 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10616 Diag(Field->getLocation(), diag::note_declared_at); 10617 Diag(CurrentLocation, diag::note_member_synthesized_at) 10618 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10619 Invalid = true; 10620 continue; 10621 } 10622 10623 // Suppress assigning zero-width bitfields. 10624 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10625 continue; 10626 10627 QualType FieldType = Field->getType().getNonReferenceType(); 10628 if (FieldType->isIncompleteArrayType()) { 10629 assert(ClassDecl->hasFlexibleArrayMember() && 10630 "Incomplete array type is not valid"); 10631 continue; 10632 } 10633 10634 // Build references to the field in the object we're copying from and to. 10635 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10636 LookupMemberName); 10637 MemberLookup.addDecl(Field); 10638 MemberLookup.resolveKind(); 10639 MemberBuilder From(MoveOther, OtherRefType, 10640 /*IsArrow=*/false, MemberLookup); 10641 MemberBuilder To(This, getCurrentThisType(), 10642 /*IsArrow=*/true, MemberLookup); 10643 10644 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10645 "Member reference with rvalue base must be rvalue except for reference " 10646 "members, which aren't allowed for move assignment."); 10647 10648 // Build the move of this field. 10649 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10650 To, From, 10651 /*CopyingBaseSubobject=*/false, 10652 /*Copying=*/false); 10653 if (Move.isInvalid()) { 10654 Diag(CurrentLocation, diag::note_member_synthesized_at) 10655 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10656 MoveAssignOperator->setInvalidDecl(); 10657 return; 10658 } 10659 10660 // Success! Record the copy. 10661 Statements.push_back(Move.getAs<Stmt>()); 10662 } 10663 10664 if (!Invalid) { 10665 // Add a "return *this;" 10666 ExprResult ThisObj = 10667 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10668 10669 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10670 if (Return.isInvalid()) 10671 Invalid = true; 10672 else { 10673 Statements.push_back(Return.getAs<Stmt>()); 10674 10675 if (Trap.hasErrorOccurred()) { 10676 Diag(CurrentLocation, diag::note_member_synthesized_at) 10677 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10678 Invalid = true; 10679 } 10680 } 10681 } 10682 10683 // The exception specification is needed because we are defining the 10684 // function. 10685 ResolveExceptionSpec(CurrentLocation, 10686 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10687 10688 if (Invalid) { 10689 MoveAssignOperator->setInvalidDecl(); 10690 return; 10691 } 10692 10693 StmtResult Body; 10694 { 10695 CompoundScopeRAII CompoundScope(*this); 10696 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10697 /*isStmtExpr=*/false); 10698 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10699 } 10700 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10701 10702 if (ASTMutationListener *L = getASTMutationListener()) { 10703 L->CompletedImplicitDefinition(MoveAssignOperator); 10704 } 10705 } 10706 10707 Sema::ImplicitExceptionSpecification 10708 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10709 CXXRecordDecl *ClassDecl = MD->getParent(); 10710 10711 ImplicitExceptionSpecification ExceptSpec(*this); 10712 if (ClassDecl->isInvalidDecl()) 10713 return ExceptSpec; 10714 10715 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10716 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10717 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10718 10719 // C++ [except.spec]p14: 10720 // An implicitly declared special member function (Clause 12) shall have an 10721 // exception-specification. [...] 10722 for (const auto &Base : ClassDecl->bases()) { 10723 // Virtual bases are handled below. 10724 if (Base.isVirtual()) 10725 continue; 10726 10727 CXXRecordDecl *BaseClassDecl 10728 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10729 if (CXXConstructorDecl *CopyConstructor = 10730 LookupCopyingConstructor(BaseClassDecl, Quals)) 10731 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10732 } 10733 for (const auto &Base : ClassDecl->vbases()) { 10734 CXXRecordDecl *BaseClassDecl 10735 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10736 if (CXXConstructorDecl *CopyConstructor = 10737 LookupCopyingConstructor(BaseClassDecl, Quals)) 10738 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10739 } 10740 for (const auto *Field : ClassDecl->fields()) { 10741 QualType FieldType = Context.getBaseElementType(Field->getType()); 10742 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10743 if (CXXConstructorDecl *CopyConstructor = 10744 LookupCopyingConstructor(FieldClassDecl, 10745 Quals | FieldType.getCVRQualifiers())) 10746 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10747 } 10748 } 10749 10750 return ExceptSpec; 10751 } 10752 10753 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10754 CXXRecordDecl *ClassDecl) { 10755 // C++ [class.copy]p4: 10756 // If the class definition does not explicitly declare a copy 10757 // constructor, one is declared implicitly. 10758 assert(ClassDecl->needsImplicitCopyConstructor()); 10759 10760 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10761 if (DSM.isAlreadyBeingDeclared()) 10762 return nullptr; 10763 10764 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10765 QualType ArgType = ClassType; 10766 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10767 if (Const) 10768 ArgType = ArgType.withConst(); 10769 ArgType = Context.getLValueReferenceType(ArgType); 10770 10771 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10772 CXXCopyConstructor, 10773 Const); 10774 10775 DeclarationName Name 10776 = Context.DeclarationNames.getCXXConstructorName( 10777 Context.getCanonicalType(ClassType)); 10778 SourceLocation ClassLoc = ClassDecl->getLocation(); 10779 DeclarationNameInfo NameInfo(Name, ClassLoc); 10780 10781 // An implicitly-declared copy constructor is an inline public 10782 // member of its class. 10783 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10784 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10785 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10786 Constexpr); 10787 CopyConstructor->setAccess(AS_public); 10788 CopyConstructor->setDefaulted(); 10789 10790 if (getLangOpts().CUDA) { 10791 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10792 CopyConstructor, 10793 /* ConstRHS */ Const, 10794 /* Diagnose */ false); 10795 } 10796 10797 // Build an exception specification pointing back at this member. 10798 FunctionProtoType::ExtProtoInfo EPI = 10799 getImplicitMethodEPI(*this, CopyConstructor); 10800 CopyConstructor->setType( 10801 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10802 10803 // Add the parameter to the constructor. 10804 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10805 ClassLoc, ClassLoc, 10806 /*IdentifierInfo=*/nullptr, 10807 ArgType, /*TInfo=*/nullptr, 10808 SC_None, nullptr); 10809 CopyConstructor->setParams(FromParam); 10810 10811 CopyConstructor->setTrivial( 10812 ClassDecl->needsOverloadResolutionForCopyConstructor() 10813 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10814 : ClassDecl->hasTrivialCopyConstructor()); 10815 10816 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10817 SetDeclDeleted(CopyConstructor, ClassLoc); 10818 10819 // Note that we have declared this constructor. 10820 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10821 10822 if (Scope *S = getScopeForContext(ClassDecl)) 10823 PushOnScopeChains(CopyConstructor, S, false); 10824 ClassDecl->addDecl(CopyConstructor); 10825 10826 return CopyConstructor; 10827 } 10828 10829 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10830 CXXConstructorDecl *CopyConstructor) { 10831 assert((CopyConstructor->isDefaulted() && 10832 CopyConstructor->isCopyConstructor() && 10833 !CopyConstructor->doesThisDeclarationHaveABody() && 10834 !CopyConstructor->isDeleted()) && 10835 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10836 10837 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10838 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10839 10840 // C++11 [class.copy]p7: 10841 // The [definition of an implicitly declared copy constructor] is 10842 // deprecated if the class has a user-declared copy assignment operator 10843 // or a user-declared destructor. 10844 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10845 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10846 10847 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10848 DiagnosticErrorTrap Trap(Diags); 10849 10850 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10851 Trap.hasErrorOccurred()) { 10852 Diag(CurrentLocation, diag::note_member_synthesized_at) 10853 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10854 CopyConstructor->setInvalidDecl(); 10855 } else { 10856 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10857 ? CopyConstructor->getLocEnd() 10858 : CopyConstructor->getLocation(); 10859 Sema::CompoundScopeRAII CompoundScope(*this); 10860 CopyConstructor->setBody( 10861 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10862 } 10863 10864 // The exception specification is needed because we are defining the 10865 // function. 10866 ResolveExceptionSpec(CurrentLocation, 10867 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10868 10869 CopyConstructor->markUsed(Context); 10870 MarkVTableUsed(CurrentLocation, ClassDecl); 10871 10872 if (ASTMutationListener *L = getASTMutationListener()) { 10873 L->CompletedImplicitDefinition(CopyConstructor); 10874 } 10875 } 10876 10877 Sema::ImplicitExceptionSpecification 10878 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10879 CXXRecordDecl *ClassDecl = MD->getParent(); 10880 10881 // C++ [except.spec]p14: 10882 // An implicitly declared special member function (Clause 12) shall have an 10883 // exception-specification. [...] 10884 ImplicitExceptionSpecification ExceptSpec(*this); 10885 if (ClassDecl->isInvalidDecl()) 10886 return ExceptSpec; 10887 10888 // Direct base-class constructors. 10889 for (const auto &B : ClassDecl->bases()) { 10890 if (B.isVirtual()) // Handled below. 10891 continue; 10892 10893 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10894 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10895 CXXConstructorDecl *Constructor = 10896 LookupMovingConstructor(BaseClassDecl, 0); 10897 // If this is a deleted function, add it anyway. This might be conformant 10898 // with the standard. This might not. I'm not sure. It might not matter. 10899 if (Constructor) 10900 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10901 } 10902 } 10903 10904 // Virtual base-class constructors. 10905 for (const auto &B : ClassDecl->vbases()) { 10906 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10907 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10908 CXXConstructorDecl *Constructor = 10909 LookupMovingConstructor(BaseClassDecl, 0); 10910 // If this is a deleted function, add it anyway. This might be conformant 10911 // with the standard. This might not. I'm not sure. It might not matter. 10912 if (Constructor) 10913 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10914 } 10915 } 10916 10917 // Field constructors. 10918 for (const auto *F : ClassDecl->fields()) { 10919 QualType FieldType = Context.getBaseElementType(F->getType()); 10920 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10921 CXXConstructorDecl *Constructor = 10922 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10923 // If this is a deleted function, add it anyway. This might be conformant 10924 // with the standard. This might not. I'm not sure. It might not matter. 10925 // In particular, the problem is that this function never gets called. It 10926 // might just be ill-formed because this function attempts to refer to 10927 // a deleted function here. 10928 if (Constructor) 10929 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10930 } 10931 } 10932 10933 return ExceptSpec; 10934 } 10935 10936 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10937 CXXRecordDecl *ClassDecl) { 10938 assert(ClassDecl->needsImplicitMoveConstructor()); 10939 10940 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10941 if (DSM.isAlreadyBeingDeclared()) 10942 return nullptr; 10943 10944 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10945 QualType ArgType = Context.getRValueReferenceType(ClassType); 10946 10947 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10948 CXXMoveConstructor, 10949 false); 10950 10951 DeclarationName Name 10952 = Context.DeclarationNames.getCXXConstructorName( 10953 Context.getCanonicalType(ClassType)); 10954 SourceLocation ClassLoc = ClassDecl->getLocation(); 10955 DeclarationNameInfo NameInfo(Name, ClassLoc); 10956 10957 // C++11 [class.copy]p11: 10958 // An implicitly-declared copy/move constructor is an inline public 10959 // member of its class. 10960 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10961 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10962 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10963 Constexpr); 10964 MoveConstructor->setAccess(AS_public); 10965 MoveConstructor->setDefaulted(); 10966 10967 if (getLangOpts().CUDA) { 10968 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 10969 MoveConstructor, 10970 /* ConstRHS */ false, 10971 /* Diagnose */ false); 10972 } 10973 10974 // Build an exception specification pointing back at this member. 10975 FunctionProtoType::ExtProtoInfo EPI = 10976 getImplicitMethodEPI(*this, MoveConstructor); 10977 MoveConstructor->setType( 10978 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10979 10980 // Add the parameter to the constructor. 10981 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10982 ClassLoc, ClassLoc, 10983 /*IdentifierInfo=*/nullptr, 10984 ArgType, /*TInfo=*/nullptr, 10985 SC_None, nullptr); 10986 MoveConstructor->setParams(FromParam); 10987 10988 MoveConstructor->setTrivial( 10989 ClassDecl->needsOverloadResolutionForMoveConstructor() 10990 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10991 : ClassDecl->hasTrivialMoveConstructor()); 10992 10993 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10994 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10995 SetDeclDeleted(MoveConstructor, ClassLoc); 10996 } 10997 10998 // Note that we have declared this constructor. 10999 ++ASTContext::NumImplicitMoveConstructorsDeclared; 11000 11001 if (Scope *S = getScopeForContext(ClassDecl)) 11002 PushOnScopeChains(MoveConstructor, S, false); 11003 ClassDecl->addDecl(MoveConstructor); 11004 11005 return MoveConstructor; 11006 } 11007 11008 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 11009 CXXConstructorDecl *MoveConstructor) { 11010 assert((MoveConstructor->isDefaulted() && 11011 MoveConstructor->isMoveConstructor() && 11012 !MoveConstructor->doesThisDeclarationHaveABody() && 11013 !MoveConstructor->isDeleted()) && 11014 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 11015 11016 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 11017 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 11018 11019 SynthesizedFunctionScope Scope(*this, MoveConstructor); 11020 DiagnosticErrorTrap Trap(Diags); 11021 11022 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 11023 Trap.hasErrorOccurred()) { 11024 Diag(CurrentLocation, diag::note_member_synthesized_at) 11025 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 11026 MoveConstructor->setInvalidDecl(); 11027 } else { 11028 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 11029 ? MoveConstructor->getLocEnd() 11030 : MoveConstructor->getLocation(); 11031 Sema::CompoundScopeRAII CompoundScope(*this); 11032 MoveConstructor->setBody(ActOnCompoundStmt( 11033 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 11034 } 11035 11036 // The exception specification is needed because we are defining the 11037 // function. 11038 ResolveExceptionSpec(CurrentLocation, 11039 MoveConstructor->getType()->castAs<FunctionProtoType>()); 11040 11041 MoveConstructor->markUsed(Context); 11042 MarkVTableUsed(CurrentLocation, ClassDecl); 11043 11044 if (ASTMutationListener *L = getASTMutationListener()) { 11045 L->CompletedImplicitDefinition(MoveConstructor); 11046 } 11047 } 11048 11049 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 11050 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 11051 } 11052 11053 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 11054 SourceLocation CurrentLocation, 11055 CXXConversionDecl *Conv) { 11056 CXXRecordDecl *Lambda = Conv->getParent(); 11057 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 11058 // If we are defining a specialization of a conversion to function-ptr 11059 // cache the deduced template arguments for this specialization 11060 // so that we can use them to retrieve the corresponding call-operator 11061 // and static-invoker. 11062 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 11063 11064 // Retrieve the corresponding call-operator specialization. 11065 if (Lambda->isGenericLambda()) { 11066 assert(Conv->isFunctionTemplateSpecialization()); 11067 FunctionTemplateDecl *CallOpTemplate = 11068 CallOp->getDescribedFunctionTemplate(); 11069 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 11070 void *InsertPos = nullptr; 11071 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 11072 DeducedTemplateArgs->asArray(), 11073 InsertPos); 11074 assert(CallOpSpec && 11075 "Conversion operator must have a corresponding call operator"); 11076 CallOp = cast<CXXMethodDecl>(CallOpSpec); 11077 } 11078 // Mark the call operator referenced (and add to pending instantiations 11079 // if necessary). 11080 // For both the conversion and static-invoker template specializations 11081 // we construct their body's in this function, so no need to add them 11082 // to the PendingInstantiations. 11083 MarkFunctionReferenced(CurrentLocation, CallOp); 11084 11085 SynthesizedFunctionScope Scope(*this, Conv); 11086 DiagnosticErrorTrap Trap(Diags); 11087 11088 // Retrieve the static invoker... 11089 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 11090 // ... and get the corresponding specialization for a generic lambda. 11091 if (Lambda->isGenericLambda()) { 11092 assert(DeducedTemplateArgs && 11093 "Must have deduced template arguments from Conversion Operator"); 11094 FunctionTemplateDecl *InvokeTemplate = 11095 Invoker->getDescribedFunctionTemplate(); 11096 void *InsertPos = nullptr; 11097 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 11098 DeducedTemplateArgs->asArray(), 11099 InsertPos); 11100 assert(InvokeSpec && 11101 "Must have a corresponding static invoker specialization"); 11102 Invoker = cast<CXXMethodDecl>(InvokeSpec); 11103 } 11104 // Construct the body of the conversion function { return __invoke; }. 11105 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 11106 VK_LValue, Conv->getLocation()).get(); 11107 assert(FunctionRef && "Can't refer to __invoke function?"); 11108 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 11109 Conv->setBody(new (Context) CompoundStmt(Context, Return, 11110 Conv->getLocation(), 11111 Conv->getLocation())); 11112 11113 Conv->markUsed(Context); 11114 Conv->setReferenced(); 11115 11116 // Fill in the __invoke function with a dummy implementation. IR generation 11117 // will fill in the actual details. 11118 Invoker->markUsed(Context); 11119 Invoker->setReferenced(); 11120 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 11121 11122 if (ASTMutationListener *L = getASTMutationListener()) { 11123 L->CompletedImplicitDefinition(Conv); 11124 L->CompletedImplicitDefinition(Invoker); 11125 } 11126 } 11127 11128 11129 11130 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11131 SourceLocation CurrentLocation, 11132 CXXConversionDecl *Conv) 11133 { 11134 assert(!Conv->getParent()->isGenericLambda()); 11135 11136 Conv->markUsed(Context); 11137 11138 SynthesizedFunctionScope Scope(*this, Conv); 11139 DiagnosticErrorTrap Trap(Diags); 11140 11141 // Copy-initialize the lambda object as needed to capture it. 11142 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11143 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11144 11145 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11146 Conv->getLocation(), 11147 Conv, DerefThis); 11148 11149 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11150 // behavior. Note that only the general conversion function does this 11151 // (since it's unusable otherwise); in the case where we inline the 11152 // block literal, it has block literal lifetime semantics. 11153 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11154 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11155 CK_CopyAndAutoreleaseBlockObject, 11156 BuildBlock.get(), nullptr, VK_RValue); 11157 11158 if (BuildBlock.isInvalid()) { 11159 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11160 Conv->setInvalidDecl(); 11161 return; 11162 } 11163 11164 // Create the return statement that returns the block from the conversion 11165 // function. 11166 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11167 if (Return.isInvalid()) { 11168 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11169 Conv->setInvalidDecl(); 11170 return; 11171 } 11172 11173 // Set the body of the conversion function. 11174 Stmt *ReturnS = Return.get(); 11175 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11176 Conv->getLocation(), 11177 Conv->getLocation())); 11178 11179 // We're done; notify the mutation listener, if any. 11180 if (ASTMutationListener *L = getASTMutationListener()) { 11181 L->CompletedImplicitDefinition(Conv); 11182 } 11183 } 11184 11185 /// \brief Determine whether the given list arguments contains exactly one 11186 /// "real" (non-default) argument. 11187 static bool hasOneRealArgument(MultiExprArg Args) { 11188 switch (Args.size()) { 11189 case 0: 11190 return false; 11191 11192 default: 11193 if (!Args[1]->isDefaultArgument()) 11194 return false; 11195 11196 // fall through 11197 case 1: 11198 return !Args[0]->isDefaultArgument(); 11199 } 11200 11201 return false; 11202 } 11203 11204 ExprResult 11205 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11206 CXXConstructorDecl *Constructor, 11207 MultiExprArg ExprArgs, 11208 bool HadMultipleCandidates, 11209 bool IsListInitialization, 11210 bool IsStdInitListInitialization, 11211 bool RequiresZeroInit, 11212 unsigned ConstructKind, 11213 SourceRange ParenRange) { 11214 bool Elidable = false; 11215 11216 // C++0x [class.copy]p34: 11217 // When certain criteria are met, an implementation is allowed to 11218 // omit the copy/move construction of a class object, even if the 11219 // copy/move constructor and/or destructor for the object have 11220 // side effects. [...] 11221 // - when a temporary class object that has not been bound to a 11222 // reference (12.2) would be copied/moved to a class object 11223 // with the same cv-unqualified type, the copy/move operation 11224 // can be omitted by constructing the temporary object 11225 // directly into the target of the omitted copy/move 11226 if (ConstructKind == CXXConstructExpr::CK_Complete && 11227 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11228 Expr *SubExpr = ExprArgs[0]; 11229 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11230 } 11231 11232 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11233 Elidable, ExprArgs, HadMultipleCandidates, 11234 IsListInitialization, 11235 IsStdInitListInitialization, RequiresZeroInit, 11236 ConstructKind, ParenRange); 11237 } 11238 11239 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11240 /// including handling of its default argument expressions. 11241 ExprResult 11242 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11243 CXXConstructorDecl *Constructor, bool Elidable, 11244 MultiExprArg ExprArgs, 11245 bool HadMultipleCandidates, 11246 bool IsListInitialization, 11247 bool IsStdInitListInitialization, 11248 bool RequiresZeroInit, 11249 unsigned ConstructKind, 11250 SourceRange ParenRange) { 11251 MarkFunctionReferenced(ConstructLoc, Constructor); 11252 return CXXConstructExpr::Create( 11253 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11254 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11255 RequiresZeroInit, 11256 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11257 ParenRange); 11258 } 11259 11260 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11261 assert(Field->hasInClassInitializer()); 11262 11263 // If we already have the in-class initializer nothing needs to be done. 11264 if (Field->getInClassInitializer()) 11265 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11266 11267 // Maybe we haven't instantiated the in-class initializer. Go check the 11268 // pattern FieldDecl to see if it has one. 11269 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11270 11271 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11272 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11273 DeclContext::lookup_result Lookup = 11274 ClassPattern->lookup(Field->getDeclName()); 11275 assert(Lookup.size() == 1); 11276 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11277 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11278 getTemplateInstantiationArgs(Field))) 11279 return ExprError(); 11280 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11281 } 11282 11283 // DR1351: 11284 // If the brace-or-equal-initializer of a non-static data member 11285 // invokes a defaulted default constructor of its class or of an 11286 // enclosing class in a potentially evaluated subexpression, the 11287 // program is ill-formed. 11288 // 11289 // This resolution is unworkable: the exception specification of the 11290 // default constructor can be needed in an unevaluated context, in 11291 // particular, in the operand of a noexcept-expression, and we can be 11292 // unable to compute an exception specification for an enclosed class. 11293 // 11294 // Any attempt to resolve the exception specification of a defaulted default 11295 // constructor before the initializer is lexically complete will ultimately 11296 // come here at which point we can diagnose it. 11297 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11298 if (OutermostClass == ParentRD) { 11299 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11300 << ParentRD << Field; 11301 } else { 11302 Diag(Field->getLocEnd(), 11303 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11304 << ParentRD << OutermostClass << Field; 11305 } 11306 11307 return ExprError(); 11308 } 11309 11310 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11311 if (VD->isInvalidDecl()) return; 11312 11313 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11314 if (ClassDecl->isInvalidDecl()) return; 11315 if (ClassDecl->hasIrrelevantDestructor()) return; 11316 if (ClassDecl->isDependentContext()) return; 11317 11318 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11319 MarkFunctionReferenced(VD->getLocation(), Destructor); 11320 CheckDestructorAccess(VD->getLocation(), Destructor, 11321 PDiag(diag::err_access_dtor_var) 11322 << VD->getDeclName() 11323 << VD->getType()); 11324 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11325 11326 if (Destructor->isTrivial()) return; 11327 if (!VD->hasGlobalStorage()) return; 11328 11329 // Emit warning for non-trivial dtor in global scope (a real global, 11330 // class-static, function-static). 11331 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11332 11333 // TODO: this should be re-enabled for static locals by !CXAAtExit 11334 if (!VD->isStaticLocal()) 11335 Diag(VD->getLocation(), diag::warn_global_destructor); 11336 } 11337 11338 /// \brief Given a constructor and the set of arguments provided for the 11339 /// constructor, convert the arguments and add any required default arguments 11340 /// to form a proper call to this constructor. 11341 /// 11342 /// \returns true if an error occurred, false otherwise. 11343 bool 11344 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11345 MultiExprArg ArgsPtr, 11346 SourceLocation Loc, 11347 SmallVectorImpl<Expr*> &ConvertedArgs, 11348 bool AllowExplicit, 11349 bool IsListInitialization) { 11350 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11351 unsigned NumArgs = ArgsPtr.size(); 11352 Expr **Args = ArgsPtr.data(); 11353 11354 const FunctionProtoType *Proto 11355 = Constructor->getType()->getAs<FunctionProtoType>(); 11356 assert(Proto && "Constructor without a prototype?"); 11357 unsigned NumParams = Proto->getNumParams(); 11358 11359 // If too few arguments are available, we'll fill in the rest with defaults. 11360 if (NumArgs < NumParams) 11361 ConvertedArgs.reserve(NumParams); 11362 else 11363 ConvertedArgs.reserve(NumArgs); 11364 11365 VariadicCallType CallType = 11366 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11367 SmallVector<Expr *, 8> AllArgs; 11368 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11369 Proto, 0, 11370 llvm::makeArrayRef(Args, NumArgs), 11371 AllArgs, 11372 CallType, AllowExplicit, 11373 IsListInitialization); 11374 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11375 11376 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11377 11378 CheckConstructorCall(Constructor, 11379 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11380 Proto, Loc); 11381 11382 return Invalid; 11383 } 11384 11385 static inline bool 11386 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11387 const FunctionDecl *FnDecl) { 11388 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11389 if (isa<NamespaceDecl>(DC)) { 11390 return SemaRef.Diag(FnDecl->getLocation(), 11391 diag::err_operator_new_delete_declared_in_namespace) 11392 << FnDecl->getDeclName(); 11393 } 11394 11395 if (isa<TranslationUnitDecl>(DC) && 11396 FnDecl->getStorageClass() == SC_Static) { 11397 return SemaRef.Diag(FnDecl->getLocation(), 11398 diag::err_operator_new_delete_declared_static) 11399 << FnDecl->getDeclName(); 11400 } 11401 11402 return false; 11403 } 11404 11405 static inline bool 11406 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11407 CanQualType ExpectedResultType, 11408 CanQualType ExpectedFirstParamType, 11409 unsigned DependentParamTypeDiag, 11410 unsigned InvalidParamTypeDiag) { 11411 QualType ResultType = 11412 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11413 11414 // Check that the result type is not dependent. 11415 if (ResultType->isDependentType()) 11416 return SemaRef.Diag(FnDecl->getLocation(), 11417 diag::err_operator_new_delete_dependent_result_type) 11418 << FnDecl->getDeclName() << ExpectedResultType; 11419 11420 // Check that the result type is what we expect. 11421 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11422 return SemaRef.Diag(FnDecl->getLocation(), 11423 diag::err_operator_new_delete_invalid_result_type) 11424 << FnDecl->getDeclName() << ExpectedResultType; 11425 11426 // A function template must have at least 2 parameters. 11427 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11428 return SemaRef.Diag(FnDecl->getLocation(), 11429 diag::err_operator_new_delete_template_too_few_parameters) 11430 << FnDecl->getDeclName(); 11431 11432 // The function decl must have at least 1 parameter. 11433 if (FnDecl->getNumParams() == 0) 11434 return SemaRef.Diag(FnDecl->getLocation(), 11435 diag::err_operator_new_delete_too_few_parameters) 11436 << FnDecl->getDeclName(); 11437 11438 // Check the first parameter type is not dependent. 11439 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11440 if (FirstParamType->isDependentType()) 11441 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11442 << FnDecl->getDeclName() << ExpectedFirstParamType; 11443 11444 // Check that the first parameter type is what we expect. 11445 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11446 ExpectedFirstParamType) 11447 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11448 << FnDecl->getDeclName() << ExpectedFirstParamType; 11449 11450 return false; 11451 } 11452 11453 static bool 11454 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11455 // C++ [basic.stc.dynamic.allocation]p1: 11456 // A program is ill-formed if an allocation function is declared in a 11457 // namespace scope other than global scope or declared static in global 11458 // scope. 11459 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11460 return true; 11461 11462 CanQualType SizeTy = 11463 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11464 11465 // C++ [basic.stc.dynamic.allocation]p1: 11466 // The return type shall be void*. The first parameter shall have type 11467 // std::size_t. 11468 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11469 SizeTy, 11470 diag::err_operator_new_dependent_param_type, 11471 diag::err_operator_new_param_type)) 11472 return true; 11473 11474 // C++ [basic.stc.dynamic.allocation]p1: 11475 // The first parameter shall not have an associated default argument. 11476 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11477 return SemaRef.Diag(FnDecl->getLocation(), 11478 diag::err_operator_new_default_arg) 11479 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11480 11481 return false; 11482 } 11483 11484 static bool 11485 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11486 // C++ [basic.stc.dynamic.deallocation]p1: 11487 // A program is ill-formed if deallocation functions are declared in a 11488 // namespace scope other than global scope or declared static in global 11489 // scope. 11490 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11491 return true; 11492 11493 // C++ [basic.stc.dynamic.deallocation]p2: 11494 // Each deallocation function shall return void and its first parameter 11495 // shall be void*. 11496 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11497 SemaRef.Context.VoidPtrTy, 11498 diag::err_operator_delete_dependent_param_type, 11499 diag::err_operator_delete_param_type)) 11500 return true; 11501 11502 return false; 11503 } 11504 11505 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11506 /// of this overloaded operator is well-formed. If so, returns false; 11507 /// otherwise, emits appropriate diagnostics and returns true. 11508 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11509 assert(FnDecl && FnDecl->isOverloadedOperator() && 11510 "Expected an overloaded operator declaration"); 11511 11512 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11513 11514 // C++ [over.oper]p5: 11515 // The allocation and deallocation functions, operator new, 11516 // operator new[], operator delete and operator delete[], are 11517 // described completely in 3.7.3. The attributes and restrictions 11518 // found in the rest of this subclause do not apply to them unless 11519 // explicitly stated in 3.7.3. 11520 if (Op == OO_Delete || Op == OO_Array_Delete) 11521 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11522 11523 if (Op == OO_New || Op == OO_Array_New) 11524 return CheckOperatorNewDeclaration(*this, FnDecl); 11525 11526 // C++ [over.oper]p6: 11527 // An operator function shall either be a non-static member 11528 // function or be a non-member function and have at least one 11529 // parameter whose type is a class, a reference to a class, an 11530 // enumeration, or a reference to an enumeration. 11531 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11532 if (MethodDecl->isStatic()) 11533 return Diag(FnDecl->getLocation(), 11534 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11535 } else { 11536 bool ClassOrEnumParam = false; 11537 for (auto Param : FnDecl->params()) { 11538 QualType ParamType = Param->getType().getNonReferenceType(); 11539 if (ParamType->isDependentType() || ParamType->isRecordType() || 11540 ParamType->isEnumeralType()) { 11541 ClassOrEnumParam = true; 11542 break; 11543 } 11544 } 11545 11546 if (!ClassOrEnumParam) 11547 return Diag(FnDecl->getLocation(), 11548 diag::err_operator_overload_needs_class_or_enum) 11549 << FnDecl->getDeclName(); 11550 } 11551 11552 // C++ [over.oper]p8: 11553 // An operator function cannot have default arguments (8.3.6), 11554 // except where explicitly stated below. 11555 // 11556 // Only the function-call operator allows default arguments 11557 // (C++ [over.call]p1). 11558 if (Op != OO_Call) { 11559 for (auto Param : FnDecl->params()) { 11560 if (Param->hasDefaultArg()) 11561 return Diag(Param->getLocation(), 11562 diag::err_operator_overload_default_arg) 11563 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11564 } 11565 } 11566 11567 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11568 { false, false, false } 11569 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11570 , { Unary, Binary, MemberOnly } 11571 #include "clang/Basic/OperatorKinds.def" 11572 }; 11573 11574 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11575 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11576 bool MustBeMemberOperator = OperatorUses[Op][2]; 11577 11578 // C++ [over.oper]p8: 11579 // [...] Operator functions cannot have more or fewer parameters 11580 // than the number required for the corresponding operator, as 11581 // described in the rest of this subclause. 11582 unsigned NumParams = FnDecl->getNumParams() 11583 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11584 if (Op != OO_Call && 11585 ((NumParams == 1 && !CanBeUnaryOperator) || 11586 (NumParams == 2 && !CanBeBinaryOperator) || 11587 (NumParams < 1) || (NumParams > 2))) { 11588 // We have the wrong number of parameters. 11589 unsigned ErrorKind; 11590 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11591 ErrorKind = 2; // 2 -> unary or binary. 11592 } else if (CanBeUnaryOperator) { 11593 ErrorKind = 0; // 0 -> unary 11594 } else { 11595 assert(CanBeBinaryOperator && 11596 "All non-call overloaded operators are unary or binary!"); 11597 ErrorKind = 1; // 1 -> binary 11598 } 11599 11600 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11601 << FnDecl->getDeclName() << NumParams << ErrorKind; 11602 } 11603 11604 // Overloaded operators other than operator() cannot be variadic. 11605 if (Op != OO_Call && 11606 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11607 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11608 << FnDecl->getDeclName(); 11609 } 11610 11611 // Some operators must be non-static member functions. 11612 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11613 return Diag(FnDecl->getLocation(), 11614 diag::err_operator_overload_must_be_member) 11615 << FnDecl->getDeclName(); 11616 } 11617 11618 // C++ [over.inc]p1: 11619 // The user-defined function called operator++ implements the 11620 // prefix and postfix ++ operator. If this function is a member 11621 // function with no parameters, or a non-member function with one 11622 // parameter of class or enumeration type, it defines the prefix 11623 // increment operator ++ for objects of that type. If the function 11624 // is a member function with one parameter (which shall be of type 11625 // int) or a non-member function with two parameters (the second 11626 // of which shall be of type int), it defines the postfix 11627 // increment operator ++ for objects of that type. 11628 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11629 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11630 QualType ParamType = LastParam->getType(); 11631 11632 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11633 !ParamType->isDependentType()) 11634 return Diag(LastParam->getLocation(), 11635 diag::err_operator_overload_post_incdec_must_be_int) 11636 << LastParam->getType() << (Op == OO_MinusMinus); 11637 } 11638 11639 return false; 11640 } 11641 11642 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11643 /// of this literal operator function is well-formed. If so, returns 11644 /// false; otherwise, emits appropriate diagnostics and returns true. 11645 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11646 if (isa<CXXMethodDecl>(FnDecl)) { 11647 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11648 << FnDecl->getDeclName(); 11649 return true; 11650 } 11651 11652 if (FnDecl->isExternC()) { 11653 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11654 return true; 11655 } 11656 11657 bool Valid = false; 11658 11659 // This might be the definition of a literal operator template. 11660 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11661 // This might be a specialization of a literal operator template. 11662 if (!TpDecl) 11663 TpDecl = FnDecl->getPrimaryTemplate(); 11664 11665 // template <char...> type operator "" name() and 11666 // template <class T, T...> type operator "" name() are the only valid 11667 // template signatures, and the only valid signatures with no parameters. 11668 if (TpDecl) { 11669 if (FnDecl->param_size() == 0) { 11670 // Must have one or two template parameters 11671 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11672 if (Params->size() == 1) { 11673 NonTypeTemplateParmDecl *PmDecl = 11674 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11675 11676 // The template parameter must be a char parameter pack. 11677 if (PmDecl && PmDecl->isTemplateParameterPack() && 11678 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11679 Valid = true; 11680 } else if (Params->size() == 2) { 11681 TemplateTypeParmDecl *PmType = 11682 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11683 NonTypeTemplateParmDecl *PmArgs = 11684 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11685 11686 // The second template parameter must be a parameter pack with the 11687 // first template parameter as its type. 11688 if (PmType && PmArgs && 11689 !PmType->isTemplateParameterPack() && 11690 PmArgs->isTemplateParameterPack()) { 11691 const TemplateTypeParmType *TArgs = 11692 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11693 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11694 TArgs->getIndex() == PmType->getIndex()) { 11695 Valid = true; 11696 if (ActiveTemplateInstantiations.empty()) 11697 Diag(FnDecl->getLocation(), 11698 diag::ext_string_literal_operator_template); 11699 } 11700 } 11701 } 11702 } 11703 } else if (FnDecl->param_size()) { 11704 // Check the first parameter 11705 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11706 11707 QualType T = (*Param)->getType().getUnqualifiedType(); 11708 11709 // unsigned long long int, long double, and any character type are allowed 11710 // as the only parameters. 11711 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11712 Context.hasSameType(T, Context.LongDoubleTy) || 11713 Context.hasSameType(T, Context.CharTy) || 11714 Context.hasSameType(T, Context.WideCharTy) || 11715 Context.hasSameType(T, Context.Char16Ty) || 11716 Context.hasSameType(T, Context.Char32Ty)) { 11717 if (++Param == FnDecl->param_end()) 11718 Valid = true; 11719 goto FinishedParams; 11720 } 11721 11722 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11723 const PointerType *PT = T->getAs<PointerType>(); 11724 if (!PT) 11725 goto FinishedParams; 11726 T = PT->getPointeeType(); 11727 if (!T.isConstQualified() || T.isVolatileQualified()) 11728 goto FinishedParams; 11729 T = T.getUnqualifiedType(); 11730 11731 // Move on to the second parameter; 11732 ++Param; 11733 11734 // If there is no second parameter, the first must be a const char * 11735 if (Param == FnDecl->param_end()) { 11736 if (Context.hasSameType(T, Context.CharTy)) 11737 Valid = true; 11738 goto FinishedParams; 11739 } 11740 11741 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11742 // are allowed as the first parameter to a two-parameter function 11743 if (!(Context.hasSameType(T, Context.CharTy) || 11744 Context.hasSameType(T, Context.WideCharTy) || 11745 Context.hasSameType(T, Context.Char16Ty) || 11746 Context.hasSameType(T, Context.Char32Ty))) 11747 goto FinishedParams; 11748 11749 // The second and final parameter must be an std::size_t 11750 T = (*Param)->getType().getUnqualifiedType(); 11751 if (Context.hasSameType(T, Context.getSizeType()) && 11752 ++Param == FnDecl->param_end()) 11753 Valid = true; 11754 } 11755 11756 // FIXME: This diagnostic is absolutely terrible. 11757 FinishedParams: 11758 if (!Valid) { 11759 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11760 << FnDecl->getDeclName(); 11761 return true; 11762 } 11763 11764 // A parameter-declaration-clause containing a default argument is not 11765 // equivalent to any of the permitted forms. 11766 for (auto Param : FnDecl->params()) { 11767 if (Param->hasDefaultArg()) { 11768 Diag(Param->getDefaultArgRange().getBegin(), 11769 diag::err_literal_operator_default_argument) 11770 << Param->getDefaultArgRange(); 11771 break; 11772 } 11773 } 11774 11775 StringRef LiteralName 11776 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11777 if (LiteralName[0] != '_') { 11778 // C++11 [usrlit.suffix]p1: 11779 // Literal suffix identifiers that do not start with an underscore 11780 // are reserved for future standardization. 11781 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11782 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11783 } 11784 11785 return false; 11786 } 11787 11788 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11789 /// linkage specification, including the language and (if present) 11790 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11791 /// language string literal. LBraceLoc, if valid, provides the location of 11792 /// the '{' brace. Otherwise, this linkage specification does not 11793 /// have any braces. 11794 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11795 Expr *LangStr, 11796 SourceLocation LBraceLoc) { 11797 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11798 if (!Lit->isAscii()) { 11799 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11800 << LangStr->getSourceRange(); 11801 return nullptr; 11802 } 11803 11804 StringRef Lang = Lit->getString(); 11805 LinkageSpecDecl::LanguageIDs Language; 11806 if (Lang == "C") 11807 Language = LinkageSpecDecl::lang_c; 11808 else if (Lang == "C++") 11809 Language = LinkageSpecDecl::lang_cxx; 11810 else { 11811 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11812 << LangStr->getSourceRange(); 11813 return nullptr; 11814 } 11815 11816 // FIXME: Add all the various semantics of linkage specifications 11817 11818 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11819 LangStr->getExprLoc(), Language, 11820 LBraceLoc.isValid()); 11821 CurContext->addDecl(D); 11822 PushDeclContext(S, D); 11823 return D; 11824 } 11825 11826 /// ActOnFinishLinkageSpecification - Complete the definition of 11827 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11828 /// valid, it's the position of the closing '}' brace in a linkage 11829 /// specification that uses braces. 11830 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11831 Decl *LinkageSpec, 11832 SourceLocation RBraceLoc) { 11833 if (RBraceLoc.isValid()) { 11834 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11835 LSDecl->setRBraceLoc(RBraceLoc); 11836 } 11837 PopDeclContext(); 11838 return LinkageSpec; 11839 } 11840 11841 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11842 AttributeList *AttrList, 11843 SourceLocation SemiLoc) { 11844 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11845 // Attribute declarations appertain to empty declaration so we handle 11846 // them here. 11847 if (AttrList) 11848 ProcessDeclAttributeList(S, ED, AttrList); 11849 11850 CurContext->addDecl(ED); 11851 return ED; 11852 } 11853 11854 /// \brief Perform semantic analysis for the variable declaration that 11855 /// occurs within a C++ catch clause, returning the newly-created 11856 /// variable. 11857 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11858 TypeSourceInfo *TInfo, 11859 SourceLocation StartLoc, 11860 SourceLocation Loc, 11861 IdentifierInfo *Name) { 11862 bool Invalid = false; 11863 QualType ExDeclType = TInfo->getType(); 11864 11865 // Arrays and functions decay. 11866 if (ExDeclType->isArrayType()) 11867 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11868 else if (ExDeclType->isFunctionType()) 11869 ExDeclType = Context.getPointerType(ExDeclType); 11870 11871 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11872 // The exception-declaration shall not denote a pointer or reference to an 11873 // incomplete type, other than [cv] void*. 11874 // N2844 forbids rvalue references. 11875 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11876 Diag(Loc, diag::err_catch_rvalue_ref); 11877 Invalid = true; 11878 } 11879 11880 QualType BaseType = ExDeclType; 11881 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11882 unsigned DK = diag::err_catch_incomplete; 11883 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11884 BaseType = Ptr->getPointeeType(); 11885 Mode = 1; 11886 DK = diag::err_catch_incomplete_ptr; 11887 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11888 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11889 BaseType = Ref->getPointeeType(); 11890 Mode = 2; 11891 DK = diag::err_catch_incomplete_ref; 11892 } 11893 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11894 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11895 Invalid = true; 11896 11897 if (!Invalid && !ExDeclType->isDependentType() && 11898 RequireNonAbstractType(Loc, ExDeclType, 11899 diag::err_abstract_type_in_decl, 11900 AbstractVariableType)) 11901 Invalid = true; 11902 11903 // Only the non-fragile NeXT runtime currently supports C++ catches 11904 // of ObjC types, and no runtime supports catching ObjC types by value. 11905 if (!Invalid && getLangOpts().ObjC1) { 11906 QualType T = ExDeclType; 11907 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11908 T = RT->getPointeeType(); 11909 11910 if (T->isObjCObjectType()) { 11911 Diag(Loc, diag::err_objc_object_catch); 11912 Invalid = true; 11913 } else if (T->isObjCObjectPointerType()) { 11914 // FIXME: should this be a test for macosx-fragile specifically? 11915 if (getLangOpts().ObjCRuntime.isFragile()) 11916 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11917 } 11918 } 11919 11920 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11921 ExDeclType, TInfo, SC_None); 11922 ExDecl->setExceptionVariable(true); 11923 11924 // In ARC, infer 'retaining' for variables of retainable type. 11925 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11926 Invalid = true; 11927 11928 if (!Invalid && !ExDeclType->isDependentType()) { 11929 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11930 // Insulate this from anything else we might currently be parsing. 11931 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11932 11933 // C++ [except.handle]p16: 11934 // The object declared in an exception-declaration or, if the 11935 // exception-declaration does not specify a name, a temporary (12.2) is 11936 // copy-initialized (8.5) from the exception object. [...] 11937 // The object is destroyed when the handler exits, after the destruction 11938 // of any automatic objects initialized within the handler. 11939 // 11940 // We just pretend to initialize the object with itself, then make sure 11941 // it can be destroyed later. 11942 QualType initType = Context.getExceptionObjectType(ExDeclType); 11943 11944 InitializedEntity entity = 11945 InitializedEntity::InitializeVariable(ExDecl); 11946 InitializationKind initKind = 11947 InitializationKind::CreateCopy(Loc, SourceLocation()); 11948 11949 Expr *opaqueValue = 11950 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11951 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11952 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11953 if (result.isInvalid()) 11954 Invalid = true; 11955 else { 11956 // If the constructor used was non-trivial, set this as the 11957 // "initializer". 11958 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11959 if (!construct->getConstructor()->isTrivial()) { 11960 Expr *init = MaybeCreateExprWithCleanups(construct); 11961 ExDecl->setInit(init); 11962 } 11963 11964 // And make sure it's destructable. 11965 FinalizeVarWithDestructor(ExDecl, recordType); 11966 } 11967 } 11968 } 11969 11970 if (Invalid) 11971 ExDecl->setInvalidDecl(); 11972 11973 return ExDecl; 11974 } 11975 11976 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11977 /// handler. 11978 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11979 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11980 bool Invalid = D.isInvalidType(); 11981 11982 // Check for unexpanded parameter packs. 11983 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11984 UPPC_ExceptionType)) { 11985 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11986 D.getIdentifierLoc()); 11987 Invalid = true; 11988 } 11989 11990 IdentifierInfo *II = D.getIdentifier(); 11991 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11992 LookupOrdinaryName, 11993 ForRedeclaration)) { 11994 // The scope should be freshly made just for us. There is just no way 11995 // it contains any previous declaration, except for function parameters in 11996 // a function-try-block's catch statement. 11997 assert(!S->isDeclScope(PrevDecl)); 11998 if (isDeclInScope(PrevDecl, CurContext, S)) { 11999 Diag(D.getIdentifierLoc(), diag::err_redefinition) 12000 << D.getIdentifier(); 12001 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12002 Invalid = true; 12003 } else if (PrevDecl->isTemplateParameter()) 12004 // Maybe we will complain about the shadowed template parameter. 12005 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12006 } 12007 12008 if (D.getCXXScopeSpec().isSet() && !Invalid) { 12009 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 12010 << D.getCXXScopeSpec().getRange(); 12011 Invalid = true; 12012 } 12013 12014 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 12015 D.getLocStart(), 12016 D.getIdentifierLoc(), 12017 D.getIdentifier()); 12018 if (Invalid) 12019 ExDecl->setInvalidDecl(); 12020 12021 // Add the exception declaration into this scope. 12022 if (II) 12023 PushOnScopeChains(ExDecl, S); 12024 else 12025 CurContext->addDecl(ExDecl); 12026 12027 ProcessDeclAttributes(S, ExDecl, D); 12028 return ExDecl; 12029 } 12030 12031 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12032 Expr *AssertExpr, 12033 Expr *AssertMessageExpr, 12034 SourceLocation RParenLoc) { 12035 StringLiteral *AssertMessage = 12036 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 12037 12038 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 12039 return nullptr; 12040 12041 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 12042 AssertMessage, RParenLoc, false); 12043 } 12044 12045 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 12046 Expr *AssertExpr, 12047 StringLiteral *AssertMessage, 12048 SourceLocation RParenLoc, 12049 bool Failed) { 12050 assert(AssertExpr != nullptr && "Expected non-null condition"); 12051 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 12052 !Failed) { 12053 // In a static_assert-declaration, the constant-expression shall be a 12054 // constant expression that can be contextually converted to bool. 12055 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 12056 if (Converted.isInvalid()) 12057 Failed = true; 12058 12059 llvm::APSInt Cond; 12060 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 12061 diag::err_static_assert_expression_is_not_constant, 12062 /*AllowFold=*/false).isInvalid()) 12063 Failed = true; 12064 12065 if (!Failed && !Cond) { 12066 SmallString<256> MsgBuffer; 12067 llvm::raw_svector_ostream Msg(MsgBuffer); 12068 if (AssertMessage) 12069 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 12070 Diag(StaticAssertLoc, diag::err_static_assert_failed) 12071 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 12072 Failed = true; 12073 } 12074 } 12075 12076 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 12077 AssertExpr, AssertMessage, RParenLoc, 12078 Failed); 12079 12080 CurContext->addDecl(Decl); 12081 return Decl; 12082 } 12083 12084 /// \brief Perform semantic analysis of the given friend type declaration. 12085 /// 12086 /// \returns A friend declaration that. 12087 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 12088 SourceLocation FriendLoc, 12089 TypeSourceInfo *TSInfo) { 12090 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 12091 12092 QualType T = TSInfo->getType(); 12093 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 12094 12095 // C++03 [class.friend]p2: 12096 // An elaborated-type-specifier shall be used in a friend declaration 12097 // for a class.* 12098 // 12099 // * The class-key of the elaborated-type-specifier is required. 12100 if (!ActiveTemplateInstantiations.empty()) { 12101 // Do not complain about the form of friend template types during 12102 // template instantiation; we will already have complained when the 12103 // template was declared. 12104 } else { 12105 if (!T->isElaboratedTypeSpecifier()) { 12106 // If we evaluated the type to a record type, suggest putting 12107 // a tag in front. 12108 if (const RecordType *RT = T->getAs<RecordType>()) { 12109 RecordDecl *RD = RT->getDecl(); 12110 12111 SmallString<16> InsertionText(" "); 12112 InsertionText += RD->getKindName(); 12113 12114 Diag(TypeRange.getBegin(), 12115 getLangOpts().CPlusPlus11 ? 12116 diag::warn_cxx98_compat_unelaborated_friend_type : 12117 diag::ext_unelaborated_friend_type) 12118 << (unsigned) RD->getTagKind() 12119 << T 12120 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 12121 InsertionText); 12122 } else { 12123 Diag(FriendLoc, 12124 getLangOpts().CPlusPlus11 ? 12125 diag::warn_cxx98_compat_nonclass_type_friend : 12126 diag::ext_nonclass_type_friend) 12127 << T 12128 << TypeRange; 12129 } 12130 } else if (T->getAs<EnumType>()) { 12131 Diag(FriendLoc, 12132 getLangOpts().CPlusPlus11 ? 12133 diag::warn_cxx98_compat_enum_friend : 12134 diag::ext_enum_friend) 12135 << T 12136 << TypeRange; 12137 } 12138 12139 // C++11 [class.friend]p3: 12140 // A friend declaration that does not declare a function shall have one 12141 // of the following forms: 12142 // friend elaborated-type-specifier ; 12143 // friend simple-type-specifier ; 12144 // friend typename-specifier ; 12145 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12146 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12147 } 12148 12149 // If the type specifier in a friend declaration designates a (possibly 12150 // cv-qualified) class type, that class is declared as a friend; otherwise, 12151 // the friend declaration is ignored. 12152 return FriendDecl::Create(Context, CurContext, 12153 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12154 FriendLoc); 12155 } 12156 12157 /// Handle a friend tag declaration where the scope specifier was 12158 /// templated. 12159 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12160 unsigned TagSpec, SourceLocation TagLoc, 12161 CXXScopeSpec &SS, 12162 IdentifierInfo *Name, 12163 SourceLocation NameLoc, 12164 AttributeList *Attr, 12165 MultiTemplateParamsArg TempParamLists) { 12166 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12167 12168 bool isExplicitSpecialization = false; 12169 bool Invalid = false; 12170 12171 if (TemplateParameterList *TemplateParams = 12172 MatchTemplateParametersToScopeSpecifier( 12173 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12174 isExplicitSpecialization, Invalid)) { 12175 if (TemplateParams->size() > 0) { 12176 // This is a declaration of a class template. 12177 if (Invalid) 12178 return nullptr; 12179 12180 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12181 NameLoc, Attr, TemplateParams, AS_public, 12182 /*ModulePrivateLoc=*/SourceLocation(), 12183 FriendLoc, TempParamLists.size() - 1, 12184 TempParamLists.data()).get(); 12185 } else { 12186 // The "template<>" header is extraneous. 12187 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12188 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12189 isExplicitSpecialization = true; 12190 } 12191 } 12192 12193 if (Invalid) return nullptr; 12194 12195 bool isAllExplicitSpecializations = true; 12196 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12197 if (TempParamLists[I]->size()) { 12198 isAllExplicitSpecializations = false; 12199 break; 12200 } 12201 } 12202 12203 // FIXME: don't ignore attributes. 12204 12205 // If it's explicit specializations all the way down, just forget 12206 // about the template header and build an appropriate non-templated 12207 // friend. TODO: for source fidelity, remember the headers. 12208 if (isAllExplicitSpecializations) { 12209 if (SS.isEmpty()) { 12210 bool Owned = false; 12211 bool IsDependent = false; 12212 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12213 Attr, AS_public, 12214 /*ModulePrivateLoc=*/SourceLocation(), 12215 MultiTemplateParamsArg(), Owned, IsDependent, 12216 /*ScopedEnumKWLoc=*/SourceLocation(), 12217 /*ScopedEnumUsesClassTag=*/false, 12218 /*UnderlyingType=*/TypeResult(), 12219 /*IsTypeSpecifier=*/false); 12220 } 12221 12222 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12223 ElaboratedTypeKeyword Keyword 12224 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12225 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12226 *Name, NameLoc); 12227 if (T.isNull()) 12228 return nullptr; 12229 12230 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12231 if (isa<DependentNameType>(T)) { 12232 DependentNameTypeLoc TL = 12233 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12234 TL.setElaboratedKeywordLoc(TagLoc); 12235 TL.setQualifierLoc(QualifierLoc); 12236 TL.setNameLoc(NameLoc); 12237 } else { 12238 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12239 TL.setElaboratedKeywordLoc(TagLoc); 12240 TL.setQualifierLoc(QualifierLoc); 12241 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12242 } 12243 12244 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12245 TSI, FriendLoc, TempParamLists); 12246 Friend->setAccess(AS_public); 12247 CurContext->addDecl(Friend); 12248 return Friend; 12249 } 12250 12251 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12252 12253 12254 12255 // Handle the case of a templated-scope friend class. e.g. 12256 // template <class T> class A<T>::B; 12257 // FIXME: we don't support these right now. 12258 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12259 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12260 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12261 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12262 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12263 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12264 TL.setElaboratedKeywordLoc(TagLoc); 12265 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12266 TL.setNameLoc(NameLoc); 12267 12268 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12269 TSI, FriendLoc, TempParamLists); 12270 Friend->setAccess(AS_public); 12271 Friend->setUnsupportedFriend(true); 12272 CurContext->addDecl(Friend); 12273 return Friend; 12274 } 12275 12276 12277 /// Handle a friend type declaration. This works in tandem with 12278 /// ActOnTag. 12279 /// 12280 /// Notes on friend class templates: 12281 /// 12282 /// We generally treat friend class declarations as if they were 12283 /// declaring a class. So, for example, the elaborated type specifier 12284 /// in a friend declaration is required to obey the restrictions of a 12285 /// class-head (i.e. no typedefs in the scope chain), template 12286 /// parameters are required to match up with simple template-ids, &c. 12287 /// However, unlike when declaring a template specialization, it's 12288 /// okay to refer to a template specialization without an empty 12289 /// template parameter declaration, e.g. 12290 /// friend class A<T>::B<unsigned>; 12291 /// We permit this as a special case; if there are any template 12292 /// parameters present at all, require proper matching, i.e. 12293 /// template <> template \<class T> friend class A<int>::B; 12294 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12295 MultiTemplateParamsArg TempParams) { 12296 SourceLocation Loc = DS.getLocStart(); 12297 12298 assert(DS.isFriendSpecified()); 12299 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12300 12301 // Try to convert the decl specifier to a type. This works for 12302 // friend templates because ActOnTag never produces a ClassTemplateDecl 12303 // for a TUK_Friend. 12304 Declarator TheDeclarator(DS, Declarator::MemberContext); 12305 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12306 QualType T = TSI->getType(); 12307 if (TheDeclarator.isInvalidType()) 12308 return nullptr; 12309 12310 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12311 return nullptr; 12312 12313 // This is definitely an error in C++98. It's probably meant to 12314 // be forbidden in C++0x, too, but the specification is just 12315 // poorly written. 12316 // 12317 // The problem is with declarations like the following: 12318 // template <T> friend A<T>::foo; 12319 // where deciding whether a class C is a friend or not now hinges 12320 // on whether there exists an instantiation of A that causes 12321 // 'foo' to equal C. There are restrictions on class-heads 12322 // (which we declare (by fiat) elaborated friend declarations to 12323 // be) that makes this tractable. 12324 // 12325 // FIXME: handle "template <> friend class A<T>;", which 12326 // is possibly well-formed? Who even knows? 12327 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12328 Diag(Loc, diag::err_tagless_friend_type_template) 12329 << DS.getSourceRange(); 12330 return nullptr; 12331 } 12332 12333 // C++98 [class.friend]p1: A friend of a class is a function 12334 // or class that is not a member of the class . . . 12335 // This is fixed in DR77, which just barely didn't make the C++03 12336 // deadline. It's also a very silly restriction that seriously 12337 // affects inner classes and which nobody else seems to implement; 12338 // thus we never diagnose it, not even in -pedantic. 12339 // 12340 // But note that we could warn about it: it's always useless to 12341 // friend one of your own members (it's not, however, worthless to 12342 // friend a member of an arbitrary specialization of your template). 12343 12344 Decl *D; 12345 if (unsigned NumTempParamLists = TempParams.size()) 12346 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12347 NumTempParamLists, 12348 TempParams.data(), 12349 TSI, 12350 DS.getFriendSpecLoc()); 12351 else 12352 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12353 12354 if (!D) 12355 return nullptr; 12356 12357 D->setAccess(AS_public); 12358 CurContext->addDecl(D); 12359 12360 return D; 12361 } 12362 12363 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12364 MultiTemplateParamsArg TemplateParams) { 12365 const DeclSpec &DS = D.getDeclSpec(); 12366 12367 assert(DS.isFriendSpecified()); 12368 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12369 12370 SourceLocation Loc = D.getIdentifierLoc(); 12371 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12372 12373 // C++ [class.friend]p1 12374 // A friend of a class is a function or class.... 12375 // Note that this sees through typedefs, which is intended. 12376 // It *doesn't* see through dependent types, which is correct 12377 // according to [temp.arg.type]p3: 12378 // If a declaration acquires a function type through a 12379 // type dependent on a template-parameter and this causes 12380 // a declaration that does not use the syntactic form of a 12381 // function declarator to have a function type, the program 12382 // is ill-formed. 12383 if (!TInfo->getType()->isFunctionType()) { 12384 Diag(Loc, diag::err_unexpected_friend); 12385 12386 // It might be worthwhile to try to recover by creating an 12387 // appropriate declaration. 12388 return nullptr; 12389 } 12390 12391 // C++ [namespace.memdef]p3 12392 // - If a friend declaration in a non-local class first declares a 12393 // class or function, the friend class or function is a member 12394 // of the innermost enclosing namespace. 12395 // - The name of the friend is not found by simple name lookup 12396 // until a matching declaration is provided in that namespace 12397 // scope (either before or after the class declaration granting 12398 // friendship). 12399 // - If a friend function is called, its name may be found by the 12400 // name lookup that considers functions from namespaces and 12401 // classes associated with the types of the function arguments. 12402 // - When looking for a prior declaration of a class or a function 12403 // declared as a friend, scopes outside the innermost enclosing 12404 // namespace scope are not considered. 12405 12406 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12407 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12408 DeclarationName Name = NameInfo.getName(); 12409 assert(Name); 12410 12411 // Check for unexpanded parameter packs. 12412 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12413 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12414 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12415 return nullptr; 12416 12417 // The context we found the declaration in, or in which we should 12418 // create the declaration. 12419 DeclContext *DC; 12420 Scope *DCScope = S; 12421 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12422 ForRedeclaration); 12423 12424 // There are five cases here. 12425 // - There's no scope specifier and we're in a local class. Only look 12426 // for functions declared in the immediately-enclosing block scope. 12427 // We recover from invalid scope qualifiers as if they just weren't there. 12428 FunctionDecl *FunctionContainingLocalClass = nullptr; 12429 if ((SS.isInvalid() || !SS.isSet()) && 12430 (FunctionContainingLocalClass = 12431 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12432 // C++11 [class.friend]p11: 12433 // If a friend declaration appears in a local class and the name 12434 // specified is an unqualified name, a prior declaration is 12435 // looked up without considering scopes that are outside the 12436 // innermost enclosing non-class scope. For a friend function 12437 // declaration, if there is no prior declaration, the program is 12438 // ill-formed. 12439 12440 // Find the innermost enclosing non-class scope. This is the block 12441 // scope containing the local class definition (or for a nested class, 12442 // the outer local class). 12443 DCScope = S->getFnParent(); 12444 12445 // Look up the function name in the scope. 12446 Previous.clear(LookupLocalFriendName); 12447 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12448 12449 if (!Previous.empty()) { 12450 // All possible previous declarations must have the same context: 12451 // either they were declared at block scope or they are members of 12452 // one of the enclosing local classes. 12453 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12454 } else { 12455 // This is ill-formed, but provide the context that we would have 12456 // declared the function in, if we were permitted to, for error recovery. 12457 DC = FunctionContainingLocalClass; 12458 } 12459 adjustContextForLocalExternDecl(DC); 12460 12461 // C++ [class.friend]p6: 12462 // A function can be defined in a friend declaration of a class if and 12463 // only if the class is a non-local class (9.8), the function name is 12464 // unqualified, and the function has namespace scope. 12465 if (D.isFunctionDefinition()) { 12466 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12467 } 12468 12469 // - There's no scope specifier, in which case we just go to the 12470 // appropriate scope and look for a function or function template 12471 // there as appropriate. 12472 } else if (SS.isInvalid() || !SS.isSet()) { 12473 // C++11 [namespace.memdef]p3: 12474 // If the name in a friend declaration is neither qualified nor 12475 // a template-id and the declaration is a function or an 12476 // elaborated-type-specifier, the lookup to determine whether 12477 // the entity has been previously declared shall not consider 12478 // any scopes outside the innermost enclosing namespace. 12479 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12480 12481 // Find the appropriate context according to the above. 12482 DC = CurContext; 12483 12484 // Skip class contexts. If someone can cite chapter and verse 12485 // for this behavior, that would be nice --- it's what GCC and 12486 // EDG do, and it seems like a reasonable intent, but the spec 12487 // really only says that checks for unqualified existing 12488 // declarations should stop at the nearest enclosing namespace, 12489 // not that they should only consider the nearest enclosing 12490 // namespace. 12491 while (DC->isRecord()) 12492 DC = DC->getParent(); 12493 12494 DeclContext *LookupDC = DC; 12495 while (LookupDC->isTransparentContext()) 12496 LookupDC = LookupDC->getParent(); 12497 12498 while (true) { 12499 LookupQualifiedName(Previous, LookupDC); 12500 12501 if (!Previous.empty()) { 12502 DC = LookupDC; 12503 break; 12504 } 12505 12506 if (isTemplateId) { 12507 if (isa<TranslationUnitDecl>(LookupDC)) break; 12508 } else { 12509 if (LookupDC->isFileContext()) break; 12510 } 12511 LookupDC = LookupDC->getParent(); 12512 } 12513 12514 DCScope = getScopeForDeclContext(S, DC); 12515 12516 // - There's a non-dependent scope specifier, in which case we 12517 // compute it and do a previous lookup there for a function 12518 // or function template. 12519 } else if (!SS.getScopeRep()->isDependent()) { 12520 DC = computeDeclContext(SS); 12521 if (!DC) return nullptr; 12522 12523 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12524 12525 LookupQualifiedName(Previous, DC); 12526 12527 // Ignore things found implicitly in the wrong scope. 12528 // TODO: better diagnostics for this case. Suggesting the right 12529 // qualified scope would be nice... 12530 LookupResult::Filter F = Previous.makeFilter(); 12531 while (F.hasNext()) { 12532 NamedDecl *D = F.next(); 12533 if (!DC->InEnclosingNamespaceSetOf( 12534 D->getDeclContext()->getRedeclContext())) 12535 F.erase(); 12536 } 12537 F.done(); 12538 12539 if (Previous.empty()) { 12540 D.setInvalidType(); 12541 Diag(Loc, diag::err_qualified_friend_not_found) 12542 << Name << TInfo->getType(); 12543 return nullptr; 12544 } 12545 12546 // C++ [class.friend]p1: A friend of a class is a function or 12547 // class that is not a member of the class . . . 12548 if (DC->Equals(CurContext)) 12549 Diag(DS.getFriendSpecLoc(), 12550 getLangOpts().CPlusPlus11 ? 12551 diag::warn_cxx98_compat_friend_is_member : 12552 diag::err_friend_is_member); 12553 12554 if (D.isFunctionDefinition()) { 12555 // C++ [class.friend]p6: 12556 // A function can be defined in a friend declaration of a class if and 12557 // only if the class is a non-local class (9.8), the function name is 12558 // unqualified, and the function has namespace scope. 12559 SemaDiagnosticBuilder DB 12560 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12561 12562 DB << SS.getScopeRep(); 12563 if (DC->isFileContext()) 12564 DB << FixItHint::CreateRemoval(SS.getRange()); 12565 SS.clear(); 12566 } 12567 12568 // - There's a scope specifier that does not match any template 12569 // parameter lists, in which case we use some arbitrary context, 12570 // create a method or method template, and wait for instantiation. 12571 // - There's a scope specifier that does match some template 12572 // parameter lists, which we don't handle right now. 12573 } else { 12574 if (D.isFunctionDefinition()) { 12575 // C++ [class.friend]p6: 12576 // A function can be defined in a friend declaration of a class if and 12577 // only if the class is a non-local class (9.8), the function name is 12578 // unqualified, and the function has namespace scope. 12579 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12580 << SS.getScopeRep(); 12581 } 12582 12583 DC = CurContext; 12584 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12585 } 12586 12587 if (!DC->isRecord()) { 12588 // This implies that it has to be an operator or function. 12589 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12590 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12591 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12592 Diag(Loc, diag::err_introducing_special_friend) << 12593 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12594 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12595 return nullptr; 12596 } 12597 } 12598 12599 // FIXME: This is an egregious hack to cope with cases where the scope stack 12600 // does not contain the declaration context, i.e., in an out-of-line 12601 // definition of a class. 12602 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12603 if (!DCScope) { 12604 FakeDCScope.setEntity(DC); 12605 DCScope = &FakeDCScope; 12606 } 12607 12608 bool AddToScope = true; 12609 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12610 TemplateParams, AddToScope); 12611 if (!ND) return nullptr; 12612 12613 assert(ND->getLexicalDeclContext() == CurContext); 12614 12615 // If we performed typo correction, we might have added a scope specifier 12616 // and changed the decl context. 12617 DC = ND->getDeclContext(); 12618 12619 // Add the function declaration to the appropriate lookup tables, 12620 // adjusting the redeclarations list as necessary. We don't 12621 // want to do this yet if the friending class is dependent. 12622 // 12623 // Also update the scope-based lookup if the target context's 12624 // lookup context is in lexical scope. 12625 if (!CurContext->isDependentContext()) { 12626 DC = DC->getRedeclContext(); 12627 DC->makeDeclVisibleInContext(ND); 12628 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12629 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12630 } 12631 12632 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12633 D.getIdentifierLoc(), ND, 12634 DS.getFriendSpecLoc()); 12635 FrD->setAccess(AS_public); 12636 CurContext->addDecl(FrD); 12637 12638 if (ND->isInvalidDecl()) { 12639 FrD->setInvalidDecl(); 12640 } else { 12641 if (DC->isRecord()) CheckFriendAccess(ND); 12642 12643 FunctionDecl *FD; 12644 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12645 FD = FTD->getTemplatedDecl(); 12646 else 12647 FD = cast<FunctionDecl>(ND); 12648 12649 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12650 // default argument expression, that declaration shall be a definition 12651 // and shall be the only declaration of the function or function 12652 // template in the translation unit. 12653 if (functionDeclHasDefaultArgument(FD)) { 12654 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12655 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12656 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12657 } else if (!D.isFunctionDefinition()) 12658 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12659 } 12660 12661 // Mark templated-scope function declarations as unsupported. 12662 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12663 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12664 << SS.getScopeRep() << SS.getRange() 12665 << cast<CXXRecordDecl>(CurContext); 12666 FrD->setUnsupportedFriend(true); 12667 } 12668 } 12669 12670 return ND; 12671 } 12672 12673 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12674 AdjustDeclIfTemplate(Dcl); 12675 12676 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12677 if (!Fn) { 12678 Diag(DelLoc, diag::err_deleted_non_function); 12679 return; 12680 } 12681 12682 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12683 // Don't consider the implicit declaration we generate for explicit 12684 // specializations. FIXME: Do not generate these implicit declarations. 12685 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12686 Prev->getPreviousDecl()) && 12687 !Prev->isDefined()) { 12688 Diag(DelLoc, diag::err_deleted_decl_not_first); 12689 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12690 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12691 : diag::note_previous_declaration); 12692 } 12693 // If the declaration wasn't the first, we delete the function anyway for 12694 // recovery. 12695 Fn = Fn->getCanonicalDecl(); 12696 } 12697 12698 // dllimport/dllexport cannot be deleted. 12699 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12700 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12701 Fn->setInvalidDecl(); 12702 } 12703 12704 if (Fn->isDeleted()) 12705 return; 12706 12707 // See if we're deleting a function which is already known to override a 12708 // non-deleted virtual function. 12709 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12710 bool IssuedDiagnostic = false; 12711 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12712 E = MD->end_overridden_methods(); 12713 I != E; ++I) { 12714 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12715 if (!IssuedDiagnostic) { 12716 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12717 IssuedDiagnostic = true; 12718 } 12719 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12720 } 12721 } 12722 } 12723 12724 // C++11 [basic.start.main]p3: 12725 // A program that defines main as deleted [...] is ill-formed. 12726 if (Fn->isMain()) 12727 Diag(DelLoc, diag::err_deleted_main); 12728 12729 Fn->setDeletedAsWritten(); 12730 } 12731 12732 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12733 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12734 12735 if (MD) { 12736 if (MD->getParent()->isDependentType()) { 12737 MD->setDefaulted(); 12738 MD->setExplicitlyDefaulted(); 12739 return; 12740 } 12741 12742 CXXSpecialMember Member = getSpecialMember(MD); 12743 if (Member == CXXInvalid) { 12744 if (!MD->isInvalidDecl()) 12745 Diag(DefaultLoc, diag::err_default_special_members); 12746 return; 12747 } 12748 12749 MD->setDefaulted(); 12750 MD->setExplicitlyDefaulted(); 12751 12752 // If this definition appears within the record, do the checking when 12753 // the record is complete. 12754 const FunctionDecl *Primary = MD; 12755 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12756 // Find the uninstantiated declaration that actually had the '= default' 12757 // on it. 12758 Pattern->isDefined(Primary); 12759 12760 // If the method was defaulted on its first declaration, we will have 12761 // already performed the checking in CheckCompletedCXXClass. Such a 12762 // declaration doesn't trigger an implicit definition. 12763 if (Primary == Primary->getCanonicalDecl()) 12764 return; 12765 12766 CheckExplicitlyDefaultedSpecialMember(MD); 12767 12768 if (MD->isInvalidDecl()) 12769 return; 12770 12771 switch (Member) { 12772 case CXXDefaultConstructor: 12773 DefineImplicitDefaultConstructor(DefaultLoc, 12774 cast<CXXConstructorDecl>(MD)); 12775 break; 12776 case CXXCopyConstructor: 12777 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12778 break; 12779 case CXXCopyAssignment: 12780 DefineImplicitCopyAssignment(DefaultLoc, MD); 12781 break; 12782 case CXXDestructor: 12783 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12784 break; 12785 case CXXMoveConstructor: 12786 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12787 break; 12788 case CXXMoveAssignment: 12789 DefineImplicitMoveAssignment(DefaultLoc, MD); 12790 break; 12791 case CXXInvalid: 12792 llvm_unreachable("Invalid special member."); 12793 } 12794 } else { 12795 Diag(DefaultLoc, diag::err_default_special_members); 12796 } 12797 } 12798 12799 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12800 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12801 Stmt *SubStmt = *CI; 12802 if (!SubStmt) 12803 continue; 12804 if (isa<ReturnStmt>(SubStmt)) 12805 Self.Diag(SubStmt->getLocStart(), 12806 diag::err_return_in_constructor_handler); 12807 if (!isa<Expr>(SubStmt)) 12808 SearchForReturnInStmt(Self, SubStmt); 12809 } 12810 } 12811 12812 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12813 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12814 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12815 SearchForReturnInStmt(*this, Handler); 12816 } 12817 } 12818 12819 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12820 const CXXMethodDecl *Old) { 12821 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12822 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12823 12824 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12825 12826 // If the calling conventions match, everything is fine 12827 if (NewCC == OldCC) 12828 return false; 12829 12830 // If the calling conventions mismatch because the new function is static, 12831 // suppress the calling convention mismatch error; the error about static 12832 // function override (err_static_overrides_virtual from 12833 // Sema::CheckFunctionDeclaration) is more clear. 12834 if (New->getStorageClass() == SC_Static) 12835 return false; 12836 12837 Diag(New->getLocation(), 12838 diag::err_conflicting_overriding_cc_attributes) 12839 << New->getDeclName() << New->getType() << Old->getType(); 12840 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12841 return true; 12842 } 12843 12844 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12845 const CXXMethodDecl *Old) { 12846 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12847 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12848 12849 if (Context.hasSameType(NewTy, OldTy) || 12850 NewTy->isDependentType() || OldTy->isDependentType()) 12851 return false; 12852 12853 // Check if the return types are covariant 12854 QualType NewClassTy, OldClassTy; 12855 12856 /// Both types must be pointers or references to classes. 12857 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12858 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12859 NewClassTy = NewPT->getPointeeType(); 12860 OldClassTy = OldPT->getPointeeType(); 12861 } 12862 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12863 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12864 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12865 NewClassTy = NewRT->getPointeeType(); 12866 OldClassTy = OldRT->getPointeeType(); 12867 } 12868 } 12869 } 12870 12871 // The return types aren't either both pointers or references to a class type. 12872 if (NewClassTy.isNull()) { 12873 Diag(New->getLocation(), 12874 diag::err_different_return_type_for_overriding_virtual_function) 12875 << New->getDeclName() << NewTy << OldTy 12876 << New->getReturnTypeSourceRange(); 12877 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12878 << Old->getReturnTypeSourceRange(); 12879 12880 return true; 12881 } 12882 12883 // C++ [class.virtual]p6: 12884 // If the return type of D::f differs from the return type of B::f, the 12885 // class type in the return type of D::f shall be complete at the point of 12886 // declaration of D::f or shall be the class type D. 12887 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12888 if (!RT->isBeingDefined() && 12889 RequireCompleteType(New->getLocation(), NewClassTy, 12890 diag::err_covariant_return_incomplete, 12891 New->getDeclName())) 12892 return true; 12893 } 12894 12895 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12896 // Check if the new class derives from the old class. 12897 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12898 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12899 << New->getDeclName() << NewTy << OldTy 12900 << New->getReturnTypeSourceRange(); 12901 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12902 << Old->getReturnTypeSourceRange(); 12903 return true; 12904 } 12905 12906 // Check if we the conversion from derived to base is valid. 12907 if (CheckDerivedToBaseConversion( 12908 NewClassTy, OldClassTy, 12909 diag::err_covariant_return_inaccessible_base, 12910 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12911 New->getLocation(), New->getReturnTypeSourceRange(), 12912 New->getDeclName(), nullptr)) { 12913 // FIXME: this note won't trigger for delayed access control 12914 // diagnostics, and it's impossible to get an undelayed error 12915 // here from access control during the original parse because 12916 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12917 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12918 << Old->getReturnTypeSourceRange(); 12919 return true; 12920 } 12921 } 12922 12923 // The qualifiers of the return types must be the same. 12924 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12925 Diag(New->getLocation(), 12926 diag::err_covariant_return_type_different_qualifications) 12927 << New->getDeclName() << NewTy << OldTy 12928 << New->getReturnTypeSourceRange(); 12929 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12930 << Old->getReturnTypeSourceRange(); 12931 return true; 12932 }; 12933 12934 12935 // The new class type must have the same or less qualifiers as the old type. 12936 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12937 Diag(New->getLocation(), 12938 diag::err_covariant_return_type_class_type_more_qualified) 12939 << New->getDeclName() << NewTy << OldTy 12940 << New->getReturnTypeSourceRange(); 12941 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12942 << Old->getReturnTypeSourceRange(); 12943 return true; 12944 }; 12945 12946 return false; 12947 } 12948 12949 /// \brief Mark the given method pure. 12950 /// 12951 /// \param Method the method to be marked pure. 12952 /// 12953 /// \param InitRange the source range that covers the "0" initializer. 12954 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12955 SourceLocation EndLoc = InitRange.getEnd(); 12956 if (EndLoc.isValid()) 12957 Method->setRangeEnd(EndLoc); 12958 12959 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12960 Method->setPure(); 12961 return false; 12962 } 12963 12964 if (!Method->isInvalidDecl()) 12965 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12966 << Method->getDeclName() << InitRange; 12967 return true; 12968 } 12969 12970 /// \brief Determine whether the given declaration is a static data member. 12971 static bool isStaticDataMember(const Decl *D) { 12972 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12973 return Var->isStaticDataMember(); 12974 12975 return false; 12976 } 12977 12978 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12979 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12980 /// is a fresh scope pushed for just this purpose. 12981 /// 12982 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12983 /// static data member of class X, names should be looked up in the scope of 12984 /// class X. 12985 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12986 // If there is no declaration, there was an error parsing it. 12987 if (!D || D->isInvalidDecl()) 12988 return; 12989 12990 // We will always have a nested name specifier here, but this declaration 12991 // might not be out of line if the specifier names the current namespace: 12992 // extern int n; 12993 // int ::n = 0; 12994 if (D->isOutOfLine()) 12995 EnterDeclaratorContext(S, D->getDeclContext()); 12996 12997 // If we are parsing the initializer for a static data member, push a 12998 // new expression evaluation context that is associated with this static 12999 // data member. 13000 if (isStaticDataMember(D)) 13001 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 13002 } 13003 13004 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 13005 /// initializer for the out-of-line declaration 'D'. 13006 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 13007 // If there is no declaration, there was an error parsing it. 13008 if (!D || D->isInvalidDecl()) 13009 return; 13010 13011 if (isStaticDataMember(D)) 13012 PopExpressionEvaluationContext(); 13013 13014 if (D->isOutOfLine()) 13015 ExitDeclaratorContext(S); 13016 } 13017 13018 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 13019 /// C++ if/switch/while/for statement. 13020 /// e.g: "if (int x = f()) {...}" 13021 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 13022 // C++ 6.4p2: 13023 // The declarator shall not specify a function or an array. 13024 // The type-specifier-seq shall not contain typedef and shall not declare a 13025 // new class or enumeration. 13026 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 13027 "Parser allowed 'typedef' as storage class of condition decl."); 13028 13029 Decl *Dcl = ActOnDeclarator(S, D); 13030 if (!Dcl) 13031 return true; 13032 13033 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 13034 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 13035 << D.getSourceRange(); 13036 return true; 13037 } 13038 13039 return Dcl; 13040 } 13041 13042 void Sema::LoadExternalVTableUses() { 13043 if (!ExternalSource) 13044 return; 13045 13046 SmallVector<ExternalVTableUse, 4> VTables; 13047 ExternalSource->ReadUsedVTables(VTables); 13048 SmallVector<VTableUse, 4> NewUses; 13049 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 13050 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 13051 = VTablesUsed.find(VTables[I].Record); 13052 // Even if a definition wasn't required before, it may be required now. 13053 if (Pos != VTablesUsed.end()) { 13054 if (!Pos->second && VTables[I].DefinitionRequired) 13055 Pos->second = true; 13056 continue; 13057 } 13058 13059 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 13060 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 13061 } 13062 13063 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 13064 } 13065 13066 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 13067 bool DefinitionRequired) { 13068 // Ignore any vtable uses in unevaluated operands or for classes that do 13069 // not have a vtable. 13070 if (!Class->isDynamicClass() || Class->isDependentContext() || 13071 CurContext->isDependentContext() || isUnevaluatedContext()) 13072 return; 13073 13074 // Try to insert this class into the map. 13075 LoadExternalVTableUses(); 13076 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13077 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 13078 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 13079 if (!Pos.second) { 13080 // If we already had an entry, check to see if we are promoting this vtable 13081 // to require a definition. If so, we need to reappend to the VTableUses 13082 // list, since we may have already processed the first entry. 13083 if (DefinitionRequired && !Pos.first->second) { 13084 Pos.first->second = true; 13085 } else { 13086 // Otherwise, we can early exit. 13087 return; 13088 } 13089 } else { 13090 // The Microsoft ABI requires that we perform the destructor body 13091 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 13092 // the deleting destructor is emitted with the vtable, not with the 13093 // destructor definition as in the Itanium ABI. 13094 // If it has a definition, we do the check at that point instead. 13095 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13096 Class->hasUserDeclaredDestructor() && 13097 !Class->getDestructor()->isDefined() && 13098 !Class->getDestructor()->isDeleted()) { 13099 CXXDestructorDecl *DD = Class->getDestructor(); 13100 ContextRAII SavedContext(*this, DD); 13101 CheckDestructor(DD); 13102 } 13103 } 13104 13105 // Local classes need to have their virtual members marked 13106 // immediately. For all other classes, we mark their virtual members 13107 // at the end of the translation unit. 13108 if (Class->isLocalClass()) 13109 MarkVirtualMembersReferenced(Loc, Class); 13110 else 13111 VTableUses.push_back(std::make_pair(Class, Loc)); 13112 } 13113 13114 bool Sema::DefineUsedVTables() { 13115 LoadExternalVTableUses(); 13116 if (VTableUses.empty()) 13117 return false; 13118 13119 // Note: The VTableUses vector could grow as a result of marking 13120 // the members of a class as "used", so we check the size each 13121 // time through the loop and prefer indices (which are stable) to 13122 // iterators (which are not). 13123 bool DefinedAnything = false; 13124 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13125 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13126 if (!Class) 13127 continue; 13128 13129 SourceLocation Loc = VTableUses[I].second; 13130 13131 bool DefineVTable = true; 13132 13133 // If this class has a key function, but that key function is 13134 // defined in another translation unit, we don't need to emit the 13135 // vtable even though we're using it. 13136 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13137 if (KeyFunction && !KeyFunction->hasBody()) { 13138 // The key function is in another translation unit. 13139 DefineVTable = false; 13140 TemplateSpecializationKind TSK = 13141 KeyFunction->getTemplateSpecializationKind(); 13142 assert(TSK != TSK_ExplicitInstantiationDefinition && 13143 TSK != TSK_ImplicitInstantiation && 13144 "Instantiations don't have key functions"); 13145 (void)TSK; 13146 } else if (!KeyFunction) { 13147 // If we have a class with no key function that is the subject 13148 // of an explicit instantiation declaration, suppress the 13149 // vtable; it will live with the explicit instantiation 13150 // definition. 13151 bool IsExplicitInstantiationDeclaration 13152 = Class->getTemplateSpecializationKind() 13153 == TSK_ExplicitInstantiationDeclaration; 13154 for (auto R : Class->redecls()) { 13155 TemplateSpecializationKind TSK 13156 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13157 if (TSK == TSK_ExplicitInstantiationDeclaration) 13158 IsExplicitInstantiationDeclaration = true; 13159 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13160 IsExplicitInstantiationDeclaration = false; 13161 break; 13162 } 13163 } 13164 13165 if (IsExplicitInstantiationDeclaration) 13166 DefineVTable = false; 13167 } 13168 13169 // The exception specifications for all virtual members may be needed even 13170 // if we are not providing an authoritative form of the vtable in this TU. 13171 // We may choose to emit it available_externally anyway. 13172 if (!DefineVTable) { 13173 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13174 continue; 13175 } 13176 13177 // Mark all of the virtual members of this class as referenced, so 13178 // that we can build a vtable. Then, tell the AST consumer that a 13179 // vtable for this class is required. 13180 DefinedAnything = true; 13181 MarkVirtualMembersReferenced(Loc, Class); 13182 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13183 if (VTablesUsed[Canonical]) 13184 Consumer.HandleVTable(Class); 13185 13186 // Optionally warn if we're emitting a weak vtable. 13187 if (Class->isExternallyVisible() && 13188 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13189 const FunctionDecl *KeyFunctionDef = nullptr; 13190 if (!KeyFunction || 13191 (KeyFunction->hasBody(KeyFunctionDef) && 13192 KeyFunctionDef->isInlined())) 13193 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13194 TSK_ExplicitInstantiationDefinition 13195 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13196 << Class; 13197 } 13198 } 13199 VTableUses.clear(); 13200 13201 return DefinedAnything; 13202 } 13203 13204 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13205 const CXXRecordDecl *RD) { 13206 for (const auto *I : RD->methods()) 13207 if (I->isVirtual() && !I->isPure()) 13208 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13209 } 13210 13211 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13212 const CXXRecordDecl *RD) { 13213 // Mark all functions which will appear in RD's vtable as used. 13214 CXXFinalOverriderMap FinalOverriders; 13215 RD->getFinalOverriders(FinalOverriders); 13216 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13217 E = FinalOverriders.end(); 13218 I != E; ++I) { 13219 for (OverridingMethods::const_iterator OI = I->second.begin(), 13220 OE = I->second.end(); 13221 OI != OE; ++OI) { 13222 assert(OI->second.size() > 0 && "no final overrider"); 13223 CXXMethodDecl *Overrider = OI->second.front().Method; 13224 13225 // C++ [basic.def.odr]p2: 13226 // [...] A virtual member function is used if it is not pure. [...] 13227 if (!Overrider->isPure()) 13228 MarkFunctionReferenced(Loc, Overrider); 13229 } 13230 } 13231 13232 // Only classes that have virtual bases need a VTT. 13233 if (RD->getNumVBases() == 0) 13234 return; 13235 13236 for (const auto &I : RD->bases()) { 13237 const CXXRecordDecl *Base = 13238 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13239 if (Base->getNumVBases() == 0) 13240 continue; 13241 MarkVirtualMembersReferenced(Loc, Base); 13242 } 13243 } 13244 13245 /// SetIvarInitializers - This routine builds initialization ASTs for the 13246 /// Objective-C implementation whose ivars need be initialized. 13247 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13248 if (!getLangOpts().CPlusPlus) 13249 return; 13250 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13251 SmallVector<ObjCIvarDecl*, 8> ivars; 13252 CollectIvarsToConstructOrDestruct(OID, ivars); 13253 if (ivars.empty()) 13254 return; 13255 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13256 for (unsigned i = 0; i < ivars.size(); i++) { 13257 FieldDecl *Field = ivars[i]; 13258 if (Field->isInvalidDecl()) 13259 continue; 13260 13261 CXXCtorInitializer *Member; 13262 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13263 InitializationKind InitKind = 13264 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13265 13266 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13267 ExprResult MemberInit = 13268 InitSeq.Perform(*this, InitEntity, InitKind, None); 13269 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13270 // Note, MemberInit could actually come back empty if no initialization 13271 // is required (e.g., because it would call a trivial default constructor) 13272 if (!MemberInit.get() || MemberInit.isInvalid()) 13273 continue; 13274 13275 Member = 13276 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13277 SourceLocation(), 13278 MemberInit.getAs<Expr>(), 13279 SourceLocation()); 13280 AllToInit.push_back(Member); 13281 13282 // Be sure that the destructor is accessible and is marked as referenced. 13283 if (const RecordType *RecordTy = 13284 Context.getBaseElementType(Field->getType()) 13285 ->getAs<RecordType>()) { 13286 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13287 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13288 MarkFunctionReferenced(Field->getLocation(), Destructor); 13289 CheckDestructorAccess(Field->getLocation(), Destructor, 13290 PDiag(diag::err_access_dtor_ivar) 13291 << Context.getBaseElementType(Field->getType())); 13292 } 13293 } 13294 } 13295 ObjCImplementation->setIvarInitializers(Context, 13296 AllToInit.data(), AllToInit.size()); 13297 } 13298 } 13299 13300 static 13301 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13302 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13303 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13304 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13305 Sema &S) { 13306 if (Ctor->isInvalidDecl()) 13307 return; 13308 13309 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13310 13311 // Target may not be determinable yet, for instance if this is a dependent 13312 // call in an uninstantiated template. 13313 if (Target) { 13314 const FunctionDecl *FNTarget = nullptr; 13315 (void)Target->hasBody(FNTarget); 13316 Target = const_cast<CXXConstructorDecl*>( 13317 cast_or_null<CXXConstructorDecl>(FNTarget)); 13318 } 13319 13320 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13321 // Avoid dereferencing a null pointer here. 13322 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13323 13324 if (!Current.insert(Canonical).second) 13325 return; 13326 13327 // We know that beyond here, we aren't chaining into a cycle. 13328 if (!Target || !Target->isDelegatingConstructor() || 13329 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13330 Valid.insert(Current.begin(), Current.end()); 13331 Current.clear(); 13332 // We've hit a cycle. 13333 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13334 Current.count(TCanonical)) { 13335 // If we haven't diagnosed this cycle yet, do so now. 13336 if (!Invalid.count(TCanonical)) { 13337 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13338 diag::warn_delegating_ctor_cycle) 13339 << Ctor; 13340 13341 // Don't add a note for a function delegating directly to itself. 13342 if (TCanonical != Canonical) 13343 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13344 13345 CXXConstructorDecl *C = Target; 13346 while (C->getCanonicalDecl() != Canonical) { 13347 const FunctionDecl *FNTarget = nullptr; 13348 (void)C->getTargetConstructor()->hasBody(FNTarget); 13349 assert(FNTarget && "Ctor cycle through bodiless function"); 13350 13351 C = const_cast<CXXConstructorDecl*>( 13352 cast<CXXConstructorDecl>(FNTarget)); 13353 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13354 } 13355 } 13356 13357 Invalid.insert(Current.begin(), Current.end()); 13358 Current.clear(); 13359 } else { 13360 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13361 } 13362 } 13363 13364 13365 void Sema::CheckDelegatingCtorCycles() { 13366 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13367 13368 for (DelegatingCtorDeclsType::iterator 13369 I = DelegatingCtorDecls.begin(ExternalSource), 13370 E = DelegatingCtorDecls.end(); 13371 I != E; ++I) 13372 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13373 13374 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13375 CE = Invalid.end(); 13376 CI != CE; ++CI) 13377 (*CI)->setInvalidDecl(); 13378 } 13379 13380 namespace { 13381 /// \brief AST visitor that finds references to the 'this' expression. 13382 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13383 Sema &S; 13384 13385 public: 13386 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13387 13388 bool VisitCXXThisExpr(CXXThisExpr *E) { 13389 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13390 << E->isImplicit(); 13391 return false; 13392 } 13393 }; 13394 } 13395 13396 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13397 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13398 if (!TSInfo) 13399 return false; 13400 13401 TypeLoc TL = TSInfo->getTypeLoc(); 13402 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13403 if (!ProtoTL) 13404 return false; 13405 13406 // C++11 [expr.prim.general]p3: 13407 // [The expression this] shall not appear before the optional 13408 // cv-qualifier-seq and it shall not appear within the declaration of a 13409 // static member function (although its type and value category are defined 13410 // within a static member function as they are within a non-static member 13411 // function). [ Note: this is because declaration matching does not occur 13412 // until the complete declarator is known. - end note ] 13413 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13414 FindCXXThisExpr Finder(*this); 13415 13416 // If the return type came after the cv-qualifier-seq, check it now. 13417 if (Proto->hasTrailingReturn() && 13418 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13419 return true; 13420 13421 // Check the exception specification. 13422 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13423 return true; 13424 13425 return checkThisInStaticMemberFunctionAttributes(Method); 13426 } 13427 13428 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13429 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13430 if (!TSInfo) 13431 return false; 13432 13433 TypeLoc TL = TSInfo->getTypeLoc(); 13434 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13435 if (!ProtoTL) 13436 return false; 13437 13438 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13439 FindCXXThisExpr Finder(*this); 13440 13441 switch (Proto->getExceptionSpecType()) { 13442 case EST_Unparsed: 13443 case EST_Uninstantiated: 13444 case EST_Unevaluated: 13445 case EST_BasicNoexcept: 13446 case EST_DynamicNone: 13447 case EST_MSAny: 13448 case EST_None: 13449 break; 13450 13451 case EST_ComputedNoexcept: 13452 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13453 return true; 13454 13455 case EST_Dynamic: 13456 for (const auto &E : Proto->exceptions()) { 13457 if (!Finder.TraverseType(E)) 13458 return true; 13459 } 13460 break; 13461 } 13462 13463 return false; 13464 } 13465 13466 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13467 FindCXXThisExpr Finder(*this); 13468 13469 // Check attributes. 13470 for (const auto *A : Method->attrs()) { 13471 // FIXME: This should be emitted by tblgen. 13472 Expr *Arg = nullptr; 13473 ArrayRef<Expr *> Args; 13474 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13475 Arg = G->getArg(); 13476 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13477 Arg = G->getArg(); 13478 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13479 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13480 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13481 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13482 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13483 Arg = ETLF->getSuccessValue(); 13484 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13485 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13486 Arg = STLF->getSuccessValue(); 13487 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13488 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13489 Arg = LR->getArg(); 13490 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13491 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13492 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13493 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13494 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13495 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13496 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13497 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13498 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13499 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13500 13501 if (Arg && !Finder.TraverseStmt(Arg)) 13502 return true; 13503 13504 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13505 if (!Finder.TraverseStmt(Args[I])) 13506 return true; 13507 } 13508 } 13509 13510 return false; 13511 } 13512 13513 void Sema::checkExceptionSpecification( 13514 bool IsTopLevel, ExceptionSpecificationType EST, 13515 ArrayRef<ParsedType> DynamicExceptions, 13516 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13517 SmallVectorImpl<QualType> &Exceptions, 13518 FunctionProtoType::ExceptionSpecInfo &ESI) { 13519 Exceptions.clear(); 13520 ESI.Type = EST; 13521 if (EST == EST_Dynamic) { 13522 Exceptions.reserve(DynamicExceptions.size()); 13523 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13524 // FIXME: Preserve type source info. 13525 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13526 13527 if (IsTopLevel) { 13528 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13529 collectUnexpandedParameterPacks(ET, Unexpanded); 13530 if (!Unexpanded.empty()) { 13531 DiagnoseUnexpandedParameterPacks( 13532 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13533 Unexpanded); 13534 continue; 13535 } 13536 } 13537 13538 // Check that the type is valid for an exception spec, and 13539 // drop it if not. 13540 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13541 Exceptions.push_back(ET); 13542 } 13543 ESI.Exceptions = Exceptions; 13544 return; 13545 } 13546 13547 if (EST == EST_ComputedNoexcept) { 13548 // If an error occurred, there's no expression here. 13549 if (NoexceptExpr) { 13550 assert((NoexceptExpr->isTypeDependent() || 13551 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13552 Context.BoolTy) && 13553 "Parser should have made sure that the expression is boolean"); 13554 if (IsTopLevel && NoexceptExpr && 13555 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13556 ESI.Type = EST_BasicNoexcept; 13557 return; 13558 } 13559 13560 if (!NoexceptExpr->isValueDependent()) 13561 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13562 diag::err_noexcept_needs_constant_expression, 13563 /*AllowFold*/ false).get(); 13564 ESI.NoexceptExpr = NoexceptExpr; 13565 } 13566 return; 13567 } 13568 } 13569 13570 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13571 ExceptionSpecificationType EST, 13572 SourceRange SpecificationRange, 13573 ArrayRef<ParsedType> DynamicExceptions, 13574 ArrayRef<SourceRange> DynamicExceptionRanges, 13575 Expr *NoexceptExpr) { 13576 if (!MethodD) 13577 return; 13578 13579 // Dig out the method we're referring to. 13580 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13581 MethodD = FunTmpl->getTemplatedDecl(); 13582 13583 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13584 if (!Method) 13585 return; 13586 13587 // Check the exception specification. 13588 llvm::SmallVector<QualType, 4> Exceptions; 13589 FunctionProtoType::ExceptionSpecInfo ESI; 13590 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13591 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13592 ESI); 13593 13594 // Update the exception specification on the function type. 13595 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13596 13597 if (Method->isStatic()) 13598 checkThisInStaticMemberFunctionExceptionSpec(Method); 13599 13600 if (Method->isVirtual()) { 13601 // Check overrides, which we previously had to delay. 13602 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13603 OEnd = Method->end_overridden_methods(); 13604 O != OEnd; ++O) 13605 CheckOverridingFunctionExceptionSpec(Method, *O); 13606 } 13607 } 13608 13609 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13610 /// 13611 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13612 SourceLocation DeclStart, 13613 Declarator &D, Expr *BitWidth, 13614 InClassInitStyle InitStyle, 13615 AccessSpecifier AS, 13616 AttributeList *MSPropertyAttr) { 13617 IdentifierInfo *II = D.getIdentifier(); 13618 if (!II) { 13619 Diag(DeclStart, diag::err_anonymous_property); 13620 return nullptr; 13621 } 13622 SourceLocation Loc = D.getIdentifierLoc(); 13623 13624 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13625 QualType T = TInfo->getType(); 13626 if (getLangOpts().CPlusPlus) { 13627 CheckExtraCXXDefaultArguments(D); 13628 13629 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13630 UPPC_DataMemberType)) { 13631 D.setInvalidType(); 13632 T = Context.IntTy; 13633 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13634 } 13635 } 13636 13637 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13638 13639 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13640 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13641 diag::err_invalid_thread) 13642 << DeclSpec::getSpecifierName(TSCS); 13643 13644 // Check to see if this name was declared as a member previously 13645 NamedDecl *PrevDecl = nullptr; 13646 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13647 LookupName(Previous, S); 13648 switch (Previous.getResultKind()) { 13649 case LookupResult::Found: 13650 case LookupResult::FoundUnresolvedValue: 13651 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13652 break; 13653 13654 case LookupResult::FoundOverloaded: 13655 PrevDecl = Previous.getRepresentativeDecl(); 13656 break; 13657 13658 case LookupResult::NotFound: 13659 case LookupResult::NotFoundInCurrentInstantiation: 13660 case LookupResult::Ambiguous: 13661 break; 13662 } 13663 13664 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13665 // Maybe we will complain about the shadowed template parameter. 13666 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13667 // Just pretend that we didn't see the previous declaration. 13668 PrevDecl = nullptr; 13669 } 13670 13671 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13672 PrevDecl = nullptr; 13673 13674 SourceLocation TSSL = D.getLocStart(); 13675 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13676 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13677 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13678 ProcessDeclAttributes(TUScope, NewPD, D); 13679 NewPD->setAccess(AS); 13680 13681 if (NewPD->isInvalidDecl()) 13682 Record->setInvalidDecl(); 13683 13684 if (D.getDeclSpec().isModulePrivateSpecified()) 13685 NewPD->setModulePrivate(); 13686 13687 if (NewPD->isInvalidDecl() && PrevDecl) { 13688 // Don't introduce NewFD into scope; there's already something 13689 // with the same name in the same scope. 13690 } else if (II) { 13691 PushOnScopeChains(NewPD, S); 13692 } else 13693 Record->addDecl(NewPD); 13694 13695 return NewPD; 13696 } 13697