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/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Lex/LiteralSupport.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Sema/CXXFieldCollector.h" 32 #include "clang/Sema/DeclSpec.h" 33 #include "clang/Sema/Initialization.h" 34 #include "clang/Sema/Lookup.h" 35 #include "clang/Sema/ParsedTemplate.h" 36 #include "clang/Sema/Scope.h" 37 #include "clang/Sema/ScopeInfo.h" 38 #include "clang/Sema/SemaInternal.h" 39 #include "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include "llvm/ADT/StringExtras.h" 43 #include <map> 44 #include <set> 45 46 using namespace clang; 47 48 //===----------------------------------------------------------------------===// 49 // CheckDefaultArgumentVisitor 50 //===----------------------------------------------------------------------===// 51 52 namespace { 53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 54 /// the default argument of a parameter to determine whether it 55 /// contains any ill-formed subexpressions. For example, this will 56 /// diagnose the use of local variables or parameters within the 57 /// default argument expression. 58 class CheckDefaultArgumentVisitor 59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 60 Expr *DefaultArg; 61 Sema *S; 62 63 public: 64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 65 : DefaultArg(defarg), S(s) {} 66 67 bool VisitExpr(Expr *Node); 68 bool VisitDeclRefExpr(DeclRefExpr *DRE); 69 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 70 bool VisitLambdaExpr(LambdaExpr *Lambda); 71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 72 }; 73 74 /// VisitExpr - Visit all of the children of this expression. 75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 76 bool IsInvalid = false; 77 for (Stmt *SubStmt : Node->children()) 78 IsInvalid |= Visit(SubStmt); 79 return IsInvalid; 80 } 81 82 /// VisitDeclRefExpr - Visit a reference to a declaration, to 83 /// determine whether this declaration can be used in the default 84 /// argument expression. 85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 86 NamedDecl *Decl = DRE->getDecl(); 87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 88 // C++ [dcl.fct.default]p9 89 // Default arguments are evaluated each time the function is 90 // called. The order of evaluation of function arguments is 91 // unspecified. Consequently, parameters of a function shall not 92 // be used in default argument expressions, even if they are not 93 // evaluated. Parameters of a function declared before a default 94 // argument expression are in scope and can hide namespace and 95 // class member names. 96 return S->Diag(DRE->getLocStart(), 97 diag::err_param_default_argument_references_param) 98 << Param->getDeclName() << DefaultArg->getSourceRange(); 99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 100 // C++ [dcl.fct.default]p7 101 // Local variables shall not be used in default argument 102 // expressions. 103 if (VDecl->isLocalVarDecl()) 104 return S->Diag(DRE->getLocStart(), 105 diag::err_param_default_argument_references_local) 106 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 107 } 108 109 return false; 110 } 111 112 /// VisitCXXThisExpr - Visit a C++ "this" expression. 113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 114 // C++ [dcl.fct.default]p8: 115 // The keyword this shall not be used in a default argument of a 116 // member function. 117 return S->Diag(ThisE->getLocStart(), 118 diag::err_param_default_argument_references_this) 119 << ThisE->getSourceRange(); 120 } 121 122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 123 bool Invalid = false; 124 for (PseudoObjectExpr::semantics_iterator 125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 126 Expr *E = *i; 127 128 // Look through bindings. 129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 130 E = OVE->getSourceExpr(); 131 assert(E && "pseudo-object binding without source expression?"); 132 } 133 134 Invalid |= Visit(E); 135 } 136 return Invalid; 137 } 138 139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 140 // C++11 [expr.lambda.prim]p13: 141 // A lambda-expression appearing in a default argument shall not 142 // implicitly or explicitly capture any entity. 143 if (Lambda->capture_begin() == Lambda->capture_end()) 144 return false; 145 146 return S->Diag(Lambda->getLocStart(), 147 diag::err_lambda_capture_default_arg); 148 } 149 } 150 151 void 152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 153 const CXXMethodDecl *Method) { 154 // If we have an MSAny spec already, don't bother. 155 if (!Method || ComputedEST == EST_MSAny) 156 return; 157 158 const FunctionProtoType *Proto 159 = Method->getType()->getAs<FunctionProtoType>(); 160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 161 if (!Proto) 162 return; 163 164 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 165 166 // If we have a throw-all spec at this point, ignore the function. 167 if (ComputedEST == EST_None) 168 return; 169 170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 171 EST = EST_BasicNoexcept; 172 173 switch(EST) { 174 // If this function can throw any exceptions, make a note of that. 175 case EST_MSAny: 176 case EST_None: 177 ClearExceptions(); 178 ComputedEST = EST; 179 return; 180 // FIXME: If the call to this decl is using any of its default arguments, we 181 // need to search them for potentially-throwing calls. 182 // If this function has a basic noexcept, it doesn't affect the outcome. 183 case EST_BasicNoexcept: 184 return; 185 // If we're still at noexcept(true) and there's a nothrow() callee, 186 // change to that specification. 187 case EST_DynamicNone: 188 if (ComputedEST == EST_BasicNoexcept) 189 ComputedEST = EST_DynamicNone; 190 return; 191 // Check out noexcept specs. 192 case EST_ComputedNoexcept: 193 { 194 FunctionProtoType::NoexceptResult NR = 195 Proto->getNoexceptSpec(Self->Context); 196 assert(NR != FunctionProtoType::NR_NoNoexcept && 197 "Must have noexcept result for EST_ComputedNoexcept."); 198 assert(NR != FunctionProtoType::NR_Dependent && 199 "Should not generate implicit declarations for dependent cases, " 200 "and don't know how to handle them anyway."); 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 default: 210 break; 211 } 212 assert(EST == EST_Dynamic && "EST case not considered earlier."); 213 assert(ComputedEST != EST_None && 214 "Shouldn't collect exceptions when throw-all is guaranteed."); 215 ComputedEST = EST_Dynamic; 216 // Record the exceptions in this function's exception specification. 217 for (const auto &E : Proto->exceptions()) 218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 219 Exceptions.push_back(E); 220 } 221 222 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 223 if (!E || ComputedEST == EST_MSAny) 224 return; 225 226 // FIXME: 227 // 228 // C++0x [except.spec]p14: 229 // [An] implicit exception-specification specifies the type-id T if and 230 // only if T is allowed by the exception-specification of a function directly 231 // invoked by f's implicit definition; f shall allow all exceptions if any 232 // function it directly invokes allows all exceptions, and f shall allow no 233 // exceptions if every function it directly invokes allows no exceptions. 234 // 235 // Note in particular that if an implicit exception-specification is generated 236 // for a function containing a throw-expression, that specification can still 237 // be noexcept(true). 238 // 239 // Note also that 'directly invoked' is not defined in the standard, and there 240 // is no indication that we should only consider potentially-evaluated calls. 241 // 242 // Ultimately we should implement the intent of the standard: the exception 243 // specification should be the set of exceptions which can be thrown by the 244 // implicit definition. For now, we assume that any non-nothrow expression can 245 // throw any exception. 246 247 if (Self->canThrow(E)) 248 ComputedEST = EST_None; 249 } 250 251 bool 252 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 253 SourceLocation EqualLoc) { 254 if (RequireCompleteType(Param->getLocation(), Param->getType(), 255 diag::err_typecheck_decl_incomplete_type)) { 256 Param->setInvalidDecl(); 257 return true; 258 } 259 260 // C++ [dcl.fct.default]p5 261 // A default argument expression is implicitly converted (clause 262 // 4) to the parameter type. The default argument expression has 263 // the same semantic constraints as the initializer expression in 264 // a declaration of a variable of the parameter type, using the 265 // copy-initialization semantics (8.5). 266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 267 Param); 268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 269 EqualLoc); 270 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 272 if (Result.isInvalid()) 273 return true; 274 Arg = Result.getAs<Expr>(); 275 276 CheckCompletedExpr(Arg, EqualLoc); 277 Arg = MaybeCreateExprWithCleanups(Arg); 278 279 // Okay: add the default argument to the parameter 280 Param->setDefaultArg(Arg); 281 282 // We have already instantiated this parameter; provide each of the 283 // instantiations with the uninstantiated default argument. 284 UnparsedDefaultArgInstantiationsMap::iterator InstPos 285 = UnparsedDefaultArgInstantiations.find(Param); 286 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 289 290 // We're done tracking this parameter's instantiations. 291 UnparsedDefaultArgInstantiations.erase(InstPos); 292 } 293 294 return false; 295 } 296 297 /// ActOnParamDefaultArgument - Check whether the default argument 298 /// provided for a function parameter is well-formed. If so, attach it 299 /// to the parameter declaration. 300 void 301 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 302 Expr *DefaultArg) { 303 if (!param || !DefaultArg) 304 return; 305 306 ParmVarDecl *Param = cast<ParmVarDecl>(param); 307 UnparsedDefaultArgLocs.erase(Param); 308 309 // Default arguments are only permitted in C++ 310 if (!getLangOpts().CPlusPlus) { 311 Diag(EqualLoc, diag::err_param_default_argument) 312 << DefaultArg->getSourceRange(); 313 Param->setInvalidDecl(); 314 return; 315 } 316 317 // Check for unexpanded parameter packs. 318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 319 Param->setInvalidDecl(); 320 return; 321 } 322 323 // C++11 [dcl.fct.default]p3 324 // A default argument expression [...] shall not be specified for a 325 // parameter pack. 326 if (Param->isParameterPack()) { 327 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 328 << DefaultArg->getSourceRange(); 329 return; 330 } 331 332 // Check that the default argument is well-formed 333 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 334 if (DefaultArgChecker.Visit(DefaultArg)) { 335 Param->setInvalidDecl(); 336 return; 337 } 338 339 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 340 } 341 342 /// ActOnParamUnparsedDefaultArgument - We've seen a default 343 /// argument for a function parameter, but we can't parse it yet 344 /// because we're inside a class definition. Note that this default 345 /// argument will be parsed later. 346 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 347 SourceLocation EqualLoc, 348 SourceLocation ArgLoc) { 349 if (!param) 350 return; 351 352 ParmVarDecl *Param = cast<ParmVarDecl>(param); 353 Param->setUnparsedDefaultArg(); 354 UnparsedDefaultArgLocs[Param] = ArgLoc; 355 } 356 357 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 358 /// the default argument for the parameter param failed. 359 void Sema::ActOnParamDefaultArgumentError(Decl *param, 360 SourceLocation EqualLoc) { 361 if (!param) 362 return; 363 364 ParmVarDecl *Param = cast<ParmVarDecl>(param); 365 Param->setInvalidDecl(); 366 UnparsedDefaultArgLocs.erase(Param); 367 Param->setDefaultArg(new(Context) 368 OpaqueValueExpr(EqualLoc, 369 Param->getType().getNonReferenceType(), 370 VK_RValue)); 371 } 372 373 /// CheckExtraCXXDefaultArguments - Check for any extra default 374 /// arguments in the declarator, which is not a function declaration 375 /// or definition and therefore is not permitted to have default 376 /// arguments. This routine should be invoked for every declarator 377 /// that is not a function declaration or definition. 378 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 379 // C++ [dcl.fct.default]p3 380 // A default argument expression shall be specified only in the 381 // parameter-declaration-clause of a function declaration or in a 382 // template-parameter (14.1). It shall not be specified for a 383 // parameter pack. If it is specified in a 384 // parameter-declaration-clause, it shall not occur within a 385 // declarator or abstract-declarator of a parameter-declaration. 386 bool MightBeFunction = D.isFunctionDeclarationContext(); 387 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 388 DeclaratorChunk &chunk = D.getTypeObject(i); 389 if (chunk.Kind == DeclaratorChunk::Function) { 390 if (MightBeFunction) { 391 // This is a function declaration. It can have default arguments, but 392 // keep looking in case its return type is a function type with default 393 // arguments. 394 MightBeFunction = false; 395 continue; 396 } 397 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 398 ++argIdx) { 399 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 400 if (Param->hasUnparsedDefaultArg()) { 401 std::unique_ptr<CachedTokens> Toks = 402 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 403 SourceRange SR; 404 if (Toks->size() > 1) 405 SR = SourceRange((*Toks)[1].getLocation(), 406 Toks->back().getLocation()); 407 else 408 SR = UnparsedDefaultArgLocs[Param]; 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << SR; 411 } else if (Param->getDefaultArg()) { 412 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 413 << Param->getDefaultArg()->getSourceRange(); 414 Param->setDefaultArg(nullptr); 415 } 416 } 417 } else if (chunk.Kind != DeclaratorChunk::Paren) { 418 MightBeFunction = false; 419 } 420 } 421 } 422 423 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 424 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 425 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 426 if (!PVD->hasDefaultArg()) 427 return false; 428 if (!PVD->hasInheritedDefaultArg()) 429 return true; 430 } 431 return false; 432 } 433 434 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 435 /// function, once we already know that they have the same 436 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 437 /// error, false otherwise. 438 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 439 Scope *S) { 440 bool Invalid = false; 441 442 // The declaration context corresponding to the scope is the semantic 443 // parent, unless this is a local function declaration, in which case 444 // it is that surrounding function. 445 DeclContext *ScopeDC = New->isLocalExternDecl() 446 ? New->getLexicalDeclContext() 447 : New->getDeclContext(); 448 449 // Find the previous declaration for the purpose of default arguments. 450 FunctionDecl *PrevForDefaultArgs = Old; 451 for (/**/; PrevForDefaultArgs; 452 // Don't bother looking back past the latest decl if this is a local 453 // extern declaration; nothing else could work. 454 PrevForDefaultArgs = New->isLocalExternDecl() 455 ? nullptr 456 : PrevForDefaultArgs->getPreviousDecl()) { 457 // Ignore hidden declarations. 458 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 459 continue; 460 461 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 462 !New->isCXXClassMember()) { 463 // Ignore default arguments of old decl if they are not in 464 // the same scope and this is not an out-of-line definition of 465 // a member function. 466 continue; 467 } 468 469 if (PrevForDefaultArgs->isLocalExternDecl() != New->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 // sufficient, and if neither is local, then they are in the same scope.) 474 continue; 475 } 476 477 // We found the right previous declaration. 478 break; 479 } 480 481 // C++ [dcl.fct.default]p4: 482 // For non-template functions, default arguments can be added in 483 // later declarations of a function in the same 484 // scope. Declarations in different scopes have completely 485 // distinct sets of default arguments. That is, declarations in 486 // inner scopes do not acquire default arguments from 487 // declarations in outer scopes, and vice versa. In a given 488 // function declaration, all parameters subsequent to a 489 // parameter with a default argument shall have default 490 // arguments supplied in this or previous declarations. A 491 // default argument shall not be redefined by a later 492 // declaration (not even to the same value). 493 // 494 // C++ [dcl.fct.default]p6: 495 // Except for member functions of class templates, the default arguments 496 // in a member function definition that appears outside of the class 497 // definition are added to the set of default arguments provided by the 498 // member function declaration in the class definition. 499 for (unsigned p = 0, NumParams = PrevForDefaultArgs 500 ? PrevForDefaultArgs->getNumParams() 501 : 0; 502 p < NumParams; ++p) { 503 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 504 ParmVarDecl *NewParam = New->getParamDecl(p); 505 506 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 507 bool NewParamHasDfl = NewParam->hasDefaultArg(); 508 509 if (OldParamHasDfl && NewParamHasDfl) { 510 unsigned DiagDefaultParamID = 511 diag::err_param_default_argument_redefinition; 512 513 // MSVC accepts that default parameters be redefined for member functions 514 // of template class. The new default parameter's value is ignored. 515 Invalid = true; 516 if (getLangOpts().MicrosoftExt) { 517 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 518 if (MD && MD->getParent()->getDescribedClassTemplate()) { 519 // Merge the old default argument into the new parameter. 520 NewParam->setHasInheritedDefaultArg(); 521 if (OldParam->hasUninstantiatedDefaultArg()) 522 NewParam->setUninstantiatedDefaultArg( 523 OldParam->getUninstantiatedDefaultArg()); 524 else 525 NewParam->setDefaultArg(OldParam->getInit()); 526 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 527 Invalid = false; 528 } 529 } 530 531 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 532 // hint here. Alternatively, we could walk the type-source information 533 // for NewParam to find the last source location in the type... but it 534 // isn't worth the effort right now. This is the kind of test case that 535 // is hard to get right: 536 // int f(int); 537 // void g(int (*fp)(int) = f); 538 // void g(int (*fp)(int) = &f); 539 Diag(NewParam->getLocation(), DiagDefaultParamID) 540 << NewParam->getDefaultArgRange(); 541 542 // Look for the function declaration where the default argument was 543 // actually written, which may be a declaration prior to Old. 544 for (auto Older = PrevForDefaultArgs; 545 OldParam->hasInheritedDefaultArg(); /**/) { 546 Older = Older->getPreviousDecl(); 547 OldParam = Older->getParamDecl(p); 548 } 549 550 Diag(OldParam->getLocation(), diag::note_previous_definition) 551 << OldParam->getDefaultArgRange(); 552 } else if (OldParamHasDfl) { 553 // Merge the old default argument into the new parameter unless the new 554 // function is a friend declaration in a template class. In the latter 555 // case the default arguments will be inherited when the friend 556 // declaration will be instantiated. 557 if (New->getFriendObjectKind() == Decl::FOK_None || 558 !New->getLexicalDeclContext()->isDependentContext()) { 559 // It's important to use getInit() here; getDefaultArg() 560 // strips off any top-level ExprWithCleanups. 561 NewParam->setHasInheritedDefaultArg(); 562 if (OldParam->hasUnparsedDefaultArg()) 563 NewParam->setUnparsedDefaultArg(); 564 else if (OldParam->hasUninstantiatedDefaultArg()) 565 NewParam->setUninstantiatedDefaultArg( 566 OldParam->getUninstantiatedDefaultArg()); 567 else 568 NewParam->setDefaultArg(OldParam->getInit()); 569 } 570 } else if (NewParamHasDfl) { 571 if (New->getDescribedFunctionTemplate()) { 572 // Paragraph 4, quoted above, only applies to non-template functions. 573 Diag(NewParam->getLocation(), 574 diag::err_param_default_argument_template_redecl) 575 << NewParam->getDefaultArgRange(); 576 Diag(PrevForDefaultArgs->getLocation(), 577 diag::note_template_prev_declaration) 578 << false; 579 } else if (New->getTemplateSpecializationKind() 580 != TSK_ImplicitInstantiation && 581 New->getTemplateSpecializationKind() != TSK_Undeclared) { 582 // C++ [temp.expr.spec]p21: 583 // Default function arguments shall not be specified in a declaration 584 // or a definition for one of the following explicit specializations: 585 // - the explicit specialization of a function template; 586 // - the explicit specialization of a member function template; 587 // - the explicit specialization of a member function of a class 588 // template where the class template specialization to which the 589 // member function specialization belongs is implicitly 590 // instantiated. 591 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 592 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 593 << New->getDeclName() 594 << NewParam->getDefaultArgRange(); 595 } else if (New->getDeclContext()->isDependentContext()) { 596 // C++ [dcl.fct.default]p6 (DR217): 597 // Default arguments for a member function of a class template shall 598 // be specified on the initial declaration of the member function 599 // within the class template. 600 // 601 // Reading the tea leaves a bit in DR217 and its reference to DR205 602 // leads me to the conclusion that one cannot add default function 603 // arguments for an out-of-line definition of a member function of a 604 // dependent type. 605 int WhichKind = 2; 606 if (CXXRecordDecl *Record 607 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 608 if (Record->getDescribedClassTemplate()) 609 WhichKind = 0; 610 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 611 WhichKind = 1; 612 else 613 WhichKind = 2; 614 } 615 616 Diag(NewParam->getLocation(), 617 diag::err_param_default_argument_member_template_redecl) 618 << WhichKind 619 << NewParam->getDefaultArgRange(); 620 } 621 } 622 } 623 624 // DR1344: If a default argument is added outside a class definition and that 625 // default argument makes the function a special member function, the program 626 // is ill-formed. This can only happen for constructors. 627 if (isa<CXXConstructorDecl>(New) && 628 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 629 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 630 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 631 if (NewSM != OldSM) { 632 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 633 assert(NewParam->hasDefaultArg()); 634 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 635 << NewParam->getDefaultArgRange() << NewSM; 636 Diag(Old->getLocation(), diag::note_previous_declaration); 637 } 638 } 639 640 const FunctionDecl *Def; 641 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 642 // template has a constexpr specifier then all its declarations shall 643 // contain the constexpr specifier. 644 if (New->isConstexpr() != Old->isConstexpr()) { 645 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 646 << New << New->isConstexpr(); 647 Diag(Old->getLocation(), diag::note_previous_declaration); 648 Invalid = true; 649 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 650 Old->isDefined(Def) && 651 // If a friend function is inlined but does not have 'inline' 652 // specifier, it is a definition. Do not report attribute conflict 653 // in this case, redefinition will be diagnosed later. 654 (New->isInlineSpecified() || 655 New->getFriendObjectKind() == Decl::FOK_None)) { 656 // C++11 [dcl.fcn.spec]p4: 657 // If the definition of a function appears in a translation unit before its 658 // first declaration as inline, the program is ill-formed. 659 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 660 Diag(Def->getLocation(), diag::note_previous_definition); 661 Invalid = true; 662 } 663 664 // FIXME: It's not clear what should happen if multiple declarations of a 665 // deduction guide have different explicitness. For now at least we simply 666 // reject any case where the explicitness changes. 667 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New); 668 if (NewGuide && NewGuide->isExplicitSpecified() != 669 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) { 670 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch) 671 << NewGuide->isExplicitSpecified(); 672 Diag(Old->getLocation(), diag::note_previous_declaration); 673 } 674 675 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 676 // argument expression, that declaration shall be a definition and shall be 677 // the only declaration of the function or function template in the 678 // translation unit. 679 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 680 functionDeclHasDefaultArgument(Old)) { 681 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 682 Diag(Old->getLocation(), diag::note_previous_declaration); 683 Invalid = true; 684 } 685 686 return Invalid; 687 } 688 689 NamedDecl * 690 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 691 MultiTemplateParamsArg TemplateParamLists) { 692 assert(D.isDecompositionDeclarator()); 693 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 694 695 // The syntax only allows a decomposition declarator as a simple-declaration, 696 // a for-range-declaration, or a condition in Clang, but we parse it in more 697 // cases than that. 698 if (!D.mayHaveDecompositionDeclarator()) { 699 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 700 << Decomp.getSourceRange(); 701 return nullptr; 702 } 703 704 if (!TemplateParamLists.empty()) { 705 // FIXME: There's no rule against this, but there are also no rules that 706 // would actually make it usable, so we reject it for now. 707 Diag(TemplateParamLists.front()->getTemplateLoc(), 708 diag::err_decomp_decl_template); 709 return nullptr; 710 } 711 712 Diag(Decomp.getLSquareLoc(), 713 !getLangOpts().CPlusPlus17 714 ? diag::ext_decomp_decl 715 : D.getContext() == DeclaratorContext::ConditionContext 716 ? diag::ext_decomp_decl_cond 717 : diag::warn_cxx14_compat_decomp_decl) 718 << Decomp.getSourceRange(); 719 720 // The semantic context is always just the current context. 721 DeclContext *const DC = CurContext; 722 723 // C++1z [dcl.dcl]/8: 724 // The decl-specifier-seq shall contain only the type-specifier auto 725 // and cv-qualifiers. 726 auto &DS = D.getDeclSpec(); 727 { 728 SmallVector<StringRef, 8> BadSpecifiers; 729 SmallVector<SourceLocation, 8> BadSpecifierLocs; 730 if (auto SCS = DS.getStorageClassSpec()) { 731 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 732 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 733 } 734 if (auto TSCS = DS.getThreadStorageClassSpec()) { 735 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 736 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 737 } 738 if (DS.isConstexprSpecified()) { 739 BadSpecifiers.push_back("constexpr"); 740 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 741 } 742 if (DS.isInlineSpecified()) { 743 BadSpecifiers.push_back("inline"); 744 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 745 } 746 if (!BadSpecifiers.empty()) { 747 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 748 Err << (int)BadSpecifiers.size() 749 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 750 // Don't add FixItHints to remove the specifiers; we do still respect 751 // them when building the underlying variable. 752 for (auto Loc : BadSpecifierLocs) 753 Err << SourceRange(Loc, Loc); 754 } 755 // We can't recover from it being declared as a typedef. 756 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 757 return nullptr; 758 } 759 760 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 761 QualType R = TInfo->getType(); 762 763 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 764 UPPC_DeclarationType)) 765 D.setInvalidType(); 766 767 // The syntax only allows a single ref-qualifier prior to the decomposition 768 // declarator. No other declarator chunks are permitted. Also check the type 769 // specifier here. 770 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 771 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 772 (D.getNumTypeObjects() == 1 && 773 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 774 Diag(Decomp.getLSquareLoc(), 775 (D.hasGroupingParens() || 776 (D.getNumTypeObjects() && 777 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 778 ? diag::err_decomp_decl_parens 779 : diag::err_decomp_decl_type) 780 << R; 781 782 // In most cases, there's no actual problem with an explicitly-specified 783 // type, but a function type won't work here, and ActOnVariableDeclarator 784 // shouldn't be called for such a type. 785 if (R->isFunctionType()) 786 D.setInvalidType(); 787 } 788 789 // Build the BindingDecls. 790 SmallVector<BindingDecl*, 8> Bindings; 791 792 // Build the BindingDecls. 793 for (auto &B : D.getDecompositionDeclarator().bindings()) { 794 // Check for name conflicts. 795 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 796 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 797 ForVisibleRedeclaration); 798 LookupName(Previous, S, 799 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 800 801 // It's not permitted to shadow a template parameter name. 802 if (Previous.isSingleResult() && 803 Previous.getFoundDecl()->isTemplateParameter()) { 804 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 805 Previous.getFoundDecl()); 806 Previous.clear(); 807 } 808 809 bool ConsiderLinkage = DC->isFunctionOrMethod() && 810 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 811 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 812 /*AllowInlineNamespace*/false); 813 if (!Previous.empty()) { 814 auto *Old = Previous.getRepresentativeDecl(); 815 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 816 Diag(Old->getLocation(), diag::note_previous_definition); 817 } 818 819 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 820 PushOnScopeChains(BD, S, true); 821 Bindings.push_back(BD); 822 ParsingInitForAutoVars.insert(BD); 823 } 824 825 // There are no prior lookup results for the variable itself, because it 826 // is unnamed. 827 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 828 Decomp.getLSquareLoc()); 829 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 830 ForVisibleRedeclaration); 831 832 // Build the variable that holds the non-decomposed object. 833 bool AddToScope = true; 834 NamedDecl *New = 835 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 836 MultiTemplateParamsArg(), AddToScope, Bindings); 837 if (AddToScope) { 838 S->AddDecl(New); 839 CurContext->addHiddenDecl(New); 840 } 841 842 if (isInOpenMPDeclareTargetContext()) 843 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 844 845 return New; 846 } 847 848 static bool checkSimpleDecomposition( 849 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 850 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 851 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 852 if ((int64_t)Bindings.size() != NumElems) { 853 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 854 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 855 << (NumElems < Bindings.size()); 856 return true; 857 } 858 859 unsigned I = 0; 860 for (auto *B : Bindings) { 861 SourceLocation Loc = B->getLocation(); 862 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 863 if (E.isInvalid()) 864 return true; 865 E = GetInit(Loc, E.get(), I++); 866 if (E.isInvalid()) 867 return true; 868 B->setBinding(ElemType, E.get()); 869 } 870 871 return false; 872 } 873 874 static bool checkArrayLikeDecomposition(Sema &S, 875 ArrayRef<BindingDecl *> Bindings, 876 ValueDecl *Src, QualType DecompType, 877 const llvm::APSInt &NumElems, 878 QualType ElemType) { 879 return checkSimpleDecomposition( 880 S, Bindings, Src, DecompType, NumElems, ElemType, 881 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 882 ExprResult E = S.ActOnIntegerConstant(Loc, I); 883 if (E.isInvalid()) 884 return ExprError(); 885 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 886 }); 887 } 888 889 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 890 ValueDecl *Src, QualType DecompType, 891 const ConstantArrayType *CAT) { 892 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 893 llvm::APSInt(CAT->getSize()), 894 CAT->getElementType()); 895 } 896 897 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 898 ValueDecl *Src, QualType DecompType, 899 const VectorType *VT) { 900 return checkArrayLikeDecomposition( 901 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 902 S.Context.getQualifiedType(VT->getElementType(), 903 DecompType.getQualifiers())); 904 } 905 906 static bool checkComplexDecomposition(Sema &S, 907 ArrayRef<BindingDecl *> Bindings, 908 ValueDecl *Src, QualType DecompType, 909 const ComplexType *CT) { 910 return checkSimpleDecomposition( 911 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 912 S.Context.getQualifiedType(CT->getElementType(), 913 DecompType.getQualifiers()), 914 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 915 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 916 }); 917 } 918 919 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 920 TemplateArgumentListInfo &Args) { 921 SmallString<128> SS; 922 llvm::raw_svector_ostream OS(SS); 923 bool First = true; 924 for (auto &Arg : Args.arguments()) { 925 if (!First) 926 OS << ", "; 927 Arg.getArgument().print(PrintingPolicy, OS); 928 First = false; 929 } 930 return OS.str(); 931 } 932 933 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 934 SourceLocation Loc, StringRef Trait, 935 TemplateArgumentListInfo &Args, 936 unsigned DiagID) { 937 auto DiagnoseMissing = [&] { 938 if (DiagID) 939 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 940 Args); 941 return true; 942 }; 943 944 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 945 NamespaceDecl *Std = S.getStdNamespace(); 946 if (!Std) 947 return DiagnoseMissing(); 948 949 // Look up the trait itself, within namespace std. We can diagnose various 950 // problems with this lookup even if we've been asked to not diagnose a 951 // missing specialization, because this can only fail if the user has been 952 // declaring their own names in namespace std or we don't support the 953 // standard library implementation in use. 954 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 955 Loc, Sema::LookupOrdinaryName); 956 if (!S.LookupQualifiedName(Result, Std)) 957 return DiagnoseMissing(); 958 if (Result.isAmbiguous()) 959 return true; 960 961 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 962 if (!TraitTD) { 963 Result.suppressDiagnostics(); 964 NamedDecl *Found = *Result.begin(); 965 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 966 S.Diag(Found->getLocation(), diag::note_declared_at); 967 return true; 968 } 969 970 // Build the template-id. 971 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 972 if (TraitTy.isNull()) 973 return true; 974 if (!S.isCompleteType(Loc, TraitTy)) { 975 if (DiagID) 976 S.RequireCompleteType( 977 Loc, TraitTy, DiagID, 978 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 979 return true; 980 } 981 982 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 983 assert(RD && "specialization of class template is not a class?"); 984 985 // Look up the member of the trait type. 986 S.LookupQualifiedName(TraitMemberLookup, RD); 987 return TraitMemberLookup.isAmbiguous(); 988 } 989 990 static TemplateArgumentLoc 991 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 992 uint64_t I) { 993 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 994 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 995 } 996 997 static TemplateArgumentLoc 998 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 999 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1000 } 1001 1002 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1003 1004 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1005 llvm::APSInt &Size) { 1006 EnterExpressionEvaluationContext ContextRAII( 1007 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1008 1009 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1010 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1011 1012 // Form template argument list for tuple_size<T>. 1013 TemplateArgumentListInfo Args(Loc, Loc); 1014 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1015 1016 // If there's no tuple_size specialization, it's not tuple-like. 1017 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1018 return IsTupleLike::NotTupleLike; 1019 1020 // If we get this far, we've committed to the tuple interpretation, but 1021 // we can still fail if there actually isn't a usable ::value. 1022 1023 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1024 LookupResult &R; 1025 TemplateArgumentListInfo &Args; 1026 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1027 : R(R), Args(Args) {} 1028 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1029 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1030 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1031 } 1032 } Diagnoser(R, Args); 1033 1034 if (R.empty()) { 1035 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1036 return IsTupleLike::Error; 1037 } 1038 1039 ExprResult E = 1040 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1041 if (E.isInvalid()) 1042 return IsTupleLike::Error; 1043 1044 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1045 if (E.isInvalid()) 1046 return IsTupleLike::Error; 1047 1048 return IsTupleLike::TupleLike; 1049 } 1050 1051 /// \return std::tuple_element<I, T>::type. 1052 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1053 unsigned I, QualType T) { 1054 // Form template argument list for tuple_element<I, T>. 1055 TemplateArgumentListInfo Args(Loc, Loc); 1056 Args.addArgument( 1057 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1058 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1059 1060 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1061 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1062 if (lookupStdTypeTraitMember( 1063 S, R, Loc, "tuple_element", Args, 1064 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1065 return QualType(); 1066 1067 auto *TD = R.getAsSingle<TypeDecl>(); 1068 if (!TD) { 1069 R.suppressDiagnostics(); 1070 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1071 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1072 if (!R.empty()) 1073 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1074 return QualType(); 1075 } 1076 1077 return S.Context.getTypeDeclType(TD); 1078 } 1079 1080 namespace { 1081 struct BindingDiagnosticTrap { 1082 Sema &S; 1083 DiagnosticErrorTrap Trap; 1084 BindingDecl *BD; 1085 1086 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1087 : S(S), Trap(S.Diags), BD(BD) {} 1088 ~BindingDiagnosticTrap() { 1089 if (Trap.hasErrorOccurred()) 1090 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1091 } 1092 }; 1093 } 1094 1095 static bool checkTupleLikeDecomposition(Sema &S, 1096 ArrayRef<BindingDecl *> Bindings, 1097 VarDecl *Src, QualType DecompType, 1098 const llvm::APSInt &TupleSize) { 1099 if ((int64_t)Bindings.size() != TupleSize) { 1100 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1101 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1102 << (TupleSize < Bindings.size()); 1103 return true; 1104 } 1105 1106 if (Bindings.empty()) 1107 return false; 1108 1109 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1110 1111 // [dcl.decomp]p3: 1112 // The unqualified-id get is looked up in the scope of E by class member 1113 // access lookup 1114 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1115 bool UseMemberGet = false; 1116 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1117 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1118 S.LookupQualifiedName(MemberGet, RD); 1119 if (MemberGet.isAmbiguous()) 1120 return true; 1121 UseMemberGet = !MemberGet.empty(); 1122 S.FilterAcceptableTemplateNames(MemberGet); 1123 } 1124 1125 unsigned I = 0; 1126 for (auto *B : Bindings) { 1127 BindingDiagnosticTrap Trap(S, B); 1128 SourceLocation Loc = B->getLocation(); 1129 1130 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1131 if (E.isInvalid()) 1132 return true; 1133 1134 // e is an lvalue if the type of the entity is an lvalue reference and 1135 // an xvalue otherwise 1136 if (!Src->getType()->isLValueReferenceType()) 1137 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1138 E.get(), nullptr, VK_XValue); 1139 1140 TemplateArgumentListInfo Args(Loc, Loc); 1141 Args.addArgument( 1142 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1143 1144 if (UseMemberGet) { 1145 // if [lookup of member get] finds at least one declaration, the 1146 // initializer is e.get<i-1>(). 1147 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1148 CXXScopeSpec(), SourceLocation(), nullptr, 1149 MemberGet, &Args, nullptr); 1150 if (E.isInvalid()) 1151 return true; 1152 1153 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1154 } else { 1155 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1156 // in the associated namespaces. 1157 Expr *Get = UnresolvedLookupExpr::Create( 1158 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1159 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1160 UnresolvedSetIterator(), UnresolvedSetIterator()); 1161 1162 Expr *Arg = E.get(); 1163 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1164 } 1165 if (E.isInvalid()) 1166 return true; 1167 Expr *Init = E.get(); 1168 1169 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1170 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1171 if (T.isNull()) 1172 return true; 1173 1174 // each vi is a variable of type "reference to T" initialized with the 1175 // initializer, where the reference is an lvalue reference if the 1176 // initializer is an lvalue and an rvalue reference otherwise 1177 QualType RefType = 1178 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1179 if (RefType.isNull()) 1180 return true; 1181 auto *RefVD = VarDecl::Create( 1182 S.Context, Src->getDeclContext(), Loc, Loc, 1183 B->getDeclName().getAsIdentifierInfo(), RefType, 1184 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1185 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1186 RefVD->setTSCSpec(Src->getTSCSpec()); 1187 RefVD->setImplicit(); 1188 if (Src->isInlineSpecified()) 1189 RefVD->setInlineSpecified(); 1190 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1191 1192 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1193 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1194 InitializationSequence Seq(S, Entity, Kind, Init); 1195 E = Seq.Perform(S, Entity, Kind, Init); 1196 if (E.isInvalid()) 1197 return true; 1198 E = S.ActOnFinishFullExpr(E.get(), Loc); 1199 if (E.isInvalid()) 1200 return true; 1201 RefVD->setInit(E.get()); 1202 RefVD->checkInitIsICE(); 1203 1204 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1205 DeclarationNameInfo(B->getDeclName(), Loc), 1206 RefVD); 1207 if (E.isInvalid()) 1208 return true; 1209 1210 B->setBinding(T, E.get()); 1211 I++; 1212 } 1213 1214 return false; 1215 } 1216 1217 /// Find the base class to decompose in a built-in decomposition of a class type. 1218 /// This base class search is, unfortunately, not quite like any other that we 1219 /// perform anywhere else in C++. 1220 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1221 SourceLocation Loc, 1222 const CXXRecordDecl *RD, 1223 CXXCastPath &BasePath) { 1224 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1225 CXXBasePath &Path) { 1226 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1227 }; 1228 1229 const CXXRecordDecl *ClassWithFields = nullptr; 1230 if (RD->hasDirectFields()) 1231 // [dcl.decomp]p4: 1232 // Otherwise, all of E's non-static data members shall be public direct 1233 // members of E ... 1234 ClassWithFields = RD; 1235 else { 1236 // ... or of ... 1237 CXXBasePaths Paths; 1238 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1239 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1240 // If no classes have fields, just decompose RD itself. (This will work 1241 // if and only if zero bindings were provided.) 1242 return RD; 1243 } 1244 1245 CXXBasePath *BestPath = nullptr; 1246 for (auto &P : Paths) { 1247 if (!BestPath) 1248 BestPath = &P; 1249 else if (!S.Context.hasSameType(P.back().Base->getType(), 1250 BestPath->back().Base->getType())) { 1251 // ... the same ... 1252 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1253 << false << RD << BestPath->back().Base->getType() 1254 << P.back().Base->getType(); 1255 return nullptr; 1256 } else if (P.Access < BestPath->Access) { 1257 BestPath = &P; 1258 } 1259 } 1260 1261 // ... unambiguous ... 1262 QualType BaseType = BestPath->back().Base->getType(); 1263 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1264 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1265 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1266 return nullptr; 1267 } 1268 1269 // ... public base class of E. 1270 if (BestPath->Access != AS_public) { 1271 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1272 << RD << BaseType; 1273 for (auto &BS : *BestPath) { 1274 if (BS.Base->getAccessSpecifier() != AS_public) { 1275 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1276 << (BS.Base->getAccessSpecifier() == AS_protected) 1277 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1278 break; 1279 } 1280 } 1281 return nullptr; 1282 } 1283 1284 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1285 S.BuildBasePathArray(Paths, BasePath); 1286 } 1287 1288 // The above search did not check whether the selected class itself has base 1289 // classes with fields, so check that now. 1290 CXXBasePaths Paths; 1291 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1292 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1293 << (ClassWithFields == RD) << RD << ClassWithFields 1294 << Paths.front().back().Base->getType(); 1295 return nullptr; 1296 } 1297 1298 return ClassWithFields; 1299 } 1300 1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1302 ValueDecl *Src, QualType DecompType, 1303 const CXXRecordDecl *RD) { 1304 CXXCastPath BasePath; 1305 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1306 if (!RD) 1307 return true; 1308 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1309 DecompType.getQualifiers()); 1310 1311 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1312 unsigned NumFields = 1313 std::count_if(RD->field_begin(), RD->field_end(), 1314 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1315 assert(Bindings.size() != NumFields); 1316 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1317 << DecompType << (unsigned)Bindings.size() << NumFields 1318 << (NumFields < Bindings.size()); 1319 return true; 1320 }; 1321 1322 // all of E's non-static data members shall be public [...] members, 1323 // E shall not have an anonymous union member, ... 1324 unsigned I = 0; 1325 for (auto *FD : RD->fields()) { 1326 if (FD->isUnnamedBitfield()) 1327 continue; 1328 1329 if (FD->isAnonymousStructOrUnion()) { 1330 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1331 << DecompType << FD->getType()->isUnionType(); 1332 S.Diag(FD->getLocation(), diag::note_declared_at); 1333 return true; 1334 } 1335 1336 // We have a real field to bind. 1337 if (I >= Bindings.size()) 1338 return DiagnoseBadNumberOfBindings(); 1339 auto *B = Bindings[I++]; 1340 1341 SourceLocation Loc = B->getLocation(); 1342 if (FD->getAccess() != AS_public) { 1343 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1344 1345 // Determine whether the access specifier was explicit. 1346 bool Implicit = true; 1347 for (const auto *D : RD->decls()) { 1348 if (declaresSameEntity(D, FD)) 1349 break; 1350 if (isa<AccessSpecDecl>(D)) { 1351 Implicit = false; 1352 break; 1353 } 1354 } 1355 1356 S.Diag(FD->getLocation(), diag::note_access_natural) 1357 << (FD->getAccess() == AS_protected) << Implicit; 1358 return true; 1359 } 1360 1361 // Initialize the binding to Src.FD. 1362 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1363 if (E.isInvalid()) 1364 return true; 1365 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1366 VK_LValue, &BasePath); 1367 if (E.isInvalid()) 1368 return true; 1369 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1370 CXXScopeSpec(), FD, 1371 DeclAccessPair::make(FD, FD->getAccess()), 1372 DeclarationNameInfo(FD->getDeclName(), Loc)); 1373 if (E.isInvalid()) 1374 return true; 1375 1376 // If the type of the member is T, the referenced type is cv T, where cv is 1377 // the cv-qualification of the decomposition expression. 1378 // 1379 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1380 // 'const' to the type of the field. 1381 Qualifiers Q = DecompType.getQualifiers(); 1382 if (FD->isMutable()) 1383 Q.removeConst(); 1384 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1385 } 1386 1387 if (I != Bindings.size()) 1388 return DiagnoseBadNumberOfBindings(); 1389 1390 return false; 1391 } 1392 1393 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1394 QualType DecompType = DD->getType(); 1395 1396 // If the type of the decomposition is dependent, then so is the type of 1397 // each binding. 1398 if (DecompType->isDependentType()) { 1399 for (auto *B : DD->bindings()) 1400 B->setType(Context.DependentTy); 1401 return; 1402 } 1403 1404 DecompType = DecompType.getNonReferenceType(); 1405 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1406 1407 // C++1z [dcl.decomp]/2: 1408 // If E is an array type [...] 1409 // As an extension, we also support decomposition of built-in complex and 1410 // vector types. 1411 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1412 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1413 DD->setInvalidDecl(); 1414 return; 1415 } 1416 if (auto *VT = DecompType->getAs<VectorType>()) { 1417 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1418 DD->setInvalidDecl(); 1419 return; 1420 } 1421 if (auto *CT = DecompType->getAs<ComplexType>()) { 1422 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1423 DD->setInvalidDecl(); 1424 return; 1425 } 1426 1427 // C++1z [dcl.decomp]/3: 1428 // if the expression std::tuple_size<E>::value is a well-formed integral 1429 // constant expression, [...] 1430 llvm::APSInt TupleSize(32); 1431 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1432 case IsTupleLike::Error: 1433 DD->setInvalidDecl(); 1434 return; 1435 1436 case IsTupleLike::TupleLike: 1437 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1438 DD->setInvalidDecl(); 1439 return; 1440 1441 case IsTupleLike::NotTupleLike: 1442 break; 1443 } 1444 1445 // C++1z [dcl.dcl]/8: 1446 // [E shall be of array or non-union class type] 1447 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1448 if (!RD || RD->isUnion()) { 1449 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1450 << DD << !RD << DecompType; 1451 DD->setInvalidDecl(); 1452 return; 1453 } 1454 1455 // C++1z [dcl.decomp]/4: 1456 // all of E's non-static data members shall be [...] direct members of 1457 // E or of the same unambiguous public base class of E, ... 1458 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1459 DD->setInvalidDecl(); 1460 } 1461 1462 /// \brief Merge the exception specifications of two variable declarations. 1463 /// 1464 /// This is called when there's a redeclaration of a VarDecl. The function 1465 /// checks if the redeclaration might have an exception specification and 1466 /// validates compatibility and merges the specs if necessary. 1467 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1468 // Shortcut if exceptions are disabled. 1469 if (!getLangOpts().CXXExceptions) 1470 return; 1471 1472 assert(Context.hasSameType(New->getType(), Old->getType()) && 1473 "Should only be called if types are otherwise the same."); 1474 1475 QualType NewType = New->getType(); 1476 QualType OldType = Old->getType(); 1477 1478 // We're only interested in pointers and references to functions, as well 1479 // as pointers to member functions. 1480 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1481 NewType = R->getPointeeType(); 1482 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1483 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1484 NewType = P->getPointeeType(); 1485 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1486 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1487 NewType = M->getPointeeType(); 1488 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1489 } 1490 1491 if (!NewType->isFunctionProtoType()) 1492 return; 1493 1494 // There's lots of special cases for functions. For function pointers, system 1495 // libraries are hopefully not as broken so that we don't need these 1496 // workarounds. 1497 if (CheckEquivalentExceptionSpec( 1498 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1499 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1500 New->setInvalidDecl(); 1501 } 1502 } 1503 1504 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1505 /// function declaration are well-formed according to C++ 1506 /// [dcl.fct.default]. 1507 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1508 unsigned NumParams = FD->getNumParams(); 1509 unsigned p; 1510 1511 // Find first parameter with a default argument 1512 for (p = 0; p < NumParams; ++p) { 1513 ParmVarDecl *Param = FD->getParamDecl(p); 1514 if (Param->hasDefaultArg()) 1515 break; 1516 } 1517 1518 // C++11 [dcl.fct.default]p4: 1519 // In a given function declaration, each parameter subsequent to a parameter 1520 // with a default argument shall have a default argument supplied in this or 1521 // a previous declaration or shall be a function parameter pack. A default 1522 // argument shall not be redefined by a later declaration (not even to the 1523 // same value). 1524 unsigned LastMissingDefaultArg = 0; 1525 for (; p < NumParams; ++p) { 1526 ParmVarDecl *Param = FD->getParamDecl(p); 1527 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1528 if (Param->isInvalidDecl()) 1529 /* We already complained about this parameter. */; 1530 else if (Param->getIdentifier()) 1531 Diag(Param->getLocation(), 1532 diag::err_param_default_argument_missing_name) 1533 << Param->getIdentifier(); 1534 else 1535 Diag(Param->getLocation(), 1536 diag::err_param_default_argument_missing); 1537 1538 LastMissingDefaultArg = p; 1539 } 1540 } 1541 1542 if (LastMissingDefaultArg > 0) { 1543 // Some default arguments were missing. Clear out all of the 1544 // default arguments up to (and including) the last missing 1545 // default argument, so that we leave the function parameters 1546 // in a semantically valid state. 1547 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1548 ParmVarDecl *Param = FD->getParamDecl(p); 1549 if (Param->hasDefaultArg()) { 1550 Param->setDefaultArg(nullptr); 1551 } 1552 } 1553 } 1554 } 1555 1556 // CheckConstexprParameterTypes - Check whether a function's parameter types 1557 // are all literal types. If so, return true. If not, produce a suitable 1558 // diagnostic and return false. 1559 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1560 const FunctionDecl *FD) { 1561 unsigned ArgIndex = 0; 1562 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1563 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1564 e = FT->param_type_end(); 1565 i != e; ++i, ++ArgIndex) { 1566 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1567 SourceLocation ParamLoc = PD->getLocation(); 1568 if (!(*i)->isDependentType() && 1569 SemaRef.RequireLiteralType(ParamLoc, *i, 1570 diag::err_constexpr_non_literal_param, 1571 ArgIndex+1, PD->getSourceRange(), 1572 isa<CXXConstructorDecl>(FD))) 1573 return false; 1574 } 1575 return true; 1576 } 1577 1578 /// \brief Get diagnostic %select index for tag kind for 1579 /// record diagnostic message. 1580 /// WARNING: Indexes apply to particular diagnostics only! 1581 /// 1582 /// \returns diagnostic %select index. 1583 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1584 switch (Tag) { 1585 case TTK_Struct: return 0; 1586 case TTK_Interface: return 1; 1587 case TTK_Class: return 2; 1588 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1589 } 1590 } 1591 1592 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1593 // the requirements of a constexpr function definition or a constexpr 1594 // constructor definition. If so, return true. If not, produce appropriate 1595 // diagnostics and return false. 1596 // 1597 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1598 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1599 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1600 if (MD && MD->isInstance()) { 1601 // C++11 [dcl.constexpr]p4: 1602 // The definition of a constexpr constructor shall satisfy the following 1603 // constraints: 1604 // - the class shall not have any virtual base classes; 1605 const CXXRecordDecl *RD = MD->getParent(); 1606 if (RD->getNumVBases()) { 1607 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1608 << isa<CXXConstructorDecl>(NewFD) 1609 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1610 for (const auto &I : RD->vbases()) 1611 Diag(I.getLocStart(), 1612 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1613 return false; 1614 } 1615 } 1616 1617 if (!isa<CXXConstructorDecl>(NewFD)) { 1618 // C++11 [dcl.constexpr]p3: 1619 // The definition of a constexpr function shall satisfy the following 1620 // constraints: 1621 // - it shall not be virtual; 1622 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1623 if (Method && Method->isVirtual()) { 1624 Method = Method->getCanonicalDecl(); 1625 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1626 1627 // If it's not obvious why this function is virtual, find an overridden 1628 // function which uses the 'virtual' keyword. 1629 const CXXMethodDecl *WrittenVirtual = Method; 1630 while (!WrittenVirtual->isVirtualAsWritten()) 1631 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1632 if (WrittenVirtual != Method) 1633 Diag(WrittenVirtual->getLocation(), 1634 diag::note_overridden_virtual_function); 1635 return false; 1636 } 1637 1638 // - its return type shall be a literal type; 1639 QualType RT = NewFD->getReturnType(); 1640 if (!RT->isDependentType() && 1641 RequireLiteralType(NewFD->getLocation(), RT, 1642 diag::err_constexpr_non_literal_return)) 1643 return false; 1644 } 1645 1646 // - each of its parameter types shall be a literal type; 1647 if (!CheckConstexprParameterTypes(*this, NewFD)) 1648 return false; 1649 1650 return true; 1651 } 1652 1653 /// Check the given declaration statement is legal within a constexpr function 1654 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1655 /// 1656 /// \return true if the body is OK (maybe only as an extension), false if we 1657 /// have diagnosed a problem. 1658 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1659 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1660 // C++11 [dcl.constexpr]p3 and p4: 1661 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1662 // contain only 1663 for (const auto *DclIt : DS->decls()) { 1664 switch (DclIt->getKind()) { 1665 case Decl::StaticAssert: 1666 case Decl::Using: 1667 case Decl::UsingShadow: 1668 case Decl::UsingDirective: 1669 case Decl::UnresolvedUsingTypename: 1670 case Decl::UnresolvedUsingValue: 1671 // - static_assert-declarations 1672 // - using-declarations, 1673 // - using-directives, 1674 continue; 1675 1676 case Decl::Typedef: 1677 case Decl::TypeAlias: { 1678 // - typedef declarations and alias-declarations that do not define 1679 // classes or enumerations, 1680 const auto *TN = cast<TypedefNameDecl>(DclIt); 1681 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1682 // Don't allow variably-modified types in constexpr functions. 1683 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1684 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1685 << TL.getSourceRange() << TL.getType() 1686 << isa<CXXConstructorDecl>(Dcl); 1687 return false; 1688 } 1689 continue; 1690 } 1691 1692 case Decl::Enum: 1693 case Decl::CXXRecord: 1694 // C++1y allows types to be defined, not just declared. 1695 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1696 SemaRef.Diag(DS->getLocStart(), 1697 SemaRef.getLangOpts().CPlusPlus14 1698 ? diag::warn_cxx11_compat_constexpr_type_definition 1699 : diag::ext_constexpr_type_definition) 1700 << isa<CXXConstructorDecl>(Dcl); 1701 continue; 1702 1703 case Decl::EnumConstant: 1704 case Decl::IndirectField: 1705 case Decl::ParmVar: 1706 // These can only appear with other declarations which are banned in 1707 // C++11 and permitted in C++1y, so ignore them. 1708 continue; 1709 1710 case Decl::Var: 1711 case Decl::Decomposition: { 1712 // C++1y [dcl.constexpr]p3 allows anything except: 1713 // a definition of a variable of non-literal type or of static or 1714 // thread storage duration or for which no initialization is performed. 1715 const auto *VD = cast<VarDecl>(DclIt); 1716 if (VD->isThisDeclarationADefinition()) { 1717 if (VD->isStaticLocal()) { 1718 SemaRef.Diag(VD->getLocation(), 1719 diag::err_constexpr_local_var_static) 1720 << isa<CXXConstructorDecl>(Dcl) 1721 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1722 return false; 1723 } 1724 if (!VD->getType()->isDependentType() && 1725 SemaRef.RequireLiteralType( 1726 VD->getLocation(), VD->getType(), 1727 diag::err_constexpr_local_var_non_literal_type, 1728 isa<CXXConstructorDecl>(Dcl))) 1729 return false; 1730 if (!VD->getType()->isDependentType() && 1731 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1732 SemaRef.Diag(VD->getLocation(), 1733 diag::err_constexpr_local_var_no_init) 1734 << isa<CXXConstructorDecl>(Dcl); 1735 return false; 1736 } 1737 } 1738 SemaRef.Diag(VD->getLocation(), 1739 SemaRef.getLangOpts().CPlusPlus14 1740 ? diag::warn_cxx11_compat_constexpr_local_var 1741 : diag::ext_constexpr_local_var) 1742 << isa<CXXConstructorDecl>(Dcl); 1743 continue; 1744 } 1745 1746 case Decl::NamespaceAlias: 1747 case Decl::Function: 1748 // These are disallowed in C++11 and permitted in C++1y. Allow them 1749 // everywhere as an extension. 1750 if (!Cxx1yLoc.isValid()) 1751 Cxx1yLoc = DS->getLocStart(); 1752 continue; 1753 1754 default: 1755 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1756 << isa<CXXConstructorDecl>(Dcl); 1757 return false; 1758 } 1759 } 1760 1761 return true; 1762 } 1763 1764 /// Check that the given field is initialized within a constexpr constructor. 1765 /// 1766 /// \param Dcl The constexpr constructor being checked. 1767 /// \param Field The field being checked. This may be a member of an anonymous 1768 /// struct or union nested within the class being checked. 1769 /// \param Inits All declarations, including anonymous struct/union members and 1770 /// indirect members, for which any initialization was provided. 1771 /// \param Diagnosed Set to true if an error is produced. 1772 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1773 const FunctionDecl *Dcl, 1774 FieldDecl *Field, 1775 llvm::SmallSet<Decl*, 16> &Inits, 1776 bool &Diagnosed) { 1777 if (Field->isInvalidDecl()) 1778 return; 1779 1780 if (Field->isUnnamedBitfield()) 1781 return; 1782 1783 // Anonymous unions with no variant members and empty anonymous structs do not 1784 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1785 // indirect fields don't need initializing. 1786 if (Field->isAnonymousStructOrUnion() && 1787 (Field->getType()->isUnionType() 1788 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1789 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1790 return; 1791 1792 if (!Inits.count(Field)) { 1793 if (!Diagnosed) { 1794 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1795 Diagnosed = true; 1796 } 1797 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1798 } else if (Field->isAnonymousStructOrUnion()) { 1799 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1800 for (auto *I : RD->fields()) 1801 // If an anonymous union contains an anonymous struct of which any member 1802 // is initialized, all members must be initialized. 1803 if (!RD->isUnion() || Inits.count(I)) 1804 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1805 } 1806 } 1807 1808 /// Check the provided statement is allowed in a constexpr function 1809 /// definition. 1810 static bool 1811 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1812 SmallVectorImpl<SourceLocation> &ReturnStmts, 1813 SourceLocation &Cxx1yLoc) { 1814 // - its function-body shall be [...] a compound-statement that contains only 1815 switch (S->getStmtClass()) { 1816 case Stmt::NullStmtClass: 1817 // - null statements, 1818 return true; 1819 1820 case Stmt::DeclStmtClass: 1821 // - static_assert-declarations 1822 // - using-declarations, 1823 // - using-directives, 1824 // - typedef declarations and alias-declarations that do not define 1825 // classes or enumerations, 1826 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1827 return false; 1828 return true; 1829 1830 case Stmt::ReturnStmtClass: 1831 // - and exactly one return statement; 1832 if (isa<CXXConstructorDecl>(Dcl)) { 1833 // C++1y allows return statements in constexpr constructors. 1834 if (!Cxx1yLoc.isValid()) 1835 Cxx1yLoc = S->getLocStart(); 1836 return true; 1837 } 1838 1839 ReturnStmts.push_back(S->getLocStart()); 1840 return true; 1841 1842 case Stmt::CompoundStmtClass: { 1843 // C++1y allows compound-statements. 1844 if (!Cxx1yLoc.isValid()) 1845 Cxx1yLoc = S->getLocStart(); 1846 1847 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1848 for (auto *BodyIt : CompStmt->body()) { 1849 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1850 Cxx1yLoc)) 1851 return false; 1852 } 1853 return true; 1854 } 1855 1856 case Stmt::AttributedStmtClass: 1857 if (!Cxx1yLoc.isValid()) 1858 Cxx1yLoc = S->getLocStart(); 1859 return true; 1860 1861 case Stmt::IfStmtClass: { 1862 // C++1y allows if-statements. 1863 if (!Cxx1yLoc.isValid()) 1864 Cxx1yLoc = S->getLocStart(); 1865 1866 IfStmt *If = cast<IfStmt>(S); 1867 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1868 Cxx1yLoc)) 1869 return false; 1870 if (If->getElse() && 1871 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1872 Cxx1yLoc)) 1873 return false; 1874 return true; 1875 } 1876 1877 case Stmt::WhileStmtClass: 1878 case Stmt::DoStmtClass: 1879 case Stmt::ForStmtClass: 1880 case Stmt::CXXForRangeStmtClass: 1881 case Stmt::ContinueStmtClass: 1882 // C++1y allows all of these. We don't allow them as extensions in C++11, 1883 // because they don't make sense without variable mutation. 1884 if (!SemaRef.getLangOpts().CPlusPlus14) 1885 break; 1886 if (!Cxx1yLoc.isValid()) 1887 Cxx1yLoc = S->getLocStart(); 1888 for (Stmt *SubStmt : S->children()) 1889 if (SubStmt && 1890 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1891 Cxx1yLoc)) 1892 return false; 1893 return true; 1894 1895 case Stmt::SwitchStmtClass: 1896 case Stmt::CaseStmtClass: 1897 case Stmt::DefaultStmtClass: 1898 case Stmt::BreakStmtClass: 1899 // C++1y allows switch-statements, and since they don't need variable 1900 // mutation, we can reasonably allow them in C++11 as an extension. 1901 if (!Cxx1yLoc.isValid()) 1902 Cxx1yLoc = S->getLocStart(); 1903 for (Stmt *SubStmt : S->children()) 1904 if (SubStmt && 1905 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1906 Cxx1yLoc)) 1907 return false; 1908 return true; 1909 1910 default: 1911 if (!isa<Expr>(S)) 1912 break; 1913 1914 // C++1y allows expression-statements. 1915 if (!Cxx1yLoc.isValid()) 1916 Cxx1yLoc = S->getLocStart(); 1917 return true; 1918 } 1919 1920 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1921 << isa<CXXConstructorDecl>(Dcl); 1922 return false; 1923 } 1924 1925 /// Check the body for the given constexpr function declaration only contains 1926 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1927 /// 1928 /// \return true if the body is OK, false if we have diagnosed a problem. 1929 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1930 if (isa<CXXTryStmt>(Body)) { 1931 // C++11 [dcl.constexpr]p3: 1932 // The definition of a constexpr function shall satisfy the following 1933 // constraints: [...] 1934 // - its function-body shall be = delete, = default, or a 1935 // compound-statement 1936 // 1937 // C++11 [dcl.constexpr]p4: 1938 // In the definition of a constexpr constructor, [...] 1939 // - its function-body shall not be a function-try-block; 1940 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1941 << isa<CXXConstructorDecl>(Dcl); 1942 return false; 1943 } 1944 1945 SmallVector<SourceLocation, 4> ReturnStmts; 1946 1947 // - its function-body shall be [...] a compound-statement that contains only 1948 // [... list of cases ...] 1949 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1950 SourceLocation Cxx1yLoc; 1951 for (auto *BodyIt : CompBody->body()) { 1952 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1953 return false; 1954 } 1955 1956 if (Cxx1yLoc.isValid()) 1957 Diag(Cxx1yLoc, 1958 getLangOpts().CPlusPlus14 1959 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1960 : diag::ext_constexpr_body_invalid_stmt) 1961 << isa<CXXConstructorDecl>(Dcl); 1962 1963 if (const CXXConstructorDecl *Constructor 1964 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1965 const CXXRecordDecl *RD = Constructor->getParent(); 1966 // DR1359: 1967 // - every non-variant non-static data member and base class sub-object 1968 // shall be initialized; 1969 // DR1460: 1970 // - if the class is a union having variant members, exactly one of them 1971 // shall be initialized; 1972 if (RD->isUnion()) { 1973 if (Constructor->getNumCtorInitializers() == 0 && 1974 RD->hasVariantMembers()) { 1975 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1976 return false; 1977 } 1978 } else if (!Constructor->isDependentContext() && 1979 !Constructor->isDelegatingConstructor()) { 1980 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1981 1982 // Skip detailed checking if we have enough initializers, and we would 1983 // allow at most one initializer per member. 1984 bool AnyAnonStructUnionMembers = false; 1985 unsigned Fields = 0; 1986 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1987 E = RD->field_end(); I != E; ++I, ++Fields) { 1988 if (I->isAnonymousStructOrUnion()) { 1989 AnyAnonStructUnionMembers = true; 1990 break; 1991 } 1992 } 1993 // DR1460: 1994 // - if the class is a union-like class, but is not a union, for each of 1995 // its anonymous union members having variant members, exactly one of 1996 // them shall be initialized; 1997 if (AnyAnonStructUnionMembers || 1998 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1999 // Check initialization of non-static data members. Base classes are 2000 // always initialized so do not need to be checked. Dependent bases 2001 // might not have initializers in the member initializer list. 2002 llvm::SmallSet<Decl*, 16> Inits; 2003 for (const auto *I: Constructor->inits()) { 2004 if (FieldDecl *FD = I->getMember()) 2005 Inits.insert(FD); 2006 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2007 Inits.insert(ID->chain_begin(), ID->chain_end()); 2008 } 2009 2010 bool Diagnosed = false; 2011 for (auto *I : RD->fields()) 2012 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2013 if (Diagnosed) 2014 return false; 2015 } 2016 } 2017 } else { 2018 if (ReturnStmts.empty()) { 2019 // C++1y doesn't require constexpr functions to contain a 'return' 2020 // statement. We still do, unless the return type might be void, because 2021 // otherwise if there's no return statement, the function cannot 2022 // be used in a core constant expression. 2023 bool OK = getLangOpts().CPlusPlus14 && 2024 (Dcl->getReturnType()->isVoidType() || 2025 Dcl->getReturnType()->isDependentType()); 2026 Diag(Dcl->getLocation(), 2027 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2028 : diag::err_constexpr_body_no_return); 2029 if (!OK) 2030 return false; 2031 } else if (ReturnStmts.size() > 1) { 2032 Diag(ReturnStmts.back(), 2033 getLangOpts().CPlusPlus14 2034 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2035 : diag::ext_constexpr_body_multiple_return); 2036 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2037 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2038 } 2039 } 2040 2041 // C++11 [dcl.constexpr]p5: 2042 // if no function argument values exist such that the function invocation 2043 // substitution would produce a constant expression, the program is 2044 // ill-formed; no diagnostic required. 2045 // C++11 [dcl.constexpr]p3: 2046 // - every constructor call and implicit conversion used in initializing the 2047 // return value shall be one of those allowed in a constant expression. 2048 // C++11 [dcl.constexpr]p4: 2049 // - every constructor involved in initializing non-static data members and 2050 // base class sub-objects shall be a constexpr constructor. 2051 SmallVector<PartialDiagnosticAt, 8> Diags; 2052 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2053 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2054 << isa<CXXConstructorDecl>(Dcl); 2055 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2056 Diag(Diags[I].first, Diags[I].second); 2057 // Don't return false here: we allow this for compatibility in 2058 // system headers. 2059 } 2060 2061 return true; 2062 } 2063 2064 /// isCurrentClassName - Determine whether the identifier II is the 2065 /// name of the class type currently being defined. In the case of 2066 /// nested classes, this will only return true if II is the name of 2067 /// the innermost class. 2068 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2069 const CXXScopeSpec *SS) { 2070 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2071 2072 CXXRecordDecl *CurDecl; 2073 if (SS && SS->isSet() && !SS->isInvalid()) { 2074 DeclContext *DC = computeDeclContext(*SS, true); 2075 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2076 } else 2077 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2078 2079 if (CurDecl && CurDecl->getIdentifier()) 2080 return &II == CurDecl->getIdentifier(); 2081 return false; 2082 } 2083 2084 /// \brief Determine whether the identifier II is a typo for the name of 2085 /// the class type currently being defined. If so, update it to the identifier 2086 /// that should have been used. 2087 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2088 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2089 2090 if (!getLangOpts().SpellChecking) 2091 return false; 2092 2093 CXXRecordDecl *CurDecl; 2094 if (SS && SS->isSet() && !SS->isInvalid()) { 2095 DeclContext *DC = computeDeclContext(*SS, true); 2096 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2097 } else 2098 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2099 2100 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2101 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2102 < II->getLength()) { 2103 II = CurDecl->getIdentifier(); 2104 return true; 2105 } 2106 2107 return false; 2108 } 2109 2110 /// \brief Determine whether the given class is a base class of the given 2111 /// class, including looking at dependent bases. 2112 static bool findCircularInheritance(const CXXRecordDecl *Class, 2113 const CXXRecordDecl *Current) { 2114 SmallVector<const CXXRecordDecl*, 8> Queue; 2115 2116 Class = Class->getCanonicalDecl(); 2117 while (true) { 2118 for (const auto &I : Current->bases()) { 2119 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2120 if (!Base) 2121 continue; 2122 2123 Base = Base->getDefinition(); 2124 if (!Base) 2125 continue; 2126 2127 if (Base->getCanonicalDecl() == Class) 2128 return true; 2129 2130 Queue.push_back(Base); 2131 } 2132 2133 if (Queue.empty()) 2134 return false; 2135 2136 Current = Queue.pop_back_val(); 2137 } 2138 2139 return false; 2140 } 2141 2142 /// \brief Check the validity of a C++ base class specifier. 2143 /// 2144 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2145 /// and returns NULL otherwise. 2146 CXXBaseSpecifier * 2147 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2148 SourceRange SpecifierRange, 2149 bool Virtual, AccessSpecifier Access, 2150 TypeSourceInfo *TInfo, 2151 SourceLocation EllipsisLoc) { 2152 QualType BaseType = TInfo->getType(); 2153 2154 // C++ [class.union]p1: 2155 // A union shall not have base classes. 2156 if (Class->isUnion()) { 2157 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2158 << SpecifierRange; 2159 return nullptr; 2160 } 2161 2162 if (EllipsisLoc.isValid() && 2163 !TInfo->getType()->containsUnexpandedParameterPack()) { 2164 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2165 << TInfo->getTypeLoc().getSourceRange(); 2166 EllipsisLoc = SourceLocation(); 2167 } 2168 2169 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2170 2171 if (BaseType->isDependentType()) { 2172 // Make sure that we don't have circular inheritance among our dependent 2173 // bases. For non-dependent bases, the check for completeness below handles 2174 // this. 2175 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2176 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2177 ((BaseDecl = BaseDecl->getDefinition()) && 2178 findCircularInheritance(Class, BaseDecl))) { 2179 Diag(BaseLoc, diag::err_circular_inheritance) 2180 << BaseType << Context.getTypeDeclType(Class); 2181 2182 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2183 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2184 << BaseType; 2185 2186 return nullptr; 2187 } 2188 } 2189 2190 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2191 Class->getTagKind() == TTK_Class, 2192 Access, TInfo, EllipsisLoc); 2193 } 2194 2195 // Base specifiers must be record types. 2196 if (!BaseType->isRecordType()) { 2197 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2198 return nullptr; 2199 } 2200 2201 // C++ [class.union]p1: 2202 // A union shall not be used as a base class. 2203 if (BaseType->isUnionType()) { 2204 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2205 return nullptr; 2206 } 2207 2208 // For the MS ABI, propagate DLL attributes to base class templates. 2209 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2210 if (Attr *ClassAttr = getDLLAttr(Class)) { 2211 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2212 BaseType->getAsCXXRecordDecl())) { 2213 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2214 BaseLoc); 2215 } 2216 } 2217 } 2218 2219 // C++ [class.derived]p2: 2220 // The class-name in a base-specifier shall not be an incompletely 2221 // defined class. 2222 if (RequireCompleteType(BaseLoc, BaseType, 2223 diag::err_incomplete_base_class, SpecifierRange)) { 2224 Class->setInvalidDecl(); 2225 return nullptr; 2226 } 2227 2228 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2229 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2230 assert(BaseDecl && "Record type has no declaration"); 2231 BaseDecl = BaseDecl->getDefinition(); 2232 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2233 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2234 assert(CXXBaseDecl && "Base type is not a C++ type"); 2235 2236 // A class which contains a flexible array member is not suitable for use as a 2237 // base class: 2238 // - If the layout determines that a base comes before another base, 2239 // the flexible array member would index into the subsequent base. 2240 // - If the layout determines that base comes before the derived class, 2241 // the flexible array member would index into the derived class. 2242 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2243 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2244 << CXXBaseDecl->getDeclName(); 2245 return nullptr; 2246 } 2247 2248 // C++ [class]p3: 2249 // If a class is marked final and it appears as a base-type-specifier in 2250 // base-clause, the program is ill-formed. 2251 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2252 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2253 << CXXBaseDecl->getDeclName() 2254 << FA->isSpelledAsSealed(); 2255 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2256 << CXXBaseDecl->getDeclName() << FA->getRange(); 2257 return nullptr; 2258 } 2259 2260 if (BaseDecl->isInvalidDecl()) 2261 Class->setInvalidDecl(); 2262 2263 // Create the base specifier. 2264 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2265 Class->getTagKind() == TTK_Class, 2266 Access, TInfo, EllipsisLoc); 2267 } 2268 2269 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2270 /// one entry in the base class list of a class specifier, for 2271 /// example: 2272 /// class foo : public bar, virtual private baz { 2273 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2274 BaseResult 2275 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2276 ParsedAttributes &Attributes, 2277 bool Virtual, AccessSpecifier Access, 2278 ParsedType basetype, SourceLocation BaseLoc, 2279 SourceLocation EllipsisLoc) { 2280 if (!classdecl) 2281 return true; 2282 2283 AdjustDeclIfTemplate(classdecl); 2284 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2285 if (!Class) 2286 return true; 2287 2288 // We haven't yet attached the base specifiers. 2289 Class->setIsParsingBaseSpecifiers(); 2290 2291 // We do not support any C++11 attributes on base-specifiers yet. 2292 // Diagnose any attributes we see. 2293 if (!Attributes.empty()) { 2294 for (AttributeList *Attr = Attributes.getList(); Attr; 2295 Attr = Attr->getNext()) { 2296 if (Attr->isInvalid() || 2297 Attr->getKind() == AttributeList::IgnoredAttribute) 2298 continue; 2299 Diag(Attr->getLoc(), 2300 Attr->getKind() == AttributeList::UnknownAttribute 2301 ? diag::warn_unknown_attribute_ignored 2302 : diag::err_base_specifier_attribute) 2303 << Attr->getName(); 2304 } 2305 } 2306 2307 TypeSourceInfo *TInfo = nullptr; 2308 GetTypeFromParser(basetype, &TInfo); 2309 2310 if (EllipsisLoc.isInvalid() && 2311 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2312 UPPC_BaseType)) 2313 return true; 2314 2315 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2316 Virtual, Access, TInfo, 2317 EllipsisLoc)) 2318 return BaseSpec; 2319 else 2320 Class->setInvalidDecl(); 2321 2322 return true; 2323 } 2324 2325 /// Use small set to collect indirect bases. As this is only used 2326 /// locally, there's no need to abstract the small size parameter. 2327 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2328 2329 /// \brief Recursively add the bases of Type. Don't add Type itself. 2330 static void 2331 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2332 const QualType &Type) 2333 { 2334 // Even though the incoming type is a base, it might not be 2335 // a class -- it could be a template parm, for instance. 2336 if (auto Rec = Type->getAs<RecordType>()) { 2337 auto Decl = Rec->getAsCXXRecordDecl(); 2338 2339 // Iterate over its bases. 2340 for (const auto &BaseSpec : Decl->bases()) { 2341 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2342 .getUnqualifiedType(); 2343 if (Set.insert(Base).second) 2344 // If we've not already seen it, recurse. 2345 NoteIndirectBases(Context, Set, Base); 2346 } 2347 } 2348 } 2349 2350 /// \brief Performs the actual work of attaching the given base class 2351 /// specifiers to a C++ class. 2352 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2353 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2354 if (Bases.empty()) 2355 return false; 2356 2357 // Used to keep track of which base types we have already seen, so 2358 // that we can properly diagnose redundant direct base types. Note 2359 // that the key is always the unqualified canonical type of the base 2360 // class. 2361 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2362 2363 // Used to track indirect bases so we can see if a direct base is 2364 // ambiguous. 2365 IndirectBaseSet IndirectBaseTypes; 2366 2367 // Copy non-redundant base specifiers into permanent storage. 2368 unsigned NumGoodBases = 0; 2369 bool Invalid = false; 2370 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2371 QualType NewBaseType 2372 = Context.getCanonicalType(Bases[idx]->getType()); 2373 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2374 2375 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2376 if (KnownBase) { 2377 // C++ [class.mi]p3: 2378 // A class shall not be specified as a direct base class of a 2379 // derived class more than once. 2380 Diag(Bases[idx]->getLocStart(), 2381 diag::err_duplicate_base_class) 2382 << KnownBase->getType() 2383 << Bases[idx]->getSourceRange(); 2384 2385 // Delete the duplicate base class specifier; we're going to 2386 // overwrite its pointer later. 2387 Context.Deallocate(Bases[idx]); 2388 2389 Invalid = true; 2390 } else { 2391 // Okay, add this new base class. 2392 KnownBase = Bases[idx]; 2393 Bases[NumGoodBases++] = Bases[idx]; 2394 2395 // Note this base's direct & indirect bases, if there could be ambiguity. 2396 if (Bases.size() > 1) 2397 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2398 2399 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2400 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2401 if (Class->isInterface() && 2402 (!RD->isInterfaceLike() || 2403 KnownBase->getAccessSpecifier() != AS_public)) { 2404 // The Microsoft extension __interface does not permit bases that 2405 // are not themselves public interfaces. 2406 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2407 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 2408 << RD->getSourceRange(); 2409 Invalid = true; 2410 } 2411 if (RD->hasAttr<WeakAttr>()) 2412 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2413 } 2414 } 2415 } 2416 2417 // Attach the remaining base class specifiers to the derived class. 2418 Class->setBases(Bases.data(), NumGoodBases); 2419 2420 // Check that the only base classes that are duplicate are virtual. 2421 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2422 // Check whether this direct base is inaccessible due to ambiguity. 2423 QualType BaseType = Bases[idx]->getType(); 2424 2425 // Skip all dependent types in templates being used as base specifiers. 2426 // Checks below assume that the base specifier is a CXXRecord. 2427 if (BaseType->isDependentType()) 2428 continue; 2429 2430 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2431 .getUnqualifiedType(); 2432 2433 if (IndirectBaseTypes.count(CanonicalBase)) { 2434 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2435 /*DetectVirtual=*/true); 2436 bool found 2437 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2438 assert(found); 2439 (void)found; 2440 2441 if (Paths.isAmbiguous(CanonicalBase)) 2442 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2443 << BaseType << getAmbiguousPathsDisplayString(Paths) 2444 << Bases[idx]->getSourceRange(); 2445 else 2446 assert(Bases[idx]->isVirtual()); 2447 } 2448 2449 // Delete the base class specifier, since its data has been copied 2450 // into the CXXRecordDecl. 2451 Context.Deallocate(Bases[idx]); 2452 } 2453 2454 return Invalid; 2455 } 2456 2457 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2458 /// class, after checking whether there are any duplicate base 2459 /// classes. 2460 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2461 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2462 if (!ClassDecl || Bases.empty()) 2463 return; 2464 2465 AdjustDeclIfTemplate(ClassDecl); 2466 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2467 } 2468 2469 /// \brief Determine whether the type \p Derived is a C++ class that is 2470 /// derived from the type \p Base. 2471 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2472 if (!getLangOpts().CPlusPlus) 2473 return false; 2474 2475 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2476 if (!DerivedRD) 2477 return false; 2478 2479 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2480 if (!BaseRD) 2481 return false; 2482 2483 // If either the base or the derived type is invalid, don't try to 2484 // check whether one is derived from the other. 2485 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2486 return false; 2487 2488 // FIXME: In a modules build, do we need the entire path to be visible for us 2489 // to be able to use the inheritance relationship? 2490 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2491 return false; 2492 2493 return DerivedRD->isDerivedFrom(BaseRD); 2494 } 2495 2496 /// \brief Determine whether the type \p Derived is a C++ class that is 2497 /// derived from the type \p Base. 2498 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2499 CXXBasePaths &Paths) { 2500 if (!getLangOpts().CPlusPlus) 2501 return false; 2502 2503 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2504 if (!DerivedRD) 2505 return false; 2506 2507 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2508 if (!BaseRD) 2509 return false; 2510 2511 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2512 return false; 2513 2514 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2515 } 2516 2517 static void BuildBasePathArray(const CXXBasePath &Path, 2518 CXXCastPath &BasePathArray) { 2519 // We first go backward and check if we have a virtual base. 2520 // FIXME: It would be better if CXXBasePath had the base specifier for 2521 // the nearest virtual base. 2522 unsigned Start = 0; 2523 for (unsigned I = Path.size(); I != 0; --I) { 2524 if (Path[I - 1].Base->isVirtual()) { 2525 Start = I - 1; 2526 break; 2527 } 2528 } 2529 2530 // Now add all bases. 2531 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2533 } 2534 2535 2536 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2537 CXXCastPath &BasePathArray) { 2538 assert(BasePathArray.empty() && "Base path array must be empty!"); 2539 assert(Paths.isRecordingPaths() && "Must record paths!"); 2540 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2541 } 2542 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2543 /// conversion (where Derived and Base are class types) is 2544 /// well-formed, meaning that the conversion is unambiguous (and 2545 /// that all of the base classes are accessible). Returns true 2546 /// and emits a diagnostic if the code is ill-formed, returns false 2547 /// otherwise. Loc is the location where this routine should point to 2548 /// if there is an error, and Range is the source range to highlight 2549 /// if there is an error. 2550 /// 2551 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2552 /// diagnostic for the respective type of error will be suppressed, but the 2553 /// check for ill-formed code will still be performed. 2554 bool 2555 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2556 unsigned InaccessibleBaseID, 2557 unsigned AmbigiousBaseConvID, 2558 SourceLocation Loc, SourceRange Range, 2559 DeclarationName Name, 2560 CXXCastPath *BasePath, 2561 bool IgnoreAccess) { 2562 // First, determine whether the path from Derived to Base is 2563 // ambiguous. This is slightly more expensive than checking whether 2564 // the Derived to Base conversion exists, because here we need to 2565 // explore multiple paths to determine if there is an ambiguity. 2566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2567 /*DetectVirtual=*/false); 2568 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2569 if (!DerivationOkay) 2570 return true; 2571 2572 const CXXBasePath *Path = nullptr; 2573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2574 Path = &Paths.front(); 2575 2576 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2577 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2578 // user to access such bases. 2579 if (!Path && getLangOpts().MSVCCompat) { 2580 for (const CXXBasePath &PossiblePath : Paths) { 2581 if (PossiblePath.size() == 1) { 2582 Path = &PossiblePath; 2583 if (AmbigiousBaseConvID) 2584 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2585 << Base << Derived << Range; 2586 break; 2587 } 2588 } 2589 } 2590 2591 if (Path) { 2592 if (!IgnoreAccess) { 2593 // Check that the base class can be accessed. 2594 switch ( 2595 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2596 case AR_inaccessible: 2597 return true; 2598 case AR_accessible: 2599 case AR_dependent: 2600 case AR_delayed: 2601 break; 2602 } 2603 } 2604 2605 // Build a base path if necessary. 2606 if (BasePath) 2607 ::BuildBasePathArray(*Path, *BasePath); 2608 return false; 2609 } 2610 2611 if (AmbigiousBaseConvID) { 2612 // We know that the derived-to-base conversion is ambiguous, and 2613 // we're going to produce a diagnostic. Perform the derived-to-base 2614 // search just one more time to compute all of the possible paths so 2615 // that we can print them out. This is more expensive than any of 2616 // the previous derived-to-base checks we've done, but at this point 2617 // performance isn't as much of an issue. 2618 Paths.clear(); 2619 Paths.setRecordingPaths(true); 2620 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2621 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2622 (void)StillOkay; 2623 2624 // Build up a textual representation of the ambiguous paths, e.g., 2625 // D -> B -> A, that will be used to illustrate the ambiguous 2626 // conversions in the diagnostic. We only print one of the paths 2627 // to each base class subobject. 2628 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2629 2630 Diag(Loc, AmbigiousBaseConvID) 2631 << Derived << Base << PathDisplayStr << Range << Name; 2632 } 2633 return true; 2634 } 2635 2636 bool 2637 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2638 SourceLocation Loc, SourceRange Range, 2639 CXXCastPath *BasePath, 2640 bool IgnoreAccess) { 2641 return CheckDerivedToBaseConversion( 2642 Derived, Base, diag::err_upcast_to_inaccessible_base, 2643 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2644 BasePath, IgnoreAccess); 2645 } 2646 2647 2648 /// @brief Builds a string representing ambiguous paths from a 2649 /// specific derived class to different subobjects of the same base 2650 /// class. 2651 /// 2652 /// This function builds a string that can be used in error messages 2653 /// to show the different paths that one can take through the 2654 /// inheritance hierarchy to go from the derived class to different 2655 /// subobjects of a base class. The result looks something like this: 2656 /// @code 2657 /// struct D -> struct B -> struct A 2658 /// struct D -> struct C -> struct A 2659 /// @endcode 2660 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2661 std::string PathDisplayStr; 2662 std::set<unsigned> DisplayedPaths; 2663 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2664 Path != Paths.end(); ++Path) { 2665 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2666 // We haven't displayed a path to this particular base 2667 // class subobject yet. 2668 PathDisplayStr += "\n "; 2669 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2670 for (CXXBasePath::const_iterator Element = Path->begin(); 2671 Element != Path->end(); ++Element) 2672 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2673 } 2674 } 2675 2676 return PathDisplayStr; 2677 } 2678 2679 //===----------------------------------------------------------------------===// 2680 // C++ class member Handling 2681 //===----------------------------------------------------------------------===// 2682 2683 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2684 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2685 SourceLocation ASLoc, 2686 SourceLocation ColonLoc, 2687 AttributeList *Attrs) { 2688 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2689 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2690 ASLoc, ColonLoc); 2691 CurContext->addHiddenDecl(ASDecl); 2692 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2693 } 2694 2695 /// CheckOverrideControl - Check C++11 override control semantics. 2696 void Sema::CheckOverrideControl(NamedDecl *D) { 2697 if (D->isInvalidDecl()) 2698 return; 2699 2700 // We only care about "override" and "final" declarations. 2701 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2702 return; 2703 2704 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2705 2706 // We can't check dependent instance methods. 2707 if (MD && MD->isInstance() && 2708 (MD->getParent()->hasAnyDependentBases() || 2709 MD->getType()->isDependentType())) 2710 return; 2711 2712 if (MD && !MD->isVirtual()) { 2713 // If we have a non-virtual method, check if if hides a virtual method. 2714 // (In that case, it's most likely the method has the wrong type.) 2715 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2716 FindHiddenVirtualMethods(MD, OverloadedMethods); 2717 2718 if (!OverloadedMethods.empty()) { 2719 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2720 Diag(OA->getLocation(), 2721 diag::override_keyword_hides_virtual_member_function) 2722 << "override" << (OverloadedMethods.size() > 1); 2723 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2724 Diag(FA->getLocation(), 2725 diag::override_keyword_hides_virtual_member_function) 2726 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2727 << (OverloadedMethods.size() > 1); 2728 } 2729 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2730 MD->setInvalidDecl(); 2731 return; 2732 } 2733 // Fall through into the general case diagnostic. 2734 // FIXME: We might want to attempt typo correction here. 2735 } 2736 2737 if (!MD || !MD->isVirtual()) { 2738 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2739 Diag(OA->getLocation(), 2740 diag::override_keyword_only_allowed_on_virtual_member_functions) 2741 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2742 D->dropAttr<OverrideAttr>(); 2743 } 2744 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2745 Diag(FA->getLocation(), 2746 diag::override_keyword_only_allowed_on_virtual_member_functions) 2747 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2748 << FixItHint::CreateRemoval(FA->getLocation()); 2749 D->dropAttr<FinalAttr>(); 2750 } 2751 return; 2752 } 2753 2754 // C++11 [class.virtual]p5: 2755 // If a function is marked with the virt-specifier override and 2756 // does not override a member function of a base class, the program is 2757 // ill-formed. 2758 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2759 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2760 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2761 << MD->getDeclName(); 2762 } 2763 2764 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2765 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2766 return; 2767 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2768 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2769 return; 2770 2771 SourceLocation Loc = MD->getLocation(); 2772 SourceLocation SpellingLoc = Loc; 2773 if (getSourceManager().isMacroArgExpansion(Loc)) 2774 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 2775 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2776 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2777 return; 2778 2779 if (MD->size_overridden_methods() > 0) { 2780 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2781 ? diag::warn_destructor_marked_not_override_overriding 2782 : diag::warn_function_marked_not_override_overriding; 2783 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2784 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2785 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2786 } 2787 } 2788 2789 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2790 /// function overrides a virtual member function marked 'final', according to 2791 /// C++11 [class.virtual]p4. 2792 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2793 const CXXMethodDecl *Old) { 2794 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2795 if (!FA) 2796 return false; 2797 2798 Diag(New->getLocation(), diag::err_final_function_overridden) 2799 << New->getDeclName() 2800 << FA->isSpelledAsSealed(); 2801 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2802 return true; 2803 } 2804 2805 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2806 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2807 // FIXME: Destruction of ObjC lifetime types has side-effects. 2808 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2809 return !RD->isCompleteDefinition() || 2810 !RD->hasTrivialDefaultConstructor() || 2811 !RD->hasTrivialDestructor(); 2812 return false; 2813 } 2814 2815 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2816 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2817 if (it->isDeclspecPropertyAttribute()) 2818 return it; 2819 return nullptr; 2820 } 2821 2822 // Check if there is a field shadowing. 2823 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2824 DeclarationName FieldName, 2825 const CXXRecordDecl *RD) { 2826 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2827 return; 2828 2829 // To record a shadowed field in a base 2830 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2831 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2832 CXXBasePath &Path) { 2833 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2834 // Record an ambiguous path directly 2835 if (Bases.find(Base) != Bases.end()) 2836 return true; 2837 for (const auto Field : Base->lookup(FieldName)) { 2838 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2839 Field->getAccess() != AS_private) { 2840 assert(Field->getAccess() != AS_none); 2841 assert(Bases.find(Base) == Bases.end()); 2842 Bases[Base] = Field; 2843 return true; 2844 } 2845 } 2846 return false; 2847 }; 2848 2849 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2850 /*DetectVirtual=*/true); 2851 if (!RD->lookupInBases(FieldShadowed, Paths)) 2852 return; 2853 2854 for (const auto &P : Paths) { 2855 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2856 auto It = Bases.find(Base); 2857 // Skip duplicated bases 2858 if (It == Bases.end()) 2859 continue; 2860 auto BaseField = It->second; 2861 assert(BaseField->getAccess() != AS_private); 2862 if (AS_none != 2863 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2864 Diag(Loc, diag::warn_shadow_field) 2865 << FieldName.getAsString() << RD->getName() << Base->getName(); 2866 Diag(BaseField->getLocation(), diag::note_shadow_field); 2867 Bases.erase(It); 2868 } 2869 } 2870 } 2871 2872 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2873 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2874 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2875 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2876 /// present (but parsing it has been deferred). 2877 NamedDecl * 2878 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2879 MultiTemplateParamsArg TemplateParameterLists, 2880 Expr *BW, const VirtSpecifiers &VS, 2881 InClassInitStyle InitStyle) { 2882 const DeclSpec &DS = D.getDeclSpec(); 2883 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2884 DeclarationName Name = NameInfo.getName(); 2885 SourceLocation Loc = NameInfo.getLoc(); 2886 2887 // For anonymous bitfields, the location should point to the type. 2888 if (Loc.isInvalid()) 2889 Loc = D.getLocStart(); 2890 2891 Expr *BitWidth = static_cast<Expr*>(BW); 2892 2893 assert(isa<CXXRecordDecl>(CurContext)); 2894 assert(!DS.isFriendSpecified()); 2895 2896 bool isFunc = D.isDeclarationOfFunction(); 2897 AttributeList *MSPropertyAttr = 2898 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2899 2900 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2901 // The Microsoft extension __interface only permits public member functions 2902 // and prohibits constructors, destructors, operators, non-public member 2903 // functions, static methods and data members. 2904 unsigned InvalidDecl; 2905 bool ShowDeclName = true; 2906 if (!isFunc && 2907 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2908 InvalidDecl = 0; 2909 else if (!isFunc) 2910 InvalidDecl = 1; 2911 else if (AS != AS_public) 2912 InvalidDecl = 2; 2913 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2914 InvalidDecl = 3; 2915 else switch (Name.getNameKind()) { 2916 case DeclarationName::CXXConstructorName: 2917 InvalidDecl = 4; 2918 ShowDeclName = false; 2919 break; 2920 2921 case DeclarationName::CXXDestructorName: 2922 InvalidDecl = 5; 2923 ShowDeclName = false; 2924 break; 2925 2926 case DeclarationName::CXXOperatorName: 2927 case DeclarationName::CXXConversionFunctionName: 2928 InvalidDecl = 6; 2929 break; 2930 2931 default: 2932 InvalidDecl = 0; 2933 break; 2934 } 2935 2936 if (InvalidDecl) { 2937 if (ShowDeclName) 2938 Diag(Loc, diag::err_invalid_member_in_interface) 2939 << (InvalidDecl-1) << Name; 2940 else 2941 Diag(Loc, diag::err_invalid_member_in_interface) 2942 << (InvalidDecl-1) << ""; 2943 return nullptr; 2944 } 2945 } 2946 2947 // C++ 9.2p6: A member shall not be declared to have automatic storage 2948 // duration (auto, register) or with the extern storage-class-specifier. 2949 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2950 // data members and cannot be applied to names declared const or static, 2951 // and cannot be applied to reference members. 2952 switch (DS.getStorageClassSpec()) { 2953 case DeclSpec::SCS_unspecified: 2954 case DeclSpec::SCS_typedef: 2955 case DeclSpec::SCS_static: 2956 break; 2957 case DeclSpec::SCS_mutable: 2958 if (isFunc) { 2959 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2960 2961 // FIXME: It would be nicer if the keyword was ignored only for this 2962 // declarator. Otherwise we could get follow-up errors. 2963 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2964 } 2965 break; 2966 default: 2967 Diag(DS.getStorageClassSpecLoc(), 2968 diag::err_storageclass_invalid_for_member); 2969 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2970 break; 2971 } 2972 2973 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2974 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2975 !isFunc); 2976 2977 if (DS.isConstexprSpecified() && isInstField) { 2978 SemaDiagnosticBuilder B = 2979 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2980 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2981 if (InitStyle == ICIS_NoInit) { 2982 B << 0 << 0; 2983 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2984 B << FixItHint::CreateRemoval(ConstexprLoc); 2985 else { 2986 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2987 D.getMutableDeclSpec().ClearConstexprSpec(); 2988 const char *PrevSpec; 2989 unsigned DiagID; 2990 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2991 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2992 (void)Failed; 2993 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2994 } 2995 } else { 2996 B << 1; 2997 const char *PrevSpec; 2998 unsigned DiagID; 2999 if (D.getMutableDeclSpec().SetStorageClassSpec( 3000 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3001 Context.getPrintingPolicy())) { 3002 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3003 "This is the only DeclSpec that should fail to be applied"); 3004 B << 1; 3005 } else { 3006 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3007 isInstField = false; 3008 } 3009 } 3010 } 3011 3012 NamedDecl *Member; 3013 if (isInstField) { 3014 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3015 3016 // Data members must have identifiers for names. 3017 if (!Name.isIdentifier()) { 3018 Diag(Loc, diag::err_bad_variable_name) 3019 << Name; 3020 return nullptr; 3021 } 3022 3023 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3024 3025 // Member field could not be with "template" keyword. 3026 // So TemplateParameterLists should be empty in this case. 3027 if (TemplateParameterLists.size()) { 3028 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3029 if (TemplateParams->size()) { 3030 // There is no such thing as a member field template. 3031 Diag(D.getIdentifierLoc(), diag::err_template_member) 3032 << II 3033 << SourceRange(TemplateParams->getTemplateLoc(), 3034 TemplateParams->getRAngleLoc()); 3035 } else { 3036 // There is an extraneous 'template<>' for this member. 3037 Diag(TemplateParams->getTemplateLoc(), 3038 diag::err_template_member_noparams) 3039 << II 3040 << SourceRange(TemplateParams->getTemplateLoc(), 3041 TemplateParams->getRAngleLoc()); 3042 } 3043 return nullptr; 3044 } 3045 3046 if (SS.isSet() && !SS.isInvalid()) { 3047 // The user provided a superfluous scope specifier inside a class 3048 // definition: 3049 // 3050 // class X { 3051 // int X::member; 3052 // }; 3053 if (DeclContext *DC = computeDeclContext(SS, false)) 3054 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3055 D.getName().getKind() == 3056 UnqualifiedIdKind::IK_TemplateId); 3057 else 3058 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3059 << Name << SS.getRange(); 3060 3061 SS.clear(); 3062 } 3063 3064 if (MSPropertyAttr) { 3065 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3066 BitWidth, InitStyle, AS, MSPropertyAttr); 3067 if (!Member) 3068 return nullptr; 3069 isInstField = false; 3070 } else { 3071 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3072 BitWidth, InitStyle, AS); 3073 if (!Member) 3074 return nullptr; 3075 } 3076 3077 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3078 } else { 3079 Member = HandleDeclarator(S, D, TemplateParameterLists); 3080 if (!Member) 3081 return nullptr; 3082 3083 // Non-instance-fields can't have a bitfield. 3084 if (BitWidth) { 3085 if (Member->isInvalidDecl()) { 3086 // don't emit another diagnostic. 3087 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3088 // C++ 9.6p3: A bit-field shall not be a static member. 3089 // "static member 'A' cannot be a bit-field" 3090 Diag(Loc, diag::err_static_not_bitfield) 3091 << Name << BitWidth->getSourceRange(); 3092 } else if (isa<TypedefDecl>(Member)) { 3093 // "typedef member 'x' cannot be a bit-field" 3094 Diag(Loc, diag::err_typedef_not_bitfield) 3095 << Name << BitWidth->getSourceRange(); 3096 } else { 3097 // A function typedef ("typedef int f(); f a;"). 3098 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3099 Diag(Loc, diag::err_not_integral_type_bitfield) 3100 << Name << cast<ValueDecl>(Member)->getType() 3101 << BitWidth->getSourceRange(); 3102 } 3103 3104 BitWidth = nullptr; 3105 Member->setInvalidDecl(); 3106 } 3107 3108 Member->setAccess(AS); 3109 3110 // If we have declared a member function template or static data member 3111 // template, set the access of the templated declaration as well. 3112 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3113 FunTmpl->getTemplatedDecl()->setAccess(AS); 3114 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3115 VarTmpl->getTemplatedDecl()->setAccess(AS); 3116 } 3117 3118 if (VS.isOverrideSpecified()) 3119 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3120 if (VS.isFinalSpecified()) 3121 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3122 VS.isFinalSpelledSealed())); 3123 3124 if (VS.getLastLocation().isValid()) { 3125 // Update the end location of a method that has a virt-specifiers. 3126 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3127 MD->setRangeEnd(VS.getLastLocation()); 3128 } 3129 3130 CheckOverrideControl(Member); 3131 3132 assert((Name || isInstField) && "No identifier for non-field ?"); 3133 3134 if (isInstField) { 3135 FieldDecl *FD = cast<FieldDecl>(Member); 3136 FieldCollector->Add(FD); 3137 3138 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3139 // Remember all explicit private FieldDecls that have a name, no side 3140 // effects and are not part of a dependent type declaration. 3141 if (!FD->isImplicit() && FD->getDeclName() && 3142 FD->getAccess() == AS_private && 3143 !FD->hasAttr<UnusedAttr>() && 3144 !FD->getParent()->isDependentContext() && 3145 !InitializationHasSideEffects(*FD)) 3146 UnusedPrivateFields.insert(FD); 3147 } 3148 } 3149 3150 return Member; 3151 } 3152 3153 namespace { 3154 class UninitializedFieldVisitor 3155 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3156 Sema &S; 3157 // List of Decls to generate a warning on. Also remove Decls that become 3158 // initialized. 3159 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3160 // List of base classes of the record. Classes are removed after their 3161 // initializers. 3162 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3163 // Vector of decls to be removed from the Decl set prior to visiting the 3164 // nodes. These Decls may have been initialized in the prior initializer. 3165 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3166 // If non-null, add a note to the warning pointing back to the constructor. 3167 const CXXConstructorDecl *Constructor; 3168 // Variables to hold state when processing an initializer list. When 3169 // InitList is true, special case initialization of FieldDecls matching 3170 // InitListFieldDecl. 3171 bool InitList; 3172 FieldDecl *InitListFieldDecl; 3173 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3174 3175 public: 3176 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3177 UninitializedFieldVisitor(Sema &S, 3178 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3179 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3180 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3181 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3182 3183 // Returns true if the use of ME is not an uninitialized use. 3184 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3185 bool CheckReferenceOnly) { 3186 llvm::SmallVector<FieldDecl*, 4> Fields; 3187 bool ReferenceField = false; 3188 while (ME) { 3189 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3190 if (!FD) 3191 return false; 3192 Fields.push_back(FD); 3193 if (FD->getType()->isReferenceType()) 3194 ReferenceField = true; 3195 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3196 } 3197 3198 // Binding a reference to an unintialized field is not an 3199 // uninitialized use. 3200 if (CheckReferenceOnly && !ReferenceField) 3201 return true; 3202 3203 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3204 // Discard the first field since it is the field decl that is being 3205 // initialized. 3206 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3207 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3208 } 3209 3210 for (auto UsedIter = UsedFieldIndex.begin(), 3211 UsedEnd = UsedFieldIndex.end(), 3212 OrigIter = InitFieldIndex.begin(), 3213 OrigEnd = InitFieldIndex.end(); 3214 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3215 if (*UsedIter < *OrigIter) 3216 return true; 3217 if (*UsedIter > *OrigIter) 3218 break; 3219 } 3220 3221 return false; 3222 } 3223 3224 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3225 bool AddressOf) { 3226 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3227 return; 3228 3229 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3230 // or union. 3231 MemberExpr *FieldME = ME; 3232 3233 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3234 3235 Expr *Base = ME; 3236 while (MemberExpr *SubME = 3237 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3238 3239 if (isa<VarDecl>(SubME->getMemberDecl())) 3240 return; 3241 3242 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3243 if (!FD->isAnonymousStructOrUnion()) 3244 FieldME = SubME; 3245 3246 if (!FieldME->getType().isPODType(S.Context)) 3247 AllPODFields = false; 3248 3249 Base = SubME->getBase(); 3250 } 3251 3252 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3253 return; 3254 3255 if (AddressOf && AllPODFields) 3256 return; 3257 3258 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3259 3260 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3261 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3262 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3263 } 3264 3265 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3266 QualType T = BaseCast->getType(); 3267 if (T->isPointerType() && 3268 BaseClasses.count(T->getPointeeType())) { 3269 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3270 << T->getPointeeType() << FoundVD; 3271 } 3272 } 3273 } 3274 3275 if (!Decls.count(FoundVD)) 3276 return; 3277 3278 const bool IsReference = FoundVD->getType()->isReferenceType(); 3279 3280 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3281 // Special checking for initializer lists. 3282 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3283 return; 3284 } 3285 } else { 3286 // Prevent double warnings on use of unbounded references. 3287 if (CheckReferenceOnly && !IsReference) 3288 return; 3289 } 3290 3291 unsigned diag = IsReference 3292 ? diag::warn_reference_field_is_uninit 3293 : diag::warn_field_is_uninit; 3294 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3295 if (Constructor) 3296 S.Diag(Constructor->getLocation(), 3297 diag::note_uninit_in_this_constructor) 3298 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3299 3300 } 3301 3302 void HandleValue(Expr *E, bool AddressOf) { 3303 E = E->IgnoreParens(); 3304 3305 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3306 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3307 AddressOf /*AddressOf*/); 3308 return; 3309 } 3310 3311 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3312 Visit(CO->getCond()); 3313 HandleValue(CO->getTrueExpr(), AddressOf); 3314 HandleValue(CO->getFalseExpr(), AddressOf); 3315 return; 3316 } 3317 3318 if (BinaryConditionalOperator *BCO = 3319 dyn_cast<BinaryConditionalOperator>(E)) { 3320 Visit(BCO->getCond()); 3321 HandleValue(BCO->getFalseExpr(), AddressOf); 3322 return; 3323 } 3324 3325 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3326 HandleValue(OVE->getSourceExpr(), AddressOf); 3327 return; 3328 } 3329 3330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3331 switch (BO->getOpcode()) { 3332 default: 3333 break; 3334 case(BO_PtrMemD): 3335 case(BO_PtrMemI): 3336 HandleValue(BO->getLHS(), AddressOf); 3337 Visit(BO->getRHS()); 3338 return; 3339 case(BO_Comma): 3340 Visit(BO->getLHS()); 3341 HandleValue(BO->getRHS(), AddressOf); 3342 return; 3343 } 3344 } 3345 3346 Visit(E); 3347 } 3348 3349 void CheckInitListExpr(InitListExpr *ILE) { 3350 InitFieldIndex.push_back(0); 3351 for (auto Child : ILE->children()) { 3352 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3353 CheckInitListExpr(SubList); 3354 } else { 3355 Visit(Child); 3356 } 3357 ++InitFieldIndex.back(); 3358 } 3359 InitFieldIndex.pop_back(); 3360 } 3361 3362 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3363 FieldDecl *Field, const Type *BaseClass) { 3364 // Remove Decls that may have been initialized in the previous 3365 // initializer. 3366 for (ValueDecl* VD : DeclsToRemove) 3367 Decls.erase(VD); 3368 DeclsToRemove.clear(); 3369 3370 Constructor = FieldConstructor; 3371 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3372 3373 if (ILE && Field) { 3374 InitList = true; 3375 InitListFieldDecl = Field; 3376 InitFieldIndex.clear(); 3377 CheckInitListExpr(ILE); 3378 } else { 3379 InitList = false; 3380 Visit(E); 3381 } 3382 3383 if (Field) 3384 Decls.erase(Field); 3385 if (BaseClass) 3386 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3387 } 3388 3389 void VisitMemberExpr(MemberExpr *ME) { 3390 // All uses of unbounded reference fields will warn. 3391 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3392 } 3393 3394 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3395 if (E->getCastKind() == CK_LValueToRValue) { 3396 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3397 return; 3398 } 3399 3400 Inherited::VisitImplicitCastExpr(E); 3401 } 3402 3403 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3404 if (E->getConstructor()->isCopyConstructor()) { 3405 Expr *ArgExpr = E->getArg(0); 3406 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3407 if (ILE->getNumInits() == 1) 3408 ArgExpr = ILE->getInit(0); 3409 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3410 if (ICE->getCastKind() == CK_NoOp) 3411 ArgExpr = ICE->getSubExpr(); 3412 HandleValue(ArgExpr, false /*AddressOf*/); 3413 return; 3414 } 3415 Inherited::VisitCXXConstructExpr(E); 3416 } 3417 3418 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3419 Expr *Callee = E->getCallee(); 3420 if (isa<MemberExpr>(Callee)) { 3421 HandleValue(Callee, false /*AddressOf*/); 3422 for (auto Arg : E->arguments()) 3423 Visit(Arg); 3424 return; 3425 } 3426 3427 Inherited::VisitCXXMemberCallExpr(E); 3428 } 3429 3430 void VisitCallExpr(CallExpr *E) { 3431 // Treat std::move as a use. 3432 if (E->isCallToStdMove()) { 3433 HandleValue(E->getArg(0), /*AddressOf=*/false); 3434 return; 3435 } 3436 3437 Inherited::VisitCallExpr(E); 3438 } 3439 3440 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3441 Expr *Callee = E->getCallee(); 3442 3443 if (isa<UnresolvedLookupExpr>(Callee)) 3444 return Inherited::VisitCXXOperatorCallExpr(E); 3445 3446 Visit(Callee); 3447 for (auto Arg : E->arguments()) 3448 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3449 } 3450 3451 void VisitBinaryOperator(BinaryOperator *E) { 3452 // If a field assignment is detected, remove the field from the 3453 // uninitiailized field set. 3454 if (E->getOpcode() == BO_Assign) 3455 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3456 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3457 if (!FD->getType()->isReferenceType()) 3458 DeclsToRemove.push_back(FD); 3459 3460 if (E->isCompoundAssignmentOp()) { 3461 HandleValue(E->getLHS(), false /*AddressOf*/); 3462 Visit(E->getRHS()); 3463 return; 3464 } 3465 3466 Inherited::VisitBinaryOperator(E); 3467 } 3468 3469 void VisitUnaryOperator(UnaryOperator *E) { 3470 if (E->isIncrementDecrementOp()) { 3471 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3472 return; 3473 } 3474 if (E->getOpcode() == UO_AddrOf) { 3475 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3476 HandleValue(ME->getBase(), true /*AddressOf*/); 3477 return; 3478 } 3479 } 3480 3481 Inherited::VisitUnaryOperator(E); 3482 } 3483 }; 3484 3485 // Diagnose value-uses of fields to initialize themselves, e.g. 3486 // foo(foo) 3487 // where foo is not also a parameter to the constructor. 3488 // Also diagnose across field uninitialized use such as 3489 // x(y), y(x) 3490 // TODO: implement -Wuninitialized and fold this into that framework. 3491 static void DiagnoseUninitializedFields( 3492 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3493 3494 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3495 Constructor->getLocation())) { 3496 return; 3497 } 3498 3499 if (Constructor->isInvalidDecl()) 3500 return; 3501 3502 const CXXRecordDecl *RD = Constructor->getParent(); 3503 3504 if (RD->getDescribedClassTemplate()) 3505 return; 3506 3507 // Holds fields that are uninitialized. 3508 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3509 3510 // At the beginning, all fields are uninitialized. 3511 for (auto *I : RD->decls()) { 3512 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3513 UninitializedFields.insert(FD); 3514 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3515 UninitializedFields.insert(IFD->getAnonField()); 3516 } 3517 } 3518 3519 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3520 for (auto I : RD->bases()) 3521 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3522 3523 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3524 return; 3525 3526 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3527 UninitializedFields, 3528 UninitializedBaseClasses); 3529 3530 for (const auto *FieldInit : Constructor->inits()) { 3531 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3532 break; 3533 3534 Expr *InitExpr = FieldInit->getInit(); 3535 if (!InitExpr) 3536 continue; 3537 3538 if (CXXDefaultInitExpr *Default = 3539 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3540 InitExpr = Default->getExpr(); 3541 if (!InitExpr) 3542 continue; 3543 // In class initializers will point to the constructor. 3544 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3545 FieldInit->getAnyMember(), 3546 FieldInit->getBaseClass()); 3547 } else { 3548 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3549 FieldInit->getAnyMember(), 3550 FieldInit->getBaseClass()); 3551 } 3552 } 3553 } 3554 } // namespace 3555 3556 /// \brief Enter a new C++ default initializer scope. After calling this, the 3557 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3558 /// parsing or instantiating the initializer failed. 3559 void Sema::ActOnStartCXXInClassMemberInitializer() { 3560 // Create a synthetic function scope to represent the call to the constructor 3561 // that notionally surrounds a use of this initializer. 3562 PushFunctionScope(); 3563 } 3564 3565 /// \brief This is invoked after parsing an in-class initializer for a 3566 /// non-static C++ class member, and after instantiating an in-class initializer 3567 /// in a class template. Such actions are deferred until the class is complete. 3568 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3569 SourceLocation InitLoc, 3570 Expr *InitExpr) { 3571 // Pop the notional constructor scope we created earlier. 3572 PopFunctionScopeInfo(nullptr, D); 3573 3574 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3575 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3576 "must set init style when field is created"); 3577 3578 if (!InitExpr) { 3579 D->setInvalidDecl(); 3580 if (FD) 3581 FD->removeInClassInitializer(); 3582 return; 3583 } 3584 3585 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3586 FD->setInvalidDecl(); 3587 FD->removeInClassInitializer(); 3588 return; 3589 } 3590 3591 ExprResult Init = InitExpr; 3592 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3593 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3594 InitializationKind Kind = 3595 FD->getInClassInitStyle() == ICIS_ListInit 3596 ? InitializationKind::CreateDirectList(InitExpr->getLocStart(), 3597 InitExpr->getLocStart(), 3598 InitExpr->getLocEnd()) 3599 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3600 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3601 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3602 if (Init.isInvalid()) { 3603 FD->setInvalidDecl(); 3604 return; 3605 } 3606 } 3607 3608 // C++11 [class.base.init]p7: 3609 // The initialization of each base and member constitutes a 3610 // full-expression. 3611 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3612 if (Init.isInvalid()) { 3613 FD->setInvalidDecl(); 3614 return; 3615 } 3616 3617 InitExpr = Init.get(); 3618 3619 FD->setInClassInitializer(InitExpr); 3620 } 3621 3622 /// \brief Find the direct and/or virtual base specifiers that 3623 /// correspond to the given base type, for use in base initialization 3624 /// within a constructor. 3625 static bool FindBaseInitializer(Sema &SemaRef, 3626 CXXRecordDecl *ClassDecl, 3627 QualType BaseType, 3628 const CXXBaseSpecifier *&DirectBaseSpec, 3629 const CXXBaseSpecifier *&VirtualBaseSpec) { 3630 // First, check for a direct base class. 3631 DirectBaseSpec = nullptr; 3632 for (const auto &Base : ClassDecl->bases()) { 3633 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3634 // We found a direct base of this type. That's what we're 3635 // initializing. 3636 DirectBaseSpec = &Base; 3637 break; 3638 } 3639 } 3640 3641 // Check for a virtual base class. 3642 // FIXME: We might be able to short-circuit this if we know in advance that 3643 // there are no virtual bases. 3644 VirtualBaseSpec = nullptr; 3645 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3646 // We haven't found a base yet; search the class hierarchy for a 3647 // virtual base class. 3648 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3649 /*DetectVirtual=*/false); 3650 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3651 SemaRef.Context.getTypeDeclType(ClassDecl), 3652 BaseType, Paths)) { 3653 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3654 Path != Paths.end(); ++Path) { 3655 if (Path->back().Base->isVirtual()) { 3656 VirtualBaseSpec = Path->back().Base; 3657 break; 3658 } 3659 } 3660 } 3661 } 3662 3663 return DirectBaseSpec || VirtualBaseSpec; 3664 } 3665 3666 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3667 MemInitResult 3668 Sema::ActOnMemInitializer(Decl *ConstructorD, 3669 Scope *S, 3670 CXXScopeSpec &SS, 3671 IdentifierInfo *MemberOrBase, 3672 ParsedType TemplateTypeTy, 3673 const DeclSpec &DS, 3674 SourceLocation IdLoc, 3675 Expr *InitList, 3676 SourceLocation EllipsisLoc) { 3677 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3678 DS, IdLoc, InitList, 3679 EllipsisLoc); 3680 } 3681 3682 /// \brief Handle a C++ member initializer using parentheses syntax. 3683 MemInitResult 3684 Sema::ActOnMemInitializer(Decl *ConstructorD, 3685 Scope *S, 3686 CXXScopeSpec &SS, 3687 IdentifierInfo *MemberOrBase, 3688 ParsedType TemplateTypeTy, 3689 const DeclSpec &DS, 3690 SourceLocation IdLoc, 3691 SourceLocation LParenLoc, 3692 ArrayRef<Expr *> Args, 3693 SourceLocation RParenLoc, 3694 SourceLocation EllipsisLoc) { 3695 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3696 Args, RParenLoc); 3697 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3698 DS, IdLoc, List, EllipsisLoc); 3699 } 3700 3701 namespace { 3702 3703 // Callback to only accept typo corrections that can be a valid C++ member 3704 // intializer: either a non-static field member or a base class. 3705 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3706 public: 3707 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3708 : ClassDecl(ClassDecl) {} 3709 3710 bool ValidateCandidate(const TypoCorrection &candidate) override { 3711 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3712 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3713 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3714 return isa<TypeDecl>(ND); 3715 } 3716 return false; 3717 } 3718 3719 private: 3720 CXXRecordDecl *ClassDecl; 3721 }; 3722 3723 } 3724 3725 /// \brief Handle a C++ member initializer. 3726 MemInitResult 3727 Sema::BuildMemInitializer(Decl *ConstructorD, 3728 Scope *S, 3729 CXXScopeSpec &SS, 3730 IdentifierInfo *MemberOrBase, 3731 ParsedType TemplateTypeTy, 3732 const DeclSpec &DS, 3733 SourceLocation IdLoc, 3734 Expr *Init, 3735 SourceLocation EllipsisLoc) { 3736 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3737 if (!Res.isUsable()) 3738 return true; 3739 Init = Res.get(); 3740 3741 if (!ConstructorD) 3742 return true; 3743 3744 AdjustDeclIfTemplate(ConstructorD); 3745 3746 CXXConstructorDecl *Constructor 3747 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3748 if (!Constructor) { 3749 // The user wrote a constructor initializer on a function that is 3750 // not a C++ constructor. Ignore the error for now, because we may 3751 // have more member initializers coming; we'll diagnose it just 3752 // once in ActOnMemInitializers. 3753 return true; 3754 } 3755 3756 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3757 3758 // C++ [class.base.init]p2: 3759 // Names in a mem-initializer-id are looked up in the scope of the 3760 // constructor's class and, if not found in that scope, are looked 3761 // up in the scope containing the constructor's definition. 3762 // [Note: if the constructor's class contains a member with the 3763 // same name as a direct or virtual base class of the class, a 3764 // mem-initializer-id naming the member or base class and composed 3765 // of a single identifier refers to the class member. A 3766 // mem-initializer-id for the hidden base class may be specified 3767 // using a qualified name. ] 3768 if (!SS.getScopeRep() && !TemplateTypeTy) { 3769 // Look for a member, first. 3770 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3771 if (!Result.empty()) { 3772 ValueDecl *Member; 3773 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3774 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3775 if (EllipsisLoc.isValid()) 3776 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3777 << MemberOrBase 3778 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3779 3780 return BuildMemberInitializer(Member, Init, IdLoc); 3781 } 3782 } 3783 } 3784 // It didn't name a member, so see if it names a class. 3785 QualType BaseType; 3786 TypeSourceInfo *TInfo = nullptr; 3787 3788 if (TemplateTypeTy) { 3789 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3790 } else if (DS.getTypeSpecType() == TST_decltype) { 3791 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3792 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3793 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3794 return true; 3795 } else { 3796 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3797 LookupParsedName(R, S, &SS); 3798 3799 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3800 if (!TyD) { 3801 if (R.isAmbiguous()) return true; 3802 3803 // We don't want access-control diagnostics here. 3804 R.suppressDiagnostics(); 3805 3806 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3807 bool NotUnknownSpecialization = false; 3808 DeclContext *DC = computeDeclContext(SS, false); 3809 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3810 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3811 3812 if (!NotUnknownSpecialization) { 3813 // When the scope specifier can refer to a member of an unknown 3814 // specialization, we take it as a type name. 3815 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3816 SS.getWithLocInContext(Context), 3817 *MemberOrBase, IdLoc); 3818 if (BaseType.isNull()) 3819 return true; 3820 3821 TInfo = Context.CreateTypeSourceInfo(BaseType); 3822 DependentNameTypeLoc TL = 3823 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3824 if (!TL.isNull()) { 3825 TL.setNameLoc(IdLoc); 3826 TL.setElaboratedKeywordLoc(SourceLocation()); 3827 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3828 } 3829 3830 R.clear(); 3831 R.setLookupName(MemberOrBase); 3832 } 3833 } 3834 3835 // If no results were found, try to correct typos. 3836 TypoCorrection Corr; 3837 if (R.empty() && BaseType.isNull() && 3838 (Corr = CorrectTypo( 3839 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3840 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3841 CTK_ErrorRecovery, ClassDecl))) { 3842 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3843 // We have found a non-static data member with a similar 3844 // name to what was typed; complain and initialize that 3845 // member. 3846 diagnoseTypo(Corr, 3847 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3848 << MemberOrBase << true); 3849 return BuildMemberInitializer(Member, Init, IdLoc); 3850 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3851 const CXXBaseSpecifier *DirectBaseSpec; 3852 const CXXBaseSpecifier *VirtualBaseSpec; 3853 if (FindBaseInitializer(*this, ClassDecl, 3854 Context.getTypeDeclType(Type), 3855 DirectBaseSpec, VirtualBaseSpec)) { 3856 // We have found a direct or virtual base class with a 3857 // similar name to what was typed; complain and initialize 3858 // that base class. 3859 diagnoseTypo(Corr, 3860 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3861 << MemberOrBase << false, 3862 PDiag() /*Suppress note, we provide our own.*/); 3863 3864 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3865 : VirtualBaseSpec; 3866 Diag(BaseSpec->getLocStart(), 3867 diag::note_base_class_specified_here) 3868 << BaseSpec->getType() 3869 << BaseSpec->getSourceRange(); 3870 3871 TyD = Type; 3872 } 3873 } 3874 } 3875 3876 if (!TyD && BaseType.isNull()) { 3877 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3878 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3879 return true; 3880 } 3881 } 3882 3883 if (BaseType.isNull()) { 3884 BaseType = Context.getTypeDeclType(TyD); 3885 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3886 if (SS.isSet()) { 3887 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3888 BaseType); 3889 TInfo = Context.CreateTypeSourceInfo(BaseType); 3890 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3891 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3892 TL.setElaboratedKeywordLoc(SourceLocation()); 3893 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3894 } 3895 } 3896 } 3897 3898 if (!TInfo) 3899 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3900 3901 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3902 } 3903 3904 /// Checks a member initializer expression for cases where reference (or 3905 /// pointer) members are bound to by-value parameters (or their addresses). 3906 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3907 Expr *Init, 3908 SourceLocation IdLoc) { 3909 QualType MemberTy = Member->getType(); 3910 3911 // We only handle pointers and references currently. 3912 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3913 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3914 return; 3915 3916 const bool IsPointer = MemberTy->isPointerType(); 3917 if (IsPointer) { 3918 if (const UnaryOperator *Op 3919 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3920 // The only case we're worried about with pointers requires taking the 3921 // address. 3922 if (Op->getOpcode() != UO_AddrOf) 3923 return; 3924 3925 Init = Op->getSubExpr(); 3926 } else { 3927 // We only handle address-of expression initializers for pointers. 3928 return; 3929 } 3930 } 3931 3932 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3933 // We only warn when referring to a non-reference parameter declaration. 3934 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3935 if (!Parameter || Parameter->getType()->isReferenceType()) 3936 return; 3937 3938 S.Diag(Init->getExprLoc(), 3939 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3940 : diag::warn_bind_ref_member_to_parameter) 3941 << Member << Parameter << Init->getSourceRange(); 3942 } else { 3943 // Other initializers are fine. 3944 return; 3945 } 3946 3947 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3948 << (unsigned)IsPointer; 3949 } 3950 3951 MemInitResult 3952 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3953 SourceLocation IdLoc) { 3954 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3955 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3956 assert((DirectMember || IndirectMember) && 3957 "Member must be a FieldDecl or IndirectFieldDecl"); 3958 3959 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3960 return true; 3961 3962 if (Member->isInvalidDecl()) 3963 return true; 3964 3965 MultiExprArg Args; 3966 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3967 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3968 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3969 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3970 } else { 3971 // Template instantiation doesn't reconstruct ParenListExprs for us. 3972 Args = Init; 3973 } 3974 3975 SourceRange InitRange = Init->getSourceRange(); 3976 3977 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3978 // Can't check initialization for a member of dependent type or when 3979 // any of the arguments are type-dependent expressions. 3980 DiscardCleanupsInEvaluationContext(); 3981 } else { 3982 bool InitList = false; 3983 if (isa<InitListExpr>(Init)) { 3984 InitList = true; 3985 Args = Init; 3986 } 3987 3988 // Initialize the member. 3989 InitializedEntity MemberEntity = 3990 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3991 : InitializedEntity::InitializeMember(IndirectMember, 3992 nullptr); 3993 InitializationKind Kind = 3994 InitList ? InitializationKind::CreateDirectList( 3995 IdLoc, Init->getLocStart(), Init->getLocEnd()) 3996 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3997 InitRange.getEnd()); 3998 3999 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4000 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4001 nullptr); 4002 if (MemberInit.isInvalid()) 4003 return true; 4004 4005 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 4006 4007 // C++11 [class.base.init]p7: 4008 // The initialization of each base and member constitutes a 4009 // full-expression. 4010 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 4011 if (MemberInit.isInvalid()) 4012 return true; 4013 4014 Init = MemberInit.get(); 4015 } 4016 4017 if (DirectMember) { 4018 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4019 InitRange.getBegin(), Init, 4020 InitRange.getEnd()); 4021 } else { 4022 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4023 InitRange.getBegin(), Init, 4024 InitRange.getEnd()); 4025 } 4026 } 4027 4028 MemInitResult 4029 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4030 CXXRecordDecl *ClassDecl) { 4031 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4032 if (!LangOpts.CPlusPlus11) 4033 return Diag(NameLoc, diag::err_delegating_ctor) 4034 << TInfo->getTypeLoc().getLocalSourceRange(); 4035 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4036 4037 bool InitList = true; 4038 MultiExprArg Args = Init; 4039 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4040 InitList = false; 4041 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4042 } 4043 4044 SourceRange InitRange = Init->getSourceRange(); 4045 // Initialize the object. 4046 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4047 QualType(ClassDecl->getTypeForDecl(), 0)); 4048 InitializationKind Kind = 4049 InitList ? InitializationKind::CreateDirectList( 4050 NameLoc, Init->getLocStart(), Init->getLocEnd()) 4051 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4052 InitRange.getEnd()); 4053 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4054 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4055 Args, nullptr); 4056 if (DelegationInit.isInvalid()) 4057 return true; 4058 4059 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4060 "Delegating constructor with no target?"); 4061 4062 // C++11 [class.base.init]p7: 4063 // The initialization of each base and member constitutes a 4064 // full-expression. 4065 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4066 InitRange.getBegin()); 4067 if (DelegationInit.isInvalid()) 4068 return true; 4069 4070 // If we are in a dependent context, template instantiation will 4071 // perform this type-checking again. Just save the arguments that we 4072 // received in a ParenListExpr. 4073 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4074 // of the information that we have about the base 4075 // initializer. However, deconstructing the ASTs is a dicey process, 4076 // and this approach is far more likely to get the corner cases right. 4077 if (CurContext->isDependentContext()) 4078 DelegationInit = Init; 4079 4080 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4081 DelegationInit.getAs<Expr>(), 4082 InitRange.getEnd()); 4083 } 4084 4085 MemInitResult 4086 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4087 Expr *Init, CXXRecordDecl *ClassDecl, 4088 SourceLocation EllipsisLoc) { 4089 SourceLocation BaseLoc 4090 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4091 4092 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4093 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4094 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4095 4096 // C++ [class.base.init]p2: 4097 // [...] Unless the mem-initializer-id names a nonstatic data 4098 // member of the constructor's class or a direct or virtual base 4099 // of that class, the mem-initializer is ill-formed. A 4100 // mem-initializer-list can initialize a base class using any 4101 // name that denotes that base class type. 4102 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4103 4104 SourceRange InitRange = Init->getSourceRange(); 4105 if (EllipsisLoc.isValid()) { 4106 // This is a pack expansion. 4107 if (!BaseType->containsUnexpandedParameterPack()) { 4108 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4109 << SourceRange(BaseLoc, InitRange.getEnd()); 4110 4111 EllipsisLoc = SourceLocation(); 4112 } 4113 } else { 4114 // Check for any unexpanded parameter packs. 4115 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4116 return true; 4117 4118 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4119 return true; 4120 } 4121 4122 // Check for direct and virtual base classes. 4123 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4124 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4125 if (!Dependent) { 4126 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4127 BaseType)) 4128 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4129 4130 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4131 VirtualBaseSpec); 4132 4133 // C++ [base.class.init]p2: 4134 // Unless the mem-initializer-id names a nonstatic data member of the 4135 // constructor's class or a direct or virtual base of that class, the 4136 // mem-initializer is ill-formed. 4137 if (!DirectBaseSpec && !VirtualBaseSpec) { 4138 // If the class has any dependent bases, then it's possible that 4139 // one of those types will resolve to the same type as 4140 // BaseType. Therefore, just treat this as a dependent base 4141 // class initialization. FIXME: Should we try to check the 4142 // initialization anyway? It seems odd. 4143 if (ClassDecl->hasAnyDependentBases()) 4144 Dependent = true; 4145 else 4146 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4147 << BaseType << Context.getTypeDeclType(ClassDecl) 4148 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4149 } 4150 } 4151 4152 if (Dependent) { 4153 DiscardCleanupsInEvaluationContext(); 4154 4155 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4156 /*IsVirtual=*/false, 4157 InitRange.getBegin(), Init, 4158 InitRange.getEnd(), EllipsisLoc); 4159 } 4160 4161 // C++ [base.class.init]p2: 4162 // If a mem-initializer-id is ambiguous because it designates both 4163 // a direct non-virtual base class and an inherited virtual base 4164 // class, the mem-initializer is ill-formed. 4165 if (DirectBaseSpec && VirtualBaseSpec) 4166 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4167 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4168 4169 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4170 if (!BaseSpec) 4171 BaseSpec = VirtualBaseSpec; 4172 4173 // Initialize the base. 4174 bool InitList = true; 4175 MultiExprArg Args = Init; 4176 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4177 InitList = false; 4178 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4179 } 4180 4181 InitializedEntity BaseEntity = 4182 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4183 InitializationKind Kind = 4184 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4185 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4186 InitRange.getEnd()); 4187 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4188 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4189 if (BaseInit.isInvalid()) 4190 return true; 4191 4192 // C++11 [class.base.init]p7: 4193 // The initialization of each base and member constitutes a 4194 // full-expression. 4195 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4196 if (BaseInit.isInvalid()) 4197 return true; 4198 4199 // If we are in a dependent context, template instantiation will 4200 // perform this type-checking again. Just save the arguments that we 4201 // received in a ParenListExpr. 4202 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4203 // of the information that we have about the base 4204 // initializer. However, deconstructing the ASTs is a dicey process, 4205 // and this approach is far more likely to get the corner cases right. 4206 if (CurContext->isDependentContext()) 4207 BaseInit = Init; 4208 4209 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4210 BaseSpec->isVirtual(), 4211 InitRange.getBegin(), 4212 BaseInit.getAs<Expr>(), 4213 InitRange.getEnd(), EllipsisLoc); 4214 } 4215 4216 // Create a static_cast\<T&&>(expr). 4217 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4218 if (T.isNull()) T = E->getType(); 4219 QualType TargetType = SemaRef.BuildReferenceType( 4220 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4221 SourceLocation ExprLoc = E->getLocStart(); 4222 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4223 TargetType, ExprLoc); 4224 4225 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4226 SourceRange(ExprLoc, ExprLoc), 4227 E->getSourceRange()).get(); 4228 } 4229 4230 /// ImplicitInitializerKind - How an implicit base or member initializer should 4231 /// initialize its base or member. 4232 enum ImplicitInitializerKind { 4233 IIK_Default, 4234 IIK_Copy, 4235 IIK_Move, 4236 IIK_Inherit 4237 }; 4238 4239 static bool 4240 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4241 ImplicitInitializerKind ImplicitInitKind, 4242 CXXBaseSpecifier *BaseSpec, 4243 bool IsInheritedVirtualBase, 4244 CXXCtorInitializer *&CXXBaseInit) { 4245 InitializedEntity InitEntity 4246 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4247 IsInheritedVirtualBase); 4248 4249 ExprResult BaseInit; 4250 4251 switch (ImplicitInitKind) { 4252 case IIK_Inherit: 4253 case IIK_Default: { 4254 InitializationKind InitKind 4255 = InitializationKind::CreateDefault(Constructor->getLocation()); 4256 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4257 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4258 break; 4259 } 4260 4261 case IIK_Move: 4262 case IIK_Copy: { 4263 bool Moving = ImplicitInitKind == IIK_Move; 4264 ParmVarDecl *Param = Constructor->getParamDecl(0); 4265 QualType ParamType = Param->getType().getNonReferenceType(); 4266 4267 Expr *CopyCtorArg = 4268 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4269 SourceLocation(), Param, false, 4270 Constructor->getLocation(), ParamType, 4271 VK_LValue, nullptr); 4272 4273 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4274 4275 // Cast to the base class to avoid ambiguities. 4276 QualType ArgTy = 4277 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4278 ParamType.getQualifiers()); 4279 4280 if (Moving) { 4281 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4282 } 4283 4284 CXXCastPath BasePath; 4285 BasePath.push_back(BaseSpec); 4286 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4287 CK_UncheckedDerivedToBase, 4288 Moving ? VK_XValue : VK_LValue, 4289 &BasePath).get(); 4290 4291 InitializationKind InitKind 4292 = InitializationKind::CreateDirect(Constructor->getLocation(), 4293 SourceLocation(), SourceLocation()); 4294 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4295 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4296 break; 4297 } 4298 } 4299 4300 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4301 if (BaseInit.isInvalid()) 4302 return true; 4303 4304 CXXBaseInit = 4305 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4306 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4307 SourceLocation()), 4308 BaseSpec->isVirtual(), 4309 SourceLocation(), 4310 BaseInit.getAs<Expr>(), 4311 SourceLocation(), 4312 SourceLocation()); 4313 4314 return false; 4315 } 4316 4317 static bool RefersToRValueRef(Expr *MemRef) { 4318 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4319 return Referenced->getType()->isRValueReferenceType(); 4320 } 4321 4322 static bool 4323 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4324 ImplicitInitializerKind ImplicitInitKind, 4325 FieldDecl *Field, IndirectFieldDecl *Indirect, 4326 CXXCtorInitializer *&CXXMemberInit) { 4327 if (Field->isInvalidDecl()) 4328 return true; 4329 4330 SourceLocation Loc = Constructor->getLocation(); 4331 4332 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4333 bool Moving = ImplicitInitKind == IIK_Move; 4334 ParmVarDecl *Param = Constructor->getParamDecl(0); 4335 QualType ParamType = Param->getType().getNonReferenceType(); 4336 4337 // Suppress copying zero-width bitfields. 4338 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 4339 return false; 4340 4341 Expr *MemberExprBase = 4342 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4343 SourceLocation(), Param, false, 4344 Loc, ParamType, VK_LValue, nullptr); 4345 4346 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4347 4348 if (Moving) { 4349 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4350 } 4351 4352 // Build a reference to this field within the parameter. 4353 CXXScopeSpec SS; 4354 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4355 Sema::LookupMemberName); 4356 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4357 : cast<ValueDecl>(Field), AS_public); 4358 MemberLookup.resolveKind(); 4359 ExprResult CtorArg 4360 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4361 ParamType, Loc, 4362 /*IsArrow=*/false, 4363 SS, 4364 /*TemplateKWLoc=*/SourceLocation(), 4365 /*FirstQualifierInScope=*/nullptr, 4366 MemberLookup, 4367 /*TemplateArgs=*/nullptr, 4368 /*S*/nullptr); 4369 if (CtorArg.isInvalid()) 4370 return true; 4371 4372 // C++11 [class.copy]p15: 4373 // - if a member m has rvalue reference type T&&, it is direct-initialized 4374 // with static_cast<T&&>(x.m); 4375 if (RefersToRValueRef(CtorArg.get())) { 4376 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4377 } 4378 4379 InitializedEntity Entity = 4380 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4381 /*Implicit*/ true) 4382 : InitializedEntity::InitializeMember(Field, nullptr, 4383 /*Implicit*/ true); 4384 4385 // Direct-initialize to use the copy constructor. 4386 InitializationKind InitKind = 4387 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4388 4389 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4390 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4391 ExprResult MemberInit = 4392 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4393 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4394 if (MemberInit.isInvalid()) 4395 return true; 4396 4397 if (Indirect) 4398 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4399 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4400 else 4401 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4402 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4403 return false; 4404 } 4405 4406 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4407 "Unhandled implicit init kind!"); 4408 4409 QualType FieldBaseElementType = 4410 SemaRef.Context.getBaseElementType(Field->getType()); 4411 4412 if (FieldBaseElementType->isRecordType()) { 4413 InitializedEntity InitEntity = 4414 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4415 /*Implicit*/ true) 4416 : InitializedEntity::InitializeMember(Field, nullptr, 4417 /*Implicit*/ true); 4418 InitializationKind InitKind = 4419 InitializationKind::CreateDefault(Loc); 4420 4421 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4422 ExprResult MemberInit = 4423 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4424 4425 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4426 if (MemberInit.isInvalid()) 4427 return true; 4428 4429 if (Indirect) 4430 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4431 Indirect, Loc, 4432 Loc, 4433 MemberInit.get(), 4434 Loc); 4435 else 4436 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4437 Field, Loc, Loc, 4438 MemberInit.get(), 4439 Loc); 4440 return false; 4441 } 4442 4443 if (!Field->getParent()->isUnion()) { 4444 if (FieldBaseElementType->isReferenceType()) { 4445 SemaRef.Diag(Constructor->getLocation(), 4446 diag::err_uninitialized_member_in_ctor) 4447 << (int)Constructor->isImplicit() 4448 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4449 << 0 << Field->getDeclName(); 4450 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4451 return true; 4452 } 4453 4454 if (FieldBaseElementType.isConstQualified()) { 4455 SemaRef.Diag(Constructor->getLocation(), 4456 diag::err_uninitialized_member_in_ctor) 4457 << (int)Constructor->isImplicit() 4458 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4459 << 1 << Field->getDeclName(); 4460 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4461 return true; 4462 } 4463 } 4464 4465 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4466 // ARC and Weak: 4467 // Default-initialize Objective-C pointers to NULL. 4468 CXXMemberInit 4469 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4470 Loc, Loc, 4471 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4472 Loc); 4473 return false; 4474 } 4475 4476 // Nothing to initialize. 4477 CXXMemberInit = nullptr; 4478 return false; 4479 } 4480 4481 namespace { 4482 struct BaseAndFieldInfo { 4483 Sema &S; 4484 CXXConstructorDecl *Ctor; 4485 bool AnyErrorsInInits; 4486 ImplicitInitializerKind IIK; 4487 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4488 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4489 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4490 4491 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4492 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4493 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4494 if (Ctor->getInheritedConstructor()) 4495 IIK = IIK_Inherit; 4496 else if (Generated && Ctor->isCopyConstructor()) 4497 IIK = IIK_Copy; 4498 else if (Generated && Ctor->isMoveConstructor()) 4499 IIK = IIK_Move; 4500 else 4501 IIK = IIK_Default; 4502 } 4503 4504 bool isImplicitCopyOrMove() const { 4505 switch (IIK) { 4506 case IIK_Copy: 4507 case IIK_Move: 4508 return true; 4509 4510 case IIK_Default: 4511 case IIK_Inherit: 4512 return false; 4513 } 4514 4515 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4516 } 4517 4518 bool addFieldInitializer(CXXCtorInitializer *Init) { 4519 AllToInit.push_back(Init); 4520 4521 // Check whether this initializer makes the field "used". 4522 if (Init->getInit()->HasSideEffects(S.Context)) 4523 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4524 4525 return false; 4526 } 4527 4528 bool isInactiveUnionMember(FieldDecl *Field) { 4529 RecordDecl *Record = Field->getParent(); 4530 if (!Record->isUnion()) 4531 return false; 4532 4533 if (FieldDecl *Active = 4534 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4535 return Active != Field->getCanonicalDecl(); 4536 4537 // In an implicit copy or move constructor, ignore any in-class initializer. 4538 if (isImplicitCopyOrMove()) 4539 return true; 4540 4541 // If there's no explicit initialization, the field is active only if it 4542 // has an in-class initializer... 4543 if (Field->hasInClassInitializer()) 4544 return false; 4545 // ... or it's an anonymous struct or union whose class has an in-class 4546 // initializer. 4547 if (!Field->isAnonymousStructOrUnion()) 4548 return true; 4549 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4550 return !FieldRD->hasInClassInitializer(); 4551 } 4552 4553 /// \brief Determine whether the given field is, or is within, a union member 4554 /// that is inactive (because there was an initializer given for a different 4555 /// member of the union, or because the union was not initialized at all). 4556 bool isWithinInactiveUnionMember(FieldDecl *Field, 4557 IndirectFieldDecl *Indirect) { 4558 if (!Indirect) 4559 return isInactiveUnionMember(Field); 4560 4561 for (auto *C : Indirect->chain()) { 4562 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4563 if (Field && isInactiveUnionMember(Field)) 4564 return true; 4565 } 4566 return false; 4567 } 4568 }; 4569 } 4570 4571 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4572 /// array type. 4573 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4574 if (T->isIncompleteArrayType()) 4575 return true; 4576 4577 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4578 if (!ArrayT->getSize()) 4579 return true; 4580 4581 T = ArrayT->getElementType(); 4582 } 4583 4584 return false; 4585 } 4586 4587 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4588 FieldDecl *Field, 4589 IndirectFieldDecl *Indirect = nullptr) { 4590 if (Field->isInvalidDecl()) 4591 return false; 4592 4593 // Overwhelmingly common case: we have a direct initializer for this field. 4594 if (CXXCtorInitializer *Init = 4595 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4596 return Info.addFieldInitializer(Init); 4597 4598 // C++11 [class.base.init]p8: 4599 // if the entity is a non-static data member that has a 4600 // brace-or-equal-initializer and either 4601 // -- the constructor's class is a union and no other variant member of that 4602 // union is designated by a mem-initializer-id or 4603 // -- the constructor's class is not a union, and, if the entity is a member 4604 // of an anonymous union, no other member of that union is designated by 4605 // a mem-initializer-id, 4606 // the entity is initialized as specified in [dcl.init]. 4607 // 4608 // We also apply the same rules to handle anonymous structs within anonymous 4609 // unions. 4610 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4611 return false; 4612 4613 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4614 ExprResult DIE = 4615 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4616 if (DIE.isInvalid()) 4617 return true; 4618 CXXCtorInitializer *Init; 4619 if (Indirect) 4620 Init = new (SemaRef.Context) 4621 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4622 SourceLocation(), DIE.get(), SourceLocation()); 4623 else 4624 Init = new (SemaRef.Context) 4625 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4626 SourceLocation(), DIE.get(), SourceLocation()); 4627 return Info.addFieldInitializer(Init); 4628 } 4629 4630 // Don't initialize incomplete or zero-length arrays. 4631 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4632 return false; 4633 4634 // Don't try to build an implicit initializer if there were semantic 4635 // errors in any of the initializers (and therefore we might be 4636 // missing some that the user actually wrote). 4637 if (Info.AnyErrorsInInits) 4638 return false; 4639 4640 CXXCtorInitializer *Init = nullptr; 4641 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4642 Indirect, Init)) 4643 return true; 4644 4645 if (!Init) 4646 return false; 4647 4648 return Info.addFieldInitializer(Init); 4649 } 4650 4651 bool 4652 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4653 CXXCtorInitializer *Initializer) { 4654 assert(Initializer->isDelegatingInitializer()); 4655 Constructor->setNumCtorInitializers(1); 4656 CXXCtorInitializer **initializer = 4657 new (Context) CXXCtorInitializer*[1]; 4658 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4659 Constructor->setCtorInitializers(initializer); 4660 4661 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4662 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4663 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4664 } 4665 4666 DelegatingCtorDecls.push_back(Constructor); 4667 4668 DiagnoseUninitializedFields(*this, Constructor); 4669 4670 return false; 4671 } 4672 4673 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4674 ArrayRef<CXXCtorInitializer *> Initializers) { 4675 if (Constructor->isDependentContext()) { 4676 // Just store the initializers as written, they will be checked during 4677 // instantiation. 4678 if (!Initializers.empty()) { 4679 Constructor->setNumCtorInitializers(Initializers.size()); 4680 CXXCtorInitializer **baseOrMemberInitializers = 4681 new (Context) CXXCtorInitializer*[Initializers.size()]; 4682 memcpy(baseOrMemberInitializers, Initializers.data(), 4683 Initializers.size() * sizeof(CXXCtorInitializer*)); 4684 Constructor->setCtorInitializers(baseOrMemberInitializers); 4685 } 4686 4687 // Let template instantiation know whether we had errors. 4688 if (AnyErrors) 4689 Constructor->setInvalidDecl(); 4690 4691 return false; 4692 } 4693 4694 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4695 4696 // We need to build the initializer AST according to order of construction 4697 // and not what user specified in the Initializers list. 4698 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4699 if (!ClassDecl) 4700 return true; 4701 4702 bool HadError = false; 4703 4704 for (unsigned i = 0; i < Initializers.size(); i++) { 4705 CXXCtorInitializer *Member = Initializers[i]; 4706 4707 if (Member->isBaseInitializer()) 4708 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4709 else { 4710 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4711 4712 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4713 for (auto *C : F->chain()) { 4714 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4715 if (FD && FD->getParent()->isUnion()) 4716 Info.ActiveUnionMember.insert(std::make_pair( 4717 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4718 } 4719 } else if (FieldDecl *FD = Member->getMember()) { 4720 if (FD->getParent()->isUnion()) 4721 Info.ActiveUnionMember.insert(std::make_pair( 4722 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4723 } 4724 } 4725 } 4726 4727 // Keep track of the direct virtual bases. 4728 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4729 for (auto &I : ClassDecl->bases()) { 4730 if (I.isVirtual()) 4731 DirectVBases.insert(&I); 4732 } 4733 4734 // Push virtual bases before others. 4735 for (auto &VBase : ClassDecl->vbases()) { 4736 if (CXXCtorInitializer *Value 4737 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4738 // [class.base.init]p7, per DR257: 4739 // A mem-initializer where the mem-initializer-id names a virtual base 4740 // class is ignored during execution of a constructor of any class that 4741 // is not the most derived class. 4742 if (ClassDecl->isAbstract()) { 4743 // FIXME: Provide a fixit to remove the base specifier. This requires 4744 // tracking the location of the associated comma for a base specifier. 4745 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4746 << VBase.getType() << ClassDecl; 4747 DiagnoseAbstractType(ClassDecl); 4748 } 4749 4750 Info.AllToInit.push_back(Value); 4751 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4752 // [class.base.init]p8, per DR257: 4753 // If a given [...] base class is not named by a mem-initializer-id 4754 // [...] and the entity is not a virtual base class of an abstract 4755 // class, then [...] the entity is default-initialized. 4756 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4757 CXXCtorInitializer *CXXBaseInit; 4758 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4759 &VBase, IsInheritedVirtualBase, 4760 CXXBaseInit)) { 4761 HadError = true; 4762 continue; 4763 } 4764 4765 Info.AllToInit.push_back(CXXBaseInit); 4766 } 4767 } 4768 4769 // Non-virtual bases. 4770 for (auto &Base : ClassDecl->bases()) { 4771 // Virtuals are in the virtual base list and already constructed. 4772 if (Base.isVirtual()) 4773 continue; 4774 4775 if (CXXCtorInitializer *Value 4776 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4777 Info.AllToInit.push_back(Value); 4778 } else if (!AnyErrors) { 4779 CXXCtorInitializer *CXXBaseInit; 4780 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4781 &Base, /*IsInheritedVirtualBase=*/false, 4782 CXXBaseInit)) { 4783 HadError = true; 4784 continue; 4785 } 4786 4787 Info.AllToInit.push_back(CXXBaseInit); 4788 } 4789 } 4790 4791 // Fields. 4792 for (auto *Mem : ClassDecl->decls()) { 4793 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4794 // C++ [class.bit]p2: 4795 // A declaration for a bit-field that omits the identifier declares an 4796 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4797 // initialized. 4798 if (F->isUnnamedBitfield()) 4799 continue; 4800 4801 // If we're not generating the implicit copy/move constructor, then we'll 4802 // handle anonymous struct/union fields based on their individual 4803 // indirect fields. 4804 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4805 continue; 4806 4807 if (CollectFieldInitializer(*this, Info, F)) 4808 HadError = true; 4809 continue; 4810 } 4811 4812 // Beyond this point, we only consider default initialization. 4813 if (Info.isImplicitCopyOrMove()) 4814 continue; 4815 4816 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4817 if (F->getType()->isIncompleteArrayType()) { 4818 assert(ClassDecl->hasFlexibleArrayMember() && 4819 "Incomplete array type is not valid"); 4820 continue; 4821 } 4822 4823 // Initialize each field of an anonymous struct individually. 4824 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4825 HadError = true; 4826 4827 continue; 4828 } 4829 } 4830 4831 unsigned NumInitializers = Info.AllToInit.size(); 4832 if (NumInitializers > 0) { 4833 Constructor->setNumCtorInitializers(NumInitializers); 4834 CXXCtorInitializer **baseOrMemberInitializers = 4835 new (Context) CXXCtorInitializer*[NumInitializers]; 4836 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4837 NumInitializers * sizeof(CXXCtorInitializer*)); 4838 Constructor->setCtorInitializers(baseOrMemberInitializers); 4839 4840 // Constructors implicitly reference the base and member 4841 // destructors. 4842 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4843 Constructor->getParent()); 4844 } 4845 4846 return HadError; 4847 } 4848 4849 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4850 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4851 const RecordDecl *RD = RT->getDecl(); 4852 if (RD->isAnonymousStructOrUnion()) { 4853 for (auto *Field : RD->fields()) 4854 PopulateKeysForFields(Field, IdealInits); 4855 return; 4856 } 4857 } 4858 IdealInits.push_back(Field->getCanonicalDecl()); 4859 } 4860 4861 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4862 return Context.getCanonicalType(BaseType).getTypePtr(); 4863 } 4864 4865 static const void *GetKeyForMember(ASTContext &Context, 4866 CXXCtorInitializer *Member) { 4867 if (!Member->isAnyMemberInitializer()) 4868 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4869 4870 return Member->getAnyMember()->getCanonicalDecl(); 4871 } 4872 4873 static void DiagnoseBaseOrMemInitializerOrder( 4874 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4875 ArrayRef<CXXCtorInitializer *> Inits) { 4876 if (Constructor->getDeclContext()->isDependentContext()) 4877 return; 4878 4879 // Don't check initializers order unless the warning is enabled at the 4880 // location of at least one initializer. 4881 bool ShouldCheckOrder = false; 4882 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4883 CXXCtorInitializer *Init = Inits[InitIndex]; 4884 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4885 Init->getSourceLocation())) { 4886 ShouldCheckOrder = true; 4887 break; 4888 } 4889 } 4890 if (!ShouldCheckOrder) 4891 return; 4892 4893 // Build the list of bases and members in the order that they'll 4894 // actually be initialized. The explicit initializers should be in 4895 // this same order but may be missing things. 4896 SmallVector<const void*, 32> IdealInitKeys; 4897 4898 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4899 4900 // 1. Virtual bases. 4901 for (const auto &VBase : ClassDecl->vbases()) 4902 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4903 4904 // 2. Non-virtual bases. 4905 for (const auto &Base : ClassDecl->bases()) { 4906 if (Base.isVirtual()) 4907 continue; 4908 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4909 } 4910 4911 // 3. Direct fields. 4912 for (auto *Field : ClassDecl->fields()) { 4913 if (Field->isUnnamedBitfield()) 4914 continue; 4915 4916 PopulateKeysForFields(Field, IdealInitKeys); 4917 } 4918 4919 unsigned NumIdealInits = IdealInitKeys.size(); 4920 unsigned IdealIndex = 0; 4921 4922 CXXCtorInitializer *PrevInit = nullptr; 4923 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4924 CXXCtorInitializer *Init = Inits[InitIndex]; 4925 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4926 4927 // Scan forward to try to find this initializer in the idealized 4928 // initializers list. 4929 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4930 if (InitKey == IdealInitKeys[IdealIndex]) 4931 break; 4932 4933 // If we didn't find this initializer, it must be because we 4934 // scanned past it on a previous iteration. That can only 4935 // happen if we're out of order; emit a warning. 4936 if (IdealIndex == NumIdealInits && PrevInit) { 4937 Sema::SemaDiagnosticBuilder D = 4938 SemaRef.Diag(PrevInit->getSourceLocation(), 4939 diag::warn_initializer_out_of_order); 4940 4941 if (PrevInit->isAnyMemberInitializer()) 4942 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4943 else 4944 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4945 4946 if (Init->isAnyMemberInitializer()) 4947 D << 0 << Init->getAnyMember()->getDeclName(); 4948 else 4949 D << 1 << Init->getTypeSourceInfo()->getType(); 4950 4951 // Move back to the initializer's location in the ideal list. 4952 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4953 if (InitKey == IdealInitKeys[IdealIndex]) 4954 break; 4955 4956 assert(IdealIndex < NumIdealInits && 4957 "initializer not found in initializer list"); 4958 } 4959 4960 PrevInit = Init; 4961 } 4962 } 4963 4964 namespace { 4965 bool CheckRedundantInit(Sema &S, 4966 CXXCtorInitializer *Init, 4967 CXXCtorInitializer *&PrevInit) { 4968 if (!PrevInit) { 4969 PrevInit = Init; 4970 return false; 4971 } 4972 4973 if (FieldDecl *Field = Init->getAnyMember()) 4974 S.Diag(Init->getSourceLocation(), 4975 diag::err_multiple_mem_initialization) 4976 << Field->getDeclName() 4977 << Init->getSourceRange(); 4978 else { 4979 const Type *BaseClass = Init->getBaseClass(); 4980 assert(BaseClass && "neither field nor base"); 4981 S.Diag(Init->getSourceLocation(), 4982 diag::err_multiple_base_initialization) 4983 << QualType(BaseClass, 0) 4984 << Init->getSourceRange(); 4985 } 4986 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4987 << 0 << PrevInit->getSourceRange(); 4988 4989 return true; 4990 } 4991 4992 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4993 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4994 4995 bool CheckRedundantUnionInit(Sema &S, 4996 CXXCtorInitializer *Init, 4997 RedundantUnionMap &Unions) { 4998 FieldDecl *Field = Init->getAnyMember(); 4999 RecordDecl *Parent = Field->getParent(); 5000 NamedDecl *Child = Field; 5001 5002 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5003 if (Parent->isUnion()) { 5004 UnionEntry &En = Unions[Parent]; 5005 if (En.first && En.first != Child) { 5006 S.Diag(Init->getSourceLocation(), 5007 diag::err_multiple_mem_union_initialization) 5008 << Field->getDeclName() 5009 << Init->getSourceRange(); 5010 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5011 << 0 << En.second->getSourceRange(); 5012 return true; 5013 } 5014 if (!En.first) { 5015 En.first = Child; 5016 En.second = Init; 5017 } 5018 if (!Parent->isAnonymousStructOrUnion()) 5019 return false; 5020 } 5021 5022 Child = Parent; 5023 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5024 } 5025 5026 return false; 5027 } 5028 } 5029 5030 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5031 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5032 SourceLocation ColonLoc, 5033 ArrayRef<CXXCtorInitializer*> MemInits, 5034 bool AnyErrors) { 5035 if (!ConstructorDecl) 5036 return; 5037 5038 AdjustDeclIfTemplate(ConstructorDecl); 5039 5040 CXXConstructorDecl *Constructor 5041 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5042 5043 if (!Constructor) { 5044 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5045 return; 5046 } 5047 5048 // Mapping for the duplicate initializers check. 5049 // For member initializers, this is keyed with a FieldDecl*. 5050 // For base initializers, this is keyed with a Type*. 5051 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5052 5053 // Mapping for the inconsistent anonymous-union initializers check. 5054 RedundantUnionMap MemberUnions; 5055 5056 bool HadError = false; 5057 for (unsigned i = 0; i < MemInits.size(); i++) { 5058 CXXCtorInitializer *Init = MemInits[i]; 5059 5060 // Set the source order index. 5061 Init->setSourceOrder(i); 5062 5063 if (Init->isAnyMemberInitializer()) { 5064 const void *Key = GetKeyForMember(Context, Init); 5065 if (CheckRedundantInit(*this, Init, Members[Key]) || 5066 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5067 HadError = true; 5068 } else if (Init->isBaseInitializer()) { 5069 const void *Key = GetKeyForMember(Context, Init); 5070 if (CheckRedundantInit(*this, Init, Members[Key])) 5071 HadError = true; 5072 } else { 5073 assert(Init->isDelegatingInitializer()); 5074 // This must be the only initializer 5075 if (MemInits.size() != 1) { 5076 Diag(Init->getSourceLocation(), 5077 diag::err_delegating_initializer_alone) 5078 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5079 // We will treat this as being the only initializer. 5080 } 5081 SetDelegatingInitializer(Constructor, MemInits[i]); 5082 // Return immediately as the initializer is set. 5083 return; 5084 } 5085 } 5086 5087 if (HadError) 5088 return; 5089 5090 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5091 5092 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5093 5094 DiagnoseUninitializedFields(*this, Constructor); 5095 } 5096 5097 void 5098 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5099 CXXRecordDecl *ClassDecl) { 5100 // Ignore dependent contexts. Also ignore unions, since their members never 5101 // have destructors implicitly called. 5102 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5103 return; 5104 5105 // FIXME: all the access-control diagnostics are positioned on the 5106 // field/base declaration. That's probably good; that said, the 5107 // user might reasonably want to know why the destructor is being 5108 // emitted, and we currently don't say. 5109 5110 // Non-static data members. 5111 for (auto *Field : ClassDecl->fields()) { 5112 if (Field->isInvalidDecl()) 5113 continue; 5114 5115 // Don't destroy incomplete or zero-length arrays. 5116 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5117 continue; 5118 5119 QualType FieldType = Context.getBaseElementType(Field->getType()); 5120 5121 const RecordType* RT = FieldType->getAs<RecordType>(); 5122 if (!RT) 5123 continue; 5124 5125 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5126 if (FieldClassDecl->isInvalidDecl()) 5127 continue; 5128 if (FieldClassDecl->hasIrrelevantDestructor()) 5129 continue; 5130 // The destructor for an implicit anonymous union member is never invoked. 5131 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5132 continue; 5133 5134 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5135 assert(Dtor && "No dtor found for FieldClassDecl!"); 5136 CheckDestructorAccess(Field->getLocation(), Dtor, 5137 PDiag(diag::err_access_dtor_field) 5138 << Field->getDeclName() 5139 << FieldType); 5140 5141 MarkFunctionReferenced(Location, Dtor); 5142 DiagnoseUseOfDecl(Dtor, Location); 5143 } 5144 5145 // We only potentially invoke the destructors of potentially constructed 5146 // subobjects. 5147 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5148 5149 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5150 5151 // Bases. 5152 for (const auto &Base : ClassDecl->bases()) { 5153 // Bases are always records in a well-formed non-dependent class. 5154 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5155 5156 // Remember direct virtual bases. 5157 if (Base.isVirtual()) { 5158 if (!VisitVirtualBases) 5159 continue; 5160 DirectVirtualBases.insert(RT); 5161 } 5162 5163 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5164 // If our base class is invalid, we probably can't get its dtor anyway. 5165 if (BaseClassDecl->isInvalidDecl()) 5166 continue; 5167 if (BaseClassDecl->hasIrrelevantDestructor()) 5168 continue; 5169 5170 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5171 assert(Dtor && "No dtor found for BaseClassDecl!"); 5172 5173 // FIXME: caret should be on the start of the class name 5174 CheckDestructorAccess(Base.getLocStart(), Dtor, 5175 PDiag(diag::err_access_dtor_base) 5176 << Base.getType() 5177 << Base.getSourceRange(), 5178 Context.getTypeDeclType(ClassDecl)); 5179 5180 MarkFunctionReferenced(Location, Dtor); 5181 DiagnoseUseOfDecl(Dtor, Location); 5182 } 5183 5184 if (!VisitVirtualBases) 5185 return; 5186 5187 // Virtual bases. 5188 for (const auto &VBase : ClassDecl->vbases()) { 5189 // Bases are always records in a well-formed non-dependent class. 5190 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5191 5192 // Ignore direct virtual bases. 5193 if (DirectVirtualBases.count(RT)) 5194 continue; 5195 5196 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5197 // If our base class is invalid, we probably can't get its dtor anyway. 5198 if (BaseClassDecl->isInvalidDecl()) 5199 continue; 5200 if (BaseClassDecl->hasIrrelevantDestructor()) 5201 continue; 5202 5203 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5204 assert(Dtor && "No dtor found for BaseClassDecl!"); 5205 if (CheckDestructorAccess( 5206 ClassDecl->getLocation(), Dtor, 5207 PDiag(diag::err_access_dtor_vbase) 5208 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5209 Context.getTypeDeclType(ClassDecl)) == 5210 AR_accessible) { 5211 CheckDerivedToBaseConversion( 5212 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5213 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5214 SourceRange(), DeclarationName(), nullptr); 5215 } 5216 5217 MarkFunctionReferenced(Location, Dtor); 5218 DiagnoseUseOfDecl(Dtor, Location); 5219 } 5220 } 5221 5222 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5223 if (!CDtorDecl) 5224 return; 5225 5226 if (CXXConstructorDecl *Constructor 5227 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5228 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5229 DiagnoseUninitializedFields(*this, Constructor); 5230 } 5231 } 5232 5233 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5234 if (!getLangOpts().CPlusPlus) 5235 return false; 5236 5237 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5238 if (!RD) 5239 return false; 5240 5241 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5242 // class template specialization here, but doing so breaks a lot of code. 5243 5244 // We can't answer whether something is abstract until it has a 5245 // definition. If it's currently being defined, we'll walk back 5246 // over all the declarations when we have a full definition. 5247 const CXXRecordDecl *Def = RD->getDefinition(); 5248 if (!Def || Def->isBeingDefined()) 5249 return false; 5250 5251 return RD->isAbstract(); 5252 } 5253 5254 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5255 TypeDiagnoser &Diagnoser) { 5256 if (!isAbstractType(Loc, T)) 5257 return false; 5258 5259 T = Context.getBaseElementType(T); 5260 Diagnoser.diagnose(*this, Loc, T); 5261 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5262 return true; 5263 } 5264 5265 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5266 // Check if we've already emitted the list of pure virtual functions 5267 // for this class. 5268 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5269 return; 5270 5271 // If the diagnostic is suppressed, don't emit the notes. We're only 5272 // going to emit them once, so try to attach them to a diagnostic we're 5273 // actually going to show. 5274 if (Diags.isLastDiagnosticIgnored()) 5275 return; 5276 5277 CXXFinalOverriderMap FinalOverriders; 5278 RD->getFinalOverriders(FinalOverriders); 5279 5280 // Keep a set of seen pure methods so we won't diagnose the same method 5281 // more than once. 5282 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5283 5284 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5285 MEnd = FinalOverriders.end(); 5286 M != MEnd; 5287 ++M) { 5288 for (OverridingMethods::iterator SO = M->second.begin(), 5289 SOEnd = M->second.end(); 5290 SO != SOEnd; ++SO) { 5291 // C++ [class.abstract]p4: 5292 // A class is abstract if it contains or inherits at least one 5293 // pure virtual function for which the final overrider is pure 5294 // virtual. 5295 5296 // 5297 if (SO->second.size() != 1) 5298 continue; 5299 5300 if (!SO->second.front().Method->isPure()) 5301 continue; 5302 5303 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5304 continue; 5305 5306 Diag(SO->second.front().Method->getLocation(), 5307 diag::note_pure_virtual_function) 5308 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5309 } 5310 } 5311 5312 if (!PureVirtualClassDiagSet) 5313 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5314 PureVirtualClassDiagSet->insert(RD); 5315 } 5316 5317 namespace { 5318 struct AbstractUsageInfo { 5319 Sema &S; 5320 CXXRecordDecl *Record; 5321 CanQualType AbstractType; 5322 bool Invalid; 5323 5324 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5325 : S(S), Record(Record), 5326 AbstractType(S.Context.getCanonicalType( 5327 S.Context.getTypeDeclType(Record))), 5328 Invalid(false) {} 5329 5330 void DiagnoseAbstractType() { 5331 if (Invalid) return; 5332 S.DiagnoseAbstractType(Record); 5333 Invalid = true; 5334 } 5335 5336 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5337 }; 5338 5339 struct CheckAbstractUsage { 5340 AbstractUsageInfo &Info; 5341 const NamedDecl *Ctx; 5342 5343 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5344 : Info(Info), Ctx(Ctx) {} 5345 5346 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5347 switch (TL.getTypeLocClass()) { 5348 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5349 #define TYPELOC(CLASS, PARENT) \ 5350 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5351 #include "clang/AST/TypeLocNodes.def" 5352 } 5353 } 5354 5355 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5356 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5357 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5358 if (!TL.getParam(I)) 5359 continue; 5360 5361 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5362 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5363 } 5364 } 5365 5366 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5367 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5368 } 5369 5370 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5371 // Visit the type parameters from a permissive context. 5372 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5373 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5374 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5375 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5376 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5377 // TODO: other template argument types? 5378 } 5379 } 5380 5381 // Visit pointee types from a permissive context. 5382 #define CheckPolymorphic(Type) \ 5383 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5384 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5385 } 5386 CheckPolymorphic(PointerTypeLoc) 5387 CheckPolymorphic(ReferenceTypeLoc) 5388 CheckPolymorphic(MemberPointerTypeLoc) 5389 CheckPolymorphic(BlockPointerTypeLoc) 5390 CheckPolymorphic(AtomicTypeLoc) 5391 5392 /// Handle all the types we haven't given a more specific 5393 /// implementation for above. 5394 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5395 // Every other kind of type that we haven't called out already 5396 // that has an inner type is either (1) sugar or (2) contains that 5397 // inner type in some way as a subobject. 5398 if (TypeLoc Next = TL.getNextTypeLoc()) 5399 return Visit(Next, Sel); 5400 5401 // If there's no inner type and we're in a permissive context, 5402 // don't diagnose. 5403 if (Sel == Sema::AbstractNone) return; 5404 5405 // Check whether the type matches the abstract type. 5406 QualType T = TL.getType(); 5407 if (T->isArrayType()) { 5408 Sel = Sema::AbstractArrayType; 5409 T = Info.S.Context.getBaseElementType(T); 5410 } 5411 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5412 if (CT != Info.AbstractType) return; 5413 5414 // It matched; do some magic. 5415 if (Sel == Sema::AbstractArrayType) { 5416 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5417 << T << TL.getSourceRange(); 5418 } else { 5419 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5420 << Sel << T << TL.getSourceRange(); 5421 } 5422 Info.DiagnoseAbstractType(); 5423 } 5424 }; 5425 5426 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5427 Sema::AbstractDiagSelID Sel) { 5428 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5429 } 5430 5431 } 5432 5433 /// Check for invalid uses of an abstract type in a method declaration. 5434 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5435 CXXMethodDecl *MD) { 5436 // No need to do the check on definitions, which require that 5437 // the return/param types be complete. 5438 if (MD->doesThisDeclarationHaveABody()) 5439 return; 5440 5441 // For safety's sake, just ignore it if we don't have type source 5442 // information. This should never happen for non-implicit methods, 5443 // but... 5444 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5445 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5446 } 5447 5448 /// Check for invalid uses of an abstract type within a class definition. 5449 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5450 CXXRecordDecl *RD) { 5451 for (auto *D : RD->decls()) { 5452 if (D->isImplicit()) continue; 5453 5454 // Methods and method templates. 5455 if (isa<CXXMethodDecl>(D)) { 5456 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5457 } else if (isa<FunctionTemplateDecl>(D)) { 5458 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5459 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5460 5461 // Fields and static variables. 5462 } else if (isa<FieldDecl>(D)) { 5463 FieldDecl *FD = cast<FieldDecl>(D); 5464 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5465 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5466 } else if (isa<VarDecl>(D)) { 5467 VarDecl *VD = cast<VarDecl>(D); 5468 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5469 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5470 5471 // Nested classes and class templates. 5472 } else if (isa<CXXRecordDecl>(D)) { 5473 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5474 } else if (isa<ClassTemplateDecl>(D)) { 5475 CheckAbstractClassUsage(Info, 5476 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5477 } 5478 } 5479 } 5480 5481 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5482 Attr *ClassAttr = getDLLAttr(Class); 5483 if (!ClassAttr) 5484 return; 5485 5486 assert(ClassAttr->getKind() == attr::DLLExport); 5487 5488 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5489 5490 if (TSK == TSK_ExplicitInstantiationDeclaration) 5491 // Don't go any further if this is just an explicit instantiation 5492 // declaration. 5493 return; 5494 5495 for (Decl *Member : Class->decls()) { 5496 // Defined static variables that are members of an exported base 5497 // class must be marked export too. 5498 auto *VD = dyn_cast<VarDecl>(Member); 5499 if (VD && Member->getAttr<DLLExportAttr>() && 5500 VD->getStorageClass() == SC_Static && 5501 TSK == TSK_ImplicitInstantiation) 5502 S.MarkVariableReferenced(VD->getLocation(), VD); 5503 5504 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5505 if (!MD) 5506 continue; 5507 5508 if (Member->getAttr<DLLExportAttr>()) { 5509 if (MD->isUserProvided()) { 5510 // Instantiate non-default class member functions ... 5511 5512 // .. except for certain kinds of template specializations. 5513 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5514 continue; 5515 5516 S.MarkFunctionReferenced(Class->getLocation(), MD); 5517 5518 // The function will be passed to the consumer when its definition is 5519 // encountered. 5520 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5521 MD->isCopyAssignmentOperator() || 5522 MD->isMoveAssignmentOperator()) { 5523 // Synthesize and instantiate non-trivial implicit methods, explicitly 5524 // defaulted methods, and the copy and move assignment operators. The 5525 // latter are exported even if they are trivial, because the address of 5526 // an operator can be taken and should compare equal across libraries. 5527 DiagnosticErrorTrap Trap(S.Diags); 5528 S.MarkFunctionReferenced(Class->getLocation(), MD); 5529 if (Trap.hasErrorOccurred()) { 5530 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5531 << Class->getName() << !S.getLangOpts().CPlusPlus11; 5532 break; 5533 } 5534 5535 // There is no later point when we will see the definition of this 5536 // function, so pass it to the consumer now. 5537 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5538 } 5539 } 5540 } 5541 } 5542 5543 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5544 CXXRecordDecl *Class) { 5545 // Only the MS ABI has default constructor closures, so we don't need to do 5546 // this semantic checking anywhere else. 5547 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5548 return; 5549 5550 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5551 for (Decl *Member : Class->decls()) { 5552 // Look for exported default constructors. 5553 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5554 if (!CD || !CD->isDefaultConstructor()) 5555 continue; 5556 auto *Attr = CD->getAttr<DLLExportAttr>(); 5557 if (!Attr) 5558 continue; 5559 5560 // If the class is non-dependent, mark the default arguments as ODR-used so 5561 // that we can properly codegen the constructor closure. 5562 if (!Class->isDependentContext()) { 5563 for (ParmVarDecl *PD : CD->parameters()) { 5564 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5565 S.DiscardCleanupsInEvaluationContext(); 5566 } 5567 } 5568 5569 if (LastExportedDefaultCtor) { 5570 S.Diag(LastExportedDefaultCtor->getLocation(), 5571 diag::err_attribute_dll_ambiguous_default_ctor) 5572 << Class; 5573 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5574 << CD->getDeclName(); 5575 return; 5576 } 5577 LastExportedDefaultCtor = CD; 5578 } 5579 } 5580 5581 /// \brief Check class-level dllimport/dllexport attribute. 5582 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5583 Attr *ClassAttr = getDLLAttr(Class); 5584 5585 // MSVC inherits DLL attributes to partial class template specializations. 5586 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5587 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5588 if (Attr *TemplateAttr = 5589 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5590 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5591 A->setInherited(true); 5592 ClassAttr = A; 5593 } 5594 } 5595 } 5596 5597 if (!ClassAttr) 5598 return; 5599 5600 if (!Class->isExternallyVisible()) { 5601 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5602 << Class << ClassAttr; 5603 return; 5604 } 5605 5606 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5607 !ClassAttr->isInherited()) { 5608 // Diagnose dll attributes on members of class with dll attribute. 5609 for (Decl *Member : Class->decls()) { 5610 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5611 continue; 5612 InheritableAttr *MemberAttr = getDLLAttr(Member); 5613 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5614 continue; 5615 5616 Diag(MemberAttr->getLocation(), 5617 diag::err_attribute_dll_member_of_dll_class) 5618 << MemberAttr << ClassAttr; 5619 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5620 Member->setInvalidDecl(); 5621 } 5622 } 5623 5624 if (Class->getDescribedClassTemplate()) 5625 // Don't inherit dll attribute until the template is instantiated. 5626 return; 5627 5628 // The class is either imported or exported. 5629 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5630 5631 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5632 5633 // Ignore explicit dllexport on explicit class template instantiation declarations. 5634 if (ClassExported && !ClassAttr->isInherited() && 5635 TSK == TSK_ExplicitInstantiationDeclaration) { 5636 Class->dropAttr<DLLExportAttr>(); 5637 return; 5638 } 5639 5640 // Force declaration of implicit members so they can inherit the attribute. 5641 ForceDeclarationOfImplicitMembers(Class); 5642 5643 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5644 // seem to be true in practice? 5645 5646 for (Decl *Member : Class->decls()) { 5647 VarDecl *VD = dyn_cast<VarDecl>(Member); 5648 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5649 5650 // Only methods and static fields inherit the attributes. 5651 if (!VD && !MD) 5652 continue; 5653 5654 if (MD) { 5655 // Don't process deleted methods. 5656 if (MD->isDeleted()) 5657 continue; 5658 5659 if (MD->isInlined()) { 5660 // MinGW does not import or export inline methods. 5661 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5662 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5663 continue; 5664 5665 // MSVC versions before 2015 don't export the move assignment operators 5666 // and move constructor, so don't attempt to import/export them if 5667 // we have a definition. 5668 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5669 if ((MD->isMoveAssignmentOperator() || 5670 (Ctor && Ctor->isMoveConstructor())) && 5671 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5672 continue; 5673 5674 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5675 // operator is exported anyway. 5676 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5677 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5678 continue; 5679 } 5680 } 5681 5682 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5683 continue; 5684 5685 if (!getDLLAttr(Member)) { 5686 auto *NewAttr = 5687 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5688 NewAttr->setInherited(true); 5689 Member->addAttr(NewAttr); 5690 5691 if (MD) { 5692 // Propagate DLLAttr to friend re-declarations of MD that have already 5693 // been constructed. 5694 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5695 FD = FD->getPreviousDecl()) { 5696 if (FD->getFriendObjectKind() == Decl::FOK_None) 5697 continue; 5698 assert(!getDLLAttr(FD) && 5699 "friend re-decl should not already have a DLLAttr"); 5700 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5701 NewAttr->setInherited(true); 5702 FD->addAttr(NewAttr); 5703 } 5704 } 5705 } 5706 } 5707 5708 if (ClassExported) 5709 DelayedDllExportClasses.push_back(Class); 5710 } 5711 5712 /// \brief Perform propagation of DLL attributes from a derived class to a 5713 /// templated base class for MS compatibility. 5714 void Sema::propagateDLLAttrToBaseClassTemplate( 5715 CXXRecordDecl *Class, Attr *ClassAttr, 5716 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5717 if (getDLLAttr( 5718 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5719 // If the base class template has a DLL attribute, don't try to change it. 5720 return; 5721 } 5722 5723 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5724 if (!getDLLAttr(BaseTemplateSpec) && 5725 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5726 TSK == TSK_ImplicitInstantiation)) { 5727 // The template hasn't been instantiated yet (or it has, but only as an 5728 // explicit instantiation declaration or implicit instantiation, which means 5729 // we haven't codegenned any members yet), so propagate the attribute. 5730 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5731 NewAttr->setInherited(true); 5732 BaseTemplateSpec->addAttr(NewAttr); 5733 5734 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5735 // needs to be run again to work see the new attribute. Otherwise this will 5736 // get run whenever the template is instantiated. 5737 if (TSK != TSK_Undeclared) 5738 checkClassLevelDLLAttribute(BaseTemplateSpec); 5739 5740 return; 5741 } 5742 5743 if (getDLLAttr(BaseTemplateSpec)) { 5744 // The template has already been specialized or instantiated with an 5745 // attribute, explicitly or through propagation. We should not try to change 5746 // it. 5747 return; 5748 } 5749 5750 // The template was previously instantiated or explicitly specialized without 5751 // a dll attribute, It's too late for us to add an attribute, so warn that 5752 // this is unsupported. 5753 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5754 << BaseTemplateSpec->isExplicitSpecialization(); 5755 Diag(ClassAttr->getLocation(), diag::note_attribute); 5756 if (BaseTemplateSpec->isExplicitSpecialization()) { 5757 Diag(BaseTemplateSpec->getLocation(), 5758 diag::note_template_class_explicit_specialization_was_here) 5759 << BaseTemplateSpec; 5760 } else { 5761 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5762 diag::note_template_class_instantiation_was_here) 5763 << BaseTemplateSpec; 5764 } 5765 } 5766 5767 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5768 SourceLocation DefaultLoc) { 5769 switch (S.getSpecialMember(MD)) { 5770 case Sema::CXXDefaultConstructor: 5771 S.DefineImplicitDefaultConstructor(DefaultLoc, 5772 cast<CXXConstructorDecl>(MD)); 5773 break; 5774 case Sema::CXXCopyConstructor: 5775 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5776 break; 5777 case Sema::CXXCopyAssignment: 5778 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5779 break; 5780 case Sema::CXXDestructor: 5781 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5782 break; 5783 case Sema::CXXMoveConstructor: 5784 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5785 break; 5786 case Sema::CXXMoveAssignment: 5787 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5788 break; 5789 case Sema::CXXInvalid: 5790 llvm_unreachable("Invalid special member."); 5791 } 5792 } 5793 5794 /// Determine whether a type is permitted to be passed or returned in 5795 /// registers, per C++ [class.temporary]p3. 5796 static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) { 5797 if (D->isDependentType() || D->isInvalidDecl()) 5798 return false; 5799 5800 // Per C++ [class.temporary]p3, the relevant condition is: 5801 // each copy constructor, move constructor, and destructor of X is 5802 // either trivial or deleted, and X has at least one non-deleted copy 5803 // or move constructor 5804 bool HasNonDeletedCopyOrMove = false; 5805 5806 if (D->needsImplicitCopyConstructor() && 5807 !D->defaultedCopyConstructorIsDeleted()) { 5808 if (!D->hasTrivialCopyConstructorForCall()) 5809 return false; 5810 HasNonDeletedCopyOrMove = true; 5811 } 5812 5813 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5814 !D->defaultedMoveConstructorIsDeleted()) { 5815 if (!D->hasTrivialMoveConstructorForCall()) 5816 return false; 5817 HasNonDeletedCopyOrMove = true; 5818 } 5819 5820 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5821 !D->hasTrivialDestructorForCall()) 5822 return false; 5823 5824 for (const CXXMethodDecl *MD : D->methods()) { 5825 if (MD->isDeleted()) 5826 continue; 5827 5828 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5829 if (CD && CD->isCopyOrMoveConstructor()) 5830 HasNonDeletedCopyOrMove = true; 5831 else if (!isa<CXXDestructorDecl>(MD)) 5832 continue; 5833 5834 if (!MD->isTrivialForCall()) 5835 return false; 5836 } 5837 5838 return HasNonDeletedCopyOrMove; 5839 } 5840 5841 /// \brief Perform semantic checks on a class definition that has been 5842 /// completing, introducing implicitly-declared members, checking for 5843 /// abstract types, etc. 5844 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5845 if (!Record) 5846 return; 5847 5848 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5849 AbstractUsageInfo Info(*this, Record); 5850 CheckAbstractClassUsage(Info, Record); 5851 } 5852 5853 // If this is not an aggregate type and has no user-declared constructor, 5854 // complain about any non-static data members of reference or const scalar 5855 // type, since they will never get initializers. 5856 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5857 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5858 !Record->isLambda()) { 5859 bool Complained = false; 5860 for (const auto *F : Record->fields()) { 5861 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5862 continue; 5863 5864 if (F->getType()->isReferenceType() || 5865 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5866 if (!Complained) { 5867 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5868 << Record->getTagKind() << Record; 5869 Complained = true; 5870 } 5871 5872 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5873 << F->getType()->isReferenceType() 5874 << F->getDeclName(); 5875 } 5876 } 5877 } 5878 5879 if (Record->getIdentifier()) { 5880 // C++ [class.mem]p13: 5881 // If T is the name of a class, then each of the following shall have a 5882 // name different from T: 5883 // - every member of every anonymous union that is a member of class T. 5884 // 5885 // C++ [class.mem]p14: 5886 // In addition, if class T has a user-declared constructor (12.1), every 5887 // non-static data member of class T shall have a name different from T. 5888 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5889 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5890 ++I) { 5891 NamedDecl *D = *I; 5892 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5893 isa<IndirectFieldDecl>(D)) { 5894 Diag(D->getLocation(), diag::err_member_name_of_class) 5895 << D->getDeclName(); 5896 break; 5897 } 5898 } 5899 } 5900 5901 // Warn if the class has virtual methods but non-virtual public destructor. 5902 if (Record->isPolymorphic() && !Record->isDependentType()) { 5903 CXXDestructorDecl *dtor = Record->getDestructor(); 5904 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5905 !Record->hasAttr<FinalAttr>()) 5906 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5907 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5908 } 5909 5910 if (Record->isAbstract()) { 5911 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5912 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5913 << FA->isSpelledAsSealed(); 5914 DiagnoseAbstractType(Record); 5915 } 5916 } 5917 5918 // Set HasTrivialSpecialMemberForCall if the record has attribute 5919 // "trivial_abi". 5920 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 5921 5922 if (HasTrivialABI) 5923 Record->setHasTrivialSpecialMemberForCall(); 5924 5925 bool HasMethodWithOverrideControl = false, 5926 HasOverridingMethodWithoutOverrideControl = false; 5927 if (!Record->isDependentType()) { 5928 for (auto *M : Record->methods()) { 5929 // See if a method overloads virtual methods in a base 5930 // class without overriding any. 5931 if (!M->isStatic()) 5932 DiagnoseHiddenVirtualMethods(M); 5933 if (M->hasAttr<OverrideAttr>()) 5934 HasMethodWithOverrideControl = true; 5935 else if (M->size_overridden_methods() > 0) 5936 HasOverridingMethodWithoutOverrideControl = true; 5937 // Check whether the explicitly-defaulted special members are valid. 5938 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5939 CheckExplicitlyDefaultedSpecialMember(M); 5940 5941 // For an explicitly defaulted or deleted special member, we defer 5942 // determining triviality until the class is complete. That time is now! 5943 CXXSpecialMember CSM = getSpecialMember(M); 5944 if (!M->isImplicit() && !M->isUserProvided()) { 5945 if (CSM != CXXInvalid) { 5946 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5947 // Inform the class that we've finished declaring this member. 5948 Record->finishedDefaultedOrDeletedMember(M); 5949 M->setTrivialForCall( 5950 HasTrivialABI || 5951 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 5952 Record->setTrivialForCallFlags(M); 5953 } 5954 } 5955 5956 // Set triviality for the purpose of calls if this is a user-provided 5957 // copy/move constructor or destructor. 5958 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 5959 CSM == CXXDestructor) && M->isUserProvided()) { 5960 M->setTrivialForCall(HasTrivialABI); 5961 Record->setTrivialForCallFlags(M); 5962 } 5963 5964 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5965 M->hasAttr<DLLExportAttr>()) { 5966 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5967 M->isTrivial() && 5968 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5969 CSM == CXXDestructor)) 5970 M->dropAttr<DLLExportAttr>(); 5971 5972 if (M->hasAttr<DLLExportAttr>()) { 5973 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5974 ActOnFinishInlineFunctionDef(M); 5975 } 5976 } 5977 } 5978 } 5979 5980 if (HasMethodWithOverrideControl && 5981 HasOverridingMethodWithoutOverrideControl) { 5982 // At least one method has the 'override' control declared. 5983 // Diagnose all other overridden methods which do not have 'override' specified on them. 5984 for (auto *M : Record->methods()) 5985 DiagnoseAbsenceOfOverrideControl(M); 5986 } 5987 5988 // ms_struct is a request to use the same ABI rules as MSVC. Check 5989 // whether this class uses any C++ features that are implemented 5990 // completely differently in MSVC, and if so, emit a diagnostic. 5991 // That diagnostic defaults to an error, but we allow projects to 5992 // map it down to a warning (or ignore it). It's a fairly common 5993 // practice among users of the ms_struct pragma to mass-annotate 5994 // headers, sweeping up a bunch of types that the project doesn't 5995 // really rely on MSVC-compatible layout for. We must therefore 5996 // support "ms_struct except for C++ stuff" as a secondary ABI. 5997 if (Record->isMsStruct(Context) && 5998 (Record->isPolymorphic() || Record->getNumBases())) { 5999 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6000 } 6001 6002 checkClassLevelDLLAttribute(Record); 6003 6004 Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record)); 6005 } 6006 6007 /// Look up the special member function that would be called by a special 6008 /// member function for a subobject of class type. 6009 /// 6010 /// \param Class The class type of the subobject. 6011 /// \param CSM The kind of special member function. 6012 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6013 /// \param ConstRHS True if this is a copy operation with a const object 6014 /// on its RHS, that is, if the argument to the outer special member 6015 /// function is 'const' and this is not a field marked 'mutable'. 6016 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6017 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6018 unsigned FieldQuals, bool ConstRHS) { 6019 unsigned LHSQuals = 0; 6020 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6021 LHSQuals = FieldQuals; 6022 6023 unsigned RHSQuals = FieldQuals; 6024 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6025 RHSQuals = 0; 6026 else if (ConstRHS) 6027 RHSQuals |= Qualifiers::Const; 6028 6029 return S.LookupSpecialMember(Class, CSM, 6030 RHSQuals & Qualifiers::Const, 6031 RHSQuals & Qualifiers::Volatile, 6032 false, 6033 LHSQuals & Qualifiers::Const, 6034 LHSQuals & Qualifiers::Volatile); 6035 } 6036 6037 class Sema::InheritedConstructorInfo { 6038 Sema &S; 6039 SourceLocation UseLoc; 6040 6041 /// A mapping from the base classes through which the constructor was 6042 /// inherited to the using shadow declaration in that base class (or a null 6043 /// pointer if the constructor was declared in that base class). 6044 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6045 InheritedFromBases; 6046 6047 public: 6048 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6049 ConstructorUsingShadowDecl *Shadow) 6050 : S(S), UseLoc(UseLoc) { 6051 bool DiagnosedMultipleConstructedBases = false; 6052 CXXRecordDecl *ConstructedBase = nullptr; 6053 UsingDecl *ConstructedBaseUsing = nullptr; 6054 6055 // Find the set of such base class subobjects and check that there's a 6056 // unique constructed subobject. 6057 for (auto *D : Shadow->redecls()) { 6058 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6059 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6060 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6061 6062 InheritedFromBases.insert( 6063 std::make_pair(DNominatedBase->getCanonicalDecl(), 6064 DShadow->getNominatedBaseClassShadowDecl())); 6065 if (DShadow->constructsVirtualBase()) 6066 InheritedFromBases.insert( 6067 std::make_pair(DConstructedBase->getCanonicalDecl(), 6068 DShadow->getConstructedBaseClassShadowDecl())); 6069 else 6070 assert(DNominatedBase == DConstructedBase); 6071 6072 // [class.inhctor.init]p2: 6073 // If the constructor was inherited from multiple base class subobjects 6074 // of type B, the program is ill-formed. 6075 if (!ConstructedBase) { 6076 ConstructedBase = DConstructedBase; 6077 ConstructedBaseUsing = D->getUsingDecl(); 6078 } else if (ConstructedBase != DConstructedBase && 6079 !Shadow->isInvalidDecl()) { 6080 if (!DiagnosedMultipleConstructedBases) { 6081 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6082 << Shadow->getTargetDecl(); 6083 S.Diag(ConstructedBaseUsing->getLocation(), 6084 diag::note_ambiguous_inherited_constructor_using) 6085 << ConstructedBase; 6086 DiagnosedMultipleConstructedBases = true; 6087 } 6088 S.Diag(D->getUsingDecl()->getLocation(), 6089 diag::note_ambiguous_inherited_constructor_using) 6090 << DConstructedBase; 6091 } 6092 } 6093 6094 if (DiagnosedMultipleConstructedBases) 6095 Shadow->setInvalidDecl(); 6096 } 6097 6098 /// Find the constructor to use for inherited construction of a base class, 6099 /// and whether that base class constructor inherits the constructor from a 6100 /// virtual base class (in which case it won't actually invoke it). 6101 std::pair<CXXConstructorDecl *, bool> 6102 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6103 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6104 if (It == InheritedFromBases.end()) 6105 return std::make_pair(nullptr, false); 6106 6107 // This is an intermediary class. 6108 if (It->second) 6109 return std::make_pair( 6110 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6111 It->second->constructsVirtualBase()); 6112 6113 // This is the base class from which the constructor was inherited. 6114 return std::make_pair(Ctor, false); 6115 } 6116 }; 6117 6118 /// Is the special member function which would be selected to perform the 6119 /// specified operation on the specified class type a constexpr constructor? 6120 static bool 6121 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6122 Sema::CXXSpecialMember CSM, unsigned Quals, 6123 bool ConstRHS, 6124 CXXConstructorDecl *InheritedCtor = nullptr, 6125 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6126 // If we're inheriting a constructor, see if we need to call it for this base 6127 // class. 6128 if (InheritedCtor) { 6129 assert(CSM == Sema::CXXDefaultConstructor); 6130 auto BaseCtor = 6131 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6132 if (BaseCtor) 6133 return BaseCtor->isConstexpr(); 6134 } 6135 6136 if (CSM == Sema::CXXDefaultConstructor) 6137 return ClassDecl->hasConstexprDefaultConstructor(); 6138 6139 Sema::SpecialMemberOverloadResult SMOR = 6140 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6141 if (!SMOR.getMethod()) 6142 // A constructor we wouldn't select can't be "involved in initializing" 6143 // anything. 6144 return true; 6145 return SMOR.getMethod()->isConstexpr(); 6146 } 6147 6148 /// Determine whether the specified special member function would be constexpr 6149 /// if it were implicitly defined. 6150 static bool defaultedSpecialMemberIsConstexpr( 6151 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6152 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6153 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6154 if (!S.getLangOpts().CPlusPlus11) 6155 return false; 6156 6157 // C++11 [dcl.constexpr]p4: 6158 // In the definition of a constexpr constructor [...] 6159 bool Ctor = true; 6160 switch (CSM) { 6161 case Sema::CXXDefaultConstructor: 6162 if (Inherited) 6163 break; 6164 // Since default constructor lookup is essentially trivial (and cannot 6165 // involve, for instance, template instantiation), we compute whether a 6166 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6167 // 6168 // This is important for performance; we need to know whether the default 6169 // constructor is constexpr to determine whether the type is a literal type. 6170 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6171 6172 case Sema::CXXCopyConstructor: 6173 case Sema::CXXMoveConstructor: 6174 // For copy or move constructors, we need to perform overload resolution. 6175 break; 6176 6177 case Sema::CXXCopyAssignment: 6178 case Sema::CXXMoveAssignment: 6179 if (!S.getLangOpts().CPlusPlus14) 6180 return false; 6181 // In C++1y, we need to perform overload resolution. 6182 Ctor = false; 6183 break; 6184 6185 case Sema::CXXDestructor: 6186 case Sema::CXXInvalid: 6187 return false; 6188 } 6189 6190 // -- if the class is a non-empty union, or for each non-empty anonymous 6191 // union member of a non-union class, exactly one non-static data member 6192 // shall be initialized; [DR1359] 6193 // 6194 // If we squint, this is guaranteed, since exactly one non-static data member 6195 // will be initialized (if the constructor isn't deleted), we just don't know 6196 // which one. 6197 if (Ctor && ClassDecl->isUnion()) 6198 return CSM == Sema::CXXDefaultConstructor 6199 ? ClassDecl->hasInClassInitializer() || 6200 !ClassDecl->hasVariantMembers() 6201 : true; 6202 6203 // -- the class shall not have any virtual base classes; 6204 if (Ctor && ClassDecl->getNumVBases()) 6205 return false; 6206 6207 // C++1y [class.copy]p26: 6208 // -- [the class] is a literal type, and 6209 if (!Ctor && !ClassDecl->isLiteral()) 6210 return false; 6211 6212 // -- every constructor involved in initializing [...] base class 6213 // sub-objects shall be a constexpr constructor; 6214 // -- the assignment operator selected to copy/move each direct base 6215 // class is a constexpr function, and 6216 for (const auto &B : ClassDecl->bases()) { 6217 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6218 if (!BaseType) continue; 6219 6220 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6221 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6222 InheritedCtor, Inherited)) 6223 return false; 6224 } 6225 6226 // -- every constructor involved in initializing non-static data members 6227 // [...] shall be a constexpr constructor; 6228 // -- every non-static data member and base class sub-object shall be 6229 // initialized 6230 // -- for each non-static data member of X that is of class type (or array 6231 // thereof), the assignment operator selected to copy/move that member is 6232 // a constexpr function 6233 for (const auto *F : ClassDecl->fields()) { 6234 if (F->isInvalidDecl()) 6235 continue; 6236 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6237 continue; 6238 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6239 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6240 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6241 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6242 BaseType.getCVRQualifiers(), 6243 ConstArg && !F->isMutable())) 6244 return false; 6245 } else if (CSM == Sema::CXXDefaultConstructor) { 6246 return false; 6247 } 6248 } 6249 6250 // All OK, it's constexpr! 6251 return true; 6252 } 6253 6254 static Sema::ImplicitExceptionSpecification 6255 ComputeDefaultedSpecialMemberExceptionSpec( 6256 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6257 Sema::InheritedConstructorInfo *ICI); 6258 6259 static Sema::ImplicitExceptionSpecification 6260 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6261 auto CSM = S.getSpecialMember(MD); 6262 if (CSM != Sema::CXXInvalid) 6263 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6264 6265 auto *CD = cast<CXXConstructorDecl>(MD); 6266 assert(CD->getInheritedConstructor() && 6267 "only special members have implicit exception specs"); 6268 Sema::InheritedConstructorInfo ICI( 6269 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6270 return ComputeDefaultedSpecialMemberExceptionSpec( 6271 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6272 } 6273 6274 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6275 CXXMethodDecl *MD) { 6276 FunctionProtoType::ExtProtoInfo EPI; 6277 6278 // Build an exception specification pointing back at this member. 6279 EPI.ExceptionSpec.Type = EST_Unevaluated; 6280 EPI.ExceptionSpec.SourceDecl = MD; 6281 6282 // Set the calling convention to the default for C++ instance methods. 6283 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6284 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6285 /*IsCXXMethod=*/true)); 6286 return EPI; 6287 } 6288 6289 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6290 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6291 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6292 return; 6293 6294 // Evaluate the exception specification. 6295 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6296 auto ESI = IES.getExceptionSpec(); 6297 6298 // Update the type of the special member to use it. 6299 UpdateExceptionSpec(MD, ESI); 6300 6301 // A user-provided destructor can be defined outside the class. When that 6302 // happens, be sure to update the exception specification on both 6303 // declarations. 6304 const FunctionProtoType *CanonicalFPT = 6305 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6306 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6307 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6308 } 6309 6310 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6311 CXXRecordDecl *RD = MD->getParent(); 6312 CXXSpecialMember CSM = getSpecialMember(MD); 6313 6314 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6315 "not an explicitly-defaulted special member"); 6316 6317 // Whether this was the first-declared instance of the constructor. 6318 // This affects whether we implicitly add an exception spec and constexpr. 6319 bool First = MD == MD->getCanonicalDecl(); 6320 6321 bool HadError = false; 6322 6323 // C++11 [dcl.fct.def.default]p1: 6324 // A function that is explicitly defaulted shall 6325 // -- be a special member function (checked elsewhere), 6326 // -- have the same type (except for ref-qualifiers, and except that a 6327 // copy operation can take a non-const reference) as an implicit 6328 // declaration, and 6329 // -- not have default arguments. 6330 unsigned ExpectedParams = 1; 6331 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6332 ExpectedParams = 0; 6333 if (MD->getNumParams() != ExpectedParams) { 6334 // This also checks for default arguments: a copy or move constructor with a 6335 // default argument is classified as a default constructor, and assignment 6336 // operations and destructors can't have default arguments. 6337 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6338 << CSM << MD->getSourceRange(); 6339 HadError = true; 6340 } else if (MD->isVariadic()) { 6341 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6342 << CSM << MD->getSourceRange(); 6343 HadError = true; 6344 } 6345 6346 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6347 6348 bool CanHaveConstParam = false; 6349 if (CSM == CXXCopyConstructor) 6350 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6351 else if (CSM == CXXCopyAssignment) 6352 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6353 6354 QualType ReturnType = Context.VoidTy; 6355 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6356 // Check for return type matching. 6357 ReturnType = Type->getReturnType(); 6358 QualType ExpectedReturnType = 6359 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6360 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6361 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6362 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6363 HadError = true; 6364 } 6365 6366 // A defaulted special member cannot have cv-qualifiers. 6367 if (Type->getTypeQuals()) { 6368 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6369 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6370 HadError = true; 6371 } 6372 } 6373 6374 // Check for parameter type matching. 6375 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6376 bool HasConstParam = false; 6377 if (ExpectedParams && ArgType->isReferenceType()) { 6378 // Argument must be reference to possibly-const T. 6379 QualType ReferentType = ArgType->getPointeeType(); 6380 HasConstParam = ReferentType.isConstQualified(); 6381 6382 if (ReferentType.isVolatileQualified()) { 6383 Diag(MD->getLocation(), 6384 diag::err_defaulted_special_member_volatile_param) << CSM; 6385 HadError = true; 6386 } 6387 6388 if (HasConstParam && !CanHaveConstParam) { 6389 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6390 Diag(MD->getLocation(), 6391 diag::err_defaulted_special_member_copy_const_param) 6392 << (CSM == CXXCopyAssignment); 6393 // FIXME: Explain why this special member can't be const. 6394 } else { 6395 Diag(MD->getLocation(), 6396 diag::err_defaulted_special_member_move_const_param) 6397 << (CSM == CXXMoveAssignment); 6398 } 6399 HadError = true; 6400 } 6401 } else if (ExpectedParams) { 6402 // A copy assignment operator can take its argument by value, but a 6403 // defaulted one cannot. 6404 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6405 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6406 HadError = true; 6407 } 6408 6409 // C++11 [dcl.fct.def.default]p2: 6410 // An explicitly-defaulted function may be declared constexpr only if it 6411 // would have been implicitly declared as constexpr, 6412 // Do not apply this rule to members of class templates, since core issue 1358 6413 // makes such functions always instantiate to constexpr functions. For 6414 // functions which cannot be constexpr (for non-constructors in C++11 and for 6415 // destructors in C++1y), this is checked elsewhere. 6416 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6417 HasConstParam); 6418 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6419 : isa<CXXConstructorDecl>(MD)) && 6420 MD->isConstexpr() && !Constexpr && 6421 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6422 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6423 // FIXME: Explain why the special member can't be constexpr. 6424 HadError = true; 6425 } 6426 6427 // and may have an explicit exception-specification only if it is compatible 6428 // with the exception-specification on the implicit declaration. 6429 if (Type->hasExceptionSpec()) { 6430 // Delay the check if this is the first declaration of the special member, 6431 // since we may not have parsed some necessary in-class initializers yet. 6432 if (First) { 6433 // If the exception specification needs to be instantiated, do so now, 6434 // before we clobber it with an EST_Unevaluated specification below. 6435 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6436 InstantiateExceptionSpec(MD->getLocStart(), MD); 6437 Type = MD->getType()->getAs<FunctionProtoType>(); 6438 } 6439 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6440 } else 6441 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6442 } 6443 6444 // If a function is explicitly defaulted on its first declaration, 6445 if (First) { 6446 // -- it is implicitly considered to be constexpr if the implicit 6447 // definition would be, 6448 MD->setConstexpr(Constexpr); 6449 6450 // -- it is implicitly considered to have the same exception-specification 6451 // as if it had been implicitly declared, 6452 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6453 EPI.ExceptionSpec.Type = EST_Unevaluated; 6454 EPI.ExceptionSpec.SourceDecl = MD; 6455 MD->setType(Context.getFunctionType(ReturnType, 6456 llvm::makeArrayRef(&ArgType, 6457 ExpectedParams), 6458 EPI)); 6459 } 6460 6461 if (ShouldDeleteSpecialMember(MD, CSM)) { 6462 if (First) { 6463 SetDeclDeleted(MD, MD->getLocation()); 6464 } else { 6465 // C++11 [dcl.fct.def.default]p4: 6466 // [For a] user-provided explicitly-defaulted function [...] if such a 6467 // function is implicitly defined as deleted, the program is ill-formed. 6468 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6469 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6470 HadError = true; 6471 } 6472 } 6473 6474 if (HadError) 6475 MD->setInvalidDecl(); 6476 } 6477 6478 /// Check whether the exception specification provided for an 6479 /// explicitly-defaulted special member matches the exception specification 6480 /// that would have been generated for an implicit special member, per 6481 /// C++11 [dcl.fct.def.default]p2. 6482 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6483 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6484 // If the exception specification was explicitly specified but hadn't been 6485 // parsed when the method was defaulted, grab it now. 6486 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6487 SpecifiedType = 6488 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6489 6490 // Compute the implicit exception specification. 6491 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6492 /*IsCXXMethod=*/true); 6493 FunctionProtoType::ExtProtoInfo EPI(CC); 6494 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6495 EPI.ExceptionSpec = IES.getExceptionSpec(); 6496 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6497 Context.getFunctionType(Context.VoidTy, None, EPI)); 6498 6499 // Ensure that it matches. 6500 CheckEquivalentExceptionSpec( 6501 PDiag(diag::err_incorrect_defaulted_exception_spec) 6502 << getSpecialMember(MD), PDiag(), 6503 ImplicitType, SourceLocation(), 6504 SpecifiedType, MD->getLocation()); 6505 } 6506 6507 void Sema::CheckDelayedMemberExceptionSpecs() { 6508 decltype(DelayedExceptionSpecChecks) Checks; 6509 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6510 6511 std::swap(Checks, DelayedExceptionSpecChecks); 6512 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6513 6514 // Perform any deferred checking of exception specifications for virtual 6515 // destructors. 6516 for (auto &Check : Checks) 6517 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6518 6519 // Check that any explicitly-defaulted methods have exception specifications 6520 // compatible with their implicit exception specifications. 6521 for (auto &Spec : Specs) 6522 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6523 } 6524 6525 namespace { 6526 /// CRTP base class for visiting operations performed by a special member 6527 /// function (or inherited constructor). 6528 template<typename Derived> 6529 struct SpecialMemberVisitor { 6530 Sema &S; 6531 CXXMethodDecl *MD; 6532 Sema::CXXSpecialMember CSM; 6533 Sema::InheritedConstructorInfo *ICI; 6534 6535 // Properties of the special member, computed for convenience. 6536 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6537 6538 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6539 Sema::InheritedConstructorInfo *ICI) 6540 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6541 switch (CSM) { 6542 case Sema::CXXDefaultConstructor: 6543 case Sema::CXXCopyConstructor: 6544 case Sema::CXXMoveConstructor: 6545 IsConstructor = true; 6546 break; 6547 case Sema::CXXCopyAssignment: 6548 case Sema::CXXMoveAssignment: 6549 IsAssignment = true; 6550 break; 6551 case Sema::CXXDestructor: 6552 break; 6553 case Sema::CXXInvalid: 6554 llvm_unreachable("invalid special member kind"); 6555 } 6556 6557 if (MD->getNumParams()) { 6558 if (const ReferenceType *RT = 6559 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6560 ConstArg = RT->getPointeeType().isConstQualified(); 6561 } 6562 } 6563 6564 Derived &getDerived() { return static_cast<Derived&>(*this); } 6565 6566 /// Is this a "move" special member? 6567 bool isMove() const { 6568 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6569 } 6570 6571 /// Look up the corresponding special member in the given class. 6572 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6573 unsigned Quals, bool IsMutable) { 6574 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6575 ConstArg && !IsMutable); 6576 } 6577 6578 /// Look up the constructor for the specified base class to see if it's 6579 /// overridden due to this being an inherited constructor. 6580 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6581 if (!ICI) 6582 return {}; 6583 assert(CSM == Sema::CXXDefaultConstructor); 6584 auto *BaseCtor = 6585 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6586 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6587 return MD; 6588 return {}; 6589 } 6590 6591 /// A base or member subobject. 6592 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6593 6594 /// Get the location to use for a subobject in diagnostics. 6595 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6596 // FIXME: For an indirect virtual base, the direct base leading to 6597 // the indirect virtual base would be a more useful choice. 6598 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6599 return B->getBaseTypeLoc(); 6600 else 6601 return Subobj.get<FieldDecl*>()->getLocation(); 6602 } 6603 6604 enum BasesToVisit { 6605 /// Visit all non-virtual (direct) bases. 6606 VisitNonVirtualBases, 6607 /// Visit all direct bases, virtual or not. 6608 VisitDirectBases, 6609 /// Visit all non-virtual bases, and all virtual bases if the class 6610 /// is not abstract. 6611 VisitPotentiallyConstructedBases, 6612 /// Visit all direct or virtual bases. 6613 VisitAllBases 6614 }; 6615 6616 // Visit the bases and members of the class. 6617 bool visit(BasesToVisit Bases) { 6618 CXXRecordDecl *RD = MD->getParent(); 6619 6620 if (Bases == VisitPotentiallyConstructedBases) 6621 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6622 6623 for (auto &B : RD->bases()) 6624 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6625 getDerived().visitBase(&B)) 6626 return true; 6627 6628 if (Bases == VisitAllBases) 6629 for (auto &B : RD->vbases()) 6630 if (getDerived().visitBase(&B)) 6631 return true; 6632 6633 for (auto *F : RD->fields()) 6634 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6635 getDerived().visitField(F)) 6636 return true; 6637 6638 return false; 6639 } 6640 }; 6641 } 6642 6643 namespace { 6644 struct SpecialMemberDeletionInfo 6645 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6646 bool Diagnose; 6647 6648 SourceLocation Loc; 6649 6650 bool AllFieldsAreConst; 6651 6652 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6653 Sema::CXXSpecialMember CSM, 6654 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6655 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6656 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6657 6658 bool inUnion() const { return MD->getParent()->isUnion(); } 6659 6660 Sema::CXXSpecialMember getEffectiveCSM() { 6661 return ICI ? Sema::CXXInvalid : CSM; 6662 } 6663 6664 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6665 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6666 6667 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6668 bool shouldDeleteForField(FieldDecl *FD); 6669 bool shouldDeleteForAllConstMembers(); 6670 6671 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6672 unsigned Quals); 6673 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6674 Sema::SpecialMemberOverloadResult SMOR, 6675 bool IsDtorCallInCtor); 6676 6677 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6678 }; 6679 } 6680 6681 /// Is the given special member inaccessible when used on the given 6682 /// sub-object. 6683 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6684 CXXMethodDecl *target) { 6685 /// If we're operating on a base class, the object type is the 6686 /// type of this special member. 6687 QualType objectTy; 6688 AccessSpecifier access = target->getAccess(); 6689 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6690 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6691 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6692 6693 // If we're operating on a field, the object type is the type of the field. 6694 } else { 6695 objectTy = S.Context.getTypeDeclType(target->getParent()); 6696 } 6697 6698 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6699 } 6700 6701 /// Check whether we should delete a special member due to the implicit 6702 /// definition containing a call to a special member of a subobject. 6703 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6704 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6705 bool IsDtorCallInCtor) { 6706 CXXMethodDecl *Decl = SMOR.getMethod(); 6707 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6708 6709 int DiagKind = -1; 6710 6711 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6712 DiagKind = !Decl ? 0 : 1; 6713 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6714 DiagKind = 2; 6715 else if (!isAccessible(Subobj, Decl)) 6716 DiagKind = 3; 6717 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6718 !Decl->isTrivial()) { 6719 // A member of a union must have a trivial corresponding special member. 6720 // As a weird special case, a destructor call from a union's constructor 6721 // must be accessible and non-deleted, but need not be trivial. Such a 6722 // destructor is never actually called, but is semantically checked as 6723 // if it were. 6724 DiagKind = 4; 6725 } 6726 6727 if (DiagKind == -1) 6728 return false; 6729 6730 if (Diagnose) { 6731 if (Field) { 6732 S.Diag(Field->getLocation(), 6733 diag::note_deleted_special_member_class_subobject) 6734 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6735 << Field << DiagKind << IsDtorCallInCtor; 6736 } else { 6737 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6738 S.Diag(Base->getLocStart(), 6739 diag::note_deleted_special_member_class_subobject) 6740 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6741 << Base->getType() << DiagKind << IsDtorCallInCtor; 6742 } 6743 6744 if (DiagKind == 1) 6745 S.NoteDeletedFunction(Decl); 6746 // FIXME: Explain inaccessibility if DiagKind == 3. 6747 } 6748 6749 return true; 6750 } 6751 6752 /// Check whether we should delete a special member function due to having a 6753 /// direct or virtual base class or non-static data member of class type M. 6754 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6755 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6756 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6757 bool IsMutable = Field && Field->isMutable(); 6758 6759 // C++11 [class.ctor]p5: 6760 // -- any direct or virtual base class, or non-static data member with no 6761 // brace-or-equal-initializer, has class type M (or array thereof) and 6762 // either M has no default constructor or overload resolution as applied 6763 // to M's default constructor results in an ambiguity or in a function 6764 // that is deleted or inaccessible 6765 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6766 // -- a direct or virtual base class B that cannot be copied/moved because 6767 // overload resolution, as applied to B's corresponding special member, 6768 // results in an ambiguity or a function that is deleted or inaccessible 6769 // from the defaulted special member 6770 // C++11 [class.dtor]p5: 6771 // -- any direct or virtual base class [...] has a type with a destructor 6772 // that is deleted or inaccessible 6773 if (!(CSM == Sema::CXXDefaultConstructor && 6774 Field && Field->hasInClassInitializer()) && 6775 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6776 false)) 6777 return true; 6778 6779 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6780 // -- any direct or virtual base class or non-static data member has a 6781 // type with a destructor that is deleted or inaccessible 6782 if (IsConstructor) { 6783 Sema::SpecialMemberOverloadResult SMOR = 6784 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6785 false, false, false, false, false); 6786 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6787 return true; 6788 } 6789 6790 return false; 6791 } 6792 6793 /// Check whether we should delete a special member function due to the class 6794 /// having a particular direct or virtual base class. 6795 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6796 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6797 // If program is correct, BaseClass cannot be null, but if it is, the error 6798 // must be reported elsewhere. 6799 if (!BaseClass) 6800 return false; 6801 // If we have an inheriting constructor, check whether we're calling an 6802 // inherited constructor instead of a default constructor. 6803 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6804 if (auto *BaseCtor = SMOR.getMethod()) { 6805 // Note that we do not check access along this path; other than that, 6806 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6807 // FIXME: Check that the base has a usable destructor! Sink this into 6808 // shouldDeleteForClassSubobject. 6809 if (BaseCtor->isDeleted() && Diagnose) { 6810 S.Diag(Base->getLocStart(), 6811 diag::note_deleted_special_member_class_subobject) 6812 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6813 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6814 S.NoteDeletedFunction(BaseCtor); 6815 } 6816 return BaseCtor->isDeleted(); 6817 } 6818 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6819 } 6820 6821 /// Check whether we should delete a special member function due to the class 6822 /// having a particular non-static data member. 6823 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6824 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6825 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6826 6827 if (CSM == Sema::CXXDefaultConstructor) { 6828 // For a default constructor, all references must be initialized in-class 6829 // and, if a union, it must have a non-const member. 6830 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6831 if (Diagnose) 6832 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6833 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6834 return true; 6835 } 6836 // C++11 [class.ctor]p5: any non-variant non-static data member of 6837 // const-qualified type (or array thereof) with no 6838 // brace-or-equal-initializer does not have a user-provided default 6839 // constructor. 6840 if (!inUnion() && FieldType.isConstQualified() && 6841 !FD->hasInClassInitializer() && 6842 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6843 if (Diagnose) 6844 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6845 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6846 return true; 6847 } 6848 6849 if (inUnion() && !FieldType.isConstQualified()) 6850 AllFieldsAreConst = false; 6851 } else if (CSM == Sema::CXXCopyConstructor) { 6852 // For a copy constructor, data members must not be of rvalue reference 6853 // type. 6854 if (FieldType->isRValueReferenceType()) { 6855 if (Diagnose) 6856 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6857 << MD->getParent() << FD << FieldType; 6858 return true; 6859 } 6860 } else if (IsAssignment) { 6861 // For an assignment operator, data members must not be of reference type. 6862 if (FieldType->isReferenceType()) { 6863 if (Diagnose) 6864 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6865 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6866 return true; 6867 } 6868 if (!FieldRecord && FieldType.isConstQualified()) { 6869 // C++11 [class.copy]p23: 6870 // -- a non-static data member of const non-class type (or array thereof) 6871 if (Diagnose) 6872 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6873 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 6874 return true; 6875 } 6876 } 6877 6878 if (FieldRecord) { 6879 // Some additional restrictions exist on the variant members. 6880 if (!inUnion() && FieldRecord->isUnion() && 6881 FieldRecord->isAnonymousStructOrUnion()) { 6882 bool AllVariantFieldsAreConst = true; 6883 6884 // FIXME: Handle anonymous unions declared within anonymous unions. 6885 for (auto *UI : FieldRecord->fields()) { 6886 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6887 6888 if (!UnionFieldType.isConstQualified()) 6889 AllVariantFieldsAreConst = false; 6890 6891 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6892 if (UnionFieldRecord && 6893 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6894 UnionFieldType.getCVRQualifiers())) 6895 return true; 6896 } 6897 6898 // At least one member in each anonymous union must be non-const 6899 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6900 !FieldRecord->field_empty()) { 6901 if (Diagnose) 6902 S.Diag(FieldRecord->getLocation(), 6903 diag::note_deleted_default_ctor_all_const) 6904 << !!ICI << MD->getParent() << /*anonymous union*/1; 6905 return true; 6906 } 6907 6908 // Don't check the implicit member of the anonymous union type. 6909 // This is technically non-conformant, but sanity demands it. 6910 return false; 6911 } 6912 6913 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6914 FieldType.getCVRQualifiers())) 6915 return true; 6916 } 6917 6918 return false; 6919 } 6920 6921 /// C++11 [class.ctor] p5: 6922 /// A defaulted default constructor for a class X is defined as deleted if 6923 /// X is a union and all of its variant members are of const-qualified type. 6924 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6925 // This is a silly definition, because it gives an empty union a deleted 6926 // default constructor. Don't do that. 6927 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 6928 bool AnyFields = false; 6929 for (auto *F : MD->getParent()->fields()) 6930 if ((AnyFields = !F->isUnnamedBitfield())) 6931 break; 6932 if (!AnyFields) 6933 return false; 6934 if (Diagnose) 6935 S.Diag(MD->getParent()->getLocation(), 6936 diag::note_deleted_default_ctor_all_const) 6937 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6938 return true; 6939 } 6940 return false; 6941 } 6942 6943 /// Determine whether a defaulted special member function should be defined as 6944 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6945 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6946 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6947 InheritedConstructorInfo *ICI, 6948 bool Diagnose) { 6949 if (MD->isInvalidDecl()) 6950 return false; 6951 CXXRecordDecl *RD = MD->getParent(); 6952 assert(!RD->isDependentType() && "do deletion after instantiation"); 6953 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6954 return false; 6955 6956 // C++11 [expr.lambda.prim]p19: 6957 // The closure type associated with a lambda-expression has a 6958 // deleted (8.4.3) default constructor and a deleted copy 6959 // assignment operator. 6960 if (RD->isLambda() && 6961 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6962 if (Diagnose) 6963 Diag(RD->getLocation(), diag::note_lambda_decl); 6964 return true; 6965 } 6966 6967 // For an anonymous struct or union, the copy and assignment special members 6968 // will never be used, so skip the check. For an anonymous union declared at 6969 // namespace scope, the constructor and destructor are used. 6970 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6971 RD->isAnonymousStructOrUnion()) 6972 return false; 6973 6974 // C++11 [class.copy]p7, p18: 6975 // If the class definition declares a move constructor or move assignment 6976 // operator, an implicitly declared copy constructor or copy assignment 6977 // operator is defined as deleted. 6978 if (MD->isImplicit() && 6979 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6980 CXXMethodDecl *UserDeclaredMove = nullptr; 6981 6982 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 6983 // deletion of the corresponding copy operation, not both copy operations. 6984 // MSVC 2015 has adopted the standards conforming behavior. 6985 bool DeletesOnlyMatchingCopy = 6986 getLangOpts().MSVCCompat && 6987 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 6988 6989 if (RD->hasUserDeclaredMoveConstructor() && 6990 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 6991 if (!Diagnose) return true; 6992 6993 // Find any user-declared move constructor. 6994 for (auto *I : RD->ctors()) { 6995 if (I->isMoveConstructor()) { 6996 UserDeclaredMove = I; 6997 break; 6998 } 6999 } 7000 assert(UserDeclaredMove); 7001 } else if (RD->hasUserDeclaredMoveAssignment() && 7002 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7003 if (!Diagnose) return true; 7004 7005 // Find any user-declared move assignment operator. 7006 for (auto *I : RD->methods()) { 7007 if (I->isMoveAssignmentOperator()) { 7008 UserDeclaredMove = I; 7009 break; 7010 } 7011 } 7012 assert(UserDeclaredMove); 7013 } 7014 7015 if (UserDeclaredMove) { 7016 Diag(UserDeclaredMove->getLocation(), 7017 diag::note_deleted_copy_user_declared_move) 7018 << (CSM == CXXCopyAssignment) << RD 7019 << UserDeclaredMove->isMoveAssignmentOperator(); 7020 return true; 7021 } 7022 } 7023 7024 // Do access control from the special member function 7025 ContextRAII MethodContext(*this, MD); 7026 7027 // C++11 [class.dtor]p5: 7028 // -- for a virtual destructor, lookup of the non-array deallocation function 7029 // results in an ambiguity or in a function that is deleted or inaccessible 7030 if (CSM == CXXDestructor && MD->isVirtual()) { 7031 FunctionDecl *OperatorDelete = nullptr; 7032 DeclarationName Name = 7033 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7034 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7035 OperatorDelete, /*Diagnose*/false)) { 7036 if (Diagnose) 7037 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7038 return true; 7039 } 7040 } 7041 7042 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7043 7044 // Per DR1611, do not consider virtual bases of constructors of abstract 7045 // classes, since we are not going to construct them. 7046 // Per DR1658, do not consider virtual bases of destructors of abstract 7047 // classes either. 7048 // Per DR2180, for assignment operators we only assign (and thus only 7049 // consider) direct bases. 7050 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7051 : SMI.VisitPotentiallyConstructedBases)) 7052 return true; 7053 7054 if (SMI.shouldDeleteForAllConstMembers()) 7055 return true; 7056 7057 if (getLangOpts().CUDA) { 7058 // We should delete the special member in CUDA mode if target inference 7059 // failed. 7060 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 7061 Diagnose); 7062 } 7063 7064 return false; 7065 } 7066 7067 /// Perform lookup for a special member of the specified kind, and determine 7068 /// whether it is trivial. If the triviality can be determined without the 7069 /// lookup, skip it. This is intended for use when determining whether a 7070 /// special member of a containing object is trivial, and thus does not ever 7071 /// perform overload resolution for default constructors. 7072 /// 7073 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7074 /// member that was most likely to be intended to be trivial, if any. 7075 /// 7076 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7077 /// determine whether the special member is trivial. 7078 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7079 Sema::CXXSpecialMember CSM, unsigned Quals, 7080 bool ConstRHS, 7081 Sema::TrivialABIHandling TAH, 7082 CXXMethodDecl **Selected) { 7083 if (Selected) 7084 *Selected = nullptr; 7085 7086 switch (CSM) { 7087 case Sema::CXXInvalid: 7088 llvm_unreachable("not a special member"); 7089 7090 case Sema::CXXDefaultConstructor: 7091 // C++11 [class.ctor]p5: 7092 // A default constructor is trivial if: 7093 // - all the [direct subobjects] have trivial default constructors 7094 // 7095 // Note, no overload resolution is performed in this case. 7096 if (RD->hasTrivialDefaultConstructor()) 7097 return true; 7098 7099 if (Selected) { 7100 // If there's a default constructor which could have been trivial, dig it 7101 // out. Otherwise, if there's any user-provided default constructor, point 7102 // to that as an example of why there's not a trivial one. 7103 CXXConstructorDecl *DefCtor = nullptr; 7104 if (RD->needsImplicitDefaultConstructor()) 7105 S.DeclareImplicitDefaultConstructor(RD); 7106 for (auto *CI : RD->ctors()) { 7107 if (!CI->isDefaultConstructor()) 7108 continue; 7109 DefCtor = CI; 7110 if (!DefCtor->isUserProvided()) 7111 break; 7112 } 7113 7114 *Selected = DefCtor; 7115 } 7116 7117 return false; 7118 7119 case Sema::CXXDestructor: 7120 // C++11 [class.dtor]p5: 7121 // A destructor is trivial if: 7122 // - all the direct [subobjects] have trivial destructors 7123 if (RD->hasTrivialDestructor() || 7124 (TAH == Sema::TAH_ConsiderTrivialABI && 7125 RD->hasTrivialDestructorForCall())) 7126 return true; 7127 7128 if (Selected) { 7129 if (RD->needsImplicitDestructor()) 7130 S.DeclareImplicitDestructor(RD); 7131 *Selected = RD->getDestructor(); 7132 } 7133 7134 return false; 7135 7136 case Sema::CXXCopyConstructor: 7137 // C++11 [class.copy]p12: 7138 // A copy constructor is trivial if: 7139 // - the constructor selected to copy each direct [subobject] is trivial 7140 if (RD->hasTrivialCopyConstructor() || 7141 (TAH == Sema::TAH_ConsiderTrivialABI && 7142 RD->hasTrivialCopyConstructorForCall())) { 7143 if (Quals == Qualifiers::Const) 7144 // We must either select the trivial copy constructor or reach an 7145 // ambiguity; no need to actually perform overload resolution. 7146 return true; 7147 } else if (!Selected) { 7148 return false; 7149 } 7150 // In C++98, we are not supposed to perform overload resolution here, but we 7151 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7152 // cases like B as having a non-trivial copy constructor: 7153 // struct A { template<typename T> A(T&); }; 7154 // struct B { mutable A a; }; 7155 goto NeedOverloadResolution; 7156 7157 case Sema::CXXCopyAssignment: 7158 // C++11 [class.copy]p25: 7159 // A copy assignment operator is trivial if: 7160 // - the assignment operator selected to copy each direct [subobject] is 7161 // trivial 7162 if (RD->hasTrivialCopyAssignment()) { 7163 if (Quals == Qualifiers::Const) 7164 return true; 7165 } else if (!Selected) { 7166 return false; 7167 } 7168 // In C++98, we are not supposed to perform overload resolution here, but we 7169 // treat that as a language defect. 7170 goto NeedOverloadResolution; 7171 7172 case Sema::CXXMoveConstructor: 7173 case Sema::CXXMoveAssignment: 7174 NeedOverloadResolution: 7175 Sema::SpecialMemberOverloadResult SMOR = 7176 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7177 7178 // The standard doesn't describe how to behave if the lookup is ambiguous. 7179 // We treat it as not making the member non-trivial, just like the standard 7180 // mandates for the default constructor. This should rarely matter, because 7181 // the member will also be deleted. 7182 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7183 return true; 7184 7185 if (!SMOR.getMethod()) { 7186 assert(SMOR.getKind() == 7187 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7188 return false; 7189 } 7190 7191 // We deliberately don't check if we found a deleted special member. We're 7192 // not supposed to! 7193 if (Selected) 7194 *Selected = SMOR.getMethod(); 7195 7196 if (TAH == Sema::TAH_ConsiderTrivialABI && 7197 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7198 return SMOR.getMethod()->isTrivialForCall(); 7199 return SMOR.getMethod()->isTrivial(); 7200 } 7201 7202 llvm_unreachable("unknown special method kind"); 7203 } 7204 7205 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7206 for (auto *CI : RD->ctors()) 7207 if (!CI->isImplicit()) 7208 return CI; 7209 7210 // Look for constructor templates. 7211 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7212 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7213 if (CXXConstructorDecl *CD = 7214 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7215 return CD; 7216 } 7217 7218 return nullptr; 7219 } 7220 7221 /// The kind of subobject we are checking for triviality. The values of this 7222 /// enumeration are used in diagnostics. 7223 enum TrivialSubobjectKind { 7224 /// The subobject is a base class. 7225 TSK_BaseClass, 7226 /// The subobject is a non-static data member. 7227 TSK_Field, 7228 /// The object is actually the complete object. 7229 TSK_CompleteObject 7230 }; 7231 7232 /// Check whether the special member selected for a given type would be trivial. 7233 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7234 QualType SubType, bool ConstRHS, 7235 Sema::CXXSpecialMember CSM, 7236 TrivialSubobjectKind Kind, 7237 Sema::TrivialABIHandling TAH, bool Diagnose) { 7238 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7239 if (!SubRD) 7240 return true; 7241 7242 CXXMethodDecl *Selected; 7243 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7244 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7245 return true; 7246 7247 if (Diagnose) { 7248 if (ConstRHS) 7249 SubType.addConst(); 7250 7251 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7252 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7253 << Kind << SubType.getUnqualifiedType(); 7254 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7255 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7256 } else if (!Selected) 7257 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7258 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7259 else if (Selected->isUserProvided()) { 7260 if (Kind == TSK_CompleteObject) 7261 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7262 << Kind << SubType.getUnqualifiedType() << CSM; 7263 else { 7264 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7265 << Kind << SubType.getUnqualifiedType() << CSM; 7266 S.Diag(Selected->getLocation(), diag::note_declared_at); 7267 } 7268 } else { 7269 if (Kind != TSK_CompleteObject) 7270 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7271 << Kind << SubType.getUnqualifiedType() << CSM; 7272 7273 // Explain why the defaulted or deleted special member isn't trivial. 7274 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7275 Diagnose); 7276 } 7277 } 7278 7279 return false; 7280 } 7281 7282 /// Check whether the members of a class type allow a special member to be 7283 /// trivial. 7284 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7285 Sema::CXXSpecialMember CSM, 7286 bool ConstArg, 7287 Sema::TrivialABIHandling TAH, 7288 bool Diagnose) { 7289 for (const auto *FI : RD->fields()) { 7290 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7291 continue; 7292 7293 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7294 7295 // Pretend anonymous struct or union members are members of this class. 7296 if (FI->isAnonymousStructOrUnion()) { 7297 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7298 CSM, ConstArg, TAH, Diagnose)) 7299 return false; 7300 continue; 7301 } 7302 7303 // C++11 [class.ctor]p5: 7304 // A default constructor is trivial if [...] 7305 // -- no non-static data member of its class has a 7306 // brace-or-equal-initializer 7307 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7308 if (Diagnose) 7309 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7310 return false; 7311 } 7312 7313 // Objective C ARC 4.3.5: 7314 // [...] nontrivally ownership-qualified types are [...] not trivially 7315 // default constructible, copy constructible, move constructible, copy 7316 // assignable, move assignable, or destructible [...] 7317 if (FieldType.hasNonTrivialObjCLifetime()) { 7318 if (Diagnose) 7319 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7320 << RD << FieldType.getObjCLifetime(); 7321 return false; 7322 } 7323 7324 bool ConstRHS = ConstArg && !FI->isMutable(); 7325 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7326 CSM, TSK_Field, TAH, Diagnose)) 7327 return false; 7328 } 7329 7330 return true; 7331 } 7332 7333 /// Diagnose why the specified class does not have a trivial special member of 7334 /// the given kind. 7335 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7336 QualType Ty = Context.getRecordType(RD); 7337 7338 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7339 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7340 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7341 /*Diagnose*/true); 7342 } 7343 7344 /// Determine whether a defaulted or deleted special member function is trivial, 7345 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7346 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7347 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7348 TrivialABIHandling TAH, bool Diagnose) { 7349 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7350 7351 CXXRecordDecl *RD = MD->getParent(); 7352 7353 bool ConstArg = false; 7354 7355 // C++11 [class.copy]p12, p25: [DR1593] 7356 // A [special member] is trivial if [...] its parameter-type-list is 7357 // equivalent to the parameter-type-list of an implicit declaration [...] 7358 switch (CSM) { 7359 case CXXDefaultConstructor: 7360 case CXXDestructor: 7361 // Trivial default constructors and destructors cannot have parameters. 7362 break; 7363 7364 case CXXCopyConstructor: 7365 case CXXCopyAssignment: { 7366 // Trivial copy operations always have const, non-volatile parameter types. 7367 ConstArg = true; 7368 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7369 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7370 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7371 if (Diagnose) 7372 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7373 << Param0->getSourceRange() << Param0->getType() 7374 << Context.getLValueReferenceType( 7375 Context.getRecordType(RD).withConst()); 7376 return false; 7377 } 7378 break; 7379 } 7380 7381 case CXXMoveConstructor: 7382 case CXXMoveAssignment: { 7383 // Trivial move operations always have non-cv-qualified parameters. 7384 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7385 const RValueReferenceType *RT = 7386 Param0->getType()->getAs<RValueReferenceType>(); 7387 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7388 if (Diagnose) 7389 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7390 << Param0->getSourceRange() << Param0->getType() 7391 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7392 return false; 7393 } 7394 break; 7395 } 7396 7397 case CXXInvalid: 7398 llvm_unreachable("not a special member"); 7399 } 7400 7401 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7402 if (Diagnose) 7403 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7404 diag::note_nontrivial_default_arg) 7405 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7406 return false; 7407 } 7408 if (MD->isVariadic()) { 7409 if (Diagnose) 7410 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7411 return false; 7412 } 7413 7414 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7415 // A copy/move [constructor or assignment operator] is trivial if 7416 // -- the [member] selected to copy/move each direct base class subobject 7417 // is trivial 7418 // 7419 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7420 // A [default constructor or destructor] is trivial if 7421 // -- all the direct base classes have trivial [default constructors or 7422 // destructors] 7423 for (const auto &BI : RD->bases()) 7424 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7425 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7426 return false; 7427 7428 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7429 // A copy/move [constructor or assignment operator] for a class X is 7430 // trivial if 7431 // -- for each non-static data member of X that is of class type (or array 7432 // thereof), the constructor selected to copy/move that member is 7433 // trivial 7434 // 7435 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7436 // A [default constructor or destructor] is trivial if 7437 // -- for all of the non-static data members of its class that are of class 7438 // type (or array thereof), each such class has a trivial [default 7439 // constructor or destructor] 7440 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7441 return false; 7442 7443 // C++11 [class.dtor]p5: 7444 // A destructor is trivial if [...] 7445 // -- the destructor is not virtual 7446 if (CSM == CXXDestructor && MD->isVirtual()) { 7447 if (Diagnose) 7448 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7449 return false; 7450 } 7451 7452 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7453 // A [special member] for class X is trivial if [...] 7454 // -- class X has no virtual functions and no virtual base classes 7455 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7456 if (!Diagnose) 7457 return false; 7458 7459 if (RD->getNumVBases()) { 7460 // Check for virtual bases. We already know that the corresponding 7461 // member in all bases is trivial, so vbases must all be direct. 7462 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7463 assert(BS.isVirtual()); 7464 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7465 return false; 7466 } 7467 7468 // Must have a virtual method. 7469 for (const auto *MI : RD->methods()) { 7470 if (MI->isVirtual()) { 7471 SourceLocation MLoc = MI->getLocStart(); 7472 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7473 return false; 7474 } 7475 } 7476 7477 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7478 } 7479 7480 // Looks like it's trivial! 7481 return true; 7482 } 7483 7484 namespace { 7485 struct FindHiddenVirtualMethod { 7486 Sema *S; 7487 CXXMethodDecl *Method; 7488 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7489 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7490 7491 private: 7492 /// Check whether any most overriden method from MD in Methods 7493 static bool CheckMostOverridenMethods( 7494 const CXXMethodDecl *MD, 7495 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7496 if (MD->size_overridden_methods() == 0) 7497 return Methods.count(MD->getCanonicalDecl()); 7498 for (const CXXMethodDecl *O : MD->overridden_methods()) 7499 if (CheckMostOverridenMethods(O, Methods)) 7500 return true; 7501 return false; 7502 } 7503 7504 public: 7505 /// Member lookup function that determines whether a given C++ 7506 /// method overloads virtual methods in a base class without overriding any, 7507 /// to be used with CXXRecordDecl::lookupInBases(). 7508 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7509 RecordDecl *BaseRecord = 7510 Specifier->getType()->getAs<RecordType>()->getDecl(); 7511 7512 DeclarationName Name = Method->getDeclName(); 7513 assert(Name.getNameKind() == DeclarationName::Identifier); 7514 7515 bool foundSameNameMethod = false; 7516 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7517 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7518 Path.Decls = Path.Decls.slice(1)) { 7519 NamedDecl *D = Path.Decls.front(); 7520 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7521 MD = MD->getCanonicalDecl(); 7522 foundSameNameMethod = true; 7523 // Interested only in hidden virtual methods. 7524 if (!MD->isVirtual()) 7525 continue; 7526 // If the method we are checking overrides a method from its base 7527 // don't warn about the other overloaded methods. Clang deviates from 7528 // GCC by only diagnosing overloads of inherited virtual functions that 7529 // do not override any other virtual functions in the base. GCC's 7530 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7531 // function from a base class. These cases may be better served by a 7532 // warning (not specific to virtual functions) on call sites when the 7533 // call would select a different function from the base class, were it 7534 // visible. 7535 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7536 if (!S->IsOverload(Method, MD, false)) 7537 return true; 7538 // Collect the overload only if its hidden. 7539 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7540 overloadedMethods.push_back(MD); 7541 } 7542 } 7543 7544 if (foundSameNameMethod) 7545 OverloadedMethods.append(overloadedMethods.begin(), 7546 overloadedMethods.end()); 7547 return foundSameNameMethod; 7548 } 7549 }; 7550 } // end anonymous namespace 7551 7552 /// \brief Add the most overriden methods from MD to Methods 7553 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7554 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7555 if (MD->size_overridden_methods() == 0) 7556 Methods.insert(MD->getCanonicalDecl()); 7557 else 7558 for (const CXXMethodDecl *O : MD->overridden_methods()) 7559 AddMostOverridenMethods(O, Methods); 7560 } 7561 7562 /// \brief Check if a method overloads virtual methods in a base class without 7563 /// overriding any. 7564 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7565 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7566 if (!MD->getDeclName().isIdentifier()) 7567 return; 7568 7569 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7570 /*bool RecordPaths=*/false, 7571 /*bool DetectVirtual=*/false); 7572 FindHiddenVirtualMethod FHVM; 7573 FHVM.Method = MD; 7574 FHVM.S = this; 7575 7576 // Keep the base methods that were overriden or introduced in the subclass 7577 // by 'using' in a set. A base method not in this set is hidden. 7578 CXXRecordDecl *DC = MD->getParent(); 7579 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7580 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7581 NamedDecl *ND = *I; 7582 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7583 ND = shad->getTargetDecl(); 7584 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7585 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7586 } 7587 7588 if (DC->lookupInBases(FHVM, Paths)) 7589 OverloadedMethods = FHVM.OverloadedMethods; 7590 } 7591 7592 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7593 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7594 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7595 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7596 PartialDiagnostic PD = PDiag( 7597 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7598 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7599 Diag(overloadedMD->getLocation(), PD); 7600 } 7601 } 7602 7603 /// \brief Diagnose methods which overload virtual methods in a base class 7604 /// without overriding any. 7605 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7606 if (MD->isInvalidDecl()) 7607 return; 7608 7609 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7610 return; 7611 7612 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7613 FindHiddenVirtualMethods(MD, OverloadedMethods); 7614 if (!OverloadedMethods.empty()) { 7615 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7616 << MD << (OverloadedMethods.size() > 1); 7617 7618 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7619 } 7620 } 7621 7622 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 7623 auto PrintDiagAndRemoveAttr = [&]() { 7624 // No diagnostics if this is a template instantiation. 7625 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 7626 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 7627 diag::ext_cannot_use_trivial_abi) << &RD; 7628 RD.dropAttr<TrivialABIAttr>(); 7629 }; 7630 7631 // Ill-formed if the struct has virtual functions. 7632 if (RD.isPolymorphic()) { 7633 PrintDiagAndRemoveAttr(); 7634 return; 7635 } 7636 7637 for (const auto &B : RD.bases()) { 7638 // Ill-formed if the base class is non-trivial for the purpose of calls or a 7639 // virtual base. 7640 if ((!B.getType()->isDependentType() && 7641 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 7642 B.isVirtual()) { 7643 PrintDiagAndRemoveAttr(); 7644 return; 7645 } 7646 } 7647 7648 for (const auto *FD : RD.fields()) { 7649 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 7650 // non-trivial for the purpose of calls. 7651 QualType FT = FD->getType(); 7652 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 7653 PrintDiagAndRemoveAttr(); 7654 return; 7655 } 7656 7657 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 7658 if (!RT->isDependentType() && 7659 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 7660 PrintDiagAndRemoveAttr(); 7661 return; 7662 } 7663 } 7664 } 7665 7666 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7667 Decl *TagDecl, 7668 SourceLocation LBrac, 7669 SourceLocation RBrac, 7670 AttributeList *AttrList) { 7671 if (!TagDecl) 7672 return; 7673 7674 AdjustDeclIfTemplate(TagDecl); 7675 7676 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7677 if (l->getKind() != AttributeList::AT_Visibility) 7678 continue; 7679 l->setInvalid(); 7680 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7681 l->getName(); 7682 } 7683 7684 // See if trivial_abi has to be dropped. 7685 auto *RD = dyn_cast<CXXRecordDecl>(TagDecl); 7686 if (RD && RD->hasAttr<TrivialABIAttr>()) 7687 checkIllFormedTrivialABIStruct(*RD); 7688 7689 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7690 // strict aliasing violation! 7691 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7692 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7693 7694 CheckCompletedCXXClass(RD); 7695 } 7696 7697 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7698 /// special functions, such as the default constructor, copy 7699 /// constructor, or destructor, to the given C++ class (C++ 7700 /// [special]p1). This routine can only be executed just before the 7701 /// definition of the class is complete. 7702 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7703 if (ClassDecl->needsImplicitDefaultConstructor()) { 7704 ++ASTContext::NumImplicitDefaultConstructors; 7705 7706 if (ClassDecl->hasInheritedConstructor()) 7707 DeclareImplicitDefaultConstructor(ClassDecl); 7708 } 7709 7710 if (ClassDecl->needsImplicitCopyConstructor()) { 7711 ++ASTContext::NumImplicitCopyConstructors; 7712 7713 // If the properties or semantics of the copy constructor couldn't be 7714 // determined while the class was being declared, force a declaration 7715 // of it now. 7716 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7717 ClassDecl->hasInheritedConstructor()) 7718 DeclareImplicitCopyConstructor(ClassDecl); 7719 // For the MS ABI we need to know whether the copy ctor is deleted. A 7720 // prerequisite for deleting the implicit copy ctor is that the class has a 7721 // move ctor or move assignment that is either user-declared or whose 7722 // semantics are inherited from a subobject. FIXME: We should provide a more 7723 // direct way for CodeGen to ask whether the constructor was deleted. 7724 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7725 (ClassDecl->hasUserDeclaredMoveConstructor() || 7726 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7727 ClassDecl->hasUserDeclaredMoveAssignment() || 7728 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7729 DeclareImplicitCopyConstructor(ClassDecl); 7730 } 7731 7732 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7733 ++ASTContext::NumImplicitMoveConstructors; 7734 7735 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7736 ClassDecl->hasInheritedConstructor()) 7737 DeclareImplicitMoveConstructor(ClassDecl); 7738 } 7739 7740 if (ClassDecl->needsImplicitCopyAssignment()) { 7741 ++ASTContext::NumImplicitCopyAssignmentOperators; 7742 7743 // If we have a dynamic class, then the copy assignment operator may be 7744 // virtual, so we have to declare it immediately. This ensures that, e.g., 7745 // it shows up in the right place in the vtable and that we diagnose 7746 // problems with the implicit exception specification. 7747 if (ClassDecl->isDynamicClass() || 7748 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7749 ClassDecl->hasInheritedAssignment()) 7750 DeclareImplicitCopyAssignment(ClassDecl); 7751 } 7752 7753 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7754 ++ASTContext::NumImplicitMoveAssignmentOperators; 7755 7756 // Likewise for the move assignment operator. 7757 if (ClassDecl->isDynamicClass() || 7758 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7759 ClassDecl->hasInheritedAssignment()) 7760 DeclareImplicitMoveAssignment(ClassDecl); 7761 } 7762 7763 if (ClassDecl->needsImplicitDestructor()) { 7764 ++ASTContext::NumImplicitDestructors; 7765 7766 // If we have a dynamic class, then the destructor may be virtual, so we 7767 // have to declare the destructor immediately. This ensures that, e.g., it 7768 // shows up in the right place in the vtable and that we diagnose problems 7769 // with the implicit exception specification. 7770 if (ClassDecl->isDynamicClass() || 7771 ClassDecl->needsOverloadResolutionForDestructor()) 7772 DeclareImplicitDestructor(ClassDecl); 7773 } 7774 } 7775 7776 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7777 if (!D) 7778 return 0; 7779 7780 // The order of template parameters is not important here. All names 7781 // get added to the same scope. 7782 SmallVector<TemplateParameterList *, 4> ParameterLists; 7783 7784 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7785 D = TD->getTemplatedDecl(); 7786 7787 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7788 ParameterLists.push_back(PSD->getTemplateParameters()); 7789 7790 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7791 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7792 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7793 7794 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7795 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7796 ParameterLists.push_back(FTD->getTemplateParameters()); 7797 } 7798 } 7799 7800 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7801 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7802 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7803 7804 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7805 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7806 ParameterLists.push_back(CTD->getTemplateParameters()); 7807 } 7808 } 7809 7810 unsigned Count = 0; 7811 for (TemplateParameterList *Params : ParameterLists) { 7812 if (Params->size() > 0) 7813 // Ignore explicit specializations; they don't contribute to the template 7814 // depth. 7815 ++Count; 7816 for (NamedDecl *Param : *Params) { 7817 if (Param->getDeclName()) { 7818 S->AddDecl(Param); 7819 IdResolver.AddDecl(Param); 7820 } 7821 } 7822 } 7823 7824 return Count; 7825 } 7826 7827 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7828 if (!RecordD) return; 7829 AdjustDeclIfTemplate(RecordD); 7830 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7831 PushDeclContext(S, Record); 7832 } 7833 7834 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7835 if (!RecordD) return; 7836 PopDeclContext(); 7837 } 7838 7839 /// This is used to implement the constant expression evaluation part of the 7840 /// attribute enable_if extension. There is nothing in standard C++ which would 7841 /// require reentering parameters. 7842 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7843 if (!Param) 7844 return; 7845 7846 S->AddDecl(Param); 7847 if (Param->getDeclName()) 7848 IdResolver.AddDecl(Param); 7849 } 7850 7851 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7852 /// parsing a top-level (non-nested) C++ class, and we are now 7853 /// parsing those parts of the given Method declaration that could 7854 /// not be parsed earlier (C++ [class.mem]p2), such as default 7855 /// arguments. This action should enter the scope of the given 7856 /// Method declaration as if we had just parsed the qualified method 7857 /// name. However, it should not bring the parameters into scope; 7858 /// that will be performed by ActOnDelayedCXXMethodParameter. 7859 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7860 } 7861 7862 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7863 /// C++ method declaration. We're (re-)introducing the given 7864 /// function parameter into scope for use in parsing later parts of 7865 /// the method declaration. For example, we could see an 7866 /// ActOnParamDefaultArgument event for this parameter. 7867 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7868 if (!ParamD) 7869 return; 7870 7871 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7872 7873 // If this parameter has an unparsed default argument, clear it out 7874 // to make way for the parsed default argument. 7875 if (Param->hasUnparsedDefaultArg()) 7876 Param->setDefaultArg(nullptr); 7877 7878 S->AddDecl(Param); 7879 if (Param->getDeclName()) 7880 IdResolver.AddDecl(Param); 7881 } 7882 7883 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7884 /// processing the delayed method declaration for Method. The method 7885 /// declaration is now considered finished. There may be a separate 7886 /// ActOnStartOfFunctionDef action later (not necessarily 7887 /// immediately!) for this method, if it was also defined inside the 7888 /// class body. 7889 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7890 if (!MethodD) 7891 return; 7892 7893 AdjustDeclIfTemplate(MethodD); 7894 7895 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7896 7897 // Now that we have our default arguments, check the constructor 7898 // again. It could produce additional diagnostics or affect whether 7899 // the class has implicitly-declared destructors, among other 7900 // things. 7901 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7902 CheckConstructor(Constructor); 7903 7904 // Check the default arguments, which we may have added. 7905 if (!Method->isInvalidDecl()) 7906 CheckCXXDefaultArguments(Method); 7907 } 7908 7909 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7910 /// the well-formedness of the constructor declarator @p D with type @p 7911 /// R. If there are any errors in the declarator, this routine will 7912 /// emit diagnostics and set the invalid bit to true. In any case, the type 7913 /// will be updated to reflect a well-formed type for the constructor and 7914 /// returned. 7915 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7916 StorageClass &SC) { 7917 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7918 7919 // C++ [class.ctor]p3: 7920 // A constructor shall not be virtual (10.3) or static (9.4). A 7921 // constructor can be invoked for a const, volatile or const 7922 // volatile object. A constructor shall not be declared const, 7923 // volatile, or const volatile (9.3.2). 7924 if (isVirtual) { 7925 if (!D.isInvalidType()) 7926 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7927 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7928 << SourceRange(D.getIdentifierLoc()); 7929 D.setInvalidType(); 7930 } 7931 if (SC == SC_Static) { 7932 if (!D.isInvalidType()) 7933 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7934 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7935 << SourceRange(D.getIdentifierLoc()); 7936 D.setInvalidType(); 7937 SC = SC_None; 7938 } 7939 7940 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7941 diagnoseIgnoredQualifiers( 7942 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7943 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7944 D.getDeclSpec().getRestrictSpecLoc(), 7945 D.getDeclSpec().getAtomicSpecLoc()); 7946 D.setInvalidType(); 7947 } 7948 7949 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7950 if (FTI.TypeQuals != 0) { 7951 if (FTI.TypeQuals & Qualifiers::Const) 7952 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7953 << "const" << SourceRange(D.getIdentifierLoc()); 7954 if (FTI.TypeQuals & Qualifiers::Volatile) 7955 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7956 << "volatile" << SourceRange(D.getIdentifierLoc()); 7957 if (FTI.TypeQuals & Qualifiers::Restrict) 7958 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7959 << "restrict" << SourceRange(D.getIdentifierLoc()); 7960 D.setInvalidType(); 7961 } 7962 7963 // C++0x [class.ctor]p4: 7964 // A constructor shall not be declared with a ref-qualifier. 7965 if (FTI.hasRefQualifier()) { 7966 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7967 << FTI.RefQualifierIsLValueRef 7968 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7969 D.setInvalidType(); 7970 } 7971 7972 // Rebuild the function type "R" without any type qualifiers (in 7973 // case any of the errors above fired) and with "void" as the 7974 // return type, since constructors don't have return types. 7975 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7976 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7977 return R; 7978 7979 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7980 EPI.TypeQuals = 0; 7981 EPI.RefQualifier = RQ_None; 7982 7983 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7984 } 7985 7986 /// CheckConstructor - Checks a fully-formed constructor for 7987 /// well-formedness, issuing any diagnostics required. Returns true if 7988 /// the constructor declarator is invalid. 7989 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7990 CXXRecordDecl *ClassDecl 7991 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7992 if (!ClassDecl) 7993 return Constructor->setInvalidDecl(); 7994 7995 // C++ [class.copy]p3: 7996 // A declaration of a constructor for a class X is ill-formed if 7997 // its first parameter is of type (optionally cv-qualified) X and 7998 // either there are no other parameters or else all other 7999 // parameters have default arguments. 8000 if (!Constructor->isInvalidDecl() && 8001 ((Constructor->getNumParams() == 1) || 8002 (Constructor->getNumParams() > 1 && 8003 Constructor->getParamDecl(1)->hasDefaultArg())) && 8004 Constructor->getTemplateSpecializationKind() 8005 != TSK_ImplicitInstantiation) { 8006 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8007 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8008 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8009 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8010 const char *ConstRef 8011 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8012 : " const &"; 8013 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8014 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8015 8016 // FIXME: Rather that making the constructor invalid, we should endeavor 8017 // to fix the type. 8018 Constructor->setInvalidDecl(); 8019 } 8020 } 8021 } 8022 8023 /// CheckDestructor - Checks a fully-formed destructor definition for 8024 /// well-formedness, issuing any diagnostics required. Returns true 8025 /// on error. 8026 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8027 CXXRecordDecl *RD = Destructor->getParent(); 8028 8029 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8030 SourceLocation Loc; 8031 8032 if (!Destructor->isImplicit()) 8033 Loc = Destructor->getLocation(); 8034 else 8035 Loc = RD->getLocation(); 8036 8037 // If we have a virtual destructor, look up the deallocation function 8038 if (FunctionDecl *OperatorDelete = 8039 FindDeallocationFunctionForDestructor(Loc, RD)) { 8040 Expr *ThisArg = nullptr; 8041 8042 // If the notional 'delete this' expression requires a non-trivial 8043 // conversion from 'this' to the type of a destroying operator delete's 8044 // first parameter, perform that conversion now. 8045 if (OperatorDelete->isDestroyingOperatorDelete()) { 8046 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8047 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8048 // C++ [class.dtor]p13: 8049 // ... as if for the expression 'delete this' appearing in a 8050 // non-virtual destructor of the destructor's class. 8051 ContextRAII SwitchContext(*this, Destructor); 8052 ExprResult This = 8053 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8054 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8055 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8056 if (This.isInvalid()) { 8057 // FIXME: Register this as a context note so that it comes out 8058 // in the right order. 8059 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8060 return true; 8061 } 8062 ThisArg = This.get(); 8063 } 8064 } 8065 8066 MarkFunctionReferenced(Loc, OperatorDelete); 8067 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8068 } 8069 } 8070 8071 return false; 8072 } 8073 8074 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8075 /// the well-formednes of the destructor declarator @p D with type @p 8076 /// R. If there are any errors in the declarator, this routine will 8077 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8078 /// will be updated to reflect a well-formed type for the destructor and 8079 /// returned. 8080 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8081 StorageClass& SC) { 8082 // C++ [class.dtor]p1: 8083 // [...] A typedef-name that names a class is a class-name 8084 // (7.1.3); however, a typedef-name that names a class shall not 8085 // be used as the identifier in the declarator for a destructor 8086 // declaration. 8087 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8088 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8089 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8090 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8091 else if (const TemplateSpecializationType *TST = 8092 DeclaratorType->getAs<TemplateSpecializationType>()) 8093 if (TST->isTypeAlias()) 8094 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8095 << DeclaratorType << 1; 8096 8097 // C++ [class.dtor]p2: 8098 // A destructor is used to destroy objects of its class type. A 8099 // destructor takes no parameters, and no return type can be 8100 // specified for it (not even void). The address of a destructor 8101 // shall not be taken. A destructor shall not be static. A 8102 // destructor can be invoked for a const, volatile or const 8103 // volatile object. A destructor shall not be declared const, 8104 // volatile or const volatile (9.3.2). 8105 if (SC == SC_Static) { 8106 if (!D.isInvalidType()) 8107 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8108 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8109 << SourceRange(D.getIdentifierLoc()) 8110 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8111 8112 SC = SC_None; 8113 } 8114 if (!D.isInvalidType()) { 8115 // Destructors don't have return types, but the parser will 8116 // happily parse something like: 8117 // 8118 // class X { 8119 // float ~X(); 8120 // }; 8121 // 8122 // The return type will be eliminated later. 8123 if (D.getDeclSpec().hasTypeSpecifier()) 8124 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8125 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8126 << SourceRange(D.getIdentifierLoc()); 8127 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8128 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8129 SourceLocation(), 8130 D.getDeclSpec().getConstSpecLoc(), 8131 D.getDeclSpec().getVolatileSpecLoc(), 8132 D.getDeclSpec().getRestrictSpecLoc(), 8133 D.getDeclSpec().getAtomicSpecLoc()); 8134 D.setInvalidType(); 8135 } 8136 } 8137 8138 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8139 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 8140 if (FTI.TypeQuals & Qualifiers::Const) 8141 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8142 << "const" << SourceRange(D.getIdentifierLoc()); 8143 if (FTI.TypeQuals & Qualifiers::Volatile) 8144 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8145 << "volatile" << SourceRange(D.getIdentifierLoc()); 8146 if (FTI.TypeQuals & Qualifiers::Restrict) 8147 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8148 << "restrict" << SourceRange(D.getIdentifierLoc()); 8149 D.setInvalidType(); 8150 } 8151 8152 // C++0x [class.dtor]p2: 8153 // A destructor shall not be declared with a ref-qualifier. 8154 if (FTI.hasRefQualifier()) { 8155 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8156 << FTI.RefQualifierIsLValueRef 8157 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8158 D.setInvalidType(); 8159 } 8160 8161 // Make sure we don't have any parameters. 8162 if (FTIHasNonVoidParameters(FTI)) { 8163 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8164 8165 // Delete the parameters. 8166 FTI.freeParams(); 8167 D.setInvalidType(); 8168 } 8169 8170 // Make sure the destructor isn't variadic. 8171 if (FTI.isVariadic) { 8172 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8173 D.setInvalidType(); 8174 } 8175 8176 // Rebuild the function type "R" without any type qualifiers or 8177 // parameters (in case any of the errors above fired) and with 8178 // "void" as the return type, since destructors don't have return 8179 // types. 8180 if (!D.isInvalidType()) 8181 return R; 8182 8183 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8184 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8185 EPI.Variadic = false; 8186 EPI.TypeQuals = 0; 8187 EPI.RefQualifier = RQ_None; 8188 return Context.getFunctionType(Context.VoidTy, None, EPI); 8189 } 8190 8191 static void extendLeft(SourceRange &R, SourceRange Before) { 8192 if (Before.isInvalid()) 8193 return; 8194 R.setBegin(Before.getBegin()); 8195 if (R.getEnd().isInvalid()) 8196 R.setEnd(Before.getEnd()); 8197 } 8198 8199 static void extendRight(SourceRange &R, SourceRange After) { 8200 if (After.isInvalid()) 8201 return; 8202 if (R.getBegin().isInvalid()) 8203 R.setBegin(After.getBegin()); 8204 R.setEnd(After.getEnd()); 8205 } 8206 8207 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8208 /// well-formednes of the conversion function declarator @p D with 8209 /// type @p R. If there are any errors in the declarator, this routine 8210 /// will emit diagnostics and return true. Otherwise, it will return 8211 /// false. Either way, the type @p R will be updated to reflect a 8212 /// well-formed type for the conversion operator. 8213 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8214 StorageClass& SC) { 8215 // C++ [class.conv.fct]p1: 8216 // Neither parameter types nor return type can be specified. The 8217 // type of a conversion function (8.3.5) is "function taking no 8218 // parameter returning conversion-type-id." 8219 if (SC == SC_Static) { 8220 if (!D.isInvalidType()) 8221 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8222 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8223 << D.getName().getSourceRange(); 8224 D.setInvalidType(); 8225 SC = SC_None; 8226 } 8227 8228 TypeSourceInfo *ConvTSI = nullptr; 8229 QualType ConvType = 8230 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8231 8232 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 8233 // Conversion functions don't have return types, but the parser will 8234 // happily parse something like: 8235 // 8236 // class X { 8237 // float operator bool(); 8238 // }; 8239 // 8240 // The return type will be changed later anyway. 8241 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8242 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8243 << SourceRange(D.getIdentifierLoc()); 8244 D.setInvalidType(); 8245 } 8246 8247 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8248 8249 // Make sure we don't have any parameters. 8250 if (Proto->getNumParams() > 0) { 8251 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8252 8253 // Delete the parameters. 8254 D.getFunctionTypeInfo().freeParams(); 8255 D.setInvalidType(); 8256 } else if (Proto->isVariadic()) { 8257 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8258 D.setInvalidType(); 8259 } 8260 8261 // Diagnose "&operator bool()" and other such nonsense. This 8262 // is actually a gcc extension which we don't support. 8263 if (Proto->getReturnType() != ConvType) { 8264 bool NeedsTypedef = false; 8265 SourceRange Before, After; 8266 8267 // Walk the chunks and extract information on them for our diagnostic. 8268 bool PastFunctionChunk = false; 8269 for (auto &Chunk : D.type_objects()) { 8270 switch (Chunk.Kind) { 8271 case DeclaratorChunk::Function: 8272 if (!PastFunctionChunk) { 8273 if (Chunk.Fun.HasTrailingReturnType) { 8274 TypeSourceInfo *TRT = nullptr; 8275 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8276 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8277 } 8278 PastFunctionChunk = true; 8279 break; 8280 } 8281 LLVM_FALLTHROUGH; 8282 case DeclaratorChunk::Array: 8283 NeedsTypedef = true; 8284 extendRight(After, Chunk.getSourceRange()); 8285 break; 8286 8287 case DeclaratorChunk::Pointer: 8288 case DeclaratorChunk::BlockPointer: 8289 case DeclaratorChunk::Reference: 8290 case DeclaratorChunk::MemberPointer: 8291 case DeclaratorChunk::Pipe: 8292 extendLeft(Before, Chunk.getSourceRange()); 8293 break; 8294 8295 case DeclaratorChunk::Paren: 8296 extendLeft(Before, Chunk.Loc); 8297 extendRight(After, Chunk.EndLoc); 8298 break; 8299 } 8300 } 8301 8302 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8303 After.isValid() ? After.getBegin() : 8304 D.getIdentifierLoc(); 8305 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8306 DB << Before << After; 8307 8308 if (!NeedsTypedef) { 8309 DB << /*don't need a typedef*/0; 8310 8311 // If we can provide a correct fix-it hint, do so. 8312 if (After.isInvalid() && ConvTSI) { 8313 SourceLocation InsertLoc = 8314 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8315 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8316 << FixItHint::CreateInsertionFromRange( 8317 InsertLoc, CharSourceRange::getTokenRange(Before)) 8318 << FixItHint::CreateRemoval(Before); 8319 } 8320 } else if (!Proto->getReturnType()->isDependentType()) { 8321 DB << /*typedef*/1 << Proto->getReturnType(); 8322 } else if (getLangOpts().CPlusPlus11) { 8323 DB << /*alias template*/2 << Proto->getReturnType(); 8324 } else { 8325 DB << /*might not be fixable*/3; 8326 } 8327 8328 // Recover by incorporating the other type chunks into the result type. 8329 // Note, this does *not* change the name of the function. This is compatible 8330 // with the GCC extension: 8331 // struct S { &operator int(); } s; 8332 // int &r = s.operator int(); // ok in GCC 8333 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8334 ConvType = Proto->getReturnType(); 8335 } 8336 8337 // C++ [class.conv.fct]p4: 8338 // The conversion-type-id shall not represent a function type nor 8339 // an array type. 8340 if (ConvType->isArrayType()) { 8341 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8342 ConvType = Context.getPointerType(ConvType); 8343 D.setInvalidType(); 8344 } else if (ConvType->isFunctionType()) { 8345 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8346 ConvType = Context.getPointerType(ConvType); 8347 D.setInvalidType(); 8348 } 8349 8350 // Rebuild the function type "R" without any parameters (in case any 8351 // of the errors above fired) and with the conversion type as the 8352 // return type. 8353 if (D.isInvalidType()) 8354 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8355 8356 // C++0x explicit conversion operators. 8357 if (D.getDeclSpec().isExplicitSpecified()) 8358 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8359 getLangOpts().CPlusPlus11 ? 8360 diag::warn_cxx98_compat_explicit_conversion_functions : 8361 diag::ext_explicit_conversion_functions) 8362 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 8363 } 8364 8365 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8366 /// the declaration of the given C++ conversion function. This routine 8367 /// is responsible for recording the conversion function in the C++ 8368 /// class, if possible. 8369 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8370 assert(Conversion && "Expected to receive a conversion function declaration"); 8371 8372 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8373 8374 // Make sure we aren't redeclaring the conversion function. 8375 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8376 8377 // C++ [class.conv.fct]p1: 8378 // [...] A conversion function is never used to convert a 8379 // (possibly cv-qualified) object to the (possibly cv-qualified) 8380 // same object type (or a reference to it), to a (possibly 8381 // cv-qualified) base class of that type (or a reference to it), 8382 // or to (possibly cv-qualified) void. 8383 // FIXME: Suppress this warning if the conversion function ends up being a 8384 // virtual function that overrides a virtual function in a base class. 8385 QualType ClassType 8386 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8387 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8388 ConvType = ConvTypeRef->getPointeeType(); 8389 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8390 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8391 /* Suppress diagnostics for instantiations. */; 8392 else if (ConvType->isRecordType()) { 8393 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8394 if (ConvType == ClassType) 8395 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8396 << ClassType; 8397 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8398 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8399 << ClassType << ConvType; 8400 } else if (ConvType->isVoidType()) { 8401 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8402 << ClassType << ConvType; 8403 } 8404 8405 if (FunctionTemplateDecl *ConversionTemplate 8406 = Conversion->getDescribedFunctionTemplate()) 8407 return ConversionTemplate; 8408 8409 return Conversion; 8410 } 8411 8412 namespace { 8413 /// Utility class to accumulate and print a diagnostic listing the invalid 8414 /// specifier(s) on a declaration. 8415 struct BadSpecifierDiagnoser { 8416 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8417 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8418 ~BadSpecifierDiagnoser() { 8419 Diagnostic << Specifiers; 8420 } 8421 8422 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8423 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8424 } 8425 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8426 return check(SpecLoc, 8427 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8428 } 8429 void check(SourceLocation SpecLoc, const char *Spec) { 8430 if (SpecLoc.isInvalid()) return; 8431 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8432 if (!Specifiers.empty()) Specifiers += " "; 8433 Specifiers += Spec; 8434 } 8435 8436 Sema &S; 8437 Sema::SemaDiagnosticBuilder Diagnostic; 8438 std::string Specifiers; 8439 }; 8440 } 8441 8442 /// Check the validity of a declarator that we parsed for a deduction-guide. 8443 /// These aren't actually declarators in the grammar, so we need to check that 8444 /// the user didn't specify any pieces that are not part of the deduction-guide 8445 /// grammar. 8446 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8447 StorageClass &SC) { 8448 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8449 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8450 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8451 8452 // C++ [temp.deduct.guide]p3: 8453 // A deduction-gide shall be declared in the same scope as the 8454 // corresponding class template. 8455 if (!CurContext->getRedeclContext()->Equals( 8456 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8457 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8458 << GuidedTemplateDecl; 8459 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8460 } 8461 8462 auto &DS = D.getMutableDeclSpec(); 8463 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8464 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8465 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8466 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8467 BadSpecifierDiagnoser Diagnoser( 8468 *this, D.getIdentifierLoc(), 8469 diag::err_deduction_guide_invalid_specifier); 8470 8471 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8472 DS.ClearStorageClassSpecs(); 8473 SC = SC_None; 8474 8475 // 'explicit' is permitted. 8476 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8477 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8478 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8479 DS.ClearConstexprSpec(); 8480 8481 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8482 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8483 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8484 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8485 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8486 DS.ClearTypeQualifiers(); 8487 8488 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8489 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8490 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8491 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8492 DS.ClearTypeSpecType(); 8493 } 8494 8495 if (D.isInvalidType()) 8496 return; 8497 8498 // Check the declarator is simple enough. 8499 bool FoundFunction = false; 8500 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8501 if (Chunk.Kind == DeclaratorChunk::Paren) 8502 continue; 8503 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8504 Diag(D.getDeclSpec().getLocStart(), 8505 diag::err_deduction_guide_with_complex_decl) 8506 << D.getSourceRange(); 8507 break; 8508 } 8509 if (!Chunk.Fun.hasTrailingReturnType()) { 8510 Diag(D.getName().getLocStart(), 8511 diag::err_deduction_guide_no_trailing_return_type); 8512 break; 8513 } 8514 8515 // Check that the return type is written as a specialization of 8516 // the template specified as the deduction-guide's name. 8517 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8518 TypeSourceInfo *TSI = nullptr; 8519 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8520 assert(TSI && "deduction guide has valid type but invalid return type?"); 8521 bool AcceptableReturnType = false; 8522 bool MightInstantiateToSpecialization = false; 8523 if (auto RetTST = 8524 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8525 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8526 bool TemplateMatches = 8527 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8528 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8529 AcceptableReturnType = true; 8530 else { 8531 // This could still instantiate to the right type, unless we know it 8532 // names the wrong class template. 8533 auto *TD = SpecifiedName.getAsTemplateDecl(); 8534 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8535 !TemplateMatches); 8536 } 8537 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8538 MightInstantiateToSpecialization = true; 8539 } 8540 8541 if (!AcceptableReturnType) { 8542 Diag(TSI->getTypeLoc().getLocStart(), 8543 diag::err_deduction_guide_bad_trailing_return_type) 8544 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8545 << TSI->getTypeLoc().getSourceRange(); 8546 } 8547 8548 // Keep going to check that we don't have any inner declarator pieces (we 8549 // could still have a function returning a pointer to a function). 8550 FoundFunction = true; 8551 } 8552 8553 if (D.isFunctionDefinition()) 8554 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8555 } 8556 8557 //===----------------------------------------------------------------------===// 8558 // Namespace Handling 8559 //===----------------------------------------------------------------------===// 8560 8561 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8562 /// reopened. 8563 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8564 SourceLocation Loc, 8565 IdentifierInfo *II, bool *IsInline, 8566 NamespaceDecl *PrevNS) { 8567 assert(*IsInline != PrevNS->isInline()); 8568 8569 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8570 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8571 // inline namespaces, with the intention of bringing names into namespace std. 8572 // 8573 // We support this just well enough to get that case working; this is not 8574 // sufficient to support reopening namespaces as inline in general. 8575 if (*IsInline && II && II->getName().startswith("__atomic") && 8576 S.getSourceManager().isInSystemHeader(Loc)) { 8577 // Mark all prior declarations of the namespace as inline. 8578 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8579 NS = NS->getPreviousDecl()) 8580 NS->setInline(*IsInline); 8581 // Patch up the lookup table for the containing namespace. This isn't really 8582 // correct, but it's good enough for this particular case. 8583 for (auto *I : PrevNS->decls()) 8584 if (auto *ND = dyn_cast<NamedDecl>(I)) 8585 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8586 return; 8587 } 8588 8589 if (PrevNS->isInline()) 8590 // The user probably just forgot the 'inline', so suggest that it 8591 // be added back. 8592 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8593 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8594 else 8595 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8596 8597 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8598 *IsInline = PrevNS->isInline(); 8599 } 8600 8601 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8602 /// definition. 8603 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8604 SourceLocation InlineLoc, 8605 SourceLocation NamespaceLoc, 8606 SourceLocation IdentLoc, 8607 IdentifierInfo *II, 8608 SourceLocation LBrace, 8609 AttributeList *AttrList, 8610 UsingDirectiveDecl *&UD) { 8611 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8612 // For anonymous namespace, take the location of the left brace. 8613 SourceLocation Loc = II ? IdentLoc : LBrace; 8614 bool IsInline = InlineLoc.isValid(); 8615 bool IsInvalid = false; 8616 bool IsStd = false; 8617 bool AddToKnown = false; 8618 Scope *DeclRegionScope = NamespcScope->getParent(); 8619 8620 NamespaceDecl *PrevNS = nullptr; 8621 if (II) { 8622 // C++ [namespace.def]p2: 8623 // The identifier in an original-namespace-definition shall not 8624 // have been previously defined in the declarative region in 8625 // which the original-namespace-definition appears. The 8626 // identifier in an original-namespace-definition is the name of 8627 // the namespace. Subsequently in that declarative region, it is 8628 // treated as an original-namespace-name. 8629 // 8630 // Since namespace names are unique in their scope, and we don't 8631 // look through using directives, just look for any ordinary names 8632 // as if by qualified name lookup. 8633 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8634 ForExternalRedeclaration); 8635 LookupQualifiedName(R, CurContext->getRedeclContext()); 8636 NamedDecl *PrevDecl = 8637 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8638 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8639 8640 if (PrevNS) { 8641 // This is an extended namespace definition. 8642 if (IsInline != PrevNS->isInline()) 8643 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8644 &IsInline, PrevNS); 8645 } else if (PrevDecl) { 8646 // This is an invalid name redefinition. 8647 Diag(Loc, diag::err_redefinition_different_kind) 8648 << II; 8649 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8650 IsInvalid = true; 8651 // Continue on to push Namespc as current DeclContext and return it. 8652 } else if (II->isStr("std") && 8653 CurContext->getRedeclContext()->isTranslationUnit()) { 8654 // This is the first "real" definition of the namespace "std", so update 8655 // our cache of the "std" namespace to point at this definition. 8656 PrevNS = getStdNamespace(); 8657 IsStd = true; 8658 AddToKnown = !IsInline; 8659 } else { 8660 // We've seen this namespace for the first time. 8661 AddToKnown = !IsInline; 8662 } 8663 } else { 8664 // Anonymous namespaces. 8665 8666 // Determine whether the parent already has an anonymous namespace. 8667 DeclContext *Parent = CurContext->getRedeclContext(); 8668 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8669 PrevNS = TU->getAnonymousNamespace(); 8670 } else { 8671 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8672 PrevNS = ND->getAnonymousNamespace(); 8673 } 8674 8675 if (PrevNS && IsInline != PrevNS->isInline()) 8676 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8677 &IsInline, PrevNS); 8678 } 8679 8680 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8681 StartLoc, Loc, II, PrevNS); 8682 if (IsInvalid) 8683 Namespc->setInvalidDecl(); 8684 8685 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8686 AddPragmaAttributes(DeclRegionScope, Namespc); 8687 8688 // FIXME: Should we be merging attributes? 8689 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8690 PushNamespaceVisibilityAttr(Attr, Loc); 8691 8692 if (IsStd) 8693 StdNamespace = Namespc; 8694 if (AddToKnown) 8695 KnownNamespaces[Namespc] = false; 8696 8697 if (II) { 8698 PushOnScopeChains(Namespc, DeclRegionScope); 8699 } else { 8700 // Link the anonymous namespace into its parent. 8701 DeclContext *Parent = CurContext->getRedeclContext(); 8702 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8703 TU->setAnonymousNamespace(Namespc); 8704 } else { 8705 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8706 } 8707 8708 CurContext->addDecl(Namespc); 8709 8710 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8711 // behaves as if it were replaced by 8712 // namespace unique { /* empty body */ } 8713 // using namespace unique; 8714 // namespace unique { namespace-body } 8715 // where all occurrences of 'unique' in a translation unit are 8716 // replaced by the same identifier and this identifier differs 8717 // from all other identifiers in the entire program. 8718 8719 // We just create the namespace with an empty name and then add an 8720 // implicit using declaration, just like the standard suggests. 8721 // 8722 // CodeGen enforces the "universally unique" aspect by giving all 8723 // declarations semantically contained within an anonymous 8724 // namespace internal linkage. 8725 8726 if (!PrevNS) { 8727 UD = UsingDirectiveDecl::Create(Context, Parent, 8728 /* 'using' */ LBrace, 8729 /* 'namespace' */ SourceLocation(), 8730 /* qualifier */ NestedNameSpecifierLoc(), 8731 /* identifier */ SourceLocation(), 8732 Namespc, 8733 /* Ancestor */ Parent); 8734 UD->setImplicit(); 8735 Parent->addDecl(UD); 8736 } 8737 } 8738 8739 ActOnDocumentableDecl(Namespc); 8740 8741 // Although we could have an invalid decl (i.e. the namespace name is a 8742 // redefinition), push it as current DeclContext and try to continue parsing. 8743 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8744 // for the namespace has the declarations that showed up in that particular 8745 // namespace definition. 8746 PushDeclContext(NamespcScope, Namespc); 8747 return Namespc; 8748 } 8749 8750 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8751 /// is a namespace alias, returns the namespace it points to. 8752 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8753 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8754 return AD->getNamespace(); 8755 return dyn_cast_or_null<NamespaceDecl>(D); 8756 } 8757 8758 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8759 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8760 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8761 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8762 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8763 Namespc->setRBraceLoc(RBrace); 8764 PopDeclContext(); 8765 if (Namespc->hasAttr<VisibilityAttr>()) 8766 PopPragmaVisibility(true, RBrace); 8767 } 8768 8769 CXXRecordDecl *Sema::getStdBadAlloc() const { 8770 return cast_or_null<CXXRecordDecl>( 8771 StdBadAlloc.get(Context.getExternalSource())); 8772 } 8773 8774 EnumDecl *Sema::getStdAlignValT() const { 8775 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8776 } 8777 8778 NamespaceDecl *Sema::getStdNamespace() const { 8779 return cast_or_null<NamespaceDecl>( 8780 StdNamespace.get(Context.getExternalSource())); 8781 } 8782 8783 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8784 if (!StdExperimentalNamespaceCache) { 8785 if (auto Std = getStdNamespace()) { 8786 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8787 SourceLocation(), LookupNamespaceName); 8788 if (!LookupQualifiedName(Result, Std) || 8789 !(StdExperimentalNamespaceCache = 8790 Result.getAsSingle<NamespaceDecl>())) 8791 Result.suppressDiagnostics(); 8792 } 8793 } 8794 return StdExperimentalNamespaceCache; 8795 } 8796 8797 /// \brief Retrieve the special "std" namespace, which may require us to 8798 /// implicitly define the namespace. 8799 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8800 if (!StdNamespace) { 8801 // The "std" namespace has not yet been defined, so build one implicitly. 8802 StdNamespace = NamespaceDecl::Create(Context, 8803 Context.getTranslationUnitDecl(), 8804 /*Inline=*/false, 8805 SourceLocation(), SourceLocation(), 8806 &PP.getIdentifierTable().get("std"), 8807 /*PrevDecl=*/nullptr); 8808 getStdNamespace()->setImplicit(true); 8809 } 8810 8811 return getStdNamespace(); 8812 } 8813 8814 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8815 assert(getLangOpts().CPlusPlus && 8816 "Looking for std::initializer_list outside of C++."); 8817 8818 // We're looking for implicit instantiations of 8819 // template <typename E> class std::initializer_list. 8820 8821 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8822 return false; 8823 8824 ClassTemplateDecl *Template = nullptr; 8825 const TemplateArgument *Arguments = nullptr; 8826 8827 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8828 8829 ClassTemplateSpecializationDecl *Specialization = 8830 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8831 if (!Specialization) 8832 return false; 8833 8834 Template = Specialization->getSpecializedTemplate(); 8835 Arguments = Specialization->getTemplateArgs().data(); 8836 } else if (const TemplateSpecializationType *TST = 8837 Ty->getAs<TemplateSpecializationType>()) { 8838 Template = dyn_cast_or_null<ClassTemplateDecl>( 8839 TST->getTemplateName().getAsTemplateDecl()); 8840 Arguments = TST->getArgs(); 8841 } 8842 if (!Template) 8843 return false; 8844 8845 if (!StdInitializerList) { 8846 // Haven't recognized std::initializer_list yet, maybe this is it. 8847 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8848 if (TemplateClass->getIdentifier() != 8849 &PP.getIdentifierTable().get("initializer_list") || 8850 !getStdNamespace()->InEnclosingNamespaceSetOf( 8851 TemplateClass->getDeclContext())) 8852 return false; 8853 // This is a template called std::initializer_list, but is it the right 8854 // template? 8855 TemplateParameterList *Params = Template->getTemplateParameters(); 8856 if (Params->getMinRequiredArguments() != 1) 8857 return false; 8858 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8859 return false; 8860 8861 // It's the right template. 8862 StdInitializerList = Template; 8863 } 8864 8865 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8866 return false; 8867 8868 // This is an instance of std::initializer_list. Find the argument type. 8869 if (Element) 8870 *Element = Arguments[0].getAsType(); 8871 return true; 8872 } 8873 8874 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8875 NamespaceDecl *Std = S.getStdNamespace(); 8876 if (!Std) { 8877 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8878 return nullptr; 8879 } 8880 8881 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8882 Loc, Sema::LookupOrdinaryName); 8883 if (!S.LookupQualifiedName(Result, Std)) { 8884 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8885 return nullptr; 8886 } 8887 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8888 if (!Template) { 8889 Result.suppressDiagnostics(); 8890 // We found something weird. Complain about the first thing we found. 8891 NamedDecl *Found = *Result.begin(); 8892 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8893 return nullptr; 8894 } 8895 8896 // We found some template called std::initializer_list. Now verify that it's 8897 // correct. 8898 TemplateParameterList *Params = Template->getTemplateParameters(); 8899 if (Params->getMinRequiredArguments() != 1 || 8900 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8901 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8902 return nullptr; 8903 } 8904 8905 return Template; 8906 } 8907 8908 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8909 if (!StdInitializerList) { 8910 StdInitializerList = LookupStdInitializerList(*this, Loc); 8911 if (!StdInitializerList) 8912 return QualType(); 8913 } 8914 8915 TemplateArgumentListInfo Args(Loc, Loc); 8916 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8917 Context.getTrivialTypeSourceInfo(Element, 8918 Loc))); 8919 return Context.getCanonicalType( 8920 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8921 } 8922 8923 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 8924 // C++ [dcl.init.list]p2: 8925 // A constructor is an initializer-list constructor if its first parameter 8926 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8927 // std::initializer_list<E> for some type E, and either there are no other 8928 // parameters or else all other parameters have default arguments. 8929 if (Ctor->getNumParams() < 1 || 8930 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8931 return false; 8932 8933 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8934 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8935 ArgType = RT->getPointeeType().getUnqualifiedType(); 8936 8937 return isStdInitializerList(ArgType, nullptr); 8938 } 8939 8940 /// \brief Determine whether a using statement is in a context where it will be 8941 /// apply in all contexts. 8942 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8943 switch (CurContext->getDeclKind()) { 8944 case Decl::TranslationUnit: 8945 return true; 8946 case Decl::LinkageSpec: 8947 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8948 default: 8949 return false; 8950 } 8951 } 8952 8953 namespace { 8954 8955 // Callback to only accept typo corrections that are namespaces. 8956 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8957 public: 8958 bool ValidateCandidate(const TypoCorrection &candidate) override { 8959 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8960 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8961 return false; 8962 } 8963 }; 8964 8965 } 8966 8967 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8968 CXXScopeSpec &SS, 8969 SourceLocation IdentLoc, 8970 IdentifierInfo *Ident) { 8971 R.clear(); 8972 if (TypoCorrection Corrected = 8973 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8974 llvm::make_unique<NamespaceValidatorCCC>(), 8975 Sema::CTK_ErrorRecovery)) { 8976 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8977 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8978 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8979 Ident->getName().equals(CorrectedStr); 8980 S.diagnoseTypo(Corrected, 8981 S.PDiag(diag::err_using_directive_member_suggest) 8982 << Ident << DC << DroppedSpecifier << SS.getRange(), 8983 S.PDiag(diag::note_namespace_defined_here)); 8984 } else { 8985 S.diagnoseTypo(Corrected, 8986 S.PDiag(diag::err_using_directive_suggest) << Ident, 8987 S.PDiag(diag::note_namespace_defined_here)); 8988 } 8989 R.addDecl(Corrected.getFoundDecl()); 8990 return true; 8991 } 8992 return false; 8993 } 8994 8995 Decl *Sema::ActOnUsingDirective(Scope *S, 8996 SourceLocation UsingLoc, 8997 SourceLocation NamespcLoc, 8998 CXXScopeSpec &SS, 8999 SourceLocation IdentLoc, 9000 IdentifierInfo *NamespcName, 9001 AttributeList *AttrList) { 9002 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9003 assert(NamespcName && "Invalid NamespcName."); 9004 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9005 9006 // This can only happen along a recovery path. 9007 while (S->isTemplateParamScope()) 9008 S = S->getParent(); 9009 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9010 9011 UsingDirectiveDecl *UDir = nullptr; 9012 NestedNameSpecifier *Qualifier = nullptr; 9013 if (SS.isSet()) 9014 Qualifier = SS.getScopeRep(); 9015 9016 // Lookup namespace name. 9017 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9018 LookupParsedName(R, S, &SS); 9019 if (R.isAmbiguous()) 9020 return nullptr; 9021 9022 if (R.empty()) { 9023 R.clear(); 9024 // Allow "using namespace std;" or "using namespace ::std;" even if 9025 // "std" hasn't been defined yet, for GCC compatibility. 9026 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9027 NamespcName->isStr("std")) { 9028 Diag(IdentLoc, diag::ext_using_undefined_std); 9029 R.addDecl(getOrCreateStdNamespace()); 9030 R.resolveKind(); 9031 } 9032 // Otherwise, attempt typo correction. 9033 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9034 } 9035 9036 if (!R.empty()) { 9037 NamedDecl *Named = R.getRepresentativeDecl(); 9038 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9039 assert(NS && "expected namespace decl"); 9040 9041 // The use of a nested name specifier may trigger deprecation warnings. 9042 DiagnoseUseOfDecl(Named, IdentLoc); 9043 9044 // C++ [namespace.udir]p1: 9045 // A using-directive specifies that the names in the nominated 9046 // namespace can be used in the scope in which the 9047 // using-directive appears after the using-directive. During 9048 // unqualified name lookup (3.4.1), the names appear as if they 9049 // were declared in the nearest enclosing namespace which 9050 // contains both the using-directive and the nominated 9051 // namespace. [Note: in this context, "contains" means "contains 9052 // directly or indirectly". ] 9053 9054 // Find enclosing context containing both using-directive and 9055 // nominated namespace. 9056 DeclContext *CommonAncestor = NS; 9057 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9058 CommonAncestor = CommonAncestor->getParent(); 9059 9060 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9061 SS.getWithLocInContext(Context), 9062 IdentLoc, Named, CommonAncestor); 9063 9064 if (IsUsingDirectiveInToplevelContext(CurContext) && 9065 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9066 Diag(IdentLoc, diag::warn_using_directive_in_header); 9067 } 9068 9069 PushUsingDirective(S, UDir); 9070 } else { 9071 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9072 } 9073 9074 if (UDir) 9075 ProcessDeclAttributeList(S, UDir, AttrList); 9076 9077 return UDir; 9078 } 9079 9080 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9081 // If the scope has an associated entity and the using directive is at 9082 // namespace or translation unit scope, add the UsingDirectiveDecl into 9083 // its lookup structure so qualified name lookup can find it. 9084 DeclContext *Ctx = S->getEntity(); 9085 if (Ctx && !Ctx->isFunctionOrMethod()) 9086 Ctx->addDecl(UDir); 9087 else 9088 // Otherwise, it is at block scope. The using-directives will affect lookup 9089 // only to the end of the scope. 9090 S->PushUsingDirective(UDir); 9091 } 9092 9093 9094 Decl *Sema::ActOnUsingDeclaration(Scope *S, 9095 AccessSpecifier AS, 9096 SourceLocation UsingLoc, 9097 SourceLocation TypenameLoc, 9098 CXXScopeSpec &SS, 9099 UnqualifiedId &Name, 9100 SourceLocation EllipsisLoc, 9101 AttributeList *AttrList) { 9102 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9103 9104 if (SS.isEmpty()) { 9105 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 9106 return nullptr; 9107 } 9108 9109 switch (Name.getKind()) { 9110 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9111 case UnqualifiedIdKind::IK_Identifier: 9112 case UnqualifiedIdKind::IK_OperatorFunctionId: 9113 case UnqualifiedIdKind::IK_LiteralOperatorId: 9114 case UnqualifiedIdKind::IK_ConversionFunctionId: 9115 break; 9116 9117 case UnqualifiedIdKind::IK_ConstructorName: 9118 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9119 // C++11 inheriting constructors. 9120 Diag(Name.getLocStart(), 9121 getLangOpts().CPlusPlus11 ? 9122 diag::warn_cxx98_compat_using_decl_constructor : 9123 diag::err_using_decl_constructor) 9124 << SS.getRange(); 9125 9126 if (getLangOpts().CPlusPlus11) break; 9127 9128 return nullptr; 9129 9130 case UnqualifiedIdKind::IK_DestructorName: 9131 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 9132 << SS.getRange(); 9133 return nullptr; 9134 9135 case UnqualifiedIdKind::IK_TemplateId: 9136 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 9137 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9138 return nullptr; 9139 9140 case UnqualifiedIdKind::IK_DeductionGuideName: 9141 llvm_unreachable("cannot parse qualified deduction guide name"); 9142 } 9143 9144 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9145 DeclarationName TargetName = TargetNameInfo.getName(); 9146 if (!TargetName) 9147 return nullptr; 9148 9149 // Warn about access declarations. 9150 if (UsingLoc.isInvalid()) { 9151 Diag(Name.getLocStart(), 9152 getLangOpts().CPlusPlus11 ? diag::err_access_decl 9153 : diag::warn_access_decl_deprecated) 9154 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9155 } 9156 9157 if (EllipsisLoc.isInvalid()) { 9158 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9159 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9160 return nullptr; 9161 } else { 9162 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9163 !TargetNameInfo.containsUnexpandedParameterPack()) { 9164 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9165 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9166 EllipsisLoc = SourceLocation(); 9167 } 9168 } 9169 9170 NamedDecl *UD = 9171 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9172 SS, TargetNameInfo, EllipsisLoc, AttrList, 9173 /*IsInstantiation*/false); 9174 if (UD) 9175 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9176 9177 return UD; 9178 } 9179 9180 /// \brief Determine whether a using declaration considers the given 9181 /// declarations as "equivalent", e.g., if they are redeclarations of 9182 /// the same entity or are both typedefs of the same type. 9183 static bool 9184 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9185 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9186 return true; 9187 9188 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9189 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9190 return Context.hasSameType(TD1->getUnderlyingType(), 9191 TD2->getUnderlyingType()); 9192 9193 return false; 9194 } 9195 9196 9197 /// Determines whether to create a using shadow decl for a particular 9198 /// decl, given the set of decls existing prior to this using lookup. 9199 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9200 const LookupResult &Previous, 9201 UsingShadowDecl *&PrevShadow) { 9202 // Diagnose finding a decl which is not from a base class of the 9203 // current class. We do this now because there are cases where this 9204 // function will silently decide not to build a shadow decl, which 9205 // will pre-empt further diagnostics. 9206 // 9207 // We don't need to do this in C++11 because we do the check once on 9208 // the qualifier. 9209 // 9210 // FIXME: diagnose the following if we care enough: 9211 // struct A { int foo; }; 9212 // struct B : A { using A::foo; }; 9213 // template <class T> struct C : A {}; 9214 // template <class T> struct D : C<T> { using B::foo; } // <--- 9215 // This is invalid (during instantiation) in C++03 because B::foo 9216 // resolves to the using decl in B, which is not a base class of D<T>. 9217 // We can't diagnose it immediately because C<T> is an unknown 9218 // specialization. The UsingShadowDecl in D<T> then points directly 9219 // to A::foo, which will look well-formed when we instantiate. 9220 // The right solution is to not collapse the shadow-decl chain. 9221 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9222 DeclContext *OrigDC = Orig->getDeclContext(); 9223 9224 // Handle enums and anonymous structs. 9225 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9226 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9227 while (OrigRec->isAnonymousStructOrUnion()) 9228 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9229 9230 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9231 if (OrigDC == CurContext) { 9232 Diag(Using->getLocation(), 9233 diag::err_using_decl_nested_name_specifier_is_current_class) 9234 << Using->getQualifierLoc().getSourceRange(); 9235 Diag(Orig->getLocation(), diag::note_using_decl_target); 9236 Using->setInvalidDecl(); 9237 return true; 9238 } 9239 9240 Diag(Using->getQualifierLoc().getBeginLoc(), 9241 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9242 << Using->getQualifier() 9243 << cast<CXXRecordDecl>(CurContext) 9244 << Using->getQualifierLoc().getSourceRange(); 9245 Diag(Orig->getLocation(), diag::note_using_decl_target); 9246 Using->setInvalidDecl(); 9247 return true; 9248 } 9249 } 9250 9251 if (Previous.empty()) return false; 9252 9253 NamedDecl *Target = Orig; 9254 if (isa<UsingShadowDecl>(Target)) 9255 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9256 9257 // If the target happens to be one of the previous declarations, we 9258 // don't have a conflict. 9259 // 9260 // FIXME: but we might be increasing its access, in which case we 9261 // should redeclare it. 9262 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9263 bool FoundEquivalentDecl = false; 9264 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9265 I != E; ++I) { 9266 NamedDecl *D = (*I)->getUnderlyingDecl(); 9267 // We can have UsingDecls in our Previous results because we use the same 9268 // LookupResult for checking whether the UsingDecl itself is a valid 9269 // redeclaration. 9270 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9271 continue; 9272 9273 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9274 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9275 PrevShadow = Shadow; 9276 FoundEquivalentDecl = true; 9277 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9278 // We don't conflict with an existing using shadow decl of an equivalent 9279 // declaration, but we're not a redeclaration of it. 9280 FoundEquivalentDecl = true; 9281 } 9282 9283 if (isVisible(D)) 9284 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9285 } 9286 9287 if (FoundEquivalentDecl) 9288 return false; 9289 9290 if (FunctionDecl *FD = Target->getAsFunction()) { 9291 NamedDecl *OldDecl = nullptr; 9292 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9293 /*IsForUsingDecl*/ true)) { 9294 case Ovl_Overload: 9295 return false; 9296 9297 case Ovl_NonFunction: 9298 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9299 break; 9300 9301 // We found a decl with the exact signature. 9302 case Ovl_Match: 9303 // If we're in a record, we want to hide the target, so we 9304 // return true (without a diagnostic) to tell the caller not to 9305 // build a shadow decl. 9306 if (CurContext->isRecord()) 9307 return true; 9308 9309 // If we're not in a record, this is an error. 9310 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9311 break; 9312 } 9313 9314 Diag(Target->getLocation(), diag::note_using_decl_target); 9315 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9316 Using->setInvalidDecl(); 9317 return true; 9318 } 9319 9320 // Target is not a function. 9321 9322 if (isa<TagDecl>(Target)) { 9323 // No conflict between a tag and a non-tag. 9324 if (!Tag) return false; 9325 9326 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9327 Diag(Target->getLocation(), diag::note_using_decl_target); 9328 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9329 Using->setInvalidDecl(); 9330 return true; 9331 } 9332 9333 // No conflict between a tag and a non-tag. 9334 if (!NonTag) return false; 9335 9336 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9337 Diag(Target->getLocation(), diag::note_using_decl_target); 9338 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9339 Using->setInvalidDecl(); 9340 return true; 9341 } 9342 9343 /// Determine whether a direct base class is a virtual base class. 9344 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9345 if (!Derived->getNumVBases()) 9346 return false; 9347 for (auto &B : Derived->bases()) 9348 if (B.getType()->getAsCXXRecordDecl() == Base) 9349 return B.isVirtual(); 9350 llvm_unreachable("not a direct base class"); 9351 } 9352 9353 /// Builds a shadow declaration corresponding to a 'using' declaration. 9354 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9355 UsingDecl *UD, 9356 NamedDecl *Orig, 9357 UsingShadowDecl *PrevDecl) { 9358 // If we resolved to another shadow declaration, just coalesce them. 9359 NamedDecl *Target = Orig; 9360 if (isa<UsingShadowDecl>(Target)) { 9361 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9362 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9363 } 9364 9365 NamedDecl *NonTemplateTarget = Target; 9366 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9367 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9368 9369 UsingShadowDecl *Shadow; 9370 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9371 bool IsVirtualBase = 9372 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9373 UD->getQualifier()->getAsRecordDecl()); 9374 Shadow = ConstructorUsingShadowDecl::Create( 9375 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9376 } else { 9377 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9378 Target); 9379 } 9380 UD->addShadowDecl(Shadow); 9381 9382 Shadow->setAccess(UD->getAccess()); 9383 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9384 Shadow->setInvalidDecl(); 9385 9386 Shadow->setPreviousDecl(PrevDecl); 9387 9388 if (S) 9389 PushOnScopeChains(Shadow, S); 9390 else 9391 CurContext->addDecl(Shadow); 9392 9393 9394 return Shadow; 9395 } 9396 9397 /// Hides a using shadow declaration. This is required by the current 9398 /// using-decl implementation when a resolvable using declaration in a 9399 /// class is followed by a declaration which would hide or override 9400 /// one or more of the using decl's targets; for example: 9401 /// 9402 /// struct Base { void foo(int); }; 9403 /// struct Derived : Base { 9404 /// using Base::foo; 9405 /// void foo(int); 9406 /// }; 9407 /// 9408 /// The governing language is C++03 [namespace.udecl]p12: 9409 /// 9410 /// When a using-declaration brings names from a base class into a 9411 /// derived class scope, member functions in the derived class 9412 /// override and/or hide member functions with the same name and 9413 /// parameter types in a base class (rather than conflicting). 9414 /// 9415 /// There are two ways to implement this: 9416 /// (1) optimistically create shadow decls when they're not hidden 9417 /// by existing declarations, or 9418 /// (2) don't create any shadow decls (or at least don't make them 9419 /// visible) until we've fully parsed/instantiated the class. 9420 /// The problem with (1) is that we might have to retroactively remove 9421 /// a shadow decl, which requires several O(n) operations because the 9422 /// decl structures are (very reasonably) not designed for removal. 9423 /// (2) avoids this but is very fiddly and phase-dependent. 9424 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9425 if (Shadow->getDeclName().getNameKind() == 9426 DeclarationName::CXXConversionFunctionName) 9427 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9428 9429 // Remove it from the DeclContext... 9430 Shadow->getDeclContext()->removeDecl(Shadow); 9431 9432 // ...and the scope, if applicable... 9433 if (S) { 9434 S->RemoveDecl(Shadow); 9435 IdResolver.RemoveDecl(Shadow); 9436 } 9437 9438 // ...and the using decl. 9439 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9440 9441 // TODO: complain somehow if Shadow was used. It shouldn't 9442 // be possible for this to happen, because...? 9443 } 9444 9445 /// Find the base specifier for a base class with the given type. 9446 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9447 QualType DesiredBase, 9448 bool &AnyDependentBases) { 9449 // Check whether the named type is a direct base class. 9450 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9451 for (auto &Base : Derived->bases()) { 9452 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9453 if (CanonicalDesiredBase == BaseType) 9454 return &Base; 9455 if (BaseType->isDependentType()) 9456 AnyDependentBases = true; 9457 } 9458 return nullptr; 9459 } 9460 9461 namespace { 9462 class UsingValidatorCCC : public CorrectionCandidateCallback { 9463 public: 9464 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9465 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9466 : HasTypenameKeyword(HasTypenameKeyword), 9467 IsInstantiation(IsInstantiation), OldNNS(NNS), 9468 RequireMemberOf(RequireMemberOf) {} 9469 9470 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9471 NamedDecl *ND = Candidate.getCorrectionDecl(); 9472 9473 // Keywords are not valid here. 9474 if (!ND || isa<NamespaceDecl>(ND)) 9475 return false; 9476 9477 // Completely unqualified names are invalid for a 'using' declaration. 9478 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9479 return false; 9480 9481 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9482 // reject. 9483 9484 if (RequireMemberOf) { 9485 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9486 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9487 // No-one ever wants a using-declaration to name an injected-class-name 9488 // of a base class, unless they're declaring an inheriting constructor. 9489 ASTContext &Ctx = ND->getASTContext(); 9490 if (!Ctx.getLangOpts().CPlusPlus11) 9491 return false; 9492 QualType FoundType = Ctx.getRecordType(FoundRecord); 9493 9494 // Check that the injected-class-name is named as a member of its own 9495 // type; we don't want to suggest 'using Derived::Base;', since that 9496 // means something else. 9497 NestedNameSpecifier *Specifier = 9498 Candidate.WillReplaceSpecifier() 9499 ? Candidate.getCorrectionSpecifier() 9500 : OldNNS; 9501 if (!Specifier->getAsType() || 9502 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9503 return false; 9504 9505 // Check that this inheriting constructor declaration actually names a 9506 // direct base class of the current class. 9507 bool AnyDependentBases = false; 9508 if (!findDirectBaseWithType(RequireMemberOf, 9509 Ctx.getRecordType(FoundRecord), 9510 AnyDependentBases) && 9511 !AnyDependentBases) 9512 return false; 9513 } else { 9514 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9515 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9516 return false; 9517 9518 // FIXME: Check that the base class member is accessible? 9519 } 9520 } else { 9521 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9522 if (FoundRecord && FoundRecord->isInjectedClassName()) 9523 return false; 9524 } 9525 9526 if (isa<TypeDecl>(ND)) 9527 return HasTypenameKeyword || !IsInstantiation; 9528 9529 return !HasTypenameKeyword; 9530 } 9531 9532 private: 9533 bool HasTypenameKeyword; 9534 bool IsInstantiation; 9535 NestedNameSpecifier *OldNNS; 9536 CXXRecordDecl *RequireMemberOf; 9537 }; 9538 } // end anonymous namespace 9539 9540 /// Builds a using declaration. 9541 /// 9542 /// \param IsInstantiation - Whether this call arises from an 9543 /// instantiation of an unresolved using declaration. We treat 9544 /// the lookup differently for these declarations. 9545 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9546 SourceLocation UsingLoc, 9547 bool HasTypenameKeyword, 9548 SourceLocation TypenameLoc, 9549 CXXScopeSpec &SS, 9550 DeclarationNameInfo NameInfo, 9551 SourceLocation EllipsisLoc, 9552 AttributeList *AttrList, 9553 bool IsInstantiation) { 9554 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9555 SourceLocation IdentLoc = NameInfo.getLoc(); 9556 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9557 9558 // FIXME: We ignore attributes for now. 9559 9560 // For an inheriting constructor declaration, the name of the using 9561 // declaration is the name of a constructor in this class, not in the 9562 // base class. 9563 DeclarationNameInfo UsingName = NameInfo; 9564 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9565 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9566 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9567 Context.getCanonicalType(Context.getRecordType(RD)))); 9568 9569 // Do the redeclaration lookup in the current scope. 9570 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9571 ForVisibleRedeclaration); 9572 Previous.setHideTags(false); 9573 if (S) { 9574 LookupName(Previous, S); 9575 9576 // It is really dumb that we have to do this. 9577 LookupResult::Filter F = Previous.makeFilter(); 9578 while (F.hasNext()) { 9579 NamedDecl *D = F.next(); 9580 if (!isDeclInScope(D, CurContext, S)) 9581 F.erase(); 9582 // If we found a local extern declaration that's not ordinarily visible, 9583 // and this declaration is being added to a non-block scope, ignore it. 9584 // We're only checking for scope conflicts here, not also for violations 9585 // of the linkage rules. 9586 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9587 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9588 F.erase(); 9589 } 9590 F.done(); 9591 } else { 9592 assert(IsInstantiation && "no scope in non-instantiation"); 9593 if (CurContext->isRecord()) 9594 LookupQualifiedName(Previous, CurContext); 9595 else { 9596 // No redeclaration check is needed here; in non-member contexts we 9597 // diagnosed all possible conflicts with other using-declarations when 9598 // building the template: 9599 // 9600 // For a dependent non-type using declaration, the only valid case is 9601 // if we instantiate to a single enumerator. We check for conflicts 9602 // between shadow declarations we introduce, and we check in the template 9603 // definition for conflicts between a non-type using declaration and any 9604 // other declaration, which together covers all cases. 9605 // 9606 // A dependent typename using declaration will never successfully 9607 // instantiate, since it will always name a class member, so we reject 9608 // that in the template definition. 9609 } 9610 } 9611 9612 // Check for invalid redeclarations. 9613 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9614 SS, IdentLoc, Previous)) 9615 return nullptr; 9616 9617 // Check for bad qualifiers. 9618 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9619 IdentLoc)) 9620 return nullptr; 9621 9622 DeclContext *LookupContext = computeDeclContext(SS); 9623 NamedDecl *D; 9624 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9625 if (!LookupContext || EllipsisLoc.isValid()) { 9626 if (HasTypenameKeyword) { 9627 // FIXME: not all declaration name kinds are legal here 9628 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9629 UsingLoc, TypenameLoc, 9630 QualifierLoc, 9631 IdentLoc, NameInfo.getName(), 9632 EllipsisLoc); 9633 } else { 9634 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9635 QualifierLoc, NameInfo, EllipsisLoc); 9636 } 9637 D->setAccess(AS); 9638 CurContext->addDecl(D); 9639 return D; 9640 } 9641 9642 auto Build = [&](bool Invalid) { 9643 UsingDecl *UD = 9644 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9645 UsingName, HasTypenameKeyword); 9646 UD->setAccess(AS); 9647 CurContext->addDecl(UD); 9648 UD->setInvalidDecl(Invalid); 9649 return UD; 9650 }; 9651 auto BuildInvalid = [&]{ return Build(true); }; 9652 auto BuildValid = [&]{ return Build(false); }; 9653 9654 if (RequireCompleteDeclContext(SS, LookupContext)) 9655 return BuildInvalid(); 9656 9657 // Look up the target name. 9658 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9659 9660 // Unlike most lookups, we don't always want to hide tag 9661 // declarations: tag names are visible through the using declaration 9662 // even if hidden by ordinary names, *except* in a dependent context 9663 // where it's important for the sanity of two-phase lookup. 9664 if (!IsInstantiation) 9665 R.setHideTags(false); 9666 9667 // For the purposes of this lookup, we have a base object type 9668 // equal to that of the current context. 9669 if (CurContext->isRecord()) { 9670 R.setBaseObjectType( 9671 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9672 } 9673 9674 LookupQualifiedName(R, LookupContext); 9675 9676 // Try to correct typos if possible. If constructor name lookup finds no 9677 // results, that means the named class has no explicit constructors, and we 9678 // suppressed declaring implicit ones (probably because it's dependent or 9679 // invalid). 9680 if (R.empty() && 9681 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9682 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9683 // it will believe that glibc provides a ::gets in cases where it does not, 9684 // and will try to pull it into namespace std with a using-declaration. 9685 // Just ignore the using-declaration in that case. 9686 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9687 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9688 CurContext->isStdNamespace() && 9689 isa<TranslationUnitDecl>(LookupContext) && 9690 getSourceManager().isInSystemHeader(UsingLoc)) 9691 return nullptr; 9692 if (TypoCorrection Corrected = CorrectTypo( 9693 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9694 llvm::make_unique<UsingValidatorCCC>( 9695 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9696 dyn_cast<CXXRecordDecl>(CurContext)), 9697 CTK_ErrorRecovery)) { 9698 // We reject candidates where DroppedSpecifier == true, hence the 9699 // literal '0' below. 9700 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9701 << NameInfo.getName() << LookupContext << 0 9702 << SS.getRange()); 9703 9704 // If we picked a correction with no attached Decl we can't do anything 9705 // useful with it, bail out. 9706 NamedDecl *ND = Corrected.getCorrectionDecl(); 9707 if (!ND) 9708 return BuildInvalid(); 9709 9710 // If we corrected to an inheriting constructor, handle it as one. 9711 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9712 if (RD && RD->isInjectedClassName()) { 9713 // The parent of the injected class name is the class itself. 9714 RD = cast<CXXRecordDecl>(RD->getParent()); 9715 9716 // Fix up the information we'll use to build the using declaration. 9717 if (Corrected.WillReplaceSpecifier()) { 9718 NestedNameSpecifierLocBuilder Builder; 9719 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9720 QualifierLoc.getSourceRange()); 9721 QualifierLoc = Builder.getWithLocInContext(Context); 9722 } 9723 9724 // In this case, the name we introduce is the name of a derived class 9725 // constructor. 9726 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9727 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9728 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9729 UsingName.setNamedTypeInfo(nullptr); 9730 for (auto *Ctor : LookupConstructors(RD)) 9731 R.addDecl(Ctor); 9732 R.resolveKind(); 9733 } else { 9734 // FIXME: Pick up all the declarations if we found an overloaded 9735 // function. 9736 UsingName.setName(ND->getDeclName()); 9737 R.addDecl(ND); 9738 } 9739 } else { 9740 Diag(IdentLoc, diag::err_no_member) 9741 << NameInfo.getName() << LookupContext << SS.getRange(); 9742 return BuildInvalid(); 9743 } 9744 } 9745 9746 if (R.isAmbiguous()) 9747 return BuildInvalid(); 9748 9749 if (HasTypenameKeyword) { 9750 // If we asked for a typename and got a non-type decl, error out. 9751 if (!R.getAsSingle<TypeDecl>()) { 9752 Diag(IdentLoc, diag::err_using_typename_non_type); 9753 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9754 Diag((*I)->getUnderlyingDecl()->getLocation(), 9755 diag::note_using_decl_target); 9756 return BuildInvalid(); 9757 } 9758 } else { 9759 // If we asked for a non-typename and we got a type, error out, 9760 // but only if this is an instantiation of an unresolved using 9761 // decl. Otherwise just silently find the type name. 9762 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9763 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9764 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9765 return BuildInvalid(); 9766 } 9767 } 9768 9769 // C++14 [namespace.udecl]p6: 9770 // A using-declaration shall not name a namespace. 9771 if (R.getAsSingle<NamespaceDecl>()) { 9772 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9773 << SS.getRange(); 9774 return BuildInvalid(); 9775 } 9776 9777 // C++14 [namespace.udecl]p7: 9778 // A using-declaration shall not name a scoped enumerator. 9779 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9780 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9781 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9782 << SS.getRange(); 9783 return BuildInvalid(); 9784 } 9785 } 9786 9787 UsingDecl *UD = BuildValid(); 9788 9789 // Some additional rules apply to inheriting constructors. 9790 if (UsingName.getName().getNameKind() == 9791 DeclarationName::CXXConstructorName) { 9792 // Suppress access diagnostics; the access check is instead performed at the 9793 // point of use for an inheriting constructor. 9794 R.suppressDiagnostics(); 9795 if (CheckInheritingConstructorUsingDecl(UD)) 9796 return UD; 9797 } 9798 9799 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9800 UsingShadowDecl *PrevDecl = nullptr; 9801 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9802 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9803 } 9804 9805 return UD; 9806 } 9807 9808 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 9809 ArrayRef<NamedDecl *> Expansions) { 9810 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 9811 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 9812 isa<UsingPackDecl>(InstantiatedFrom)); 9813 9814 auto *UPD = 9815 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 9816 UPD->setAccess(InstantiatedFrom->getAccess()); 9817 CurContext->addDecl(UPD); 9818 return UPD; 9819 } 9820 9821 /// Additional checks for a using declaration referring to a constructor name. 9822 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9823 assert(!UD->hasTypename() && "expecting a constructor name"); 9824 9825 const Type *SourceType = UD->getQualifier()->getAsType(); 9826 assert(SourceType && 9827 "Using decl naming constructor doesn't have type in scope spec."); 9828 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9829 9830 // Check whether the named type is a direct base class. 9831 bool AnyDependentBases = false; 9832 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9833 AnyDependentBases); 9834 if (!Base && !AnyDependentBases) { 9835 Diag(UD->getUsingLoc(), 9836 diag::err_using_decl_constructor_not_in_direct_base) 9837 << UD->getNameInfo().getSourceRange() 9838 << QualType(SourceType, 0) << TargetClass; 9839 UD->setInvalidDecl(); 9840 return true; 9841 } 9842 9843 if (Base) 9844 Base->setInheritConstructors(); 9845 9846 return false; 9847 } 9848 9849 /// Checks that the given using declaration is not an invalid 9850 /// redeclaration. Note that this is checking only for the using decl 9851 /// itself, not for any ill-formedness among the UsingShadowDecls. 9852 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9853 bool HasTypenameKeyword, 9854 const CXXScopeSpec &SS, 9855 SourceLocation NameLoc, 9856 const LookupResult &Prev) { 9857 NestedNameSpecifier *Qual = SS.getScopeRep(); 9858 9859 // C++03 [namespace.udecl]p8: 9860 // C++0x [namespace.udecl]p10: 9861 // A using-declaration is a declaration and can therefore be used 9862 // repeatedly where (and only where) multiple declarations are 9863 // allowed. 9864 // 9865 // That's in non-member contexts. 9866 if (!CurContext->getRedeclContext()->isRecord()) { 9867 // A dependent qualifier outside a class can only ever resolve to an 9868 // enumeration type. Therefore it conflicts with any other non-type 9869 // declaration in the same scope. 9870 // FIXME: How should we check for dependent type-type conflicts at block 9871 // scope? 9872 if (Qual->isDependent() && !HasTypenameKeyword) { 9873 for (auto *D : Prev) { 9874 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 9875 bool OldCouldBeEnumerator = 9876 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 9877 Diag(NameLoc, 9878 OldCouldBeEnumerator ? diag::err_redefinition 9879 : diag::err_redefinition_different_kind) 9880 << Prev.getLookupName(); 9881 Diag(D->getLocation(), diag::note_previous_definition); 9882 return true; 9883 } 9884 } 9885 } 9886 return false; 9887 } 9888 9889 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9890 NamedDecl *D = *I; 9891 9892 bool DTypename; 9893 NestedNameSpecifier *DQual; 9894 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9895 DTypename = UD->hasTypename(); 9896 DQual = UD->getQualifier(); 9897 } else if (UnresolvedUsingValueDecl *UD 9898 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9899 DTypename = false; 9900 DQual = UD->getQualifier(); 9901 } else if (UnresolvedUsingTypenameDecl *UD 9902 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9903 DTypename = true; 9904 DQual = UD->getQualifier(); 9905 } else continue; 9906 9907 // using decls differ if one says 'typename' and the other doesn't. 9908 // FIXME: non-dependent using decls? 9909 if (HasTypenameKeyword != DTypename) continue; 9910 9911 // using decls differ if they name different scopes (but note that 9912 // template instantiation can cause this check to trigger when it 9913 // didn't before instantiation). 9914 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9915 Context.getCanonicalNestedNameSpecifier(DQual)) 9916 continue; 9917 9918 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9919 Diag(D->getLocation(), diag::note_using_decl) << 1; 9920 return true; 9921 } 9922 9923 return false; 9924 } 9925 9926 9927 /// Checks that the given nested-name qualifier used in a using decl 9928 /// in the current context is appropriately related to the current 9929 /// scope. If an error is found, diagnoses it and returns true. 9930 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9931 bool HasTypename, 9932 const CXXScopeSpec &SS, 9933 const DeclarationNameInfo &NameInfo, 9934 SourceLocation NameLoc) { 9935 DeclContext *NamedContext = computeDeclContext(SS); 9936 9937 if (!CurContext->isRecord()) { 9938 // C++03 [namespace.udecl]p3: 9939 // C++0x [namespace.udecl]p8: 9940 // A using-declaration for a class member shall be a member-declaration. 9941 9942 // If we weren't able to compute a valid scope, it might validly be a 9943 // dependent class scope or a dependent enumeration unscoped scope. If 9944 // we have a 'typename' keyword, the scope must resolve to a class type. 9945 if ((HasTypename && !NamedContext) || 9946 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 9947 auto *RD = NamedContext 9948 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9949 : nullptr; 9950 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9951 RD = nullptr; 9952 9953 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9954 << SS.getRange(); 9955 9956 // If we have a complete, non-dependent source type, try to suggest a 9957 // way to get the same effect. 9958 if (!RD) 9959 return true; 9960 9961 // Find what this using-declaration was referring to. 9962 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9963 R.setHideTags(false); 9964 R.suppressDiagnostics(); 9965 LookupQualifiedName(R, RD); 9966 9967 if (R.getAsSingle<TypeDecl>()) { 9968 if (getLangOpts().CPlusPlus11) { 9969 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9970 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9971 << 0 // alias declaration 9972 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9973 NameInfo.getName().getAsString() + 9974 " = "); 9975 } else { 9976 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9977 SourceLocation InsertLoc = 9978 getLocForEndOfToken(NameInfo.getLocEnd()); 9979 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9980 << 1 // typedef declaration 9981 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9982 << FixItHint::CreateInsertion( 9983 InsertLoc, " " + NameInfo.getName().getAsString()); 9984 } 9985 } else if (R.getAsSingle<VarDecl>()) { 9986 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9987 // repeating the type of the static data member here. 9988 FixItHint FixIt; 9989 if (getLangOpts().CPlusPlus11) { 9990 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9991 FixIt = FixItHint::CreateReplacement( 9992 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9993 } 9994 9995 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9996 << 2 // reference declaration 9997 << FixIt; 9998 } else if (R.getAsSingle<EnumConstantDecl>()) { 9999 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10000 // repeating the type of the enumeration here, and we can't do so if 10001 // the type is anonymous. 10002 FixItHint FixIt; 10003 if (getLangOpts().CPlusPlus11) { 10004 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10005 FixIt = FixItHint::CreateReplacement( 10006 UsingLoc, 10007 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10008 } 10009 10010 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10011 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10012 << FixIt; 10013 } 10014 return true; 10015 } 10016 10017 // Otherwise, this might be valid. 10018 return false; 10019 } 10020 10021 // The current scope is a record. 10022 10023 // If the named context is dependent, we can't decide much. 10024 if (!NamedContext) { 10025 // FIXME: in C++0x, we can diagnose if we can prove that the 10026 // nested-name-specifier does not refer to a base class, which is 10027 // still possible in some cases. 10028 10029 // Otherwise we have to conservatively report that things might be 10030 // okay. 10031 return false; 10032 } 10033 10034 if (!NamedContext->isRecord()) { 10035 // Ideally this would point at the last name in the specifier, 10036 // but we don't have that level of source info. 10037 Diag(SS.getRange().getBegin(), 10038 diag::err_using_decl_nested_name_specifier_is_not_class) 10039 << SS.getScopeRep() << SS.getRange(); 10040 return true; 10041 } 10042 10043 if (!NamedContext->isDependentContext() && 10044 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10045 return true; 10046 10047 if (getLangOpts().CPlusPlus11) { 10048 // C++11 [namespace.udecl]p3: 10049 // In a using-declaration used as a member-declaration, the 10050 // nested-name-specifier shall name a base class of the class 10051 // being defined. 10052 10053 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10054 cast<CXXRecordDecl>(NamedContext))) { 10055 if (CurContext == NamedContext) { 10056 Diag(NameLoc, 10057 diag::err_using_decl_nested_name_specifier_is_current_class) 10058 << SS.getRange(); 10059 return true; 10060 } 10061 10062 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10063 Diag(SS.getRange().getBegin(), 10064 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10065 << SS.getScopeRep() 10066 << cast<CXXRecordDecl>(CurContext) 10067 << SS.getRange(); 10068 } 10069 return true; 10070 } 10071 10072 return false; 10073 } 10074 10075 // C++03 [namespace.udecl]p4: 10076 // A using-declaration used as a member-declaration shall refer 10077 // to a member of a base class of the class being defined [etc.]. 10078 10079 // Salient point: SS doesn't have to name a base class as long as 10080 // lookup only finds members from base classes. Therefore we can 10081 // diagnose here only if we can prove that that can't happen, 10082 // i.e. if the class hierarchies provably don't intersect. 10083 10084 // TODO: it would be nice if "definitely valid" results were cached 10085 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10086 // need to be repeated. 10087 10088 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10089 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10090 Bases.insert(Base); 10091 return true; 10092 }; 10093 10094 // Collect all bases. Return false if we find a dependent base. 10095 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10096 return false; 10097 10098 // Returns true if the base is dependent or is one of the accumulated base 10099 // classes. 10100 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10101 return !Bases.count(Base); 10102 }; 10103 10104 // Return false if the class has a dependent base or if it or one 10105 // of its bases is present in the base set of the current context. 10106 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10107 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10108 return false; 10109 10110 Diag(SS.getRange().getBegin(), 10111 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10112 << SS.getScopeRep() 10113 << cast<CXXRecordDecl>(CurContext) 10114 << SS.getRange(); 10115 10116 return true; 10117 } 10118 10119 Decl *Sema::ActOnAliasDeclaration(Scope *S, 10120 AccessSpecifier AS, 10121 MultiTemplateParamsArg TemplateParamLists, 10122 SourceLocation UsingLoc, 10123 UnqualifiedId &Name, 10124 AttributeList *AttrList, 10125 TypeResult Type, 10126 Decl *DeclFromDeclSpec) { 10127 // Skip up to the relevant declaration scope. 10128 while (S->isTemplateParamScope()) 10129 S = S->getParent(); 10130 assert((S->getFlags() & Scope::DeclScope) && 10131 "got alias-declaration outside of declaration scope"); 10132 10133 if (Type.isInvalid()) 10134 return nullptr; 10135 10136 bool Invalid = false; 10137 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10138 TypeSourceInfo *TInfo = nullptr; 10139 GetTypeFromParser(Type.get(), &TInfo); 10140 10141 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10142 return nullptr; 10143 10144 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10145 UPPC_DeclarationType)) { 10146 Invalid = true; 10147 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10148 TInfo->getTypeLoc().getBeginLoc()); 10149 } 10150 10151 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10152 TemplateParamLists.size() 10153 ? forRedeclarationInCurContext() 10154 : ForVisibleRedeclaration); 10155 LookupName(Previous, S); 10156 10157 // Warn about shadowing the name of a template parameter. 10158 if (Previous.isSingleResult() && 10159 Previous.getFoundDecl()->isTemplateParameter()) { 10160 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10161 Previous.clear(); 10162 } 10163 10164 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10165 "name in alias declaration must be an identifier"); 10166 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10167 Name.StartLocation, 10168 Name.Identifier, TInfo); 10169 10170 NewTD->setAccess(AS); 10171 10172 if (Invalid) 10173 NewTD->setInvalidDecl(); 10174 10175 ProcessDeclAttributeList(S, NewTD, AttrList); 10176 AddPragmaAttributes(S, NewTD); 10177 10178 CheckTypedefForVariablyModifiedType(S, NewTD); 10179 Invalid |= NewTD->isInvalidDecl(); 10180 10181 bool Redeclaration = false; 10182 10183 NamedDecl *NewND; 10184 if (TemplateParamLists.size()) { 10185 TypeAliasTemplateDecl *OldDecl = nullptr; 10186 TemplateParameterList *OldTemplateParams = nullptr; 10187 10188 if (TemplateParamLists.size() != 1) { 10189 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10190 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10191 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10192 } 10193 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10194 10195 // Check that we can declare a template here. 10196 if (CheckTemplateDeclScope(S, TemplateParams)) 10197 return nullptr; 10198 10199 // Only consider previous declarations in the same scope. 10200 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10201 /*ExplicitInstantiationOrSpecialization*/false); 10202 if (!Previous.empty()) { 10203 Redeclaration = true; 10204 10205 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10206 if (!OldDecl && !Invalid) { 10207 Diag(UsingLoc, diag::err_redefinition_different_kind) 10208 << Name.Identifier; 10209 10210 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10211 if (OldD->getLocation().isValid()) 10212 Diag(OldD->getLocation(), diag::note_previous_definition); 10213 10214 Invalid = true; 10215 } 10216 10217 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10218 if (TemplateParameterListsAreEqual(TemplateParams, 10219 OldDecl->getTemplateParameters(), 10220 /*Complain=*/true, 10221 TPL_TemplateMatch)) 10222 OldTemplateParams = OldDecl->getTemplateParameters(); 10223 else 10224 Invalid = true; 10225 10226 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10227 if (!Invalid && 10228 !Context.hasSameType(OldTD->getUnderlyingType(), 10229 NewTD->getUnderlyingType())) { 10230 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10231 // but we can't reasonably accept it. 10232 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10233 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10234 if (OldTD->getLocation().isValid()) 10235 Diag(OldTD->getLocation(), diag::note_previous_definition); 10236 Invalid = true; 10237 } 10238 } 10239 } 10240 10241 // Merge any previous default template arguments into our parameters, 10242 // and check the parameter list. 10243 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10244 TPC_TypeAliasTemplate)) 10245 return nullptr; 10246 10247 TypeAliasTemplateDecl *NewDecl = 10248 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10249 Name.Identifier, TemplateParams, 10250 NewTD); 10251 NewTD->setDescribedAliasTemplate(NewDecl); 10252 10253 NewDecl->setAccess(AS); 10254 10255 if (Invalid) 10256 NewDecl->setInvalidDecl(); 10257 else if (OldDecl) { 10258 NewDecl->setPreviousDecl(OldDecl); 10259 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10260 } 10261 10262 NewND = NewDecl; 10263 } else { 10264 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10265 setTagNameForLinkagePurposes(TD, NewTD); 10266 handleTagNumbering(TD, S); 10267 } 10268 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10269 NewND = NewTD; 10270 } 10271 10272 PushOnScopeChains(NewND, S); 10273 ActOnDocumentableDecl(NewND); 10274 return NewND; 10275 } 10276 10277 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10278 SourceLocation AliasLoc, 10279 IdentifierInfo *Alias, CXXScopeSpec &SS, 10280 SourceLocation IdentLoc, 10281 IdentifierInfo *Ident) { 10282 10283 // Lookup the namespace name. 10284 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10285 LookupParsedName(R, S, &SS); 10286 10287 if (R.isAmbiguous()) 10288 return nullptr; 10289 10290 if (R.empty()) { 10291 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10292 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10293 return nullptr; 10294 } 10295 } 10296 assert(!R.isAmbiguous() && !R.empty()); 10297 NamedDecl *ND = R.getRepresentativeDecl(); 10298 10299 // Check if we have a previous declaration with the same name. 10300 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10301 ForVisibleRedeclaration); 10302 LookupName(PrevR, S); 10303 10304 // Check we're not shadowing a template parameter. 10305 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10306 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10307 PrevR.clear(); 10308 } 10309 10310 // Filter out any other lookup result from an enclosing scope. 10311 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10312 /*AllowInlineNamespace*/false); 10313 10314 // Find the previous declaration and check that we can redeclare it. 10315 NamespaceAliasDecl *Prev = nullptr; 10316 if (PrevR.isSingleResult()) { 10317 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10318 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10319 // We already have an alias with the same name that points to the same 10320 // namespace; check that it matches. 10321 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10322 Prev = AD; 10323 } else if (isVisible(PrevDecl)) { 10324 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10325 << Alias; 10326 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10327 << AD->getNamespace(); 10328 return nullptr; 10329 } 10330 } else if (isVisible(PrevDecl)) { 10331 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10332 ? diag::err_redefinition 10333 : diag::err_redefinition_different_kind; 10334 Diag(AliasLoc, DiagID) << Alias; 10335 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10336 return nullptr; 10337 } 10338 } 10339 10340 // The use of a nested name specifier may trigger deprecation warnings. 10341 DiagnoseUseOfDecl(ND, IdentLoc); 10342 10343 NamespaceAliasDecl *AliasDecl = 10344 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10345 Alias, SS.getWithLocInContext(Context), 10346 IdentLoc, ND); 10347 if (Prev) 10348 AliasDecl->setPreviousDecl(Prev); 10349 10350 PushOnScopeChains(AliasDecl, S); 10351 return AliasDecl; 10352 } 10353 10354 namespace { 10355 struct SpecialMemberExceptionSpecInfo 10356 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10357 SourceLocation Loc; 10358 Sema::ImplicitExceptionSpecification ExceptSpec; 10359 10360 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10361 Sema::CXXSpecialMember CSM, 10362 Sema::InheritedConstructorInfo *ICI, 10363 SourceLocation Loc) 10364 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10365 10366 bool visitBase(CXXBaseSpecifier *Base); 10367 bool visitField(FieldDecl *FD); 10368 10369 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10370 unsigned Quals); 10371 10372 void visitSubobjectCall(Subobject Subobj, 10373 Sema::SpecialMemberOverloadResult SMOR); 10374 }; 10375 } 10376 10377 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10378 auto *RT = Base->getType()->getAs<RecordType>(); 10379 if (!RT) 10380 return false; 10381 10382 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10383 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10384 if (auto *BaseCtor = SMOR.getMethod()) { 10385 visitSubobjectCall(Base, BaseCtor); 10386 return false; 10387 } 10388 10389 visitClassSubobject(BaseClass, Base, 0); 10390 return false; 10391 } 10392 10393 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10394 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10395 Expr *E = FD->getInClassInitializer(); 10396 if (!E) 10397 // FIXME: It's a little wasteful to build and throw away a 10398 // CXXDefaultInitExpr here. 10399 // FIXME: We should have a single context note pointing at Loc, and 10400 // this location should be MD->getLocation() instead, since that's 10401 // the location where we actually use the default init expression. 10402 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10403 if (E) 10404 ExceptSpec.CalledExpr(E); 10405 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10406 ->getAs<RecordType>()) { 10407 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10408 FD->getType().getCVRQualifiers()); 10409 } 10410 return false; 10411 } 10412 10413 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10414 Subobject Subobj, 10415 unsigned Quals) { 10416 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10417 bool IsMutable = Field && Field->isMutable(); 10418 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10419 } 10420 10421 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10422 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10423 // Note, if lookup fails, it doesn't matter what exception specification we 10424 // choose because the special member will be deleted. 10425 if (CXXMethodDecl *MD = SMOR.getMethod()) 10426 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10427 } 10428 10429 static Sema::ImplicitExceptionSpecification 10430 ComputeDefaultedSpecialMemberExceptionSpec( 10431 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10432 Sema::InheritedConstructorInfo *ICI) { 10433 CXXRecordDecl *ClassDecl = MD->getParent(); 10434 10435 // C++ [except.spec]p14: 10436 // An implicitly declared special member function (Clause 12) shall have an 10437 // exception-specification. [...] 10438 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10439 if (ClassDecl->isInvalidDecl()) 10440 return Info.ExceptSpec; 10441 10442 // C++1z [except.spec]p7: 10443 // [Look for exceptions thrown by] a constructor selected [...] to 10444 // initialize a potentially constructed subobject, 10445 // C++1z [except.spec]p8: 10446 // The exception specification for an implicitly-declared destructor, or a 10447 // destructor without a noexcept-specifier, is potentially-throwing if and 10448 // only if any of the destructors for any of its potentially constructed 10449 // subojects is potentially throwing. 10450 // FIXME: We respect the first rule but ignore the "potentially constructed" 10451 // in the second rule to resolve a core issue (no number yet) that would have 10452 // us reject: 10453 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10454 // struct B : A {}; 10455 // struct C : B { void f(); }; 10456 // ... due to giving B::~B() a non-throwing exception specification. 10457 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10458 : Info.VisitAllBases); 10459 10460 return Info.ExceptSpec; 10461 } 10462 10463 namespace { 10464 /// RAII object to register a special member as being currently declared. 10465 struct DeclaringSpecialMember { 10466 Sema &S; 10467 Sema::SpecialMemberDecl D; 10468 Sema::ContextRAII SavedContext; 10469 bool WasAlreadyBeingDeclared; 10470 10471 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10472 : S(S), D(RD, CSM), SavedContext(S, RD) { 10473 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10474 if (WasAlreadyBeingDeclared) 10475 // This almost never happens, but if it does, ensure that our cache 10476 // doesn't contain a stale result. 10477 S.SpecialMemberCache.clear(); 10478 else { 10479 // Register a note to be produced if we encounter an error while 10480 // declaring the special member. 10481 Sema::CodeSynthesisContext Ctx; 10482 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10483 // FIXME: We don't have a location to use here. Using the class's 10484 // location maintains the fiction that we declare all special members 10485 // with the class, but (1) it's not clear that lying about that helps our 10486 // users understand what's going on, and (2) there may be outer contexts 10487 // on the stack (some of which are relevant) and printing them exposes 10488 // our lies. 10489 Ctx.PointOfInstantiation = RD->getLocation(); 10490 Ctx.Entity = RD; 10491 Ctx.SpecialMember = CSM; 10492 S.pushCodeSynthesisContext(Ctx); 10493 } 10494 } 10495 ~DeclaringSpecialMember() { 10496 if (!WasAlreadyBeingDeclared) { 10497 S.SpecialMembersBeingDeclared.erase(D); 10498 S.popCodeSynthesisContext(); 10499 } 10500 } 10501 10502 /// \brief Are we already trying to declare this special member? 10503 bool isAlreadyBeingDeclared() const { 10504 return WasAlreadyBeingDeclared; 10505 } 10506 }; 10507 } 10508 10509 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10510 // Look up any existing declarations, but don't trigger declaration of all 10511 // implicit special members with this name. 10512 DeclarationName Name = FD->getDeclName(); 10513 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10514 ForExternalRedeclaration); 10515 for (auto *D : FD->getParent()->lookup(Name)) 10516 if (auto *Acceptable = R.getAcceptableDecl(D)) 10517 R.addDecl(Acceptable); 10518 R.resolveKind(); 10519 R.suppressDiagnostics(); 10520 10521 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10522 } 10523 10524 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10525 CXXRecordDecl *ClassDecl) { 10526 // C++ [class.ctor]p5: 10527 // A default constructor for a class X is a constructor of class X 10528 // that can be called without an argument. If there is no 10529 // user-declared constructor for class X, a default constructor is 10530 // implicitly declared. An implicitly-declared default constructor 10531 // is an inline public member of its class. 10532 assert(ClassDecl->needsImplicitDefaultConstructor() && 10533 "Should not build implicit default constructor!"); 10534 10535 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10536 if (DSM.isAlreadyBeingDeclared()) 10537 return nullptr; 10538 10539 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10540 CXXDefaultConstructor, 10541 false); 10542 10543 // Create the actual constructor declaration. 10544 CanQualType ClassType 10545 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10546 SourceLocation ClassLoc = ClassDecl->getLocation(); 10547 DeclarationName Name 10548 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10549 DeclarationNameInfo NameInfo(Name, ClassLoc); 10550 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10551 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10552 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10553 /*isImplicitlyDeclared=*/true, Constexpr); 10554 DefaultCon->setAccess(AS_public); 10555 DefaultCon->setDefaulted(); 10556 10557 if (getLangOpts().CUDA) { 10558 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10559 DefaultCon, 10560 /* ConstRHS */ false, 10561 /* Diagnose */ false); 10562 } 10563 10564 // Build an exception specification pointing back at this constructor. 10565 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10566 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10567 10568 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10569 // constructors is easy to compute. 10570 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10571 10572 // Note that we have declared this constructor. 10573 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10574 10575 Scope *S = getScopeForContext(ClassDecl); 10576 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10577 10578 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10579 SetDeclDeleted(DefaultCon, ClassLoc); 10580 10581 if (S) 10582 PushOnScopeChains(DefaultCon, S, false); 10583 ClassDecl->addDecl(DefaultCon); 10584 10585 return DefaultCon; 10586 } 10587 10588 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10589 CXXConstructorDecl *Constructor) { 10590 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10591 !Constructor->doesThisDeclarationHaveABody() && 10592 !Constructor->isDeleted()) && 10593 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10594 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10595 return; 10596 10597 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10598 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10599 10600 SynthesizedFunctionScope Scope(*this, Constructor); 10601 10602 // The exception specification is needed because we are defining the 10603 // function. 10604 ResolveExceptionSpec(CurrentLocation, 10605 Constructor->getType()->castAs<FunctionProtoType>()); 10606 MarkVTableUsed(CurrentLocation, ClassDecl); 10607 10608 // Add a context note for diagnostics produced after this point. 10609 Scope.addContextNote(CurrentLocation); 10610 10611 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10612 Constructor->setInvalidDecl(); 10613 return; 10614 } 10615 10616 SourceLocation Loc = Constructor->getLocEnd().isValid() 10617 ? Constructor->getLocEnd() 10618 : Constructor->getLocation(); 10619 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10620 Constructor->markUsed(Context); 10621 10622 if (ASTMutationListener *L = getASTMutationListener()) { 10623 L->CompletedImplicitDefinition(Constructor); 10624 } 10625 10626 DiagnoseUninitializedFields(*this, Constructor); 10627 } 10628 10629 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10630 // Perform any delayed checks on exception specifications. 10631 CheckDelayedMemberExceptionSpecs(); 10632 } 10633 10634 /// Find or create the fake constructor we synthesize to model constructing an 10635 /// object of a derived class via a constructor of a base class. 10636 CXXConstructorDecl * 10637 Sema::findInheritingConstructor(SourceLocation Loc, 10638 CXXConstructorDecl *BaseCtor, 10639 ConstructorUsingShadowDecl *Shadow) { 10640 CXXRecordDecl *Derived = Shadow->getParent(); 10641 SourceLocation UsingLoc = Shadow->getLocation(); 10642 10643 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10644 // For now we use the name of the base class constructor as a member of the 10645 // derived class to indicate a (fake) inherited constructor name. 10646 DeclarationName Name = BaseCtor->getDeclName(); 10647 10648 // Check to see if we already have a fake constructor for this inherited 10649 // constructor call. 10650 for (NamedDecl *Ctor : Derived->lookup(Name)) 10651 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10652 ->getInheritedConstructor() 10653 .getConstructor(), 10654 BaseCtor)) 10655 return cast<CXXConstructorDecl>(Ctor); 10656 10657 DeclarationNameInfo NameInfo(Name, UsingLoc); 10658 TypeSourceInfo *TInfo = 10659 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10660 FunctionProtoTypeLoc ProtoLoc = 10661 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10662 10663 // Check the inherited constructor is valid and find the list of base classes 10664 // from which it was inherited. 10665 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10666 10667 bool Constexpr = 10668 BaseCtor->isConstexpr() && 10669 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10670 false, BaseCtor, &ICI); 10671 10672 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10673 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10674 BaseCtor->isExplicit(), /*Inline=*/true, 10675 /*ImplicitlyDeclared=*/true, Constexpr, 10676 InheritedConstructor(Shadow, BaseCtor)); 10677 if (Shadow->isInvalidDecl()) 10678 DerivedCtor->setInvalidDecl(); 10679 10680 // Build an unevaluated exception specification for this fake constructor. 10681 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10682 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10683 EPI.ExceptionSpec.Type = EST_Unevaluated; 10684 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10685 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10686 FPT->getParamTypes(), EPI)); 10687 10688 // Build the parameter declarations. 10689 SmallVector<ParmVarDecl *, 16> ParamDecls; 10690 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10691 TypeSourceInfo *TInfo = 10692 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10693 ParmVarDecl *PD = ParmVarDecl::Create( 10694 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10695 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10696 PD->setScopeInfo(0, I); 10697 PD->setImplicit(); 10698 // Ensure attributes are propagated onto parameters (this matters for 10699 // format, pass_object_size, ...). 10700 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10701 ParamDecls.push_back(PD); 10702 ProtoLoc.setParam(I, PD); 10703 } 10704 10705 // Set up the new constructor. 10706 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10707 DerivedCtor->setAccess(BaseCtor->getAccess()); 10708 DerivedCtor->setParams(ParamDecls); 10709 Derived->addDecl(DerivedCtor); 10710 10711 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10712 SetDeclDeleted(DerivedCtor, UsingLoc); 10713 10714 return DerivedCtor; 10715 } 10716 10717 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10718 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10719 Ctor->getInheritedConstructor().getShadowDecl()); 10720 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10721 /*Diagnose*/true); 10722 } 10723 10724 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10725 CXXConstructorDecl *Constructor) { 10726 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10727 assert(Constructor->getInheritedConstructor() && 10728 !Constructor->doesThisDeclarationHaveABody() && 10729 !Constructor->isDeleted()); 10730 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10731 return; 10732 10733 // Initializations are performed "as if by a defaulted default constructor", 10734 // so enter the appropriate scope. 10735 SynthesizedFunctionScope Scope(*this, Constructor); 10736 10737 // The exception specification is needed because we are defining the 10738 // function. 10739 ResolveExceptionSpec(CurrentLocation, 10740 Constructor->getType()->castAs<FunctionProtoType>()); 10741 MarkVTableUsed(CurrentLocation, ClassDecl); 10742 10743 // Add a context note for diagnostics produced after this point. 10744 Scope.addContextNote(CurrentLocation); 10745 10746 ConstructorUsingShadowDecl *Shadow = 10747 Constructor->getInheritedConstructor().getShadowDecl(); 10748 CXXConstructorDecl *InheritedCtor = 10749 Constructor->getInheritedConstructor().getConstructor(); 10750 10751 // [class.inhctor.init]p1: 10752 // initialization proceeds as if a defaulted default constructor is used to 10753 // initialize the D object and each base class subobject from which the 10754 // constructor was inherited 10755 10756 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10757 CXXRecordDecl *RD = Shadow->getParent(); 10758 SourceLocation InitLoc = Shadow->getLocation(); 10759 10760 // Build explicit initializers for all base classes from which the 10761 // constructor was inherited. 10762 SmallVector<CXXCtorInitializer*, 8> Inits; 10763 for (bool VBase : {false, true}) { 10764 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10765 if (B.isVirtual() != VBase) 10766 continue; 10767 10768 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10769 if (!BaseRD) 10770 continue; 10771 10772 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10773 if (!BaseCtor.first) 10774 continue; 10775 10776 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10777 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10778 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10779 10780 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10781 Inits.push_back(new (Context) CXXCtorInitializer( 10782 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10783 SourceLocation())); 10784 } 10785 } 10786 10787 // We now proceed as if for a defaulted default constructor, with the relevant 10788 // initializers replaced. 10789 10790 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 10791 Constructor->setInvalidDecl(); 10792 return; 10793 } 10794 10795 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10796 Constructor->markUsed(Context); 10797 10798 if (ASTMutationListener *L = getASTMutationListener()) { 10799 L->CompletedImplicitDefinition(Constructor); 10800 } 10801 10802 DiagnoseUninitializedFields(*this, Constructor); 10803 } 10804 10805 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10806 // C++ [class.dtor]p2: 10807 // If a class has no user-declared destructor, a destructor is 10808 // declared implicitly. An implicitly-declared destructor is an 10809 // inline public member of its class. 10810 assert(ClassDecl->needsImplicitDestructor()); 10811 10812 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10813 if (DSM.isAlreadyBeingDeclared()) 10814 return nullptr; 10815 10816 // Create the actual destructor declaration. 10817 CanQualType ClassType 10818 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10819 SourceLocation ClassLoc = ClassDecl->getLocation(); 10820 DeclarationName Name 10821 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10822 DeclarationNameInfo NameInfo(Name, ClassLoc); 10823 CXXDestructorDecl *Destructor 10824 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10825 QualType(), nullptr, /*isInline=*/true, 10826 /*isImplicitlyDeclared=*/true); 10827 Destructor->setAccess(AS_public); 10828 Destructor->setDefaulted(); 10829 10830 if (getLangOpts().CUDA) { 10831 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10832 Destructor, 10833 /* ConstRHS */ false, 10834 /* Diagnose */ false); 10835 } 10836 10837 // Build an exception specification pointing back at this destructor. 10838 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10839 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10840 10841 // We don't need to use SpecialMemberIsTrivial here; triviality for 10842 // destructors is easy to compute. 10843 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10844 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 10845 ClassDecl->hasTrivialDestructorForCall()); 10846 10847 // Note that we have declared this destructor. 10848 ++ASTContext::NumImplicitDestructorsDeclared; 10849 10850 Scope *S = getScopeForContext(ClassDecl); 10851 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10852 10853 // We can't check whether an implicit destructor is deleted before we complete 10854 // the definition of the class, because its validity depends on the alignment 10855 // of the class. We'll check this from ActOnFields once the class is complete. 10856 if (ClassDecl->isCompleteDefinition() && 10857 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10858 SetDeclDeleted(Destructor, ClassLoc); 10859 10860 // Introduce this destructor into its scope. 10861 if (S) 10862 PushOnScopeChains(Destructor, S, false); 10863 ClassDecl->addDecl(Destructor); 10864 10865 return Destructor; 10866 } 10867 10868 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10869 CXXDestructorDecl *Destructor) { 10870 assert((Destructor->isDefaulted() && 10871 !Destructor->doesThisDeclarationHaveABody() && 10872 !Destructor->isDeleted()) && 10873 "DefineImplicitDestructor - call it for implicit default dtor"); 10874 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 10875 return; 10876 10877 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10878 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10879 10880 SynthesizedFunctionScope Scope(*this, Destructor); 10881 10882 // The exception specification is needed because we are defining the 10883 // function. 10884 ResolveExceptionSpec(CurrentLocation, 10885 Destructor->getType()->castAs<FunctionProtoType>()); 10886 MarkVTableUsed(CurrentLocation, ClassDecl); 10887 10888 // Add a context note for diagnostics produced after this point. 10889 Scope.addContextNote(CurrentLocation); 10890 10891 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10892 Destructor->getParent()); 10893 10894 if (CheckDestructor(Destructor)) { 10895 Destructor->setInvalidDecl(); 10896 return; 10897 } 10898 10899 SourceLocation Loc = Destructor->getLocEnd().isValid() 10900 ? Destructor->getLocEnd() 10901 : Destructor->getLocation(); 10902 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10903 Destructor->markUsed(Context); 10904 10905 if (ASTMutationListener *L = getASTMutationListener()) { 10906 L->CompletedImplicitDefinition(Destructor); 10907 } 10908 } 10909 10910 /// \brief Perform any semantic analysis which needs to be delayed until all 10911 /// pending class member declarations have been parsed. 10912 void Sema::ActOnFinishCXXMemberDecls() { 10913 // If the context is an invalid C++ class, just suppress these checks. 10914 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10915 if (Record->isInvalidDecl()) { 10916 DelayedDefaultedMemberExceptionSpecs.clear(); 10917 DelayedExceptionSpecChecks.clear(); 10918 return; 10919 } 10920 checkForMultipleExportedDefaultConstructors(*this, Record); 10921 } 10922 } 10923 10924 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10925 referenceDLLExportedClassMethods(); 10926 } 10927 10928 void Sema::referenceDLLExportedClassMethods() { 10929 if (!DelayedDllExportClasses.empty()) { 10930 // Calling ReferenceDllExportedMembers might cause the current function to 10931 // be called again, so use a local copy of DelayedDllExportClasses. 10932 SmallVector<CXXRecordDecl *, 4> WorkList; 10933 std::swap(DelayedDllExportClasses, WorkList); 10934 for (CXXRecordDecl *Class : WorkList) 10935 ReferenceDllExportedMembers(*this, Class); 10936 } 10937 } 10938 10939 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10940 CXXDestructorDecl *Destructor) { 10941 assert(getLangOpts().CPlusPlus11 && 10942 "adjusting dtor exception specs was introduced in c++11"); 10943 10944 // C++11 [class.dtor]p3: 10945 // A declaration of a destructor that does not have an exception- 10946 // specification is implicitly considered to have the same exception- 10947 // specification as an implicit declaration. 10948 const FunctionProtoType *DtorType = Destructor->getType()-> 10949 getAs<FunctionProtoType>(); 10950 if (DtorType->hasExceptionSpec()) 10951 return; 10952 10953 // Replace the destructor's type, building off the existing one. Fortunately, 10954 // the only thing of interest in the destructor type is its extended info. 10955 // The return and arguments are fixed. 10956 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10957 EPI.ExceptionSpec.Type = EST_Unevaluated; 10958 EPI.ExceptionSpec.SourceDecl = Destructor; 10959 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10960 10961 // FIXME: If the destructor has a body that could throw, and the newly created 10962 // spec doesn't allow exceptions, we should emit a warning, because this 10963 // change in behavior can break conforming C++03 programs at runtime. 10964 // However, we don't have a body or an exception specification yet, so it 10965 // needs to be done somewhere else. 10966 } 10967 10968 namespace { 10969 /// \brief An abstract base class for all helper classes used in building the 10970 // copy/move operators. These classes serve as factory functions and help us 10971 // avoid using the same Expr* in the AST twice. 10972 class ExprBuilder { 10973 ExprBuilder(const ExprBuilder&) = delete; 10974 ExprBuilder &operator=(const ExprBuilder&) = delete; 10975 10976 protected: 10977 static Expr *assertNotNull(Expr *E) { 10978 assert(E && "Expression construction must not fail."); 10979 return E; 10980 } 10981 10982 public: 10983 ExprBuilder() {} 10984 virtual ~ExprBuilder() {} 10985 10986 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10987 }; 10988 10989 class RefBuilder: public ExprBuilder { 10990 VarDecl *Var; 10991 QualType VarType; 10992 10993 public: 10994 Expr *build(Sema &S, SourceLocation Loc) const override { 10995 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10996 } 10997 10998 RefBuilder(VarDecl *Var, QualType VarType) 10999 : Var(Var), VarType(VarType) {} 11000 }; 11001 11002 class ThisBuilder: public ExprBuilder { 11003 public: 11004 Expr *build(Sema &S, SourceLocation Loc) const override { 11005 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11006 } 11007 }; 11008 11009 class CastBuilder: public ExprBuilder { 11010 const ExprBuilder &Builder; 11011 QualType Type; 11012 ExprValueKind Kind; 11013 const CXXCastPath &Path; 11014 11015 public: 11016 Expr *build(Sema &S, SourceLocation Loc) const override { 11017 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11018 CK_UncheckedDerivedToBase, Kind, 11019 &Path).get()); 11020 } 11021 11022 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11023 const CXXCastPath &Path) 11024 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11025 }; 11026 11027 class DerefBuilder: public ExprBuilder { 11028 const ExprBuilder &Builder; 11029 11030 public: 11031 Expr *build(Sema &S, SourceLocation Loc) const override { 11032 return assertNotNull( 11033 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11034 } 11035 11036 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11037 }; 11038 11039 class MemberBuilder: public ExprBuilder { 11040 const ExprBuilder &Builder; 11041 QualType Type; 11042 CXXScopeSpec SS; 11043 bool IsArrow; 11044 LookupResult &MemberLookup; 11045 11046 public: 11047 Expr *build(Sema &S, SourceLocation Loc) const override { 11048 return assertNotNull(S.BuildMemberReferenceExpr( 11049 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11050 nullptr, MemberLookup, nullptr, nullptr).get()); 11051 } 11052 11053 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11054 LookupResult &MemberLookup) 11055 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11056 MemberLookup(MemberLookup) {} 11057 }; 11058 11059 class MoveCastBuilder: public ExprBuilder { 11060 const ExprBuilder &Builder; 11061 11062 public: 11063 Expr *build(Sema &S, SourceLocation Loc) const override { 11064 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11065 } 11066 11067 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11068 }; 11069 11070 class LvalueConvBuilder: public ExprBuilder { 11071 const ExprBuilder &Builder; 11072 11073 public: 11074 Expr *build(Sema &S, SourceLocation Loc) const override { 11075 return assertNotNull( 11076 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11077 } 11078 11079 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11080 }; 11081 11082 class SubscriptBuilder: public ExprBuilder { 11083 const ExprBuilder &Base; 11084 const ExprBuilder &Index; 11085 11086 public: 11087 Expr *build(Sema &S, SourceLocation Loc) const override { 11088 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11089 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11090 } 11091 11092 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11093 : Base(Base), Index(Index) {} 11094 }; 11095 11096 } // end anonymous namespace 11097 11098 /// When generating a defaulted copy or move assignment operator, if a field 11099 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11100 /// do so. This optimization only applies for arrays of scalars, and for arrays 11101 /// of class type where the selected copy/move-assignment operator is trivial. 11102 static StmtResult 11103 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11104 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11105 // Compute the size of the memory buffer to be copied. 11106 QualType SizeType = S.Context.getSizeType(); 11107 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11108 S.Context.getTypeSizeInChars(T).getQuantity()); 11109 11110 // Take the address of the field references for "from" and "to". We 11111 // directly construct UnaryOperators here because semantic analysis 11112 // does not permit us to take the address of an xvalue. 11113 Expr *From = FromB.build(S, Loc); 11114 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11115 S.Context.getPointerType(From->getType()), 11116 VK_RValue, OK_Ordinary, Loc, false); 11117 Expr *To = ToB.build(S, Loc); 11118 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11119 S.Context.getPointerType(To->getType()), 11120 VK_RValue, OK_Ordinary, Loc, false); 11121 11122 const Type *E = T->getBaseElementTypeUnsafe(); 11123 bool NeedsCollectableMemCpy = 11124 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11125 11126 // Create a reference to the __builtin_objc_memmove_collectable function 11127 StringRef MemCpyName = NeedsCollectableMemCpy ? 11128 "__builtin_objc_memmove_collectable" : 11129 "__builtin_memcpy"; 11130 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11131 Sema::LookupOrdinaryName); 11132 S.LookupName(R, S.TUScope, true); 11133 11134 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11135 if (!MemCpy) 11136 // Something went horribly wrong earlier, and we will have complained 11137 // about it. 11138 return StmtError(); 11139 11140 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11141 VK_RValue, Loc, nullptr); 11142 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11143 11144 Expr *CallArgs[] = { 11145 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11146 }; 11147 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11148 Loc, CallArgs, Loc); 11149 11150 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11151 return Call.getAs<Stmt>(); 11152 } 11153 11154 /// \brief Builds a statement that copies/moves the given entity from \p From to 11155 /// \c To. 11156 /// 11157 /// This routine is used to copy/move the members of a class with an 11158 /// implicitly-declared copy/move assignment operator. When the entities being 11159 /// copied are arrays, this routine builds for loops to copy them. 11160 /// 11161 /// \param S The Sema object used for type-checking. 11162 /// 11163 /// \param Loc The location where the implicit copy/move is being generated. 11164 /// 11165 /// \param T The type of the expressions being copied/moved. Both expressions 11166 /// must have this type. 11167 /// 11168 /// \param To The expression we are copying/moving to. 11169 /// 11170 /// \param From The expression we are copying/moving from. 11171 /// 11172 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11173 /// Otherwise, it's a non-static member subobject. 11174 /// 11175 /// \param Copying Whether we're copying or moving. 11176 /// 11177 /// \param Depth Internal parameter recording the depth of the recursion. 11178 /// 11179 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11180 /// if a memcpy should be used instead. 11181 static StmtResult 11182 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11183 const ExprBuilder &To, const ExprBuilder &From, 11184 bool CopyingBaseSubobject, bool Copying, 11185 unsigned Depth = 0) { 11186 // C++11 [class.copy]p28: 11187 // Each subobject is assigned in the manner appropriate to its type: 11188 // 11189 // - if the subobject is of class type, as if by a call to operator= with 11190 // the subobject as the object expression and the corresponding 11191 // subobject of x as a single function argument (as if by explicit 11192 // qualification; that is, ignoring any possible virtual overriding 11193 // functions in more derived classes); 11194 // 11195 // C++03 [class.copy]p13: 11196 // - if the subobject is of class type, the copy assignment operator for 11197 // the class is used (as if by explicit qualification; that is, 11198 // ignoring any possible virtual overriding functions in more derived 11199 // classes); 11200 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11201 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11202 11203 // Look for operator=. 11204 DeclarationName Name 11205 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11206 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11207 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11208 11209 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11210 // operator. 11211 if (!S.getLangOpts().CPlusPlus11) { 11212 LookupResult::Filter F = OpLookup.makeFilter(); 11213 while (F.hasNext()) { 11214 NamedDecl *D = F.next(); 11215 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11216 if (Method->isCopyAssignmentOperator() || 11217 (!Copying && Method->isMoveAssignmentOperator())) 11218 continue; 11219 11220 F.erase(); 11221 } 11222 F.done(); 11223 } 11224 11225 // Suppress the protected check (C++ [class.protected]) for each of the 11226 // assignment operators we found. This strange dance is required when 11227 // we're assigning via a base classes's copy-assignment operator. To 11228 // ensure that we're getting the right base class subobject (without 11229 // ambiguities), we need to cast "this" to that subobject type; to 11230 // ensure that we don't go through the virtual call mechanism, we need 11231 // to qualify the operator= name with the base class (see below). However, 11232 // this means that if the base class has a protected copy assignment 11233 // operator, the protected member access check will fail. So, we 11234 // rewrite "protected" access to "public" access in this case, since we 11235 // know by construction that we're calling from a derived class. 11236 if (CopyingBaseSubobject) { 11237 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11238 L != LEnd; ++L) { 11239 if (L.getAccess() == AS_protected) 11240 L.setAccess(AS_public); 11241 } 11242 } 11243 11244 // Create the nested-name-specifier that will be used to qualify the 11245 // reference to operator=; this is required to suppress the virtual 11246 // call mechanism. 11247 CXXScopeSpec SS; 11248 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11249 SS.MakeTrivial(S.Context, 11250 NestedNameSpecifier::Create(S.Context, nullptr, false, 11251 CanonicalT), 11252 Loc); 11253 11254 // Create the reference to operator=. 11255 ExprResult OpEqualRef 11256 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11257 SS, /*TemplateKWLoc=*/SourceLocation(), 11258 /*FirstQualifierInScope=*/nullptr, 11259 OpLookup, 11260 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11261 /*SuppressQualifierCheck=*/true); 11262 if (OpEqualRef.isInvalid()) 11263 return StmtError(); 11264 11265 // Build the call to the assignment operator. 11266 11267 Expr *FromInst = From.build(S, Loc); 11268 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11269 OpEqualRef.getAs<Expr>(), 11270 Loc, FromInst, Loc); 11271 if (Call.isInvalid()) 11272 return StmtError(); 11273 11274 // If we built a call to a trivial 'operator=' while copying an array, 11275 // bail out. We'll replace the whole shebang with a memcpy. 11276 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11277 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11278 return StmtResult((Stmt*)nullptr); 11279 11280 // Convert to an expression-statement, and clean up any produced 11281 // temporaries. 11282 return S.ActOnExprStmt(Call); 11283 } 11284 11285 // - if the subobject is of scalar type, the built-in assignment 11286 // operator is used. 11287 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11288 if (!ArrayTy) { 11289 ExprResult Assignment = S.CreateBuiltinBinOp( 11290 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11291 if (Assignment.isInvalid()) 11292 return StmtError(); 11293 return S.ActOnExprStmt(Assignment); 11294 } 11295 11296 // - if the subobject is an array, each element is assigned, in the 11297 // manner appropriate to the element type; 11298 11299 // Construct a loop over the array bounds, e.g., 11300 // 11301 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11302 // 11303 // that will copy each of the array elements. 11304 QualType SizeType = S.Context.getSizeType(); 11305 11306 // Create the iteration variable. 11307 IdentifierInfo *IterationVarName = nullptr; 11308 { 11309 SmallString<8> Str; 11310 llvm::raw_svector_ostream OS(Str); 11311 OS << "__i" << Depth; 11312 IterationVarName = &S.Context.Idents.get(OS.str()); 11313 } 11314 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11315 IterationVarName, SizeType, 11316 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11317 SC_None); 11318 11319 // Initialize the iteration variable to zero. 11320 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11321 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11322 11323 // Creates a reference to the iteration variable. 11324 RefBuilder IterationVarRef(IterationVar, SizeType); 11325 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11326 11327 // Create the DeclStmt that holds the iteration variable. 11328 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11329 11330 // Subscript the "from" and "to" expressions with the iteration variable. 11331 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11332 MoveCastBuilder FromIndexMove(FromIndexCopy); 11333 const ExprBuilder *FromIndex; 11334 if (Copying) 11335 FromIndex = &FromIndexCopy; 11336 else 11337 FromIndex = &FromIndexMove; 11338 11339 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11340 11341 // Build the copy/move for an individual element of the array. 11342 StmtResult Copy = 11343 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11344 ToIndex, *FromIndex, CopyingBaseSubobject, 11345 Copying, Depth + 1); 11346 // Bail out if copying fails or if we determined that we should use memcpy. 11347 if (Copy.isInvalid() || !Copy.get()) 11348 return Copy; 11349 11350 // Create the comparison against the array bound. 11351 llvm::APInt Upper 11352 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11353 Expr *Comparison 11354 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11355 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11356 BO_NE, S.Context.BoolTy, 11357 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11358 11359 // Create the pre-increment of the iteration variable. We can determine 11360 // whether the increment will overflow based on the value of the array 11361 // bound. 11362 Expr *Increment = new (S.Context) 11363 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11364 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11365 11366 // Construct the loop that copies all elements of this array. 11367 return S.ActOnForStmt( 11368 Loc, Loc, InitStmt, 11369 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11370 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11371 } 11372 11373 static StmtResult 11374 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11375 const ExprBuilder &To, const ExprBuilder &From, 11376 bool CopyingBaseSubobject, bool Copying) { 11377 // Maybe we should use a memcpy? 11378 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11379 T.isTriviallyCopyableType(S.Context)) 11380 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11381 11382 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11383 CopyingBaseSubobject, 11384 Copying, 0)); 11385 11386 // If we ended up picking a trivial assignment operator for an array of a 11387 // non-trivially-copyable class type, just emit a memcpy. 11388 if (!Result.isInvalid() && !Result.get()) 11389 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11390 11391 return Result; 11392 } 11393 11394 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11395 // Note: The following rules are largely analoguous to the copy 11396 // constructor rules. Note that virtual bases are not taken into account 11397 // for determining the argument type of the operator. Note also that 11398 // operators taking an object instead of a reference are allowed. 11399 assert(ClassDecl->needsImplicitCopyAssignment()); 11400 11401 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11402 if (DSM.isAlreadyBeingDeclared()) 11403 return nullptr; 11404 11405 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11406 QualType RetType = Context.getLValueReferenceType(ArgType); 11407 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11408 if (Const) 11409 ArgType = ArgType.withConst(); 11410 ArgType = Context.getLValueReferenceType(ArgType); 11411 11412 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11413 CXXCopyAssignment, 11414 Const); 11415 11416 // An implicitly-declared copy assignment operator is an inline public 11417 // member of its class. 11418 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11419 SourceLocation ClassLoc = ClassDecl->getLocation(); 11420 DeclarationNameInfo NameInfo(Name, ClassLoc); 11421 CXXMethodDecl *CopyAssignment = 11422 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11423 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11424 /*isInline=*/true, Constexpr, SourceLocation()); 11425 CopyAssignment->setAccess(AS_public); 11426 CopyAssignment->setDefaulted(); 11427 CopyAssignment->setImplicit(); 11428 11429 if (getLangOpts().CUDA) { 11430 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11431 CopyAssignment, 11432 /* ConstRHS */ Const, 11433 /* Diagnose */ false); 11434 } 11435 11436 // Build an exception specification pointing back at this member. 11437 FunctionProtoType::ExtProtoInfo EPI = 11438 getImplicitMethodEPI(*this, CopyAssignment); 11439 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11440 11441 // Add the parameter to the operator. 11442 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11443 ClassLoc, ClassLoc, 11444 /*Id=*/nullptr, ArgType, 11445 /*TInfo=*/nullptr, SC_None, 11446 nullptr); 11447 CopyAssignment->setParams(FromParam); 11448 11449 CopyAssignment->setTrivial( 11450 ClassDecl->needsOverloadResolutionForCopyAssignment() 11451 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11452 : ClassDecl->hasTrivialCopyAssignment()); 11453 11454 // Note that we have added this copy-assignment operator. 11455 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11456 11457 Scope *S = getScopeForContext(ClassDecl); 11458 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11459 11460 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11461 SetDeclDeleted(CopyAssignment, ClassLoc); 11462 11463 if (S) 11464 PushOnScopeChains(CopyAssignment, S, false); 11465 ClassDecl->addDecl(CopyAssignment); 11466 11467 return CopyAssignment; 11468 } 11469 11470 /// Diagnose an implicit copy operation for a class which is odr-used, but 11471 /// which is deprecated because the class has a user-declared copy constructor, 11472 /// copy assignment operator, or destructor. 11473 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11474 assert(CopyOp->isImplicit()); 11475 11476 CXXRecordDecl *RD = CopyOp->getParent(); 11477 CXXMethodDecl *UserDeclaredOperation = nullptr; 11478 11479 // In Microsoft mode, assignment operations don't affect constructors and 11480 // vice versa. 11481 if (RD->hasUserDeclaredDestructor()) { 11482 UserDeclaredOperation = RD->getDestructor(); 11483 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11484 RD->hasUserDeclaredCopyConstructor() && 11485 !S.getLangOpts().MSVCCompat) { 11486 // Find any user-declared copy constructor. 11487 for (auto *I : RD->ctors()) { 11488 if (I->isCopyConstructor()) { 11489 UserDeclaredOperation = I; 11490 break; 11491 } 11492 } 11493 assert(UserDeclaredOperation); 11494 } else if (isa<CXXConstructorDecl>(CopyOp) && 11495 RD->hasUserDeclaredCopyAssignment() && 11496 !S.getLangOpts().MSVCCompat) { 11497 // Find any user-declared move assignment operator. 11498 for (auto *I : RD->methods()) { 11499 if (I->isCopyAssignmentOperator()) { 11500 UserDeclaredOperation = I; 11501 break; 11502 } 11503 } 11504 assert(UserDeclaredOperation); 11505 } 11506 11507 if (UserDeclaredOperation) { 11508 S.Diag(UserDeclaredOperation->getLocation(), 11509 diag::warn_deprecated_copy_operation) 11510 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11511 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11512 } 11513 } 11514 11515 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11516 CXXMethodDecl *CopyAssignOperator) { 11517 assert((CopyAssignOperator->isDefaulted() && 11518 CopyAssignOperator->isOverloadedOperator() && 11519 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11520 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11521 !CopyAssignOperator->isDeleted()) && 11522 "DefineImplicitCopyAssignment called for wrong function"); 11523 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11524 return; 11525 11526 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11527 if (ClassDecl->isInvalidDecl()) { 11528 CopyAssignOperator->setInvalidDecl(); 11529 return; 11530 } 11531 11532 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11533 11534 // The exception specification is needed because we are defining the 11535 // function. 11536 ResolveExceptionSpec(CurrentLocation, 11537 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11538 11539 // Add a context note for diagnostics produced after this point. 11540 Scope.addContextNote(CurrentLocation); 11541 11542 // C++11 [class.copy]p18: 11543 // The [definition of an implicitly declared copy assignment operator] is 11544 // deprecated if the class has a user-declared copy constructor or a 11545 // user-declared destructor. 11546 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11547 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11548 11549 // C++0x [class.copy]p30: 11550 // The implicitly-defined or explicitly-defaulted copy assignment operator 11551 // for a non-union class X performs memberwise copy assignment of its 11552 // subobjects. The direct base classes of X are assigned first, in the 11553 // order of their declaration in the base-specifier-list, and then the 11554 // immediate non-static data members of X are assigned, in the order in 11555 // which they were declared in the class definition. 11556 11557 // The statements that form the synthesized function body. 11558 SmallVector<Stmt*, 8> Statements; 11559 11560 // The parameter for the "other" object, which we are copying from. 11561 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11562 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11563 QualType OtherRefType = Other->getType(); 11564 if (const LValueReferenceType *OtherRef 11565 = OtherRefType->getAs<LValueReferenceType>()) { 11566 OtherRefType = OtherRef->getPointeeType(); 11567 OtherQuals = OtherRefType.getQualifiers(); 11568 } 11569 11570 // Our location for everything implicitly-generated. 11571 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11572 ? CopyAssignOperator->getLocEnd() 11573 : CopyAssignOperator->getLocation(); 11574 11575 // Builds a DeclRefExpr for the "other" object. 11576 RefBuilder OtherRef(Other, OtherRefType); 11577 11578 // Builds the "this" pointer. 11579 ThisBuilder This; 11580 11581 // Assign base classes. 11582 bool Invalid = false; 11583 for (auto &Base : ClassDecl->bases()) { 11584 // Form the assignment: 11585 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11586 QualType BaseType = Base.getType().getUnqualifiedType(); 11587 if (!BaseType->isRecordType()) { 11588 Invalid = true; 11589 continue; 11590 } 11591 11592 CXXCastPath BasePath; 11593 BasePath.push_back(&Base); 11594 11595 // Construct the "from" expression, which is an implicit cast to the 11596 // appropriately-qualified base type. 11597 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11598 VK_LValue, BasePath); 11599 11600 // Dereference "this". 11601 DerefBuilder DerefThis(This); 11602 CastBuilder To(DerefThis, 11603 Context.getCVRQualifiedType( 11604 BaseType, CopyAssignOperator->getTypeQualifiers()), 11605 VK_LValue, BasePath); 11606 11607 // Build the copy. 11608 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11609 To, From, 11610 /*CopyingBaseSubobject=*/true, 11611 /*Copying=*/true); 11612 if (Copy.isInvalid()) { 11613 CopyAssignOperator->setInvalidDecl(); 11614 return; 11615 } 11616 11617 // Success! Record the copy. 11618 Statements.push_back(Copy.getAs<Expr>()); 11619 } 11620 11621 // Assign non-static members. 11622 for (auto *Field : ClassDecl->fields()) { 11623 // FIXME: We should form some kind of AST representation for the implied 11624 // memcpy in a union copy operation. 11625 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11626 continue; 11627 11628 if (Field->isInvalidDecl()) { 11629 Invalid = true; 11630 continue; 11631 } 11632 11633 // Check for members of reference type; we can't copy those. 11634 if (Field->getType()->isReferenceType()) { 11635 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11636 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11637 Diag(Field->getLocation(), diag::note_declared_at); 11638 Invalid = true; 11639 continue; 11640 } 11641 11642 // Check for members of const-qualified, non-class type. 11643 QualType BaseType = Context.getBaseElementType(Field->getType()); 11644 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11645 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11646 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11647 Diag(Field->getLocation(), diag::note_declared_at); 11648 Invalid = true; 11649 continue; 11650 } 11651 11652 // Suppress assigning zero-width bitfields. 11653 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11654 continue; 11655 11656 QualType FieldType = Field->getType().getNonReferenceType(); 11657 if (FieldType->isIncompleteArrayType()) { 11658 assert(ClassDecl->hasFlexibleArrayMember() && 11659 "Incomplete array type is not valid"); 11660 continue; 11661 } 11662 11663 // Build references to the field in the object we're copying from and to. 11664 CXXScopeSpec SS; // Intentionally empty 11665 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11666 LookupMemberName); 11667 MemberLookup.addDecl(Field); 11668 MemberLookup.resolveKind(); 11669 11670 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11671 11672 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11673 11674 // Build the copy of this field. 11675 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11676 To, From, 11677 /*CopyingBaseSubobject=*/false, 11678 /*Copying=*/true); 11679 if (Copy.isInvalid()) { 11680 CopyAssignOperator->setInvalidDecl(); 11681 return; 11682 } 11683 11684 // Success! Record the copy. 11685 Statements.push_back(Copy.getAs<Stmt>()); 11686 } 11687 11688 if (!Invalid) { 11689 // Add a "return *this;" 11690 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11691 11692 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11693 if (Return.isInvalid()) 11694 Invalid = true; 11695 else 11696 Statements.push_back(Return.getAs<Stmt>()); 11697 } 11698 11699 if (Invalid) { 11700 CopyAssignOperator->setInvalidDecl(); 11701 return; 11702 } 11703 11704 StmtResult Body; 11705 { 11706 CompoundScopeRAII CompoundScope(*this); 11707 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11708 /*isStmtExpr=*/false); 11709 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11710 } 11711 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11712 CopyAssignOperator->markUsed(Context); 11713 11714 if (ASTMutationListener *L = getASTMutationListener()) { 11715 L->CompletedImplicitDefinition(CopyAssignOperator); 11716 } 11717 } 11718 11719 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11720 assert(ClassDecl->needsImplicitMoveAssignment()); 11721 11722 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11723 if (DSM.isAlreadyBeingDeclared()) 11724 return nullptr; 11725 11726 // Note: The following rules are largely analoguous to the move 11727 // constructor rules. 11728 11729 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11730 QualType RetType = Context.getLValueReferenceType(ArgType); 11731 ArgType = Context.getRValueReferenceType(ArgType); 11732 11733 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11734 CXXMoveAssignment, 11735 false); 11736 11737 // An implicitly-declared move assignment operator is an inline public 11738 // member of its class. 11739 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11740 SourceLocation ClassLoc = ClassDecl->getLocation(); 11741 DeclarationNameInfo NameInfo(Name, ClassLoc); 11742 CXXMethodDecl *MoveAssignment = 11743 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11744 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11745 /*isInline=*/true, Constexpr, SourceLocation()); 11746 MoveAssignment->setAccess(AS_public); 11747 MoveAssignment->setDefaulted(); 11748 MoveAssignment->setImplicit(); 11749 11750 if (getLangOpts().CUDA) { 11751 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11752 MoveAssignment, 11753 /* ConstRHS */ false, 11754 /* Diagnose */ false); 11755 } 11756 11757 // Build an exception specification pointing back at this member. 11758 FunctionProtoType::ExtProtoInfo EPI = 11759 getImplicitMethodEPI(*this, MoveAssignment); 11760 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11761 11762 // Add the parameter to the operator. 11763 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11764 ClassLoc, ClassLoc, 11765 /*Id=*/nullptr, ArgType, 11766 /*TInfo=*/nullptr, SC_None, 11767 nullptr); 11768 MoveAssignment->setParams(FromParam); 11769 11770 MoveAssignment->setTrivial( 11771 ClassDecl->needsOverloadResolutionForMoveAssignment() 11772 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11773 : ClassDecl->hasTrivialMoveAssignment()); 11774 11775 // Note that we have added this copy-assignment operator. 11776 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11777 11778 Scope *S = getScopeForContext(ClassDecl); 11779 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11780 11781 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11782 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11783 SetDeclDeleted(MoveAssignment, ClassLoc); 11784 } 11785 11786 if (S) 11787 PushOnScopeChains(MoveAssignment, S, false); 11788 ClassDecl->addDecl(MoveAssignment); 11789 11790 return MoveAssignment; 11791 } 11792 11793 /// Check if we're implicitly defining a move assignment operator for a class 11794 /// with virtual bases. Such a move assignment might move-assign the virtual 11795 /// base multiple times. 11796 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11797 SourceLocation CurrentLocation) { 11798 assert(!Class->isDependentContext() && "should not define dependent move"); 11799 11800 // Only a virtual base could get implicitly move-assigned multiple times. 11801 // Only a non-trivial move assignment can observe this. We only want to 11802 // diagnose if we implicitly define an assignment operator that assigns 11803 // two base classes, both of which move-assign the same virtual base. 11804 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11805 Class->getNumBases() < 2) 11806 return; 11807 11808 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11809 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11810 VBaseMap VBases; 11811 11812 for (auto &BI : Class->bases()) { 11813 Worklist.push_back(&BI); 11814 while (!Worklist.empty()) { 11815 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11816 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11817 11818 // If the base has no non-trivial move assignment operators, 11819 // we don't care about moves from it. 11820 if (!Base->hasNonTrivialMoveAssignment()) 11821 continue; 11822 11823 // If there's nothing virtual here, skip it. 11824 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11825 continue; 11826 11827 // If we're not actually going to call a move assignment for this base, 11828 // or the selected move assignment is trivial, skip it. 11829 Sema::SpecialMemberOverloadResult SMOR = 11830 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11831 /*ConstArg*/false, /*VolatileArg*/false, 11832 /*RValueThis*/true, /*ConstThis*/false, 11833 /*VolatileThis*/false); 11834 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 11835 !SMOR.getMethod()->isMoveAssignmentOperator()) 11836 continue; 11837 11838 if (BaseSpec->isVirtual()) { 11839 // We're going to move-assign this virtual base, and its move 11840 // assignment operator is not trivial. If this can happen for 11841 // multiple distinct direct bases of Class, diagnose it. (If it 11842 // only happens in one base, we'll diagnose it when synthesizing 11843 // that base class's move assignment operator.) 11844 CXXBaseSpecifier *&Existing = 11845 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11846 .first->second; 11847 if (Existing && Existing != &BI) { 11848 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11849 << Class << Base; 11850 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11851 << (Base->getCanonicalDecl() == 11852 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11853 << Base << Existing->getType() << Existing->getSourceRange(); 11854 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11855 << (Base->getCanonicalDecl() == 11856 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11857 << Base << BI.getType() << BaseSpec->getSourceRange(); 11858 11859 // Only diagnose each vbase once. 11860 Existing = nullptr; 11861 } 11862 } else { 11863 // Only walk over bases that have defaulted move assignment operators. 11864 // We assume that any user-provided move assignment operator handles 11865 // the multiple-moves-of-vbase case itself somehow. 11866 if (!SMOR.getMethod()->isDefaulted()) 11867 continue; 11868 11869 // We're going to move the base classes of Base. Add them to the list. 11870 for (auto &BI : Base->bases()) 11871 Worklist.push_back(&BI); 11872 } 11873 } 11874 } 11875 } 11876 11877 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11878 CXXMethodDecl *MoveAssignOperator) { 11879 assert((MoveAssignOperator->isDefaulted() && 11880 MoveAssignOperator->isOverloadedOperator() && 11881 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11882 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11883 !MoveAssignOperator->isDeleted()) && 11884 "DefineImplicitMoveAssignment called for wrong function"); 11885 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 11886 return; 11887 11888 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11889 if (ClassDecl->isInvalidDecl()) { 11890 MoveAssignOperator->setInvalidDecl(); 11891 return; 11892 } 11893 11894 // C++0x [class.copy]p28: 11895 // The implicitly-defined or move assignment operator for a non-union class 11896 // X performs memberwise move assignment of its subobjects. The direct base 11897 // classes of X are assigned first, in the order of their declaration in the 11898 // base-specifier-list, and then the immediate non-static data members of X 11899 // are assigned, in the order in which they were declared in the class 11900 // definition. 11901 11902 // Issue a warning if our implicit move assignment operator will move 11903 // from a virtual base more than once. 11904 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11905 11906 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11907 11908 // The exception specification is needed because we are defining the 11909 // function. 11910 ResolveExceptionSpec(CurrentLocation, 11911 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11912 11913 // Add a context note for diagnostics produced after this point. 11914 Scope.addContextNote(CurrentLocation); 11915 11916 // The statements that form the synthesized function body. 11917 SmallVector<Stmt*, 8> Statements; 11918 11919 // The parameter for the "other" object, which we are move from. 11920 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11921 QualType OtherRefType = Other->getType()-> 11922 getAs<RValueReferenceType>()->getPointeeType(); 11923 assert(!OtherRefType.getQualifiers() && 11924 "Bad argument type of defaulted move assignment"); 11925 11926 // Our location for everything implicitly-generated. 11927 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11928 ? MoveAssignOperator->getLocEnd() 11929 : MoveAssignOperator->getLocation(); 11930 11931 // Builds a reference to the "other" object. 11932 RefBuilder OtherRef(Other, OtherRefType); 11933 // Cast to rvalue. 11934 MoveCastBuilder MoveOther(OtherRef); 11935 11936 // Builds the "this" pointer. 11937 ThisBuilder This; 11938 11939 // Assign base classes. 11940 bool Invalid = false; 11941 for (auto &Base : ClassDecl->bases()) { 11942 // C++11 [class.copy]p28: 11943 // It is unspecified whether subobjects representing virtual base classes 11944 // are assigned more than once by the implicitly-defined copy assignment 11945 // operator. 11946 // FIXME: Do not assign to a vbase that will be assigned by some other base 11947 // class. For a move-assignment, this can result in the vbase being moved 11948 // multiple times. 11949 11950 // Form the assignment: 11951 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11952 QualType BaseType = Base.getType().getUnqualifiedType(); 11953 if (!BaseType->isRecordType()) { 11954 Invalid = true; 11955 continue; 11956 } 11957 11958 CXXCastPath BasePath; 11959 BasePath.push_back(&Base); 11960 11961 // Construct the "from" expression, which is an implicit cast to the 11962 // appropriately-qualified base type. 11963 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11964 11965 // Dereference "this". 11966 DerefBuilder DerefThis(This); 11967 11968 // Implicitly cast "this" to the appropriately-qualified base type. 11969 CastBuilder To(DerefThis, 11970 Context.getCVRQualifiedType( 11971 BaseType, MoveAssignOperator->getTypeQualifiers()), 11972 VK_LValue, BasePath); 11973 11974 // Build the move. 11975 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11976 To, From, 11977 /*CopyingBaseSubobject=*/true, 11978 /*Copying=*/false); 11979 if (Move.isInvalid()) { 11980 MoveAssignOperator->setInvalidDecl(); 11981 return; 11982 } 11983 11984 // Success! Record the move. 11985 Statements.push_back(Move.getAs<Expr>()); 11986 } 11987 11988 // Assign non-static members. 11989 for (auto *Field : ClassDecl->fields()) { 11990 // FIXME: We should form some kind of AST representation for the implied 11991 // memcpy in a union copy operation. 11992 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11993 continue; 11994 11995 if (Field->isInvalidDecl()) { 11996 Invalid = true; 11997 continue; 11998 } 11999 12000 // Check for members of reference type; we can't move those. 12001 if (Field->getType()->isReferenceType()) { 12002 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12003 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12004 Diag(Field->getLocation(), diag::note_declared_at); 12005 Invalid = true; 12006 continue; 12007 } 12008 12009 // Check for members of const-qualified, non-class type. 12010 QualType BaseType = Context.getBaseElementType(Field->getType()); 12011 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12012 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12013 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12014 Diag(Field->getLocation(), diag::note_declared_at); 12015 Invalid = true; 12016 continue; 12017 } 12018 12019 // Suppress assigning zero-width bitfields. 12020 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 12021 continue; 12022 12023 QualType FieldType = Field->getType().getNonReferenceType(); 12024 if (FieldType->isIncompleteArrayType()) { 12025 assert(ClassDecl->hasFlexibleArrayMember() && 12026 "Incomplete array type is not valid"); 12027 continue; 12028 } 12029 12030 // Build references to the field in the object we're copying from and to. 12031 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12032 LookupMemberName); 12033 MemberLookup.addDecl(Field); 12034 MemberLookup.resolveKind(); 12035 MemberBuilder From(MoveOther, OtherRefType, 12036 /*IsArrow=*/false, MemberLookup); 12037 MemberBuilder To(This, getCurrentThisType(), 12038 /*IsArrow=*/true, MemberLookup); 12039 12040 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12041 "Member reference with rvalue base must be rvalue except for reference " 12042 "members, which aren't allowed for move assignment."); 12043 12044 // Build the move of this field. 12045 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12046 To, From, 12047 /*CopyingBaseSubobject=*/false, 12048 /*Copying=*/false); 12049 if (Move.isInvalid()) { 12050 MoveAssignOperator->setInvalidDecl(); 12051 return; 12052 } 12053 12054 // Success! Record the copy. 12055 Statements.push_back(Move.getAs<Stmt>()); 12056 } 12057 12058 if (!Invalid) { 12059 // Add a "return *this;" 12060 ExprResult ThisObj = 12061 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12062 12063 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12064 if (Return.isInvalid()) 12065 Invalid = true; 12066 else 12067 Statements.push_back(Return.getAs<Stmt>()); 12068 } 12069 12070 if (Invalid) { 12071 MoveAssignOperator->setInvalidDecl(); 12072 return; 12073 } 12074 12075 StmtResult Body; 12076 { 12077 CompoundScopeRAII CompoundScope(*this); 12078 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12079 /*isStmtExpr=*/false); 12080 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12081 } 12082 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12083 MoveAssignOperator->markUsed(Context); 12084 12085 if (ASTMutationListener *L = getASTMutationListener()) { 12086 L->CompletedImplicitDefinition(MoveAssignOperator); 12087 } 12088 } 12089 12090 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12091 CXXRecordDecl *ClassDecl) { 12092 // C++ [class.copy]p4: 12093 // If the class definition does not explicitly declare a copy 12094 // constructor, one is declared implicitly. 12095 assert(ClassDecl->needsImplicitCopyConstructor()); 12096 12097 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12098 if (DSM.isAlreadyBeingDeclared()) 12099 return nullptr; 12100 12101 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12102 QualType ArgType = ClassType; 12103 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12104 if (Const) 12105 ArgType = ArgType.withConst(); 12106 ArgType = Context.getLValueReferenceType(ArgType); 12107 12108 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12109 CXXCopyConstructor, 12110 Const); 12111 12112 DeclarationName Name 12113 = Context.DeclarationNames.getCXXConstructorName( 12114 Context.getCanonicalType(ClassType)); 12115 SourceLocation ClassLoc = ClassDecl->getLocation(); 12116 DeclarationNameInfo NameInfo(Name, ClassLoc); 12117 12118 // An implicitly-declared copy constructor is an inline public 12119 // member of its class. 12120 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12121 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12122 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12123 Constexpr); 12124 CopyConstructor->setAccess(AS_public); 12125 CopyConstructor->setDefaulted(); 12126 12127 if (getLangOpts().CUDA) { 12128 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12129 CopyConstructor, 12130 /* ConstRHS */ Const, 12131 /* Diagnose */ false); 12132 } 12133 12134 // Build an exception specification pointing back at this member. 12135 FunctionProtoType::ExtProtoInfo EPI = 12136 getImplicitMethodEPI(*this, CopyConstructor); 12137 CopyConstructor->setType( 12138 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12139 12140 // Add the parameter to the constructor. 12141 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12142 ClassLoc, ClassLoc, 12143 /*IdentifierInfo=*/nullptr, 12144 ArgType, /*TInfo=*/nullptr, 12145 SC_None, nullptr); 12146 CopyConstructor->setParams(FromParam); 12147 12148 CopyConstructor->setTrivial( 12149 ClassDecl->needsOverloadResolutionForCopyConstructor() 12150 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12151 : ClassDecl->hasTrivialCopyConstructor()); 12152 12153 CopyConstructor->setTrivialForCall( 12154 ClassDecl->hasAttr<TrivialABIAttr>() || 12155 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12156 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12157 TAH_ConsiderTrivialABI) 12158 : ClassDecl->hasTrivialCopyConstructorForCall())); 12159 12160 // Note that we have declared this constructor. 12161 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12162 12163 Scope *S = getScopeForContext(ClassDecl); 12164 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12165 12166 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12167 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12168 SetDeclDeleted(CopyConstructor, ClassLoc); 12169 } 12170 12171 if (S) 12172 PushOnScopeChains(CopyConstructor, S, false); 12173 ClassDecl->addDecl(CopyConstructor); 12174 12175 return CopyConstructor; 12176 } 12177 12178 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12179 CXXConstructorDecl *CopyConstructor) { 12180 assert((CopyConstructor->isDefaulted() && 12181 CopyConstructor->isCopyConstructor() && 12182 !CopyConstructor->doesThisDeclarationHaveABody() && 12183 !CopyConstructor->isDeleted()) && 12184 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12185 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12186 return; 12187 12188 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12189 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12190 12191 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12192 12193 // The exception specification is needed because we are defining the 12194 // function. 12195 ResolveExceptionSpec(CurrentLocation, 12196 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12197 MarkVTableUsed(CurrentLocation, ClassDecl); 12198 12199 // Add a context note for diagnostics produced after this point. 12200 Scope.addContextNote(CurrentLocation); 12201 12202 // C++11 [class.copy]p7: 12203 // The [definition of an implicitly declared copy constructor] is 12204 // deprecated if the class has a user-declared copy assignment operator 12205 // or a user-declared destructor. 12206 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12207 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12208 12209 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12210 CopyConstructor->setInvalidDecl(); 12211 } else { 12212 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 12213 ? CopyConstructor->getLocEnd() 12214 : CopyConstructor->getLocation(); 12215 Sema::CompoundScopeRAII CompoundScope(*this); 12216 CopyConstructor->setBody( 12217 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12218 CopyConstructor->markUsed(Context); 12219 } 12220 12221 if (ASTMutationListener *L = getASTMutationListener()) { 12222 L->CompletedImplicitDefinition(CopyConstructor); 12223 } 12224 } 12225 12226 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12227 CXXRecordDecl *ClassDecl) { 12228 assert(ClassDecl->needsImplicitMoveConstructor()); 12229 12230 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12231 if (DSM.isAlreadyBeingDeclared()) 12232 return nullptr; 12233 12234 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12235 QualType ArgType = Context.getRValueReferenceType(ClassType); 12236 12237 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12238 CXXMoveConstructor, 12239 false); 12240 12241 DeclarationName Name 12242 = Context.DeclarationNames.getCXXConstructorName( 12243 Context.getCanonicalType(ClassType)); 12244 SourceLocation ClassLoc = ClassDecl->getLocation(); 12245 DeclarationNameInfo NameInfo(Name, ClassLoc); 12246 12247 // C++11 [class.copy]p11: 12248 // An implicitly-declared copy/move constructor is an inline public 12249 // member of its class. 12250 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12251 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12252 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12253 Constexpr); 12254 MoveConstructor->setAccess(AS_public); 12255 MoveConstructor->setDefaulted(); 12256 12257 if (getLangOpts().CUDA) { 12258 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12259 MoveConstructor, 12260 /* ConstRHS */ false, 12261 /* Diagnose */ false); 12262 } 12263 12264 // Build an exception specification pointing back at this member. 12265 FunctionProtoType::ExtProtoInfo EPI = 12266 getImplicitMethodEPI(*this, MoveConstructor); 12267 MoveConstructor->setType( 12268 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12269 12270 // Add the parameter to the constructor. 12271 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12272 ClassLoc, ClassLoc, 12273 /*IdentifierInfo=*/nullptr, 12274 ArgType, /*TInfo=*/nullptr, 12275 SC_None, nullptr); 12276 MoveConstructor->setParams(FromParam); 12277 12278 MoveConstructor->setTrivial( 12279 ClassDecl->needsOverloadResolutionForMoveConstructor() 12280 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12281 : ClassDecl->hasTrivialMoveConstructor()); 12282 12283 MoveConstructor->setTrivialForCall( 12284 ClassDecl->hasAttr<TrivialABIAttr>() || 12285 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12286 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12287 TAH_ConsiderTrivialABI) 12288 : ClassDecl->hasTrivialMoveConstructorForCall())); 12289 12290 // Note that we have declared this constructor. 12291 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12292 12293 Scope *S = getScopeForContext(ClassDecl); 12294 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12295 12296 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12297 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12298 SetDeclDeleted(MoveConstructor, ClassLoc); 12299 } 12300 12301 if (S) 12302 PushOnScopeChains(MoveConstructor, S, false); 12303 ClassDecl->addDecl(MoveConstructor); 12304 12305 return MoveConstructor; 12306 } 12307 12308 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12309 CXXConstructorDecl *MoveConstructor) { 12310 assert((MoveConstructor->isDefaulted() && 12311 MoveConstructor->isMoveConstructor() && 12312 !MoveConstructor->doesThisDeclarationHaveABody() && 12313 !MoveConstructor->isDeleted()) && 12314 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12315 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12316 return; 12317 12318 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12319 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12320 12321 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12322 12323 // The exception specification is needed because we are defining the 12324 // function. 12325 ResolveExceptionSpec(CurrentLocation, 12326 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12327 MarkVTableUsed(CurrentLocation, ClassDecl); 12328 12329 // Add a context note for diagnostics produced after this point. 12330 Scope.addContextNote(CurrentLocation); 12331 12332 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12333 MoveConstructor->setInvalidDecl(); 12334 } else { 12335 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12336 ? MoveConstructor->getLocEnd() 12337 : MoveConstructor->getLocation(); 12338 Sema::CompoundScopeRAII CompoundScope(*this); 12339 MoveConstructor->setBody(ActOnCompoundStmt( 12340 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12341 MoveConstructor->markUsed(Context); 12342 } 12343 12344 if (ASTMutationListener *L = getASTMutationListener()) { 12345 L->CompletedImplicitDefinition(MoveConstructor); 12346 } 12347 } 12348 12349 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12350 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12351 } 12352 12353 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12354 SourceLocation CurrentLocation, 12355 CXXConversionDecl *Conv) { 12356 SynthesizedFunctionScope Scope(*this, Conv); 12357 assert(!Conv->getReturnType()->isUndeducedType()); 12358 12359 CXXRecordDecl *Lambda = Conv->getParent(); 12360 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12361 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12362 12363 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 12364 CallOp = InstantiateFunctionDeclaration( 12365 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12366 if (!CallOp) 12367 return; 12368 12369 Invoker = InstantiateFunctionDeclaration( 12370 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12371 if (!Invoker) 12372 return; 12373 } 12374 12375 if (CallOp->isInvalidDecl()) 12376 return; 12377 12378 // Mark the call operator referenced (and add to pending instantiations 12379 // if necessary). 12380 // For both the conversion and static-invoker template specializations 12381 // we construct their body's in this function, so no need to add them 12382 // to the PendingInstantiations. 12383 MarkFunctionReferenced(CurrentLocation, CallOp); 12384 12385 // Fill in the __invoke function with a dummy implementation. IR generation 12386 // will fill in the actual details. Update its type in case it contained 12387 // an 'auto'. 12388 Invoker->markUsed(Context); 12389 Invoker->setReferenced(); 12390 Invoker->setType(Conv->getReturnType()->getPointeeType()); 12391 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12392 12393 // Construct the body of the conversion function { return __invoke; }. 12394 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12395 VK_LValue, Conv->getLocation()).get(); 12396 assert(FunctionRef && "Can't refer to __invoke function?"); 12397 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12398 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 12399 Conv->getLocation())); 12400 Conv->markUsed(Context); 12401 Conv->setReferenced(); 12402 12403 if (ASTMutationListener *L = getASTMutationListener()) { 12404 L->CompletedImplicitDefinition(Conv); 12405 L->CompletedImplicitDefinition(Invoker); 12406 } 12407 } 12408 12409 12410 12411 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12412 SourceLocation CurrentLocation, 12413 CXXConversionDecl *Conv) 12414 { 12415 assert(!Conv->getParent()->isGenericLambda()); 12416 12417 SynthesizedFunctionScope Scope(*this, Conv); 12418 12419 // Copy-initialize the lambda object as needed to capture it. 12420 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12421 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12422 12423 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12424 Conv->getLocation(), 12425 Conv, DerefThis); 12426 12427 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12428 // behavior. Note that only the general conversion function does this 12429 // (since it's unusable otherwise); in the case where we inline the 12430 // block literal, it has block literal lifetime semantics. 12431 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12432 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12433 CK_CopyAndAutoreleaseBlockObject, 12434 BuildBlock.get(), nullptr, VK_RValue); 12435 12436 if (BuildBlock.isInvalid()) { 12437 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12438 Conv->setInvalidDecl(); 12439 return; 12440 } 12441 12442 // Create the return statement that returns the block from the conversion 12443 // function. 12444 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12445 if (Return.isInvalid()) { 12446 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12447 Conv->setInvalidDecl(); 12448 return; 12449 } 12450 12451 // Set the body of the conversion function. 12452 Stmt *ReturnS = Return.get(); 12453 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 12454 Conv->getLocation())); 12455 Conv->markUsed(Context); 12456 12457 // We're done; notify the mutation listener, if any. 12458 if (ASTMutationListener *L = getASTMutationListener()) { 12459 L->CompletedImplicitDefinition(Conv); 12460 } 12461 } 12462 12463 /// \brief Determine whether the given list arguments contains exactly one 12464 /// "real" (non-default) argument. 12465 static bool hasOneRealArgument(MultiExprArg Args) { 12466 switch (Args.size()) { 12467 case 0: 12468 return false; 12469 12470 default: 12471 if (!Args[1]->isDefaultArgument()) 12472 return false; 12473 12474 LLVM_FALLTHROUGH; 12475 case 1: 12476 return !Args[0]->isDefaultArgument(); 12477 } 12478 12479 return false; 12480 } 12481 12482 ExprResult 12483 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12484 NamedDecl *FoundDecl, 12485 CXXConstructorDecl *Constructor, 12486 MultiExprArg ExprArgs, 12487 bool HadMultipleCandidates, 12488 bool IsListInitialization, 12489 bool IsStdInitListInitialization, 12490 bool RequiresZeroInit, 12491 unsigned ConstructKind, 12492 SourceRange ParenRange) { 12493 bool Elidable = false; 12494 12495 // C++0x [class.copy]p34: 12496 // When certain criteria are met, an implementation is allowed to 12497 // omit the copy/move construction of a class object, even if the 12498 // copy/move constructor and/or destructor for the object have 12499 // side effects. [...] 12500 // - when a temporary class object that has not been bound to a 12501 // reference (12.2) would be copied/moved to a class object 12502 // with the same cv-unqualified type, the copy/move operation 12503 // can be omitted by constructing the temporary object 12504 // directly into the target of the omitted copy/move 12505 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12506 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12507 Expr *SubExpr = ExprArgs[0]; 12508 Elidable = SubExpr->isTemporaryObject( 12509 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12510 } 12511 12512 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12513 FoundDecl, Constructor, 12514 Elidable, ExprArgs, HadMultipleCandidates, 12515 IsListInitialization, 12516 IsStdInitListInitialization, RequiresZeroInit, 12517 ConstructKind, ParenRange); 12518 } 12519 12520 ExprResult 12521 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12522 NamedDecl *FoundDecl, 12523 CXXConstructorDecl *Constructor, 12524 bool Elidable, 12525 MultiExprArg ExprArgs, 12526 bool HadMultipleCandidates, 12527 bool IsListInitialization, 12528 bool IsStdInitListInitialization, 12529 bool RequiresZeroInit, 12530 unsigned ConstructKind, 12531 SourceRange ParenRange) { 12532 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12533 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12534 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12535 return ExprError(); 12536 } 12537 12538 return BuildCXXConstructExpr( 12539 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12540 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12541 RequiresZeroInit, ConstructKind, ParenRange); 12542 } 12543 12544 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12545 /// including handling of its default argument expressions. 12546 ExprResult 12547 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12548 CXXConstructorDecl *Constructor, 12549 bool Elidable, 12550 MultiExprArg ExprArgs, 12551 bool HadMultipleCandidates, 12552 bool IsListInitialization, 12553 bool IsStdInitListInitialization, 12554 bool RequiresZeroInit, 12555 unsigned ConstructKind, 12556 SourceRange ParenRange) { 12557 assert(declaresSameEntity( 12558 Constructor->getParent(), 12559 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12560 "given constructor for wrong type"); 12561 MarkFunctionReferenced(ConstructLoc, Constructor); 12562 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12563 return ExprError(); 12564 12565 return CXXConstructExpr::Create( 12566 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12567 ExprArgs, HadMultipleCandidates, IsListInitialization, 12568 IsStdInitListInitialization, RequiresZeroInit, 12569 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12570 ParenRange); 12571 } 12572 12573 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12574 assert(Field->hasInClassInitializer()); 12575 12576 // If we already have the in-class initializer nothing needs to be done. 12577 if (Field->getInClassInitializer()) 12578 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12579 12580 // If we might have already tried and failed to instantiate, don't try again. 12581 if (Field->isInvalidDecl()) 12582 return ExprError(); 12583 12584 // Maybe we haven't instantiated the in-class initializer. Go check the 12585 // pattern FieldDecl to see if it has one. 12586 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12587 12588 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12589 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12590 DeclContext::lookup_result Lookup = 12591 ClassPattern->lookup(Field->getDeclName()); 12592 12593 // Lookup can return at most two results: the pattern for the field, or the 12594 // injected class name of the parent record. No other member can have the 12595 // same name as the field. 12596 // In modules mode, lookup can return multiple results (coming from 12597 // different modules). 12598 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12599 "more than two lookup results for field name"); 12600 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12601 if (!Pattern) { 12602 assert(isa<CXXRecordDecl>(Lookup[0]) && 12603 "cannot have other non-field member with same name"); 12604 for (auto L : Lookup) 12605 if (isa<FieldDecl>(L)) { 12606 Pattern = cast<FieldDecl>(L); 12607 break; 12608 } 12609 assert(Pattern && "We must have set the Pattern!"); 12610 } 12611 12612 if (!Pattern->hasInClassInitializer() || 12613 InstantiateInClassInitializer(Loc, Field, Pattern, 12614 getTemplateInstantiationArgs(Field))) { 12615 // Don't diagnose this again. 12616 Field->setInvalidDecl(); 12617 return ExprError(); 12618 } 12619 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12620 } 12621 12622 // DR1351: 12623 // If the brace-or-equal-initializer of a non-static data member 12624 // invokes a defaulted default constructor of its class or of an 12625 // enclosing class in a potentially evaluated subexpression, the 12626 // program is ill-formed. 12627 // 12628 // This resolution is unworkable: the exception specification of the 12629 // default constructor can be needed in an unevaluated context, in 12630 // particular, in the operand of a noexcept-expression, and we can be 12631 // unable to compute an exception specification for an enclosed class. 12632 // 12633 // Any attempt to resolve the exception specification of a defaulted default 12634 // constructor before the initializer is lexically complete will ultimately 12635 // come here at which point we can diagnose it. 12636 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12637 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12638 << OutermostClass << Field; 12639 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12640 // Recover by marking the field invalid, unless we're in a SFINAE context. 12641 if (!isSFINAEContext()) 12642 Field->setInvalidDecl(); 12643 return ExprError(); 12644 } 12645 12646 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12647 if (VD->isInvalidDecl()) return; 12648 12649 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12650 if (ClassDecl->isInvalidDecl()) return; 12651 if (ClassDecl->hasIrrelevantDestructor()) return; 12652 if (ClassDecl->isDependentContext()) return; 12653 12654 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12655 MarkFunctionReferenced(VD->getLocation(), Destructor); 12656 CheckDestructorAccess(VD->getLocation(), Destructor, 12657 PDiag(diag::err_access_dtor_var) 12658 << VD->getDeclName() 12659 << VD->getType()); 12660 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12661 12662 if (Destructor->isTrivial()) return; 12663 if (!VD->hasGlobalStorage()) return; 12664 12665 // Emit warning for non-trivial dtor in global scope (a real global, 12666 // class-static, function-static). 12667 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12668 12669 // TODO: this should be re-enabled for static locals by !CXAAtExit 12670 if (!VD->isStaticLocal()) 12671 Diag(VD->getLocation(), diag::warn_global_destructor); 12672 } 12673 12674 /// \brief Given a constructor and the set of arguments provided for the 12675 /// constructor, convert the arguments and add any required default arguments 12676 /// to form a proper call to this constructor. 12677 /// 12678 /// \returns true if an error occurred, false otherwise. 12679 bool 12680 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12681 MultiExprArg ArgsPtr, 12682 SourceLocation Loc, 12683 SmallVectorImpl<Expr*> &ConvertedArgs, 12684 bool AllowExplicit, 12685 bool IsListInitialization) { 12686 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12687 unsigned NumArgs = ArgsPtr.size(); 12688 Expr **Args = ArgsPtr.data(); 12689 12690 const FunctionProtoType *Proto 12691 = Constructor->getType()->getAs<FunctionProtoType>(); 12692 assert(Proto && "Constructor without a prototype?"); 12693 unsigned NumParams = Proto->getNumParams(); 12694 12695 // If too few arguments are available, we'll fill in the rest with defaults. 12696 if (NumArgs < NumParams) 12697 ConvertedArgs.reserve(NumParams); 12698 else 12699 ConvertedArgs.reserve(NumArgs); 12700 12701 VariadicCallType CallType = 12702 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12703 SmallVector<Expr *, 8> AllArgs; 12704 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12705 Proto, 0, 12706 llvm::makeArrayRef(Args, NumArgs), 12707 AllArgs, 12708 CallType, AllowExplicit, 12709 IsListInitialization); 12710 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12711 12712 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12713 12714 CheckConstructorCall(Constructor, 12715 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12716 Proto, Loc); 12717 12718 return Invalid; 12719 } 12720 12721 static inline bool 12722 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12723 const FunctionDecl *FnDecl) { 12724 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12725 if (isa<NamespaceDecl>(DC)) { 12726 return SemaRef.Diag(FnDecl->getLocation(), 12727 diag::err_operator_new_delete_declared_in_namespace) 12728 << FnDecl->getDeclName(); 12729 } 12730 12731 if (isa<TranslationUnitDecl>(DC) && 12732 FnDecl->getStorageClass() == SC_Static) { 12733 return SemaRef.Diag(FnDecl->getLocation(), 12734 diag::err_operator_new_delete_declared_static) 12735 << FnDecl->getDeclName(); 12736 } 12737 12738 return false; 12739 } 12740 12741 static inline bool 12742 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12743 CanQualType ExpectedResultType, 12744 CanQualType ExpectedFirstParamType, 12745 unsigned DependentParamTypeDiag, 12746 unsigned InvalidParamTypeDiag) { 12747 QualType ResultType = 12748 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12749 12750 // Check that the result type is not dependent. 12751 if (ResultType->isDependentType()) 12752 return SemaRef.Diag(FnDecl->getLocation(), 12753 diag::err_operator_new_delete_dependent_result_type) 12754 << FnDecl->getDeclName() << ExpectedResultType; 12755 12756 // Check that the result type is what we expect. 12757 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12758 return SemaRef.Diag(FnDecl->getLocation(), 12759 diag::err_operator_new_delete_invalid_result_type) 12760 << FnDecl->getDeclName() << ExpectedResultType; 12761 12762 // A function template must have at least 2 parameters. 12763 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12764 return SemaRef.Diag(FnDecl->getLocation(), 12765 diag::err_operator_new_delete_template_too_few_parameters) 12766 << FnDecl->getDeclName(); 12767 12768 // The function decl must have at least 1 parameter. 12769 if (FnDecl->getNumParams() == 0) 12770 return SemaRef.Diag(FnDecl->getLocation(), 12771 diag::err_operator_new_delete_too_few_parameters) 12772 << FnDecl->getDeclName(); 12773 12774 // Check the first parameter type is not dependent. 12775 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12776 if (FirstParamType->isDependentType()) 12777 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12778 << FnDecl->getDeclName() << ExpectedFirstParamType; 12779 12780 // Check that the first parameter type is what we expect. 12781 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12782 ExpectedFirstParamType) 12783 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12784 << FnDecl->getDeclName() << ExpectedFirstParamType; 12785 12786 return false; 12787 } 12788 12789 static bool 12790 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12791 // C++ [basic.stc.dynamic.allocation]p1: 12792 // A program is ill-formed if an allocation function is declared in a 12793 // namespace scope other than global scope or declared static in global 12794 // scope. 12795 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12796 return true; 12797 12798 CanQualType SizeTy = 12799 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12800 12801 // C++ [basic.stc.dynamic.allocation]p1: 12802 // The return type shall be void*. The first parameter shall have type 12803 // std::size_t. 12804 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12805 SizeTy, 12806 diag::err_operator_new_dependent_param_type, 12807 diag::err_operator_new_param_type)) 12808 return true; 12809 12810 // C++ [basic.stc.dynamic.allocation]p1: 12811 // The first parameter shall not have an associated default argument. 12812 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12813 return SemaRef.Diag(FnDecl->getLocation(), 12814 diag::err_operator_new_default_arg) 12815 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12816 12817 return false; 12818 } 12819 12820 static bool 12821 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12822 // C++ [basic.stc.dynamic.deallocation]p1: 12823 // A program is ill-formed if deallocation functions are declared in a 12824 // namespace scope other than global scope or declared static in global 12825 // scope. 12826 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12827 return true; 12828 12829 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 12830 12831 // C++ P0722: 12832 // Within a class C, the first parameter of a destroying operator delete 12833 // shall be of type C *. The first parameter of any other deallocation 12834 // function shall be of type void *. 12835 CanQualType ExpectedFirstParamType = 12836 MD && MD->isDestroyingOperatorDelete() 12837 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 12838 SemaRef.Context.getRecordType(MD->getParent()))) 12839 : SemaRef.Context.VoidPtrTy; 12840 12841 // C++ [basic.stc.dynamic.deallocation]p2: 12842 // Each deallocation function shall return void 12843 if (CheckOperatorNewDeleteTypes( 12844 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 12845 diag::err_operator_delete_dependent_param_type, 12846 diag::err_operator_delete_param_type)) 12847 return true; 12848 12849 // C++ P0722: 12850 // A destroying operator delete shall be a usual deallocation function. 12851 if (MD && !MD->getParent()->isDependentContext() && 12852 MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) { 12853 SemaRef.Diag(MD->getLocation(), 12854 diag::err_destroying_operator_delete_not_usual); 12855 return true; 12856 } 12857 12858 return false; 12859 } 12860 12861 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12862 /// of this overloaded operator is well-formed. If so, returns false; 12863 /// otherwise, emits appropriate diagnostics and returns true. 12864 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12865 assert(FnDecl && FnDecl->isOverloadedOperator() && 12866 "Expected an overloaded operator declaration"); 12867 12868 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12869 12870 // C++ [over.oper]p5: 12871 // The allocation and deallocation functions, operator new, 12872 // operator new[], operator delete and operator delete[], are 12873 // described completely in 3.7.3. The attributes and restrictions 12874 // found in the rest of this subclause do not apply to them unless 12875 // explicitly stated in 3.7.3. 12876 if (Op == OO_Delete || Op == OO_Array_Delete) 12877 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12878 12879 if (Op == OO_New || Op == OO_Array_New) 12880 return CheckOperatorNewDeclaration(*this, FnDecl); 12881 12882 // C++ [over.oper]p6: 12883 // An operator function shall either be a non-static member 12884 // function or be a non-member function and have at least one 12885 // parameter whose type is a class, a reference to a class, an 12886 // enumeration, or a reference to an enumeration. 12887 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12888 if (MethodDecl->isStatic()) 12889 return Diag(FnDecl->getLocation(), 12890 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12891 } else { 12892 bool ClassOrEnumParam = false; 12893 for (auto Param : FnDecl->parameters()) { 12894 QualType ParamType = Param->getType().getNonReferenceType(); 12895 if (ParamType->isDependentType() || ParamType->isRecordType() || 12896 ParamType->isEnumeralType()) { 12897 ClassOrEnumParam = true; 12898 break; 12899 } 12900 } 12901 12902 if (!ClassOrEnumParam) 12903 return Diag(FnDecl->getLocation(), 12904 diag::err_operator_overload_needs_class_or_enum) 12905 << FnDecl->getDeclName(); 12906 } 12907 12908 // C++ [over.oper]p8: 12909 // An operator function cannot have default arguments (8.3.6), 12910 // except where explicitly stated below. 12911 // 12912 // Only the function-call operator allows default arguments 12913 // (C++ [over.call]p1). 12914 if (Op != OO_Call) { 12915 for (auto Param : FnDecl->parameters()) { 12916 if (Param->hasDefaultArg()) 12917 return Diag(Param->getLocation(), 12918 diag::err_operator_overload_default_arg) 12919 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12920 } 12921 } 12922 12923 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12924 { false, false, false } 12925 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12926 , { Unary, Binary, MemberOnly } 12927 #include "clang/Basic/OperatorKinds.def" 12928 }; 12929 12930 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12931 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12932 bool MustBeMemberOperator = OperatorUses[Op][2]; 12933 12934 // C++ [over.oper]p8: 12935 // [...] Operator functions cannot have more or fewer parameters 12936 // than the number required for the corresponding operator, as 12937 // described in the rest of this subclause. 12938 unsigned NumParams = FnDecl->getNumParams() 12939 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12940 if (Op != OO_Call && 12941 ((NumParams == 1 && !CanBeUnaryOperator) || 12942 (NumParams == 2 && !CanBeBinaryOperator) || 12943 (NumParams < 1) || (NumParams > 2))) { 12944 // We have the wrong number of parameters. 12945 unsigned ErrorKind; 12946 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12947 ErrorKind = 2; // 2 -> unary or binary. 12948 } else if (CanBeUnaryOperator) { 12949 ErrorKind = 0; // 0 -> unary 12950 } else { 12951 assert(CanBeBinaryOperator && 12952 "All non-call overloaded operators are unary or binary!"); 12953 ErrorKind = 1; // 1 -> binary 12954 } 12955 12956 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12957 << FnDecl->getDeclName() << NumParams << ErrorKind; 12958 } 12959 12960 // Overloaded operators other than operator() cannot be variadic. 12961 if (Op != OO_Call && 12962 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12963 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12964 << FnDecl->getDeclName(); 12965 } 12966 12967 // Some operators must be non-static member functions. 12968 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12969 return Diag(FnDecl->getLocation(), 12970 diag::err_operator_overload_must_be_member) 12971 << FnDecl->getDeclName(); 12972 } 12973 12974 // C++ [over.inc]p1: 12975 // The user-defined function called operator++ implements the 12976 // prefix and postfix ++ operator. If this function is a member 12977 // function with no parameters, or a non-member function with one 12978 // parameter of class or enumeration type, it defines the prefix 12979 // increment operator ++ for objects of that type. If the function 12980 // is a member function with one parameter (which shall be of type 12981 // int) or a non-member function with two parameters (the second 12982 // of which shall be of type int), it defines the postfix 12983 // increment operator ++ for objects of that type. 12984 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12985 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12986 QualType ParamType = LastParam->getType(); 12987 12988 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12989 !ParamType->isDependentType()) 12990 return Diag(LastParam->getLocation(), 12991 diag::err_operator_overload_post_incdec_must_be_int) 12992 << LastParam->getType() << (Op == OO_MinusMinus); 12993 } 12994 12995 return false; 12996 } 12997 12998 static bool 12999 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13000 FunctionTemplateDecl *TpDecl) { 13001 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13002 13003 // Must have one or two template parameters. 13004 if (TemplateParams->size() == 1) { 13005 NonTypeTemplateParmDecl *PmDecl = 13006 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13007 13008 // The template parameter must be a char parameter pack. 13009 if (PmDecl && PmDecl->isTemplateParameterPack() && 13010 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13011 return false; 13012 13013 } else if (TemplateParams->size() == 2) { 13014 TemplateTypeParmDecl *PmType = 13015 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13016 NonTypeTemplateParmDecl *PmArgs = 13017 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13018 13019 // The second template parameter must be a parameter pack with the 13020 // first template parameter as its type. 13021 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13022 PmArgs->isTemplateParameterPack()) { 13023 const TemplateTypeParmType *TArgs = 13024 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13025 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13026 TArgs->getIndex() == PmType->getIndex()) { 13027 if (!SemaRef.inTemplateInstantiation()) 13028 SemaRef.Diag(TpDecl->getLocation(), 13029 diag::ext_string_literal_operator_template); 13030 return false; 13031 } 13032 } 13033 } 13034 13035 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13036 diag::err_literal_operator_template) 13037 << TpDecl->getTemplateParameters()->getSourceRange(); 13038 return true; 13039 } 13040 13041 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13042 /// of this literal operator function is well-formed. If so, returns 13043 /// false; otherwise, emits appropriate diagnostics and returns true. 13044 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13045 if (isa<CXXMethodDecl>(FnDecl)) { 13046 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13047 << FnDecl->getDeclName(); 13048 return true; 13049 } 13050 13051 if (FnDecl->isExternC()) { 13052 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13053 if (const LinkageSpecDecl *LSD = 13054 FnDecl->getDeclContext()->getExternCContext()) 13055 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13056 return true; 13057 } 13058 13059 // This might be the definition of a literal operator template. 13060 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13061 13062 // This might be a specialization of a literal operator template. 13063 if (!TpDecl) 13064 TpDecl = FnDecl->getPrimaryTemplate(); 13065 13066 // template <char...> type operator "" name() and 13067 // template <class T, T...> type operator "" name() are the only valid 13068 // template signatures, and the only valid signatures with no parameters. 13069 if (TpDecl) { 13070 if (FnDecl->param_size() != 0) { 13071 Diag(FnDecl->getLocation(), 13072 diag::err_literal_operator_template_with_params); 13073 return true; 13074 } 13075 13076 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13077 return true; 13078 13079 } else if (FnDecl->param_size() == 1) { 13080 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13081 13082 QualType ParamType = Param->getType().getUnqualifiedType(); 13083 13084 // Only unsigned long long int, long double, any character type, and const 13085 // char * are allowed as the only parameters. 13086 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13087 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13088 Context.hasSameType(ParamType, Context.CharTy) || 13089 Context.hasSameType(ParamType, Context.WideCharTy) || 13090 Context.hasSameType(ParamType, Context.Char16Ty) || 13091 Context.hasSameType(ParamType, Context.Char32Ty)) { 13092 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13093 QualType InnerType = Ptr->getPointeeType(); 13094 13095 // Pointer parameter must be a const char *. 13096 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13097 Context.CharTy) && 13098 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13099 Diag(Param->getSourceRange().getBegin(), 13100 diag::err_literal_operator_param) 13101 << ParamType << "'const char *'" << Param->getSourceRange(); 13102 return true; 13103 } 13104 13105 } else if (ParamType->isRealFloatingType()) { 13106 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13107 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13108 return true; 13109 13110 } else if (ParamType->isIntegerType()) { 13111 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13112 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13113 return true; 13114 13115 } else { 13116 Diag(Param->getSourceRange().getBegin(), 13117 diag::err_literal_operator_invalid_param) 13118 << ParamType << Param->getSourceRange(); 13119 return true; 13120 } 13121 13122 } else if (FnDecl->param_size() == 2) { 13123 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13124 13125 // First, verify that the first parameter is correct. 13126 13127 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13128 13129 // Two parameter function must have a pointer to const as a 13130 // first parameter; let's strip those qualifiers. 13131 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13132 13133 if (!PT) { 13134 Diag((*Param)->getSourceRange().getBegin(), 13135 diag::err_literal_operator_param) 13136 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13137 return true; 13138 } 13139 13140 QualType PointeeType = PT->getPointeeType(); 13141 // First parameter must be const 13142 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13143 Diag((*Param)->getSourceRange().getBegin(), 13144 diag::err_literal_operator_param) 13145 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13146 return true; 13147 } 13148 13149 QualType InnerType = PointeeType.getUnqualifiedType(); 13150 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 13151 // are allowed as the first parameter to a two-parameter function 13152 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13153 Context.hasSameType(InnerType, Context.WideCharTy) || 13154 Context.hasSameType(InnerType, Context.Char16Ty) || 13155 Context.hasSameType(InnerType, Context.Char32Ty))) { 13156 Diag((*Param)->getSourceRange().getBegin(), 13157 diag::err_literal_operator_param) 13158 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13159 return true; 13160 } 13161 13162 // Move on to the second and final parameter. 13163 ++Param; 13164 13165 // The second parameter must be a std::size_t. 13166 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13167 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13168 Diag((*Param)->getSourceRange().getBegin(), 13169 diag::err_literal_operator_param) 13170 << SecondParamType << Context.getSizeType() 13171 << (*Param)->getSourceRange(); 13172 return true; 13173 } 13174 } else { 13175 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13176 return true; 13177 } 13178 13179 // Parameters are good. 13180 13181 // A parameter-declaration-clause containing a default argument is not 13182 // equivalent to any of the permitted forms. 13183 for (auto Param : FnDecl->parameters()) { 13184 if (Param->hasDefaultArg()) { 13185 Diag(Param->getDefaultArgRange().getBegin(), 13186 diag::err_literal_operator_default_argument) 13187 << Param->getDefaultArgRange(); 13188 break; 13189 } 13190 } 13191 13192 StringRef LiteralName 13193 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13194 if (LiteralName[0] != '_' && 13195 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13196 // C++11 [usrlit.suffix]p1: 13197 // Literal suffix identifiers that do not start with an underscore 13198 // are reserved for future standardization. 13199 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13200 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13201 } 13202 13203 return false; 13204 } 13205 13206 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13207 /// linkage specification, including the language and (if present) 13208 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13209 /// language string literal. LBraceLoc, if valid, provides the location of 13210 /// the '{' brace. Otherwise, this linkage specification does not 13211 /// have any braces. 13212 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13213 Expr *LangStr, 13214 SourceLocation LBraceLoc) { 13215 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13216 if (!Lit->isAscii()) { 13217 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13218 << LangStr->getSourceRange(); 13219 return nullptr; 13220 } 13221 13222 StringRef Lang = Lit->getString(); 13223 LinkageSpecDecl::LanguageIDs Language; 13224 if (Lang == "C") 13225 Language = LinkageSpecDecl::lang_c; 13226 else if (Lang == "C++") 13227 Language = LinkageSpecDecl::lang_cxx; 13228 else { 13229 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13230 << LangStr->getSourceRange(); 13231 return nullptr; 13232 } 13233 13234 // FIXME: Add all the various semantics of linkage specifications 13235 13236 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13237 LangStr->getExprLoc(), Language, 13238 LBraceLoc.isValid()); 13239 CurContext->addDecl(D); 13240 PushDeclContext(S, D); 13241 return D; 13242 } 13243 13244 /// ActOnFinishLinkageSpecification - Complete the definition of 13245 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13246 /// valid, it's the position of the closing '}' brace in a linkage 13247 /// specification that uses braces. 13248 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13249 Decl *LinkageSpec, 13250 SourceLocation RBraceLoc) { 13251 if (RBraceLoc.isValid()) { 13252 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13253 LSDecl->setRBraceLoc(RBraceLoc); 13254 } 13255 PopDeclContext(); 13256 return LinkageSpec; 13257 } 13258 13259 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13260 AttributeList *AttrList, 13261 SourceLocation SemiLoc) { 13262 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13263 // Attribute declarations appertain to empty declaration so we handle 13264 // them here. 13265 if (AttrList) 13266 ProcessDeclAttributeList(S, ED, AttrList); 13267 13268 CurContext->addDecl(ED); 13269 return ED; 13270 } 13271 13272 /// \brief Perform semantic analysis for the variable declaration that 13273 /// occurs within a C++ catch clause, returning the newly-created 13274 /// variable. 13275 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13276 TypeSourceInfo *TInfo, 13277 SourceLocation StartLoc, 13278 SourceLocation Loc, 13279 IdentifierInfo *Name) { 13280 bool Invalid = false; 13281 QualType ExDeclType = TInfo->getType(); 13282 13283 // Arrays and functions decay. 13284 if (ExDeclType->isArrayType()) 13285 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13286 else if (ExDeclType->isFunctionType()) 13287 ExDeclType = Context.getPointerType(ExDeclType); 13288 13289 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13290 // The exception-declaration shall not denote a pointer or reference to an 13291 // incomplete type, other than [cv] void*. 13292 // N2844 forbids rvalue references. 13293 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13294 Diag(Loc, diag::err_catch_rvalue_ref); 13295 Invalid = true; 13296 } 13297 13298 if (ExDeclType->isVariablyModifiedType()) { 13299 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13300 Invalid = true; 13301 } 13302 13303 QualType BaseType = ExDeclType; 13304 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13305 unsigned DK = diag::err_catch_incomplete; 13306 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13307 BaseType = Ptr->getPointeeType(); 13308 Mode = 1; 13309 DK = diag::err_catch_incomplete_ptr; 13310 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13311 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13312 BaseType = Ref->getPointeeType(); 13313 Mode = 2; 13314 DK = diag::err_catch_incomplete_ref; 13315 } 13316 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13317 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13318 Invalid = true; 13319 13320 if (!Invalid && !ExDeclType->isDependentType() && 13321 RequireNonAbstractType(Loc, ExDeclType, 13322 diag::err_abstract_type_in_decl, 13323 AbstractVariableType)) 13324 Invalid = true; 13325 13326 // Only the non-fragile NeXT runtime currently supports C++ catches 13327 // of ObjC types, and no runtime supports catching ObjC types by value. 13328 if (!Invalid && getLangOpts().ObjC1) { 13329 QualType T = ExDeclType; 13330 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13331 T = RT->getPointeeType(); 13332 13333 if (T->isObjCObjectType()) { 13334 Diag(Loc, diag::err_objc_object_catch); 13335 Invalid = true; 13336 } else if (T->isObjCObjectPointerType()) { 13337 // FIXME: should this be a test for macosx-fragile specifically? 13338 if (getLangOpts().ObjCRuntime.isFragile()) 13339 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13340 } 13341 } 13342 13343 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13344 ExDeclType, TInfo, SC_None); 13345 ExDecl->setExceptionVariable(true); 13346 13347 // In ARC, infer 'retaining' for variables of retainable type. 13348 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13349 Invalid = true; 13350 13351 if (!Invalid && !ExDeclType->isDependentType()) { 13352 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13353 // Insulate this from anything else we might currently be parsing. 13354 EnterExpressionEvaluationContext scope( 13355 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13356 13357 // C++ [except.handle]p16: 13358 // The object declared in an exception-declaration or, if the 13359 // exception-declaration does not specify a name, a temporary (12.2) is 13360 // copy-initialized (8.5) from the exception object. [...] 13361 // The object is destroyed when the handler exits, after the destruction 13362 // of any automatic objects initialized within the handler. 13363 // 13364 // We just pretend to initialize the object with itself, then make sure 13365 // it can be destroyed later. 13366 QualType initType = Context.getExceptionObjectType(ExDeclType); 13367 13368 InitializedEntity entity = 13369 InitializedEntity::InitializeVariable(ExDecl); 13370 InitializationKind initKind = 13371 InitializationKind::CreateCopy(Loc, SourceLocation()); 13372 13373 Expr *opaqueValue = 13374 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13375 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13376 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13377 if (result.isInvalid()) 13378 Invalid = true; 13379 else { 13380 // If the constructor used was non-trivial, set this as the 13381 // "initializer". 13382 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13383 if (!construct->getConstructor()->isTrivial()) { 13384 Expr *init = MaybeCreateExprWithCleanups(construct); 13385 ExDecl->setInit(init); 13386 } 13387 13388 // And make sure it's destructable. 13389 FinalizeVarWithDestructor(ExDecl, recordType); 13390 } 13391 } 13392 } 13393 13394 if (Invalid) 13395 ExDecl->setInvalidDecl(); 13396 13397 return ExDecl; 13398 } 13399 13400 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13401 /// handler. 13402 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13403 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13404 bool Invalid = D.isInvalidType(); 13405 13406 // Check for unexpanded parameter packs. 13407 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13408 UPPC_ExceptionType)) { 13409 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13410 D.getIdentifierLoc()); 13411 Invalid = true; 13412 } 13413 13414 IdentifierInfo *II = D.getIdentifier(); 13415 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13416 LookupOrdinaryName, 13417 ForVisibleRedeclaration)) { 13418 // The scope should be freshly made just for us. There is just no way 13419 // it contains any previous declaration, except for function parameters in 13420 // a function-try-block's catch statement. 13421 assert(!S->isDeclScope(PrevDecl)); 13422 if (isDeclInScope(PrevDecl, CurContext, S)) { 13423 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13424 << D.getIdentifier(); 13425 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13426 Invalid = true; 13427 } else if (PrevDecl->isTemplateParameter()) 13428 // Maybe we will complain about the shadowed template parameter. 13429 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13430 } 13431 13432 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13433 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13434 << D.getCXXScopeSpec().getRange(); 13435 Invalid = true; 13436 } 13437 13438 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13439 D.getLocStart(), 13440 D.getIdentifierLoc(), 13441 D.getIdentifier()); 13442 if (Invalid) 13443 ExDecl->setInvalidDecl(); 13444 13445 // Add the exception declaration into this scope. 13446 if (II) 13447 PushOnScopeChains(ExDecl, S); 13448 else 13449 CurContext->addDecl(ExDecl); 13450 13451 ProcessDeclAttributes(S, ExDecl, D); 13452 return ExDecl; 13453 } 13454 13455 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13456 Expr *AssertExpr, 13457 Expr *AssertMessageExpr, 13458 SourceLocation RParenLoc) { 13459 StringLiteral *AssertMessage = 13460 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13461 13462 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13463 return nullptr; 13464 13465 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13466 AssertMessage, RParenLoc, false); 13467 } 13468 13469 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13470 Expr *AssertExpr, 13471 StringLiteral *AssertMessage, 13472 SourceLocation RParenLoc, 13473 bool Failed) { 13474 assert(AssertExpr != nullptr && "Expected non-null condition"); 13475 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13476 !Failed) { 13477 // In a static_assert-declaration, the constant-expression shall be a 13478 // constant expression that can be contextually converted to bool. 13479 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13480 if (Converted.isInvalid()) 13481 Failed = true; 13482 13483 llvm::APSInt Cond; 13484 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13485 diag::err_static_assert_expression_is_not_constant, 13486 /*AllowFold=*/false).isInvalid()) 13487 Failed = true; 13488 13489 if (!Failed && !Cond) { 13490 SmallString<256> MsgBuffer; 13491 llvm::raw_svector_ostream Msg(MsgBuffer); 13492 if (AssertMessage) 13493 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13494 13495 Expr *InnerCond = nullptr; 13496 std::string InnerCondDescription; 13497 std::tie(InnerCond, InnerCondDescription) = 13498 findFailedBooleanCondition(Converted.get(), 13499 /*AllowTopLevelCond=*/false); 13500 if (InnerCond) { 13501 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13502 << InnerCondDescription << !AssertMessage 13503 << Msg.str() << InnerCond->getSourceRange(); 13504 } else { 13505 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13506 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13507 } 13508 Failed = true; 13509 } 13510 } 13511 13512 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13513 /*DiscardedValue*/false, 13514 /*IsConstexpr*/true); 13515 if (FullAssertExpr.isInvalid()) 13516 Failed = true; 13517 else 13518 AssertExpr = FullAssertExpr.get(); 13519 13520 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13521 AssertExpr, AssertMessage, RParenLoc, 13522 Failed); 13523 13524 CurContext->addDecl(Decl); 13525 return Decl; 13526 } 13527 13528 /// \brief Perform semantic analysis of the given friend type declaration. 13529 /// 13530 /// \returns A friend declaration that. 13531 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13532 SourceLocation FriendLoc, 13533 TypeSourceInfo *TSInfo) { 13534 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13535 13536 QualType T = TSInfo->getType(); 13537 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13538 13539 // C++03 [class.friend]p2: 13540 // An elaborated-type-specifier shall be used in a friend declaration 13541 // for a class.* 13542 // 13543 // * The class-key of the elaborated-type-specifier is required. 13544 if (!CodeSynthesisContexts.empty()) { 13545 // Do not complain about the form of friend template types during any kind 13546 // of code synthesis. For template instantiation, we will have complained 13547 // when the template was defined. 13548 } else { 13549 if (!T->isElaboratedTypeSpecifier()) { 13550 // If we evaluated the type to a record type, suggest putting 13551 // a tag in front. 13552 if (const RecordType *RT = T->getAs<RecordType>()) { 13553 RecordDecl *RD = RT->getDecl(); 13554 13555 SmallString<16> InsertionText(" "); 13556 InsertionText += RD->getKindName(); 13557 13558 Diag(TypeRange.getBegin(), 13559 getLangOpts().CPlusPlus11 ? 13560 diag::warn_cxx98_compat_unelaborated_friend_type : 13561 diag::ext_unelaborated_friend_type) 13562 << (unsigned) RD->getTagKind() 13563 << T 13564 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13565 InsertionText); 13566 } else { 13567 Diag(FriendLoc, 13568 getLangOpts().CPlusPlus11 ? 13569 diag::warn_cxx98_compat_nonclass_type_friend : 13570 diag::ext_nonclass_type_friend) 13571 << T 13572 << TypeRange; 13573 } 13574 } else if (T->getAs<EnumType>()) { 13575 Diag(FriendLoc, 13576 getLangOpts().CPlusPlus11 ? 13577 diag::warn_cxx98_compat_enum_friend : 13578 diag::ext_enum_friend) 13579 << T 13580 << TypeRange; 13581 } 13582 13583 // C++11 [class.friend]p3: 13584 // A friend declaration that does not declare a function shall have one 13585 // of the following forms: 13586 // friend elaborated-type-specifier ; 13587 // friend simple-type-specifier ; 13588 // friend typename-specifier ; 13589 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13590 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13591 } 13592 13593 // If the type specifier in a friend declaration designates a (possibly 13594 // cv-qualified) class type, that class is declared as a friend; otherwise, 13595 // the friend declaration is ignored. 13596 return FriendDecl::Create(Context, CurContext, 13597 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13598 FriendLoc); 13599 } 13600 13601 /// Handle a friend tag declaration where the scope specifier was 13602 /// templated. 13603 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13604 unsigned TagSpec, SourceLocation TagLoc, 13605 CXXScopeSpec &SS, 13606 IdentifierInfo *Name, 13607 SourceLocation NameLoc, 13608 AttributeList *Attr, 13609 MultiTemplateParamsArg TempParamLists) { 13610 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13611 13612 bool IsMemberSpecialization = false; 13613 bool Invalid = false; 13614 13615 if (TemplateParameterList *TemplateParams = 13616 MatchTemplateParametersToScopeSpecifier( 13617 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13618 IsMemberSpecialization, Invalid)) { 13619 if (TemplateParams->size() > 0) { 13620 // This is a declaration of a class template. 13621 if (Invalid) 13622 return nullptr; 13623 13624 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13625 NameLoc, Attr, TemplateParams, AS_public, 13626 /*ModulePrivateLoc=*/SourceLocation(), 13627 FriendLoc, TempParamLists.size() - 1, 13628 TempParamLists.data()).get(); 13629 } else { 13630 // The "template<>" header is extraneous. 13631 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13632 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13633 IsMemberSpecialization = true; 13634 } 13635 } 13636 13637 if (Invalid) return nullptr; 13638 13639 bool isAllExplicitSpecializations = true; 13640 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13641 if (TempParamLists[I]->size()) { 13642 isAllExplicitSpecializations = false; 13643 break; 13644 } 13645 } 13646 13647 // FIXME: don't ignore attributes. 13648 13649 // If it's explicit specializations all the way down, just forget 13650 // about the template header and build an appropriate non-templated 13651 // friend. TODO: for source fidelity, remember the headers. 13652 if (isAllExplicitSpecializations) { 13653 if (SS.isEmpty()) { 13654 bool Owned = false; 13655 bool IsDependent = false; 13656 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13657 Attr, AS_public, 13658 /*ModulePrivateLoc=*/SourceLocation(), 13659 MultiTemplateParamsArg(), Owned, IsDependent, 13660 /*ScopedEnumKWLoc=*/SourceLocation(), 13661 /*ScopedEnumUsesClassTag=*/false, 13662 /*UnderlyingType=*/TypeResult(), 13663 /*IsTypeSpecifier=*/false, 13664 /*IsTemplateParamOrArg=*/false); 13665 } 13666 13667 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13668 ElaboratedTypeKeyword Keyword 13669 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13670 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13671 *Name, NameLoc); 13672 if (T.isNull()) 13673 return nullptr; 13674 13675 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13676 if (isa<DependentNameType>(T)) { 13677 DependentNameTypeLoc TL = 13678 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13679 TL.setElaboratedKeywordLoc(TagLoc); 13680 TL.setQualifierLoc(QualifierLoc); 13681 TL.setNameLoc(NameLoc); 13682 } else { 13683 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13684 TL.setElaboratedKeywordLoc(TagLoc); 13685 TL.setQualifierLoc(QualifierLoc); 13686 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13687 } 13688 13689 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13690 TSI, FriendLoc, TempParamLists); 13691 Friend->setAccess(AS_public); 13692 CurContext->addDecl(Friend); 13693 return Friend; 13694 } 13695 13696 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13697 13698 13699 13700 // Handle the case of a templated-scope friend class. e.g. 13701 // template <class T> class A<T>::B; 13702 // FIXME: we don't support these right now. 13703 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13704 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13705 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13706 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13707 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13708 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13709 TL.setElaboratedKeywordLoc(TagLoc); 13710 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13711 TL.setNameLoc(NameLoc); 13712 13713 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13714 TSI, FriendLoc, TempParamLists); 13715 Friend->setAccess(AS_public); 13716 Friend->setUnsupportedFriend(true); 13717 CurContext->addDecl(Friend); 13718 return Friend; 13719 } 13720 13721 13722 /// Handle a friend type declaration. This works in tandem with 13723 /// ActOnTag. 13724 /// 13725 /// Notes on friend class templates: 13726 /// 13727 /// We generally treat friend class declarations as if they were 13728 /// declaring a class. So, for example, the elaborated type specifier 13729 /// in a friend declaration is required to obey the restrictions of a 13730 /// class-head (i.e. no typedefs in the scope chain), template 13731 /// parameters are required to match up with simple template-ids, &c. 13732 /// However, unlike when declaring a template specialization, it's 13733 /// okay to refer to a template specialization without an empty 13734 /// template parameter declaration, e.g. 13735 /// friend class A<T>::B<unsigned>; 13736 /// We permit this as a special case; if there are any template 13737 /// parameters present at all, require proper matching, i.e. 13738 /// template <> template \<class T> friend class A<int>::B; 13739 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13740 MultiTemplateParamsArg TempParams) { 13741 SourceLocation Loc = DS.getLocStart(); 13742 13743 assert(DS.isFriendSpecified()); 13744 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13745 13746 // Try to convert the decl specifier to a type. This works for 13747 // friend templates because ActOnTag never produces a ClassTemplateDecl 13748 // for a TUK_Friend. 13749 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 13750 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13751 QualType T = TSI->getType(); 13752 if (TheDeclarator.isInvalidType()) 13753 return nullptr; 13754 13755 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13756 return nullptr; 13757 13758 // This is definitely an error in C++98. It's probably meant to 13759 // be forbidden in C++0x, too, but the specification is just 13760 // poorly written. 13761 // 13762 // The problem is with declarations like the following: 13763 // template <T> friend A<T>::foo; 13764 // where deciding whether a class C is a friend or not now hinges 13765 // on whether there exists an instantiation of A that causes 13766 // 'foo' to equal C. There are restrictions on class-heads 13767 // (which we declare (by fiat) elaborated friend declarations to 13768 // be) that makes this tractable. 13769 // 13770 // FIXME: handle "template <> friend class A<T>;", which 13771 // is possibly well-formed? Who even knows? 13772 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13773 Diag(Loc, diag::err_tagless_friend_type_template) 13774 << DS.getSourceRange(); 13775 return nullptr; 13776 } 13777 13778 // C++98 [class.friend]p1: A friend of a class is a function 13779 // or class that is not a member of the class . . . 13780 // This is fixed in DR77, which just barely didn't make the C++03 13781 // deadline. It's also a very silly restriction that seriously 13782 // affects inner classes and which nobody else seems to implement; 13783 // thus we never diagnose it, not even in -pedantic. 13784 // 13785 // But note that we could warn about it: it's always useless to 13786 // friend one of your own members (it's not, however, worthless to 13787 // friend a member of an arbitrary specialization of your template). 13788 13789 Decl *D; 13790 if (!TempParams.empty()) 13791 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13792 TempParams, 13793 TSI, 13794 DS.getFriendSpecLoc()); 13795 else 13796 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13797 13798 if (!D) 13799 return nullptr; 13800 13801 D->setAccess(AS_public); 13802 CurContext->addDecl(D); 13803 13804 return D; 13805 } 13806 13807 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13808 MultiTemplateParamsArg TemplateParams) { 13809 const DeclSpec &DS = D.getDeclSpec(); 13810 13811 assert(DS.isFriendSpecified()); 13812 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13813 13814 SourceLocation Loc = D.getIdentifierLoc(); 13815 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13816 13817 // C++ [class.friend]p1 13818 // A friend of a class is a function or class.... 13819 // Note that this sees through typedefs, which is intended. 13820 // It *doesn't* see through dependent types, which is correct 13821 // according to [temp.arg.type]p3: 13822 // If a declaration acquires a function type through a 13823 // type dependent on a template-parameter and this causes 13824 // a declaration that does not use the syntactic form of a 13825 // function declarator to have a function type, the program 13826 // is ill-formed. 13827 if (!TInfo->getType()->isFunctionType()) { 13828 Diag(Loc, diag::err_unexpected_friend); 13829 13830 // It might be worthwhile to try to recover by creating an 13831 // appropriate declaration. 13832 return nullptr; 13833 } 13834 13835 // C++ [namespace.memdef]p3 13836 // - If a friend declaration in a non-local class first declares a 13837 // class or function, the friend class or function is a member 13838 // of the innermost enclosing namespace. 13839 // - The name of the friend is not found by simple name lookup 13840 // until a matching declaration is provided in that namespace 13841 // scope (either before or after the class declaration granting 13842 // friendship). 13843 // - If a friend function is called, its name may be found by the 13844 // name lookup that considers functions from namespaces and 13845 // classes associated with the types of the function arguments. 13846 // - When looking for a prior declaration of a class or a function 13847 // declared as a friend, scopes outside the innermost enclosing 13848 // namespace scope are not considered. 13849 13850 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13851 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13852 DeclarationName Name = NameInfo.getName(); 13853 assert(Name); 13854 13855 // Check for unexpanded parameter packs. 13856 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13857 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13858 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13859 return nullptr; 13860 13861 // The context we found the declaration in, or in which we should 13862 // create the declaration. 13863 DeclContext *DC; 13864 Scope *DCScope = S; 13865 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13866 ForExternalRedeclaration); 13867 13868 // There are five cases here. 13869 // - There's no scope specifier and we're in a local class. Only look 13870 // for functions declared in the immediately-enclosing block scope. 13871 // We recover from invalid scope qualifiers as if they just weren't there. 13872 FunctionDecl *FunctionContainingLocalClass = nullptr; 13873 if ((SS.isInvalid() || !SS.isSet()) && 13874 (FunctionContainingLocalClass = 13875 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13876 // C++11 [class.friend]p11: 13877 // If a friend declaration appears in a local class and the name 13878 // specified is an unqualified name, a prior declaration is 13879 // looked up without considering scopes that are outside the 13880 // innermost enclosing non-class scope. For a friend function 13881 // declaration, if there is no prior declaration, the program is 13882 // ill-formed. 13883 13884 // Find the innermost enclosing non-class scope. This is the block 13885 // scope containing the local class definition (or for a nested class, 13886 // the outer local class). 13887 DCScope = S->getFnParent(); 13888 13889 // Look up the function name in the scope. 13890 Previous.clear(LookupLocalFriendName); 13891 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13892 13893 if (!Previous.empty()) { 13894 // All possible previous declarations must have the same context: 13895 // either they were declared at block scope or they are members of 13896 // one of the enclosing local classes. 13897 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13898 } else { 13899 // This is ill-formed, but provide the context that we would have 13900 // declared the function in, if we were permitted to, for error recovery. 13901 DC = FunctionContainingLocalClass; 13902 } 13903 adjustContextForLocalExternDecl(DC); 13904 13905 // C++ [class.friend]p6: 13906 // A function can be defined in a friend declaration of a class if and 13907 // only if the class is a non-local class (9.8), the function name is 13908 // unqualified, and the function has namespace scope. 13909 if (D.isFunctionDefinition()) { 13910 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13911 } 13912 13913 // - There's no scope specifier, in which case we just go to the 13914 // appropriate scope and look for a function or function template 13915 // there as appropriate. 13916 } else if (SS.isInvalid() || !SS.isSet()) { 13917 // C++11 [namespace.memdef]p3: 13918 // If the name in a friend declaration is neither qualified nor 13919 // a template-id and the declaration is a function or an 13920 // elaborated-type-specifier, the lookup to determine whether 13921 // the entity has been previously declared shall not consider 13922 // any scopes outside the innermost enclosing namespace. 13923 bool isTemplateId = 13924 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 13925 13926 // Find the appropriate context according to the above. 13927 DC = CurContext; 13928 13929 // Skip class contexts. If someone can cite chapter and verse 13930 // for this behavior, that would be nice --- it's what GCC and 13931 // EDG do, and it seems like a reasonable intent, but the spec 13932 // really only says that checks for unqualified existing 13933 // declarations should stop at the nearest enclosing namespace, 13934 // not that they should only consider the nearest enclosing 13935 // namespace. 13936 while (DC->isRecord()) 13937 DC = DC->getParent(); 13938 13939 DeclContext *LookupDC = DC; 13940 while (LookupDC->isTransparentContext()) 13941 LookupDC = LookupDC->getParent(); 13942 13943 while (true) { 13944 LookupQualifiedName(Previous, LookupDC); 13945 13946 if (!Previous.empty()) { 13947 DC = LookupDC; 13948 break; 13949 } 13950 13951 if (isTemplateId) { 13952 if (isa<TranslationUnitDecl>(LookupDC)) break; 13953 } else { 13954 if (LookupDC->isFileContext()) break; 13955 } 13956 LookupDC = LookupDC->getParent(); 13957 } 13958 13959 DCScope = getScopeForDeclContext(S, DC); 13960 13961 // - There's a non-dependent scope specifier, in which case we 13962 // compute it and do a previous lookup there for a function 13963 // or function template. 13964 } else if (!SS.getScopeRep()->isDependent()) { 13965 DC = computeDeclContext(SS); 13966 if (!DC) return nullptr; 13967 13968 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13969 13970 LookupQualifiedName(Previous, DC); 13971 13972 // Ignore things found implicitly in the wrong scope. 13973 // TODO: better diagnostics for this case. Suggesting the right 13974 // qualified scope would be nice... 13975 LookupResult::Filter F = Previous.makeFilter(); 13976 while (F.hasNext()) { 13977 NamedDecl *D = F.next(); 13978 if (!DC->InEnclosingNamespaceSetOf( 13979 D->getDeclContext()->getRedeclContext())) 13980 F.erase(); 13981 } 13982 F.done(); 13983 13984 if (Previous.empty()) { 13985 D.setInvalidType(); 13986 Diag(Loc, diag::err_qualified_friend_not_found) 13987 << Name << TInfo->getType(); 13988 return nullptr; 13989 } 13990 13991 // C++ [class.friend]p1: A friend of a class is a function or 13992 // class that is not a member of the class . . . 13993 if (DC->Equals(CurContext)) 13994 Diag(DS.getFriendSpecLoc(), 13995 getLangOpts().CPlusPlus11 ? 13996 diag::warn_cxx98_compat_friend_is_member : 13997 diag::err_friend_is_member); 13998 13999 if (D.isFunctionDefinition()) { 14000 // C++ [class.friend]p6: 14001 // A function can be defined in a friend declaration of a class if and 14002 // only if the class is a non-local class (9.8), the function name is 14003 // unqualified, and the function has namespace scope. 14004 SemaDiagnosticBuilder DB 14005 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14006 14007 DB << SS.getScopeRep(); 14008 if (DC->isFileContext()) 14009 DB << FixItHint::CreateRemoval(SS.getRange()); 14010 SS.clear(); 14011 } 14012 14013 // - There's a scope specifier that does not match any template 14014 // parameter lists, in which case we use some arbitrary context, 14015 // create a method or method template, and wait for instantiation. 14016 // - There's a scope specifier that does match some template 14017 // parameter lists, which we don't handle right now. 14018 } else { 14019 if (D.isFunctionDefinition()) { 14020 // C++ [class.friend]p6: 14021 // A function can be defined in a friend declaration of a class if and 14022 // only if the class is a non-local class (9.8), the function name is 14023 // unqualified, and the function has namespace scope. 14024 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14025 << SS.getScopeRep(); 14026 } 14027 14028 DC = CurContext; 14029 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14030 } 14031 14032 if (!DC->isRecord()) { 14033 int DiagArg = -1; 14034 switch (D.getName().getKind()) { 14035 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14036 case UnqualifiedIdKind::IK_ConstructorName: 14037 DiagArg = 0; 14038 break; 14039 case UnqualifiedIdKind::IK_DestructorName: 14040 DiagArg = 1; 14041 break; 14042 case UnqualifiedIdKind::IK_ConversionFunctionId: 14043 DiagArg = 2; 14044 break; 14045 case UnqualifiedIdKind::IK_DeductionGuideName: 14046 DiagArg = 3; 14047 break; 14048 case UnqualifiedIdKind::IK_Identifier: 14049 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14050 case UnqualifiedIdKind::IK_LiteralOperatorId: 14051 case UnqualifiedIdKind::IK_OperatorFunctionId: 14052 case UnqualifiedIdKind::IK_TemplateId: 14053 break; 14054 } 14055 // This implies that it has to be an operator or function. 14056 if (DiagArg >= 0) { 14057 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14058 return nullptr; 14059 } 14060 } 14061 14062 // FIXME: This is an egregious hack to cope with cases where the scope stack 14063 // does not contain the declaration context, i.e., in an out-of-line 14064 // definition of a class. 14065 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14066 if (!DCScope) { 14067 FakeDCScope.setEntity(DC); 14068 DCScope = &FakeDCScope; 14069 } 14070 14071 bool AddToScope = true; 14072 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14073 TemplateParams, AddToScope); 14074 if (!ND) return nullptr; 14075 14076 assert(ND->getLexicalDeclContext() == CurContext); 14077 14078 // If we performed typo correction, we might have added a scope specifier 14079 // and changed the decl context. 14080 DC = ND->getDeclContext(); 14081 14082 // Add the function declaration to the appropriate lookup tables, 14083 // adjusting the redeclarations list as necessary. We don't 14084 // want to do this yet if the friending class is dependent. 14085 // 14086 // Also update the scope-based lookup if the target context's 14087 // lookup context is in lexical scope. 14088 if (!CurContext->isDependentContext()) { 14089 DC = DC->getRedeclContext(); 14090 DC->makeDeclVisibleInContext(ND); 14091 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14092 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14093 } 14094 14095 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14096 D.getIdentifierLoc(), ND, 14097 DS.getFriendSpecLoc()); 14098 FrD->setAccess(AS_public); 14099 CurContext->addDecl(FrD); 14100 14101 if (ND->isInvalidDecl()) { 14102 FrD->setInvalidDecl(); 14103 } else { 14104 if (DC->isRecord()) CheckFriendAccess(ND); 14105 14106 FunctionDecl *FD; 14107 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14108 FD = FTD->getTemplatedDecl(); 14109 else 14110 FD = cast<FunctionDecl>(ND); 14111 14112 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14113 // default argument expression, that declaration shall be a definition 14114 // and shall be the only declaration of the function or function 14115 // template in the translation unit. 14116 if (functionDeclHasDefaultArgument(FD)) { 14117 // We can't look at FD->getPreviousDecl() because it may not have been set 14118 // if we're in a dependent context. If the function is known to be a 14119 // redeclaration, we will have narrowed Previous down to the right decl. 14120 if (D.isRedeclaration()) { 14121 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14122 Diag(Previous.getRepresentativeDecl()->getLocation(), 14123 diag::note_previous_declaration); 14124 } else if (!D.isFunctionDefinition()) 14125 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14126 } 14127 14128 // Mark templated-scope function declarations as unsupported. 14129 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14130 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14131 << SS.getScopeRep() << SS.getRange() 14132 << cast<CXXRecordDecl>(CurContext); 14133 FrD->setUnsupportedFriend(true); 14134 } 14135 } 14136 14137 return ND; 14138 } 14139 14140 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14141 AdjustDeclIfTemplate(Dcl); 14142 14143 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14144 if (!Fn) { 14145 Diag(DelLoc, diag::err_deleted_non_function); 14146 return; 14147 } 14148 14149 // Deleted function does not have a body. 14150 Fn->setWillHaveBody(false); 14151 14152 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14153 // Don't consider the implicit declaration we generate for explicit 14154 // specializations. FIXME: Do not generate these implicit declarations. 14155 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14156 Prev->getPreviousDecl()) && 14157 !Prev->isDefined()) { 14158 Diag(DelLoc, diag::err_deleted_decl_not_first); 14159 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14160 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14161 : diag::note_previous_declaration); 14162 } 14163 // If the declaration wasn't the first, we delete the function anyway for 14164 // recovery. 14165 Fn = Fn->getCanonicalDecl(); 14166 } 14167 14168 // dllimport/dllexport cannot be deleted. 14169 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14170 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14171 Fn->setInvalidDecl(); 14172 } 14173 14174 if (Fn->isDeleted()) 14175 return; 14176 14177 // See if we're deleting a function which is already known to override a 14178 // non-deleted virtual function. 14179 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14180 bool IssuedDiagnostic = false; 14181 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14182 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14183 if (!IssuedDiagnostic) { 14184 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14185 IssuedDiagnostic = true; 14186 } 14187 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14188 } 14189 } 14190 // If this function was implicitly deleted because it was defaulted, 14191 // explain why it was deleted. 14192 if (IssuedDiagnostic && MD->isDefaulted()) 14193 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14194 /*Diagnose*/true); 14195 } 14196 14197 // C++11 [basic.start.main]p3: 14198 // A program that defines main as deleted [...] is ill-formed. 14199 if (Fn->isMain()) 14200 Diag(DelLoc, diag::err_deleted_main); 14201 14202 // C++11 [dcl.fct.def.delete]p4: 14203 // A deleted function is implicitly inline. 14204 Fn->setImplicitlyInline(); 14205 Fn->setDeletedAsWritten(); 14206 } 14207 14208 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14209 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14210 14211 if (MD) { 14212 if (MD->getParent()->isDependentType()) { 14213 MD->setDefaulted(); 14214 MD->setExplicitlyDefaulted(); 14215 return; 14216 } 14217 14218 CXXSpecialMember Member = getSpecialMember(MD); 14219 if (Member == CXXInvalid) { 14220 if (!MD->isInvalidDecl()) 14221 Diag(DefaultLoc, diag::err_default_special_members); 14222 return; 14223 } 14224 14225 MD->setDefaulted(); 14226 MD->setExplicitlyDefaulted(); 14227 14228 // Unset that we will have a body for this function. We might not, 14229 // if it turns out to be trivial, and we don't need this marking now 14230 // that we've marked it as defaulted. 14231 MD->setWillHaveBody(false); 14232 14233 // If this definition appears within the record, do the checking when 14234 // the record is complete. 14235 const FunctionDecl *Primary = MD; 14236 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14237 // Ask the template instantiation pattern that actually had the 14238 // '= default' on it. 14239 Primary = Pattern; 14240 14241 // If the method was defaulted on its first declaration, we will have 14242 // already performed the checking in CheckCompletedCXXClass. Such a 14243 // declaration doesn't trigger an implicit definition. 14244 if (Primary->getCanonicalDecl()->isDefaulted()) 14245 return; 14246 14247 CheckExplicitlyDefaultedSpecialMember(MD); 14248 14249 if (!MD->isInvalidDecl()) 14250 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14251 } else { 14252 Diag(DefaultLoc, diag::err_default_special_members); 14253 } 14254 } 14255 14256 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14257 for (Stmt *SubStmt : S->children()) { 14258 if (!SubStmt) 14259 continue; 14260 if (isa<ReturnStmt>(SubStmt)) 14261 Self.Diag(SubStmt->getLocStart(), 14262 diag::err_return_in_constructor_handler); 14263 if (!isa<Expr>(SubStmt)) 14264 SearchForReturnInStmt(Self, SubStmt); 14265 } 14266 } 14267 14268 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14269 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14270 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14271 SearchForReturnInStmt(*this, Handler); 14272 } 14273 } 14274 14275 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14276 const CXXMethodDecl *Old) { 14277 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14278 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14279 14280 if (OldFT->hasExtParameterInfos()) { 14281 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14282 // A parameter of the overriding method should be annotated with noescape 14283 // if the corresponding parameter of the overridden method is annotated. 14284 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14285 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14286 Diag(New->getParamDecl(I)->getLocation(), 14287 diag::warn_overriding_method_missing_noescape); 14288 Diag(Old->getParamDecl(I)->getLocation(), 14289 diag::note_overridden_marked_noescape); 14290 } 14291 } 14292 14293 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14294 14295 // If the calling conventions match, everything is fine 14296 if (NewCC == OldCC) 14297 return false; 14298 14299 // If the calling conventions mismatch because the new function is static, 14300 // suppress the calling convention mismatch error; the error about static 14301 // function override (err_static_overrides_virtual from 14302 // Sema::CheckFunctionDeclaration) is more clear. 14303 if (New->getStorageClass() == SC_Static) 14304 return false; 14305 14306 Diag(New->getLocation(), 14307 diag::err_conflicting_overriding_cc_attributes) 14308 << New->getDeclName() << New->getType() << Old->getType(); 14309 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14310 return true; 14311 } 14312 14313 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14314 const CXXMethodDecl *Old) { 14315 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14316 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14317 14318 if (Context.hasSameType(NewTy, OldTy) || 14319 NewTy->isDependentType() || OldTy->isDependentType()) 14320 return false; 14321 14322 // Check if the return types are covariant 14323 QualType NewClassTy, OldClassTy; 14324 14325 /// Both types must be pointers or references to classes. 14326 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14327 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14328 NewClassTy = NewPT->getPointeeType(); 14329 OldClassTy = OldPT->getPointeeType(); 14330 } 14331 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14332 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14333 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14334 NewClassTy = NewRT->getPointeeType(); 14335 OldClassTy = OldRT->getPointeeType(); 14336 } 14337 } 14338 } 14339 14340 // The return types aren't either both pointers or references to a class type. 14341 if (NewClassTy.isNull()) { 14342 Diag(New->getLocation(), 14343 diag::err_different_return_type_for_overriding_virtual_function) 14344 << New->getDeclName() << NewTy << OldTy 14345 << New->getReturnTypeSourceRange(); 14346 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14347 << Old->getReturnTypeSourceRange(); 14348 14349 return true; 14350 } 14351 14352 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14353 // C++14 [class.virtual]p8: 14354 // If the class type in the covariant return type of D::f differs from 14355 // that of B::f, the class type in the return type of D::f shall be 14356 // complete at the point of declaration of D::f or shall be the class 14357 // type D. 14358 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14359 if (!RT->isBeingDefined() && 14360 RequireCompleteType(New->getLocation(), NewClassTy, 14361 diag::err_covariant_return_incomplete, 14362 New->getDeclName())) 14363 return true; 14364 } 14365 14366 // Check if the new class derives from the old class. 14367 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14368 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14369 << New->getDeclName() << NewTy << OldTy 14370 << New->getReturnTypeSourceRange(); 14371 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14372 << Old->getReturnTypeSourceRange(); 14373 return true; 14374 } 14375 14376 // Check if we the conversion from derived to base is valid. 14377 if (CheckDerivedToBaseConversion( 14378 NewClassTy, OldClassTy, 14379 diag::err_covariant_return_inaccessible_base, 14380 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14381 New->getLocation(), New->getReturnTypeSourceRange(), 14382 New->getDeclName(), nullptr)) { 14383 // FIXME: this note won't trigger for delayed access control 14384 // diagnostics, and it's impossible to get an undelayed error 14385 // here from access control during the original parse because 14386 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14387 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14388 << Old->getReturnTypeSourceRange(); 14389 return true; 14390 } 14391 } 14392 14393 // The qualifiers of the return types must be the same. 14394 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14395 Diag(New->getLocation(), 14396 diag::err_covariant_return_type_different_qualifications) 14397 << New->getDeclName() << NewTy << OldTy 14398 << New->getReturnTypeSourceRange(); 14399 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14400 << Old->getReturnTypeSourceRange(); 14401 return true; 14402 } 14403 14404 14405 // The new class type must have the same or less qualifiers as the old type. 14406 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14407 Diag(New->getLocation(), 14408 diag::err_covariant_return_type_class_type_more_qualified) 14409 << New->getDeclName() << NewTy << OldTy 14410 << New->getReturnTypeSourceRange(); 14411 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14412 << Old->getReturnTypeSourceRange(); 14413 return true; 14414 } 14415 14416 return false; 14417 } 14418 14419 /// \brief Mark the given method pure. 14420 /// 14421 /// \param Method the method to be marked pure. 14422 /// 14423 /// \param InitRange the source range that covers the "0" initializer. 14424 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14425 SourceLocation EndLoc = InitRange.getEnd(); 14426 if (EndLoc.isValid()) 14427 Method->setRangeEnd(EndLoc); 14428 14429 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14430 Method->setPure(); 14431 return false; 14432 } 14433 14434 if (!Method->isInvalidDecl()) 14435 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14436 << Method->getDeclName() << InitRange; 14437 return true; 14438 } 14439 14440 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14441 if (D->getFriendObjectKind()) 14442 Diag(D->getLocation(), diag::err_pure_friend); 14443 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14444 CheckPureMethod(M, ZeroLoc); 14445 else 14446 Diag(D->getLocation(), diag::err_illegal_initializer); 14447 } 14448 14449 /// \brief Determine whether the given declaration is a global variable or 14450 /// static data member. 14451 static bool isNonlocalVariable(const Decl *D) { 14452 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14453 return Var->hasGlobalStorage(); 14454 14455 return false; 14456 } 14457 14458 /// Invoked when we are about to parse an initializer for the declaration 14459 /// 'Dcl'. 14460 /// 14461 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14462 /// static data member of class X, names should be looked up in the scope of 14463 /// class X. If the declaration had a scope specifier, a scope will have 14464 /// been created and passed in for this purpose. Otherwise, S will be null. 14465 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14466 // If there is no declaration, there was an error parsing it. 14467 if (!D || D->isInvalidDecl()) 14468 return; 14469 14470 // We will always have a nested name specifier here, but this declaration 14471 // might not be out of line if the specifier names the current namespace: 14472 // extern int n; 14473 // int ::n = 0; 14474 if (S && D->isOutOfLine()) 14475 EnterDeclaratorContext(S, D->getDeclContext()); 14476 14477 // If we are parsing the initializer for a static data member, push a 14478 // new expression evaluation context that is associated with this static 14479 // data member. 14480 if (isNonlocalVariable(D)) 14481 PushExpressionEvaluationContext( 14482 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14483 } 14484 14485 /// Invoked after we are finished parsing an initializer for the declaration D. 14486 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14487 // If there is no declaration, there was an error parsing it. 14488 if (!D || D->isInvalidDecl()) 14489 return; 14490 14491 if (isNonlocalVariable(D)) 14492 PopExpressionEvaluationContext(); 14493 14494 if (S && D->isOutOfLine()) 14495 ExitDeclaratorContext(S); 14496 } 14497 14498 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14499 /// C++ if/switch/while/for statement. 14500 /// e.g: "if (int x = f()) {...}" 14501 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14502 // C++ 6.4p2: 14503 // The declarator shall not specify a function or an array. 14504 // The type-specifier-seq shall not contain typedef and shall not declare a 14505 // new class or enumeration. 14506 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14507 "Parser allowed 'typedef' as storage class of condition decl."); 14508 14509 Decl *Dcl = ActOnDeclarator(S, D); 14510 if (!Dcl) 14511 return true; 14512 14513 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14514 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14515 << D.getSourceRange(); 14516 return true; 14517 } 14518 14519 return Dcl; 14520 } 14521 14522 void Sema::LoadExternalVTableUses() { 14523 if (!ExternalSource) 14524 return; 14525 14526 SmallVector<ExternalVTableUse, 4> VTables; 14527 ExternalSource->ReadUsedVTables(VTables); 14528 SmallVector<VTableUse, 4> NewUses; 14529 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14530 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14531 = VTablesUsed.find(VTables[I].Record); 14532 // Even if a definition wasn't required before, it may be required now. 14533 if (Pos != VTablesUsed.end()) { 14534 if (!Pos->second && VTables[I].DefinitionRequired) 14535 Pos->second = true; 14536 continue; 14537 } 14538 14539 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14540 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14541 } 14542 14543 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14544 } 14545 14546 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14547 bool DefinitionRequired) { 14548 // Ignore any vtable uses in unevaluated operands or for classes that do 14549 // not have a vtable. 14550 if (!Class->isDynamicClass() || Class->isDependentContext() || 14551 CurContext->isDependentContext() || isUnevaluatedContext()) 14552 return; 14553 14554 // Try to insert this class into the map. 14555 LoadExternalVTableUses(); 14556 Class = Class->getCanonicalDecl(); 14557 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14558 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14559 if (!Pos.second) { 14560 // If we already had an entry, check to see if we are promoting this vtable 14561 // to require a definition. If so, we need to reappend to the VTableUses 14562 // list, since we may have already processed the first entry. 14563 if (DefinitionRequired && !Pos.first->second) { 14564 Pos.first->second = true; 14565 } else { 14566 // Otherwise, we can early exit. 14567 return; 14568 } 14569 } else { 14570 // The Microsoft ABI requires that we perform the destructor body 14571 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14572 // the deleting destructor is emitted with the vtable, not with the 14573 // destructor definition as in the Itanium ABI. 14574 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14575 CXXDestructorDecl *DD = Class->getDestructor(); 14576 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14577 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14578 // If this is an out-of-line declaration, marking it referenced will 14579 // not do anything. Manually call CheckDestructor to look up operator 14580 // delete(). 14581 ContextRAII SavedContext(*this, DD); 14582 CheckDestructor(DD); 14583 } else { 14584 MarkFunctionReferenced(Loc, Class->getDestructor()); 14585 } 14586 } 14587 } 14588 } 14589 14590 // Local classes need to have their virtual members marked 14591 // immediately. For all other classes, we mark their virtual members 14592 // at the end of the translation unit. 14593 if (Class->isLocalClass()) 14594 MarkVirtualMembersReferenced(Loc, Class); 14595 else 14596 VTableUses.push_back(std::make_pair(Class, Loc)); 14597 } 14598 14599 bool Sema::DefineUsedVTables() { 14600 LoadExternalVTableUses(); 14601 if (VTableUses.empty()) 14602 return false; 14603 14604 // Note: The VTableUses vector could grow as a result of marking 14605 // the members of a class as "used", so we check the size each 14606 // time through the loop and prefer indices (which are stable) to 14607 // iterators (which are not). 14608 bool DefinedAnything = false; 14609 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14610 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14611 if (!Class) 14612 continue; 14613 TemplateSpecializationKind ClassTSK = 14614 Class->getTemplateSpecializationKind(); 14615 14616 SourceLocation Loc = VTableUses[I].second; 14617 14618 bool DefineVTable = true; 14619 14620 // If this class has a key function, but that key function is 14621 // defined in another translation unit, we don't need to emit the 14622 // vtable even though we're using it. 14623 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14624 if (KeyFunction && !KeyFunction->hasBody()) { 14625 // The key function is in another translation unit. 14626 DefineVTable = false; 14627 TemplateSpecializationKind TSK = 14628 KeyFunction->getTemplateSpecializationKind(); 14629 assert(TSK != TSK_ExplicitInstantiationDefinition && 14630 TSK != TSK_ImplicitInstantiation && 14631 "Instantiations don't have key functions"); 14632 (void)TSK; 14633 } else if (!KeyFunction) { 14634 // If we have a class with no key function that is the subject 14635 // of an explicit instantiation declaration, suppress the 14636 // vtable; it will live with the explicit instantiation 14637 // definition. 14638 bool IsExplicitInstantiationDeclaration = 14639 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14640 for (auto R : Class->redecls()) { 14641 TemplateSpecializationKind TSK 14642 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14643 if (TSK == TSK_ExplicitInstantiationDeclaration) 14644 IsExplicitInstantiationDeclaration = true; 14645 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14646 IsExplicitInstantiationDeclaration = false; 14647 break; 14648 } 14649 } 14650 14651 if (IsExplicitInstantiationDeclaration) 14652 DefineVTable = false; 14653 } 14654 14655 // The exception specifications for all virtual members may be needed even 14656 // if we are not providing an authoritative form of the vtable in this TU. 14657 // We may choose to emit it available_externally anyway. 14658 if (!DefineVTable) { 14659 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14660 continue; 14661 } 14662 14663 // Mark all of the virtual members of this class as referenced, so 14664 // that we can build a vtable. Then, tell the AST consumer that a 14665 // vtable for this class is required. 14666 DefinedAnything = true; 14667 MarkVirtualMembersReferenced(Loc, Class); 14668 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 14669 if (VTablesUsed[Canonical]) 14670 Consumer.HandleVTable(Class); 14671 14672 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14673 // no key function or the key function is inlined. Don't warn in C++ ABIs 14674 // that lack key functions, since the user won't be able to make one. 14675 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14676 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14677 const FunctionDecl *KeyFunctionDef = nullptr; 14678 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14679 KeyFunctionDef->isInlined())) { 14680 Diag(Class->getLocation(), 14681 ClassTSK == TSK_ExplicitInstantiationDefinition 14682 ? diag::warn_weak_template_vtable 14683 : diag::warn_weak_vtable) 14684 << Class; 14685 } 14686 } 14687 } 14688 VTableUses.clear(); 14689 14690 return DefinedAnything; 14691 } 14692 14693 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14694 const CXXRecordDecl *RD) { 14695 for (const auto *I : RD->methods()) 14696 if (I->isVirtual() && !I->isPure()) 14697 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14698 } 14699 14700 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14701 const CXXRecordDecl *RD) { 14702 // Mark all functions which will appear in RD's vtable as used. 14703 CXXFinalOverriderMap FinalOverriders; 14704 RD->getFinalOverriders(FinalOverriders); 14705 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14706 E = FinalOverriders.end(); 14707 I != E; ++I) { 14708 for (OverridingMethods::const_iterator OI = I->second.begin(), 14709 OE = I->second.end(); 14710 OI != OE; ++OI) { 14711 assert(OI->second.size() > 0 && "no final overrider"); 14712 CXXMethodDecl *Overrider = OI->second.front().Method; 14713 14714 // C++ [basic.def.odr]p2: 14715 // [...] A virtual member function is used if it is not pure. [...] 14716 if (!Overrider->isPure()) 14717 MarkFunctionReferenced(Loc, Overrider); 14718 } 14719 } 14720 14721 // Only classes that have virtual bases need a VTT. 14722 if (RD->getNumVBases() == 0) 14723 return; 14724 14725 for (const auto &I : RD->bases()) { 14726 const CXXRecordDecl *Base = 14727 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14728 if (Base->getNumVBases() == 0) 14729 continue; 14730 MarkVirtualMembersReferenced(Loc, Base); 14731 } 14732 } 14733 14734 /// SetIvarInitializers - This routine builds initialization ASTs for the 14735 /// Objective-C implementation whose ivars need be initialized. 14736 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14737 if (!getLangOpts().CPlusPlus) 14738 return; 14739 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14740 SmallVector<ObjCIvarDecl*, 8> ivars; 14741 CollectIvarsToConstructOrDestruct(OID, ivars); 14742 if (ivars.empty()) 14743 return; 14744 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14745 for (unsigned i = 0; i < ivars.size(); i++) { 14746 FieldDecl *Field = ivars[i]; 14747 if (Field->isInvalidDecl()) 14748 continue; 14749 14750 CXXCtorInitializer *Member; 14751 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14752 InitializationKind InitKind = 14753 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14754 14755 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14756 ExprResult MemberInit = 14757 InitSeq.Perform(*this, InitEntity, InitKind, None); 14758 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14759 // Note, MemberInit could actually come back empty if no initialization 14760 // is required (e.g., because it would call a trivial default constructor) 14761 if (!MemberInit.get() || MemberInit.isInvalid()) 14762 continue; 14763 14764 Member = 14765 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14766 SourceLocation(), 14767 MemberInit.getAs<Expr>(), 14768 SourceLocation()); 14769 AllToInit.push_back(Member); 14770 14771 // Be sure that the destructor is accessible and is marked as referenced. 14772 if (const RecordType *RecordTy = 14773 Context.getBaseElementType(Field->getType()) 14774 ->getAs<RecordType>()) { 14775 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14776 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14777 MarkFunctionReferenced(Field->getLocation(), Destructor); 14778 CheckDestructorAccess(Field->getLocation(), Destructor, 14779 PDiag(diag::err_access_dtor_ivar) 14780 << Context.getBaseElementType(Field->getType())); 14781 } 14782 } 14783 } 14784 ObjCImplementation->setIvarInitializers(Context, 14785 AllToInit.data(), AllToInit.size()); 14786 } 14787 } 14788 14789 static 14790 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14791 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14792 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14793 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14794 Sema &S) { 14795 if (Ctor->isInvalidDecl()) 14796 return; 14797 14798 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14799 14800 // Target may not be determinable yet, for instance if this is a dependent 14801 // call in an uninstantiated template. 14802 if (Target) { 14803 const FunctionDecl *FNTarget = nullptr; 14804 (void)Target->hasBody(FNTarget); 14805 Target = const_cast<CXXConstructorDecl*>( 14806 cast_or_null<CXXConstructorDecl>(FNTarget)); 14807 } 14808 14809 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14810 // Avoid dereferencing a null pointer here. 14811 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14812 14813 if (!Current.insert(Canonical).second) 14814 return; 14815 14816 // We know that beyond here, we aren't chaining into a cycle. 14817 if (!Target || !Target->isDelegatingConstructor() || 14818 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14819 Valid.insert(Current.begin(), Current.end()); 14820 Current.clear(); 14821 // We've hit a cycle. 14822 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14823 Current.count(TCanonical)) { 14824 // If we haven't diagnosed this cycle yet, do so now. 14825 if (!Invalid.count(TCanonical)) { 14826 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14827 diag::warn_delegating_ctor_cycle) 14828 << Ctor; 14829 14830 // Don't add a note for a function delegating directly to itself. 14831 if (TCanonical != Canonical) 14832 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14833 14834 CXXConstructorDecl *C = Target; 14835 while (C->getCanonicalDecl() != Canonical) { 14836 const FunctionDecl *FNTarget = nullptr; 14837 (void)C->getTargetConstructor()->hasBody(FNTarget); 14838 assert(FNTarget && "Ctor cycle through bodiless function"); 14839 14840 C = const_cast<CXXConstructorDecl*>( 14841 cast<CXXConstructorDecl>(FNTarget)); 14842 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14843 } 14844 } 14845 14846 Invalid.insert(Current.begin(), Current.end()); 14847 Current.clear(); 14848 } else { 14849 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14850 } 14851 } 14852 14853 14854 void Sema::CheckDelegatingCtorCycles() { 14855 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14856 14857 for (DelegatingCtorDeclsType::iterator 14858 I = DelegatingCtorDecls.begin(ExternalSource), 14859 E = DelegatingCtorDecls.end(); 14860 I != E; ++I) 14861 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14862 14863 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14864 CE = Invalid.end(); 14865 CI != CE; ++CI) 14866 (*CI)->setInvalidDecl(); 14867 } 14868 14869 namespace { 14870 /// \brief AST visitor that finds references to the 'this' expression. 14871 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14872 Sema &S; 14873 14874 public: 14875 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14876 14877 bool VisitCXXThisExpr(CXXThisExpr *E) { 14878 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14879 << E->isImplicit(); 14880 return false; 14881 } 14882 }; 14883 } 14884 14885 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14886 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14887 if (!TSInfo) 14888 return false; 14889 14890 TypeLoc TL = TSInfo->getTypeLoc(); 14891 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14892 if (!ProtoTL) 14893 return false; 14894 14895 // C++11 [expr.prim.general]p3: 14896 // [The expression this] shall not appear before the optional 14897 // cv-qualifier-seq and it shall not appear within the declaration of a 14898 // static member function (although its type and value category are defined 14899 // within a static member function as they are within a non-static member 14900 // function). [ Note: this is because declaration matching does not occur 14901 // until the complete declarator is known. - end note ] 14902 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14903 FindCXXThisExpr Finder(*this); 14904 14905 // If the return type came after the cv-qualifier-seq, check it now. 14906 if (Proto->hasTrailingReturn() && 14907 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14908 return true; 14909 14910 // Check the exception specification. 14911 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14912 return true; 14913 14914 return checkThisInStaticMemberFunctionAttributes(Method); 14915 } 14916 14917 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14918 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14919 if (!TSInfo) 14920 return false; 14921 14922 TypeLoc TL = TSInfo->getTypeLoc(); 14923 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14924 if (!ProtoTL) 14925 return false; 14926 14927 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14928 FindCXXThisExpr Finder(*this); 14929 14930 switch (Proto->getExceptionSpecType()) { 14931 case EST_Unparsed: 14932 case EST_Uninstantiated: 14933 case EST_Unevaluated: 14934 case EST_BasicNoexcept: 14935 case EST_DynamicNone: 14936 case EST_MSAny: 14937 case EST_None: 14938 break; 14939 14940 case EST_ComputedNoexcept: 14941 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14942 return true; 14943 LLVM_FALLTHROUGH; 14944 14945 case EST_Dynamic: 14946 for (const auto &E : Proto->exceptions()) { 14947 if (!Finder.TraverseType(E)) 14948 return true; 14949 } 14950 break; 14951 } 14952 14953 return false; 14954 } 14955 14956 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14957 FindCXXThisExpr Finder(*this); 14958 14959 // Check attributes. 14960 for (const auto *A : Method->attrs()) { 14961 // FIXME: This should be emitted by tblgen. 14962 Expr *Arg = nullptr; 14963 ArrayRef<Expr *> Args; 14964 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14965 Arg = G->getArg(); 14966 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14967 Arg = G->getArg(); 14968 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14969 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14970 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14971 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14972 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14973 Arg = ETLF->getSuccessValue(); 14974 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14975 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14976 Arg = STLF->getSuccessValue(); 14977 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14978 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14979 Arg = LR->getArg(); 14980 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14981 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14982 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14983 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14984 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14985 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14986 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14987 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14988 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14989 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14990 14991 if (Arg && !Finder.TraverseStmt(Arg)) 14992 return true; 14993 14994 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14995 if (!Finder.TraverseStmt(Args[I])) 14996 return true; 14997 } 14998 } 14999 15000 return false; 15001 } 15002 15003 void Sema::checkExceptionSpecification( 15004 bool IsTopLevel, ExceptionSpecificationType EST, 15005 ArrayRef<ParsedType> DynamicExceptions, 15006 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15007 SmallVectorImpl<QualType> &Exceptions, 15008 FunctionProtoType::ExceptionSpecInfo &ESI) { 15009 Exceptions.clear(); 15010 ESI.Type = EST; 15011 if (EST == EST_Dynamic) { 15012 Exceptions.reserve(DynamicExceptions.size()); 15013 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15014 // FIXME: Preserve type source info. 15015 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15016 15017 if (IsTopLevel) { 15018 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15019 collectUnexpandedParameterPacks(ET, Unexpanded); 15020 if (!Unexpanded.empty()) { 15021 DiagnoseUnexpandedParameterPacks( 15022 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15023 Unexpanded); 15024 continue; 15025 } 15026 } 15027 15028 // Check that the type is valid for an exception spec, and 15029 // drop it if not. 15030 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15031 Exceptions.push_back(ET); 15032 } 15033 ESI.Exceptions = Exceptions; 15034 return; 15035 } 15036 15037 if (EST == EST_ComputedNoexcept) { 15038 // If an error occurred, there's no expression here. 15039 if (NoexceptExpr) { 15040 assert((NoexceptExpr->isTypeDependent() || 15041 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15042 Context.BoolTy) && 15043 "Parser should have made sure that the expression is boolean"); 15044 if (IsTopLevel && NoexceptExpr && 15045 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15046 ESI.Type = EST_BasicNoexcept; 15047 return; 15048 } 15049 15050 if (!NoexceptExpr->isValueDependent()) { 15051 ExprResult Result = VerifyIntegerConstantExpression( 15052 NoexceptExpr, nullptr, diag::err_noexcept_needs_constant_expression, 15053 /*AllowFold*/ false); 15054 if (Result.isInvalid()) { 15055 ESI.Type = EST_BasicNoexcept; 15056 return; 15057 } 15058 NoexceptExpr = Result.get(); 15059 } 15060 ESI.NoexceptExpr = NoexceptExpr; 15061 } 15062 return; 15063 } 15064 } 15065 15066 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15067 ExceptionSpecificationType EST, 15068 SourceRange SpecificationRange, 15069 ArrayRef<ParsedType> DynamicExceptions, 15070 ArrayRef<SourceRange> DynamicExceptionRanges, 15071 Expr *NoexceptExpr) { 15072 if (!MethodD) 15073 return; 15074 15075 // Dig out the method we're referring to. 15076 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15077 MethodD = FunTmpl->getTemplatedDecl(); 15078 15079 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15080 if (!Method) 15081 return; 15082 15083 // Check the exception specification. 15084 llvm::SmallVector<QualType, 4> Exceptions; 15085 FunctionProtoType::ExceptionSpecInfo ESI; 15086 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15087 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15088 ESI); 15089 15090 // Update the exception specification on the function type. 15091 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15092 15093 if (Method->isStatic()) 15094 checkThisInStaticMemberFunctionExceptionSpec(Method); 15095 15096 if (Method->isVirtual()) { 15097 // Check overrides, which we previously had to delay. 15098 for (const CXXMethodDecl *O : Method->overridden_methods()) 15099 CheckOverridingFunctionExceptionSpec(Method, O); 15100 } 15101 } 15102 15103 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15104 /// 15105 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15106 SourceLocation DeclStart, 15107 Declarator &D, Expr *BitWidth, 15108 InClassInitStyle InitStyle, 15109 AccessSpecifier AS, 15110 AttributeList *MSPropertyAttr) { 15111 IdentifierInfo *II = D.getIdentifier(); 15112 if (!II) { 15113 Diag(DeclStart, diag::err_anonymous_property); 15114 return nullptr; 15115 } 15116 SourceLocation Loc = D.getIdentifierLoc(); 15117 15118 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15119 QualType T = TInfo->getType(); 15120 if (getLangOpts().CPlusPlus) { 15121 CheckExtraCXXDefaultArguments(D); 15122 15123 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15124 UPPC_DataMemberType)) { 15125 D.setInvalidType(); 15126 T = Context.IntTy; 15127 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15128 } 15129 } 15130 15131 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15132 15133 if (D.getDeclSpec().isInlineSpecified()) 15134 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15135 << getLangOpts().CPlusPlus17; 15136 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15137 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15138 diag::err_invalid_thread) 15139 << DeclSpec::getSpecifierName(TSCS); 15140 15141 // Check to see if this name was declared as a member previously 15142 NamedDecl *PrevDecl = nullptr; 15143 LookupResult Previous(*this, II, Loc, LookupMemberName, 15144 ForVisibleRedeclaration); 15145 LookupName(Previous, S); 15146 switch (Previous.getResultKind()) { 15147 case LookupResult::Found: 15148 case LookupResult::FoundUnresolvedValue: 15149 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15150 break; 15151 15152 case LookupResult::FoundOverloaded: 15153 PrevDecl = Previous.getRepresentativeDecl(); 15154 break; 15155 15156 case LookupResult::NotFound: 15157 case LookupResult::NotFoundInCurrentInstantiation: 15158 case LookupResult::Ambiguous: 15159 break; 15160 } 15161 15162 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15163 // Maybe we will complain about the shadowed template parameter. 15164 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15165 // Just pretend that we didn't see the previous declaration. 15166 PrevDecl = nullptr; 15167 } 15168 15169 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15170 PrevDecl = nullptr; 15171 15172 SourceLocation TSSL = D.getLocStart(); 15173 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 15174 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 15175 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 15176 ProcessDeclAttributes(TUScope, NewPD, D); 15177 NewPD->setAccess(AS); 15178 15179 if (NewPD->isInvalidDecl()) 15180 Record->setInvalidDecl(); 15181 15182 if (D.getDeclSpec().isModulePrivateSpecified()) 15183 NewPD->setModulePrivate(); 15184 15185 if (NewPD->isInvalidDecl() && PrevDecl) { 15186 // Don't introduce NewFD into scope; there's already something 15187 // with the same name in the same scope. 15188 } else if (II) { 15189 PushOnScopeChains(NewPD, S); 15190 } else 15191 Record->addDecl(NewPD); 15192 15193 return NewPD; 15194 } 15195