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 // or a for-range-declaration, but we parse it in more cases than that. 697 if (!D.mayHaveDecompositionDeclarator()) { 698 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 699 << Decomp.getSourceRange(); 700 return nullptr; 701 } 702 703 if (!TemplateParamLists.empty()) { 704 // FIXME: There's no rule against this, but there are also no rules that 705 // would actually make it usable, so we reject it for now. 706 Diag(TemplateParamLists.front()->getTemplateLoc(), 707 diag::err_decomp_decl_template); 708 return nullptr; 709 } 710 711 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z 712 ? diag::warn_cxx14_compat_decomp_decl 713 : diag::ext_decomp_decl) 714 << Decomp.getSourceRange(); 715 716 // The semantic context is always just the current context. 717 DeclContext *const DC = CurContext; 718 719 // C++1z [dcl.dcl]/8: 720 // The decl-specifier-seq shall contain only the type-specifier auto 721 // and cv-qualifiers. 722 auto &DS = D.getDeclSpec(); 723 { 724 SmallVector<StringRef, 8> BadSpecifiers; 725 SmallVector<SourceLocation, 8> BadSpecifierLocs; 726 if (auto SCS = DS.getStorageClassSpec()) { 727 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 728 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 729 } 730 if (auto TSCS = DS.getThreadStorageClassSpec()) { 731 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 732 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 733 } 734 if (DS.isConstexprSpecified()) { 735 BadSpecifiers.push_back("constexpr"); 736 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 737 } 738 if (DS.isInlineSpecified()) { 739 BadSpecifiers.push_back("inline"); 740 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 741 } 742 if (!BadSpecifiers.empty()) { 743 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 744 Err << (int)BadSpecifiers.size() 745 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 746 // Don't add FixItHints to remove the specifiers; we do still respect 747 // them when building the underlying variable. 748 for (auto Loc : BadSpecifierLocs) 749 Err << SourceRange(Loc, Loc); 750 } 751 // We can't recover from it being declared as a typedef. 752 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 753 return nullptr; 754 } 755 756 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 757 QualType R = TInfo->getType(); 758 759 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 760 UPPC_DeclarationType)) 761 D.setInvalidType(); 762 763 // The syntax only allows a single ref-qualifier prior to the decomposition 764 // declarator. No other declarator chunks are permitted. Also check the type 765 // specifier here. 766 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 767 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 768 (D.getNumTypeObjects() == 1 && 769 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 770 Diag(Decomp.getLSquareLoc(), 771 (D.hasGroupingParens() || 772 (D.getNumTypeObjects() && 773 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 774 ? diag::err_decomp_decl_parens 775 : diag::err_decomp_decl_type) 776 << R; 777 778 // In most cases, there's no actual problem with an explicitly-specified 779 // type, but a function type won't work here, and ActOnVariableDeclarator 780 // shouldn't be called for such a type. 781 if (R->isFunctionType()) 782 D.setInvalidType(); 783 } 784 785 // Build the BindingDecls. 786 SmallVector<BindingDecl*, 8> Bindings; 787 788 // Build the BindingDecls. 789 for (auto &B : D.getDecompositionDeclarator().bindings()) { 790 // Check for name conflicts. 791 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 792 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 793 ForVisibleRedeclaration); 794 LookupName(Previous, S, 795 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 796 797 // It's not permitted to shadow a template parameter name. 798 if (Previous.isSingleResult() && 799 Previous.getFoundDecl()->isTemplateParameter()) { 800 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 801 Previous.getFoundDecl()); 802 Previous.clear(); 803 } 804 805 bool ConsiderLinkage = DC->isFunctionOrMethod() && 806 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 807 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 808 /*AllowInlineNamespace*/false); 809 if (!Previous.empty()) { 810 auto *Old = Previous.getRepresentativeDecl(); 811 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 812 Diag(Old->getLocation(), diag::note_previous_definition); 813 } 814 815 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 816 PushOnScopeChains(BD, S, true); 817 Bindings.push_back(BD); 818 ParsingInitForAutoVars.insert(BD); 819 } 820 821 // There are no prior lookup results for the variable itself, because it 822 // is unnamed. 823 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 824 Decomp.getLSquareLoc()); 825 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 826 ForVisibleRedeclaration); 827 828 // Build the variable that holds the non-decomposed object. 829 bool AddToScope = true; 830 NamedDecl *New = 831 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 832 MultiTemplateParamsArg(), AddToScope, Bindings); 833 if (AddToScope) { 834 S->AddDecl(New); 835 CurContext->addHiddenDecl(New); 836 } 837 838 if (isInOpenMPDeclareTargetContext()) 839 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 840 841 return New; 842 } 843 844 static bool checkSimpleDecomposition( 845 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 846 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 847 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 848 if ((int64_t)Bindings.size() != NumElems) { 849 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 850 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 851 << (NumElems < Bindings.size()); 852 return true; 853 } 854 855 unsigned I = 0; 856 for (auto *B : Bindings) { 857 SourceLocation Loc = B->getLocation(); 858 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 859 if (E.isInvalid()) 860 return true; 861 E = GetInit(Loc, E.get(), I++); 862 if (E.isInvalid()) 863 return true; 864 B->setBinding(ElemType, E.get()); 865 } 866 867 return false; 868 } 869 870 static bool checkArrayLikeDecomposition(Sema &S, 871 ArrayRef<BindingDecl *> Bindings, 872 ValueDecl *Src, QualType DecompType, 873 const llvm::APSInt &NumElems, 874 QualType ElemType) { 875 return checkSimpleDecomposition( 876 S, Bindings, Src, DecompType, NumElems, ElemType, 877 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 878 ExprResult E = S.ActOnIntegerConstant(Loc, I); 879 if (E.isInvalid()) 880 return ExprError(); 881 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 882 }); 883 } 884 885 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 886 ValueDecl *Src, QualType DecompType, 887 const ConstantArrayType *CAT) { 888 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 889 llvm::APSInt(CAT->getSize()), 890 CAT->getElementType()); 891 } 892 893 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 894 ValueDecl *Src, QualType DecompType, 895 const VectorType *VT) { 896 return checkArrayLikeDecomposition( 897 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 898 S.Context.getQualifiedType(VT->getElementType(), 899 DecompType.getQualifiers())); 900 } 901 902 static bool checkComplexDecomposition(Sema &S, 903 ArrayRef<BindingDecl *> Bindings, 904 ValueDecl *Src, QualType DecompType, 905 const ComplexType *CT) { 906 return checkSimpleDecomposition( 907 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 908 S.Context.getQualifiedType(CT->getElementType(), 909 DecompType.getQualifiers()), 910 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 911 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 912 }); 913 } 914 915 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 916 TemplateArgumentListInfo &Args) { 917 SmallString<128> SS; 918 llvm::raw_svector_ostream OS(SS); 919 bool First = true; 920 for (auto &Arg : Args.arguments()) { 921 if (!First) 922 OS << ", "; 923 Arg.getArgument().print(PrintingPolicy, OS); 924 First = false; 925 } 926 return OS.str(); 927 } 928 929 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 930 SourceLocation Loc, StringRef Trait, 931 TemplateArgumentListInfo &Args, 932 unsigned DiagID) { 933 auto DiagnoseMissing = [&] { 934 if (DiagID) 935 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 936 Args); 937 return true; 938 }; 939 940 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 941 NamespaceDecl *Std = S.getStdNamespace(); 942 if (!Std) 943 return DiagnoseMissing(); 944 945 // Look up the trait itself, within namespace std. We can diagnose various 946 // problems with this lookup even if we've been asked to not diagnose a 947 // missing specialization, because this can only fail if the user has been 948 // declaring their own names in namespace std or we don't support the 949 // standard library implementation in use. 950 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 951 Loc, Sema::LookupOrdinaryName); 952 if (!S.LookupQualifiedName(Result, Std)) 953 return DiagnoseMissing(); 954 if (Result.isAmbiguous()) 955 return true; 956 957 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 958 if (!TraitTD) { 959 Result.suppressDiagnostics(); 960 NamedDecl *Found = *Result.begin(); 961 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 962 S.Diag(Found->getLocation(), diag::note_declared_at); 963 return true; 964 } 965 966 // Build the template-id. 967 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 968 if (TraitTy.isNull()) 969 return true; 970 if (!S.isCompleteType(Loc, TraitTy)) { 971 if (DiagID) 972 S.RequireCompleteType( 973 Loc, TraitTy, DiagID, 974 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 975 return true; 976 } 977 978 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 979 assert(RD && "specialization of class template is not a class?"); 980 981 // Look up the member of the trait type. 982 S.LookupQualifiedName(TraitMemberLookup, RD); 983 return TraitMemberLookup.isAmbiguous(); 984 } 985 986 static TemplateArgumentLoc 987 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 988 uint64_t I) { 989 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 990 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 991 } 992 993 static TemplateArgumentLoc 994 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 995 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 996 } 997 998 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 999 1000 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1001 llvm::APSInt &Size) { 1002 EnterExpressionEvaluationContext ContextRAII( 1003 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1004 1005 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1006 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1007 1008 // Form template argument list for tuple_size<T>. 1009 TemplateArgumentListInfo Args(Loc, Loc); 1010 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1011 1012 // If there's no tuple_size specialization, it's not tuple-like. 1013 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1014 return IsTupleLike::NotTupleLike; 1015 1016 // If we get this far, we've committed to the tuple interpretation, but 1017 // we can still fail if there actually isn't a usable ::value. 1018 1019 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1020 LookupResult &R; 1021 TemplateArgumentListInfo &Args; 1022 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1023 : R(R), Args(Args) {} 1024 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1025 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1026 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1027 } 1028 } Diagnoser(R, Args); 1029 1030 if (R.empty()) { 1031 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1032 return IsTupleLike::Error; 1033 } 1034 1035 ExprResult E = 1036 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1037 if (E.isInvalid()) 1038 return IsTupleLike::Error; 1039 1040 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1041 if (E.isInvalid()) 1042 return IsTupleLike::Error; 1043 1044 return IsTupleLike::TupleLike; 1045 } 1046 1047 /// \return std::tuple_element<I, T>::type. 1048 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1049 unsigned I, QualType T) { 1050 // Form template argument list for tuple_element<I, T>. 1051 TemplateArgumentListInfo Args(Loc, Loc); 1052 Args.addArgument( 1053 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1054 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1055 1056 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1057 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1058 if (lookupStdTypeTraitMember( 1059 S, R, Loc, "tuple_element", Args, 1060 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1061 return QualType(); 1062 1063 auto *TD = R.getAsSingle<TypeDecl>(); 1064 if (!TD) { 1065 R.suppressDiagnostics(); 1066 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1067 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1068 if (!R.empty()) 1069 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1070 return QualType(); 1071 } 1072 1073 return S.Context.getTypeDeclType(TD); 1074 } 1075 1076 namespace { 1077 struct BindingDiagnosticTrap { 1078 Sema &S; 1079 DiagnosticErrorTrap Trap; 1080 BindingDecl *BD; 1081 1082 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1083 : S(S), Trap(S.Diags), BD(BD) {} 1084 ~BindingDiagnosticTrap() { 1085 if (Trap.hasErrorOccurred()) 1086 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1087 } 1088 }; 1089 } 1090 1091 static bool checkTupleLikeDecomposition(Sema &S, 1092 ArrayRef<BindingDecl *> Bindings, 1093 VarDecl *Src, QualType DecompType, 1094 const llvm::APSInt &TupleSize) { 1095 if ((int64_t)Bindings.size() != TupleSize) { 1096 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1097 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1098 << (TupleSize < Bindings.size()); 1099 return true; 1100 } 1101 1102 if (Bindings.empty()) 1103 return false; 1104 1105 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1106 1107 // [dcl.decomp]p3: 1108 // The unqualified-id get is looked up in the scope of E by class member 1109 // access lookup 1110 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1111 bool UseMemberGet = false; 1112 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1113 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1114 S.LookupQualifiedName(MemberGet, RD); 1115 if (MemberGet.isAmbiguous()) 1116 return true; 1117 UseMemberGet = !MemberGet.empty(); 1118 S.FilterAcceptableTemplateNames(MemberGet); 1119 } 1120 1121 unsigned I = 0; 1122 for (auto *B : Bindings) { 1123 BindingDiagnosticTrap Trap(S, B); 1124 SourceLocation Loc = B->getLocation(); 1125 1126 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1127 if (E.isInvalid()) 1128 return true; 1129 1130 // e is an lvalue if the type of the entity is an lvalue reference and 1131 // an xvalue otherwise 1132 if (!Src->getType()->isLValueReferenceType()) 1133 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1134 E.get(), nullptr, VK_XValue); 1135 1136 TemplateArgumentListInfo Args(Loc, Loc); 1137 Args.addArgument( 1138 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1139 1140 if (UseMemberGet) { 1141 // if [lookup of member get] finds at least one declaration, the 1142 // initializer is e.get<i-1>(). 1143 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1144 CXXScopeSpec(), SourceLocation(), nullptr, 1145 MemberGet, &Args, nullptr); 1146 if (E.isInvalid()) 1147 return true; 1148 1149 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1150 } else { 1151 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1152 // in the associated namespaces. 1153 Expr *Get = UnresolvedLookupExpr::Create( 1154 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1155 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1156 UnresolvedSetIterator(), UnresolvedSetIterator()); 1157 1158 Expr *Arg = E.get(); 1159 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1160 } 1161 if (E.isInvalid()) 1162 return true; 1163 Expr *Init = E.get(); 1164 1165 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1166 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1167 if (T.isNull()) 1168 return true; 1169 1170 // each vi is a variable of type "reference to T" initialized with the 1171 // initializer, where the reference is an lvalue reference if the 1172 // initializer is an lvalue and an rvalue reference otherwise 1173 QualType RefType = 1174 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1175 if (RefType.isNull()) 1176 return true; 1177 auto *RefVD = VarDecl::Create( 1178 S.Context, Src->getDeclContext(), Loc, Loc, 1179 B->getDeclName().getAsIdentifierInfo(), RefType, 1180 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1181 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1182 RefVD->setTSCSpec(Src->getTSCSpec()); 1183 RefVD->setImplicit(); 1184 if (Src->isInlineSpecified()) 1185 RefVD->setInlineSpecified(); 1186 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1187 1188 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1189 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1190 InitializationSequence Seq(S, Entity, Kind, Init); 1191 E = Seq.Perform(S, Entity, Kind, Init); 1192 if (E.isInvalid()) 1193 return true; 1194 E = S.ActOnFinishFullExpr(E.get(), Loc); 1195 if (E.isInvalid()) 1196 return true; 1197 RefVD->setInit(E.get()); 1198 RefVD->checkInitIsICE(); 1199 1200 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1201 DeclarationNameInfo(B->getDeclName(), Loc), 1202 RefVD); 1203 if (E.isInvalid()) 1204 return true; 1205 1206 B->setBinding(T, E.get()); 1207 I++; 1208 } 1209 1210 return false; 1211 } 1212 1213 /// Find the base class to decompose in a built-in decomposition of a class type. 1214 /// This base class search is, unfortunately, not quite like any other that we 1215 /// perform anywhere else in C++. 1216 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1217 SourceLocation Loc, 1218 const CXXRecordDecl *RD, 1219 CXXCastPath &BasePath) { 1220 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1221 CXXBasePath &Path) { 1222 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1223 }; 1224 1225 const CXXRecordDecl *ClassWithFields = nullptr; 1226 if (RD->hasDirectFields()) 1227 // [dcl.decomp]p4: 1228 // Otherwise, all of E's non-static data members shall be public direct 1229 // members of E ... 1230 ClassWithFields = RD; 1231 else { 1232 // ... or of ... 1233 CXXBasePaths Paths; 1234 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1235 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1236 // If no classes have fields, just decompose RD itself. (This will work 1237 // if and only if zero bindings were provided.) 1238 return RD; 1239 } 1240 1241 CXXBasePath *BestPath = nullptr; 1242 for (auto &P : Paths) { 1243 if (!BestPath) 1244 BestPath = &P; 1245 else if (!S.Context.hasSameType(P.back().Base->getType(), 1246 BestPath->back().Base->getType())) { 1247 // ... the same ... 1248 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1249 << false << RD << BestPath->back().Base->getType() 1250 << P.back().Base->getType(); 1251 return nullptr; 1252 } else if (P.Access < BestPath->Access) { 1253 BestPath = &P; 1254 } 1255 } 1256 1257 // ... unambiguous ... 1258 QualType BaseType = BestPath->back().Base->getType(); 1259 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1260 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1261 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1262 return nullptr; 1263 } 1264 1265 // ... public base class of E. 1266 if (BestPath->Access != AS_public) { 1267 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1268 << RD << BaseType; 1269 for (auto &BS : *BestPath) { 1270 if (BS.Base->getAccessSpecifier() != AS_public) { 1271 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1272 << (BS.Base->getAccessSpecifier() == AS_protected) 1273 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1274 break; 1275 } 1276 } 1277 return nullptr; 1278 } 1279 1280 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1281 S.BuildBasePathArray(Paths, BasePath); 1282 } 1283 1284 // The above search did not check whether the selected class itself has base 1285 // classes with fields, so check that now. 1286 CXXBasePaths Paths; 1287 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1288 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1289 << (ClassWithFields == RD) << RD << ClassWithFields 1290 << Paths.front().back().Base->getType(); 1291 return nullptr; 1292 } 1293 1294 return ClassWithFields; 1295 } 1296 1297 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1298 ValueDecl *Src, QualType DecompType, 1299 const CXXRecordDecl *RD) { 1300 CXXCastPath BasePath; 1301 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1302 if (!RD) 1303 return true; 1304 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1305 DecompType.getQualifiers()); 1306 1307 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1308 unsigned NumFields = 1309 std::count_if(RD->field_begin(), RD->field_end(), 1310 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1311 assert(Bindings.size() != NumFields); 1312 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1313 << DecompType << (unsigned)Bindings.size() << NumFields 1314 << (NumFields < Bindings.size()); 1315 return true; 1316 }; 1317 1318 // all of E's non-static data members shall be public [...] members, 1319 // E shall not have an anonymous union member, ... 1320 unsigned I = 0; 1321 for (auto *FD : RD->fields()) { 1322 if (FD->isUnnamedBitfield()) 1323 continue; 1324 1325 if (FD->isAnonymousStructOrUnion()) { 1326 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1327 << DecompType << FD->getType()->isUnionType(); 1328 S.Diag(FD->getLocation(), diag::note_declared_at); 1329 return true; 1330 } 1331 1332 // We have a real field to bind. 1333 if (I >= Bindings.size()) 1334 return DiagnoseBadNumberOfBindings(); 1335 auto *B = Bindings[I++]; 1336 1337 SourceLocation Loc = B->getLocation(); 1338 if (FD->getAccess() != AS_public) { 1339 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1340 1341 // Determine whether the access specifier was explicit. 1342 bool Implicit = true; 1343 for (const auto *D : RD->decls()) { 1344 if (declaresSameEntity(D, FD)) 1345 break; 1346 if (isa<AccessSpecDecl>(D)) { 1347 Implicit = false; 1348 break; 1349 } 1350 } 1351 1352 S.Diag(FD->getLocation(), diag::note_access_natural) 1353 << (FD->getAccess() == AS_protected) << Implicit; 1354 return true; 1355 } 1356 1357 // Initialize the binding to Src.FD. 1358 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1359 if (E.isInvalid()) 1360 return true; 1361 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1362 VK_LValue, &BasePath); 1363 if (E.isInvalid()) 1364 return true; 1365 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1366 CXXScopeSpec(), FD, 1367 DeclAccessPair::make(FD, FD->getAccess()), 1368 DeclarationNameInfo(FD->getDeclName(), Loc)); 1369 if (E.isInvalid()) 1370 return true; 1371 1372 // If the type of the member is T, the referenced type is cv T, where cv is 1373 // the cv-qualification of the decomposition expression. 1374 // 1375 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1376 // 'const' to the type of the field. 1377 Qualifiers Q = DecompType.getQualifiers(); 1378 if (FD->isMutable()) 1379 Q.removeConst(); 1380 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1381 } 1382 1383 if (I != Bindings.size()) 1384 return DiagnoseBadNumberOfBindings(); 1385 1386 return false; 1387 } 1388 1389 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1390 QualType DecompType = DD->getType(); 1391 1392 // If the type of the decomposition is dependent, then so is the type of 1393 // each binding. 1394 if (DecompType->isDependentType()) { 1395 for (auto *B : DD->bindings()) 1396 B->setType(Context.DependentTy); 1397 return; 1398 } 1399 1400 DecompType = DecompType.getNonReferenceType(); 1401 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1402 1403 // C++1z [dcl.decomp]/2: 1404 // If E is an array type [...] 1405 // As an extension, we also support decomposition of built-in complex and 1406 // vector types. 1407 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1408 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1409 DD->setInvalidDecl(); 1410 return; 1411 } 1412 if (auto *VT = DecompType->getAs<VectorType>()) { 1413 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1414 DD->setInvalidDecl(); 1415 return; 1416 } 1417 if (auto *CT = DecompType->getAs<ComplexType>()) { 1418 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1419 DD->setInvalidDecl(); 1420 return; 1421 } 1422 1423 // C++1z [dcl.decomp]/3: 1424 // if the expression std::tuple_size<E>::value is a well-formed integral 1425 // constant expression, [...] 1426 llvm::APSInt TupleSize(32); 1427 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1428 case IsTupleLike::Error: 1429 DD->setInvalidDecl(); 1430 return; 1431 1432 case IsTupleLike::TupleLike: 1433 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1434 DD->setInvalidDecl(); 1435 return; 1436 1437 case IsTupleLike::NotTupleLike: 1438 break; 1439 } 1440 1441 // C++1z [dcl.dcl]/8: 1442 // [E shall be of array or non-union class type] 1443 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1444 if (!RD || RD->isUnion()) { 1445 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1446 << DD << !RD << DecompType; 1447 DD->setInvalidDecl(); 1448 return; 1449 } 1450 1451 // C++1z [dcl.decomp]/4: 1452 // all of E's non-static data members shall be [...] direct members of 1453 // E or of the same unambiguous public base class of E, ... 1454 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1455 DD->setInvalidDecl(); 1456 } 1457 1458 /// \brief Merge the exception specifications of two variable declarations. 1459 /// 1460 /// This is called when there's a redeclaration of a VarDecl. The function 1461 /// checks if the redeclaration might have an exception specification and 1462 /// validates compatibility and merges the specs if necessary. 1463 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1464 // Shortcut if exceptions are disabled. 1465 if (!getLangOpts().CXXExceptions) 1466 return; 1467 1468 assert(Context.hasSameType(New->getType(), Old->getType()) && 1469 "Should only be called if types are otherwise the same."); 1470 1471 QualType NewType = New->getType(); 1472 QualType OldType = Old->getType(); 1473 1474 // We're only interested in pointers and references to functions, as well 1475 // as pointers to member functions. 1476 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1477 NewType = R->getPointeeType(); 1478 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1479 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1480 NewType = P->getPointeeType(); 1481 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1482 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1483 NewType = M->getPointeeType(); 1484 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1485 } 1486 1487 if (!NewType->isFunctionProtoType()) 1488 return; 1489 1490 // There's lots of special cases for functions. For function pointers, system 1491 // libraries are hopefully not as broken so that we don't need these 1492 // workarounds. 1493 if (CheckEquivalentExceptionSpec( 1494 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1495 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1496 New->setInvalidDecl(); 1497 } 1498 } 1499 1500 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1501 /// function declaration are well-formed according to C++ 1502 /// [dcl.fct.default]. 1503 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1504 unsigned NumParams = FD->getNumParams(); 1505 unsigned p; 1506 1507 // Find first parameter with a default argument 1508 for (p = 0; p < NumParams; ++p) { 1509 ParmVarDecl *Param = FD->getParamDecl(p); 1510 if (Param->hasDefaultArg()) 1511 break; 1512 } 1513 1514 // C++11 [dcl.fct.default]p4: 1515 // In a given function declaration, each parameter subsequent to a parameter 1516 // with a default argument shall have a default argument supplied in this or 1517 // a previous declaration or shall be a function parameter pack. A default 1518 // argument shall not be redefined by a later declaration (not even to the 1519 // same value). 1520 unsigned LastMissingDefaultArg = 0; 1521 for (; p < NumParams; ++p) { 1522 ParmVarDecl *Param = FD->getParamDecl(p); 1523 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1524 if (Param->isInvalidDecl()) 1525 /* We already complained about this parameter. */; 1526 else if (Param->getIdentifier()) 1527 Diag(Param->getLocation(), 1528 diag::err_param_default_argument_missing_name) 1529 << Param->getIdentifier(); 1530 else 1531 Diag(Param->getLocation(), 1532 diag::err_param_default_argument_missing); 1533 1534 LastMissingDefaultArg = p; 1535 } 1536 } 1537 1538 if (LastMissingDefaultArg > 0) { 1539 // Some default arguments were missing. Clear out all of the 1540 // default arguments up to (and including) the last missing 1541 // default argument, so that we leave the function parameters 1542 // in a semantically valid state. 1543 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1544 ParmVarDecl *Param = FD->getParamDecl(p); 1545 if (Param->hasDefaultArg()) { 1546 Param->setDefaultArg(nullptr); 1547 } 1548 } 1549 } 1550 } 1551 1552 // CheckConstexprParameterTypes - Check whether a function's parameter types 1553 // are all literal types. If so, return true. If not, produce a suitable 1554 // diagnostic and return false. 1555 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1556 const FunctionDecl *FD) { 1557 unsigned ArgIndex = 0; 1558 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1559 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1560 e = FT->param_type_end(); 1561 i != e; ++i, ++ArgIndex) { 1562 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1563 SourceLocation ParamLoc = PD->getLocation(); 1564 if (!(*i)->isDependentType() && 1565 SemaRef.RequireLiteralType(ParamLoc, *i, 1566 diag::err_constexpr_non_literal_param, 1567 ArgIndex+1, PD->getSourceRange(), 1568 isa<CXXConstructorDecl>(FD))) 1569 return false; 1570 } 1571 return true; 1572 } 1573 1574 /// \brief Get diagnostic %select index for tag kind for 1575 /// record diagnostic message. 1576 /// WARNING: Indexes apply to particular diagnostics only! 1577 /// 1578 /// \returns diagnostic %select index. 1579 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1580 switch (Tag) { 1581 case TTK_Struct: return 0; 1582 case TTK_Interface: return 1; 1583 case TTK_Class: return 2; 1584 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1585 } 1586 } 1587 1588 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1589 // the requirements of a constexpr function definition or a constexpr 1590 // constructor definition. If so, return true. If not, produce appropriate 1591 // diagnostics and return false. 1592 // 1593 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1594 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1595 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1596 if (MD && MD->isInstance()) { 1597 // C++11 [dcl.constexpr]p4: 1598 // The definition of a constexpr constructor shall satisfy the following 1599 // constraints: 1600 // - the class shall not have any virtual base classes; 1601 const CXXRecordDecl *RD = MD->getParent(); 1602 if (RD->getNumVBases()) { 1603 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1604 << isa<CXXConstructorDecl>(NewFD) 1605 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1606 for (const auto &I : RD->vbases()) 1607 Diag(I.getLocStart(), 1608 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1609 return false; 1610 } 1611 } 1612 1613 if (!isa<CXXConstructorDecl>(NewFD)) { 1614 // C++11 [dcl.constexpr]p3: 1615 // The definition of a constexpr function shall satisfy the following 1616 // constraints: 1617 // - it shall not be virtual; 1618 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1619 if (Method && Method->isVirtual()) { 1620 Method = Method->getCanonicalDecl(); 1621 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1622 1623 // If it's not obvious why this function is virtual, find an overridden 1624 // function which uses the 'virtual' keyword. 1625 const CXXMethodDecl *WrittenVirtual = Method; 1626 while (!WrittenVirtual->isVirtualAsWritten()) 1627 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1628 if (WrittenVirtual != Method) 1629 Diag(WrittenVirtual->getLocation(), 1630 diag::note_overridden_virtual_function); 1631 return false; 1632 } 1633 1634 // - its return type shall be a literal type; 1635 QualType RT = NewFD->getReturnType(); 1636 if (!RT->isDependentType() && 1637 RequireLiteralType(NewFD->getLocation(), RT, 1638 diag::err_constexpr_non_literal_return)) 1639 return false; 1640 } 1641 1642 // - each of its parameter types shall be a literal type; 1643 if (!CheckConstexprParameterTypes(*this, NewFD)) 1644 return false; 1645 1646 return true; 1647 } 1648 1649 /// Check the given declaration statement is legal within a constexpr function 1650 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1651 /// 1652 /// \return true if the body is OK (maybe only as an extension), false if we 1653 /// have diagnosed a problem. 1654 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1655 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1656 // C++11 [dcl.constexpr]p3 and p4: 1657 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1658 // contain only 1659 for (const auto *DclIt : DS->decls()) { 1660 switch (DclIt->getKind()) { 1661 case Decl::StaticAssert: 1662 case Decl::Using: 1663 case Decl::UsingShadow: 1664 case Decl::UsingDirective: 1665 case Decl::UnresolvedUsingTypename: 1666 case Decl::UnresolvedUsingValue: 1667 // - static_assert-declarations 1668 // - using-declarations, 1669 // - using-directives, 1670 continue; 1671 1672 case Decl::Typedef: 1673 case Decl::TypeAlias: { 1674 // - typedef declarations and alias-declarations that do not define 1675 // classes or enumerations, 1676 const auto *TN = cast<TypedefNameDecl>(DclIt); 1677 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1678 // Don't allow variably-modified types in constexpr functions. 1679 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1680 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1681 << TL.getSourceRange() << TL.getType() 1682 << isa<CXXConstructorDecl>(Dcl); 1683 return false; 1684 } 1685 continue; 1686 } 1687 1688 case Decl::Enum: 1689 case Decl::CXXRecord: 1690 // C++1y allows types to be defined, not just declared. 1691 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1692 SemaRef.Diag(DS->getLocStart(), 1693 SemaRef.getLangOpts().CPlusPlus14 1694 ? diag::warn_cxx11_compat_constexpr_type_definition 1695 : diag::ext_constexpr_type_definition) 1696 << isa<CXXConstructorDecl>(Dcl); 1697 continue; 1698 1699 case Decl::EnumConstant: 1700 case Decl::IndirectField: 1701 case Decl::ParmVar: 1702 // These can only appear with other declarations which are banned in 1703 // C++11 and permitted in C++1y, so ignore them. 1704 continue; 1705 1706 case Decl::Var: 1707 case Decl::Decomposition: { 1708 // C++1y [dcl.constexpr]p3 allows anything except: 1709 // a definition of a variable of non-literal type or of static or 1710 // thread storage duration or for which no initialization is performed. 1711 const auto *VD = cast<VarDecl>(DclIt); 1712 if (VD->isThisDeclarationADefinition()) { 1713 if (VD->isStaticLocal()) { 1714 SemaRef.Diag(VD->getLocation(), 1715 diag::err_constexpr_local_var_static) 1716 << isa<CXXConstructorDecl>(Dcl) 1717 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1718 return false; 1719 } 1720 if (!VD->getType()->isDependentType() && 1721 SemaRef.RequireLiteralType( 1722 VD->getLocation(), VD->getType(), 1723 diag::err_constexpr_local_var_non_literal_type, 1724 isa<CXXConstructorDecl>(Dcl))) 1725 return false; 1726 if (!VD->getType()->isDependentType() && 1727 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1728 SemaRef.Diag(VD->getLocation(), 1729 diag::err_constexpr_local_var_no_init) 1730 << isa<CXXConstructorDecl>(Dcl); 1731 return false; 1732 } 1733 } 1734 SemaRef.Diag(VD->getLocation(), 1735 SemaRef.getLangOpts().CPlusPlus14 1736 ? diag::warn_cxx11_compat_constexpr_local_var 1737 : diag::ext_constexpr_local_var) 1738 << isa<CXXConstructorDecl>(Dcl); 1739 continue; 1740 } 1741 1742 case Decl::NamespaceAlias: 1743 case Decl::Function: 1744 // These are disallowed in C++11 and permitted in C++1y. Allow them 1745 // everywhere as an extension. 1746 if (!Cxx1yLoc.isValid()) 1747 Cxx1yLoc = DS->getLocStart(); 1748 continue; 1749 1750 default: 1751 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1752 << isa<CXXConstructorDecl>(Dcl); 1753 return false; 1754 } 1755 } 1756 1757 return true; 1758 } 1759 1760 /// Check that the given field is initialized within a constexpr constructor. 1761 /// 1762 /// \param Dcl The constexpr constructor being checked. 1763 /// \param Field The field being checked. This may be a member of an anonymous 1764 /// struct or union nested within the class being checked. 1765 /// \param Inits All declarations, including anonymous struct/union members and 1766 /// indirect members, for which any initialization was provided. 1767 /// \param Diagnosed Set to true if an error is produced. 1768 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1769 const FunctionDecl *Dcl, 1770 FieldDecl *Field, 1771 llvm::SmallSet<Decl*, 16> &Inits, 1772 bool &Diagnosed) { 1773 if (Field->isInvalidDecl()) 1774 return; 1775 1776 if (Field->isUnnamedBitfield()) 1777 return; 1778 1779 // Anonymous unions with no variant members and empty anonymous structs do not 1780 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1781 // indirect fields don't need initializing. 1782 if (Field->isAnonymousStructOrUnion() && 1783 (Field->getType()->isUnionType() 1784 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1785 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1786 return; 1787 1788 if (!Inits.count(Field)) { 1789 if (!Diagnosed) { 1790 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1791 Diagnosed = true; 1792 } 1793 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1794 } else if (Field->isAnonymousStructOrUnion()) { 1795 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1796 for (auto *I : RD->fields()) 1797 // If an anonymous union contains an anonymous struct of which any member 1798 // is initialized, all members must be initialized. 1799 if (!RD->isUnion() || Inits.count(I)) 1800 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1801 } 1802 } 1803 1804 /// Check the provided statement is allowed in a constexpr function 1805 /// definition. 1806 static bool 1807 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1808 SmallVectorImpl<SourceLocation> &ReturnStmts, 1809 SourceLocation &Cxx1yLoc) { 1810 // - its function-body shall be [...] a compound-statement that contains only 1811 switch (S->getStmtClass()) { 1812 case Stmt::NullStmtClass: 1813 // - null statements, 1814 return true; 1815 1816 case Stmt::DeclStmtClass: 1817 // - static_assert-declarations 1818 // - using-declarations, 1819 // - using-directives, 1820 // - typedef declarations and alias-declarations that do not define 1821 // classes or enumerations, 1822 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1823 return false; 1824 return true; 1825 1826 case Stmt::ReturnStmtClass: 1827 // - and exactly one return statement; 1828 if (isa<CXXConstructorDecl>(Dcl)) { 1829 // C++1y allows return statements in constexpr constructors. 1830 if (!Cxx1yLoc.isValid()) 1831 Cxx1yLoc = S->getLocStart(); 1832 return true; 1833 } 1834 1835 ReturnStmts.push_back(S->getLocStart()); 1836 return true; 1837 1838 case Stmt::CompoundStmtClass: { 1839 // C++1y allows compound-statements. 1840 if (!Cxx1yLoc.isValid()) 1841 Cxx1yLoc = S->getLocStart(); 1842 1843 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1844 for (auto *BodyIt : CompStmt->body()) { 1845 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1846 Cxx1yLoc)) 1847 return false; 1848 } 1849 return true; 1850 } 1851 1852 case Stmt::AttributedStmtClass: 1853 if (!Cxx1yLoc.isValid()) 1854 Cxx1yLoc = S->getLocStart(); 1855 return true; 1856 1857 case Stmt::IfStmtClass: { 1858 // C++1y allows if-statements. 1859 if (!Cxx1yLoc.isValid()) 1860 Cxx1yLoc = S->getLocStart(); 1861 1862 IfStmt *If = cast<IfStmt>(S); 1863 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1864 Cxx1yLoc)) 1865 return false; 1866 if (If->getElse() && 1867 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1868 Cxx1yLoc)) 1869 return false; 1870 return true; 1871 } 1872 1873 case Stmt::WhileStmtClass: 1874 case Stmt::DoStmtClass: 1875 case Stmt::ForStmtClass: 1876 case Stmt::CXXForRangeStmtClass: 1877 case Stmt::ContinueStmtClass: 1878 // C++1y allows all of these. We don't allow them as extensions in C++11, 1879 // because they don't make sense without variable mutation. 1880 if (!SemaRef.getLangOpts().CPlusPlus14) 1881 break; 1882 if (!Cxx1yLoc.isValid()) 1883 Cxx1yLoc = S->getLocStart(); 1884 for (Stmt *SubStmt : S->children()) 1885 if (SubStmt && 1886 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1887 Cxx1yLoc)) 1888 return false; 1889 return true; 1890 1891 case Stmt::SwitchStmtClass: 1892 case Stmt::CaseStmtClass: 1893 case Stmt::DefaultStmtClass: 1894 case Stmt::BreakStmtClass: 1895 // C++1y allows switch-statements, and since they don't need variable 1896 // mutation, we can reasonably allow them in C++11 as an extension. 1897 if (!Cxx1yLoc.isValid()) 1898 Cxx1yLoc = S->getLocStart(); 1899 for (Stmt *SubStmt : S->children()) 1900 if (SubStmt && 1901 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1902 Cxx1yLoc)) 1903 return false; 1904 return true; 1905 1906 default: 1907 if (!isa<Expr>(S)) 1908 break; 1909 1910 // C++1y allows expression-statements. 1911 if (!Cxx1yLoc.isValid()) 1912 Cxx1yLoc = S->getLocStart(); 1913 return true; 1914 } 1915 1916 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1917 << isa<CXXConstructorDecl>(Dcl); 1918 return false; 1919 } 1920 1921 /// Check the body for the given constexpr function declaration only contains 1922 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1923 /// 1924 /// \return true if the body is OK, false if we have diagnosed a problem. 1925 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1926 if (isa<CXXTryStmt>(Body)) { 1927 // C++11 [dcl.constexpr]p3: 1928 // The definition of a constexpr function shall satisfy the following 1929 // constraints: [...] 1930 // - its function-body shall be = delete, = default, or a 1931 // compound-statement 1932 // 1933 // C++11 [dcl.constexpr]p4: 1934 // In the definition of a constexpr constructor, [...] 1935 // - its function-body shall not be a function-try-block; 1936 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1937 << isa<CXXConstructorDecl>(Dcl); 1938 return false; 1939 } 1940 1941 SmallVector<SourceLocation, 4> ReturnStmts; 1942 1943 // - its function-body shall be [...] a compound-statement that contains only 1944 // [... list of cases ...] 1945 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1946 SourceLocation Cxx1yLoc; 1947 for (auto *BodyIt : CompBody->body()) { 1948 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1949 return false; 1950 } 1951 1952 if (Cxx1yLoc.isValid()) 1953 Diag(Cxx1yLoc, 1954 getLangOpts().CPlusPlus14 1955 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1956 : diag::ext_constexpr_body_invalid_stmt) 1957 << isa<CXXConstructorDecl>(Dcl); 1958 1959 if (const CXXConstructorDecl *Constructor 1960 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1961 const CXXRecordDecl *RD = Constructor->getParent(); 1962 // DR1359: 1963 // - every non-variant non-static data member and base class sub-object 1964 // shall be initialized; 1965 // DR1460: 1966 // - if the class is a union having variant members, exactly one of them 1967 // shall be initialized; 1968 if (RD->isUnion()) { 1969 if (Constructor->getNumCtorInitializers() == 0 && 1970 RD->hasVariantMembers()) { 1971 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1972 return false; 1973 } 1974 } else if (!Constructor->isDependentContext() && 1975 !Constructor->isDelegatingConstructor()) { 1976 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1977 1978 // Skip detailed checking if we have enough initializers, and we would 1979 // allow at most one initializer per member. 1980 bool AnyAnonStructUnionMembers = false; 1981 unsigned Fields = 0; 1982 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1983 E = RD->field_end(); I != E; ++I, ++Fields) { 1984 if (I->isAnonymousStructOrUnion()) { 1985 AnyAnonStructUnionMembers = true; 1986 break; 1987 } 1988 } 1989 // DR1460: 1990 // - if the class is a union-like class, but is not a union, for each of 1991 // its anonymous union members having variant members, exactly one of 1992 // them shall be initialized; 1993 if (AnyAnonStructUnionMembers || 1994 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1995 // Check initialization of non-static data members. Base classes are 1996 // always initialized so do not need to be checked. Dependent bases 1997 // might not have initializers in the member initializer list. 1998 llvm::SmallSet<Decl*, 16> Inits; 1999 for (const auto *I: Constructor->inits()) { 2000 if (FieldDecl *FD = I->getMember()) 2001 Inits.insert(FD); 2002 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2003 Inits.insert(ID->chain_begin(), ID->chain_end()); 2004 } 2005 2006 bool Diagnosed = false; 2007 for (auto *I : RD->fields()) 2008 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2009 if (Diagnosed) 2010 return false; 2011 } 2012 } 2013 } else { 2014 if (ReturnStmts.empty()) { 2015 // C++1y doesn't require constexpr functions to contain a 'return' 2016 // statement. We still do, unless the return type might be void, because 2017 // otherwise if there's no return statement, the function cannot 2018 // be used in a core constant expression. 2019 bool OK = getLangOpts().CPlusPlus14 && 2020 (Dcl->getReturnType()->isVoidType() || 2021 Dcl->getReturnType()->isDependentType()); 2022 Diag(Dcl->getLocation(), 2023 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2024 : diag::err_constexpr_body_no_return); 2025 if (!OK) 2026 return false; 2027 } else if (ReturnStmts.size() > 1) { 2028 Diag(ReturnStmts.back(), 2029 getLangOpts().CPlusPlus14 2030 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2031 : diag::ext_constexpr_body_multiple_return); 2032 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2033 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2034 } 2035 } 2036 2037 // C++11 [dcl.constexpr]p5: 2038 // if no function argument values exist such that the function invocation 2039 // substitution would produce a constant expression, the program is 2040 // ill-formed; no diagnostic required. 2041 // C++11 [dcl.constexpr]p3: 2042 // - every constructor call and implicit conversion used in initializing the 2043 // return value shall be one of those allowed in a constant expression. 2044 // C++11 [dcl.constexpr]p4: 2045 // - every constructor involved in initializing non-static data members and 2046 // base class sub-objects shall be a constexpr constructor. 2047 SmallVector<PartialDiagnosticAt, 8> Diags; 2048 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2049 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2050 << isa<CXXConstructorDecl>(Dcl); 2051 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2052 Diag(Diags[I].first, Diags[I].second); 2053 // Don't return false here: we allow this for compatibility in 2054 // system headers. 2055 } 2056 2057 return true; 2058 } 2059 2060 /// isCurrentClassName - Determine whether the identifier II is the 2061 /// name of the class type currently being defined. In the case of 2062 /// nested classes, this will only return true if II is the name of 2063 /// the innermost class. 2064 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2065 const CXXScopeSpec *SS) { 2066 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2067 2068 CXXRecordDecl *CurDecl; 2069 if (SS && SS->isSet() && !SS->isInvalid()) { 2070 DeclContext *DC = computeDeclContext(*SS, true); 2071 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2072 } else 2073 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2074 2075 if (CurDecl && CurDecl->getIdentifier()) 2076 return &II == CurDecl->getIdentifier(); 2077 return false; 2078 } 2079 2080 /// \brief Determine whether the identifier II is a typo for the name of 2081 /// the class type currently being defined. If so, update it to the identifier 2082 /// that should have been used. 2083 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2084 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2085 2086 if (!getLangOpts().SpellChecking) 2087 return false; 2088 2089 CXXRecordDecl *CurDecl; 2090 if (SS && SS->isSet() && !SS->isInvalid()) { 2091 DeclContext *DC = computeDeclContext(*SS, true); 2092 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2093 } else 2094 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2095 2096 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2097 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2098 < II->getLength()) { 2099 II = CurDecl->getIdentifier(); 2100 return true; 2101 } 2102 2103 return false; 2104 } 2105 2106 /// \brief Determine whether the given class is a base class of the given 2107 /// class, including looking at dependent bases. 2108 static bool findCircularInheritance(const CXXRecordDecl *Class, 2109 const CXXRecordDecl *Current) { 2110 SmallVector<const CXXRecordDecl*, 8> Queue; 2111 2112 Class = Class->getCanonicalDecl(); 2113 while (true) { 2114 for (const auto &I : Current->bases()) { 2115 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2116 if (!Base) 2117 continue; 2118 2119 Base = Base->getDefinition(); 2120 if (!Base) 2121 continue; 2122 2123 if (Base->getCanonicalDecl() == Class) 2124 return true; 2125 2126 Queue.push_back(Base); 2127 } 2128 2129 if (Queue.empty()) 2130 return false; 2131 2132 Current = Queue.pop_back_val(); 2133 } 2134 2135 return false; 2136 } 2137 2138 /// \brief Check the validity of a C++ base class specifier. 2139 /// 2140 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2141 /// and returns NULL otherwise. 2142 CXXBaseSpecifier * 2143 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2144 SourceRange SpecifierRange, 2145 bool Virtual, AccessSpecifier Access, 2146 TypeSourceInfo *TInfo, 2147 SourceLocation EllipsisLoc) { 2148 QualType BaseType = TInfo->getType(); 2149 2150 // C++ [class.union]p1: 2151 // A union shall not have base classes. 2152 if (Class->isUnion()) { 2153 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2154 << SpecifierRange; 2155 return nullptr; 2156 } 2157 2158 if (EllipsisLoc.isValid() && 2159 !TInfo->getType()->containsUnexpandedParameterPack()) { 2160 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2161 << TInfo->getTypeLoc().getSourceRange(); 2162 EllipsisLoc = SourceLocation(); 2163 } 2164 2165 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2166 2167 if (BaseType->isDependentType()) { 2168 // Make sure that we don't have circular inheritance among our dependent 2169 // bases. For non-dependent bases, the check for completeness below handles 2170 // this. 2171 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2172 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2173 ((BaseDecl = BaseDecl->getDefinition()) && 2174 findCircularInheritance(Class, BaseDecl))) { 2175 Diag(BaseLoc, diag::err_circular_inheritance) 2176 << BaseType << Context.getTypeDeclType(Class); 2177 2178 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2179 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2180 << BaseType; 2181 2182 return nullptr; 2183 } 2184 } 2185 2186 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2187 Class->getTagKind() == TTK_Class, 2188 Access, TInfo, EllipsisLoc); 2189 } 2190 2191 // Base specifiers must be record types. 2192 if (!BaseType->isRecordType()) { 2193 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2194 return nullptr; 2195 } 2196 2197 // C++ [class.union]p1: 2198 // A union shall not be used as a base class. 2199 if (BaseType->isUnionType()) { 2200 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2201 return nullptr; 2202 } 2203 2204 // For the MS ABI, propagate DLL attributes to base class templates. 2205 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2206 if (Attr *ClassAttr = getDLLAttr(Class)) { 2207 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2208 BaseType->getAsCXXRecordDecl())) { 2209 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2210 BaseLoc); 2211 } 2212 } 2213 } 2214 2215 // C++ [class.derived]p2: 2216 // The class-name in a base-specifier shall not be an incompletely 2217 // defined class. 2218 if (RequireCompleteType(BaseLoc, BaseType, 2219 diag::err_incomplete_base_class, SpecifierRange)) { 2220 Class->setInvalidDecl(); 2221 return nullptr; 2222 } 2223 2224 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2225 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2226 assert(BaseDecl && "Record type has no declaration"); 2227 BaseDecl = BaseDecl->getDefinition(); 2228 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2229 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2230 assert(CXXBaseDecl && "Base type is not a C++ type"); 2231 2232 // A class which contains a flexible array member is not suitable for use as a 2233 // base class: 2234 // - If the layout determines that a base comes before another base, 2235 // the flexible array member would index into the subsequent base. 2236 // - If the layout determines that base comes before the derived class, 2237 // the flexible array member would index into the derived class. 2238 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2239 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2240 << CXXBaseDecl->getDeclName(); 2241 return nullptr; 2242 } 2243 2244 // C++ [class]p3: 2245 // If a class is marked final and it appears as a base-type-specifier in 2246 // base-clause, the program is ill-formed. 2247 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2248 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2249 << CXXBaseDecl->getDeclName() 2250 << FA->isSpelledAsSealed(); 2251 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2252 << CXXBaseDecl->getDeclName() << FA->getRange(); 2253 return nullptr; 2254 } 2255 2256 if (BaseDecl->isInvalidDecl()) 2257 Class->setInvalidDecl(); 2258 2259 // Create the base specifier. 2260 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2261 Class->getTagKind() == TTK_Class, 2262 Access, TInfo, EllipsisLoc); 2263 } 2264 2265 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2266 /// one entry in the base class list of a class specifier, for 2267 /// example: 2268 /// class foo : public bar, virtual private baz { 2269 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2270 BaseResult 2271 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2272 ParsedAttributes &Attributes, 2273 bool Virtual, AccessSpecifier Access, 2274 ParsedType basetype, SourceLocation BaseLoc, 2275 SourceLocation EllipsisLoc) { 2276 if (!classdecl) 2277 return true; 2278 2279 AdjustDeclIfTemplate(classdecl); 2280 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2281 if (!Class) 2282 return true; 2283 2284 // We haven't yet attached the base specifiers. 2285 Class->setIsParsingBaseSpecifiers(); 2286 2287 // We do not support any C++11 attributes on base-specifiers yet. 2288 // Diagnose any attributes we see. 2289 if (!Attributes.empty()) { 2290 for (AttributeList *Attr = Attributes.getList(); Attr; 2291 Attr = Attr->getNext()) { 2292 if (Attr->isInvalid() || 2293 Attr->getKind() == AttributeList::IgnoredAttribute) 2294 continue; 2295 Diag(Attr->getLoc(), 2296 Attr->getKind() == AttributeList::UnknownAttribute 2297 ? diag::warn_unknown_attribute_ignored 2298 : diag::err_base_specifier_attribute) 2299 << Attr->getName(); 2300 } 2301 } 2302 2303 TypeSourceInfo *TInfo = nullptr; 2304 GetTypeFromParser(basetype, &TInfo); 2305 2306 if (EllipsisLoc.isInvalid() && 2307 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2308 UPPC_BaseType)) 2309 return true; 2310 2311 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2312 Virtual, Access, TInfo, 2313 EllipsisLoc)) 2314 return BaseSpec; 2315 else 2316 Class->setInvalidDecl(); 2317 2318 return true; 2319 } 2320 2321 /// Use small set to collect indirect bases. As this is only used 2322 /// locally, there's no need to abstract the small size parameter. 2323 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2324 2325 /// \brief Recursively add the bases of Type. Don't add Type itself. 2326 static void 2327 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2328 const QualType &Type) 2329 { 2330 // Even though the incoming type is a base, it might not be 2331 // a class -- it could be a template parm, for instance. 2332 if (auto Rec = Type->getAs<RecordType>()) { 2333 auto Decl = Rec->getAsCXXRecordDecl(); 2334 2335 // Iterate over its bases. 2336 for (const auto &BaseSpec : Decl->bases()) { 2337 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2338 .getUnqualifiedType(); 2339 if (Set.insert(Base).second) 2340 // If we've not already seen it, recurse. 2341 NoteIndirectBases(Context, Set, Base); 2342 } 2343 } 2344 } 2345 2346 /// \brief Performs the actual work of attaching the given base class 2347 /// specifiers to a C++ class. 2348 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2349 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2350 if (Bases.empty()) 2351 return false; 2352 2353 // Used to keep track of which base types we have already seen, so 2354 // that we can properly diagnose redundant direct base types. Note 2355 // that the key is always the unqualified canonical type of the base 2356 // class. 2357 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2358 2359 // Used to track indirect bases so we can see if a direct base is 2360 // ambiguous. 2361 IndirectBaseSet IndirectBaseTypes; 2362 2363 // Copy non-redundant base specifiers into permanent storage. 2364 unsigned NumGoodBases = 0; 2365 bool Invalid = false; 2366 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2367 QualType NewBaseType 2368 = Context.getCanonicalType(Bases[idx]->getType()); 2369 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2370 2371 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2372 if (KnownBase) { 2373 // C++ [class.mi]p3: 2374 // A class shall not be specified as a direct base class of a 2375 // derived class more than once. 2376 Diag(Bases[idx]->getLocStart(), 2377 diag::err_duplicate_base_class) 2378 << KnownBase->getType() 2379 << Bases[idx]->getSourceRange(); 2380 2381 // Delete the duplicate base class specifier; we're going to 2382 // overwrite its pointer later. 2383 Context.Deallocate(Bases[idx]); 2384 2385 Invalid = true; 2386 } else { 2387 // Okay, add this new base class. 2388 KnownBase = Bases[idx]; 2389 Bases[NumGoodBases++] = Bases[idx]; 2390 2391 // Note this base's direct & indirect bases, if there could be ambiguity. 2392 if (Bases.size() > 1) 2393 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2394 2395 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2396 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2397 if (Class->isInterface() && 2398 (!RD->isInterfaceLike() || 2399 KnownBase->getAccessSpecifier() != AS_public)) { 2400 // The Microsoft extension __interface does not permit bases that 2401 // are not themselves public interfaces. 2402 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2403 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 2404 << RD->getSourceRange(); 2405 Invalid = true; 2406 } 2407 if (RD->hasAttr<WeakAttr>()) 2408 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2409 } 2410 } 2411 } 2412 2413 // Attach the remaining base class specifiers to the derived class. 2414 Class->setBases(Bases.data(), NumGoodBases); 2415 2416 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2417 // Check whether this direct base is inaccessible due to ambiguity. 2418 QualType BaseType = Bases[idx]->getType(); 2419 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2420 .getUnqualifiedType(); 2421 2422 if (IndirectBaseTypes.count(CanonicalBase)) { 2423 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2424 /*DetectVirtual=*/true); 2425 bool found 2426 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2427 assert(found); 2428 (void)found; 2429 2430 if (Paths.isAmbiguous(CanonicalBase)) 2431 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2432 << BaseType << getAmbiguousPathsDisplayString(Paths) 2433 << Bases[idx]->getSourceRange(); 2434 else 2435 assert(Bases[idx]->isVirtual()); 2436 } 2437 2438 // Delete the base class specifier, since its data has been copied 2439 // into the CXXRecordDecl. 2440 Context.Deallocate(Bases[idx]); 2441 } 2442 2443 return Invalid; 2444 } 2445 2446 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2447 /// class, after checking whether there are any duplicate base 2448 /// classes. 2449 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2450 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2451 if (!ClassDecl || Bases.empty()) 2452 return; 2453 2454 AdjustDeclIfTemplate(ClassDecl); 2455 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2456 } 2457 2458 /// \brief Determine whether the type \p Derived is a C++ class that is 2459 /// derived from the type \p Base. 2460 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2461 if (!getLangOpts().CPlusPlus) 2462 return false; 2463 2464 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2465 if (!DerivedRD) 2466 return false; 2467 2468 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2469 if (!BaseRD) 2470 return false; 2471 2472 // If either the base or the derived type is invalid, don't try to 2473 // check whether one is derived from the other. 2474 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2475 return false; 2476 2477 // FIXME: In a modules build, do we need the entire path to be visible for us 2478 // to be able to use the inheritance relationship? 2479 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2480 return false; 2481 2482 return DerivedRD->isDerivedFrom(BaseRD); 2483 } 2484 2485 /// \brief Determine whether the type \p Derived is a C++ class that is 2486 /// derived from the type \p Base. 2487 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2488 CXXBasePaths &Paths) { 2489 if (!getLangOpts().CPlusPlus) 2490 return false; 2491 2492 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2493 if (!DerivedRD) 2494 return false; 2495 2496 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2497 if (!BaseRD) 2498 return false; 2499 2500 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2501 return false; 2502 2503 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2504 } 2505 2506 static void BuildBasePathArray(const CXXBasePath &Path, 2507 CXXCastPath &BasePathArray) { 2508 // We first go backward and check if we have a virtual base. 2509 // FIXME: It would be better if CXXBasePath had the base specifier for 2510 // the nearest virtual base. 2511 unsigned Start = 0; 2512 for (unsigned I = Path.size(); I != 0; --I) { 2513 if (Path[I - 1].Base->isVirtual()) { 2514 Start = I - 1; 2515 break; 2516 } 2517 } 2518 2519 // Now add all bases. 2520 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2521 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2522 } 2523 2524 2525 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2526 CXXCastPath &BasePathArray) { 2527 assert(BasePathArray.empty() && "Base path array must be empty!"); 2528 assert(Paths.isRecordingPaths() && "Must record paths!"); 2529 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2530 } 2531 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2532 /// conversion (where Derived and Base are class types) is 2533 /// well-formed, meaning that the conversion is unambiguous (and 2534 /// that all of the base classes are accessible). Returns true 2535 /// and emits a diagnostic if the code is ill-formed, returns false 2536 /// otherwise. Loc is the location where this routine should point to 2537 /// if there is an error, and Range is the source range to highlight 2538 /// if there is an error. 2539 /// 2540 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2541 /// diagnostic for the respective type of error will be suppressed, but the 2542 /// check for ill-formed code will still be performed. 2543 bool 2544 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2545 unsigned InaccessibleBaseID, 2546 unsigned AmbigiousBaseConvID, 2547 SourceLocation Loc, SourceRange Range, 2548 DeclarationName Name, 2549 CXXCastPath *BasePath, 2550 bool IgnoreAccess) { 2551 // First, determine whether the path from Derived to Base is 2552 // ambiguous. This is slightly more expensive than checking whether 2553 // the Derived to Base conversion exists, because here we need to 2554 // explore multiple paths to determine if there is an ambiguity. 2555 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2556 /*DetectVirtual=*/false); 2557 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2558 if (!DerivationOkay) 2559 return true; 2560 2561 const CXXBasePath *Path = nullptr; 2562 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2563 Path = &Paths.front(); 2564 2565 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2566 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2567 // user to access such bases. 2568 if (!Path && getLangOpts().MSVCCompat) { 2569 for (const CXXBasePath &PossiblePath : Paths) { 2570 if (PossiblePath.size() == 1) { 2571 Path = &PossiblePath; 2572 if (AmbigiousBaseConvID) 2573 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2574 << Base << Derived << Range; 2575 break; 2576 } 2577 } 2578 } 2579 2580 if (Path) { 2581 if (!IgnoreAccess) { 2582 // Check that the base class can be accessed. 2583 switch ( 2584 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2585 case AR_inaccessible: 2586 return true; 2587 case AR_accessible: 2588 case AR_dependent: 2589 case AR_delayed: 2590 break; 2591 } 2592 } 2593 2594 // Build a base path if necessary. 2595 if (BasePath) 2596 ::BuildBasePathArray(*Path, *BasePath); 2597 return false; 2598 } 2599 2600 if (AmbigiousBaseConvID) { 2601 // We know that the derived-to-base conversion is ambiguous, and 2602 // we're going to produce a diagnostic. Perform the derived-to-base 2603 // search just one more time to compute all of the possible paths so 2604 // that we can print them out. This is more expensive than any of 2605 // the previous derived-to-base checks we've done, but at this point 2606 // performance isn't as much of an issue. 2607 Paths.clear(); 2608 Paths.setRecordingPaths(true); 2609 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2610 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2611 (void)StillOkay; 2612 2613 // Build up a textual representation of the ambiguous paths, e.g., 2614 // D -> B -> A, that will be used to illustrate the ambiguous 2615 // conversions in the diagnostic. We only print one of the paths 2616 // to each base class subobject. 2617 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2618 2619 Diag(Loc, AmbigiousBaseConvID) 2620 << Derived << Base << PathDisplayStr << Range << Name; 2621 } 2622 return true; 2623 } 2624 2625 bool 2626 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2627 SourceLocation Loc, SourceRange Range, 2628 CXXCastPath *BasePath, 2629 bool IgnoreAccess) { 2630 return CheckDerivedToBaseConversion( 2631 Derived, Base, diag::err_upcast_to_inaccessible_base, 2632 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2633 BasePath, IgnoreAccess); 2634 } 2635 2636 2637 /// @brief Builds a string representing ambiguous paths from a 2638 /// specific derived class to different subobjects of the same base 2639 /// class. 2640 /// 2641 /// This function builds a string that can be used in error messages 2642 /// to show the different paths that one can take through the 2643 /// inheritance hierarchy to go from the derived class to different 2644 /// subobjects of a base class. The result looks something like this: 2645 /// @code 2646 /// struct D -> struct B -> struct A 2647 /// struct D -> struct C -> struct A 2648 /// @endcode 2649 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2650 std::string PathDisplayStr; 2651 std::set<unsigned> DisplayedPaths; 2652 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2653 Path != Paths.end(); ++Path) { 2654 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2655 // We haven't displayed a path to this particular base 2656 // class subobject yet. 2657 PathDisplayStr += "\n "; 2658 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2659 for (CXXBasePath::const_iterator Element = Path->begin(); 2660 Element != Path->end(); ++Element) 2661 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2662 } 2663 } 2664 2665 return PathDisplayStr; 2666 } 2667 2668 //===----------------------------------------------------------------------===// 2669 // C++ class member Handling 2670 //===----------------------------------------------------------------------===// 2671 2672 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2673 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2674 SourceLocation ASLoc, 2675 SourceLocation ColonLoc, 2676 AttributeList *Attrs) { 2677 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2678 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2679 ASLoc, ColonLoc); 2680 CurContext->addHiddenDecl(ASDecl); 2681 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2682 } 2683 2684 /// CheckOverrideControl - Check C++11 override control semantics. 2685 void Sema::CheckOverrideControl(NamedDecl *D) { 2686 if (D->isInvalidDecl()) 2687 return; 2688 2689 // We only care about "override" and "final" declarations. 2690 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2691 return; 2692 2693 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2694 2695 // We can't check dependent instance methods. 2696 if (MD && MD->isInstance() && 2697 (MD->getParent()->hasAnyDependentBases() || 2698 MD->getType()->isDependentType())) 2699 return; 2700 2701 if (MD && !MD->isVirtual()) { 2702 // If we have a non-virtual method, check if if hides a virtual method. 2703 // (In that case, it's most likely the method has the wrong type.) 2704 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2705 FindHiddenVirtualMethods(MD, OverloadedMethods); 2706 2707 if (!OverloadedMethods.empty()) { 2708 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2709 Diag(OA->getLocation(), 2710 diag::override_keyword_hides_virtual_member_function) 2711 << "override" << (OverloadedMethods.size() > 1); 2712 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2713 Diag(FA->getLocation(), 2714 diag::override_keyword_hides_virtual_member_function) 2715 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2716 << (OverloadedMethods.size() > 1); 2717 } 2718 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2719 MD->setInvalidDecl(); 2720 return; 2721 } 2722 // Fall through into the general case diagnostic. 2723 // FIXME: We might want to attempt typo correction here. 2724 } 2725 2726 if (!MD || !MD->isVirtual()) { 2727 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2728 Diag(OA->getLocation(), 2729 diag::override_keyword_only_allowed_on_virtual_member_functions) 2730 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2731 D->dropAttr<OverrideAttr>(); 2732 } 2733 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2734 Diag(FA->getLocation(), 2735 diag::override_keyword_only_allowed_on_virtual_member_functions) 2736 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2737 << FixItHint::CreateRemoval(FA->getLocation()); 2738 D->dropAttr<FinalAttr>(); 2739 } 2740 return; 2741 } 2742 2743 // C++11 [class.virtual]p5: 2744 // If a function is marked with the virt-specifier override and 2745 // does not override a member function of a base class, the program is 2746 // ill-formed. 2747 bool HasOverriddenMethods = 2748 MD->begin_overridden_methods() != MD->end_overridden_methods(); 2749 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2750 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2751 << MD->getDeclName(); 2752 } 2753 2754 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2755 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2756 return; 2757 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2758 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2759 return; 2760 2761 SourceLocation Loc = MD->getLocation(); 2762 SourceLocation SpellingLoc = Loc; 2763 if (getSourceManager().isMacroArgExpansion(Loc)) 2764 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 2765 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2766 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2767 return; 2768 2769 if (MD->size_overridden_methods() > 0) { 2770 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2771 ? diag::warn_destructor_marked_not_override_overriding 2772 : diag::warn_function_marked_not_override_overriding; 2773 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2774 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2775 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2776 } 2777 } 2778 2779 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2780 /// function overrides a virtual member function marked 'final', according to 2781 /// C++11 [class.virtual]p4. 2782 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2783 const CXXMethodDecl *Old) { 2784 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2785 if (!FA) 2786 return false; 2787 2788 Diag(New->getLocation(), diag::err_final_function_overridden) 2789 << New->getDeclName() 2790 << FA->isSpelledAsSealed(); 2791 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2792 return true; 2793 } 2794 2795 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2796 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2797 // FIXME: Destruction of ObjC lifetime types has side-effects. 2798 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2799 return !RD->isCompleteDefinition() || 2800 !RD->hasTrivialDefaultConstructor() || 2801 !RD->hasTrivialDestructor(); 2802 return false; 2803 } 2804 2805 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2806 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2807 if (it->isDeclspecPropertyAttribute()) 2808 return it; 2809 return nullptr; 2810 } 2811 2812 // Check if there is a field shadowing. 2813 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2814 DeclarationName FieldName, 2815 const CXXRecordDecl *RD) { 2816 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2817 return; 2818 2819 // To record a shadowed field in a base 2820 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2821 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2822 CXXBasePath &Path) { 2823 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2824 // Record an ambiguous path directly 2825 if (Bases.find(Base) != Bases.end()) 2826 return true; 2827 for (const auto Field : Base->lookup(FieldName)) { 2828 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2829 Field->getAccess() != AS_private) { 2830 assert(Field->getAccess() != AS_none); 2831 assert(Bases.find(Base) == Bases.end()); 2832 Bases[Base] = Field; 2833 return true; 2834 } 2835 } 2836 return false; 2837 }; 2838 2839 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2840 /*DetectVirtual=*/true); 2841 if (!RD->lookupInBases(FieldShadowed, Paths)) 2842 return; 2843 2844 for (const auto &P : Paths) { 2845 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2846 auto It = Bases.find(Base); 2847 // Skip duplicated bases 2848 if (It == Bases.end()) 2849 continue; 2850 auto BaseField = It->second; 2851 assert(BaseField->getAccess() != AS_private); 2852 if (AS_none != 2853 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2854 Diag(Loc, diag::warn_shadow_field) 2855 << FieldName.getAsString() << RD->getName() << Base->getName(); 2856 Diag(BaseField->getLocation(), diag::note_shadow_field); 2857 Bases.erase(It); 2858 } 2859 } 2860 } 2861 2862 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2863 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2864 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2865 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2866 /// present (but parsing it has been deferred). 2867 NamedDecl * 2868 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2869 MultiTemplateParamsArg TemplateParameterLists, 2870 Expr *BW, const VirtSpecifiers &VS, 2871 InClassInitStyle InitStyle) { 2872 const DeclSpec &DS = D.getDeclSpec(); 2873 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2874 DeclarationName Name = NameInfo.getName(); 2875 SourceLocation Loc = NameInfo.getLoc(); 2876 2877 // For anonymous bitfields, the location should point to the type. 2878 if (Loc.isInvalid()) 2879 Loc = D.getLocStart(); 2880 2881 Expr *BitWidth = static_cast<Expr*>(BW); 2882 2883 assert(isa<CXXRecordDecl>(CurContext)); 2884 assert(!DS.isFriendSpecified()); 2885 2886 bool isFunc = D.isDeclarationOfFunction(); 2887 AttributeList *MSPropertyAttr = 2888 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2889 2890 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2891 // The Microsoft extension __interface only permits public member functions 2892 // and prohibits constructors, destructors, operators, non-public member 2893 // functions, static methods and data members. 2894 unsigned InvalidDecl; 2895 bool ShowDeclName = true; 2896 if (!isFunc && 2897 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2898 InvalidDecl = 0; 2899 else if (!isFunc) 2900 InvalidDecl = 1; 2901 else if (AS != AS_public) 2902 InvalidDecl = 2; 2903 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2904 InvalidDecl = 3; 2905 else switch (Name.getNameKind()) { 2906 case DeclarationName::CXXConstructorName: 2907 InvalidDecl = 4; 2908 ShowDeclName = false; 2909 break; 2910 2911 case DeclarationName::CXXDestructorName: 2912 InvalidDecl = 5; 2913 ShowDeclName = false; 2914 break; 2915 2916 case DeclarationName::CXXOperatorName: 2917 case DeclarationName::CXXConversionFunctionName: 2918 InvalidDecl = 6; 2919 break; 2920 2921 default: 2922 InvalidDecl = 0; 2923 break; 2924 } 2925 2926 if (InvalidDecl) { 2927 if (ShowDeclName) 2928 Diag(Loc, diag::err_invalid_member_in_interface) 2929 << (InvalidDecl-1) << Name; 2930 else 2931 Diag(Loc, diag::err_invalid_member_in_interface) 2932 << (InvalidDecl-1) << ""; 2933 return nullptr; 2934 } 2935 } 2936 2937 // C++ 9.2p6: A member shall not be declared to have automatic storage 2938 // duration (auto, register) or with the extern storage-class-specifier. 2939 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2940 // data members and cannot be applied to names declared const or static, 2941 // and cannot be applied to reference members. 2942 switch (DS.getStorageClassSpec()) { 2943 case DeclSpec::SCS_unspecified: 2944 case DeclSpec::SCS_typedef: 2945 case DeclSpec::SCS_static: 2946 break; 2947 case DeclSpec::SCS_mutable: 2948 if (isFunc) { 2949 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2950 2951 // FIXME: It would be nicer if the keyword was ignored only for this 2952 // declarator. Otherwise we could get follow-up errors. 2953 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2954 } 2955 break; 2956 default: 2957 Diag(DS.getStorageClassSpecLoc(), 2958 diag::err_storageclass_invalid_for_member); 2959 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2960 break; 2961 } 2962 2963 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2964 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2965 !isFunc); 2966 2967 if (DS.isConstexprSpecified() && isInstField) { 2968 SemaDiagnosticBuilder B = 2969 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2970 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2971 if (InitStyle == ICIS_NoInit) { 2972 B << 0 << 0; 2973 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2974 B << FixItHint::CreateRemoval(ConstexprLoc); 2975 else { 2976 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2977 D.getMutableDeclSpec().ClearConstexprSpec(); 2978 const char *PrevSpec; 2979 unsigned DiagID; 2980 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2981 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2982 (void)Failed; 2983 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2984 } 2985 } else { 2986 B << 1; 2987 const char *PrevSpec; 2988 unsigned DiagID; 2989 if (D.getMutableDeclSpec().SetStorageClassSpec( 2990 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2991 Context.getPrintingPolicy())) { 2992 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2993 "This is the only DeclSpec that should fail to be applied"); 2994 B << 1; 2995 } else { 2996 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2997 isInstField = false; 2998 } 2999 } 3000 } 3001 3002 NamedDecl *Member; 3003 if (isInstField) { 3004 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3005 3006 // Data members must have identifiers for names. 3007 if (!Name.isIdentifier()) { 3008 Diag(Loc, diag::err_bad_variable_name) 3009 << Name; 3010 return nullptr; 3011 } 3012 3013 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3014 3015 // Member field could not be with "template" keyword. 3016 // So TemplateParameterLists should be empty in this case. 3017 if (TemplateParameterLists.size()) { 3018 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3019 if (TemplateParams->size()) { 3020 // There is no such thing as a member field template. 3021 Diag(D.getIdentifierLoc(), diag::err_template_member) 3022 << II 3023 << SourceRange(TemplateParams->getTemplateLoc(), 3024 TemplateParams->getRAngleLoc()); 3025 } else { 3026 // There is an extraneous 'template<>' for this member. 3027 Diag(TemplateParams->getTemplateLoc(), 3028 diag::err_template_member_noparams) 3029 << II 3030 << SourceRange(TemplateParams->getTemplateLoc(), 3031 TemplateParams->getRAngleLoc()); 3032 } 3033 return nullptr; 3034 } 3035 3036 if (SS.isSet() && !SS.isInvalid()) { 3037 // The user provided a superfluous scope specifier inside a class 3038 // definition: 3039 // 3040 // class X { 3041 // int X::member; 3042 // }; 3043 if (DeclContext *DC = computeDeclContext(SS, false)) 3044 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 3045 else 3046 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3047 << Name << SS.getRange(); 3048 3049 SS.clear(); 3050 } 3051 3052 if (MSPropertyAttr) { 3053 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3054 BitWidth, InitStyle, AS, MSPropertyAttr); 3055 if (!Member) 3056 return nullptr; 3057 isInstField = false; 3058 } else { 3059 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3060 BitWidth, InitStyle, AS); 3061 if (!Member) 3062 return nullptr; 3063 } 3064 3065 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3066 } else { 3067 Member = HandleDeclarator(S, D, TemplateParameterLists); 3068 if (!Member) 3069 return nullptr; 3070 3071 // Non-instance-fields can't have a bitfield. 3072 if (BitWidth) { 3073 if (Member->isInvalidDecl()) { 3074 // don't emit another diagnostic. 3075 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3076 // C++ 9.6p3: A bit-field shall not be a static member. 3077 // "static member 'A' cannot be a bit-field" 3078 Diag(Loc, diag::err_static_not_bitfield) 3079 << Name << BitWidth->getSourceRange(); 3080 } else if (isa<TypedefDecl>(Member)) { 3081 // "typedef member 'x' cannot be a bit-field" 3082 Diag(Loc, diag::err_typedef_not_bitfield) 3083 << Name << BitWidth->getSourceRange(); 3084 } else { 3085 // A function typedef ("typedef int f(); f a;"). 3086 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3087 Diag(Loc, diag::err_not_integral_type_bitfield) 3088 << Name << cast<ValueDecl>(Member)->getType() 3089 << BitWidth->getSourceRange(); 3090 } 3091 3092 BitWidth = nullptr; 3093 Member->setInvalidDecl(); 3094 } 3095 3096 Member->setAccess(AS); 3097 3098 // If we have declared a member function template or static data member 3099 // template, set the access of the templated declaration as well. 3100 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3101 FunTmpl->getTemplatedDecl()->setAccess(AS); 3102 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3103 VarTmpl->getTemplatedDecl()->setAccess(AS); 3104 } 3105 3106 if (VS.isOverrideSpecified()) 3107 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3108 if (VS.isFinalSpecified()) 3109 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3110 VS.isFinalSpelledSealed())); 3111 3112 if (VS.getLastLocation().isValid()) { 3113 // Update the end location of a method that has a virt-specifiers. 3114 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3115 MD->setRangeEnd(VS.getLastLocation()); 3116 } 3117 3118 CheckOverrideControl(Member); 3119 3120 assert((Name || isInstField) && "No identifier for non-field ?"); 3121 3122 if (isInstField) { 3123 FieldDecl *FD = cast<FieldDecl>(Member); 3124 FieldCollector->Add(FD); 3125 3126 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3127 // Remember all explicit private FieldDecls that have a name, no side 3128 // effects and are not part of a dependent type declaration. 3129 if (!FD->isImplicit() && FD->getDeclName() && 3130 FD->getAccess() == AS_private && 3131 !FD->hasAttr<UnusedAttr>() && 3132 !FD->getParent()->isDependentContext() && 3133 !InitializationHasSideEffects(*FD)) 3134 UnusedPrivateFields.insert(FD); 3135 } 3136 } 3137 3138 return Member; 3139 } 3140 3141 namespace { 3142 class UninitializedFieldVisitor 3143 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3144 Sema &S; 3145 // List of Decls to generate a warning on. Also remove Decls that become 3146 // initialized. 3147 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3148 // List of base classes of the record. Classes are removed after their 3149 // initializers. 3150 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3151 // Vector of decls to be removed from the Decl set prior to visiting the 3152 // nodes. These Decls may have been initialized in the prior initializer. 3153 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3154 // If non-null, add a note to the warning pointing back to the constructor. 3155 const CXXConstructorDecl *Constructor; 3156 // Variables to hold state when processing an initializer list. When 3157 // InitList is true, special case initialization of FieldDecls matching 3158 // InitListFieldDecl. 3159 bool InitList; 3160 FieldDecl *InitListFieldDecl; 3161 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3162 3163 public: 3164 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3165 UninitializedFieldVisitor(Sema &S, 3166 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3167 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3168 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3169 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3170 3171 // Returns true if the use of ME is not an uninitialized use. 3172 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3173 bool CheckReferenceOnly) { 3174 llvm::SmallVector<FieldDecl*, 4> Fields; 3175 bool ReferenceField = false; 3176 while (ME) { 3177 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3178 if (!FD) 3179 return false; 3180 Fields.push_back(FD); 3181 if (FD->getType()->isReferenceType()) 3182 ReferenceField = true; 3183 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3184 } 3185 3186 // Binding a reference to an unintialized field is not an 3187 // uninitialized use. 3188 if (CheckReferenceOnly && !ReferenceField) 3189 return true; 3190 3191 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3192 // Discard the first field since it is the field decl that is being 3193 // initialized. 3194 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3195 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3196 } 3197 3198 for (auto UsedIter = UsedFieldIndex.begin(), 3199 UsedEnd = UsedFieldIndex.end(), 3200 OrigIter = InitFieldIndex.begin(), 3201 OrigEnd = InitFieldIndex.end(); 3202 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3203 if (*UsedIter < *OrigIter) 3204 return true; 3205 if (*UsedIter > *OrigIter) 3206 break; 3207 } 3208 3209 return false; 3210 } 3211 3212 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3213 bool AddressOf) { 3214 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3215 return; 3216 3217 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3218 // or union. 3219 MemberExpr *FieldME = ME; 3220 3221 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3222 3223 Expr *Base = ME; 3224 while (MemberExpr *SubME = 3225 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3226 3227 if (isa<VarDecl>(SubME->getMemberDecl())) 3228 return; 3229 3230 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3231 if (!FD->isAnonymousStructOrUnion()) 3232 FieldME = SubME; 3233 3234 if (!FieldME->getType().isPODType(S.Context)) 3235 AllPODFields = false; 3236 3237 Base = SubME->getBase(); 3238 } 3239 3240 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3241 return; 3242 3243 if (AddressOf && AllPODFields) 3244 return; 3245 3246 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3247 3248 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3249 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3250 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3251 } 3252 3253 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3254 QualType T = BaseCast->getType(); 3255 if (T->isPointerType() && 3256 BaseClasses.count(T->getPointeeType())) { 3257 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3258 << T->getPointeeType() << FoundVD; 3259 } 3260 } 3261 } 3262 3263 if (!Decls.count(FoundVD)) 3264 return; 3265 3266 const bool IsReference = FoundVD->getType()->isReferenceType(); 3267 3268 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3269 // Special checking for initializer lists. 3270 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3271 return; 3272 } 3273 } else { 3274 // Prevent double warnings on use of unbounded references. 3275 if (CheckReferenceOnly && !IsReference) 3276 return; 3277 } 3278 3279 unsigned diag = IsReference 3280 ? diag::warn_reference_field_is_uninit 3281 : diag::warn_field_is_uninit; 3282 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3283 if (Constructor) 3284 S.Diag(Constructor->getLocation(), 3285 diag::note_uninit_in_this_constructor) 3286 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3287 3288 } 3289 3290 void HandleValue(Expr *E, bool AddressOf) { 3291 E = E->IgnoreParens(); 3292 3293 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3294 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3295 AddressOf /*AddressOf*/); 3296 return; 3297 } 3298 3299 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3300 Visit(CO->getCond()); 3301 HandleValue(CO->getTrueExpr(), AddressOf); 3302 HandleValue(CO->getFalseExpr(), AddressOf); 3303 return; 3304 } 3305 3306 if (BinaryConditionalOperator *BCO = 3307 dyn_cast<BinaryConditionalOperator>(E)) { 3308 Visit(BCO->getCond()); 3309 HandleValue(BCO->getFalseExpr(), AddressOf); 3310 return; 3311 } 3312 3313 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3314 HandleValue(OVE->getSourceExpr(), AddressOf); 3315 return; 3316 } 3317 3318 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3319 switch (BO->getOpcode()) { 3320 default: 3321 break; 3322 case(BO_PtrMemD): 3323 case(BO_PtrMemI): 3324 HandleValue(BO->getLHS(), AddressOf); 3325 Visit(BO->getRHS()); 3326 return; 3327 case(BO_Comma): 3328 Visit(BO->getLHS()); 3329 HandleValue(BO->getRHS(), AddressOf); 3330 return; 3331 } 3332 } 3333 3334 Visit(E); 3335 } 3336 3337 void CheckInitListExpr(InitListExpr *ILE) { 3338 InitFieldIndex.push_back(0); 3339 for (auto Child : ILE->children()) { 3340 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3341 CheckInitListExpr(SubList); 3342 } else { 3343 Visit(Child); 3344 } 3345 ++InitFieldIndex.back(); 3346 } 3347 InitFieldIndex.pop_back(); 3348 } 3349 3350 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3351 FieldDecl *Field, const Type *BaseClass) { 3352 // Remove Decls that may have been initialized in the previous 3353 // initializer. 3354 for (ValueDecl* VD : DeclsToRemove) 3355 Decls.erase(VD); 3356 DeclsToRemove.clear(); 3357 3358 Constructor = FieldConstructor; 3359 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3360 3361 if (ILE && Field) { 3362 InitList = true; 3363 InitListFieldDecl = Field; 3364 InitFieldIndex.clear(); 3365 CheckInitListExpr(ILE); 3366 } else { 3367 InitList = false; 3368 Visit(E); 3369 } 3370 3371 if (Field) 3372 Decls.erase(Field); 3373 if (BaseClass) 3374 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3375 } 3376 3377 void VisitMemberExpr(MemberExpr *ME) { 3378 // All uses of unbounded reference fields will warn. 3379 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3380 } 3381 3382 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3383 if (E->getCastKind() == CK_LValueToRValue) { 3384 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3385 return; 3386 } 3387 3388 Inherited::VisitImplicitCastExpr(E); 3389 } 3390 3391 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3392 if (E->getConstructor()->isCopyConstructor()) { 3393 Expr *ArgExpr = E->getArg(0); 3394 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3395 if (ILE->getNumInits() == 1) 3396 ArgExpr = ILE->getInit(0); 3397 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3398 if (ICE->getCastKind() == CK_NoOp) 3399 ArgExpr = ICE->getSubExpr(); 3400 HandleValue(ArgExpr, false /*AddressOf*/); 3401 return; 3402 } 3403 Inherited::VisitCXXConstructExpr(E); 3404 } 3405 3406 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3407 Expr *Callee = E->getCallee(); 3408 if (isa<MemberExpr>(Callee)) { 3409 HandleValue(Callee, false /*AddressOf*/); 3410 for (auto Arg : E->arguments()) 3411 Visit(Arg); 3412 return; 3413 } 3414 3415 Inherited::VisitCXXMemberCallExpr(E); 3416 } 3417 3418 void VisitCallExpr(CallExpr *E) { 3419 // Treat std::move as a use. 3420 if (E->isCallToStdMove()) { 3421 HandleValue(E->getArg(0), /*AddressOf=*/false); 3422 return; 3423 } 3424 3425 Inherited::VisitCallExpr(E); 3426 } 3427 3428 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3429 Expr *Callee = E->getCallee(); 3430 3431 if (isa<UnresolvedLookupExpr>(Callee)) 3432 return Inherited::VisitCXXOperatorCallExpr(E); 3433 3434 Visit(Callee); 3435 for (auto Arg : E->arguments()) 3436 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3437 } 3438 3439 void VisitBinaryOperator(BinaryOperator *E) { 3440 // If a field assignment is detected, remove the field from the 3441 // uninitiailized field set. 3442 if (E->getOpcode() == BO_Assign) 3443 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3444 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3445 if (!FD->getType()->isReferenceType()) 3446 DeclsToRemove.push_back(FD); 3447 3448 if (E->isCompoundAssignmentOp()) { 3449 HandleValue(E->getLHS(), false /*AddressOf*/); 3450 Visit(E->getRHS()); 3451 return; 3452 } 3453 3454 Inherited::VisitBinaryOperator(E); 3455 } 3456 3457 void VisitUnaryOperator(UnaryOperator *E) { 3458 if (E->isIncrementDecrementOp()) { 3459 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3460 return; 3461 } 3462 if (E->getOpcode() == UO_AddrOf) { 3463 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3464 HandleValue(ME->getBase(), true /*AddressOf*/); 3465 return; 3466 } 3467 } 3468 3469 Inherited::VisitUnaryOperator(E); 3470 } 3471 }; 3472 3473 // Diagnose value-uses of fields to initialize themselves, e.g. 3474 // foo(foo) 3475 // where foo is not also a parameter to the constructor. 3476 // Also diagnose across field uninitialized use such as 3477 // x(y), y(x) 3478 // TODO: implement -Wuninitialized and fold this into that framework. 3479 static void DiagnoseUninitializedFields( 3480 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3481 3482 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3483 Constructor->getLocation())) { 3484 return; 3485 } 3486 3487 if (Constructor->isInvalidDecl()) 3488 return; 3489 3490 const CXXRecordDecl *RD = Constructor->getParent(); 3491 3492 if (RD->getDescribedClassTemplate()) 3493 return; 3494 3495 // Holds fields that are uninitialized. 3496 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3497 3498 // At the beginning, all fields are uninitialized. 3499 for (auto *I : RD->decls()) { 3500 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3501 UninitializedFields.insert(FD); 3502 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3503 UninitializedFields.insert(IFD->getAnonField()); 3504 } 3505 } 3506 3507 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3508 for (auto I : RD->bases()) 3509 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3510 3511 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3512 return; 3513 3514 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3515 UninitializedFields, 3516 UninitializedBaseClasses); 3517 3518 for (const auto *FieldInit : Constructor->inits()) { 3519 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3520 break; 3521 3522 Expr *InitExpr = FieldInit->getInit(); 3523 if (!InitExpr) 3524 continue; 3525 3526 if (CXXDefaultInitExpr *Default = 3527 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3528 InitExpr = Default->getExpr(); 3529 if (!InitExpr) 3530 continue; 3531 // In class initializers will point to the constructor. 3532 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3533 FieldInit->getAnyMember(), 3534 FieldInit->getBaseClass()); 3535 } else { 3536 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3537 FieldInit->getAnyMember(), 3538 FieldInit->getBaseClass()); 3539 } 3540 } 3541 } 3542 } // namespace 3543 3544 /// \brief Enter a new C++ default initializer scope. After calling this, the 3545 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3546 /// parsing or instantiating the initializer failed. 3547 void Sema::ActOnStartCXXInClassMemberInitializer() { 3548 // Create a synthetic function scope to represent the call to the constructor 3549 // that notionally surrounds a use of this initializer. 3550 PushFunctionScope(); 3551 } 3552 3553 /// \brief This is invoked after parsing an in-class initializer for a 3554 /// non-static C++ class member, and after instantiating an in-class initializer 3555 /// in a class template. Such actions are deferred until the class is complete. 3556 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3557 SourceLocation InitLoc, 3558 Expr *InitExpr) { 3559 // Pop the notional constructor scope we created earlier. 3560 PopFunctionScopeInfo(nullptr, D); 3561 3562 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3563 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3564 "must set init style when field is created"); 3565 3566 if (!InitExpr) { 3567 D->setInvalidDecl(); 3568 if (FD) 3569 FD->removeInClassInitializer(); 3570 return; 3571 } 3572 3573 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3574 FD->setInvalidDecl(); 3575 FD->removeInClassInitializer(); 3576 return; 3577 } 3578 3579 ExprResult Init = InitExpr; 3580 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3581 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3582 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 3583 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 3584 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3585 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3586 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3587 if (Init.isInvalid()) { 3588 FD->setInvalidDecl(); 3589 return; 3590 } 3591 } 3592 3593 // C++11 [class.base.init]p7: 3594 // The initialization of each base and member constitutes a 3595 // full-expression. 3596 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3597 if (Init.isInvalid()) { 3598 FD->setInvalidDecl(); 3599 return; 3600 } 3601 3602 InitExpr = Init.get(); 3603 3604 FD->setInClassInitializer(InitExpr); 3605 } 3606 3607 /// \brief Find the direct and/or virtual base specifiers that 3608 /// correspond to the given base type, for use in base initialization 3609 /// within a constructor. 3610 static bool FindBaseInitializer(Sema &SemaRef, 3611 CXXRecordDecl *ClassDecl, 3612 QualType BaseType, 3613 const CXXBaseSpecifier *&DirectBaseSpec, 3614 const CXXBaseSpecifier *&VirtualBaseSpec) { 3615 // First, check for a direct base class. 3616 DirectBaseSpec = nullptr; 3617 for (const auto &Base : ClassDecl->bases()) { 3618 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3619 // We found a direct base of this type. That's what we're 3620 // initializing. 3621 DirectBaseSpec = &Base; 3622 break; 3623 } 3624 } 3625 3626 // Check for a virtual base class. 3627 // FIXME: We might be able to short-circuit this if we know in advance that 3628 // there are no virtual bases. 3629 VirtualBaseSpec = nullptr; 3630 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3631 // We haven't found a base yet; search the class hierarchy for a 3632 // virtual base class. 3633 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3634 /*DetectVirtual=*/false); 3635 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3636 SemaRef.Context.getTypeDeclType(ClassDecl), 3637 BaseType, Paths)) { 3638 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3639 Path != Paths.end(); ++Path) { 3640 if (Path->back().Base->isVirtual()) { 3641 VirtualBaseSpec = Path->back().Base; 3642 break; 3643 } 3644 } 3645 } 3646 } 3647 3648 return DirectBaseSpec || VirtualBaseSpec; 3649 } 3650 3651 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3652 MemInitResult 3653 Sema::ActOnMemInitializer(Decl *ConstructorD, 3654 Scope *S, 3655 CXXScopeSpec &SS, 3656 IdentifierInfo *MemberOrBase, 3657 ParsedType TemplateTypeTy, 3658 const DeclSpec &DS, 3659 SourceLocation IdLoc, 3660 Expr *InitList, 3661 SourceLocation EllipsisLoc) { 3662 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3663 DS, IdLoc, InitList, 3664 EllipsisLoc); 3665 } 3666 3667 /// \brief Handle a C++ member initializer using parentheses syntax. 3668 MemInitResult 3669 Sema::ActOnMemInitializer(Decl *ConstructorD, 3670 Scope *S, 3671 CXXScopeSpec &SS, 3672 IdentifierInfo *MemberOrBase, 3673 ParsedType TemplateTypeTy, 3674 const DeclSpec &DS, 3675 SourceLocation IdLoc, 3676 SourceLocation LParenLoc, 3677 ArrayRef<Expr *> Args, 3678 SourceLocation RParenLoc, 3679 SourceLocation EllipsisLoc) { 3680 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3681 Args, RParenLoc); 3682 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3683 DS, IdLoc, List, EllipsisLoc); 3684 } 3685 3686 namespace { 3687 3688 // Callback to only accept typo corrections that can be a valid C++ member 3689 // intializer: either a non-static field member or a base class. 3690 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3691 public: 3692 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3693 : ClassDecl(ClassDecl) {} 3694 3695 bool ValidateCandidate(const TypoCorrection &candidate) override { 3696 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3697 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3698 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3699 return isa<TypeDecl>(ND); 3700 } 3701 return false; 3702 } 3703 3704 private: 3705 CXXRecordDecl *ClassDecl; 3706 }; 3707 3708 } 3709 3710 /// \brief Handle a C++ member initializer. 3711 MemInitResult 3712 Sema::BuildMemInitializer(Decl *ConstructorD, 3713 Scope *S, 3714 CXXScopeSpec &SS, 3715 IdentifierInfo *MemberOrBase, 3716 ParsedType TemplateTypeTy, 3717 const DeclSpec &DS, 3718 SourceLocation IdLoc, 3719 Expr *Init, 3720 SourceLocation EllipsisLoc) { 3721 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3722 if (!Res.isUsable()) 3723 return true; 3724 Init = Res.get(); 3725 3726 if (!ConstructorD) 3727 return true; 3728 3729 AdjustDeclIfTemplate(ConstructorD); 3730 3731 CXXConstructorDecl *Constructor 3732 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3733 if (!Constructor) { 3734 // The user wrote a constructor initializer on a function that is 3735 // not a C++ constructor. Ignore the error for now, because we may 3736 // have more member initializers coming; we'll diagnose it just 3737 // once in ActOnMemInitializers. 3738 return true; 3739 } 3740 3741 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3742 3743 // C++ [class.base.init]p2: 3744 // Names in a mem-initializer-id are looked up in the scope of the 3745 // constructor's class and, if not found in that scope, are looked 3746 // up in the scope containing the constructor's definition. 3747 // [Note: if the constructor's class contains a member with the 3748 // same name as a direct or virtual base class of the class, a 3749 // mem-initializer-id naming the member or base class and composed 3750 // of a single identifier refers to the class member. A 3751 // mem-initializer-id for the hidden base class may be specified 3752 // using a qualified name. ] 3753 if (!SS.getScopeRep() && !TemplateTypeTy) { 3754 // Look for a member, first. 3755 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3756 if (!Result.empty()) { 3757 ValueDecl *Member; 3758 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3759 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3760 if (EllipsisLoc.isValid()) 3761 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3762 << MemberOrBase 3763 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3764 3765 return BuildMemberInitializer(Member, Init, IdLoc); 3766 } 3767 } 3768 } 3769 // It didn't name a member, so see if it names a class. 3770 QualType BaseType; 3771 TypeSourceInfo *TInfo = nullptr; 3772 3773 if (TemplateTypeTy) { 3774 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3775 } else if (DS.getTypeSpecType() == TST_decltype) { 3776 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3777 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3778 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3779 return true; 3780 } else { 3781 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3782 LookupParsedName(R, S, &SS); 3783 3784 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3785 if (!TyD) { 3786 if (R.isAmbiguous()) return true; 3787 3788 // We don't want access-control diagnostics here. 3789 R.suppressDiagnostics(); 3790 3791 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3792 bool NotUnknownSpecialization = false; 3793 DeclContext *DC = computeDeclContext(SS, false); 3794 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3795 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3796 3797 if (!NotUnknownSpecialization) { 3798 // When the scope specifier can refer to a member of an unknown 3799 // specialization, we take it as a type name. 3800 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3801 SS.getWithLocInContext(Context), 3802 *MemberOrBase, IdLoc); 3803 if (BaseType.isNull()) 3804 return true; 3805 3806 TInfo = Context.CreateTypeSourceInfo(BaseType); 3807 DependentNameTypeLoc TL = 3808 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3809 if (!TL.isNull()) { 3810 TL.setNameLoc(IdLoc); 3811 TL.setElaboratedKeywordLoc(SourceLocation()); 3812 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3813 } 3814 3815 R.clear(); 3816 R.setLookupName(MemberOrBase); 3817 } 3818 } 3819 3820 // If no results were found, try to correct typos. 3821 TypoCorrection Corr; 3822 if (R.empty() && BaseType.isNull() && 3823 (Corr = CorrectTypo( 3824 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3825 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3826 CTK_ErrorRecovery, ClassDecl))) { 3827 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3828 // We have found a non-static data member with a similar 3829 // name to what was typed; complain and initialize that 3830 // member. 3831 diagnoseTypo(Corr, 3832 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3833 << MemberOrBase << true); 3834 return BuildMemberInitializer(Member, Init, IdLoc); 3835 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3836 const CXXBaseSpecifier *DirectBaseSpec; 3837 const CXXBaseSpecifier *VirtualBaseSpec; 3838 if (FindBaseInitializer(*this, ClassDecl, 3839 Context.getTypeDeclType(Type), 3840 DirectBaseSpec, VirtualBaseSpec)) { 3841 // We have found a direct or virtual base class with a 3842 // similar name to what was typed; complain and initialize 3843 // that base class. 3844 diagnoseTypo(Corr, 3845 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3846 << MemberOrBase << false, 3847 PDiag() /*Suppress note, we provide our own.*/); 3848 3849 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3850 : VirtualBaseSpec; 3851 Diag(BaseSpec->getLocStart(), 3852 diag::note_base_class_specified_here) 3853 << BaseSpec->getType() 3854 << BaseSpec->getSourceRange(); 3855 3856 TyD = Type; 3857 } 3858 } 3859 } 3860 3861 if (!TyD && BaseType.isNull()) { 3862 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3863 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3864 return true; 3865 } 3866 } 3867 3868 if (BaseType.isNull()) { 3869 BaseType = Context.getTypeDeclType(TyD); 3870 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3871 if (SS.isSet()) { 3872 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3873 BaseType); 3874 TInfo = Context.CreateTypeSourceInfo(BaseType); 3875 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3876 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3877 TL.setElaboratedKeywordLoc(SourceLocation()); 3878 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3879 } 3880 } 3881 } 3882 3883 if (!TInfo) 3884 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3885 3886 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3887 } 3888 3889 /// Checks a member initializer expression for cases where reference (or 3890 /// pointer) members are bound to by-value parameters (or their addresses). 3891 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3892 Expr *Init, 3893 SourceLocation IdLoc) { 3894 QualType MemberTy = Member->getType(); 3895 3896 // We only handle pointers and references currently. 3897 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3898 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3899 return; 3900 3901 const bool IsPointer = MemberTy->isPointerType(); 3902 if (IsPointer) { 3903 if (const UnaryOperator *Op 3904 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3905 // The only case we're worried about with pointers requires taking the 3906 // address. 3907 if (Op->getOpcode() != UO_AddrOf) 3908 return; 3909 3910 Init = Op->getSubExpr(); 3911 } else { 3912 // We only handle address-of expression initializers for pointers. 3913 return; 3914 } 3915 } 3916 3917 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3918 // We only warn when referring to a non-reference parameter declaration. 3919 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3920 if (!Parameter || Parameter->getType()->isReferenceType()) 3921 return; 3922 3923 S.Diag(Init->getExprLoc(), 3924 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3925 : diag::warn_bind_ref_member_to_parameter) 3926 << Member << Parameter << Init->getSourceRange(); 3927 } else { 3928 // Other initializers are fine. 3929 return; 3930 } 3931 3932 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3933 << (unsigned)IsPointer; 3934 } 3935 3936 MemInitResult 3937 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3938 SourceLocation IdLoc) { 3939 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3940 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3941 assert((DirectMember || IndirectMember) && 3942 "Member must be a FieldDecl or IndirectFieldDecl"); 3943 3944 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3945 return true; 3946 3947 if (Member->isInvalidDecl()) 3948 return true; 3949 3950 MultiExprArg Args; 3951 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3952 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3953 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3954 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3955 } else { 3956 // Template instantiation doesn't reconstruct ParenListExprs for us. 3957 Args = Init; 3958 } 3959 3960 SourceRange InitRange = Init->getSourceRange(); 3961 3962 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3963 // Can't check initialization for a member of dependent type or when 3964 // any of the arguments are type-dependent expressions. 3965 DiscardCleanupsInEvaluationContext(); 3966 } else { 3967 bool InitList = false; 3968 if (isa<InitListExpr>(Init)) { 3969 InitList = true; 3970 Args = Init; 3971 } 3972 3973 // Initialize the member. 3974 InitializedEntity MemberEntity = 3975 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3976 : InitializedEntity::InitializeMember(IndirectMember, 3977 nullptr); 3978 InitializationKind Kind = 3979 InitList ? InitializationKind::CreateDirectList(IdLoc) 3980 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3981 InitRange.getEnd()); 3982 3983 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3984 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3985 nullptr); 3986 if (MemberInit.isInvalid()) 3987 return true; 3988 3989 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3990 3991 // C++11 [class.base.init]p7: 3992 // The initialization of each base and member constitutes a 3993 // full-expression. 3994 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3995 if (MemberInit.isInvalid()) 3996 return true; 3997 3998 Init = MemberInit.get(); 3999 } 4000 4001 if (DirectMember) { 4002 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4003 InitRange.getBegin(), Init, 4004 InitRange.getEnd()); 4005 } else { 4006 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4007 InitRange.getBegin(), Init, 4008 InitRange.getEnd()); 4009 } 4010 } 4011 4012 MemInitResult 4013 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4014 CXXRecordDecl *ClassDecl) { 4015 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4016 if (!LangOpts.CPlusPlus11) 4017 return Diag(NameLoc, diag::err_delegating_ctor) 4018 << TInfo->getTypeLoc().getLocalSourceRange(); 4019 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4020 4021 bool InitList = true; 4022 MultiExprArg Args = Init; 4023 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4024 InitList = false; 4025 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4026 } 4027 4028 SourceRange InitRange = Init->getSourceRange(); 4029 // Initialize the object. 4030 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4031 QualType(ClassDecl->getTypeForDecl(), 0)); 4032 InitializationKind Kind = 4033 InitList ? InitializationKind::CreateDirectList(NameLoc) 4034 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4035 InitRange.getEnd()); 4036 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4037 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4038 Args, nullptr); 4039 if (DelegationInit.isInvalid()) 4040 return true; 4041 4042 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4043 "Delegating constructor with no target?"); 4044 4045 // C++11 [class.base.init]p7: 4046 // The initialization of each base and member constitutes a 4047 // full-expression. 4048 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4049 InitRange.getBegin()); 4050 if (DelegationInit.isInvalid()) 4051 return true; 4052 4053 // If we are in a dependent context, template instantiation will 4054 // perform this type-checking again. Just save the arguments that we 4055 // received in a ParenListExpr. 4056 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4057 // of the information that we have about the base 4058 // initializer. However, deconstructing the ASTs is a dicey process, 4059 // and this approach is far more likely to get the corner cases right. 4060 if (CurContext->isDependentContext()) 4061 DelegationInit = Init; 4062 4063 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4064 DelegationInit.getAs<Expr>(), 4065 InitRange.getEnd()); 4066 } 4067 4068 MemInitResult 4069 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4070 Expr *Init, CXXRecordDecl *ClassDecl, 4071 SourceLocation EllipsisLoc) { 4072 SourceLocation BaseLoc 4073 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4074 4075 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4076 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4077 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4078 4079 // C++ [class.base.init]p2: 4080 // [...] Unless the mem-initializer-id names a nonstatic data 4081 // member of the constructor's class or a direct or virtual base 4082 // of that class, the mem-initializer is ill-formed. A 4083 // mem-initializer-list can initialize a base class using any 4084 // name that denotes that base class type. 4085 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4086 4087 SourceRange InitRange = Init->getSourceRange(); 4088 if (EllipsisLoc.isValid()) { 4089 // This is a pack expansion. 4090 if (!BaseType->containsUnexpandedParameterPack()) { 4091 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4092 << SourceRange(BaseLoc, InitRange.getEnd()); 4093 4094 EllipsisLoc = SourceLocation(); 4095 } 4096 } else { 4097 // Check for any unexpanded parameter packs. 4098 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4099 return true; 4100 4101 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4102 return true; 4103 } 4104 4105 // Check for direct and virtual base classes. 4106 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4107 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4108 if (!Dependent) { 4109 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4110 BaseType)) 4111 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4112 4113 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4114 VirtualBaseSpec); 4115 4116 // C++ [base.class.init]p2: 4117 // Unless the mem-initializer-id names a nonstatic data member of the 4118 // constructor's class or a direct or virtual base of that class, the 4119 // mem-initializer is ill-formed. 4120 if (!DirectBaseSpec && !VirtualBaseSpec) { 4121 // If the class has any dependent bases, then it's possible that 4122 // one of those types will resolve to the same type as 4123 // BaseType. Therefore, just treat this as a dependent base 4124 // class initialization. FIXME: Should we try to check the 4125 // initialization anyway? It seems odd. 4126 if (ClassDecl->hasAnyDependentBases()) 4127 Dependent = true; 4128 else 4129 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4130 << BaseType << Context.getTypeDeclType(ClassDecl) 4131 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4132 } 4133 } 4134 4135 if (Dependent) { 4136 DiscardCleanupsInEvaluationContext(); 4137 4138 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4139 /*IsVirtual=*/false, 4140 InitRange.getBegin(), Init, 4141 InitRange.getEnd(), EllipsisLoc); 4142 } 4143 4144 // C++ [base.class.init]p2: 4145 // If a mem-initializer-id is ambiguous because it designates both 4146 // a direct non-virtual base class and an inherited virtual base 4147 // class, the mem-initializer is ill-formed. 4148 if (DirectBaseSpec && VirtualBaseSpec) 4149 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4150 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4151 4152 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4153 if (!BaseSpec) 4154 BaseSpec = VirtualBaseSpec; 4155 4156 // Initialize the base. 4157 bool InitList = true; 4158 MultiExprArg Args = Init; 4159 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4160 InitList = false; 4161 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4162 } 4163 4164 InitializedEntity BaseEntity = 4165 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4166 InitializationKind Kind = 4167 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4168 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4169 InitRange.getEnd()); 4170 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4171 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4172 if (BaseInit.isInvalid()) 4173 return true; 4174 4175 // C++11 [class.base.init]p7: 4176 // The initialization of each base and member constitutes a 4177 // full-expression. 4178 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4179 if (BaseInit.isInvalid()) 4180 return true; 4181 4182 // If we are in a dependent context, template instantiation will 4183 // perform this type-checking again. Just save the arguments that we 4184 // received in a ParenListExpr. 4185 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4186 // of the information that we have about the base 4187 // initializer. However, deconstructing the ASTs is a dicey process, 4188 // and this approach is far more likely to get the corner cases right. 4189 if (CurContext->isDependentContext()) 4190 BaseInit = Init; 4191 4192 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4193 BaseSpec->isVirtual(), 4194 InitRange.getBegin(), 4195 BaseInit.getAs<Expr>(), 4196 InitRange.getEnd(), EllipsisLoc); 4197 } 4198 4199 // Create a static_cast\<T&&>(expr). 4200 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4201 if (T.isNull()) T = E->getType(); 4202 QualType TargetType = SemaRef.BuildReferenceType( 4203 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4204 SourceLocation ExprLoc = E->getLocStart(); 4205 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4206 TargetType, ExprLoc); 4207 4208 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4209 SourceRange(ExprLoc, ExprLoc), 4210 E->getSourceRange()).get(); 4211 } 4212 4213 /// ImplicitInitializerKind - How an implicit base or member initializer should 4214 /// initialize its base or member. 4215 enum ImplicitInitializerKind { 4216 IIK_Default, 4217 IIK_Copy, 4218 IIK_Move, 4219 IIK_Inherit 4220 }; 4221 4222 static bool 4223 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4224 ImplicitInitializerKind ImplicitInitKind, 4225 CXXBaseSpecifier *BaseSpec, 4226 bool IsInheritedVirtualBase, 4227 CXXCtorInitializer *&CXXBaseInit) { 4228 InitializedEntity InitEntity 4229 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4230 IsInheritedVirtualBase); 4231 4232 ExprResult BaseInit; 4233 4234 switch (ImplicitInitKind) { 4235 case IIK_Inherit: 4236 case IIK_Default: { 4237 InitializationKind InitKind 4238 = InitializationKind::CreateDefault(Constructor->getLocation()); 4239 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4240 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4241 break; 4242 } 4243 4244 case IIK_Move: 4245 case IIK_Copy: { 4246 bool Moving = ImplicitInitKind == IIK_Move; 4247 ParmVarDecl *Param = Constructor->getParamDecl(0); 4248 QualType ParamType = Param->getType().getNonReferenceType(); 4249 4250 Expr *CopyCtorArg = 4251 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4252 SourceLocation(), Param, false, 4253 Constructor->getLocation(), ParamType, 4254 VK_LValue, nullptr); 4255 4256 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4257 4258 // Cast to the base class to avoid ambiguities. 4259 QualType ArgTy = 4260 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4261 ParamType.getQualifiers()); 4262 4263 if (Moving) { 4264 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4265 } 4266 4267 CXXCastPath BasePath; 4268 BasePath.push_back(BaseSpec); 4269 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4270 CK_UncheckedDerivedToBase, 4271 Moving ? VK_XValue : VK_LValue, 4272 &BasePath).get(); 4273 4274 InitializationKind InitKind 4275 = InitializationKind::CreateDirect(Constructor->getLocation(), 4276 SourceLocation(), SourceLocation()); 4277 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4278 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4279 break; 4280 } 4281 } 4282 4283 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4284 if (BaseInit.isInvalid()) 4285 return true; 4286 4287 CXXBaseInit = 4288 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4289 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4290 SourceLocation()), 4291 BaseSpec->isVirtual(), 4292 SourceLocation(), 4293 BaseInit.getAs<Expr>(), 4294 SourceLocation(), 4295 SourceLocation()); 4296 4297 return false; 4298 } 4299 4300 static bool RefersToRValueRef(Expr *MemRef) { 4301 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4302 return Referenced->getType()->isRValueReferenceType(); 4303 } 4304 4305 static bool 4306 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4307 ImplicitInitializerKind ImplicitInitKind, 4308 FieldDecl *Field, IndirectFieldDecl *Indirect, 4309 CXXCtorInitializer *&CXXMemberInit) { 4310 if (Field->isInvalidDecl()) 4311 return true; 4312 4313 SourceLocation Loc = Constructor->getLocation(); 4314 4315 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4316 bool Moving = ImplicitInitKind == IIK_Move; 4317 ParmVarDecl *Param = Constructor->getParamDecl(0); 4318 QualType ParamType = Param->getType().getNonReferenceType(); 4319 4320 // Suppress copying zero-width bitfields. 4321 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 4322 return false; 4323 4324 Expr *MemberExprBase = 4325 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4326 SourceLocation(), Param, false, 4327 Loc, ParamType, VK_LValue, nullptr); 4328 4329 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4330 4331 if (Moving) { 4332 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4333 } 4334 4335 // Build a reference to this field within the parameter. 4336 CXXScopeSpec SS; 4337 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4338 Sema::LookupMemberName); 4339 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4340 : cast<ValueDecl>(Field), AS_public); 4341 MemberLookup.resolveKind(); 4342 ExprResult CtorArg 4343 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4344 ParamType, Loc, 4345 /*IsArrow=*/false, 4346 SS, 4347 /*TemplateKWLoc=*/SourceLocation(), 4348 /*FirstQualifierInScope=*/nullptr, 4349 MemberLookup, 4350 /*TemplateArgs=*/nullptr, 4351 /*S*/nullptr); 4352 if (CtorArg.isInvalid()) 4353 return true; 4354 4355 // C++11 [class.copy]p15: 4356 // - if a member m has rvalue reference type T&&, it is direct-initialized 4357 // with static_cast<T&&>(x.m); 4358 if (RefersToRValueRef(CtorArg.get())) { 4359 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4360 } 4361 4362 InitializedEntity Entity = 4363 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4364 /*Implicit*/ true) 4365 : InitializedEntity::InitializeMember(Field, nullptr, 4366 /*Implicit*/ true); 4367 4368 // Direct-initialize to use the copy constructor. 4369 InitializationKind InitKind = 4370 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4371 4372 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4373 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4374 ExprResult MemberInit = 4375 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4376 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4377 if (MemberInit.isInvalid()) 4378 return true; 4379 4380 if (Indirect) 4381 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4382 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4383 else 4384 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4385 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4386 return false; 4387 } 4388 4389 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4390 "Unhandled implicit init kind!"); 4391 4392 QualType FieldBaseElementType = 4393 SemaRef.Context.getBaseElementType(Field->getType()); 4394 4395 if (FieldBaseElementType->isRecordType()) { 4396 InitializedEntity InitEntity = 4397 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4398 /*Implicit*/ true) 4399 : InitializedEntity::InitializeMember(Field, nullptr, 4400 /*Implicit*/ true); 4401 InitializationKind InitKind = 4402 InitializationKind::CreateDefault(Loc); 4403 4404 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4405 ExprResult MemberInit = 4406 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4407 4408 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4409 if (MemberInit.isInvalid()) 4410 return true; 4411 4412 if (Indirect) 4413 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4414 Indirect, Loc, 4415 Loc, 4416 MemberInit.get(), 4417 Loc); 4418 else 4419 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4420 Field, Loc, Loc, 4421 MemberInit.get(), 4422 Loc); 4423 return false; 4424 } 4425 4426 if (!Field->getParent()->isUnion()) { 4427 if (FieldBaseElementType->isReferenceType()) { 4428 SemaRef.Diag(Constructor->getLocation(), 4429 diag::err_uninitialized_member_in_ctor) 4430 << (int)Constructor->isImplicit() 4431 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4432 << 0 << Field->getDeclName(); 4433 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4434 return true; 4435 } 4436 4437 if (FieldBaseElementType.isConstQualified()) { 4438 SemaRef.Diag(Constructor->getLocation(), 4439 diag::err_uninitialized_member_in_ctor) 4440 << (int)Constructor->isImplicit() 4441 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4442 << 1 << Field->getDeclName(); 4443 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4444 return true; 4445 } 4446 } 4447 4448 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4449 // ARC and Weak: 4450 // Default-initialize Objective-C pointers to NULL. 4451 CXXMemberInit 4452 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4453 Loc, Loc, 4454 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4455 Loc); 4456 return false; 4457 } 4458 4459 // Nothing to initialize. 4460 CXXMemberInit = nullptr; 4461 return false; 4462 } 4463 4464 namespace { 4465 struct BaseAndFieldInfo { 4466 Sema &S; 4467 CXXConstructorDecl *Ctor; 4468 bool AnyErrorsInInits; 4469 ImplicitInitializerKind IIK; 4470 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4471 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4472 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4473 4474 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4475 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4476 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4477 if (Ctor->getInheritedConstructor()) 4478 IIK = IIK_Inherit; 4479 else if (Generated && Ctor->isCopyConstructor()) 4480 IIK = IIK_Copy; 4481 else if (Generated && Ctor->isMoveConstructor()) 4482 IIK = IIK_Move; 4483 else 4484 IIK = IIK_Default; 4485 } 4486 4487 bool isImplicitCopyOrMove() const { 4488 switch (IIK) { 4489 case IIK_Copy: 4490 case IIK_Move: 4491 return true; 4492 4493 case IIK_Default: 4494 case IIK_Inherit: 4495 return false; 4496 } 4497 4498 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4499 } 4500 4501 bool addFieldInitializer(CXXCtorInitializer *Init) { 4502 AllToInit.push_back(Init); 4503 4504 // Check whether this initializer makes the field "used". 4505 if (Init->getInit()->HasSideEffects(S.Context)) 4506 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4507 4508 return false; 4509 } 4510 4511 bool isInactiveUnionMember(FieldDecl *Field) { 4512 RecordDecl *Record = Field->getParent(); 4513 if (!Record->isUnion()) 4514 return false; 4515 4516 if (FieldDecl *Active = 4517 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4518 return Active != Field->getCanonicalDecl(); 4519 4520 // In an implicit copy or move constructor, ignore any in-class initializer. 4521 if (isImplicitCopyOrMove()) 4522 return true; 4523 4524 // If there's no explicit initialization, the field is active only if it 4525 // has an in-class initializer... 4526 if (Field->hasInClassInitializer()) 4527 return false; 4528 // ... or it's an anonymous struct or union whose class has an in-class 4529 // initializer. 4530 if (!Field->isAnonymousStructOrUnion()) 4531 return true; 4532 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4533 return !FieldRD->hasInClassInitializer(); 4534 } 4535 4536 /// \brief Determine whether the given field is, or is within, a union member 4537 /// that is inactive (because there was an initializer given for a different 4538 /// member of the union, or because the union was not initialized at all). 4539 bool isWithinInactiveUnionMember(FieldDecl *Field, 4540 IndirectFieldDecl *Indirect) { 4541 if (!Indirect) 4542 return isInactiveUnionMember(Field); 4543 4544 for (auto *C : Indirect->chain()) { 4545 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4546 if (Field && isInactiveUnionMember(Field)) 4547 return true; 4548 } 4549 return false; 4550 } 4551 }; 4552 } 4553 4554 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4555 /// array type. 4556 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4557 if (T->isIncompleteArrayType()) 4558 return true; 4559 4560 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4561 if (!ArrayT->getSize()) 4562 return true; 4563 4564 T = ArrayT->getElementType(); 4565 } 4566 4567 return false; 4568 } 4569 4570 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4571 FieldDecl *Field, 4572 IndirectFieldDecl *Indirect = nullptr) { 4573 if (Field->isInvalidDecl()) 4574 return false; 4575 4576 // Overwhelmingly common case: we have a direct initializer for this field. 4577 if (CXXCtorInitializer *Init = 4578 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4579 return Info.addFieldInitializer(Init); 4580 4581 // C++11 [class.base.init]p8: 4582 // if the entity is a non-static data member that has a 4583 // brace-or-equal-initializer and either 4584 // -- the constructor's class is a union and no other variant member of that 4585 // union is designated by a mem-initializer-id or 4586 // -- the constructor's class is not a union, and, if the entity is a member 4587 // of an anonymous union, no other member of that union is designated by 4588 // a mem-initializer-id, 4589 // the entity is initialized as specified in [dcl.init]. 4590 // 4591 // We also apply the same rules to handle anonymous structs within anonymous 4592 // unions. 4593 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4594 return false; 4595 4596 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4597 ExprResult DIE = 4598 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4599 if (DIE.isInvalid()) 4600 return true; 4601 CXXCtorInitializer *Init; 4602 if (Indirect) 4603 Init = new (SemaRef.Context) 4604 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4605 SourceLocation(), DIE.get(), SourceLocation()); 4606 else 4607 Init = new (SemaRef.Context) 4608 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4609 SourceLocation(), DIE.get(), SourceLocation()); 4610 return Info.addFieldInitializer(Init); 4611 } 4612 4613 // Don't initialize incomplete or zero-length arrays. 4614 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4615 return false; 4616 4617 // Don't try to build an implicit initializer if there were semantic 4618 // errors in any of the initializers (and therefore we might be 4619 // missing some that the user actually wrote). 4620 if (Info.AnyErrorsInInits) 4621 return false; 4622 4623 CXXCtorInitializer *Init = nullptr; 4624 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4625 Indirect, Init)) 4626 return true; 4627 4628 if (!Init) 4629 return false; 4630 4631 return Info.addFieldInitializer(Init); 4632 } 4633 4634 bool 4635 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4636 CXXCtorInitializer *Initializer) { 4637 assert(Initializer->isDelegatingInitializer()); 4638 Constructor->setNumCtorInitializers(1); 4639 CXXCtorInitializer **initializer = 4640 new (Context) CXXCtorInitializer*[1]; 4641 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4642 Constructor->setCtorInitializers(initializer); 4643 4644 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4645 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4646 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4647 } 4648 4649 DelegatingCtorDecls.push_back(Constructor); 4650 4651 DiagnoseUninitializedFields(*this, Constructor); 4652 4653 return false; 4654 } 4655 4656 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4657 ArrayRef<CXXCtorInitializer *> Initializers) { 4658 if (Constructor->isDependentContext()) { 4659 // Just store the initializers as written, they will be checked during 4660 // instantiation. 4661 if (!Initializers.empty()) { 4662 Constructor->setNumCtorInitializers(Initializers.size()); 4663 CXXCtorInitializer **baseOrMemberInitializers = 4664 new (Context) CXXCtorInitializer*[Initializers.size()]; 4665 memcpy(baseOrMemberInitializers, Initializers.data(), 4666 Initializers.size() * sizeof(CXXCtorInitializer*)); 4667 Constructor->setCtorInitializers(baseOrMemberInitializers); 4668 } 4669 4670 // Let template instantiation know whether we had errors. 4671 if (AnyErrors) 4672 Constructor->setInvalidDecl(); 4673 4674 return false; 4675 } 4676 4677 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4678 4679 // We need to build the initializer AST according to order of construction 4680 // and not what user specified in the Initializers list. 4681 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4682 if (!ClassDecl) 4683 return true; 4684 4685 bool HadError = false; 4686 4687 for (unsigned i = 0; i < Initializers.size(); i++) { 4688 CXXCtorInitializer *Member = Initializers[i]; 4689 4690 if (Member->isBaseInitializer()) 4691 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4692 else { 4693 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4694 4695 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4696 for (auto *C : F->chain()) { 4697 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4698 if (FD && FD->getParent()->isUnion()) 4699 Info.ActiveUnionMember.insert(std::make_pair( 4700 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4701 } 4702 } else if (FieldDecl *FD = Member->getMember()) { 4703 if (FD->getParent()->isUnion()) 4704 Info.ActiveUnionMember.insert(std::make_pair( 4705 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4706 } 4707 } 4708 } 4709 4710 // Keep track of the direct virtual bases. 4711 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4712 for (auto &I : ClassDecl->bases()) { 4713 if (I.isVirtual()) 4714 DirectVBases.insert(&I); 4715 } 4716 4717 // Push virtual bases before others. 4718 for (auto &VBase : ClassDecl->vbases()) { 4719 if (CXXCtorInitializer *Value 4720 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4721 // [class.base.init]p7, per DR257: 4722 // A mem-initializer where the mem-initializer-id names a virtual base 4723 // class is ignored during execution of a constructor of any class that 4724 // is not the most derived class. 4725 if (ClassDecl->isAbstract()) { 4726 // FIXME: Provide a fixit to remove the base specifier. This requires 4727 // tracking the location of the associated comma for a base specifier. 4728 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4729 << VBase.getType() << ClassDecl; 4730 DiagnoseAbstractType(ClassDecl); 4731 } 4732 4733 Info.AllToInit.push_back(Value); 4734 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4735 // [class.base.init]p8, per DR257: 4736 // If a given [...] base class is not named by a mem-initializer-id 4737 // [...] and the entity is not a virtual base class of an abstract 4738 // class, then [...] the entity is default-initialized. 4739 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4740 CXXCtorInitializer *CXXBaseInit; 4741 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4742 &VBase, IsInheritedVirtualBase, 4743 CXXBaseInit)) { 4744 HadError = true; 4745 continue; 4746 } 4747 4748 Info.AllToInit.push_back(CXXBaseInit); 4749 } 4750 } 4751 4752 // Non-virtual bases. 4753 for (auto &Base : ClassDecl->bases()) { 4754 // Virtuals are in the virtual base list and already constructed. 4755 if (Base.isVirtual()) 4756 continue; 4757 4758 if (CXXCtorInitializer *Value 4759 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4760 Info.AllToInit.push_back(Value); 4761 } else if (!AnyErrors) { 4762 CXXCtorInitializer *CXXBaseInit; 4763 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4764 &Base, /*IsInheritedVirtualBase=*/false, 4765 CXXBaseInit)) { 4766 HadError = true; 4767 continue; 4768 } 4769 4770 Info.AllToInit.push_back(CXXBaseInit); 4771 } 4772 } 4773 4774 // Fields. 4775 for (auto *Mem : ClassDecl->decls()) { 4776 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4777 // C++ [class.bit]p2: 4778 // A declaration for a bit-field that omits the identifier declares an 4779 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4780 // initialized. 4781 if (F->isUnnamedBitfield()) 4782 continue; 4783 4784 // If we're not generating the implicit copy/move constructor, then we'll 4785 // handle anonymous struct/union fields based on their individual 4786 // indirect fields. 4787 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4788 continue; 4789 4790 if (CollectFieldInitializer(*this, Info, F)) 4791 HadError = true; 4792 continue; 4793 } 4794 4795 // Beyond this point, we only consider default initialization. 4796 if (Info.isImplicitCopyOrMove()) 4797 continue; 4798 4799 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4800 if (F->getType()->isIncompleteArrayType()) { 4801 assert(ClassDecl->hasFlexibleArrayMember() && 4802 "Incomplete array type is not valid"); 4803 continue; 4804 } 4805 4806 // Initialize each field of an anonymous struct individually. 4807 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4808 HadError = true; 4809 4810 continue; 4811 } 4812 } 4813 4814 unsigned NumInitializers = Info.AllToInit.size(); 4815 if (NumInitializers > 0) { 4816 Constructor->setNumCtorInitializers(NumInitializers); 4817 CXXCtorInitializer **baseOrMemberInitializers = 4818 new (Context) CXXCtorInitializer*[NumInitializers]; 4819 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4820 NumInitializers * sizeof(CXXCtorInitializer*)); 4821 Constructor->setCtorInitializers(baseOrMemberInitializers); 4822 4823 // Constructors implicitly reference the base and member 4824 // destructors. 4825 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4826 Constructor->getParent()); 4827 } 4828 4829 return HadError; 4830 } 4831 4832 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4833 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4834 const RecordDecl *RD = RT->getDecl(); 4835 if (RD->isAnonymousStructOrUnion()) { 4836 for (auto *Field : RD->fields()) 4837 PopulateKeysForFields(Field, IdealInits); 4838 return; 4839 } 4840 } 4841 IdealInits.push_back(Field->getCanonicalDecl()); 4842 } 4843 4844 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4845 return Context.getCanonicalType(BaseType).getTypePtr(); 4846 } 4847 4848 static const void *GetKeyForMember(ASTContext &Context, 4849 CXXCtorInitializer *Member) { 4850 if (!Member->isAnyMemberInitializer()) 4851 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4852 4853 return Member->getAnyMember()->getCanonicalDecl(); 4854 } 4855 4856 static void DiagnoseBaseOrMemInitializerOrder( 4857 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4858 ArrayRef<CXXCtorInitializer *> Inits) { 4859 if (Constructor->getDeclContext()->isDependentContext()) 4860 return; 4861 4862 // Don't check initializers order unless the warning is enabled at the 4863 // location of at least one initializer. 4864 bool ShouldCheckOrder = false; 4865 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4866 CXXCtorInitializer *Init = Inits[InitIndex]; 4867 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4868 Init->getSourceLocation())) { 4869 ShouldCheckOrder = true; 4870 break; 4871 } 4872 } 4873 if (!ShouldCheckOrder) 4874 return; 4875 4876 // Build the list of bases and members in the order that they'll 4877 // actually be initialized. The explicit initializers should be in 4878 // this same order but may be missing things. 4879 SmallVector<const void*, 32> IdealInitKeys; 4880 4881 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4882 4883 // 1. Virtual bases. 4884 for (const auto &VBase : ClassDecl->vbases()) 4885 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4886 4887 // 2. Non-virtual bases. 4888 for (const auto &Base : ClassDecl->bases()) { 4889 if (Base.isVirtual()) 4890 continue; 4891 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4892 } 4893 4894 // 3. Direct fields. 4895 for (auto *Field : ClassDecl->fields()) { 4896 if (Field->isUnnamedBitfield()) 4897 continue; 4898 4899 PopulateKeysForFields(Field, IdealInitKeys); 4900 } 4901 4902 unsigned NumIdealInits = IdealInitKeys.size(); 4903 unsigned IdealIndex = 0; 4904 4905 CXXCtorInitializer *PrevInit = nullptr; 4906 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4907 CXXCtorInitializer *Init = Inits[InitIndex]; 4908 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4909 4910 // Scan forward to try to find this initializer in the idealized 4911 // initializers list. 4912 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4913 if (InitKey == IdealInitKeys[IdealIndex]) 4914 break; 4915 4916 // If we didn't find this initializer, it must be because we 4917 // scanned past it on a previous iteration. That can only 4918 // happen if we're out of order; emit a warning. 4919 if (IdealIndex == NumIdealInits && PrevInit) { 4920 Sema::SemaDiagnosticBuilder D = 4921 SemaRef.Diag(PrevInit->getSourceLocation(), 4922 diag::warn_initializer_out_of_order); 4923 4924 if (PrevInit->isAnyMemberInitializer()) 4925 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4926 else 4927 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4928 4929 if (Init->isAnyMemberInitializer()) 4930 D << 0 << Init->getAnyMember()->getDeclName(); 4931 else 4932 D << 1 << Init->getTypeSourceInfo()->getType(); 4933 4934 // Move back to the initializer's location in the ideal list. 4935 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4936 if (InitKey == IdealInitKeys[IdealIndex]) 4937 break; 4938 4939 assert(IdealIndex < NumIdealInits && 4940 "initializer not found in initializer list"); 4941 } 4942 4943 PrevInit = Init; 4944 } 4945 } 4946 4947 namespace { 4948 bool CheckRedundantInit(Sema &S, 4949 CXXCtorInitializer *Init, 4950 CXXCtorInitializer *&PrevInit) { 4951 if (!PrevInit) { 4952 PrevInit = Init; 4953 return false; 4954 } 4955 4956 if (FieldDecl *Field = Init->getAnyMember()) 4957 S.Diag(Init->getSourceLocation(), 4958 diag::err_multiple_mem_initialization) 4959 << Field->getDeclName() 4960 << Init->getSourceRange(); 4961 else { 4962 const Type *BaseClass = Init->getBaseClass(); 4963 assert(BaseClass && "neither field nor base"); 4964 S.Diag(Init->getSourceLocation(), 4965 diag::err_multiple_base_initialization) 4966 << QualType(BaseClass, 0) 4967 << Init->getSourceRange(); 4968 } 4969 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4970 << 0 << PrevInit->getSourceRange(); 4971 4972 return true; 4973 } 4974 4975 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4976 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4977 4978 bool CheckRedundantUnionInit(Sema &S, 4979 CXXCtorInitializer *Init, 4980 RedundantUnionMap &Unions) { 4981 FieldDecl *Field = Init->getAnyMember(); 4982 RecordDecl *Parent = Field->getParent(); 4983 NamedDecl *Child = Field; 4984 4985 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4986 if (Parent->isUnion()) { 4987 UnionEntry &En = Unions[Parent]; 4988 if (En.first && En.first != Child) { 4989 S.Diag(Init->getSourceLocation(), 4990 diag::err_multiple_mem_union_initialization) 4991 << Field->getDeclName() 4992 << Init->getSourceRange(); 4993 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4994 << 0 << En.second->getSourceRange(); 4995 return true; 4996 } 4997 if (!En.first) { 4998 En.first = Child; 4999 En.second = Init; 5000 } 5001 if (!Parent->isAnonymousStructOrUnion()) 5002 return false; 5003 } 5004 5005 Child = Parent; 5006 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5007 } 5008 5009 return false; 5010 } 5011 } 5012 5013 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5014 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5015 SourceLocation ColonLoc, 5016 ArrayRef<CXXCtorInitializer*> MemInits, 5017 bool AnyErrors) { 5018 if (!ConstructorDecl) 5019 return; 5020 5021 AdjustDeclIfTemplate(ConstructorDecl); 5022 5023 CXXConstructorDecl *Constructor 5024 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5025 5026 if (!Constructor) { 5027 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5028 return; 5029 } 5030 5031 // Mapping for the duplicate initializers check. 5032 // For member initializers, this is keyed with a FieldDecl*. 5033 // For base initializers, this is keyed with a Type*. 5034 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5035 5036 // Mapping for the inconsistent anonymous-union initializers check. 5037 RedundantUnionMap MemberUnions; 5038 5039 bool HadError = false; 5040 for (unsigned i = 0; i < MemInits.size(); i++) { 5041 CXXCtorInitializer *Init = MemInits[i]; 5042 5043 // Set the source order index. 5044 Init->setSourceOrder(i); 5045 5046 if (Init->isAnyMemberInitializer()) { 5047 const void *Key = GetKeyForMember(Context, Init); 5048 if (CheckRedundantInit(*this, Init, Members[Key]) || 5049 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5050 HadError = true; 5051 } else if (Init->isBaseInitializer()) { 5052 const void *Key = GetKeyForMember(Context, Init); 5053 if (CheckRedundantInit(*this, Init, Members[Key])) 5054 HadError = true; 5055 } else { 5056 assert(Init->isDelegatingInitializer()); 5057 // This must be the only initializer 5058 if (MemInits.size() != 1) { 5059 Diag(Init->getSourceLocation(), 5060 diag::err_delegating_initializer_alone) 5061 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5062 // We will treat this as being the only initializer. 5063 } 5064 SetDelegatingInitializer(Constructor, MemInits[i]); 5065 // Return immediately as the initializer is set. 5066 return; 5067 } 5068 } 5069 5070 if (HadError) 5071 return; 5072 5073 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5074 5075 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5076 5077 DiagnoseUninitializedFields(*this, Constructor); 5078 } 5079 5080 void 5081 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5082 CXXRecordDecl *ClassDecl) { 5083 // Ignore dependent contexts. Also ignore unions, since their members never 5084 // have destructors implicitly called. 5085 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5086 return; 5087 5088 // FIXME: all the access-control diagnostics are positioned on the 5089 // field/base declaration. That's probably good; that said, the 5090 // user might reasonably want to know why the destructor is being 5091 // emitted, and we currently don't say. 5092 5093 // Non-static data members. 5094 for (auto *Field : ClassDecl->fields()) { 5095 if (Field->isInvalidDecl()) 5096 continue; 5097 5098 // Don't destroy incomplete or zero-length arrays. 5099 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5100 continue; 5101 5102 QualType FieldType = Context.getBaseElementType(Field->getType()); 5103 5104 const RecordType* RT = FieldType->getAs<RecordType>(); 5105 if (!RT) 5106 continue; 5107 5108 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5109 if (FieldClassDecl->isInvalidDecl()) 5110 continue; 5111 if (FieldClassDecl->hasIrrelevantDestructor()) 5112 continue; 5113 // The destructor for an implicit anonymous union member is never invoked. 5114 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5115 continue; 5116 5117 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5118 assert(Dtor && "No dtor found for FieldClassDecl!"); 5119 CheckDestructorAccess(Field->getLocation(), Dtor, 5120 PDiag(diag::err_access_dtor_field) 5121 << Field->getDeclName() 5122 << FieldType); 5123 5124 MarkFunctionReferenced(Location, Dtor); 5125 DiagnoseUseOfDecl(Dtor, Location); 5126 } 5127 5128 // We only potentially invoke the destructors of potentially constructed 5129 // subobjects. 5130 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5131 5132 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5133 5134 // Bases. 5135 for (const auto &Base : ClassDecl->bases()) { 5136 // Bases are always records in a well-formed non-dependent class. 5137 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5138 5139 // Remember direct virtual bases. 5140 if (Base.isVirtual()) { 5141 if (!VisitVirtualBases) 5142 continue; 5143 DirectVirtualBases.insert(RT); 5144 } 5145 5146 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5147 // If our base class is invalid, we probably can't get its dtor anyway. 5148 if (BaseClassDecl->isInvalidDecl()) 5149 continue; 5150 if (BaseClassDecl->hasIrrelevantDestructor()) 5151 continue; 5152 5153 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5154 assert(Dtor && "No dtor found for BaseClassDecl!"); 5155 5156 // FIXME: caret should be on the start of the class name 5157 CheckDestructorAccess(Base.getLocStart(), Dtor, 5158 PDiag(diag::err_access_dtor_base) 5159 << Base.getType() 5160 << Base.getSourceRange(), 5161 Context.getTypeDeclType(ClassDecl)); 5162 5163 MarkFunctionReferenced(Location, Dtor); 5164 DiagnoseUseOfDecl(Dtor, Location); 5165 } 5166 5167 if (!VisitVirtualBases) 5168 return; 5169 5170 // Virtual bases. 5171 for (const auto &VBase : ClassDecl->vbases()) { 5172 // Bases are always records in a well-formed non-dependent class. 5173 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5174 5175 // Ignore direct virtual bases. 5176 if (DirectVirtualBases.count(RT)) 5177 continue; 5178 5179 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5180 // If our base class is invalid, we probably can't get its dtor anyway. 5181 if (BaseClassDecl->isInvalidDecl()) 5182 continue; 5183 if (BaseClassDecl->hasIrrelevantDestructor()) 5184 continue; 5185 5186 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5187 assert(Dtor && "No dtor found for BaseClassDecl!"); 5188 if (CheckDestructorAccess( 5189 ClassDecl->getLocation(), Dtor, 5190 PDiag(diag::err_access_dtor_vbase) 5191 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5192 Context.getTypeDeclType(ClassDecl)) == 5193 AR_accessible) { 5194 CheckDerivedToBaseConversion( 5195 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5196 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5197 SourceRange(), DeclarationName(), nullptr); 5198 } 5199 5200 MarkFunctionReferenced(Location, Dtor); 5201 DiagnoseUseOfDecl(Dtor, Location); 5202 } 5203 } 5204 5205 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5206 if (!CDtorDecl) 5207 return; 5208 5209 if (CXXConstructorDecl *Constructor 5210 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5211 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5212 DiagnoseUninitializedFields(*this, Constructor); 5213 } 5214 } 5215 5216 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5217 if (!getLangOpts().CPlusPlus) 5218 return false; 5219 5220 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5221 if (!RD) 5222 return false; 5223 5224 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5225 // class template specialization here, but doing so breaks a lot of code. 5226 5227 // We can't answer whether something is abstract until it has a 5228 // definition. If it's currently being defined, we'll walk back 5229 // over all the declarations when we have a full definition. 5230 const CXXRecordDecl *Def = RD->getDefinition(); 5231 if (!Def || Def->isBeingDefined()) 5232 return false; 5233 5234 return RD->isAbstract(); 5235 } 5236 5237 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5238 TypeDiagnoser &Diagnoser) { 5239 if (!isAbstractType(Loc, T)) 5240 return false; 5241 5242 T = Context.getBaseElementType(T); 5243 Diagnoser.diagnose(*this, Loc, T); 5244 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5245 return true; 5246 } 5247 5248 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5249 // Check if we've already emitted the list of pure virtual functions 5250 // for this class. 5251 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5252 return; 5253 5254 // If the diagnostic is suppressed, don't emit the notes. We're only 5255 // going to emit them once, so try to attach them to a diagnostic we're 5256 // actually going to show. 5257 if (Diags.isLastDiagnosticIgnored()) 5258 return; 5259 5260 CXXFinalOverriderMap FinalOverriders; 5261 RD->getFinalOverriders(FinalOverriders); 5262 5263 // Keep a set of seen pure methods so we won't diagnose the same method 5264 // more than once. 5265 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5266 5267 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5268 MEnd = FinalOverriders.end(); 5269 M != MEnd; 5270 ++M) { 5271 for (OverridingMethods::iterator SO = M->second.begin(), 5272 SOEnd = M->second.end(); 5273 SO != SOEnd; ++SO) { 5274 // C++ [class.abstract]p4: 5275 // A class is abstract if it contains or inherits at least one 5276 // pure virtual function for which the final overrider is pure 5277 // virtual. 5278 5279 // 5280 if (SO->second.size() != 1) 5281 continue; 5282 5283 if (!SO->second.front().Method->isPure()) 5284 continue; 5285 5286 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5287 continue; 5288 5289 Diag(SO->second.front().Method->getLocation(), 5290 diag::note_pure_virtual_function) 5291 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5292 } 5293 } 5294 5295 if (!PureVirtualClassDiagSet) 5296 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5297 PureVirtualClassDiagSet->insert(RD); 5298 } 5299 5300 namespace { 5301 struct AbstractUsageInfo { 5302 Sema &S; 5303 CXXRecordDecl *Record; 5304 CanQualType AbstractType; 5305 bool Invalid; 5306 5307 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5308 : S(S), Record(Record), 5309 AbstractType(S.Context.getCanonicalType( 5310 S.Context.getTypeDeclType(Record))), 5311 Invalid(false) {} 5312 5313 void DiagnoseAbstractType() { 5314 if (Invalid) return; 5315 S.DiagnoseAbstractType(Record); 5316 Invalid = true; 5317 } 5318 5319 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5320 }; 5321 5322 struct CheckAbstractUsage { 5323 AbstractUsageInfo &Info; 5324 const NamedDecl *Ctx; 5325 5326 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5327 : Info(Info), Ctx(Ctx) {} 5328 5329 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5330 switch (TL.getTypeLocClass()) { 5331 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5332 #define TYPELOC(CLASS, PARENT) \ 5333 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5334 #include "clang/AST/TypeLocNodes.def" 5335 } 5336 } 5337 5338 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5339 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5340 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5341 if (!TL.getParam(I)) 5342 continue; 5343 5344 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5345 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5346 } 5347 } 5348 5349 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5350 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5351 } 5352 5353 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5354 // Visit the type parameters from a permissive context. 5355 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5356 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5357 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5358 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5359 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5360 // TODO: other template argument types? 5361 } 5362 } 5363 5364 // Visit pointee types from a permissive context. 5365 #define CheckPolymorphic(Type) \ 5366 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5367 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5368 } 5369 CheckPolymorphic(PointerTypeLoc) 5370 CheckPolymorphic(ReferenceTypeLoc) 5371 CheckPolymorphic(MemberPointerTypeLoc) 5372 CheckPolymorphic(BlockPointerTypeLoc) 5373 CheckPolymorphic(AtomicTypeLoc) 5374 5375 /// Handle all the types we haven't given a more specific 5376 /// implementation for above. 5377 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5378 // Every other kind of type that we haven't called out already 5379 // that has an inner type is either (1) sugar or (2) contains that 5380 // inner type in some way as a subobject. 5381 if (TypeLoc Next = TL.getNextTypeLoc()) 5382 return Visit(Next, Sel); 5383 5384 // If there's no inner type and we're in a permissive context, 5385 // don't diagnose. 5386 if (Sel == Sema::AbstractNone) return; 5387 5388 // Check whether the type matches the abstract type. 5389 QualType T = TL.getType(); 5390 if (T->isArrayType()) { 5391 Sel = Sema::AbstractArrayType; 5392 T = Info.S.Context.getBaseElementType(T); 5393 } 5394 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5395 if (CT != Info.AbstractType) return; 5396 5397 // It matched; do some magic. 5398 if (Sel == Sema::AbstractArrayType) { 5399 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5400 << T << TL.getSourceRange(); 5401 } else { 5402 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5403 << Sel << T << TL.getSourceRange(); 5404 } 5405 Info.DiagnoseAbstractType(); 5406 } 5407 }; 5408 5409 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5410 Sema::AbstractDiagSelID Sel) { 5411 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5412 } 5413 5414 } 5415 5416 /// Check for invalid uses of an abstract type in a method declaration. 5417 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5418 CXXMethodDecl *MD) { 5419 // No need to do the check on definitions, which require that 5420 // the return/param types be complete. 5421 if (MD->doesThisDeclarationHaveABody()) 5422 return; 5423 5424 // For safety's sake, just ignore it if we don't have type source 5425 // information. This should never happen for non-implicit methods, 5426 // but... 5427 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5428 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5429 } 5430 5431 /// Check for invalid uses of an abstract type within a class definition. 5432 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5433 CXXRecordDecl *RD) { 5434 for (auto *D : RD->decls()) { 5435 if (D->isImplicit()) continue; 5436 5437 // Methods and method templates. 5438 if (isa<CXXMethodDecl>(D)) { 5439 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5440 } else if (isa<FunctionTemplateDecl>(D)) { 5441 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5442 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5443 5444 // Fields and static variables. 5445 } else if (isa<FieldDecl>(D)) { 5446 FieldDecl *FD = cast<FieldDecl>(D); 5447 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5448 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5449 } else if (isa<VarDecl>(D)) { 5450 VarDecl *VD = cast<VarDecl>(D); 5451 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5452 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5453 5454 // Nested classes and class templates. 5455 } else if (isa<CXXRecordDecl>(D)) { 5456 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5457 } else if (isa<ClassTemplateDecl>(D)) { 5458 CheckAbstractClassUsage(Info, 5459 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5460 } 5461 } 5462 } 5463 5464 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 5465 Attr *ClassAttr = getDLLAttr(Class); 5466 if (!ClassAttr) 5467 return; 5468 5469 assert(ClassAttr->getKind() == attr::DLLExport); 5470 5471 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5472 5473 if (TSK == TSK_ExplicitInstantiationDeclaration) 5474 // Don't go any further if this is just an explicit instantiation 5475 // declaration. 5476 return; 5477 5478 for (Decl *Member : Class->decls()) { 5479 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5480 if (!MD) 5481 continue; 5482 5483 if (Member->getAttr<DLLExportAttr>()) { 5484 if (MD->isUserProvided()) { 5485 // Instantiate non-default class member functions ... 5486 5487 // .. except for certain kinds of template specializations. 5488 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5489 continue; 5490 5491 S.MarkFunctionReferenced(Class->getLocation(), MD); 5492 5493 // The function will be passed to the consumer when its definition is 5494 // encountered. 5495 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5496 MD->isCopyAssignmentOperator() || 5497 MD->isMoveAssignmentOperator()) { 5498 // Synthesize and instantiate non-trivial implicit methods, explicitly 5499 // defaulted methods, and the copy and move assignment operators. The 5500 // latter are exported even if they are trivial, because the address of 5501 // an operator can be taken and should compare equal across libraries. 5502 DiagnosticErrorTrap Trap(S.Diags); 5503 S.MarkFunctionReferenced(Class->getLocation(), MD); 5504 if (Trap.hasErrorOccurred()) { 5505 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5506 << Class->getName() << !S.getLangOpts().CPlusPlus11; 5507 break; 5508 } 5509 5510 // There is no later point when we will see the definition of this 5511 // function, so pass it to the consumer now. 5512 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5513 } 5514 } 5515 } 5516 } 5517 5518 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5519 CXXRecordDecl *Class) { 5520 // Only the MS ABI has default constructor closures, so we don't need to do 5521 // this semantic checking anywhere else. 5522 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5523 return; 5524 5525 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5526 for (Decl *Member : Class->decls()) { 5527 // Look for exported default constructors. 5528 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5529 if (!CD || !CD->isDefaultConstructor()) 5530 continue; 5531 auto *Attr = CD->getAttr<DLLExportAttr>(); 5532 if (!Attr) 5533 continue; 5534 5535 // If the class is non-dependent, mark the default arguments as ODR-used so 5536 // that we can properly codegen the constructor closure. 5537 if (!Class->isDependentContext()) { 5538 for (ParmVarDecl *PD : CD->parameters()) { 5539 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5540 S.DiscardCleanupsInEvaluationContext(); 5541 } 5542 } 5543 5544 if (LastExportedDefaultCtor) { 5545 S.Diag(LastExportedDefaultCtor->getLocation(), 5546 diag::err_attribute_dll_ambiguous_default_ctor) 5547 << Class; 5548 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5549 << CD->getDeclName(); 5550 return; 5551 } 5552 LastExportedDefaultCtor = CD; 5553 } 5554 } 5555 5556 /// \brief Check class-level dllimport/dllexport attribute. 5557 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5558 Attr *ClassAttr = getDLLAttr(Class); 5559 5560 // MSVC inherits DLL attributes to partial class template specializations. 5561 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5562 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5563 if (Attr *TemplateAttr = 5564 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5565 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5566 A->setInherited(true); 5567 ClassAttr = A; 5568 } 5569 } 5570 } 5571 5572 if (!ClassAttr) 5573 return; 5574 5575 if (!Class->isExternallyVisible()) { 5576 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5577 << Class << ClassAttr; 5578 return; 5579 } 5580 5581 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5582 !ClassAttr->isInherited()) { 5583 // Diagnose dll attributes on members of class with dll attribute. 5584 for (Decl *Member : Class->decls()) { 5585 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5586 continue; 5587 InheritableAttr *MemberAttr = getDLLAttr(Member); 5588 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5589 continue; 5590 5591 Diag(MemberAttr->getLocation(), 5592 diag::err_attribute_dll_member_of_dll_class) 5593 << MemberAttr << ClassAttr; 5594 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5595 Member->setInvalidDecl(); 5596 } 5597 } 5598 5599 if (Class->getDescribedClassTemplate()) 5600 // Don't inherit dll attribute until the template is instantiated. 5601 return; 5602 5603 // The class is either imported or exported. 5604 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5605 5606 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5607 5608 // Ignore explicit dllexport on explicit class template instantiation declarations. 5609 if (ClassExported && !ClassAttr->isInherited() && 5610 TSK == TSK_ExplicitInstantiationDeclaration) { 5611 Class->dropAttr<DLLExportAttr>(); 5612 return; 5613 } 5614 5615 // Force declaration of implicit members so they can inherit the attribute. 5616 ForceDeclarationOfImplicitMembers(Class); 5617 5618 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5619 // seem to be true in practice? 5620 5621 for (Decl *Member : Class->decls()) { 5622 VarDecl *VD = dyn_cast<VarDecl>(Member); 5623 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5624 5625 // Only methods and static fields inherit the attributes. 5626 if (!VD && !MD) 5627 continue; 5628 5629 if (MD) { 5630 // Don't process deleted methods. 5631 if (MD->isDeleted()) 5632 continue; 5633 5634 if (MD->isInlined()) { 5635 // MinGW does not import or export inline methods. 5636 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5637 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5638 continue; 5639 5640 // MSVC versions before 2015 don't export the move assignment operators 5641 // and move constructor, so don't attempt to import/export them if 5642 // we have a definition. 5643 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5644 if ((MD->isMoveAssignmentOperator() || 5645 (Ctor && Ctor->isMoveConstructor())) && 5646 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5647 continue; 5648 5649 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5650 // operator is exported anyway. 5651 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5652 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5653 continue; 5654 } 5655 } 5656 5657 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5658 continue; 5659 5660 if (!getDLLAttr(Member)) { 5661 auto *NewAttr = 5662 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5663 NewAttr->setInherited(true); 5664 Member->addAttr(NewAttr); 5665 } 5666 } 5667 5668 if (ClassExported) 5669 DelayedDllExportClasses.push_back(Class); 5670 } 5671 5672 /// \brief Perform propagation of DLL attributes from a derived class to a 5673 /// templated base class for MS compatibility. 5674 void Sema::propagateDLLAttrToBaseClassTemplate( 5675 CXXRecordDecl *Class, Attr *ClassAttr, 5676 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5677 if (getDLLAttr( 5678 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5679 // If the base class template has a DLL attribute, don't try to change it. 5680 return; 5681 } 5682 5683 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5684 if (!getDLLAttr(BaseTemplateSpec) && 5685 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5686 TSK == TSK_ImplicitInstantiation)) { 5687 // The template hasn't been instantiated yet (or it has, but only as an 5688 // explicit instantiation declaration or implicit instantiation, which means 5689 // we haven't codegenned any members yet), so propagate the attribute. 5690 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5691 NewAttr->setInherited(true); 5692 BaseTemplateSpec->addAttr(NewAttr); 5693 5694 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5695 // needs to be run again to work see the new attribute. Otherwise this will 5696 // get run whenever the template is instantiated. 5697 if (TSK != TSK_Undeclared) 5698 checkClassLevelDLLAttribute(BaseTemplateSpec); 5699 5700 return; 5701 } 5702 5703 if (getDLLAttr(BaseTemplateSpec)) { 5704 // The template has already been specialized or instantiated with an 5705 // attribute, explicitly or through propagation. We should not try to change 5706 // it. 5707 return; 5708 } 5709 5710 // The template was previously instantiated or explicitly specialized without 5711 // a dll attribute, It's too late for us to add an attribute, so warn that 5712 // this is unsupported. 5713 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5714 << BaseTemplateSpec->isExplicitSpecialization(); 5715 Diag(ClassAttr->getLocation(), diag::note_attribute); 5716 if (BaseTemplateSpec->isExplicitSpecialization()) { 5717 Diag(BaseTemplateSpec->getLocation(), 5718 diag::note_template_class_explicit_specialization_was_here) 5719 << BaseTemplateSpec; 5720 } else { 5721 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5722 diag::note_template_class_instantiation_was_here) 5723 << BaseTemplateSpec; 5724 } 5725 } 5726 5727 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5728 SourceLocation DefaultLoc) { 5729 switch (S.getSpecialMember(MD)) { 5730 case Sema::CXXDefaultConstructor: 5731 S.DefineImplicitDefaultConstructor(DefaultLoc, 5732 cast<CXXConstructorDecl>(MD)); 5733 break; 5734 case Sema::CXXCopyConstructor: 5735 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5736 break; 5737 case Sema::CXXCopyAssignment: 5738 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5739 break; 5740 case Sema::CXXDestructor: 5741 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5742 break; 5743 case Sema::CXXMoveConstructor: 5744 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5745 break; 5746 case Sema::CXXMoveAssignment: 5747 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5748 break; 5749 case Sema::CXXInvalid: 5750 llvm_unreachable("Invalid special member."); 5751 } 5752 } 5753 5754 /// Determine whether a type is permitted to be passed or returned in 5755 /// registers, per C++ [class.temporary]p3. 5756 static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) { 5757 if (D->isDependentType() || D->isInvalidDecl()) 5758 return false; 5759 5760 // Per C++ [class.temporary]p3, the relevant condition is: 5761 // each copy constructor, move constructor, and destructor of X is 5762 // either trivial or deleted, and X has at least one non-deleted copy 5763 // or move constructor 5764 bool HasNonDeletedCopyOrMove = false; 5765 5766 if (D->needsImplicitCopyConstructor() && 5767 !D->defaultedCopyConstructorIsDeleted()) { 5768 if (!D->hasTrivialCopyConstructor()) 5769 return false; 5770 HasNonDeletedCopyOrMove = true; 5771 } 5772 5773 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5774 !D->defaultedMoveConstructorIsDeleted()) { 5775 if (!D->hasTrivialMoveConstructor()) 5776 return false; 5777 HasNonDeletedCopyOrMove = true; 5778 } 5779 5780 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5781 !D->hasTrivialDestructor()) 5782 return false; 5783 5784 for (const CXXMethodDecl *MD : D->methods()) { 5785 if (MD->isDeleted()) 5786 continue; 5787 5788 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5789 if (CD && CD->isCopyOrMoveConstructor()) 5790 HasNonDeletedCopyOrMove = true; 5791 else if (!isa<CXXDestructorDecl>(MD)) 5792 continue; 5793 5794 if (!MD->isTrivial()) 5795 return false; 5796 } 5797 5798 return HasNonDeletedCopyOrMove; 5799 } 5800 5801 /// \brief Perform semantic checks on a class definition that has been 5802 /// completing, introducing implicitly-declared members, checking for 5803 /// abstract types, etc. 5804 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5805 if (!Record) 5806 return; 5807 5808 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5809 AbstractUsageInfo Info(*this, Record); 5810 CheckAbstractClassUsage(Info, Record); 5811 } 5812 5813 // If this is not an aggregate type and has no user-declared constructor, 5814 // complain about any non-static data members of reference or const scalar 5815 // type, since they will never get initializers. 5816 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5817 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5818 !Record->isLambda()) { 5819 bool Complained = false; 5820 for (const auto *F : Record->fields()) { 5821 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5822 continue; 5823 5824 if (F->getType()->isReferenceType() || 5825 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5826 if (!Complained) { 5827 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5828 << Record->getTagKind() << Record; 5829 Complained = true; 5830 } 5831 5832 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5833 << F->getType()->isReferenceType() 5834 << F->getDeclName(); 5835 } 5836 } 5837 } 5838 5839 if (Record->getIdentifier()) { 5840 // C++ [class.mem]p13: 5841 // If T is the name of a class, then each of the following shall have a 5842 // name different from T: 5843 // - every member of every anonymous union that is a member of class T. 5844 // 5845 // C++ [class.mem]p14: 5846 // In addition, if class T has a user-declared constructor (12.1), every 5847 // non-static data member of class T shall have a name different from T. 5848 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5849 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5850 ++I) { 5851 NamedDecl *D = *I; 5852 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5853 isa<IndirectFieldDecl>(D)) { 5854 Diag(D->getLocation(), diag::err_member_name_of_class) 5855 << D->getDeclName(); 5856 break; 5857 } 5858 } 5859 } 5860 5861 // Warn if the class has virtual methods but non-virtual public destructor. 5862 if (Record->isPolymorphic() && !Record->isDependentType()) { 5863 CXXDestructorDecl *dtor = Record->getDestructor(); 5864 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5865 !Record->hasAttr<FinalAttr>()) 5866 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5867 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5868 } 5869 5870 if (Record->isAbstract()) { 5871 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5872 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5873 << FA->isSpelledAsSealed(); 5874 DiagnoseAbstractType(Record); 5875 } 5876 } 5877 5878 bool HasMethodWithOverrideControl = false, 5879 HasOverridingMethodWithoutOverrideControl = false; 5880 if (!Record->isDependentType()) { 5881 for (auto *M : Record->methods()) { 5882 // See if a method overloads virtual methods in a base 5883 // class without overriding any. 5884 if (!M->isStatic()) 5885 DiagnoseHiddenVirtualMethods(M); 5886 if (M->hasAttr<OverrideAttr>()) 5887 HasMethodWithOverrideControl = true; 5888 else if (M->size_overridden_methods() > 0) 5889 HasOverridingMethodWithoutOverrideControl = true; 5890 // Check whether the explicitly-defaulted special members are valid. 5891 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5892 CheckExplicitlyDefaultedSpecialMember(M); 5893 5894 // For an explicitly defaulted or deleted special member, we defer 5895 // determining triviality until the class is complete. That time is now! 5896 CXXSpecialMember CSM = getSpecialMember(M); 5897 if (!M->isImplicit() && !M->isUserProvided()) { 5898 if (CSM != CXXInvalid) { 5899 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5900 5901 // Inform the class that we've finished declaring this member. 5902 Record->finishedDefaultedOrDeletedMember(M); 5903 } 5904 } 5905 5906 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5907 M->hasAttr<DLLExportAttr>()) { 5908 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5909 M->isTrivial() && 5910 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5911 CSM == CXXDestructor)) 5912 M->dropAttr<DLLExportAttr>(); 5913 5914 if (M->hasAttr<DLLExportAttr>()) { 5915 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5916 ActOnFinishInlineFunctionDef(M); 5917 } 5918 } 5919 } 5920 } 5921 5922 if (HasMethodWithOverrideControl && 5923 HasOverridingMethodWithoutOverrideControl) { 5924 // At least one method has the 'override' control declared. 5925 // Diagnose all other overridden methods which do not have 'override' specified on them. 5926 for (auto *M : Record->methods()) 5927 DiagnoseAbsenceOfOverrideControl(M); 5928 } 5929 5930 // ms_struct is a request to use the same ABI rules as MSVC. Check 5931 // whether this class uses any C++ features that are implemented 5932 // completely differently in MSVC, and if so, emit a diagnostic. 5933 // That diagnostic defaults to an error, but we allow projects to 5934 // map it down to a warning (or ignore it). It's a fairly common 5935 // practice among users of the ms_struct pragma to mass-annotate 5936 // headers, sweeping up a bunch of types that the project doesn't 5937 // really rely on MSVC-compatible layout for. We must therefore 5938 // support "ms_struct except for C++ stuff" as a secondary ABI. 5939 if (Record->isMsStruct(Context) && 5940 (Record->isPolymorphic() || Record->getNumBases())) { 5941 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5942 } 5943 5944 checkClassLevelDLLAttribute(Record); 5945 5946 Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record)); 5947 } 5948 5949 /// Look up the special member function that would be called by a special 5950 /// member function for a subobject of class type. 5951 /// 5952 /// \param Class The class type of the subobject. 5953 /// \param CSM The kind of special member function. 5954 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5955 /// \param ConstRHS True if this is a copy operation with a const object 5956 /// on its RHS, that is, if the argument to the outer special member 5957 /// function is 'const' and this is not a field marked 'mutable'. 5958 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 5959 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5960 unsigned FieldQuals, bool ConstRHS) { 5961 unsigned LHSQuals = 0; 5962 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5963 LHSQuals = FieldQuals; 5964 5965 unsigned RHSQuals = FieldQuals; 5966 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5967 RHSQuals = 0; 5968 else if (ConstRHS) 5969 RHSQuals |= Qualifiers::Const; 5970 5971 return S.LookupSpecialMember(Class, CSM, 5972 RHSQuals & Qualifiers::Const, 5973 RHSQuals & Qualifiers::Volatile, 5974 false, 5975 LHSQuals & Qualifiers::Const, 5976 LHSQuals & Qualifiers::Volatile); 5977 } 5978 5979 class Sema::InheritedConstructorInfo { 5980 Sema &S; 5981 SourceLocation UseLoc; 5982 5983 /// A mapping from the base classes through which the constructor was 5984 /// inherited to the using shadow declaration in that base class (or a null 5985 /// pointer if the constructor was declared in that base class). 5986 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 5987 InheritedFromBases; 5988 5989 public: 5990 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 5991 ConstructorUsingShadowDecl *Shadow) 5992 : S(S), UseLoc(UseLoc) { 5993 bool DiagnosedMultipleConstructedBases = false; 5994 CXXRecordDecl *ConstructedBase = nullptr; 5995 UsingDecl *ConstructedBaseUsing = nullptr; 5996 5997 // Find the set of such base class subobjects and check that there's a 5998 // unique constructed subobject. 5999 for (auto *D : Shadow->redecls()) { 6000 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6001 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6002 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6003 6004 InheritedFromBases.insert( 6005 std::make_pair(DNominatedBase->getCanonicalDecl(), 6006 DShadow->getNominatedBaseClassShadowDecl())); 6007 if (DShadow->constructsVirtualBase()) 6008 InheritedFromBases.insert( 6009 std::make_pair(DConstructedBase->getCanonicalDecl(), 6010 DShadow->getConstructedBaseClassShadowDecl())); 6011 else 6012 assert(DNominatedBase == DConstructedBase); 6013 6014 // [class.inhctor.init]p2: 6015 // If the constructor was inherited from multiple base class subobjects 6016 // of type B, the program is ill-formed. 6017 if (!ConstructedBase) { 6018 ConstructedBase = DConstructedBase; 6019 ConstructedBaseUsing = D->getUsingDecl(); 6020 } else if (ConstructedBase != DConstructedBase && 6021 !Shadow->isInvalidDecl()) { 6022 if (!DiagnosedMultipleConstructedBases) { 6023 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6024 << Shadow->getTargetDecl(); 6025 S.Diag(ConstructedBaseUsing->getLocation(), 6026 diag::note_ambiguous_inherited_constructor_using) 6027 << ConstructedBase; 6028 DiagnosedMultipleConstructedBases = true; 6029 } 6030 S.Diag(D->getUsingDecl()->getLocation(), 6031 diag::note_ambiguous_inherited_constructor_using) 6032 << DConstructedBase; 6033 } 6034 } 6035 6036 if (DiagnosedMultipleConstructedBases) 6037 Shadow->setInvalidDecl(); 6038 } 6039 6040 /// Find the constructor to use for inherited construction of a base class, 6041 /// and whether that base class constructor inherits the constructor from a 6042 /// virtual base class (in which case it won't actually invoke it). 6043 std::pair<CXXConstructorDecl *, bool> 6044 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6045 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6046 if (It == InheritedFromBases.end()) 6047 return std::make_pair(nullptr, false); 6048 6049 // This is an intermediary class. 6050 if (It->second) 6051 return std::make_pair( 6052 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6053 It->second->constructsVirtualBase()); 6054 6055 // This is the base class from which the constructor was inherited. 6056 return std::make_pair(Ctor, false); 6057 } 6058 }; 6059 6060 /// Is the special member function which would be selected to perform the 6061 /// specified operation on the specified class type a constexpr constructor? 6062 static bool 6063 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6064 Sema::CXXSpecialMember CSM, unsigned Quals, 6065 bool ConstRHS, 6066 CXXConstructorDecl *InheritedCtor = nullptr, 6067 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6068 // If we're inheriting a constructor, see if we need to call it for this base 6069 // class. 6070 if (InheritedCtor) { 6071 assert(CSM == Sema::CXXDefaultConstructor); 6072 auto BaseCtor = 6073 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6074 if (BaseCtor) 6075 return BaseCtor->isConstexpr(); 6076 } 6077 6078 if (CSM == Sema::CXXDefaultConstructor) 6079 return ClassDecl->hasConstexprDefaultConstructor(); 6080 6081 Sema::SpecialMemberOverloadResult SMOR = 6082 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6083 if (!SMOR.getMethod()) 6084 // A constructor we wouldn't select can't be "involved in initializing" 6085 // anything. 6086 return true; 6087 return SMOR.getMethod()->isConstexpr(); 6088 } 6089 6090 /// Determine whether the specified special member function would be constexpr 6091 /// if it were implicitly defined. 6092 static bool defaultedSpecialMemberIsConstexpr( 6093 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6094 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6095 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6096 if (!S.getLangOpts().CPlusPlus11) 6097 return false; 6098 6099 // C++11 [dcl.constexpr]p4: 6100 // In the definition of a constexpr constructor [...] 6101 bool Ctor = true; 6102 switch (CSM) { 6103 case Sema::CXXDefaultConstructor: 6104 if (Inherited) 6105 break; 6106 // Since default constructor lookup is essentially trivial (and cannot 6107 // involve, for instance, template instantiation), we compute whether a 6108 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6109 // 6110 // This is important for performance; we need to know whether the default 6111 // constructor is constexpr to determine whether the type is a literal type. 6112 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6113 6114 case Sema::CXXCopyConstructor: 6115 case Sema::CXXMoveConstructor: 6116 // For copy or move constructors, we need to perform overload resolution. 6117 break; 6118 6119 case Sema::CXXCopyAssignment: 6120 case Sema::CXXMoveAssignment: 6121 if (!S.getLangOpts().CPlusPlus14) 6122 return false; 6123 // In C++1y, we need to perform overload resolution. 6124 Ctor = false; 6125 break; 6126 6127 case Sema::CXXDestructor: 6128 case Sema::CXXInvalid: 6129 return false; 6130 } 6131 6132 // -- if the class is a non-empty union, or for each non-empty anonymous 6133 // union member of a non-union class, exactly one non-static data member 6134 // shall be initialized; [DR1359] 6135 // 6136 // If we squint, this is guaranteed, since exactly one non-static data member 6137 // will be initialized (if the constructor isn't deleted), we just don't know 6138 // which one. 6139 if (Ctor && ClassDecl->isUnion()) 6140 return CSM == Sema::CXXDefaultConstructor 6141 ? ClassDecl->hasInClassInitializer() || 6142 !ClassDecl->hasVariantMembers() 6143 : true; 6144 6145 // -- the class shall not have any virtual base classes; 6146 if (Ctor && ClassDecl->getNumVBases()) 6147 return false; 6148 6149 // C++1y [class.copy]p26: 6150 // -- [the class] is a literal type, and 6151 if (!Ctor && !ClassDecl->isLiteral()) 6152 return false; 6153 6154 // -- every constructor involved in initializing [...] base class 6155 // sub-objects shall be a constexpr constructor; 6156 // -- the assignment operator selected to copy/move each direct base 6157 // class is a constexpr function, and 6158 for (const auto &B : ClassDecl->bases()) { 6159 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6160 if (!BaseType) continue; 6161 6162 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6163 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6164 InheritedCtor, Inherited)) 6165 return false; 6166 } 6167 6168 // -- every constructor involved in initializing non-static data members 6169 // [...] shall be a constexpr constructor; 6170 // -- every non-static data member and base class sub-object shall be 6171 // initialized 6172 // -- for each non-static data member of X that is of class type (or array 6173 // thereof), the assignment operator selected to copy/move that member is 6174 // a constexpr function 6175 for (const auto *F : ClassDecl->fields()) { 6176 if (F->isInvalidDecl()) 6177 continue; 6178 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6179 continue; 6180 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6181 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6182 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6183 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6184 BaseType.getCVRQualifiers(), 6185 ConstArg && !F->isMutable())) 6186 return false; 6187 } else if (CSM == Sema::CXXDefaultConstructor) { 6188 return false; 6189 } 6190 } 6191 6192 // All OK, it's constexpr! 6193 return true; 6194 } 6195 6196 static Sema::ImplicitExceptionSpecification 6197 ComputeDefaultedSpecialMemberExceptionSpec( 6198 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6199 Sema::InheritedConstructorInfo *ICI); 6200 6201 static Sema::ImplicitExceptionSpecification 6202 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6203 auto CSM = S.getSpecialMember(MD); 6204 if (CSM != Sema::CXXInvalid) 6205 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6206 6207 auto *CD = cast<CXXConstructorDecl>(MD); 6208 assert(CD->getInheritedConstructor() && 6209 "only special members have implicit exception specs"); 6210 Sema::InheritedConstructorInfo ICI( 6211 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6212 return ComputeDefaultedSpecialMemberExceptionSpec( 6213 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6214 } 6215 6216 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6217 CXXMethodDecl *MD) { 6218 FunctionProtoType::ExtProtoInfo EPI; 6219 6220 // Build an exception specification pointing back at this member. 6221 EPI.ExceptionSpec.Type = EST_Unevaluated; 6222 EPI.ExceptionSpec.SourceDecl = MD; 6223 6224 // Set the calling convention to the default for C++ instance methods. 6225 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6226 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6227 /*IsCXXMethod=*/true)); 6228 return EPI; 6229 } 6230 6231 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6232 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6233 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6234 return; 6235 6236 // Evaluate the exception specification. 6237 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6238 auto ESI = IES.getExceptionSpec(); 6239 6240 // Update the type of the special member to use it. 6241 UpdateExceptionSpec(MD, ESI); 6242 6243 // A user-provided destructor can be defined outside the class. When that 6244 // happens, be sure to update the exception specification on both 6245 // declarations. 6246 const FunctionProtoType *CanonicalFPT = 6247 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6248 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6249 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6250 } 6251 6252 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6253 CXXRecordDecl *RD = MD->getParent(); 6254 CXXSpecialMember CSM = getSpecialMember(MD); 6255 6256 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6257 "not an explicitly-defaulted special member"); 6258 6259 // Whether this was the first-declared instance of the constructor. 6260 // This affects whether we implicitly add an exception spec and constexpr. 6261 bool First = MD == MD->getCanonicalDecl(); 6262 6263 bool HadError = false; 6264 6265 // C++11 [dcl.fct.def.default]p1: 6266 // A function that is explicitly defaulted shall 6267 // -- be a special member function (checked elsewhere), 6268 // -- have the same type (except for ref-qualifiers, and except that a 6269 // copy operation can take a non-const reference) as an implicit 6270 // declaration, and 6271 // -- not have default arguments. 6272 unsigned ExpectedParams = 1; 6273 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6274 ExpectedParams = 0; 6275 if (MD->getNumParams() != ExpectedParams) { 6276 // This also checks for default arguments: a copy or move constructor with a 6277 // default argument is classified as a default constructor, and assignment 6278 // operations and destructors can't have default arguments. 6279 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6280 << CSM << MD->getSourceRange(); 6281 HadError = true; 6282 } else if (MD->isVariadic()) { 6283 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6284 << CSM << MD->getSourceRange(); 6285 HadError = true; 6286 } 6287 6288 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6289 6290 bool CanHaveConstParam = false; 6291 if (CSM == CXXCopyConstructor) 6292 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6293 else if (CSM == CXXCopyAssignment) 6294 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6295 6296 QualType ReturnType = Context.VoidTy; 6297 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6298 // Check for return type matching. 6299 ReturnType = Type->getReturnType(); 6300 QualType ExpectedReturnType = 6301 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6302 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6303 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6304 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6305 HadError = true; 6306 } 6307 6308 // A defaulted special member cannot have cv-qualifiers. 6309 if (Type->getTypeQuals()) { 6310 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6311 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6312 HadError = true; 6313 } 6314 } 6315 6316 // Check for parameter type matching. 6317 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6318 bool HasConstParam = false; 6319 if (ExpectedParams && ArgType->isReferenceType()) { 6320 // Argument must be reference to possibly-const T. 6321 QualType ReferentType = ArgType->getPointeeType(); 6322 HasConstParam = ReferentType.isConstQualified(); 6323 6324 if (ReferentType.isVolatileQualified()) { 6325 Diag(MD->getLocation(), 6326 diag::err_defaulted_special_member_volatile_param) << CSM; 6327 HadError = true; 6328 } 6329 6330 if (HasConstParam && !CanHaveConstParam) { 6331 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6332 Diag(MD->getLocation(), 6333 diag::err_defaulted_special_member_copy_const_param) 6334 << (CSM == CXXCopyAssignment); 6335 // FIXME: Explain why this special member can't be const. 6336 } else { 6337 Diag(MD->getLocation(), 6338 diag::err_defaulted_special_member_move_const_param) 6339 << (CSM == CXXMoveAssignment); 6340 } 6341 HadError = true; 6342 } 6343 } else if (ExpectedParams) { 6344 // A copy assignment operator can take its argument by value, but a 6345 // defaulted one cannot. 6346 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6347 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6348 HadError = true; 6349 } 6350 6351 // C++11 [dcl.fct.def.default]p2: 6352 // An explicitly-defaulted function may be declared constexpr only if it 6353 // would have been implicitly declared as constexpr, 6354 // Do not apply this rule to members of class templates, since core issue 1358 6355 // makes such functions always instantiate to constexpr functions. For 6356 // functions which cannot be constexpr (for non-constructors in C++11 and for 6357 // destructors in C++1y), this is checked elsewhere. 6358 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6359 HasConstParam); 6360 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6361 : isa<CXXConstructorDecl>(MD)) && 6362 MD->isConstexpr() && !Constexpr && 6363 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6364 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6365 // FIXME: Explain why the special member can't be constexpr. 6366 HadError = true; 6367 } 6368 6369 // and may have an explicit exception-specification only if it is compatible 6370 // with the exception-specification on the implicit declaration. 6371 if (Type->hasExceptionSpec()) { 6372 // Delay the check if this is the first declaration of the special member, 6373 // since we may not have parsed some necessary in-class initializers yet. 6374 if (First) { 6375 // If the exception specification needs to be instantiated, do so now, 6376 // before we clobber it with an EST_Unevaluated specification below. 6377 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6378 InstantiateExceptionSpec(MD->getLocStart(), MD); 6379 Type = MD->getType()->getAs<FunctionProtoType>(); 6380 } 6381 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6382 } else 6383 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6384 } 6385 6386 // If a function is explicitly defaulted on its first declaration, 6387 if (First) { 6388 // -- it is implicitly considered to be constexpr if the implicit 6389 // definition would be, 6390 MD->setConstexpr(Constexpr); 6391 6392 // -- it is implicitly considered to have the same exception-specification 6393 // as if it had been implicitly declared, 6394 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6395 EPI.ExceptionSpec.Type = EST_Unevaluated; 6396 EPI.ExceptionSpec.SourceDecl = MD; 6397 MD->setType(Context.getFunctionType(ReturnType, 6398 llvm::makeArrayRef(&ArgType, 6399 ExpectedParams), 6400 EPI)); 6401 } 6402 6403 if (ShouldDeleteSpecialMember(MD, CSM)) { 6404 if (First) { 6405 SetDeclDeleted(MD, MD->getLocation()); 6406 } else { 6407 // C++11 [dcl.fct.def.default]p4: 6408 // [For a] user-provided explicitly-defaulted function [...] if such a 6409 // function is implicitly defined as deleted, the program is ill-formed. 6410 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6411 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6412 HadError = true; 6413 } 6414 } 6415 6416 if (HadError) 6417 MD->setInvalidDecl(); 6418 } 6419 6420 /// Check whether the exception specification provided for an 6421 /// explicitly-defaulted special member matches the exception specification 6422 /// that would have been generated for an implicit special member, per 6423 /// C++11 [dcl.fct.def.default]p2. 6424 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6425 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6426 // If the exception specification was explicitly specified but hadn't been 6427 // parsed when the method was defaulted, grab it now. 6428 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6429 SpecifiedType = 6430 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6431 6432 // Compute the implicit exception specification. 6433 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6434 /*IsCXXMethod=*/true); 6435 FunctionProtoType::ExtProtoInfo EPI(CC); 6436 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6437 EPI.ExceptionSpec = IES.getExceptionSpec(); 6438 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6439 Context.getFunctionType(Context.VoidTy, None, EPI)); 6440 6441 // Ensure that it matches. 6442 CheckEquivalentExceptionSpec( 6443 PDiag(diag::err_incorrect_defaulted_exception_spec) 6444 << getSpecialMember(MD), PDiag(), 6445 ImplicitType, SourceLocation(), 6446 SpecifiedType, MD->getLocation()); 6447 } 6448 6449 void Sema::CheckDelayedMemberExceptionSpecs() { 6450 decltype(DelayedExceptionSpecChecks) Checks; 6451 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6452 6453 std::swap(Checks, DelayedExceptionSpecChecks); 6454 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6455 6456 // Perform any deferred checking of exception specifications for virtual 6457 // destructors. 6458 for (auto &Check : Checks) 6459 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6460 6461 // Check that any explicitly-defaulted methods have exception specifications 6462 // compatible with their implicit exception specifications. 6463 for (auto &Spec : Specs) 6464 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6465 } 6466 6467 namespace { 6468 /// CRTP base class for visiting operations performed by a special member 6469 /// function (or inherited constructor). 6470 template<typename Derived> 6471 struct SpecialMemberVisitor { 6472 Sema &S; 6473 CXXMethodDecl *MD; 6474 Sema::CXXSpecialMember CSM; 6475 Sema::InheritedConstructorInfo *ICI; 6476 6477 // Properties of the special member, computed for convenience. 6478 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6479 6480 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6481 Sema::InheritedConstructorInfo *ICI) 6482 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6483 switch (CSM) { 6484 case Sema::CXXDefaultConstructor: 6485 case Sema::CXXCopyConstructor: 6486 case Sema::CXXMoveConstructor: 6487 IsConstructor = true; 6488 break; 6489 case Sema::CXXCopyAssignment: 6490 case Sema::CXXMoveAssignment: 6491 IsAssignment = true; 6492 break; 6493 case Sema::CXXDestructor: 6494 break; 6495 case Sema::CXXInvalid: 6496 llvm_unreachable("invalid special member kind"); 6497 } 6498 6499 if (MD->getNumParams()) { 6500 if (const ReferenceType *RT = 6501 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6502 ConstArg = RT->getPointeeType().isConstQualified(); 6503 } 6504 } 6505 6506 Derived &getDerived() { return static_cast<Derived&>(*this); } 6507 6508 /// Is this a "move" special member? 6509 bool isMove() const { 6510 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6511 } 6512 6513 /// Look up the corresponding special member in the given class. 6514 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6515 unsigned Quals, bool IsMutable) { 6516 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6517 ConstArg && !IsMutable); 6518 } 6519 6520 /// Look up the constructor for the specified base class to see if it's 6521 /// overridden due to this being an inherited constructor. 6522 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6523 if (!ICI) 6524 return {}; 6525 assert(CSM == Sema::CXXDefaultConstructor); 6526 auto *BaseCtor = 6527 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6528 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6529 return MD; 6530 return {}; 6531 } 6532 6533 /// A base or member subobject. 6534 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6535 6536 /// Get the location to use for a subobject in diagnostics. 6537 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6538 // FIXME: For an indirect virtual base, the direct base leading to 6539 // the indirect virtual base would be a more useful choice. 6540 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6541 return B->getBaseTypeLoc(); 6542 else 6543 return Subobj.get<FieldDecl*>()->getLocation(); 6544 } 6545 6546 enum BasesToVisit { 6547 /// Visit all non-virtual (direct) bases. 6548 VisitNonVirtualBases, 6549 /// Visit all direct bases, virtual or not. 6550 VisitDirectBases, 6551 /// Visit all non-virtual bases, and all virtual bases if the class 6552 /// is not abstract. 6553 VisitPotentiallyConstructedBases, 6554 /// Visit all direct or virtual bases. 6555 VisitAllBases 6556 }; 6557 6558 // Visit the bases and members of the class. 6559 bool visit(BasesToVisit Bases) { 6560 CXXRecordDecl *RD = MD->getParent(); 6561 6562 if (Bases == VisitPotentiallyConstructedBases) 6563 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6564 6565 for (auto &B : RD->bases()) 6566 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6567 getDerived().visitBase(&B)) 6568 return true; 6569 6570 if (Bases == VisitAllBases) 6571 for (auto &B : RD->vbases()) 6572 if (getDerived().visitBase(&B)) 6573 return true; 6574 6575 for (auto *F : RD->fields()) 6576 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6577 getDerived().visitField(F)) 6578 return true; 6579 6580 return false; 6581 } 6582 }; 6583 } 6584 6585 namespace { 6586 struct SpecialMemberDeletionInfo 6587 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6588 bool Diagnose; 6589 6590 SourceLocation Loc; 6591 6592 bool AllFieldsAreConst; 6593 6594 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6595 Sema::CXXSpecialMember CSM, 6596 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6597 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6598 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6599 6600 bool inUnion() const { return MD->getParent()->isUnion(); } 6601 6602 Sema::CXXSpecialMember getEffectiveCSM() { 6603 return ICI ? Sema::CXXInvalid : CSM; 6604 } 6605 6606 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6607 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6608 6609 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6610 bool shouldDeleteForField(FieldDecl *FD); 6611 bool shouldDeleteForAllConstMembers(); 6612 6613 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6614 unsigned Quals); 6615 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6616 Sema::SpecialMemberOverloadResult SMOR, 6617 bool IsDtorCallInCtor); 6618 6619 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6620 }; 6621 } 6622 6623 /// Is the given special member inaccessible when used on the given 6624 /// sub-object. 6625 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6626 CXXMethodDecl *target) { 6627 /// If we're operating on a base class, the object type is the 6628 /// type of this special member. 6629 QualType objectTy; 6630 AccessSpecifier access = target->getAccess(); 6631 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6632 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6633 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6634 6635 // If we're operating on a field, the object type is the type of the field. 6636 } else { 6637 objectTy = S.Context.getTypeDeclType(target->getParent()); 6638 } 6639 6640 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6641 } 6642 6643 /// Check whether we should delete a special member due to the implicit 6644 /// definition containing a call to a special member of a subobject. 6645 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6646 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6647 bool IsDtorCallInCtor) { 6648 CXXMethodDecl *Decl = SMOR.getMethod(); 6649 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6650 6651 int DiagKind = -1; 6652 6653 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6654 DiagKind = !Decl ? 0 : 1; 6655 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6656 DiagKind = 2; 6657 else if (!isAccessible(Subobj, Decl)) 6658 DiagKind = 3; 6659 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6660 !Decl->isTrivial()) { 6661 // A member of a union must have a trivial corresponding special member. 6662 // As a weird special case, a destructor call from a union's constructor 6663 // must be accessible and non-deleted, but need not be trivial. Such a 6664 // destructor is never actually called, but is semantically checked as 6665 // if it were. 6666 DiagKind = 4; 6667 } 6668 6669 if (DiagKind == -1) 6670 return false; 6671 6672 if (Diagnose) { 6673 if (Field) { 6674 S.Diag(Field->getLocation(), 6675 diag::note_deleted_special_member_class_subobject) 6676 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6677 << Field << DiagKind << IsDtorCallInCtor; 6678 } else { 6679 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6680 S.Diag(Base->getLocStart(), 6681 diag::note_deleted_special_member_class_subobject) 6682 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6683 << Base->getType() << DiagKind << IsDtorCallInCtor; 6684 } 6685 6686 if (DiagKind == 1) 6687 S.NoteDeletedFunction(Decl); 6688 // FIXME: Explain inaccessibility if DiagKind == 3. 6689 } 6690 6691 return true; 6692 } 6693 6694 /// Check whether we should delete a special member function due to having a 6695 /// direct or virtual base class or non-static data member of class type M. 6696 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6697 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6698 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6699 bool IsMutable = Field && Field->isMutable(); 6700 6701 // C++11 [class.ctor]p5: 6702 // -- any direct or virtual base class, or non-static data member with no 6703 // brace-or-equal-initializer, has class type M (or array thereof) and 6704 // either M has no default constructor or overload resolution as applied 6705 // to M's default constructor results in an ambiguity or in a function 6706 // that is deleted or inaccessible 6707 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6708 // -- a direct or virtual base class B that cannot be copied/moved because 6709 // overload resolution, as applied to B's corresponding special member, 6710 // results in an ambiguity or a function that is deleted or inaccessible 6711 // from the defaulted special member 6712 // C++11 [class.dtor]p5: 6713 // -- any direct or virtual base class [...] has a type with a destructor 6714 // that is deleted or inaccessible 6715 if (!(CSM == Sema::CXXDefaultConstructor && 6716 Field && Field->hasInClassInitializer()) && 6717 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6718 false)) 6719 return true; 6720 6721 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6722 // -- any direct or virtual base class or non-static data member has a 6723 // type with a destructor that is deleted or inaccessible 6724 if (IsConstructor) { 6725 Sema::SpecialMemberOverloadResult SMOR = 6726 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6727 false, false, false, false, false); 6728 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6729 return true; 6730 } 6731 6732 return false; 6733 } 6734 6735 /// Check whether we should delete a special member function due to the class 6736 /// having a particular direct or virtual base class. 6737 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6738 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6739 // If program is correct, BaseClass cannot be null, but if it is, the error 6740 // must be reported elsewhere. 6741 if (!BaseClass) 6742 return false; 6743 // If we have an inheriting constructor, check whether we're calling an 6744 // inherited constructor instead of a default constructor. 6745 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6746 if (auto *BaseCtor = SMOR.getMethod()) { 6747 // Note that we do not check access along this path; other than that, 6748 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6749 // FIXME: Check that the base has a usable destructor! Sink this into 6750 // shouldDeleteForClassSubobject. 6751 if (BaseCtor->isDeleted() && Diagnose) { 6752 S.Diag(Base->getLocStart(), 6753 diag::note_deleted_special_member_class_subobject) 6754 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6755 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6756 S.NoteDeletedFunction(BaseCtor); 6757 } 6758 return BaseCtor->isDeleted(); 6759 } 6760 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6761 } 6762 6763 /// Check whether we should delete a special member function due to the class 6764 /// having a particular non-static data member. 6765 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6766 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6767 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6768 6769 if (CSM == Sema::CXXDefaultConstructor) { 6770 // For a default constructor, all references must be initialized in-class 6771 // and, if a union, it must have a non-const member. 6772 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6773 if (Diagnose) 6774 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6775 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6776 return true; 6777 } 6778 // C++11 [class.ctor]p5: any non-variant non-static data member of 6779 // const-qualified type (or array thereof) with no 6780 // brace-or-equal-initializer does not have a user-provided default 6781 // constructor. 6782 if (!inUnion() && FieldType.isConstQualified() && 6783 !FD->hasInClassInitializer() && 6784 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6785 if (Diagnose) 6786 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6787 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6788 return true; 6789 } 6790 6791 if (inUnion() && !FieldType.isConstQualified()) 6792 AllFieldsAreConst = false; 6793 } else if (CSM == Sema::CXXCopyConstructor) { 6794 // For a copy constructor, data members must not be of rvalue reference 6795 // type. 6796 if (FieldType->isRValueReferenceType()) { 6797 if (Diagnose) 6798 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6799 << MD->getParent() << FD << FieldType; 6800 return true; 6801 } 6802 } else if (IsAssignment) { 6803 // For an assignment operator, data members must not be of reference type. 6804 if (FieldType->isReferenceType()) { 6805 if (Diagnose) 6806 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6807 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6808 return true; 6809 } 6810 if (!FieldRecord && FieldType.isConstQualified()) { 6811 // C++11 [class.copy]p23: 6812 // -- a non-static data member of const non-class type (or array thereof) 6813 if (Diagnose) 6814 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6815 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 6816 return true; 6817 } 6818 } 6819 6820 if (FieldRecord) { 6821 // Some additional restrictions exist on the variant members. 6822 if (!inUnion() && FieldRecord->isUnion() && 6823 FieldRecord->isAnonymousStructOrUnion()) { 6824 bool AllVariantFieldsAreConst = true; 6825 6826 // FIXME: Handle anonymous unions declared within anonymous unions. 6827 for (auto *UI : FieldRecord->fields()) { 6828 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6829 6830 if (!UnionFieldType.isConstQualified()) 6831 AllVariantFieldsAreConst = false; 6832 6833 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6834 if (UnionFieldRecord && 6835 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6836 UnionFieldType.getCVRQualifiers())) 6837 return true; 6838 } 6839 6840 // At least one member in each anonymous union must be non-const 6841 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6842 !FieldRecord->field_empty()) { 6843 if (Diagnose) 6844 S.Diag(FieldRecord->getLocation(), 6845 diag::note_deleted_default_ctor_all_const) 6846 << !!ICI << MD->getParent() << /*anonymous union*/1; 6847 return true; 6848 } 6849 6850 // Don't check the implicit member of the anonymous union type. 6851 // This is technically non-conformant, but sanity demands it. 6852 return false; 6853 } 6854 6855 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6856 FieldType.getCVRQualifiers())) 6857 return true; 6858 } 6859 6860 return false; 6861 } 6862 6863 /// C++11 [class.ctor] p5: 6864 /// A defaulted default constructor for a class X is defined as deleted if 6865 /// X is a union and all of its variant members are of const-qualified type. 6866 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6867 // This is a silly definition, because it gives an empty union a deleted 6868 // default constructor. Don't do that. 6869 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 6870 bool AnyFields = false; 6871 for (auto *F : MD->getParent()->fields()) 6872 if ((AnyFields = !F->isUnnamedBitfield())) 6873 break; 6874 if (!AnyFields) 6875 return false; 6876 if (Diagnose) 6877 S.Diag(MD->getParent()->getLocation(), 6878 diag::note_deleted_default_ctor_all_const) 6879 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6880 return true; 6881 } 6882 return false; 6883 } 6884 6885 /// Determine whether a defaulted special member function should be defined as 6886 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6887 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6888 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6889 InheritedConstructorInfo *ICI, 6890 bool Diagnose) { 6891 if (MD->isInvalidDecl()) 6892 return false; 6893 CXXRecordDecl *RD = MD->getParent(); 6894 assert(!RD->isDependentType() && "do deletion after instantiation"); 6895 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6896 return false; 6897 6898 // C++11 [expr.lambda.prim]p19: 6899 // The closure type associated with a lambda-expression has a 6900 // deleted (8.4.3) default constructor and a deleted copy 6901 // assignment operator. 6902 if (RD->isLambda() && 6903 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6904 if (Diagnose) 6905 Diag(RD->getLocation(), diag::note_lambda_decl); 6906 return true; 6907 } 6908 6909 // For an anonymous struct or union, the copy and assignment special members 6910 // will never be used, so skip the check. For an anonymous union declared at 6911 // namespace scope, the constructor and destructor are used. 6912 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6913 RD->isAnonymousStructOrUnion()) 6914 return false; 6915 6916 // C++11 [class.copy]p7, p18: 6917 // If the class definition declares a move constructor or move assignment 6918 // operator, an implicitly declared copy constructor or copy assignment 6919 // operator is defined as deleted. 6920 if (MD->isImplicit() && 6921 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6922 CXXMethodDecl *UserDeclaredMove = nullptr; 6923 6924 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 6925 // deletion of the corresponding copy operation, not both copy operations. 6926 // MSVC 2015 has adopted the standards conforming behavior. 6927 bool DeletesOnlyMatchingCopy = 6928 getLangOpts().MSVCCompat && 6929 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 6930 6931 if (RD->hasUserDeclaredMoveConstructor() && 6932 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 6933 if (!Diagnose) return true; 6934 6935 // Find any user-declared move constructor. 6936 for (auto *I : RD->ctors()) { 6937 if (I->isMoveConstructor()) { 6938 UserDeclaredMove = I; 6939 break; 6940 } 6941 } 6942 assert(UserDeclaredMove); 6943 } else if (RD->hasUserDeclaredMoveAssignment() && 6944 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 6945 if (!Diagnose) return true; 6946 6947 // Find any user-declared move assignment operator. 6948 for (auto *I : RD->methods()) { 6949 if (I->isMoveAssignmentOperator()) { 6950 UserDeclaredMove = I; 6951 break; 6952 } 6953 } 6954 assert(UserDeclaredMove); 6955 } 6956 6957 if (UserDeclaredMove) { 6958 Diag(UserDeclaredMove->getLocation(), 6959 diag::note_deleted_copy_user_declared_move) 6960 << (CSM == CXXCopyAssignment) << RD 6961 << UserDeclaredMove->isMoveAssignmentOperator(); 6962 return true; 6963 } 6964 } 6965 6966 // Do access control from the special member function 6967 ContextRAII MethodContext(*this, MD); 6968 6969 // C++11 [class.dtor]p5: 6970 // -- for a virtual destructor, lookup of the non-array deallocation function 6971 // results in an ambiguity or in a function that is deleted or inaccessible 6972 if (CSM == CXXDestructor && MD->isVirtual()) { 6973 FunctionDecl *OperatorDelete = nullptr; 6974 DeclarationName Name = 6975 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6976 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 6977 OperatorDelete, /*Diagnose*/false)) { 6978 if (Diagnose) 6979 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 6980 return true; 6981 } 6982 } 6983 6984 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 6985 6986 // Per DR1611, do not consider virtual bases of constructors of abstract 6987 // classes, since we are not going to construct them. 6988 // Per DR1658, do not consider virtual bases of destructors of abstract 6989 // classes either. 6990 // Per DR2180, for assignment operators we only assign (and thus only 6991 // consider) direct bases. 6992 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 6993 : SMI.VisitPotentiallyConstructedBases)) 6994 return true; 6995 6996 if (SMI.shouldDeleteForAllConstMembers()) 6997 return true; 6998 6999 if (getLangOpts().CUDA) { 7000 // We should delete the special member in CUDA mode if target inference 7001 // failed. 7002 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 7003 Diagnose); 7004 } 7005 7006 return false; 7007 } 7008 7009 /// Perform lookup for a special member of the specified kind, and determine 7010 /// whether it is trivial. If the triviality can be determined without the 7011 /// lookup, skip it. This is intended for use when determining whether a 7012 /// special member of a containing object is trivial, and thus does not ever 7013 /// perform overload resolution for default constructors. 7014 /// 7015 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7016 /// member that was most likely to be intended to be trivial, if any. 7017 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7018 Sema::CXXSpecialMember CSM, unsigned Quals, 7019 bool ConstRHS, CXXMethodDecl **Selected) { 7020 if (Selected) 7021 *Selected = nullptr; 7022 7023 switch (CSM) { 7024 case Sema::CXXInvalid: 7025 llvm_unreachable("not a special member"); 7026 7027 case Sema::CXXDefaultConstructor: 7028 // C++11 [class.ctor]p5: 7029 // A default constructor is trivial if: 7030 // - all the [direct subobjects] have trivial default constructors 7031 // 7032 // Note, no overload resolution is performed in this case. 7033 if (RD->hasTrivialDefaultConstructor()) 7034 return true; 7035 7036 if (Selected) { 7037 // If there's a default constructor which could have been trivial, dig it 7038 // out. Otherwise, if there's any user-provided default constructor, point 7039 // to that as an example of why there's not a trivial one. 7040 CXXConstructorDecl *DefCtor = nullptr; 7041 if (RD->needsImplicitDefaultConstructor()) 7042 S.DeclareImplicitDefaultConstructor(RD); 7043 for (auto *CI : RD->ctors()) { 7044 if (!CI->isDefaultConstructor()) 7045 continue; 7046 DefCtor = CI; 7047 if (!DefCtor->isUserProvided()) 7048 break; 7049 } 7050 7051 *Selected = DefCtor; 7052 } 7053 7054 return false; 7055 7056 case Sema::CXXDestructor: 7057 // C++11 [class.dtor]p5: 7058 // A destructor is trivial if: 7059 // - all the direct [subobjects] have trivial destructors 7060 if (RD->hasTrivialDestructor()) 7061 return true; 7062 7063 if (Selected) { 7064 if (RD->needsImplicitDestructor()) 7065 S.DeclareImplicitDestructor(RD); 7066 *Selected = RD->getDestructor(); 7067 } 7068 7069 return false; 7070 7071 case Sema::CXXCopyConstructor: 7072 // C++11 [class.copy]p12: 7073 // A copy constructor is trivial if: 7074 // - the constructor selected to copy each direct [subobject] is trivial 7075 if (RD->hasTrivialCopyConstructor()) { 7076 if (Quals == Qualifiers::Const) 7077 // We must either select the trivial copy constructor or reach an 7078 // ambiguity; no need to actually perform overload resolution. 7079 return true; 7080 } else if (!Selected) { 7081 return false; 7082 } 7083 // In C++98, we are not supposed to perform overload resolution here, but we 7084 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7085 // cases like B as having a non-trivial copy constructor: 7086 // struct A { template<typename T> A(T&); }; 7087 // struct B { mutable A a; }; 7088 goto NeedOverloadResolution; 7089 7090 case Sema::CXXCopyAssignment: 7091 // C++11 [class.copy]p25: 7092 // A copy assignment operator is trivial if: 7093 // - the assignment operator selected to copy each direct [subobject] is 7094 // trivial 7095 if (RD->hasTrivialCopyAssignment()) { 7096 if (Quals == Qualifiers::Const) 7097 return true; 7098 } else if (!Selected) { 7099 return false; 7100 } 7101 // In C++98, we are not supposed to perform overload resolution here, but we 7102 // treat that as a language defect. 7103 goto NeedOverloadResolution; 7104 7105 case Sema::CXXMoveConstructor: 7106 case Sema::CXXMoveAssignment: 7107 NeedOverloadResolution: 7108 Sema::SpecialMemberOverloadResult SMOR = 7109 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7110 7111 // The standard doesn't describe how to behave if the lookup is ambiguous. 7112 // We treat it as not making the member non-trivial, just like the standard 7113 // mandates for the default constructor. This should rarely matter, because 7114 // the member will also be deleted. 7115 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7116 return true; 7117 7118 if (!SMOR.getMethod()) { 7119 assert(SMOR.getKind() == 7120 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7121 return false; 7122 } 7123 7124 // We deliberately don't check if we found a deleted special member. We're 7125 // not supposed to! 7126 if (Selected) 7127 *Selected = SMOR.getMethod(); 7128 return SMOR.getMethod()->isTrivial(); 7129 } 7130 7131 llvm_unreachable("unknown special method kind"); 7132 } 7133 7134 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7135 for (auto *CI : RD->ctors()) 7136 if (!CI->isImplicit()) 7137 return CI; 7138 7139 // Look for constructor templates. 7140 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7141 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7142 if (CXXConstructorDecl *CD = 7143 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7144 return CD; 7145 } 7146 7147 return nullptr; 7148 } 7149 7150 /// The kind of subobject we are checking for triviality. The values of this 7151 /// enumeration are used in diagnostics. 7152 enum TrivialSubobjectKind { 7153 /// The subobject is a base class. 7154 TSK_BaseClass, 7155 /// The subobject is a non-static data member. 7156 TSK_Field, 7157 /// The object is actually the complete object. 7158 TSK_CompleteObject 7159 }; 7160 7161 /// Check whether the special member selected for a given type would be trivial. 7162 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7163 QualType SubType, bool ConstRHS, 7164 Sema::CXXSpecialMember CSM, 7165 TrivialSubobjectKind Kind, 7166 bool Diagnose) { 7167 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7168 if (!SubRD) 7169 return true; 7170 7171 CXXMethodDecl *Selected; 7172 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7173 ConstRHS, Diagnose ? &Selected : nullptr)) 7174 return true; 7175 7176 if (Diagnose) { 7177 if (ConstRHS) 7178 SubType.addConst(); 7179 7180 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7181 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7182 << Kind << SubType.getUnqualifiedType(); 7183 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7184 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7185 } else if (!Selected) 7186 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7187 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7188 else if (Selected->isUserProvided()) { 7189 if (Kind == TSK_CompleteObject) 7190 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7191 << Kind << SubType.getUnqualifiedType() << CSM; 7192 else { 7193 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7194 << Kind << SubType.getUnqualifiedType() << CSM; 7195 S.Diag(Selected->getLocation(), diag::note_declared_at); 7196 } 7197 } else { 7198 if (Kind != TSK_CompleteObject) 7199 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7200 << Kind << SubType.getUnqualifiedType() << CSM; 7201 7202 // Explain why the defaulted or deleted special member isn't trivial. 7203 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 7204 } 7205 } 7206 7207 return false; 7208 } 7209 7210 /// Check whether the members of a class type allow a special member to be 7211 /// trivial. 7212 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7213 Sema::CXXSpecialMember CSM, 7214 bool ConstArg, bool Diagnose) { 7215 for (const auto *FI : RD->fields()) { 7216 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7217 continue; 7218 7219 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7220 7221 // Pretend anonymous struct or union members are members of this class. 7222 if (FI->isAnonymousStructOrUnion()) { 7223 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7224 CSM, ConstArg, Diagnose)) 7225 return false; 7226 continue; 7227 } 7228 7229 // C++11 [class.ctor]p5: 7230 // A default constructor is trivial if [...] 7231 // -- no non-static data member of its class has a 7232 // brace-or-equal-initializer 7233 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7234 if (Diagnose) 7235 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7236 return false; 7237 } 7238 7239 // Objective C ARC 4.3.5: 7240 // [...] nontrivally ownership-qualified types are [...] not trivially 7241 // default constructible, copy constructible, move constructible, copy 7242 // assignable, move assignable, or destructible [...] 7243 if (FieldType.hasNonTrivialObjCLifetime()) { 7244 if (Diagnose) 7245 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7246 << RD << FieldType.getObjCLifetime(); 7247 return false; 7248 } 7249 7250 bool ConstRHS = ConstArg && !FI->isMutable(); 7251 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7252 CSM, TSK_Field, Diagnose)) 7253 return false; 7254 } 7255 7256 return true; 7257 } 7258 7259 /// Diagnose why the specified class does not have a trivial special member of 7260 /// the given kind. 7261 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7262 QualType Ty = Context.getRecordType(RD); 7263 7264 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7265 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7266 TSK_CompleteObject, /*Diagnose*/true); 7267 } 7268 7269 /// Determine whether a defaulted or deleted special member function is trivial, 7270 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7271 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7272 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7273 bool Diagnose) { 7274 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7275 7276 CXXRecordDecl *RD = MD->getParent(); 7277 7278 bool ConstArg = false; 7279 7280 // C++11 [class.copy]p12, p25: [DR1593] 7281 // A [special member] is trivial if [...] its parameter-type-list is 7282 // equivalent to the parameter-type-list of an implicit declaration [...] 7283 switch (CSM) { 7284 case CXXDefaultConstructor: 7285 case CXXDestructor: 7286 // Trivial default constructors and destructors cannot have parameters. 7287 break; 7288 7289 case CXXCopyConstructor: 7290 case CXXCopyAssignment: { 7291 // Trivial copy operations always have const, non-volatile parameter types. 7292 ConstArg = true; 7293 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7294 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7295 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7296 if (Diagnose) 7297 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7298 << Param0->getSourceRange() << Param0->getType() 7299 << Context.getLValueReferenceType( 7300 Context.getRecordType(RD).withConst()); 7301 return false; 7302 } 7303 break; 7304 } 7305 7306 case CXXMoveConstructor: 7307 case CXXMoveAssignment: { 7308 // Trivial move operations always have non-cv-qualified parameters. 7309 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7310 const RValueReferenceType *RT = 7311 Param0->getType()->getAs<RValueReferenceType>(); 7312 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7313 if (Diagnose) 7314 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7315 << Param0->getSourceRange() << Param0->getType() 7316 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7317 return false; 7318 } 7319 break; 7320 } 7321 7322 case CXXInvalid: 7323 llvm_unreachable("not a special member"); 7324 } 7325 7326 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7327 if (Diagnose) 7328 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7329 diag::note_nontrivial_default_arg) 7330 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7331 return false; 7332 } 7333 if (MD->isVariadic()) { 7334 if (Diagnose) 7335 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7336 return false; 7337 } 7338 7339 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7340 // A copy/move [constructor or assignment operator] is trivial if 7341 // -- the [member] selected to copy/move each direct base class subobject 7342 // is trivial 7343 // 7344 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7345 // A [default constructor or destructor] is trivial if 7346 // -- all the direct base classes have trivial [default constructors or 7347 // destructors] 7348 for (const auto &BI : RD->bases()) 7349 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7350 ConstArg, CSM, TSK_BaseClass, Diagnose)) 7351 return false; 7352 7353 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7354 // A copy/move [constructor or assignment operator] for a class X is 7355 // trivial if 7356 // -- for each non-static data member of X that is of class type (or array 7357 // thereof), the constructor selected to copy/move that member is 7358 // trivial 7359 // 7360 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7361 // A [default constructor or destructor] is trivial if 7362 // -- for all of the non-static data members of its class that are of class 7363 // type (or array thereof), each such class has a trivial [default 7364 // constructor or destructor] 7365 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 7366 return false; 7367 7368 // C++11 [class.dtor]p5: 7369 // A destructor is trivial if [...] 7370 // -- the destructor is not virtual 7371 if (CSM == CXXDestructor && MD->isVirtual()) { 7372 if (Diagnose) 7373 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7374 return false; 7375 } 7376 7377 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7378 // A [special member] for class X is trivial if [...] 7379 // -- class X has no virtual functions and no virtual base classes 7380 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7381 if (!Diagnose) 7382 return false; 7383 7384 if (RD->getNumVBases()) { 7385 // Check for virtual bases. We already know that the corresponding 7386 // member in all bases is trivial, so vbases must all be direct. 7387 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7388 assert(BS.isVirtual()); 7389 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7390 return false; 7391 } 7392 7393 // Must have a virtual method. 7394 for (const auto *MI : RD->methods()) { 7395 if (MI->isVirtual()) { 7396 SourceLocation MLoc = MI->getLocStart(); 7397 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7398 return false; 7399 } 7400 } 7401 7402 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7403 } 7404 7405 // Looks like it's trivial! 7406 return true; 7407 } 7408 7409 namespace { 7410 struct FindHiddenVirtualMethod { 7411 Sema *S; 7412 CXXMethodDecl *Method; 7413 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7414 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7415 7416 private: 7417 /// Check whether any most overriden method from MD in Methods 7418 static bool CheckMostOverridenMethods( 7419 const CXXMethodDecl *MD, 7420 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7421 if (MD->size_overridden_methods() == 0) 7422 return Methods.count(MD->getCanonicalDecl()); 7423 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7424 E = MD->end_overridden_methods(); 7425 I != E; ++I) 7426 if (CheckMostOverridenMethods(*I, Methods)) 7427 return true; 7428 return false; 7429 } 7430 7431 public: 7432 /// Member lookup function that determines whether a given C++ 7433 /// method overloads virtual methods in a base class without overriding any, 7434 /// to be used with CXXRecordDecl::lookupInBases(). 7435 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7436 RecordDecl *BaseRecord = 7437 Specifier->getType()->getAs<RecordType>()->getDecl(); 7438 7439 DeclarationName Name = Method->getDeclName(); 7440 assert(Name.getNameKind() == DeclarationName::Identifier); 7441 7442 bool foundSameNameMethod = false; 7443 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7444 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7445 Path.Decls = Path.Decls.slice(1)) { 7446 NamedDecl *D = Path.Decls.front(); 7447 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7448 MD = MD->getCanonicalDecl(); 7449 foundSameNameMethod = true; 7450 // Interested only in hidden virtual methods. 7451 if (!MD->isVirtual()) 7452 continue; 7453 // If the method we are checking overrides a method from its base 7454 // don't warn about the other overloaded methods. Clang deviates from 7455 // GCC by only diagnosing overloads of inherited virtual functions that 7456 // do not override any other virtual functions in the base. GCC's 7457 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7458 // function from a base class. These cases may be better served by a 7459 // warning (not specific to virtual functions) on call sites when the 7460 // call would select a different function from the base class, were it 7461 // visible. 7462 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7463 if (!S->IsOverload(Method, MD, false)) 7464 return true; 7465 // Collect the overload only if its hidden. 7466 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7467 overloadedMethods.push_back(MD); 7468 } 7469 } 7470 7471 if (foundSameNameMethod) 7472 OverloadedMethods.append(overloadedMethods.begin(), 7473 overloadedMethods.end()); 7474 return foundSameNameMethod; 7475 } 7476 }; 7477 } // end anonymous namespace 7478 7479 /// \brief Add the most overriden methods from MD to Methods 7480 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7481 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7482 if (MD->size_overridden_methods() == 0) 7483 Methods.insert(MD->getCanonicalDecl()); 7484 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7485 E = MD->end_overridden_methods(); 7486 I != E; ++I) 7487 AddMostOverridenMethods(*I, Methods); 7488 } 7489 7490 /// \brief Check if a method overloads virtual methods in a base class without 7491 /// overriding any. 7492 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7493 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7494 if (!MD->getDeclName().isIdentifier()) 7495 return; 7496 7497 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7498 /*bool RecordPaths=*/false, 7499 /*bool DetectVirtual=*/false); 7500 FindHiddenVirtualMethod FHVM; 7501 FHVM.Method = MD; 7502 FHVM.S = this; 7503 7504 // Keep the base methods that were overriden or introduced in the subclass 7505 // by 'using' in a set. A base method not in this set is hidden. 7506 CXXRecordDecl *DC = MD->getParent(); 7507 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7508 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7509 NamedDecl *ND = *I; 7510 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7511 ND = shad->getTargetDecl(); 7512 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7513 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7514 } 7515 7516 if (DC->lookupInBases(FHVM, Paths)) 7517 OverloadedMethods = FHVM.OverloadedMethods; 7518 } 7519 7520 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7521 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7522 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7523 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7524 PartialDiagnostic PD = PDiag( 7525 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7526 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7527 Diag(overloadedMD->getLocation(), PD); 7528 } 7529 } 7530 7531 /// \brief Diagnose methods which overload virtual methods in a base class 7532 /// without overriding any. 7533 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7534 if (MD->isInvalidDecl()) 7535 return; 7536 7537 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7538 return; 7539 7540 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7541 FindHiddenVirtualMethods(MD, OverloadedMethods); 7542 if (!OverloadedMethods.empty()) { 7543 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7544 << MD << (OverloadedMethods.size() > 1); 7545 7546 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7547 } 7548 } 7549 7550 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7551 Decl *TagDecl, 7552 SourceLocation LBrac, 7553 SourceLocation RBrac, 7554 AttributeList *AttrList) { 7555 if (!TagDecl) 7556 return; 7557 7558 AdjustDeclIfTemplate(TagDecl); 7559 7560 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7561 if (l->getKind() != AttributeList::AT_Visibility) 7562 continue; 7563 l->setInvalid(); 7564 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7565 l->getName(); 7566 } 7567 7568 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7569 // strict aliasing violation! 7570 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7571 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7572 7573 CheckCompletedCXXClass(dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 7574 } 7575 7576 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7577 /// special functions, such as the default constructor, copy 7578 /// constructor, or destructor, to the given C++ class (C++ 7579 /// [special]p1). This routine can only be executed just before the 7580 /// definition of the class is complete. 7581 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7582 if (ClassDecl->needsImplicitDefaultConstructor()) { 7583 ++ASTContext::NumImplicitDefaultConstructors; 7584 7585 if (ClassDecl->hasInheritedConstructor()) 7586 DeclareImplicitDefaultConstructor(ClassDecl); 7587 } 7588 7589 if (ClassDecl->needsImplicitCopyConstructor()) { 7590 ++ASTContext::NumImplicitCopyConstructors; 7591 7592 // If the properties or semantics of the copy constructor couldn't be 7593 // determined while the class was being declared, force a declaration 7594 // of it now. 7595 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7596 ClassDecl->hasInheritedConstructor()) 7597 DeclareImplicitCopyConstructor(ClassDecl); 7598 // For the MS ABI we need to know whether the copy ctor is deleted. A 7599 // prerequisite for deleting the implicit copy ctor is that the class has a 7600 // move ctor or move assignment that is either user-declared or whose 7601 // semantics are inherited from a subobject. FIXME: We should provide a more 7602 // direct way for CodeGen to ask whether the constructor was deleted. 7603 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7604 (ClassDecl->hasUserDeclaredMoveConstructor() || 7605 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7606 ClassDecl->hasUserDeclaredMoveAssignment() || 7607 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7608 DeclareImplicitCopyConstructor(ClassDecl); 7609 } 7610 7611 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7612 ++ASTContext::NumImplicitMoveConstructors; 7613 7614 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7615 ClassDecl->hasInheritedConstructor()) 7616 DeclareImplicitMoveConstructor(ClassDecl); 7617 } 7618 7619 if (ClassDecl->needsImplicitCopyAssignment()) { 7620 ++ASTContext::NumImplicitCopyAssignmentOperators; 7621 7622 // If we have a dynamic class, then the copy assignment operator may be 7623 // virtual, so we have to declare it immediately. This ensures that, e.g., 7624 // it shows up in the right place in the vtable and that we diagnose 7625 // problems with the implicit exception specification. 7626 if (ClassDecl->isDynamicClass() || 7627 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7628 ClassDecl->hasInheritedAssignment()) 7629 DeclareImplicitCopyAssignment(ClassDecl); 7630 } 7631 7632 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7633 ++ASTContext::NumImplicitMoveAssignmentOperators; 7634 7635 // Likewise for the move assignment operator. 7636 if (ClassDecl->isDynamicClass() || 7637 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7638 ClassDecl->hasInheritedAssignment()) 7639 DeclareImplicitMoveAssignment(ClassDecl); 7640 } 7641 7642 if (ClassDecl->needsImplicitDestructor()) { 7643 ++ASTContext::NumImplicitDestructors; 7644 7645 // If we have a dynamic class, then the destructor may be virtual, so we 7646 // have to declare the destructor immediately. This ensures that, e.g., it 7647 // shows up in the right place in the vtable and that we diagnose problems 7648 // with the implicit exception specification. 7649 if (ClassDecl->isDynamicClass() || 7650 ClassDecl->needsOverloadResolutionForDestructor()) 7651 DeclareImplicitDestructor(ClassDecl); 7652 } 7653 } 7654 7655 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7656 if (!D) 7657 return 0; 7658 7659 // The order of template parameters is not important here. All names 7660 // get added to the same scope. 7661 SmallVector<TemplateParameterList *, 4> ParameterLists; 7662 7663 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7664 D = TD->getTemplatedDecl(); 7665 7666 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7667 ParameterLists.push_back(PSD->getTemplateParameters()); 7668 7669 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7670 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7671 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7672 7673 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7674 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7675 ParameterLists.push_back(FTD->getTemplateParameters()); 7676 } 7677 } 7678 7679 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7680 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7681 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7682 7683 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7684 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7685 ParameterLists.push_back(CTD->getTemplateParameters()); 7686 } 7687 } 7688 7689 unsigned Count = 0; 7690 for (TemplateParameterList *Params : ParameterLists) { 7691 if (Params->size() > 0) 7692 // Ignore explicit specializations; they don't contribute to the template 7693 // depth. 7694 ++Count; 7695 for (NamedDecl *Param : *Params) { 7696 if (Param->getDeclName()) { 7697 S->AddDecl(Param); 7698 IdResolver.AddDecl(Param); 7699 } 7700 } 7701 } 7702 7703 return Count; 7704 } 7705 7706 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7707 if (!RecordD) return; 7708 AdjustDeclIfTemplate(RecordD); 7709 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7710 PushDeclContext(S, Record); 7711 } 7712 7713 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7714 if (!RecordD) return; 7715 PopDeclContext(); 7716 } 7717 7718 /// This is used to implement the constant expression evaluation part of the 7719 /// attribute enable_if extension. There is nothing in standard C++ which would 7720 /// require reentering parameters. 7721 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7722 if (!Param) 7723 return; 7724 7725 S->AddDecl(Param); 7726 if (Param->getDeclName()) 7727 IdResolver.AddDecl(Param); 7728 } 7729 7730 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7731 /// parsing a top-level (non-nested) C++ class, and we are now 7732 /// parsing those parts of the given Method declaration that could 7733 /// not be parsed earlier (C++ [class.mem]p2), such as default 7734 /// arguments. This action should enter the scope of the given 7735 /// Method declaration as if we had just parsed the qualified method 7736 /// name. However, it should not bring the parameters into scope; 7737 /// that will be performed by ActOnDelayedCXXMethodParameter. 7738 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7739 } 7740 7741 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7742 /// C++ method declaration. We're (re-)introducing the given 7743 /// function parameter into scope for use in parsing later parts of 7744 /// the method declaration. For example, we could see an 7745 /// ActOnParamDefaultArgument event for this parameter. 7746 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7747 if (!ParamD) 7748 return; 7749 7750 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7751 7752 // If this parameter has an unparsed default argument, clear it out 7753 // to make way for the parsed default argument. 7754 if (Param->hasUnparsedDefaultArg()) 7755 Param->setDefaultArg(nullptr); 7756 7757 S->AddDecl(Param); 7758 if (Param->getDeclName()) 7759 IdResolver.AddDecl(Param); 7760 } 7761 7762 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7763 /// processing the delayed method declaration for Method. The method 7764 /// declaration is now considered finished. There may be a separate 7765 /// ActOnStartOfFunctionDef action later (not necessarily 7766 /// immediately!) for this method, if it was also defined inside the 7767 /// class body. 7768 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7769 if (!MethodD) 7770 return; 7771 7772 AdjustDeclIfTemplate(MethodD); 7773 7774 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7775 7776 // Now that we have our default arguments, check the constructor 7777 // again. It could produce additional diagnostics or affect whether 7778 // the class has implicitly-declared destructors, among other 7779 // things. 7780 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7781 CheckConstructor(Constructor); 7782 7783 // Check the default arguments, which we may have added. 7784 if (!Method->isInvalidDecl()) 7785 CheckCXXDefaultArguments(Method); 7786 } 7787 7788 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7789 /// the well-formedness of the constructor declarator @p D with type @p 7790 /// R. If there are any errors in the declarator, this routine will 7791 /// emit diagnostics and set the invalid bit to true. In any case, the type 7792 /// will be updated to reflect a well-formed type for the constructor and 7793 /// returned. 7794 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7795 StorageClass &SC) { 7796 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7797 7798 // C++ [class.ctor]p3: 7799 // A constructor shall not be virtual (10.3) or static (9.4). A 7800 // constructor can be invoked for a const, volatile or const 7801 // volatile object. A constructor shall not be declared const, 7802 // volatile, or const volatile (9.3.2). 7803 if (isVirtual) { 7804 if (!D.isInvalidType()) 7805 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7806 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7807 << SourceRange(D.getIdentifierLoc()); 7808 D.setInvalidType(); 7809 } 7810 if (SC == SC_Static) { 7811 if (!D.isInvalidType()) 7812 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7814 << SourceRange(D.getIdentifierLoc()); 7815 D.setInvalidType(); 7816 SC = SC_None; 7817 } 7818 7819 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7820 diagnoseIgnoredQualifiers( 7821 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7822 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7823 D.getDeclSpec().getRestrictSpecLoc(), 7824 D.getDeclSpec().getAtomicSpecLoc()); 7825 D.setInvalidType(); 7826 } 7827 7828 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7829 if (FTI.TypeQuals != 0) { 7830 if (FTI.TypeQuals & Qualifiers::Const) 7831 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7832 << "const" << SourceRange(D.getIdentifierLoc()); 7833 if (FTI.TypeQuals & Qualifiers::Volatile) 7834 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7835 << "volatile" << SourceRange(D.getIdentifierLoc()); 7836 if (FTI.TypeQuals & Qualifiers::Restrict) 7837 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7838 << "restrict" << SourceRange(D.getIdentifierLoc()); 7839 D.setInvalidType(); 7840 } 7841 7842 // C++0x [class.ctor]p4: 7843 // A constructor shall not be declared with a ref-qualifier. 7844 if (FTI.hasRefQualifier()) { 7845 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7846 << FTI.RefQualifierIsLValueRef 7847 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7848 D.setInvalidType(); 7849 } 7850 7851 // Rebuild the function type "R" without any type qualifiers (in 7852 // case any of the errors above fired) and with "void" as the 7853 // return type, since constructors don't have return types. 7854 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7855 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7856 return R; 7857 7858 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7859 EPI.TypeQuals = 0; 7860 EPI.RefQualifier = RQ_None; 7861 7862 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7863 } 7864 7865 /// CheckConstructor - Checks a fully-formed constructor for 7866 /// well-formedness, issuing any diagnostics required. Returns true if 7867 /// the constructor declarator is invalid. 7868 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7869 CXXRecordDecl *ClassDecl 7870 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7871 if (!ClassDecl) 7872 return Constructor->setInvalidDecl(); 7873 7874 // C++ [class.copy]p3: 7875 // A declaration of a constructor for a class X is ill-formed if 7876 // its first parameter is of type (optionally cv-qualified) X and 7877 // either there are no other parameters or else all other 7878 // parameters have default arguments. 7879 if (!Constructor->isInvalidDecl() && 7880 ((Constructor->getNumParams() == 1) || 7881 (Constructor->getNumParams() > 1 && 7882 Constructor->getParamDecl(1)->hasDefaultArg())) && 7883 Constructor->getTemplateSpecializationKind() 7884 != TSK_ImplicitInstantiation) { 7885 QualType ParamType = Constructor->getParamDecl(0)->getType(); 7886 QualType ClassTy = Context.getTagDeclType(ClassDecl); 7887 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 7888 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 7889 const char *ConstRef 7890 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 7891 : " const &"; 7892 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 7893 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 7894 7895 // FIXME: Rather that making the constructor invalid, we should endeavor 7896 // to fix the type. 7897 Constructor->setInvalidDecl(); 7898 } 7899 } 7900 } 7901 7902 /// CheckDestructor - Checks a fully-formed destructor definition for 7903 /// well-formedness, issuing any diagnostics required. Returns true 7904 /// on error. 7905 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 7906 CXXRecordDecl *RD = Destructor->getParent(); 7907 7908 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 7909 SourceLocation Loc; 7910 7911 if (!Destructor->isImplicit()) 7912 Loc = Destructor->getLocation(); 7913 else 7914 Loc = RD->getLocation(); 7915 7916 // If we have a virtual destructor, look up the deallocation function 7917 if (FunctionDecl *OperatorDelete = 7918 FindDeallocationFunctionForDestructor(Loc, RD)) { 7919 Expr *ThisArg = nullptr; 7920 7921 // If the notional 'delete this' expression requires a non-trivial 7922 // conversion from 'this' to the type of a destroying operator delete's 7923 // first parameter, perform that conversion now. 7924 if (OperatorDelete->isDestroyingOperatorDelete()) { 7925 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 7926 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 7927 // C++ [class.dtor]p13: 7928 // ... as if for the expression 'delete this' appearing in a 7929 // non-virtual destructor of the destructor's class. 7930 ContextRAII SwitchContext(*this, Destructor); 7931 ExprResult This = 7932 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 7933 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 7934 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 7935 if (This.isInvalid()) { 7936 // FIXME: Register this as a context note so that it comes out 7937 // in the right order. 7938 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 7939 return true; 7940 } 7941 ThisArg = This.get(); 7942 } 7943 } 7944 7945 MarkFunctionReferenced(Loc, OperatorDelete); 7946 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 7947 } 7948 } 7949 7950 return false; 7951 } 7952 7953 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 7954 /// the well-formednes of the destructor declarator @p D with type @p 7955 /// R. If there are any errors in the declarator, this routine will 7956 /// emit diagnostics and set the declarator to invalid. Even if this happens, 7957 /// will be updated to reflect a well-formed type for the destructor and 7958 /// returned. 7959 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 7960 StorageClass& SC) { 7961 // C++ [class.dtor]p1: 7962 // [...] A typedef-name that names a class is a class-name 7963 // (7.1.3); however, a typedef-name that names a class shall not 7964 // be used as the identifier in the declarator for a destructor 7965 // declaration. 7966 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 7967 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 7968 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7969 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 7970 else if (const TemplateSpecializationType *TST = 7971 DeclaratorType->getAs<TemplateSpecializationType>()) 7972 if (TST->isTypeAlias()) 7973 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7974 << DeclaratorType << 1; 7975 7976 // C++ [class.dtor]p2: 7977 // A destructor is used to destroy objects of its class type. A 7978 // destructor takes no parameters, and no return type can be 7979 // specified for it (not even void). The address of a destructor 7980 // shall not be taken. A destructor shall not be static. A 7981 // destructor can be invoked for a const, volatile or const 7982 // volatile object. A destructor shall not be declared const, 7983 // volatile or const volatile (9.3.2). 7984 if (SC == SC_Static) { 7985 if (!D.isInvalidType()) 7986 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 7987 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7988 << SourceRange(D.getIdentifierLoc()) 7989 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7990 7991 SC = SC_None; 7992 } 7993 if (!D.isInvalidType()) { 7994 // Destructors don't have return types, but the parser will 7995 // happily parse something like: 7996 // 7997 // class X { 7998 // float ~X(); 7999 // }; 8000 // 8001 // The return type will be eliminated later. 8002 if (D.getDeclSpec().hasTypeSpecifier()) 8003 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8004 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8005 << SourceRange(D.getIdentifierLoc()); 8006 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8007 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8008 SourceLocation(), 8009 D.getDeclSpec().getConstSpecLoc(), 8010 D.getDeclSpec().getVolatileSpecLoc(), 8011 D.getDeclSpec().getRestrictSpecLoc(), 8012 D.getDeclSpec().getAtomicSpecLoc()); 8013 D.setInvalidType(); 8014 } 8015 } 8016 8017 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8018 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 8019 if (FTI.TypeQuals & Qualifiers::Const) 8020 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8021 << "const" << SourceRange(D.getIdentifierLoc()); 8022 if (FTI.TypeQuals & Qualifiers::Volatile) 8023 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8024 << "volatile" << SourceRange(D.getIdentifierLoc()); 8025 if (FTI.TypeQuals & Qualifiers::Restrict) 8026 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8027 << "restrict" << SourceRange(D.getIdentifierLoc()); 8028 D.setInvalidType(); 8029 } 8030 8031 // C++0x [class.dtor]p2: 8032 // A destructor shall not be declared with a ref-qualifier. 8033 if (FTI.hasRefQualifier()) { 8034 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8035 << FTI.RefQualifierIsLValueRef 8036 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8037 D.setInvalidType(); 8038 } 8039 8040 // Make sure we don't have any parameters. 8041 if (FTIHasNonVoidParameters(FTI)) { 8042 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8043 8044 // Delete the parameters. 8045 FTI.freeParams(); 8046 D.setInvalidType(); 8047 } 8048 8049 // Make sure the destructor isn't variadic. 8050 if (FTI.isVariadic) { 8051 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8052 D.setInvalidType(); 8053 } 8054 8055 // Rebuild the function type "R" without any type qualifiers or 8056 // parameters (in case any of the errors above fired) and with 8057 // "void" as the return type, since destructors don't have return 8058 // types. 8059 if (!D.isInvalidType()) 8060 return R; 8061 8062 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8063 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8064 EPI.Variadic = false; 8065 EPI.TypeQuals = 0; 8066 EPI.RefQualifier = RQ_None; 8067 return Context.getFunctionType(Context.VoidTy, None, EPI); 8068 } 8069 8070 static void extendLeft(SourceRange &R, SourceRange Before) { 8071 if (Before.isInvalid()) 8072 return; 8073 R.setBegin(Before.getBegin()); 8074 if (R.getEnd().isInvalid()) 8075 R.setEnd(Before.getEnd()); 8076 } 8077 8078 static void extendRight(SourceRange &R, SourceRange After) { 8079 if (After.isInvalid()) 8080 return; 8081 if (R.getBegin().isInvalid()) 8082 R.setBegin(After.getBegin()); 8083 R.setEnd(After.getEnd()); 8084 } 8085 8086 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8087 /// well-formednes of the conversion function declarator @p D with 8088 /// type @p R. If there are any errors in the declarator, this routine 8089 /// will emit diagnostics and return true. Otherwise, it will return 8090 /// false. Either way, the type @p R will be updated to reflect a 8091 /// well-formed type for the conversion operator. 8092 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8093 StorageClass& SC) { 8094 // C++ [class.conv.fct]p1: 8095 // Neither parameter types nor return type can be specified. The 8096 // type of a conversion function (8.3.5) is "function taking no 8097 // parameter returning conversion-type-id." 8098 if (SC == SC_Static) { 8099 if (!D.isInvalidType()) 8100 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8101 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8102 << D.getName().getSourceRange(); 8103 D.setInvalidType(); 8104 SC = SC_None; 8105 } 8106 8107 TypeSourceInfo *ConvTSI = nullptr; 8108 QualType ConvType = 8109 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8110 8111 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 8112 // Conversion functions don't have return types, but the parser will 8113 // happily parse something like: 8114 // 8115 // class X { 8116 // float operator bool(); 8117 // }; 8118 // 8119 // The return type will be changed later anyway. 8120 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8121 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8122 << SourceRange(D.getIdentifierLoc()); 8123 D.setInvalidType(); 8124 } 8125 8126 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8127 8128 // Make sure we don't have any parameters. 8129 if (Proto->getNumParams() > 0) { 8130 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8131 8132 // Delete the parameters. 8133 D.getFunctionTypeInfo().freeParams(); 8134 D.setInvalidType(); 8135 } else if (Proto->isVariadic()) { 8136 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8137 D.setInvalidType(); 8138 } 8139 8140 // Diagnose "&operator bool()" and other such nonsense. This 8141 // is actually a gcc extension which we don't support. 8142 if (Proto->getReturnType() != ConvType) { 8143 bool NeedsTypedef = false; 8144 SourceRange Before, After; 8145 8146 // Walk the chunks and extract information on them for our diagnostic. 8147 bool PastFunctionChunk = false; 8148 for (auto &Chunk : D.type_objects()) { 8149 switch (Chunk.Kind) { 8150 case DeclaratorChunk::Function: 8151 if (!PastFunctionChunk) { 8152 if (Chunk.Fun.HasTrailingReturnType) { 8153 TypeSourceInfo *TRT = nullptr; 8154 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8155 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8156 } 8157 PastFunctionChunk = true; 8158 break; 8159 } 8160 // Fall through. 8161 case DeclaratorChunk::Array: 8162 NeedsTypedef = true; 8163 extendRight(After, Chunk.getSourceRange()); 8164 break; 8165 8166 case DeclaratorChunk::Pointer: 8167 case DeclaratorChunk::BlockPointer: 8168 case DeclaratorChunk::Reference: 8169 case DeclaratorChunk::MemberPointer: 8170 case DeclaratorChunk::Pipe: 8171 extendLeft(Before, Chunk.getSourceRange()); 8172 break; 8173 8174 case DeclaratorChunk::Paren: 8175 extendLeft(Before, Chunk.Loc); 8176 extendRight(After, Chunk.EndLoc); 8177 break; 8178 } 8179 } 8180 8181 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8182 After.isValid() ? After.getBegin() : 8183 D.getIdentifierLoc(); 8184 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8185 DB << Before << After; 8186 8187 if (!NeedsTypedef) { 8188 DB << /*don't need a typedef*/0; 8189 8190 // If we can provide a correct fix-it hint, do so. 8191 if (After.isInvalid() && ConvTSI) { 8192 SourceLocation InsertLoc = 8193 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8194 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8195 << FixItHint::CreateInsertionFromRange( 8196 InsertLoc, CharSourceRange::getTokenRange(Before)) 8197 << FixItHint::CreateRemoval(Before); 8198 } 8199 } else if (!Proto->getReturnType()->isDependentType()) { 8200 DB << /*typedef*/1 << Proto->getReturnType(); 8201 } else if (getLangOpts().CPlusPlus11) { 8202 DB << /*alias template*/2 << Proto->getReturnType(); 8203 } else { 8204 DB << /*might not be fixable*/3; 8205 } 8206 8207 // Recover by incorporating the other type chunks into the result type. 8208 // Note, this does *not* change the name of the function. This is compatible 8209 // with the GCC extension: 8210 // struct S { &operator int(); } s; 8211 // int &r = s.operator int(); // ok in GCC 8212 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8213 ConvType = Proto->getReturnType(); 8214 } 8215 8216 // C++ [class.conv.fct]p4: 8217 // The conversion-type-id shall not represent a function type nor 8218 // an array type. 8219 if (ConvType->isArrayType()) { 8220 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8221 ConvType = Context.getPointerType(ConvType); 8222 D.setInvalidType(); 8223 } else if (ConvType->isFunctionType()) { 8224 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8225 ConvType = Context.getPointerType(ConvType); 8226 D.setInvalidType(); 8227 } 8228 8229 // Rebuild the function type "R" without any parameters (in case any 8230 // of the errors above fired) and with the conversion type as the 8231 // return type. 8232 if (D.isInvalidType()) 8233 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8234 8235 // C++0x explicit conversion operators. 8236 if (D.getDeclSpec().isExplicitSpecified()) 8237 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8238 getLangOpts().CPlusPlus11 ? 8239 diag::warn_cxx98_compat_explicit_conversion_functions : 8240 diag::ext_explicit_conversion_functions) 8241 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 8242 } 8243 8244 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8245 /// the declaration of the given C++ conversion function. This routine 8246 /// is responsible for recording the conversion function in the C++ 8247 /// class, if possible. 8248 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8249 assert(Conversion && "Expected to receive a conversion function declaration"); 8250 8251 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8252 8253 // Make sure we aren't redeclaring the conversion function. 8254 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8255 8256 // C++ [class.conv.fct]p1: 8257 // [...] A conversion function is never used to convert a 8258 // (possibly cv-qualified) object to the (possibly cv-qualified) 8259 // same object type (or a reference to it), to a (possibly 8260 // cv-qualified) base class of that type (or a reference to it), 8261 // or to (possibly cv-qualified) void. 8262 // FIXME: Suppress this warning if the conversion function ends up being a 8263 // virtual function that overrides a virtual function in a base class. 8264 QualType ClassType 8265 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8266 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8267 ConvType = ConvTypeRef->getPointeeType(); 8268 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8269 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8270 /* Suppress diagnostics for instantiations. */; 8271 else if (ConvType->isRecordType()) { 8272 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8273 if (ConvType == ClassType) 8274 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8275 << ClassType; 8276 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8277 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8278 << ClassType << ConvType; 8279 } else if (ConvType->isVoidType()) { 8280 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8281 << ClassType << ConvType; 8282 } 8283 8284 if (FunctionTemplateDecl *ConversionTemplate 8285 = Conversion->getDescribedFunctionTemplate()) 8286 return ConversionTemplate; 8287 8288 return Conversion; 8289 } 8290 8291 namespace { 8292 /// Utility class to accumulate and print a diagnostic listing the invalid 8293 /// specifier(s) on a declaration. 8294 struct BadSpecifierDiagnoser { 8295 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8296 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8297 ~BadSpecifierDiagnoser() { 8298 Diagnostic << Specifiers; 8299 } 8300 8301 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8302 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8303 } 8304 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8305 return check(SpecLoc, 8306 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8307 } 8308 void check(SourceLocation SpecLoc, const char *Spec) { 8309 if (SpecLoc.isInvalid()) return; 8310 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8311 if (!Specifiers.empty()) Specifiers += " "; 8312 Specifiers += Spec; 8313 } 8314 8315 Sema &S; 8316 Sema::SemaDiagnosticBuilder Diagnostic; 8317 std::string Specifiers; 8318 }; 8319 } 8320 8321 /// Check the validity of a declarator that we parsed for a deduction-guide. 8322 /// These aren't actually declarators in the grammar, so we need to check that 8323 /// the user didn't specify any pieces that are not part of the deduction-guide 8324 /// grammar. 8325 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8326 StorageClass &SC) { 8327 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8328 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8329 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8330 8331 // C++ [temp.deduct.guide]p3: 8332 // A deduction-gide shall be declared in the same scope as the 8333 // corresponding class template. 8334 if (!CurContext->getRedeclContext()->Equals( 8335 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8336 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8337 << GuidedTemplateDecl; 8338 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8339 } 8340 8341 auto &DS = D.getMutableDeclSpec(); 8342 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8343 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8344 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8345 DS.isNoreturnSpecified() || DS.isConstexprSpecified() || 8346 DS.isConceptSpecified()) { 8347 BadSpecifierDiagnoser Diagnoser( 8348 *this, D.getIdentifierLoc(), 8349 diag::err_deduction_guide_invalid_specifier); 8350 8351 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8352 DS.ClearStorageClassSpecs(); 8353 SC = SC_None; 8354 8355 // 'explicit' is permitted. 8356 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8357 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8358 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8359 Diagnoser.check(DS.getConceptSpecLoc(), "concept"); 8360 DS.ClearConstexprSpec(); 8361 DS.ClearConceptSpec(); 8362 8363 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8364 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8365 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8366 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8367 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8368 DS.ClearTypeQualifiers(); 8369 8370 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8371 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8372 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8373 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8374 DS.ClearTypeSpecType(); 8375 } 8376 8377 if (D.isInvalidType()) 8378 return; 8379 8380 // Check the declarator is simple enough. 8381 bool FoundFunction = false; 8382 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8383 if (Chunk.Kind == DeclaratorChunk::Paren) 8384 continue; 8385 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8386 Diag(D.getDeclSpec().getLocStart(), 8387 diag::err_deduction_guide_with_complex_decl) 8388 << D.getSourceRange(); 8389 break; 8390 } 8391 if (!Chunk.Fun.hasTrailingReturnType()) { 8392 Diag(D.getName().getLocStart(), 8393 diag::err_deduction_guide_no_trailing_return_type); 8394 break; 8395 } 8396 8397 // Check that the return type is written as a specialization of 8398 // the template specified as the deduction-guide's name. 8399 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8400 TypeSourceInfo *TSI = nullptr; 8401 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8402 assert(TSI && "deduction guide has valid type but invalid return type?"); 8403 bool AcceptableReturnType = false; 8404 bool MightInstantiateToSpecialization = false; 8405 if (auto RetTST = 8406 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8407 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8408 bool TemplateMatches = 8409 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8410 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8411 AcceptableReturnType = true; 8412 else { 8413 // This could still instantiate to the right type, unless we know it 8414 // names the wrong class template. 8415 auto *TD = SpecifiedName.getAsTemplateDecl(); 8416 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8417 !TemplateMatches); 8418 } 8419 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8420 MightInstantiateToSpecialization = true; 8421 } 8422 8423 if (!AcceptableReturnType) { 8424 Diag(TSI->getTypeLoc().getLocStart(), 8425 diag::err_deduction_guide_bad_trailing_return_type) 8426 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8427 << TSI->getTypeLoc().getSourceRange(); 8428 } 8429 8430 // Keep going to check that we don't have any inner declarator pieces (we 8431 // could still have a function returning a pointer to a function). 8432 FoundFunction = true; 8433 } 8434 8435 if (D.isFunctionDefinition()) 8436 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8437 } 8438 8439 //===----------------------------------------------------------------------===// 8440 // Namespace Handling 8441 //===----------------------------------------------------------------------===// 8442 8443 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8444 /// reopened. 8445 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8446 SourceLocation Loc, 8447 IdentifierInfo *II, bool *IsInline, 8448 NamespaceDecl *PrevNS) { 8449 assert(*IsInline != PrevNS->isInline()); 8450 8451 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8452 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8453 // inline namespaces, with the intention of bringing names into namespace std. 8454 // 8455 // We support this just well enough to get that case working; this is not 8456 // sufficient to support reopening namespaces as inline in general. 8457 if (*IsInline && II && II->getName().startswith("__atomic") && 8458 S.getSourceManager().isInSystemHeader(Loc)) { 8459 // Mark all prior declarations of the namespace as inline. 8460 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8461 NS = NS->getPreviousDecl()) 8462 NS->setInline(*IsInline); 8463 // Patch up the lookup table for the containing namespace. This isn't really 8464 // correct, but it's good enough for this particular case. 8465 for (auto *I : PrevNS->decls()) 8466 if (auto *ND = dyn_cast<NamedDecl>(I)) 8467 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8468 return; 8469 } 8470 8471 if (PrevNS->isInline()) 8472 // The user probably just forgot the 'inline', so suggest that it 8473 // be added back. 8474 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8475 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8476 else 8477 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8478 8479 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8480 *IsInline = PrevNS->isInline(); 8481 } 8482 8483 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8484 /// definition. 8485 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8486 SourceLocation InlineLoc, 8487 SourceLocation NamespaceLoc, 8488 SourceLocation IdentLoc, 8489 IdentifierInfo *II, 8490 SourceLocation LBrace, 8491 AttributeList *AttrList, 8492 UsingDirectiveDecl *&UD) { 8493 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8494 // For anonymous namespace, take the location of the left brace. 8495 SourceLocation Loc = II ? IdentLoc : LBrace; 8496 bool IsInline = InlineLoc.isValid(); 8497 bool IsInvalid = false; 8498 bool IsStd = false; 8499 bool AddToKnown = false; 8500 Scope *DeclRegionScope = NamespcScope->getParent(); 8501 8502 NamespaceDecl *PrevNS = nullptr; 8503 if (II) { 8504 // C++ [namespace.def]p2: 8505 // The identifier in an original-namespace-definition shall not 8506 // have been previously defined in the declarative region in 8507 // which the original-namespace-definition appears. The 8508 // identifier in an original-namespace-definition is the name of 8509 // the namespace. Subsequently in that declarative region, it is 8510 // treated as an original-namespace-name. 8511 // 8512 // Since namespace names are unique in their scope, and we don't 8513 // look through using directives, just look for any ordinary names 8514 // as if by qualified name lookup. 8515 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8516 ForExternalRedeclaration); 8517 LookupQualifiedName(R, CurContext->getRedeclContext()); 8518 NamedDecl *PrevDecl = 8519 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8520 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8521 8522 if (PrevNS) { 8523 // This is an extended namespace definition. 8524 if (IsInline != PrevNS->isInline()) 8525 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8526 &IsInline, PrevNS); 8527 } else if (PrevDecl) { 8528 // This is an invalid name redefinition. 8529 Diag(Loc, diag::err_redefinition_different_kind) 8530 << II; 8531 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8532 IsInvalid = true; 8533 // Continue on to push Namespc as current DeclContext and return it. 8534 } else if (II->isStr("std") && 8535 CurContext->getRedeclContext()->isTranslationUnit()) { 8536 // This is the first "real" definition of the namespace "std", so update 8537 // our cache of the "std" namespace to point at this definition. 8538 PrevNS = getStdNamespace(); 8539 IsStd = true; 8540 AddToKnown = !IsInline; 8541 } else { 8542 // We've seen this namespace for the first time. 8543 AddToKnown = !IsInline; 8544 } 8545 } else { 8546 // Anonymous namespaces. 8547 8548 // Determine whether the parent already has an anonymous namespace. 8549 DeclContext *Parent = CurContext->getRedeclContext(); 8550 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8551 PrevNS = TU->getAnonymousNamespace(); 8552 } else { 8553 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8554 PrevNS = ND->getAnonymousNamespace(); 8555 } 8556 8557 if (PrevNS && IsInline != PrevNS->isInline()) 8558 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8559 &IsInline, PrevNS); 8560 } 8561 8562 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8563 StartLoc, Loc, II, PrevNS); 8564 if (IsInvalid) 8565 Namespc->setInvalidDecl(); 8566 8567 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8568 AddPragmaAttributes(DeclRegionScope, Namespc); 8569 8570 // FIXME: Should we be merging attributes? 8571 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8572 PushNamespaceVisibilityAttr(Attr, Loc); 8573 8574 if (IsStd) 8575 StdNamespace = Namespc; 8576 if (AddToKnown) 8577 KnownNamespaces[Namespc] = false; 8578 8579 if (II) { 8580 PushOnScopeChains(Namespc, DeclRegionScope); 8581 } else { 8582 // Link the anonymous namespace into its parent. 8583 DeclContext *Parent = CurContext->getRedeclContext(); 8584 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8585 TU->setAnonymousNamespace(Namespc); 8586 } else { 8587 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8588 } 8589 8590 CurContext->addDecl(Namespc); 8591 8592 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8593 // behaves as if it were replaced by 8594 // namespace unique { /* empty body */ } 8595 // using namespace unique; 8596 // namespace unique { namespace-body } 8597 // where all occurrences of 'unique' in a translation unit are 8598 // replaced by the same identifier and this identifier differs 8599 // from all other identifiers in the entire program. 8600 8601 // We just create the namespace with an empty name and then add an 8602 // implicit using declaration, just like the standard suggests. 8603 // 8604 // CodeGen enforces the "universally unique" aspect by giving all 8605 // declarations semantically contained within an anonymous 8606 // namespace internal linkage. 8607 8608 if (!PrevNS) { 8609 UD = UsingDirectiveDecl::Create(Context, Parent, 8610 /* 'using' */ LBrace, 8611 /* 'namespace' */ SourceLocation(), 8612 /* qualifier */ NestedNameSpecifierLoc(), 8613 /* identifier */ SourceLocation(), 8614 Namespc, 8615 /* Ancestor */ Parent); 8616 UD->setImplicit(); 8617 Parent->addDecl(UD); 8618 } 8619 } 8620 8621 ActOnDocumentableDecl(Namespc); 8622 8623 // Although we could have an invalid decl (i.e. the namespace name is a 8624 // redefinition), push it as current DeclContext and try to continue parsing. 8625 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8626 // for the namespace has the declarations that showed up in that particular 8627 // namespace definition. 8628 PushDeclContext(NamespcScope, Namespc); 8629 return Namespc; 8630 } 8631 8632 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8633 /// is a namespace alias, returns the namespace it points to. 8634 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8635 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8636 return AD->getNamespace(); 8637 return dyn_cast_or_null<NamespaceDecl>(D); 8638 } 8639 8640 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8641 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8642 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8643 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8644 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8645 Namespc->setRBraceLoc(RBrace); 8646 PopDeclContext(); 8647 if (Namespc->hasAttr<VisibilityAttr>()) 8648 PopPragmaVisibility(true, RBrace); 8649 } 8650 8651 CXXRecordDecl *Sema::getStdBadAlloc() const { 8652 return cast_or_null<CXXRecordDecl>( 8653 StdBadAlloc.get(Context.getExternalSource())); 8654 } 8655 8656 EnumDecl *Sema::getStdAlignValT() const { 8657 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8658 } 8659 8660 NamespaceDecl *Sema::getStdNamespace() const { 8661 return cast_or_null<NamespaceDecl>( 8662 StdNamespace.get(Context.getExternalSource())); 8663 } 8664 8665 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8666 if (!StdExperimentalNamespaceCache) { 8667 if (auto Std = getStdNamespace()) { 8668 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8669 SourceLocation(), LookupNamespaceName); 8670 if (!LookupQualifiedName(Result, Std) || 8671 !(StdExperimentalNamespaceCache = 8672 Result.getAsSingle<NamespaceDecl>())) 8673 Result.suppressDiagnostics(); 8674 } 8675 } 8676 return StdExperimentalNamespaceCache; 8677 } 8678 8679 /// \brief Retrieve the special "std" namespace, which may require us to 8680 /// implicitly define the namespace. 8681 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8682 if (!StdNamespace) { 8683 // The "std" namespace has not yet been defined, so build one implicitly. 8684 StdNamespace = NamespaceDecl::Create(Context, 8685 Context.getTranslationUnitDecl(), 8686 /*Inline=*/false, 8687 SourceLocation(), SourceLocation(), 8688 &PP.getIdentifierTable().get("std"), 8689 /*PrevDecl=*/nullptr); 8690 getStdNamespace()->setImplicit(true); 8691 } 8692 8693 return getStdNamespace(); 8694 } 8695 8696 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8697 assert(getLangOpts().CPlusPlus && 8698 "Looking for std::initializer_list outside of C++."); 8699 8700 // We're looking for implicit instantiations of 8701 // template <typename E> class std::initializer_list. 8702 8703 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8704 return false; 8705 8706 ClassTemplateDecl *Template = nullptr; 8707 const TemplateArgument *Arguments = nullptr; 8708 8709 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8710 8711 ClassTemplateSpecializationDecl *Specialization = 8712 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8713 if (!Specialization) 8714 return false; 8715 8716 Template = Specialization->getSpecializedTemplate(); 8717 Arguments = Specialization->getTemplateArgs().data(); 8718 } else if (const TemplateSpecializationType *TST = 8719 Ty->getAs<TemplateSpecializationType>()) { 8720 Template = dyn_cast_or_null<ClassTemplateDecl>( 8721 TST->getTemplateName().getAsTemplateDecl()); 8722 Arguments = TST->getArgs(); 8723 } 8724 if (!Template) 8725 return false; 8726 8727 if (!StdInitializerList) { 8728 // Haven't recognized std::initializer_list yet, maybe this is it. 8729 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8730 if (TemplateClass->getIdentifier() != 8731 &PP.getIdentifierTable().get("initializer_list") || 8732 !getStdNamespace()->InEnclosingNamespaceSetOf( 8733 TemplateClass->getDeclContext())) 8734 return false; 8735 // This is a template called std::initializer_list, but is it the right 8736 // template? 8737 TemplateParameterList *Params = Template->getTemplateParameters(); 8738 if (Params->getMinRequiredArguments() != 1) 8739 return false; 8740 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8741 return false; 8742 8743 // It's the right template. 8744 StdInitializerList = Template; 8745 } 8746 8747 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8748 return false; 8749 8750 // This is an instance of std::initializer_list. Find the argument type. 8751 if (Element) 8752 *Element = Arguments[0].getAsType(); 8753 return true; 8754 } 8755 8756 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8757 NamespaceDecl *Std = S.getStdNamespace(); 8758 if (!Std) { 8759 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8760 return nullptr; 8761 } 8762 8763 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8764 Loc, Sema::LookupOrdinaryName); 8765 if (!S.LookupQualifiedName(Result, Std)) { 8766 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8767 return nullptr; 8768 } 8769 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8770 if (!Template) { 8771 Result.suppressDiagnostics(); 8772 // We found something weird. Complain about the first thing we found. 8773 NamedDecl *Found = *Result.begin(); 8774 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8775 return nullptr; 8776 } 8777 8778 // We found some template called std::initializer_list. Now verify that it's 8779 // correct. 8780 TemplateParameterList *Params = Template->getTemplateParameters(); 8781 if (Params->getMinRequiredArguments() != 1 || 8782 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8783 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8784 return nullptr; 8785 } 8786 8787 return Template; 8788 } 8789 8790 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8791 if (!StdInitializerList) { 8792 StdInitializerList = LookupStdInitializerList(*this, Loc); 8793 if (!StdInitializerList) 8794 return QualType(); 8795 } 8796 8797 TemplateArgumentListInfo Args(Loc, Loc); 8798 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8799 Context.getTrivialTypeSourceInfo(Element, 8800 Loc))); 8801 return Context.getCanonicalType( 8802 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8803 } 8804 8805 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 8806 // C++ [dcl.init.list]p2: 8807 // A constructor is an initializer-list constructor if its first parameter 8808 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8809 // std::initializer_list<E> for some type E, and either there are no other 8810 // parameters or else all other parameters have default arguments. 8811 if (Ctor->getNumParams() < 1 || 8812 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8813 return false; 8814 8815 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8816 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8817 ArgType = RT->getPointeeType().getUnqualifiedType(); 8818 8819 return isStdInitializerList(ArgType, nullptr); 8820 } 8821 8822 /// \brief Determine whether a using statement is in a context where it will be 8823 /// apply in all contexts. 8824 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8825 switch (CurContext->getDeclKind()) { 8826 case Decl::TranslationUnit: 8827 return true; 8828 case Decl::LinkageSpec: 8829 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8830 default: 8831 return false; 8832 } 8833 } 8834 8835 namespace { 8836 8837 // Callback to only accept typo corrections that are namespaces. 8838 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8839 public: 8840 bool ValidateCandidate(const TypoCorrection &candidate) override { 8841 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8842 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8843 return false; 8844 } 8845 }; 8846 8847 } 8848 8849 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8850 CXXScopeSpec &SS, 8851 SourceLocation IdentLoc, 8852 IdentifierInfo *Ident) { 8853 R.clear(); 8854 if (TypoCorrection Corrected = 8855 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8856 llvm::make_unique<NamespaceValidatorCCC>(), 8857 Sema::CTK_ErrorRecovery)) { 8858 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8859 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8860 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8861 Ident->getName().equals(CorrectedStr); 8862 S.diagnoseTypo(Corrected, 8863 S.PDiag(diag::err_using_directive_member_suggest) 8864 << Ident << DC << DroppedSpecifier << SS.getRange(), 8865 S.PDiag(diag::note_namespace_defined_here)); 8866 } else { 8867 S.diagnoseTypo(Corrected, 8868 S.PDiag(diag::err_using_directive_suggest) << Ident, 8869 S.PDiag(diag::note_namespace_defined_here)); 8870 } 8871 R.addDecl(Corrected.getFoundDecl()); 8872 return true; 8873 } 8874 return false; 8875 } 8876 8877 Decl *Sema::ActOnUsingDirective(Scope *S, 8878 SourceLocation UsingLoc, 8879 SourceLocation NamespcLoc, 8880 CXXScopeSpec &SS, 8881 SourceLocation IdentLoc, 8882 IdentifierInfo *NamespcName, 8883 AttributeList *AttrList) { 8884 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8885 assert(NamespcName && "Invalid NamespcName."); 8886 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 8887 8888 // This can only happen along a recovery path. 8889 while (S->isTemplateParamScope()) 8890 S = S->getParent(); 8891 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8892 8893 UsingDirectiveDecl *UDir = nullptr; 8894 NestedNameSpecifier *Qualifier = nullptr; 8895 if (SS.isSet()) 8896 Qualifier = SS.getScopeRep(); 8897 8898 // Lookup namespace name. 8899 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 8900 LookupParsedName(R, S, &SS); 8901 if (R.isAmbiguous()) 8902 return nullptr; 8903 8904 if (R.empty()) { 8905 R.clear(); 8906 // Allow "using namespace std;" or "using namespace ::std;" even if 8907 // "std" hasn't been defined yet, for GCC compatibility. 8908 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 8909 NamespcName->isStr("std")) { 8910 Diag(IdentLoc, diag::ext_using_undefined_std); 8911 R.addDecl(getOrCreateStdNamespace()); 8912 R.resolveKind(); 8913 } 8914 // Otherwise, attempt typo correction. 8915 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 8916 } 8917 8918 if (!R.empty()) { 8919 NamedDecl *Named = R.getRepresentativeDecl(); 8920 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 8921 assert(NS && "expected namespace decl"); 8922 8923 // The use of a nested name specifier may trigger deprecation warnings. 8924 DiagnoseUseOfDecl(Named, IdentLoc); 8925 8926 // C++ [namespace.udir]p1: 8927 // A using-directive specifies that the names in the nominated 8928 // namespace can be used in the scope in which the 8929 // using-directive appears after the using-directive. During 8930 // unqualified name lookup (3.4.1), the names appear as if they 8931 // were declared in the nearest enclosing namespace which 8932 // contains both the using-directive and the nominated 8933 // namespace. [Note: in this context, "contains" means "contains 8934 // directly or indirectly". ] 8935 8936 // Find enclosing context containing both using-directive and 8937 // nominated namespace. 8938 DeclContext *CommonAncestor = cast<DeclContext>(NS); 8939 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 8940 CommonAncestor = CommonAncestor->getParent(); 8941 8942 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 8943 SS.getWithLocInContext(Context), 8944 IdentLoc, Named, CommonAncestor); 8945 8946 if (IsUsingDirectiveInToplevelContext(CurContext) && 8947 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 8948 Diag(IdentLoc, diag::warn_using_directive_in_header); 8949 } 8950 8951 PushUsingDirective(S, UDir); 8952 } else { 8953 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8954 } 8955 8956 if (UDir) 8957 ProcessDeclAttributeList(S, UDir, AttrList); 8958 8959 return UDir; 8960 } 8961 8962 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 8963 // If the scope has an associated entity and the using directive is at 8964 // namespace or translation unit scope, add the UsingDirectiveDecl into 8965 // its lookup structure so qualified name lookup can find it. 8966 DeclContext *Ctx = S->getEntity(); 8967 if (Ctx && !Ctx->isFunctionOrMethod()) 8968 Ctx->addDecl(UDir); 8969 else 8970 // Otherwise, it is at block scope. The using-directives will affect lookup 8971 // only to the end of the scope. 8972 S->PushUsingDirective(UDir); 8973 } 8974 8975 8976 Decl *Sema::ActOnUsingDeclaration(Scope *S, 8977 AccessSpecifier AS, 8978 SourceLocation UsingLoc, 8979 SourceLocation TypenameLoc, 8980 CXXScopeSpec &SS, 8981 UnqualifiedId &Name, 8982 SourceLocation EllipsisLoc, 8983 AttributeList *AttrList) { 8984 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8985 8986 if (SS.isEmpty()) { 8987 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 8988 return nullptr; 8989 } 8990 8991 switch (Name.getKind()) { 8992 case UnqualifiedId::IK_ImplicitSelfParam: 8993 case UnqualifiedId::IK_Identifier: 8994 case UnqualifiedId::IK_OperatorFunctionId: 8995 case UnqualifiedId::IK_LiteralOperatorId: 8996 case UnqualifiedId::IK_ConversionFunctionId: 8997 break; 8998 8999 case UnqualifiedId::IK_ConstructorName: 9000 case UnqualifiedId::IK_ConstructorTemplateId: 9001 // C++11 inheriting constructors. 9002 Diag(Name.getLocStart(), 9003 getLangOpts().CPlusPlus11 ? 9004 diag::warn_cxx98_compat_using_decl_constructor : 9005 diag::err_using_decl_constructor) 9006 << SS.getRange(); 9007 9008 if (getLangOpts().CPlusPlus11) break; 9009 9010 return nullptr; 9011 9012 case UnqualifiedId::IK_DestructorName: 9013 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 9014 << SS.getRange(); 9015 return nullptr; 9016 9017 case UnqualifiedId::IK_TemplateId: 9018 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 9019 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9020 return nullptr; 9021 9022 case UnqualifiedId::IK_DeductionGuideName: 9023 llvm_unreachable("cannot parse qualified deduction guide name"); 9024 } 9025 9026 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9027 DeclarationName TargetName = TargetNameInfo.getName(); 9028 if (!TargetName) 9029 return nullptr; 9030 9031 // Warn about access declarations. 9032 if (UsingLoc.isInvalid()) { 9033 Diag(Name.getLocStart(), 9034 getLangOpts().CPlusPlus11 ? diag::err_access_decl 9035 : diag::warn_access_decl_deprecated) 9036 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9037 } 9038 9039 if (EllipsisLoc.isInvalid()) { 9040 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9041 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9042 return nullptr; 9043 } else { 9044 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9045 !TargetNameInfo.containsUnexpandedParameterPack()) { 9046 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9047 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9048 EllipsisLoc = SourceLocation(); 9049 } 9050 } 9051 9052 NamedDecl *UD = 9053 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9054 SS, TargetNameInfo, EllipsisLoc, AttrList, 9055 /*IsInstantiation*/false); 9056 if (UD) 9057 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9058 9059 return UD; 9060 } 9061 9062 /// \brief Determine whether a using declaration considers the given 9063 /// declarations as "equivalent", e.g., if they are redeclarations of 9064 /// the same entity or are both typedefs of the same type. 9065 static bool 9066 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9067 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9068 return true; 9069 9070 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9071 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9072 return Context.hasSameType(TD1->getUnderlyingType(), 9073 TD2->getUnderlyingType()); 9074 9075 return false; 9076 } 9077 9078 9079 /// Determines whether to create a using shadow decl for a particular 9080 /// decl, given the set of decls existing prior to this using lookup. 9081 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9082 const LookupResult &Previous, 9083 UsingShadowDecl *&PrevShadow) { 9084 // Diagnose finding a decl which is not from a base class of the 9085 // current class. We do this now because there are cases where this 9086 // function will silently decide not to build a shadow decl, which 9087 // will pre-empt further diagnostics. 9088 // 9089 // We don't need to do this in C++11 because we do the check once on 9090 // the qualifier. 9091 // 9092 // FIXME: diagnose the following if we care enough: 9093 // struct A { int foo; }; 9094 // struct B : A { using A::foo; }; 9095 // template <class T> struct C : A {}; 9096 // template <class T> struct D : C<T> { using B::foo; } // <--- 9097 // This is invalid (during instantiation) in C++03 because B::foo 9098 // resolves to the using decl in B, which is not a base class of D<T>. 9099 // We can't diagnose it immediately because C<T> is an unknown 9100 // specialization. The UsingShadowDecl in D<T> then points directly 9101 // to A::foo, which will look well-formed when we instantiate. 9102 // The right solution is to not collapse the shadow-decl chain. 9103 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9104 DeclContext *OrigDC = Orig->getDeclContext(); 9105 9106 // Handle enums and anonymous structs. 9107 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9108 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9109 while (OrigRec->isAnonymousStructOrUnion()) 9110 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9111 9112 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9113 if (OrigDC == CurContext) { 9114 Diag(Using->getLocation(), 9115 diag::err_using_decl_nested_name_specifier_is_current_class) 9116 << Using->getQualifierLoc().getSourceRange(); 9117 Diag(Orig->getLocation(), diag::note_using_decl_target); 9118 Using->setInvalidDecl(); 9119 return true; 9120 } 9121 9122 Diag(Using->getQualifierLoc().getBeginLoc(), 9123 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9124 << Using->getQualifier() 9125 << cast<CXXRecordDecl>(CurContext) 9126 << Using->getQualifierLoc().getSourceRange(); 9127 Diag(Orig->getLocation(), diag::note_using_decl_target); 9128 Using->setInvalidDecl(); 9129 return true; 9130 } 9131 } 9132 9133 if (Previous.empty()) return false; 9134 9135 NamedDecl *Target = Orig; 9136 if (isa<UsingShadowDecl>(Target)) 9137 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9138 9139 // If the target happens to be one of the previous declarations, we 9140 // don't have a conflict. 9141 // 9142 // FIXME: but we might be increasing its access, in which case we 9143 // should redeclare it. 9144 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9145 bool FoundEquivalentDecl = false; 9146 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9147 I != E; ++I) { 9148 NamedDecl *D = (*I)->getUnderlyingDecl(); 9149 // We can have UsingDecls in our Previous results because we use the same 9150 // LookupResult for checking whether the UsingDecl itself is a valid 9151 // redeclaration. 9152 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9153 continue; 9154 9155 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9156 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9157 PrevShadow = Shadow; 9158 FoundEquivalentDecl = true; 9159 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9160 // We don't conflict with an existing using shadow decl of an equivalent 9161 // declaration, but we're not a redeclaration of it. 9162 FoundEquivalentDecl = true; 9163 } 9164 9165 if (isVisible(D)) 9166 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9167 } 9168 9169 if (FoundEquivalentDecl) 9170 return false; 9171 9172 if (FunctionDecl *FD = Target->getAsFunction()) { 9173 NamedDecl *OldDecl = nullptr; 9174 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9175 /*IsForUsingDecl*/ true)) { 9176 case Ovl_Overload: 9177 return false; 9178 9179 case Ovl_NonFunction: 9180 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9181 break; 9182 9183 // We found a decl with the exact signature. 9184 case Ovl_Match: 9185 // If we're in a record, we want to hide the target, so we 9186 // return true (without a diagnostic) to tell the caller not to 9187 // build a shadow decl. 9188 if (CurContext->isRecord()) 9189 return true; 9190 9191 // If we're not in a record, this is an error. 9192 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9193 break; 9194 } 9195 9196 Diag(Target->getLocation(), diag::note_using_decl_target); 9197 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9198 Using->setInvalidDecl(); 9199 return true; 9200 } 9201 9202 // Target is not a function. 9203 9204 if (isa<TagDecl>(Target)) { 9205 // No conflict between a tag and a non-tag. 9206 if (!Tag) return false; 9207 9208 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9209 Diag(Target->getLocation(), diag::note_using_decl_target); 9210 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9211 Using->setInvalidDecl(); 9212 return true; 9213 } 9214 9215 // No conflict between a tag and a non-tag. 9216 if (!NonTag) return false; 9217 9218 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9219 Diag(Target->getLocation(), diag::note_using_decl_target); 9220 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9221 Using->setInvalidDecl(); 9222 return true; 9223 } 9224 9225 /// Determine whether a direct base class is a virtual base class. 9226 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9227 if (!Derived->getNumVBases()) 9228 return false; 9229 for (auto &B : Derived->bases()) 9230 if (B.getType()->getAsCXXRecordDecl() == Base) 9231 return B.isVirtual(); 9232 llvm_unreachable("not a direct base class"); 9233 } 9234 9235 /// Builds a shadow declaration corresponding to a 'using' declaration. 9236 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9237 UsingDecl *UD, 9238 NamedDecl *Orig, 9239 UsingShadowDecl *PrevDecl) { 9240 // If we resolved to another shadow declaration, just coalesce them. 9241 NamedDecl *Target = Orig; 9242 if (isa<UsingShadowDecl>(Target)) { 9243 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9244 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9245 } 9246 9247 NamedDecl *NonTemplateTarget = Target; 9248 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9249 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9250 9251 UsingShadowDecl *Shadow; 9252 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9253 bool IsVirtualBase = 9254 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9255 UD->getQualifier()->getAsRecordDecl()); 9256 Shadow = ConstructorUsingShadowDecl::Create( 9257 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9258 } else { 9259 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9260 Target); 9261 } 9262 UD->addShadowDecl(Shadow); 9263 9264 Shadow->setAccess(UD->getAccess()); 9265 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9266 Shadow->setInvalidDecl(); 9267 9268 Shadow->setPreviousDecl(PrevDecl); 9269 9270 if (S) 9271 PushOnScopeChains(Shadow, S); 9272 else 9273 CurContext->addDecl(Shadow); 9274 9275 9276 return Shadow; 9277 } 9278 9279 /// Hides a using shadow declaration. This is required by the current 9280 /// using-decl implementation when a resolvable using declaration in a 9281 /// class is followed by a declaration which would hide or override 9282 /// one or more of the using decl's targets; for example: 9283 /// 9284 /// struct Base { void foo(int); }; 9285 /// struct Derived : Base { 9286 /// using Base::foo; 9287 /// void foo(int); 9288 /// }; 9289 /// 9290 /// The governing language is C++03 [namespace.udecl]p12: 9291 /// 9292 /// When a using-declaration brings names from a base class into a 9293 /// derived class scope, member functions in the derived class 9294 /// override and/or hide member functions with the same name and 9295 /// parameter types in a base class (rather than conflicting). 9296 /// 9297 /// There are two ways to implement this: 9298 /// (1) optimistically create shadow decls when they're not hidden 9299 /// by existing declarations, or 9300 /// (2) don't create any shadow decls (or at least don't make them 9301 /// visible) until we've fully parsed/instantiated the class. 9302 /// The problem with (1) is that we might have to retroactively remove 9303 /// a shadow decl, which requires several O(n) operations because the 9304 /// decl structures are (very reasonably) not designed for removal. 9305 /// (2) avoids this but is very fiddly and phase-dependent. 9306 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9307 if (Shadow->getDeclName().getNameKind() == 9308 DeclarationName::CXXConversionFunctionName) 9309 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9310 9311 // Remove it from the DeclContext... 9312 Shadow->getDeclContext()->removeDecl(Shadow); 9313 9314 // ...and the scope, if applicable... 9315 if (S) { 9316 S->RemoveDecl(Shadow); 9317 IdResolver.RemoveDecl(Shadow); 9318 } 9319 9320 // ...and the using decl. 9321 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9322 9323 // TODO: complain somehow if Shadow was used. It shouldn't 9324 // be possible for this to happen, because...? 9325 } 9326 9327 /// Find the base specifier for a base class with the given type. 9328 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9329 QualType DesiredBase, 9330 bool &AnyDependentBases) { 9331 // Check whether the named type is a direct base class. 9332 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9333 for (auto &Base : Derived->bases()) { 9334 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9335 if (CanonicalDesiredBase == BaseType) 9336 return &Base; 9337 if (BaseType->isDependentType()) 9338 AnyDependentBases = true; 9339 } 9340 return nullptr; 9341 } 9342 9343 namespace { 9344 class UsingValidatorCCC : public CorrectionCandidateCallback { 9345 public: 9346 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9347 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9348 : HasTypenameKeyword(HasTypenameKeyword), 9349 IsInstantiation(IsInstantiation), OldNNS(NNS), 9350 RequireMemberOf(RequireMemberOf) {} 9351 9352 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9353 NamedDecl *ND = Candidate.getCorrectionDecl(); 9354 9355 // Keywords are not valid here. 9356 if (!ND || isa<NamespaceDecl>(ND)) 9357 return false; 9358 9359 // Completely unqualified names are invalid for a 'using' declaration. 9360 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9361 return false; 9362 9363 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9364 // reject. 9365 9366 if (RequireMemberOf) { 9367 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9368 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9369 // No-one ever wants a using-declaration to name an injected-class-name 9370 // of a base class, unless they're declaring an inheriting constructor. 9371 ASTContext &Ctx = ND->getASTContext(); 9372 if (!Ctx.getLangOpts().CPlusPlus11) 9373 return false; 9374 QualType FoundType = Ctx.getRecordType(FoundRecord); 9375 9376 // Check that the injected-class-name is named as a member of its own 9377 // type; we don't want to suggest 'using Derived::Base;', since that 9378 // means something else. 9379 NestedNameSpecifier *Specifier = 9380 Candidate.WillReplaceSpecifier() 9381 ? Candidate.getCorrectionSpecifier() 9382 : OldNNS; 9383 if (!Specifier->getAsType() || 9384 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9385 return false; 9386 9387 // Check that this inheriting constructor declaration actually names a 9388 // direct base class of the current class. 9389 bool AnyDependentBases = false; 9390 if (!findDirectBaseWithType(RequireMemberOf, 9391 Ctx.getRecordType(FoundRecord), 9392 AnyDependentBases) && 9393 !AnyDependentBases) 9394 return false; 9395 } else { 9396 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9397 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9398 return false; 9399 9400 // FIXME: Check that the base class member is accessible? 9401 } 9402 } else { 9403 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9404 if (FoundRecord && FoundRecord->isInjectedClassName()) 9405 return false; 9406 } 9407 9408 if (isa<TypeDecl>(ND)) 9409 return HasTypenameKeyword || !IsInstantiation; 9410 9411 return !HasTypenameKeyword; 9412 } 9413 9414 private: 9415 bool HasTypenameKeyword; 9416 bool IsInstantiation; 9417 NestedNameSpecifier *OldNNS; 9418 CXXRecordDecl *RequireMemberOf; 9419 }; 9420 } // end anonymous namespace 9421 9422 /// Builds a using declaration. 9423 /// 9424 /// \param IsInstantiation - Whether this call arises from an 9425 /// instantiation of an unresolved using declaration. We treat 9426 /// the lookup differently for these declarations. 9427 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9428 SourceLocation UsingLoc, 9429 bool HasTypenameKeyword, 9430 SourceLocation TypenameLoc, 9431 CXXScopeSpec &SS, 9432 DeclarationNameInfo NameInfo, 9433 SourceLocation EllipsisLoc, 9434 AttributeList *AttrList, 9435 bool IsInstantiation) { 9436 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9437 SourceLocation IdentLoc = NameInfo.getLoc(); 9438 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9439 9440 // FIXME: We ignore attributes for now. 9441 9442 // For an inheriting constructor declaration, the name of the using 9443 // declaration is the name of a constructor in this class, not in the 9444 // base class. 9445 DeclarationNameInfo UsingName = NameInfo; 9446 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9447 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9448 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9449 Context.getCanonicalType(Context.getRecordType(RD)))); 9450 9451 // Do the redeclaration lookup in the current scope. 9452 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9453 ForVisibleRedeclaration); 9454 Previous.setHideTags(false); 9455 if (S) { 9456 LookupName(Previous, S); 9457 9458 // It is really dumb that we have to do this. 9459 LookupResult::Filter F = Previous.makeFilter(); 9460 while (F.hasNext()) { 9461 NamedDecl *D = F.next(); 9462 if (!isDeclInScope(D, CurContext, S)) 9463 F.erase(); 9464 // If we found a local extern declaration that's not ordinarily visible, 9465 // and this declaration is being added to a non-block scope, ignore it. 9466 // We're only checking for scope conflicts here, not also for violations 9467 // of the linkage rules. 9468 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9469 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9470 F.erase(); 9471 } 9472 F.done(); 9473 } else { 9474 assert(IsInstantiation && "no scope in non-instantiation"); 9475 if (CurContext->isRecord()) 9476 LookupQualifiedName(Previous, CurContext); 9477 else { 9478 // No redeclaration check is needed here; in non-member contexts we 9479 // diagnosed all possible conflicts with other using-declarations when 9480 // building the template: 9481 // 9482 // For a dependent non-type using declaration, the only valid case is 9483 // if we instantiate to a single enumerator. We check for conflicts 9484 // between shadow declarations we introduce, and we check in the template 9485 // definition for conflicts between a non-type using declaration and any 9486 // other declaration, which together covers all cases. 9487 // 9488 // A dependent typename using declaration will never successfully 9489 // instantiate, since it will always name a class member, so we reject 9490 // that in the template definition. 9491 } 9492 } 9493 9494 // Check for invalid redeclarations. 9495 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9496 SS, IdentLoc, Previous)) 9497 return nullptr; 9498 9499 // Check for bad qualifiers. 9500 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9501 IdentLoc)) 9502 return nullptr; 9503 9504 DeclContext *LookupContext = computeDeclContext(SS); 9505 NamedDecl *D; 9506 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9507 if (!LookupContext || EllipsisLoc.isValid()) { 9508 if (HasTypenameKeyword) { 9509 // FIXME: not all declaration name kinds are legal here 9510 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9511 UsingLoc, TypenameLoc, 9512 QualifierLoc, 9513 IdentLoc, NameInfo.getName(), 9514 EllipsisLoc); 9515 } else { 9516 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9517 QualifierLoc, NameInfo, EllipsisLoc); 9518 } 9519 D->setAccess(AS); 9520 CurContext->addDecl(D); 9521 return D; 9522 } 9523 9524 auto Build = [&](bool Invalid) { 9525 UsingDecl *UD = 9526 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9527 UsingName, HasTypenameKeyword); 9528 UD->setAccess(AS); 9529 CurContext->addDecl(UD); 9530 UD->setInvalidDecl(Invalid); 9531 return UD; 9532 }; 9533 auto BuildInvalid = [&]{ return Build(true); }; 9534 auto BuildValid = [&]{ return Build(false); }; 9535 9536 if (RequireCompleteDeclContext(SS, LookupContext)) 9537 return BuildInvalid(); 9538 9539 // Look up the target name. 9540 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9541 9542 // Unlike most lookups, we don't always want to hide tag 9543 // declarations: tag names are visible through the using declaration 9544 // even if hidden by ordinary names, *except* in a dependent context 9545 // where it's important for the sanity of two-phase lookup. 9546 if (!IsInstantiation) 9547 R.setHideTags(false); 9548 9549 // For the purposes of this lookup, we have a base object type 9550 // equal to that of the current context. 9551 if (CurContext->isRecord()) { 9552 R.setBaseObjectType( 9553 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9554 } 9555 9556 LookupQualifiedName(R, LookupContext); 9557 9558 // Try to correct typos if possible. If constructor name lookup finds no 9559 // results, that means the named class has no explicit constructors, and we 9560 // suppressed declaring implicit ones (probably because it's dependent or 9561 // invalid). 9562 if (R.empty() && 9563 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9564 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9565 // it will believe that glibc provides a ::gets in cases where it does not, 9566 // and will try to pull it into namespace std with a using-declaration. 9567 // Just ignore the using-declaration in that case. 9568 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9569 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9570 CurContext->isStdNamespace() && 9571 isa<TranslationUnitDecl>(LookupContext) && 9572 getSourceManager().isInSystemHeader(UsingLoc)) 9573 return nullptr; 9574 if (TypoCorrection Corrected = CorrectTypo( 9575 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9576 llvm::make_unique<UsingValidatorCCC>( 9577 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9578 dyn_cast<CXXRecordDecl>(CurContext)), 9579 CTK_ErrorRecovery)) { 9580 // We reject candidates where DroppedSpecifier == true, hence the 9581 // literal '0' below. 9582 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9583 << NameInfo.getName() << LookupContext << 0 9584 << SS.getRange()); 9585 9586 // If we picked a correction with no attached Decl we can't do anything 9587 // useful with it, bail out. 9588 NamedDecl *ND = Corrected.getCorrectionDecl(); 9589 if (!ND) 9590 return BuildInvalid(); 9591 9592 // If we corrected to an inheriting constructor, handle it as one. 9593 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9594 if (RD && RD->isInjectedClassName()) { 9595 // The parent of the injected class name is the class itself. 9596 RD = cast<CXXRecordDecl>(RD->getParent()); 9597 9598 // Fix up the information we'll use to build the using declaration. 9599 if (Corrected.WillReplaceSpecifier()) { 9600 NestedNameSpecifierLocBuilder Builder; 9601 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9602 QualifierLoc.getSourceRange()); 9603 QualifierLoc = Builder.getWithLocInContext(Context); 9604 } 9605 9606 // In this case, the name we introduce is the name of a derived class 9607 // constructor. 9608 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9609 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9610 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9611 UsingName.setNamedTypeInfo(nullptr); 9612 for (auto *Ctor : LookupConstructors(RD)) 9613 R.addDecl(Ctor); 9614 R.resolveKind(); 9615 } else { 9616 // FIXME: Pick up all the declarations if we found an overloaded 9617 // function. 9618 UsingName.setName(ND->getDeclName()); 9619 R.addDecl(ND); 9620 } 9621 } else { 9622 Diag(IdentLoc, diag::err_no_member) 9623 << NameInfo.getName() << LookupContext << SS.getRange(); 9624 return BuildInvalid(); 9625 } 9626 } 9627 9628 if (R.isAmbiguous()) 9629 return BuildInvalid(); 9630 9631 if (HasTypenameKeyword) { 9632 // If we asked for a typename and got a non-type decl, error out. 9633 if (!R.getAsSingle<TypeDecl>()) { 9634 Diag(IdentLoc, diag::err_using_typename_non_type); 9635 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9636 Diag((*I)->getUnderlyingDecl()->getLocation(), 9637 diag::note_using_decl_target); 9638 return BuildInvalid(); 9639 } 9640 } else { 9641 // If we asked for a non-typename and we got a type, error out, 9642 // but only if this is an instantiation of an unresolved using 9643 // decl. Otherwise just silently find the type name. 9644 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9645 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9646 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9647 return BuildInvalid(); 9648 } 9649 } 9650 9651 // C++14 [namespace.udecl]p6: 9652 // A using-declaration shall not name a namespace. 9653 if (R.getAsSingle<NamespaceDecl>()) { 9654 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9655 << SS.getRange(); 9656 return BuildInvalid(); 9657 } 9658 9659 // C++14 [namespace.udecl]p7: 9660 // A using-declaration shall not name a scoped enumerator. 9661 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9662 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9663 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9664 << SS.getRange(); 9665 return BuildInvalid(); 9666 } 9667 } 9668 9669 UsingDecl *UD = BuildValid(); 9670 9671 // Some additional rules apply to inheriting constructors. 9672 if (UsingName.getName().getNameKind() == 9673 DeclarationName::CXXConstructorName) { 9674 // Suppress access diagnostics; the access check is instead performed at the 9675 // point of use for an inheriting constructor. 9676 R.suppressDiagnostics(); 9677 if (CheckInheritingConstructorUsingDecl(UD)) 9678 return UD; 9679 } 9680 9681 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9682 UsingShadowDecl *PrevDecl = nullptr; 9683 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9684 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9685 } 9686 9687 return UD; 9688 } 9689 9690 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 9691 ArrayRef<NamedDecl *> Expansions) { 9692 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 9693 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 9694 isa<UsingPackDecl>(InstantiatedFrom)); 9695 9696 auto *UPD = 9697 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 9698 UPD->setAccess(InstantiatedFrom->getAccess()); 9699 CurContext->addDecl(UPD); 9700 return UPD; 9701 } 9702 9703 /// Additional checks for a using declaration referring to a constructor name. 9704 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9705 assert(!UD->hasTypename() && "expecting a constructor name"); 9706 9707 const Type *SourceType = UD->getQualifier()->getAsType(); 9708 assert(SourceType && 9709 "Using decl naming constructor doesn't have type in scope spec."); 9710 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9711 9712 // Check whether the named type is a direct base class. 9713 bool AnyDependentBases = false; 9714 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9715 AnyDependentBases); 9716 if (!Base && !AnyDependentBases) { 9717 Diag(UD->getUsingLoc(), 9718 diag::err_using_decl_constructor_not_in_direct_base) 9719 << UD->getNameInfo().getSourceRange() 9720 << QualType(SourceType, 0) << TargetClass; 9721 UD->setInvalidDecl(); 9722 return true; 9723 } 9724 9725 if (Base) 9726 Base->setInheritConstructors(); 9727 9728 return false; 9729 } 9730 9731 /// Checks that the given using declaration is not an invalid 9732 /// redeclaration. Note that this is checking only for the using decl 9733 /// itself, not for any ill-formedness among the UsingShadowDecls. 9734 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9735 bool HasTypenameKeyword, 9736 const CXXScopeSpec &SS, 9737 SourceLocation NameLoc, 9738 const LookupResult &Prev) { 9739 NestedNameSpecifier *Qual = SS.getScopeRep(); 9740 9741 // C++03 [namespace.udecl]p8: 9742 // C++0x [namespace.udecl]p10: 9743 // A using-declaration is a declaration and can therefore be used 9744 // repeatedly where (and only where) multiple declarations are 9745 // allowed. 9746 // 9747 // That's in non-member contexts. 9748 if (!CurContext->getRedeclContext()->isRecord()) { 9749 // A dependent qualifier outside a class can only ever resolve to an 9750 // enumeration type. Therefore it conflicts with any other non-type 9751 // declaration in the same scope. 9752 // FIXME: How should we check for dependent type-type conflicts at block 9753 // scope? 9754 if (Qual->isDependent() && !HasTypenameKeyword) { 9755 for (auto *D : Prev) { 9756 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 9757 bool OldCouldBeEnumerator = 9758 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 9759 Diag(NameLoc, 9760 OldCouldBeEnumerator ? diag::err_redefinition 9761 : diag::err_redefinition_different_kind) 9762 << Prev.getLookupName(); 9763 Diag(D->getLocation(), diag::note_previous_definition); 9764 return true; 9765 } 9766 } 9767 } 9768 return false; 9769 } 9770 9771 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9772 NamedDecl *D = *I; 9773 9774 bool DTypename; 9775 NestedNameSpecifier *DQual; 9776 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9777 DTypename = UD->hasTypename(); 9778 DQual = UD->getQualifier(); 9779 } else if (UnresolvedUsingValueDecl *UD 9780 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9781 DTypename = false; 9782 DQual = UD->getQualifier(); 9783 } else if (UnresolvedUsingTypenameDecl *UD 9784 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9785 DTypename = true; 9786 DQual = UD->getQualifier(); 9787 } else continue; 9788 9789 // using decls differ if one says 'typename' and the other doesn't. 9790 // FIXME: non-dependent using decls? 9791 if (HasTypenameKeyword != DTypename) continue; 9792 9793 // using decls differ if they name different scopes (but note that 9794 // template instantiation can cause this check to trigger when it 9795 // didn't before instantiation). 9796 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9797 Context.getCanonicalNestedNameSpecifier(DQual)) 9798 continue; 9799 9800 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9801 Diag(D->getLocation(), diag::note_using_decl) << 1; 9802 return true; 9803 } 9804 9805 return false; 9806 } 9807 9808 9809 /// Checks that the given nested-name qualifier used in a using decl 9810 /// in the current context is appropriately related to the current 9811 /// scope. If an error is found, diagnoses it and returns true. 9812 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9813 bool HasTypename, 9814 const CXXScopeSpec &SS, 9815 const DeclarationNameInfo &NameInfo, 9816 SourceLocation NameLoc) { 9817 DeclContext *NamedContext = computeDeclContext(SS); 9818 9819 if (!CurContext->isRecord()) { 9820 // C++03 [namespace.udecl]p3: 9821 // C++0x [namespace.udecl]p8: 9822 // A using-declaration for a class member shall be a member-declaration. 9823 9824 // If we weren't able to compute a valid scope, it might validly be a 9825 // dependent class scope or a dependent enumeration unscoped scope. If 9826 // we have a 'typename' keyword, the scope must resolve to a class type. 9827 if ((HasTypename && !NamedContext) || 9828 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 9829 auto *RD = NamedContext 9830 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9831 : nullptr; 9832 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9833 RD = nullptr; 9834 9835 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9836 << SS.getRange(); 9837 9838 // If we have a complete, non-dependent source type, try to suggest a 9839 // way to get the same effect. 9840 if (!RD) 9841 return true; 9842 9843 // Find what this using-declaration was referring to. 9844 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9845 R.setHideTags(false); 9846 R.suppressDiagnostics(); 9847 LookupQualifiedName(R, RD); 9848 9849 if (R.getAsSingle<TypeDecl>()) { 9850 if (getLangOpts().CPlusPlus11) { 9851 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9852 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9853 << 0 // alias declaration 9854 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9855 NameInfo.getName().getAsString() + 9856 " = "); 9857 } else { 9858 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9859 SourceLocation InsertLoc = 9860 getLocForEndOfToken(NameInfo.getLocEnd()); 9861 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9862 << 1 // typedef declaration 9863 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9864 << FixItHint::CreateInsertion( 9865 InsertLoc, " " + NameInfo.getName().getAsString()); 9866 } 9867 } else if (R.getAsSingle<VarDecl>()) { 9868 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9869 // repeating the type of the static data member here. 9870 FixItHint FixIt; 9871 if (getLangOpts().CPlusPlus11) { 9872 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9873 FixIt = FixItHint::CreateReplacement( 9874 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9875 } 9876 9877 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9878 << 2 // reference declaration 9879 << FixIt; 9880 } else if (R.getAsSingle<EnumConstantDecl>()) { 9881 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9882 // repeating the type of the enumeration here, and we can't do so if 9883 // the type is anonymous. 9884 FixItHint FixIt; 9885 if (getLangOpts().CPlusPlus11) { 9886 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9887 FixIt = FixItHint::CreateReplacement( 9888 UsingLoc, 9889 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 9890 } 9891 9892 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9893 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 9894 << FixIt; 9895 } 9896 return true; 9897 } 9898 9899 // Otherwise, this might be valid. 9900 return false; 9901 } 9902 9903 // The current scope is a record. 9904 9905 // If the named context is dependent, we can't decide much. 9906 if (!NamedContext) { 9907 // FIXME: in C++0x, we can diagnose if we can prove that the 9908 // nested-name-specifier does not refer to a base class, which is 9909 // still possible in some cases. 9910 9911 // Otherwise we have to conservatively report that things might be 9912 // okay. 9913 return false; 9914 } 9915 9916 if (!NamedContext->isRecord()) { 9917 // Ideally this would point at the last name in the specifier, 9918 // but we don't have that level of source info. 9919 Diag(SS.getRange().getBegin(), 9920 diag::err_using_decl_nested_name_specifier_is_not_class) 9921 << SS.getScopeRep() << SS.getRange(); 9922 return true; 9923 } 9924 9925 if (!NamedContext->isDependentContext() && 9926 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 9927 return true; 9928 9929 if (getLangOpts().CPlusPlus11) { 9930 // C++11 [namespace.udecl]p3: 9931 // In a using-declaration used as a member-declaration, the 9932 // nested-name-specifier shall name a base class of the class 9933 // being defined. 9934 9935 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 9936 cast<CXXRecordDecl>(NamedContext))) { 9937 if (CurContext == NamedContext) { 9938 Diag(NameLoc, 9939 diag::err_using_decl_nested_name_specifier_is_current_class) 9940 << SS.getRange(); 9941 return true; 9942 } 9943 9944 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 9945 Diag(SS.getRange().getBegin(), 9946 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9947 << SS.getScopeRep() 9948 << cast<CXXRecordDecl>(CurContext) 9949 << SS.getRange(); 9950 } 9951 return true; 9952 } 9953 9954 return false; 9955 } 9956 9957 // C++03 [namespace.udecl]p4: 9958 // A using-declaration used as a member-declaration shall refer 9959 // to a member of a base class of the class being defined [etc.]. 9960 9961 // Salient point: SS doesn't have to name a base class as long as 9962 // lookup only finds members from base classes. Therefore we can 9963 // diagnose here only if we can prove that that can't happen, 9964 // i.e. if the class hierarchies provably don't intersect. 9965 9966 // TODO: it would be nice if "definitely valid" results were cached 9967 // in the UsingDecl and UsingShadowDecl so that these checks didn't 9968 // need to be repeated. 9969 9970 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 9971 auto Collect = [&Bases](const CXXRecordDecl *Base) { 9972 Bases.insert(Base); 9973 return true; 9974 }; 9975 9976 // Collect all bases. Return false if we find a dependent base. 9977 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 9978 return false; 9979 9980 // Returns true if the base is dependent or is one of the accumulated base 9981 // classes. 9982 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 9983 return !Bases.count(Base); 9984 }; 9985 9986 // Return false if the class has a dependent base or if it or one 9987 // of its bases is present in the base set of the current context. 9988 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 9989 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 9990 return false; 9991 9992 Diag(SS.getRange().getBegin(), 9993 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9994 << SS.getScopeRep() 9995 << cast<CXXRecordDecl>(CurContext) 9996 << SS.getRange(); 9997 9998 return true; 9999 } 10000 10001 Decl *Sema::ActOnAliasDeclaration(Scope *S, 10002 AccessSpecifier AS, 10003 MultiTemplateParamsArg TemplateParamLists, 10004 SourceLocation UsingLoc, 10005 UnqualifiedId &Name, 10006 AttributeList *AttrList, 10007 TypeResult Type, 10008 Decl *DeclFromDeclSpec) { 10009 // Skip up to the relevant declaration scope. 10010 while (S->isTemplateParamScope()) 10011 S = S->getParent(); 10012 assert((S->getFlags() & Scope::DeclScope) && 10013 "got alias-declaration outside of declaration scope"); 10014 10015 if (Type.isInvalid()) 10016 return nullptr; 10017 10018 bool Invalid = false; 10019 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10020 TypeSourceInfo *TInfo = nullptr; 10021 GetTypeFromParser(Type.get(), &TInfo); 10022 10023 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10024 return nullptr; 10025 10026 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10027 UPPC_DeclarationType)) { 10028 Invalid = true; 10029 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10030 TInfo->getTypeLoc().getBeginLoc()); 10031 } 10032 10033 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10034 TemplateParamLists.size() 10035 ? forRedeclarationInCurContext() 10036 : ForVisibleRedeclaration); 10037 LookupName(Previous, S); 10038 10039 // Warn about shadowing the name of a template parameter. 10040 if (Previous.isSingleResult() && 10041 Previous.getFoundDecl()->isTemplateParameter()) { 10042 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10043 Previous.clear(); 10044 } 10045 10046 assert(Name.Kind == UnqualifiedId::IK_Identifier && 10047 "name in alias declaration must be an identifier"); 10048 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10049 Name.StartLocation, 10050 Name.Identifier, TInfo); 10051 10052 NewTD->setAccess(AS); 10053 10054 if (Invalid) 10055 NewTD->setInvalidDecl(); 10056 10057 ProcessDeclAttributeList(S, NewTD, AttrList); 10058 AddPragmaAttributes(S, NewTD); 10059 10060 CheckTypedefForVariablyModifiedType(S, NewTD); 10061 Invalid |= NewTD->isInvalidDecl(); 10062 10063 bool Redeclaration = false; 10064 10065 NamedDecl *NewND; 10066 if (TemplateParamLists.size()) { 10067 TypeAliasTemplateDecl *OldDecl = nullptr; 10068 TemplateParameterList *OldTemplateParams = nullptr; 10069 10070 if (TemplateParamLists.size() != 1) { 10071 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10072 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10073 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10074 } 10075 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10076 10077 // Check that we can declare a template here. 10078 if (CheckTemplateDeclScope(S, TemplateParams)) 10079 return nullptr; 10080 10081 // Only consider previous declarations in the same scope. 10082 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10083 /*ExplicitInstantiationOrSpecialization*/false); 10084 if (!Previous.empty()) { 10085 Redeclaration = true; 10086 10087 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10088 if (!OldDecl && !Invalid) { 10089 Diag(UsingLoc, diag::err_redefinition_different_kind) 10090 << Name.Identifier; 10091 10092 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10093 if (OldD->getLocation().isValid()) 10094 Diag(OldD->getLocation(), diag::note_previous_definition); 10095 10096 Invalid = true; 10097 } 10098 10099 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10100 if (TemplateParameterListsAreEqual(TemplateParams, 10101 OldDecl->getTemplateParameters(), 10102 /*Complain=*/true, 10103 TPL_TemplateMatch)) 10104 OldTemplateParams = OldDecl->getTemplateParameters(); 10105 else 10106 Invalid = true; 10107 10108 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10109 if (!Invalid && 10110 !Context.hasSameType(OldTD->getUnderlyingType(), 10111 NewTD->getUnderlyingType())) { 10112 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10113 // but we can't reasonably accept it. 10114 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10115 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10116 if (OldTD->getLocation().isValid()) 10117 Diag(OldTD->getLocation(), diag::note_previous_definition); 10118 Invalid = true; 10119 } 10120 } 10121 } 10122 10123 // Merge any previous default template arguments into our parameters, 10124 // and check the parameter list. 10125 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10126 TPC_TypeAliasTemplate)) 10127 return nullptr; 10128 10129 TypeAliasTemplateDecl *NewDecl = 10130 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10131 Name.Identifier, TemplateParams, 10132 NewTD); 10133 NewTD->setDescribedAliasTemplate(NewDecl); 10134 10135 NewDecl->setAccess(AS); 10136 10137 if (Invalid) 10138 NewDecl->setInvalidDecl(); 10139 else if (OldDecl) { 10140 NewDecl->setPreviousDecl(OldDecl); 10141 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10142 } 10143 10144 NewND = NewDecl; 10145 } else { 10146 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10147 setTagNameForLinkagePurposes(TD, NewTD); 10148 handleTagNumbering(TD, S); 10149 } 10150 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10151 NewND = NewTD; 10152 } 10153 10154 PushOnScopeChains(NewND, S); 10155 ActOnDocumentableDecl(NewND); 10156 return NewND; 10157 } 10158 10159 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10160 SourceLocation AliasLoc, 10161 IdentifierInfo *Alias, CXXScopeSpec &SS, 10162 SourceLocation IdentLoc, 10163 IdentifierInfo *Ident) { 10164 10165 // Lookup the namespace name. 10166 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10167 LookupParsedName(R, S, &SS); 10168 10169 if (R.isAmbiguous()) 10170 return nullptr; 10171 10172 if (R.empty()) { 10173 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10174 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10175 return nullptr; 10176 } 10177 } 10178 assert(!R.isAmbiguous() && !R.empty()); 10179 NamedDecl *ND = R.getRepresentativeDecl(); 10180 10181 // Check if we have a previous declaration with the same name. 10182 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10183 ForVisibleRedeclaration); 10184 LookupName(PrevR, S); 10185 10186 // Check we're not shadowing a template parameter. 10187 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10188 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10189 PrevR.clear(); 10190 } 10191 10192 // Filter out any other lookup result from an enclosing scope. 10193 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10194 /*AllowInlineNamespace*/false); 10195 10196 // Find the previous declaration and check that we can redeclare it. 10197 NamespaceAliasDecl *Prev = nullptr; 10198 if (PrevR.isSingleResult()) { 10199 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10200 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10201 // We already have an alias with the same name that points to the same 10202 // namespace; check that it matches. 10203 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10204 Prev = AD; 10205 } else if (isVisible(PrevDecl)) { 10206 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10207 << Alias; 10208 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10209 << AD->getNamespace(); 10210 return nullptr; 10211 } 10212 } else if (isVisible(PrevDecl)) { 10213 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10214 ? diag::err_redefinition 10215 : diag::err_redefinition_different_kind; 10216 Diag(AliasLoc, DiagID) << Alias; 10217 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10218 return nullptr; 10219 } 10220 } 10221 10222 // The use of a nested name specifier may trigger deprecation warnings. 10223 DiagnoseUseOfDecl(ND, IdentLoc); 10224 10225 NamespaceAliasDecl *AliasDecl = 10226 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10227 Alias, SS.getWithLocInContext(Context), 10228 IdentLoc, ND); 10229 if (Prev) 10230 AliasDecl->setPreviousDecl(Prev); 10231 10232 PushOnScopeChains(AliasDecl, S); 10233 return AliasDecl; 10234 } 10235 10236 namespace { 10237 struct SpecialMemberExceptionSpecInfo 10238 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10239 SourceLocation Loc; 10240 Sema::ImplicitExceptionSpecification ExceptSpec; 10241 10242 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10243 Sema::CXXSpecialMember CSM, 10244 Sema::InheritedConstructorInfo *ICI, 10245 SourceLocation Loc) 10246 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10247 10248 bool visitBase(CXXBaseSpecifier *Base); 10249 bool visitField(FieldDecl *FD); 10250 10251 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10252 unsigned Quals); 10253 10254 void visitSubobjectCall(Subobject Subobj, 10255 Sema::SpecialMemberOverloadResult SMOR); 10256 }; 10257 } 10258 10259 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10260 auto *RT = Base->getType()->getAs<RecordType>(); 10261 if (!RT) 10262 return false; 10263 10264 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10265 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10266 if (auto *BaseCtor = SMOR.getMethod()) { 10267 visitSubobjectCall(Base, BaseCtor); 10268 return false; 10269 } 10270 10271 visitClassSubobject(BaseClass, Base, 0); 10272 return false; 10273 } 10274 10275 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10276 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10277 Expr *E = FD->getInClassInitializer(); 10278 if (!E) 10279 // FIXME: It's a little wasteful to build and throw away a 10280 // CXXDefaultInitExpr here. 10281 // FIXME: We should have a single context note pointing at Loc, and 10282 // this location should be MD->getLocation() instead, since that's 10283 // the location where we actually use the default init expression. 10284 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10285 if (E) 10286 ExceptSpec.CalledExpr(E); 10287 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10288 ->getAs<RecordType>()) { 10289 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10290 FD->getType().getCVRQualifiers()); 10291 } 10292 return false; 10293 } 10294 10295 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10296 Subobject Subobj, 10297 unsigned Quals) { 10298 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10299 bool IsMutable = Field && Field->isMutable(); 10300 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10301 } 10302 10303 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10304 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10305 // Note, if lookup fails, it doesn't matter what exception specification we 10306 // choose because the special member will be deleted. 10307 if (CXXMethodDecl *MD = SMOR.getMethod()) 10308 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10309 } 10310 10311 static Sema::ImplicitExceptionSpecification 10312 ComputeDefaultedSpecialMemberExceptionSpec( 10313 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10314 Sema::InheritedConstructorInfo *ICI) { 10315 CXXRecordDecl *ClassDecl = MD->getParent(); 10316 10317 // C++ [except.spec]p14: 10318 // An implicitly declared special member function (Clause 12) shall have an 10319 // exception-specification. [...] 10320 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10321 if (ClassDecl->isInvalidDecl()) 10322 return Info.ExceptSpec; 10323 10324 // C++1z [except.spec]p7: 10325 // [Look for exceptions thrown by] a constructor selected [...] to 10326 // initialize a potentially constructed subobject, 10327 // C++1z [except.spec]p8: 10328 // The exception specification for an implicitly-declared destructor, or a 10329 // destructor without a noexcept-specifier, is potentially-throwing if and 10330 // only if any of the destructors for any of its potentially constructed 10331 // subojects is potentially throwing. 10332 // FIXME: We respect the first rule but ignore the "potentially constructed" 10333 // in the second rule to resolve a core issue (no number yet) that would have 10334 // us reject: 10335 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10336 // struct B : A {}; 10337 // struct C : B { void f(); }; 10338 // ... due to giving B::~B() a non-throwing exception specification. 10339 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10340 : Info.VisitAllBases); 10341 10342 return Info.ExceptSpec; 10343 } 10344 10345 namespace { 10346 /// RAII object to register a special member as being currently declared. 10347 struct DeclaringSpecialMember { 10348 Sema &S; 10349 Sema::SpecialMemberDecl D; 10350 Sema::ContextRAII SavedContext; 10351 bool WasAlreadyBeingDeclared; 10352 10353 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10354 : S(S), D(RD, CSM), SavedContext(S, RD) { 10355 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10356 if (WasAlreadyBeingDeclared) 10357 // This almost never happens, but if it does, ensure that our cache 10358 // doesn't contain a stale result. 10359 S.SpecialMemberCache.clear(); 10360 else { 10361 // Register a note to be produced if we encounter an error while 10362 // declaring the special member. 10363 Sema::CodeSynthesisContext Ctx; 10364 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10365 // FIXME: We don't have a location to use here. Using the class's 10366 // location maintains the fiction that we declare all special members 10367 // with the class, but (1) it's not clear that lying about that helps our 10368 // users understand what's going on, and (2) there may be outer contexts 10369 // on the stack (some of which are relevant) and printing them exposes 10370 // our lies. 10371 Ctx.PointOfInstantiation = RD->getLocation(); 10372 Ctx.Entity = RD; 10373 Ctx.SpecialMember = CSM; 10374 S.pushCodeSynthesisContext(Ctx); 10375 } 10376 } 10377 ~DeclaringSpecialMember() { 10378 if (!WasAlreadyBeingDeclared) { 10379 S.SpecialMembersBeingDeclared.erase(D); 10380 S.popCodeSynthesisContext(); 10381 } 10382 } 10383 10384 /// \brief Are we already trying to declare this special member? 10385 bool isAlreadyBeingDeclared() const { 10386 return WasAlreadyBeingDeclared; 10387 } 10388 }; 10389 } 10390 10391 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10392 // Look up any existing declarations, but don't trigger declaration of all 10393 // implicit special members with this name. 10394 DeclarationName Name = FD->getDeclName(); 10395 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10396 ForExternalRedeclaration); 10397 for (auto *D : FD->getParent()->lookup(Name)) 10398 if (auto *Acceptable = R.getAcceptableDecl(D)) 10399 R.addDecl(Acceptable); 10400 R.resolveKind(); 10401 R.suppressDiagnostics(); 10402 10403 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10404 } 10405 10406 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10407 CXXRecordDecl *ClassDecl) { 10408 // C++ [class.ctor]p5: 10409 // A default constructor for a class X is a constructor of class X 10410 // that can be called without an argument. If there is no 10411 // user-declared constructor for class X, a default constructor is 10412 // implicitly declared. An implicitly-declared default constructor 10413 // is an inline public member of its class. 10414 assert(ClassDecl->needsImplicitDefaultConstructor() && 10415 "Should not build implicit default constructor!"); 10416 10417 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10418 if (DSM.isAlreadyBeingDeclared()) 10419 return nullptr; 10420 10421 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10422 CXXDefaultConstructor, 10423 false); 10424 10425 // Create the actual constructor declaration. 10426 CanQualType ClassType 10427 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10428 SourceLocation ClassLoc = ClassDecl->getLocation(); 10429 DeclarationName Name 10430 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10431 DeclarationNameInfo NameInfo(Name, ClassLoc); 10432 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10433 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10434 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10435 /*isImplicitlyDeclared=*/true, Constexpr); 10436 DefaultCon->setAccess(AS_public); 10437 DefaultCon->setDefaulted(); 10438 10439 if (getLangOpts().CUDA) { 10440 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10441 DefaultCon, 10442 /* ConstRHS */ false, 10443 /* Diagnose */ false); 10444 } 10445 10446 // Build an exception specification pointing back at this constructor. 10447 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10448 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10449 10450 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10451 // constructors is easy to compute. 10452 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10453 10454 // Note that we have declared this constructor. 10455 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10456 10457 Scope *S = getScopeForContext(ClassDecl); 10458 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10459 10460 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10461 SetDeclDeleted(DefaultCon, ClassLoc); 10462 10463 if (S) 10464 PushOnScopeChains(DefaultCon, S, false); 10465 ClassDecl->addDecl(DefaultCon); 10466 10467 return DefaultCon; 10468 } 10469 10470 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10471 CXXConstructorDecl *Constructor) { 10472 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10473 !Constructor->doesThisDeclarationHaveABody() && 10474 !Constructor->isDeleted()) && 10475 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10476 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10477 return; 10478 10479 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10480 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10481 10482 SynthesizedFunctionScope Scope(*this, Constructor); 10483 10484 // The exception specification is needed because we are defining the 10485 // function. 10486 ResolveExceptionSpec(CurrentLocation, 10487 Constructor->getType()->castAs<FunctionProtoType>()); 10488 MarkVTableUsed(CurrentLocation, ClassDecl); 10489 10490 // Add a context note for diagnostics produced after this point. 10491 Scope.addContextNote(CurrentLocation); 10492 10493 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10494 Constructor->setInvalidDecl(); 10495 return; 10496 } 10497 10498 SourceLocation Loc = Constructor->getLocEnd().isValid() 10499 ? Constructor->getLocEnd() 10500 : Constructor->getLocation(); 10501 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10502 Constructor->markUsed(Context); 10503 10504 if (ASTMutationListener *L = getASTMutationListener()) { 10505 L->CompletedImplicitDefinition(Constructor); 10506 } 10507 10508 DiagnoseUninitializedFields(*this, Constructor); 10509 } 10510 10511 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10512 // Perform any delayed checks on exception specifications. 10513 CheckDelayedMemberExceptionSpecs(); 10514 } 10515 10516 /// Find or create the fake constructor we synthesize to model constructing an 10517 /// object of a derived class via a constructor of a base class. 10518 CXXConstructorDecl * 10519 Sema::findInheritingConstructor(SourceLocation Loc, 10520 CXXConstructorDecl *BaseCtor, 10521 ConstructorUsingShadowDecl *Shadow) { 10522 CXXRecordDecl *Derived = Shadow->getParent(); 10523 SourceLocation UsingLoc = Shadow->getLocation(); 10524 10525 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10526 // For now we use the name of the base class constructor as a member of the 10527 // derived class to indicate a (fake) inherited constructor name. 10528 DeclarationName Name = BaseCtor->getDeclName(); 10529 10530 // Check to see if we already have a fake constructor for this inherited 10531 // constructor call. 10532 for (NamedDecl *Ctor : Derived->lookup(Name)) 10533 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10534 ->getInheritedConstructor() 10535 .getConstructor(), 10536 BaseCtor)) 10537 return cast<CXXConstructorDecl>(Ctor); 10538 10539 DeclarationNameInfo NameInfo(Name, UsingLoc); 10540 TypeSourceInfo *TInfo = 10541 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10542 FunctionProtoTypeLoc ProtoLoc = 10543 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10544 10545 // Check the inherited constructor is valid and find the list of base classes 10546 // from which it was inherited. 10547 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10548 10549 bool Constexpr = 10550 BaseCtor->isConstexpr() && 10551 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10552 false, BaseCtor, &ICI); 10553 10554 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10555 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10556 BaseCtor->isExplicit(), /*Inline=*/true, 10557 /*ImplicitlyDeclared=*/true, Constexpr, 10558 InheritedConstructor(Shadow, BaseCtor)); 10559 if (Shadow->isInvalidDecl()) 10560 DerivedCtor->setInvalidDecl(); 10561 10562 // Build an unevaluated exception specification for this fake constructor. 10563 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10564 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10565 EPI.ExceptionSpec.Type = EST_Unevaluated; 10566 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10567 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10568 FPT->getParamTypes(), EPI)); 10569 10570 // Build the parameter declarations. 10571 SmallVector<ParmVarDecl *, 16> ParamDecls; 10572 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10573 TypeSourceInfo *TInfo = 10574 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10575 ParmVarDecl *PD = ParmVarDecl::Create( 10576 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10577 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10578 PD->setScopeInfo(0, I); 10579 PD->setImplicit(); 10580 // Ensure attributes are propagated onto parameters (this matters for 10581 // format, pass_object_size, ...). 10582 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10583 ParamDecls.push_back(PD); 10584 ProtoLoc.setParam(I, PD); 10585 } 10586 10587 // Set up the new constructor. 10588 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10589 DerivedCtor->setAccess(BaseCtor->getAccess()); 10590 DerivedCtor->setParams(ParamDecls); 10591 Derived->addDecl(DerivedCtor); 10592 10593 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10594 SetDeclDeleted(DerivedCtor, UsingLoc); 10595 10596 return DerivedCtor; 10597 } 10598 10599 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10600 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10601 Ctor->getInheritedConstructor().getShadowDecl()); 10602 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10603 /*Diagnose*/true); 10604 } 10605 10606 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10607 CXXConstructorDecl *Constructor) { 10608 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10609 assert(Constructor->getInheritedConstructor() && 10610 !Constructor->doesThisDeclarationHaveABody() && 10611 !Constructor->isDeleted()); 10612 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10613 return; 10614 10615 // Initializations are performed "as if by a defaulted default constructor", 10616 // so enter the appropriate scope. 10617 SynthesizedFunctionScope Scope(*this, Constructor); 10618 10619 // The exception specification is needed because we are defining the 10620 // function. 10621 ResolveExceptionSpec(CurrentLocation, 10622 Constructor->getType()->castAs<FunctionProtoType>()); 10623 MarkVTableUsed(CurrentLocation, ClassDecl); 10624 10625 // Add a context note for diagnostics produced after this point. 10626 Scope.addContextNote(CurrentLocation); 10627 10628 ConstructorUsingShadowDecl *Shadow = 10629 Constructor->getInheritedConstructor().getShadowDecl(); 10630 CXXConstructorDecl *InheritedCtor = 10631 Constructor->getInheritedConstructor().getConstructor(); 10632 10633 // [class.inhctor.init]p1: 10634 // initialization proceeds as if a defaulted default constructor is used to 10635 // initialize the D object and each base class subobject from which the 10636 // constructor was inherited 10637 10638 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10639 CXXRecordDecl *RD = Shadow->getParent(); 10640 SourceLocation InitLoc = Shadow->getLocation(); 10641 10642 // Build explicit initializers for all base classes from which the 10643 // constructor was inherited. 10644 SmallVector<CXXCtorInitializer*, 8> Inits; 10645 for (bool VBase : {false, true}) { 10646 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10647 if (B.isVirtual() != VBase) 10648 continue; 10649 10650 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10651 if (!BaseRD) 10652 continue; 10653 10654 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10655 if (!BaseCtor.first) 10656 continue; 10657 10658 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10659 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10660 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10661 10662 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10663 Inits.push_back(new (Context) CXXCtorInitializer( 10664 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10665 SourceLocation())); 10666 } 10667 } 10668 10669 // We now proceed as if for a defaulted default constructor, with the relevant 10670 // initializers replaced. 10671 10672 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 10673 Constructor->setInvalidDecl(); 10674 return; 10675 } 10676 10677 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10678 Constructor->markUsed(Context); 10679 10680 if (ASTMutationListener *L = getASTMutationListener()) { 10681 L->CompletedImplicitDefinition(Constructor); 10682 } 10683 10684 DiagnoseUninitializedFields(*this, Constructor); 10685 } 10686 10687 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10688 // C++ [class.dtor]p2: 10689 // If a class has no user-declared destructor, a destructor is 10690 // declared implicitly. An implicitly-declared destructor is an 10691 // inline public member of its class. 10692 assert(ClassDecl->needsImplicitDestructor()); 10693 10694 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10695 if (DSM.isAlreadyBeingDeclared()) 10696 return nullptr; 10697 10698 // Create the actual destructor declaration. 10699 CanQualType ClassType 10700 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10701 SourceLocation ClassLoc = ClassDecl->getLocation(); 10702 DeclarationName Name 10703 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10704 DeclarationNameInfo NameInfo(Name, ClassLoc); 10705 CXXDestructorDecl *Destructor 10706 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10707 QualType(), nullptr, /*isInline=*/true, 10708 /*isImplicitlyDeclared=*/true); 10709 Destructor->setAccess(AS_public); 10710 Destructor->setDefaulted(); 10711 10712 if (getLangOpts().CUDA) { 10713 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10714 Destructor, 10715 /* ConstRHS */ false, 10716 /* Diagnose */ false); 10717 } 10718 10719 // Build an exception specification pointing back at this destructor. 10720 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10721 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10722 10723 // We don't need to use SpecialMemberIsTrivial here; triviality for 10724 // destructors is easy to compute. 10725 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10726 10727 // Note that we have declared this destructor. 10728 ++ASTContext::NumImplicitDestructorsDeclared; 10729 10730 Scope *S = getScopeForContext(ClassDecl); 10731 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10732 10733 // We can't check whether an implicit destructor is deleted before we complete 10734 // the definition of the class, because its validity depends on the alignment 10735 // of the class. We'll check this from ActOnFields once the class is complete. 10736 if (ClassDecl->isCompleteDefinition() && 10737 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10738 SetDeclDeleted(Destructor, ClassLoc); 10739 10740 // Introduce this destructor into its scope. 10741 if (S) 10742 PushOnScopeChains(Destructor, S, false); 10743 ClassDecl->addDecl(Destructor); 10744 10745 return Destructor; 10746 } 10747 10748 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10749 CXXDestructorDecl *Destructor) { 10750 assert((Destructor->isDefaulted() && 10751 !Destructor->doesThisDeclarationHaveABody() && 10752 !Destructor->isDeleted()) && 10753 "DefineImplicitDestructor - call it for implicit default dtor"); 10754 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 10755 return; 10756 10757 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10758 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10759 10760 SynthesizedFunctionScope Scope(*this, Destructor); 10761 10762 // The exception specification is needed because we are defining the 10763 // function. 10764 ResolveExceptionSpec(CurrentLocation, 10765 Destructor->getType()->castAs<FunctionProtoType>()); 10766 MarkVTableUsed(CurrentLocation, ClassDecl); 10767 10768 // Add a context note for diagnostics produced after this point. 10769 Scope.addContextNote(CurrentLocation); 10770 10771 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10772 Destructor->getParent()); 10773 10774 if (CheckDestructor(Destructor)) { 10775 Destructor->setInvalidDecl(); 10776 return; 10777 } 10778 10779 SourceLocation Loc = Destructor->getLocEnd().isValid() 10780 ? Destructor->getLocEnd() 10781 : Destructor->getLocation(); 10782 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10783 Destructor->markUsed(Context); 10784 10785 if (ASTMutationListener *L = getASTMutationListener()) { 10786 L->CompletedImplicitDefinition(Destructor); 10787 } 10788 } 10789 10790 /// \brief Perform any semantic analysis which needs to be delayed until all 10791 /// pending class member declarations have been parsed. 10792 void Sema::ActOnFinishCXXMemberDecls() { 10793 // If the context is an invalid C++ class, just suppress these checks. 10794 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10795 if (Record->isInvalidDecl()) { 10796 DelayedDefaultedMemberExceptionSpecs.clear(); 10797 DelayedExceptionSpecChecks.clear(); 10798 return; 10799 } 10800 checkForMultipleExportedDefaultConstructors(*this, Record); 10801 } 10802 } 10803 10804 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10805 referenceDLLExportedClassMethods(); 10806 } 10807 10808 void Sema::referenceDLLExportedClassMethods() { 10809 if (!DelayedDllExportClasses.empty()) { 10810 // Calling ReferenceDllExportedMethods might cause the current function to 10811 // be called again, so use a local copy of DelayedDllExportClasses. 10812 SmallVector<CXXRecordDecl *, 4> WorkList; 10813 std::swap(DelayedDllExportClasses, WorkList); 10814 for (CXXRecordDecl *Class : WorkList) 10815 ReferenceDllExportedMethods(*this, Class); 10816 } 10817 } 10818 10819 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10820 CXXDestructorDecl *Destructor) { 10821 assert(getLangOpts().CPlusPlus11 && 10822 "adjusting dtor exception specs was introduced in c++11"); 10823 10824 // C++11 [class.dtor]p3: 10825 // A declaration of a destructor that does not have an exception- 10826 // specification is implicitly considered to have the same exception- 10827 // specification as an implicit declaration. 10828 const FunctionProtoType *DtorType = Destructor->getType()-> 10829 getAs<FunctionProtoType>(); 10830 if (DtorType->hasExceptionSpec()) 10831 return; 10832 10833 // Replace the destructor's type, building off the existing one. Fortunately, 10834 // the only thing of interest in the destructor type is its extended info. 10835 // The return and arguments are fixed. 10836 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10837 EPI.ExceptionSpec.Type = EST_Unevaluated; 10838 EPI.ExceptionSpec.SourceDecl = Destructor; 10839 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10840 10841 // FIXME: If the destructor has a body that could throw, and the newly created 10842 // spec doesn't allow exceptions, we should emit a warning, because this 10843 // change in behavior can break conforming C++03 programs at runtime. 10844 // However, we don't have a body or an exception specification yet, so it 10845 // needs to be done somewhere else. 10846 } 10847 10848 namespace { 10849 /// \brief An abstract base class for all helper classes used in building the 10850 // copy/move operators. These classes serve as factory functions and help us 10851 // avoid using the same Expr* in the AST twice. 10852 class ExprBuilder { 10853 ExprBuilder(const ExprBuilder&) = delete; 10854 ExprBuilder &operator=(const ExprBuilder&) = delete; 10855 10856 protected: 10857 static Expr *assertNotNull(Expr *E) { 10858 assert(E && "Expression construction must not fail."); 10859 return E; 10860 } 10861 10862 public: 10863 ExprBuilder() {} 10864 virtual ~ExprBuilder() {} 10865 10866 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10867 }; 10868 10869 class RefBuilder: public ExprBuilder { 10870 VarDecl *Var; 10871 QualType VarType; 10872 10873 public: 10874 Expr *build(Sema &S, SourceLocation Loc) const override { 10875 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10876 } 10877 10878 RefBuilder(VarDecl *Var, QualType VarType) 10879 : Var(Var), VarType(VarType) {} 10880 }; 10881 10882 class ThisBuilder: public ExprBuilder { 10883 public: 10884 Expr *build(Sema &S, SourceLocation Loc) const override { 10885 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 10886 } 10887 }; 10888 10889 class CastBuilder: public ExprBuilder { 10890 const ExprBuilder &Builder; 10891 QualType Type; 10892 ExprValueKind Kind; 10893 const CXXCastPath &Path; 10894 10895 public: 10896 Expr *build(Sema &S, SourceLocation Loc) const override { 10897 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 10898 CK_UncheckedDerivedToBase, Kind, 10899 &Path).get()); 10900 } 10901 10902 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 10903 const CXXCastPath &Path) 10904 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 10905 }; 10906 10907 class DerefBuilder: public ExprBuilder { 10908 const ExprBuilder &Builder; 10909 10910 public: 10911 Expr *build(Sema &S, SourceLocation Loc) const override { 10912 return assertNotNull( 10913 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 10914 } 10915 10916 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10917 }; 10918 10919 class MemberBuilder: public ExprBuilder { 10920 const ExprBuilder &Builder; 10921 QualType Type; 10922 CXXScopeSpec SS; 10923 bool IsArrow; 10924 LookupResult &MemberLookup; 10925 10926 public: 10927 Expr *build(Sema &S, SourceLocation Loc) const override { 10928 return assertNotNull(S.BuildMemberReferenceExpr( 10929 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 10930 nullptr, MemberLookup, nullptr, nullptr).get()); 10931 } 10932 10933 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 10934 LookupResult &MemberLookup) 10935 : Builder(Builder), Type(Type), IsArrow(IsArrow), 10936 MemberLookup(MemberLookup) {} 10937 }; 10938 10939 class MoveCastBuilder: public ExprBuilder { 10940 const ExprBuilder &Builder; 10941 10942 public: 10943 Expr *build(Sema &S, SourceLocation Loc) const override { 10944 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 10945 } 10946 10947 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10948 }; 10949 10950 class LvalueConvBuilder: public ExprBuilder { 10951 const ExprBuilder &Builder; 10952 10953 public: 10954 Expr *build(Sema &S, SourceLocation Loc) const override { 10955 return assertNotNull( 10956 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 10957 } 10958 10959 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10960 }; 10961 10962 class SubscriptBuilder: public ExprBuilder { 10963 const ExprBuilder &Base; 10964 const ExprBuilder &Index; 10965 10966 public: 10967 Expr *build(Sema &S, SourceLocation Loc) const override { 10968 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 10969 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 10970 } 10971 10972 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 10973 : Base(Base), Index(Index) {} 10974 }; 10975 10976 } // end anonymous namespace 10977 10978 /// When generating a defaulted copy or move assignment operator, if a field 10979 /// should be copied with __builtin_memcpy rather than via explicit assignments, 10980 /// do so. This optimization only applies for arrays of scalars, and for arrays 10981 /// of class type where the selected copy/move-assignment operator is trivial. 10982 static StmtResult 10983 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 10984 const ExprBuilder &ToB, const ExprBuilder &FromB) { 10985 // Compute the size of the memory buffer to be copied. 10986 QualType SizeType = S.Context.getSizeType(); 10987 llvm::APInt Size(S.Context.getTypeSize(SizeType), 10988 S.Context.getTypeSizeInChars(T).getQuantity()); 10989 10990 // Take the address of the field references for "from" and "to". We 10991 // directly construct UnaryOperators here because semantic analysis 10992 // does not permit us to take the address of an xvalue. 10993 Expr *From = FromB.build(S, Loc); 10994 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 10995 S.Context.getPointerType(From->getType()), 10996 VK_RValue, OK_Ordinary, Loc); 10997 Expr *To = ToB.build(S, Loc); 10998 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 10999 S.Context.getPointerType(To->getType()), 11000 VK_RValue, OK_Ordinary, Loc); 11001 11002 const Type *E = T->getBaseElementTypeUnsafe(); 11003 bool NeedsCollectableMemCpy = 11004 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11005 11006 // Create a reference to the __builtin_objc_memmove_collectable function 11007 StringRef MemCpyName = NeedsCollectableMemCpy ? 11008 "__builtin_objc_memmove_collectable" : 11009 "__builtin_memcpy"; 11010 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11011 Sema::LookupOrdinaryName); 11012 S.LookupName(R, S.TUScope, true); 11013 11014 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11015 if (!MemCpy) 11016 // Something went horribly wrong earlier, and we will have complained 11017 // about it. 11018 return StmtError(); 11019 11020 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11021 VK_RValue, Loc, nullptr); 11022 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11023 11024 Expr *CallArgs[] = { 11025 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11026 }; 11027 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11028 Loc, CallArgs, Loc); 11029 11030 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11031 return Call.getAs<Stmt>(); 11032 } 11033 11034 /// \brief Builds a statement that copies/moves the given entity from \p From to 11035 /// \c To. 11036 /// 11037 /// This routine is used to copy/move the members of a class with an 11038 /// implicitly-declared copy/move assignment operator. When the entities being 11039 /// copied are arrays, this routine builds for loops to copy them. 11040 /// 11041 /// \param S The Sema object used for type-checking. 11042 /// 11043 /// \param Loc The location where the implicit copy/move is being generated. 11044 /// 11045 /// \param T The type of the expressions being copied/moved. Both expressions 11046 /// must have this type. 11047 /// 11048 /// \param To The expression we are copying/moving to. 11049 /// 11050 /// \param From The expression we are copying/moving from. 11051 /// 11052 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11053 /// Otherwise, it's a non-static member subobject. 11054 /// 11055 /// \param Copying Whether we're copying or moving. 11056 /// 11057 /// \param Depth Internal parameter recording the depth of the recursion. 11058 /// 11059 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11060 /// if a memcpy should be used instead. 11061 static StmtResult 11062 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11063 const ExprBuilder &To, const ExprBuilder &From, 11064 bool CopyingBaseSubobject, bool Copying, 11065 unsigned Depth = 0) { 11066 // C++11 [class.copy]p28: 11067 // Each subobject is assigned in the manner appropriate to its type: 11068 // 11069 // - if the subobject is of class type, as if by a call to operator= with 11070 // the subobject as the object expression and the corresponding 11071 // subobject of x as a single function argument (as if by explicit 11072 // qualification; that is, ignoring any possible virtual overriding 11073 // functions in more derived classes); 11074 // 11075 // C++03 [class.copy]p13: 11076 // - if the subobject is of class type, the copy assignment operator for 11077 // the class is used (as if by explicit qualification; that is, 11078 // ignoring any possible virtual overriding functions in more derived 11079 // classes); 11080 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11081 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11082 11083 // Look for operator=. 11084 DeclarationName Name 11085 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11086 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11087 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11088 11089 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11090 // operator. 11091 if (!S.getLangOpts().CPlusPlus11) { 11092 LookupResult::Filter F = OpLookup.makeFilter(); 11093 while (F.hasNext()) { 11094 NamedDecl *D = F.next(); 11095 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11096 if (Method->isCopyAssignmentOperator() || 11097 (!Copying && Method->isMoveAssignmentOperator())) 11098 continue; 11099 11100 F.erase(); 11101 } 11102 F.done(); 11103 } 11104 11105 // Suppress the protected check (C++ [class.protected]) for each of the 11106 // assignment operators we found. This strange dance is required when 11107 // we're assigning via a base classes's copy-assignment operator. To 11108 // ensure that we're getting the right base class subobject (without 11109 // ambiguities), we need to cast "this" to that subobject type; to 11110 // ensure that we don't go through the virtual call mechanism, we need 11111 // to qualify the operator= name with the base class (see below). However, 11112 // this means that if the base class has a protected copy assignment 11113 // operator, the protected member access check will fail. So, we 11114 // rewrite "protected" access to "public" access in this case, since we 11115 // know by construction that we're calling from a derived class. 11116 if (CopyingBaseSubobject) { 11117 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11118 L != LEnd; ++L) { 11119 if (L.getAccess() == AS_protected) 11120 L.setAccess(AS_public); 11121 } 11122 } 11123 11124 // Create the nested-name-specifier that will be used to qualify the 11125 // reference to operator=; this is required to suppress the virtual 11126 // call mechanism. 11127 CXXScopeSpec SS; 11128 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11129 SS.MakeTrivial(S.Context, 11130 NestedNameSpecifier::Create(S.Context, nullptr, false, 11131 CanonicalT), 11132 Loc); 11133 11134 // Create the reference to operator=. 11135 ExprResult OpEqualRef 11136 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11137 SS, /*TemplateKWLoc=*/SourceLocation(), 11138 /*FirstQualifierInScope=*/nullptr, 11139 OpLookup, 11140 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11141 /*SuppressQualifierCheck=*/true); 11142 if (OpEqualRef.isInvalid()) 11143 return StmtError(); 11144 11145 // Build the call to the assignment operator. 11146 11147 Expr *FromInst = From.build(S, Loc); 11148 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11149 OpEqualRef.getAs<Expr>(), 11150 Loc, FromInst, Loc); 11151 if (Call.isInvalid()) 11152 return StmtError(); 11153 11154 // If we built a call to a trivial 'operator=' while copying an array, 11155 // bail out. We'll replace the whole shebang with a memcpy. 11156 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11157 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11158 return StmtResult((Stmt*)nullptr); 11159 11160 // Convert to an expression-statement, and clean up any produced 11161 // temporaries. 11162 return S.ActOnExprStmt(Call); 11163 } 11164 11165 // - if the subobject is of scalar type, the built-in assignment 11166 // operator is used. 11167 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11168 if (!ArrayTy) { 11169 ExprResult Assignment = S.CreateBuiltinBinOp( 11170 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11171 if (Assignment.isInvalid()) 11172 return StmtError(); 11173 return S.ActOnExprStmt(Assignment); 11174 } 11175 11176 // - if the subobject is an array, each element is assigned, in the 11177 // manner appropriate to the element type; 11178 11179 // Construct a loop over the array bounds, e.g., 11180 // 11181 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11182 // 11183 // that will copy each of the array elements. 11184 QualType SizeType = S.Context.getSizeType(); 11185 11186 // Create the iteration variable. 11187 IdentifierInfo *IterationVarName = nullptr; 11188 { 11189 SmallString<8> Str; 11190 llvm::raw_svector_ostream OS(Str); 11191 OS << "__i" << Depth; 11192 IterationVarName = &S.Context.Idents.get(OS.str()); 11193 } 11194 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11195 IterationVarName, SizeType, 11196 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11197 SC_None); 11198 11199 // Initialize the iteration variable to zero. 11200 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11201 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11202 11203 // Creates a reference to the iteration variable. 11204 RefBuilder IterationVarRef(IterationVar, SizeType); 11205 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11206 11207 // Create the DeclStmt that holds the iteration variable. 11208 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11209 11210 // Subscript the "from" and "to" expressions with the iteration variable. 11211 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11212 MoveCastBuilder FromIndexMove(FromIndexCopy); 11213 const ExprBuilder *FromIndex; 11214 if (Copying) 11215 FromIndex = &FromIndexCopy; 11216 else 11217 FromIndex = &FromIndexMove; 11218 11219 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11220 11221 // Build the copy/move for an individual element of the array. 11222 StmtResult Copy = 11223 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11224 ToIndex, *FromIndex, CopyingBaseSubobject, 11225 Copying, Depth + 1); 11226 // Bail out if copying fails or if we determined that we should use memcpy. 11227 if (Copy.isInvalid() || !Copy.get()) 11228 return Copy; 11229 11230 // Create the comparison against the array bound. 11231 llvm::APInt Upper 11232 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11233 Expr *Comparison 11234 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11235 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11236 BO_NE, S.Context.BoolTy, 11237 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11238 11239 // Create the pre-increment of the iteration variable. 11240 Expr *Increment 11241 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 11242 SizeType, VK_LValue, OK_Ordinary, Loc); 11243 11244 // Construct the loop that copies all elements of this array. 11245 return S.ActOnForStmt( 11246 Loc, Loc, InitStmt, 11247 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11248 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11249 } 11250 11251 static StmtResult 11252 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11253 const ExprBuilder &To, const ExprBuilder &From, 11254 bool CopyingBaseSubobject, bool Copying) { 11255 // Maybe we should use a memcpy? 11256 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11257 T.isTriviallyCopyableType(S.Context)) 11258 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11259 11260 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11261 CopyingBaseSubobject, 11262 Copying, 0)); 11263 11264 // If we ended up picking a trivial assignment operator for an array of a 11265 // non-trivially-copyable class type, just emit a memcpy. 11266 if (!Result.isInvalid() && !Result.get()) 11267 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11268 11269 return Result; 11270 } 11271 11272 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11273 // Note: The following rules are largely analoguous to the copy 11274 // constructor rules. Note that virtual bases are not taken into account 11275 // for determining the argument type of the operator. Note also that 11276 // operators taking an object instead of a reference are allowed. 11277 assert(ClassDecl->needsImplicitCopyAssignment()); 11278 11279 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11280 if (DSM.isAlreadyBeingDeclared()) 11281 return nullptr; 11282 11283 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11284 QualType RetType = Context.getLValueReferenceType(ArgType); 11285 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11286 if (Const) 11287 ArgType = ArgType.withConst(); 11288 ArgType = Context.getLValueReferenceType(ArgType); 11289 11290 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11291 CXXCopyAssignment, 11292 Const); 11293 11294 // An implicitly-declared copy assignment operator is an inline public 11295 // member of its class. 11296 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11297 SourceLocation ClassLoc = ClassDecl->getLocation(); 11298 DeclarationNameInfo NameInfo(Name, ClassLoc); 11299 CXXMethodDecl *CopyAssignment = 11300 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11301 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11302 /*isInline=*/true, Constexpr, SourceLocation()); 11303 CopyAssignment->setAccess(AS_public); 11304 CopyAssignment->setDefaulted(); 11305 CopyAssignment->setImplicit(); 11306 11307 if (getLangOpts().CUDA) { 11308 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11309 CopyAssignment, 11310 /* ConstRHS */ Const, 11311 /* Diagnose */ false); 11312 } 11313 11314 // Build an exception specification pointing back at this member. 11315 FunctionProtoType::ExtProtoInfo EPI = 11316 getImplicitMethodEPI(*this, CopyAssignment); 11317 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11318 11319 // Add the parameter to the operator. 11320 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11321 ClassLoc, ClassLoc, 11322 /*Id=*/nullptr, ArgType, 11323 /*TInfo=*/nullptr, SC_None, 11324 nullptr); 11325 CopyAssignment->setParams(FromParam); 11326 11327 CopyAssignment->setTrivial( 11328 ClassDecl->needsOverloadResolutionForCopyAssignment() 11329 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11330 : ClassDecl->hasTrivialCopyAssignment()); 11331 11332 // Note that we have added this copy-assignment operator. 11333 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11334 11335 Scope *S = getScopeForContext(ClassDecl); 11336 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11337 11338 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11339 SetDeclDeleted(CopyAssignment, ClassLoc); 11340 11341 if (S) 11342 PushOnScopeChains(CopyAssignment, S, false); 11343 ClassDecl->addDecl(CopyAssignment); 11344 11345 return CopyAssignment; 11346 } 11347 11348 /// Diagnose an implicit copy operation for a class which is odr-used, but 11349 /// which is deprecated because the class has a user-declared copy constructor, 11350 /// copy assignment operator, or destructor. 11351 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11352 assert(CopyOp->isImplicit()); 11353 11354 CXXRecordDecl *RD = CopyOp->getParent(); 11355 CXXMethodDecl *UserDeclaredOperation = nullptr; 11356 11357 // In Microsoft mode, assignment operations don't affect constructors and 11358 // vice versa. 11359 if (RD->hasUserDeclaredDestructor()) { 11360 UserDeclaredOperation = RD->getDestructor(); 11361 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11362 RD->hasUserDeclaredCopyConstructor() && 11363 !S.getLangOpts().MSVCCompat) { 11364 // Find any user-declared copy constructor. 11365 for (auto *I : RD->ctors()) { 11366 if (I->isCopyConstructor()) { 11367 UserDeclaredOperation = I; 11368 break; 11369 } 11370 } 11371 assert(UserDeclaredOperation); 11372 } else if (isa<CXXConstructorDecl>(CopyOp) && 11373 RD->hasUserDeclaredCopyAssignment() && 11374 !S.getLangOpts().MSVCCompat) { 11375 // Find any user-declared move assignment operator. 11376 for (auto *I : RD->methods()) { 11377 if (I->isCopyAssignmentOperator()) { 11378 UserDeclaredOperation = I; 11379 break; 11380 } 11381 } 11382 assert(UserDeclaredOperation); 11383 } 11384 11385 if (UserDeclaredOperation) { 11386 S.Diag(UserDeclaredOperation->getLocation(), 11387 diag::warn_deprecated_copy_operation) 11388 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11389 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11390 } 11391 } 11392 11393 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11394 CXXMethodDecl *CopyAssignOperator) { 11395 assert((CopyAssignOperator->isDefaulted() && 11396 CopyAssignOperator->isOverloadedOperator() && 11397 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11398 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11399 !CopyAssignOperator->isDeleted()) && 11400 "DefineImplicitCopyAssignment called for wrong function"); 11401 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11402 return; 11403 11404 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11405 if (ClassDecl->isInvalidDecl()) { 11406 CopyAssignOperator->setInvalidDecl(); 11407 return; 11408 } 11409 11410 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11411 11412 // The exception specification is needed because we are defining the 11413 // function. 11414 ResolveExceptionSpec(CurrentLocation, 11415 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11416 11417 // Add a context note for diagnostics produced after this point. 11418 Scope.addContextNote(CurrentLocation); 11419 11420 // C++11 [class.copy]p18: 11421 // The [definition of an implicitly declared copy assignment operator] is 11422 // deprecated if the class has a user-declared copy constructor or a 11423 // user-declared destructor. 11424 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11425 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11426 11427 // C++0x [class.copy]p30: 11428 // The implicitly-defined or explicitly-defaulted copy assignment operator 11429 // for a non-union class X performs memberwise copy assignment of its 11430 // subobjects. The direct base classes of X are assigned first, in the 11431 // order of their declaration in the base-specifier-list, and then the 11432 // immediate non-static data members of X are assigned, in the order in 11433 // which they were declared in the class definition. 11434 11435 // The statements that form the synthesized function body. 11436 SmallVector<Stmt*, 8> Statements; 11437 11438 // The parameter for the "other" object, which we are copying from. 11439 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11440 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11441 QualType OtherRefType = Other->getType(); 11442 if (const LValueReferenceType *OtherRef 11443 = OtherRefType->getAs<LValueReferenceType>()) { 11444 OtherRefType = OtherRef->getPointeeType(); 11445 OtherQuals = OtherRefType.getQualifiers(); 11446 } 11447 11448 // Our location for everything implicitly-generated. 11449 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11450 ? CopyAssignOperator->getLocEnd() 11451 : CopyAssignOperator->getLocation(); 11452 11453 // Builds a DeclRefExpr for the "other" object. 11454 RefBuilder OtherRef(Other, OtherRefType); 11455 11456 // Builds the "this" pointer. 11457 ThisBuilder This; 11458 11459 // Assign base classes. 11460 bool Invalid = false; 11461 for (auto &Base : ClassDecl->bases()) { 11462 // Form the assignment: 11463 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11464 QualType BaseType = Base.getType().getUnqualifiedType(); 11465 if (!BaseType->isRecordType()) { 11466 Invalid = true; 11467 continue; 11468 } 11469 11470 CXXCastPath BasePath; 11471 BasePath.push_back(&Base); 11472 11473 // Construct the "from" expression, which is an implicit cast to the 11474 // appropriately-qualified base type. 11475 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11476 VK_LValue, BasePath); 11477 11478 // Dereference "this". 11479 DerefBuilder DerefThis(This); 11480 CastBuilder To(DerefThis, 11481 Context.getCVRQualifiedType( 11482 BaseType, CopyAssignOperator->getTypeQualifiers()), 11483 VK_LValue, BasePath); 11484 11485 // Build the copy. 11486 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11487 To, From, 11488 /*CopyingBaseSubobject=*/true, 11489 /*Copying=*/true); 11490 if (Copy.isInvalid()) { 11491 CopyAssignOperator->setInvalidDecl(); 11492 return; 11493 } 11494 11495 // Success! Record the copy. 11496 Statements.push_back(Copy.getAs<Expr>()); 11497 } 11498 11499 // Assign non-static members. 11500 for (auto *Field : ClassDecl->fields()) { 11501 // FIXME: We should form some kind of AST representation for the implied 11502 // memcpy in a union copy operation. 11503 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11504 continue; 11505 11506 if (Field->isInvalidDecl()) { 11507 Invalid = true; 11508 continue; 11509 } 11510 11511 // Check for members of reference type; we can't copy those. 11512 if (Field->getType()->isReferenceType()) { 11513 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11514 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11515 Diag(Field->getLocation(), diag::note_declared_at); 11516 Invalid = true; 11517 continue; 11518 } 11519 11520 // Check for members of const-qualified, non-class type. 11521 QualType BaseType = Context.getBaseElementType(Field->getType()); 11522 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11523 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11524 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11525 Diag(Field->getLocation(), diag::note_declared_at); 11526 Invalid = true; 11527 continue; 11528 } 11529 11530 // Suppress assigning zero-width bitfields. 11531 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11532 continue; 11533 11534 QualType FieldType = Field->getType().getNonReferenceType(); 11535 if (FieldType->isIncompleteArrayType()) { 11536 assert(ClassDecl->hasFlexibleArrayMember() && 11537 "Incomplete array type is not valid"); 11538 continue; 11539 } 11540 11541 // Build references to the field in the object we're copying from and to. 11542 CXXScopeSpec SS; // Intentionally empty 11543 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11544 LookupMemberName); 11545 MemberLookup.addDecl(Field); 11546 MemberLookup.resolveKind(); 11547 11548 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11549 11550 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11551 11552 // Build the copy of this field. 11553 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11554 To, From, 11555 /*CopyingBaseSubobject=*/false, 11556 /*Copying=*/true); 11557 if (Copy.isInvalid()) { 11558 CopyAssignOperator->setInvalidDecl(); 11559 return; 11560 } 11561 11562 // Success! Record the copy. 11563 Statements.push_back(Copy.getAs<Stmt>()); 11564 } 11565 11566 if (!Invalid) { 11567 // Add a "return *this;" 11568 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11569 11570 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11571 if (Return.isInvalid()) 11572 Invalid = true; 11573 else 11574 Statements.push_back(Return.getAs<Stmt>()); 11575 } 11576 11577 if (Invalid) { 11578 CopyAssignOperator->setInvalidDecl(); 11579 return; 11580 } 11581 11582 StmtResult Body; 11583 { 11584 CompoundScopeRAII CompoundScope(*this); 11585 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11586 /*isStmtExpr=*/false); 11587 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11588 } 11589 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11590 CopyAssignOperator->markUsed(Context); 11591 11592 if (ASTMutationListener *L = getASTMutationListener()) { 11593 L->CompletedImplicitDefinition(CopyAssignOperator); 11594 } 11595 } 11596 11597 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11598 assert(ClassDecl->needsImplicitMoveAssignment()); 11599 11600 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11601 if (DSM.isAlreadyBeingDeclared()) 11602 return nullptr; 11603 11604 // Note: The following rules are largely analoguous to the move 11605 // constructor rules. 11606 11607 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11608 QualType RetType = Context.getLValueReferenceType(ArgType); 11609 ArgType = Context.getRValueReferenceType(ArgType); 11610 11611 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11612 CXXMoveAssignment, 11613 false); 11614 11615 // An implicitly-declared move assignment operator is an inline public 11616 // member of its class. 11617 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11618 SourceLocation ClassLoc = ClassDecl->getLocation(); 11619 DeclarationNameInfo NameInfo(Name, ClassLoc); 11620 CXXMethodDecl *MoveAssignment = 11621 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11622 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11623 /*isInline=*/true, Constexpr, SourceLocation()); 11624 MoveAssignment->setAccess(AS_public); 11625 MoveAssignment->setDefaulted(); 11626 MoveAssignment->setImplicit(); 11627 11628 if (getLangOpts().CUDA) { 11629 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11630 MoveAssignment, 11631 /* ConstRHS */ false, 11632 /* Diagnose */ false); 11633 } 11634 11635 // Build an exception specification pointing back at this member. 11636 FunctionProtoType::ExtProtoInfo EPI = 11637 getImplicitMethodEPI(*this, MoveAssignment); 11638 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11639 11640 // Add the parameter to the operator. 11641 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11642 ClassLoc, ClassLoc, 11643 /*Id=*/nullptr, ArgType, 11644 /*TInfo=*/nullptr, SC_None, 11645 nullptr); 11646 MoveAssignment->setParams(FromParam); 11647 11648 MoveAssignment->setTrivial( 11649 ClassDecl->needsOverloadResolutionForMoveAssignment() 11650 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11651 : ClassDecl->hasTrivialMoveAssignment()); 11652 11653 // Note that we have added this copy-assignment operator. 11654 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11655 11656 Scope *S = getScopeForContext(ClassDecl); 11657 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11658 11659 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11660 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11661 SetDeclDeleted(MoveAssignment, ClassLoc); 11662 } 11663 11664 if (S) 11665 PushOnScopeChains(MoveAssignment, S, false); 11666 ClassDecl->addDecl(MoveAssignment); 11667 11668 return MoveAssignment; 11669 } 11670 11671 /// Check if we're implicitly defining a move assignment operator for a class 11672 /// with virtual bases. Such a move assignment might move-assign the virtual 11673 /// base multiple times. 11674 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11675 SourceLocation CurrentLocation) { 11676 assert(!Class->isDependentContext() && "should not define dependent move"); 11677 11678 // Only a virtual base could get implicitly move-assigned multiple times. 11679 // Only a non-trivial move assignment can observe this. We only want to 11680 // diagnose if we implicitly define an assignment operator that assigns 11681 // two base classes, both of which move-assign the same virtual base. 11682 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11683 Class->getNumBases() < 2) 11684 return; 11685 11686 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11687 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11688 VBaseMap VBases; 11689 11690 for (auto &BI : Class->bases()) { 11691 Worklist.push_back(&BI); 11692 while (!Worklist.empty()) { 11693 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11694 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11695 11696 // If the base has no non-trivial move assignment operators, 11697 // we don't care about moves from it. 11698 if (!Base->hasNonTrivialMoveAssignment()) 11699 continue; 11700 11701 // If there's nothing virtual here, skip it. 11702 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11703 continue; 11704 11705 // If we're not actually going to call a move assignment for this base, 11706 // or the selected move assignment is trivial, skip it. 11707 Sema::SpecialMemberOverloadResult SMOR = 11708 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11709 /*ConstArg*/false, /*VolatileArg*/false, 11710 /*RValueThis*/true, /*ConstThis*/false, 11711 /*VolatileThis*/false); 11712 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 11713 !SMOR.getMethod()->isMoveAssignmentOperator()) 11714 continue; 11715 11716 if (BaseSpec->isVirtual()) { 11717 // We're going to move-assign this virtual base, and its move 11718 // assignment operator is not trivial. If this can happen for 11719 // multiple distinct direct bases of Class, diagnose it. (If it 11720 // only happens in one base, we'll diagnose it when synthesizing 11721 // that base class's move assignment operator.) 11722 CXXBaseSpecifier *&Existing = 11723 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11724 .first->second; 11725 if (Existing && Existing != &BI) { 11726 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11727 << Class << Base; 11728 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11729 << (Base->getCanonicalDecl() == 11730 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11731 << Base << Existing->getType() << Existing->getSourceRange(); 11732 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11733 << (Base->getCanonicalDecl() == 11734 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11735 << Base << BI.getType() << BaseSpec->getSourceRange(); 11736 11737 // Only diagnose each vbase once. 11738 Existing = nullptr; 11739 } 11740 } else { 11741 // Only walk over bases that have defaulted move assignment operators. 11742 // We assume that any user-provided move assignment operator handles 11743 // the multiple-moves-of-vbase case itself somehow. 11744 if (!SMOR.getMethod()->isDefaulted()) 11745 continue; 11746 11747 // We're going to move the base classes of Base. Add them to the list. 11748 for (auto &BI : Base->bases()) 11749 Worklist.push_back(&BI); 11750 } 11751 } 11752 } 11753 } 11754 11755 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11756 CXXMethodDecl *MoveAssignOperator) { 11757 assert((MoveAssignOperator->isDefaulted() && 11758 MoveAssignOperator->isOverloadedOperator() && 11759 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11760 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11761 !MoveAssignOperator->isDeleted()) && 11762 "DefineImplicitMoveAssignment called for wrong function"); 11763 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 11764 return; 11765 11766 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11767 if (ClassDecl->isInvalidDecl()) { 11768 MoveAssignOperator->setInvalidDecl(); 11769 return; 11770 } 11771 11772 // C++0x [class.copy]p28: 11773 // The implicitly-defined or move assignment operator for a non-union class 11774 // X performs memberwise move assignment of its subobjects. The direct base 11775 // classes of X are assigned first, in the order of their declaration in the 11776 // base-specifier-list, and then the immediate non-static data members of X 11777 // are assigned, in the order in which they were declared in the class 11778 // definition. 11779 11780 // Issue a warning if our implicit move assignment operator will move 11781 // from a virtual base more than once. 11782 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11783 11784 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11785 11786 // The exception specification is needed because we are defining the 11787 // function. 11788 ResolveExceptionSpec(CurrentLocation, 11789 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11790 11791 // Add a context note for diagnostics produced after this point. 11792 Scope.addContextNote(CurrentLocation); 11793 11794 // The statements that form the synthesized function body. 11795 SmallVector<Stmt*, 8> Statements; 11796 11797 // The parameter for the "other" object, which we are move from. 11798 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11799 QualType OtherRefType = Other->getType()-> 11800 getAs<RValueReferenceType>()->getPointeeType(); 11801 assert(!OtherRefType.getQualifiers() && 11802 "Bad argument type of defaulted move assignment"); 11803 11804 // Our location for everything implicitly-generated. 11805 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11806 ? MoveAssignOperator->getLocEnd() 11807 : MoveAssignOperator->getLocation(); 11808 11809 // Builds a reference to the "other" object. 11810 RefBuilder OtherRef(Other, OtherRefType); 11811 // Cast to rvalue. 11812 MoveCastBuilder MoveOther(OtherRef); 11813 11814 // Builds the "this" pointer. 11815 ThisBuilder This; 11816 11817 // Assign base classes. 11818 bool Invalid = false; 11819 for (auto &Base : ClassDecl->bases()) { 11820 // C++11 [class.copy]p28: 11821 // It is unspecified whether subobjects representing virtual base classes 11822 // are assigned more than once by the implicitly-defined copy assignment 11823 // operator. 11824 // FIXME: Do not assign to a vbase that will be assigned by some other base 11825 // class. For a move-assignment, this can result in the vbase being moved 11826 // multiple times. 11827 11828 // Form the assignment: 11829 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11830 QualType BaseType = Base.getType().getUnqualifiedType(); 11831 if (!BaseType->isRecordType()) { 11832 Invalid = true; 11833 continue; 11834 } 11835 11836 CXXCastPath BasePath; 11837 BasePath.push_back(&Base); 11838 11839 // Construct the "from" expression, which is an implicit cast to the 11840 // appropriately-qualified base type. 11841 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11842 11843 // Dereference "this". 11844 DerefBuilder DerefThis(This); 11845 11846 // Implicitly cast "this" to the appropriately-qualified base type. 11847 CastBuilder To(DerefThis, 11848 Context.getCVRQualifiedType( 11849 BaseType, MoveAssignOperator->getTypeQualifiers()), 11850 VK_LValue, BasePath); 11851 11852 // Build the move. 11853 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11854 To, From, 11855 /*CopyingBaseSubobject=*/true, 11856 /*Copying=*/false); 11857 if (Move.isInvalid()) { 11858 MoveAssignOperator->setInvalidDecl(); 11859 return; 11860 } 11861 11862 // Success! Record the move. 11863 Statements.push_back(Move.getAs<Expr>()); 11864 } 11865 11866 // Assign non-static members. 11867 for (auto *Field : ClassDecl->fields()) { 11868 // FIXME: We should form some kind of AST representation for the implied 11869 // memcpy in a union copy operation. 11870 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11871 continue; 11872 11873 if (Field->isInvalidDecl()) { 11874 Invalid = true; 11875 continue; 11876 } 11877 11878 // Check for members of reference type; we can't move those. 11879 if (Field->getType()->isReferenceType()) { 11880 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11881 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11882 Diag(Field->getLocation(), diag::note_declared_at); 11883 Invalid = true; 11884 continue; 11885 } 11886 11887 // Check for members of const-qualified, non-class type. 11888 QualType BaseType = Context.getBaseElementType(Field->getType()); 11889 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11890 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11891 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11892 Diag(Field->getLocation(), diag::note_declared_at); 11893 Invalid = true; 11894 continue; 11895 } 11896 11897 // Suppress assigning zero-width bitfields. 11898 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11899 continue; 11900 11901 QualType FieldType = Field->getType().getNonReferenceType(); 11902 if (FieldType->isIncompleteArrayType()) { 11903 assert(ClassDecl->hasFlexibleArrayMember() && 11904 "Incomplete array type is not valid"); 11905 continue; 11906 } 11907 11908 // Build references to the field in the object we're copying from and to. 11909 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11910 LookupMemberName); 11911 MemberLookup.addDecl(Field); 11912 MemberLookup.resolveKind(); 11913 MemberBuilder From(MoveOther, OtherRefType, 11914 /*IsArrow=*/false, MemberLookup); 11915 MemberBuilder To(This, getCurrentThisType(), 11916 /*IsArrow=*/true, MemberLookup); 11917 11918 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 11919 "Member reference with rvalue base must be rvalue except for reference " 11920 "members, which aren't allowed for move assignment."); 11921 11922 // Build the move of this field. 11923 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 11924 To, From, 11925 /*CopyingBaseSubobject=*/false, 11926 /*Copying=*/false); 11927 if (Move.isInvalid()) { 11928 MoveAssignOperator->setInvalidDecl(); 11929 return; 11930 } 11931 11932 // Success! Record the copy. 11933 Statements.push_back(Move.getAs<Stmt>()); 11934 } 11935 11936 if (!Invalid) { 11937 // Add a "return *this;" 11938 ExprResult ThisObj = 11939 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11940 11941 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11942 if (Return.isInvalid()) 11943 Invalid = true; 11944 else 11945 Statements.push_back(Return.getAs<Stmt>()); 11946 } 11947 11948 if (Invalid) { 11949 MoveAssignOperator->setInvalidDecl(); 11950 return; 11951 } 11952 11953 StmtResult Body; 11954 { 11955 CompoundScopeRAII CompoundScope(*this); 11956 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11957 /*isStmtExpr=*/false); 11958 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11959 } 11960 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 11961 MoveAssignOperator->markUsed(Context); 11962 11963 if (ASTMutationListener *L = getASTMutationListener()) { 11964 L->CompletedImplicitDefinition(MoveAssignOperator); 11965 } 11966 } 11967 11968 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 11969 CXXRecordDecl *ClassDecl) { 11970 // C++ [class.copy]p4: 11971 // If the class definition does not explicitly declare a copy 11972 // constructor, one is declared implicitly. 11973 assert(ClassDecl->needsImplicitCopyConstructor()); 11974 11975 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 11976 if (DSM.isAlreadyBeingDeclared()) 11977 return nullptr; 11978 11979 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11980 QualType ArgType = ClassType; 11981 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 11982 if (Const) 11983 ArgType = ArgType.withConst(); 11984 ArgType = Context.getLValueReferenceType(ArgType); 11985 11986 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11987 CXXCopyConstructor, 11988 Const); 11989 11990 DeclarationName Name 11991 = Context.DeclarationNames.getCXXConstructorName( 11992 Context.getCanonicalType(ClassType)); 11993 SourceLocation ClassLoc = ClassDecl->getLocation(); 11994 DeclarationNameInfo NameInfo(Name, ClassLoc); 11995 11996 // An implicitly-declared copy constructor is an inline public 11997 // member of its class. 11998 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 11999 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12000 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12001 Constexpr); 12002 CopyConstructor->setAccess(AS_public); 12003 CopyConstructor->setDefaulted(); 12004 12005 if (getLangOpts().CUDA) { 12006 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12007 CopyConstructor, 12008 /* ConstRHS */ Const, 12009 /* Diagnose */ false); 12010 } 12011 12012 // Build an exception specification pointing back at this member. 12013 FunctionProtoType::ExtProtoInfo EPI = 12014 getImplicitMethodEPI(*this, CopyConstructor); 12015 CopyConstructor->setType( 12016 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12017 12018 // Add the parameter to the constructor. 12019 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12020 ClassLoc, ClassLoc, 12021 /*IdentifierInfo=*/nullptr, 12022 ArgType, /*TInfo=*/nullptr, 12023 SC_None, nullptr); 12024 CopyConstructor->setParams(FromParam); 12025 12026 CopyConstructor->setTrivial( 12027 ClassDecl->needsOverloadResolutionForCopyConstructor() 12028 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12029 : ClassDecl->hasTrivialCopyConstructor()); 12030 12031 // Note that we have declared this constructor. 12032 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12033 12034 Scope *S = getScopeForContext(ClassDecl); 12035 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12036 12037 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12038 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12039 SetDeclDeleted(CopyConstructor, ClassLoc); 12040 } 12041 12042 if (S) 12043 PushOnScopeChains(CopyConstructor, S, false); 12044 ClassDecl->addDecl(CopyConstructor); 12045 12046 return CopyConstructor; 12047 } 12048 12049 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12050 CXXConstructorDecl *CopyConstructor) { 12051 assert((CopyConstructor->isDefaulted() && 12052 CopyConstructor->isCopyConstructor() && 12053 !CopyConstructor->doesThisDeclarationHaveABody() && 12054 !CopyConstructor->isDeleted()) && 12055 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12056 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12057 return; 12058 12059 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12060 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12061 12062 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12063 12064 // The exception specification is needed because we are defining the 12065 // function. 12066 ResolveExceptionSpec(CurrentLocation, 12067 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12068 MarkVTableUsed(CurrentLocation, ClassDecl); 12069 12070 // Add a context note for diagnostics produced after this point. 12071 Scope.addContextNote(CurrentLocation); 12072 12073 // C++11 [class.copy]p7: 12074 // The [definition of an implicitly declared copy constructor] is 12075 // deprecated if the class has a user-declared copy assignment operator 12076 // or a user-declared destructor. 12077 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12078 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12079 12080 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12081 CopyConstructor->setInvalidDecl(); 12082 } else { 12083 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 12084 ? CopyConstructor->getLocEnd() 12085 : CopyConstructor->getLocation(); 12086 Sema::CompoundScopeRAII CompoundScope(*this); 12087 CopyConstructor->setBody( 12088 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12089 CopyConstructor->markUsed(Context); 12090 } 12091 12092 if (ASTMutationListener *L = getASTMutationListener()) { 12093 L->CompletedImplicitDefinition(CopyConstructor); 12094 } 12095 } 12096 12097 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12098 CXXRecordDecl *ClassDecl) { 12099 assert(ClassDecl->needsImplicitMoveConstructor()); 12100 12101 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12102 if (DSM.isAlreadyBeingDeclared()) 12103 return nullptr; 12104 12105 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12106 QualType ArgType = Context.getRValueReferenceType(ClassType); 12107 12108 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12109 CXXMoveConstructor, 12110 false); 12111 12112 DeclarationName Name 12113 = Context.DeclarationNames.getCXXConstructorName( 12114 Context.getCanonicalType(ClassType)); 12115 SourceLocation ClassLoc = ClassDecl->getLocation(); 12116 DeclarationNameInfo NameInfo(Name, ClassLoc); 12117 12118 // C++11 [class.copy]p11: 12119 // An implicitly-declared copy/move constructor is an inline public 12120 // member of its class. 12121 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12122 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12123 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12124 Constexpr); 12125 MoveConstructor->setAccess(AS_public); 12126 MoveConstructor->setDefaulted(); 12127 12128 if (getLangOpts().CUDA) { 12129 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12130 MoveConstructor, 12131 /* ConstRHS */ false, 12132 /* Diagnose */ false); 12133 } 12134 12135 // Build an exception specification pointing back at this member. 12136 FunctionProtoType::ExtProtoInfo EPI = 12137 getImplicitMethodEPI(*this, MoveConstructor); 12138 MoveConstructor->setType( 12139 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12140 12141 // Add the parameter to the constructor. 12142 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12143 ClassLoc, ClassLoc, 12144 /*IdentifierInfo=*/nullptr, 12145 ArgType, /*TInfo=*/nullptr, 12146 SC_None, nullptr); 12147 MoveConstructor->setParams(FromParam); 12148 12149 MoveConstructor->setTrivial( 12150 ClassDecl->needsOverloadResolutionForMoveConstructor() 12151 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12152 : ClassDecl->hasTrivialMoveConstructor()); 12153 12154 // Note that we have declared this constructor. 12155 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12156 12157 Scope *S = getScopeForContext(ClassDecl); 12158 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12159 12160 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12161 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12162 SetDeclDeleted(MoveConstructor, ClassLoc); 12163 } 12164 12165 if (S) 12166 PushOnScopeChains(MoveConstructor, S, false); 12167 ClassDecl->addDecl(MoveConstructor); 12168 12169 return MoveConstructor; 12170 } 12171 12172 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12173 CXXConstructorDecl *MoveConstructor) { 12174 assert((MoveConstructor->isDefaulted() && 12175 MoveConstructor->isMoveConstructor() && 12176 !MoveConstructor->doesThisDeclarationHaveABody() && 12177 !MoveConstructor->isDeleted()) && 12178 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12179 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12180 return; 12181 12182 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12183 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12184 12185 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12186 12187 // The exception specification is needed because we are defining the 12188 // function. 12189 ResolveExceptionSpec(CurrentLocation, 12190 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12191 MarkVTableUsed(CurrentLocation, ClassDecl); 12192 12193 // Add a context note for diagnostics produced after this point. 12194 Scope.addContextNote(CurrentLocation); 12195 12196 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12197 MoveConstructor->setInvalidDecl(); 12198 } else { 12199 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12200 ? MoveConstructor->getLocEnd() 12201 : MoveConstructor->getLocation(); 12202 Sema::CompoundScopeRAII CompoundScope(*this); 12203 MoveConstructor->setBody(ActOnCompoundStmt( 12204 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12205 MoveConstructor->markUsed(Context); 12206 } 12207 12208 if (ASTMutationListener *L = getASTMutationListener()) { 12209 L->CompletedImplicitDefinition(MoveConstructor); 12210 } 12211 } 12212 12213 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12214 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12215 } 12216 12217 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12218 SourceLocation CurrentLocation, 12219 CXXConversionDecl *Conv) { 12220 SynthesizedFunctionScope Scope(*this, Conv); 12221 12222 CXXRecordDecl *Lambda = Conv->getParent(); 12223 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 12224 // If we are defining a specialization of a conversion to function-ptr 12225 // cache the deduced template arguments for this specialization 12226 // so that we can use them to retrieve the corresponding call-operator 12227 // and static-invoker. 12228 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 12229 12230 // Retrieve the corresponding call-operator specialization. 12231 if (Lambda->isGenericLambda()) { 12232 assert(Conv->isFunctionTemplateSpecialization()); 12233 FunctionTemplateDecl *CallOpTemplate = 12234 CallOp->getDescribedFunctionTemplate(); 12235 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 12236 void *InsertPos = nullptr; 12237 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 12238 DeducedTemplateArgs->asArray(), 12239 InsertPos); 12240 assert(CallOpSpec && 12241 "Conversion operator must have a corresponding call operator"); 12242 CallOp = cast<CXXMethodDecl>(CallOpSpec); 12243 } 12244 12245 // Mark the call operator referenced (and add to pending instantiations 12246 // if necessary). 12247 // For both the conversion and static-invoker template specializations 12248 // we construct their body's in this function, so no need to add them 12249 // to the PendingInstantiations. 12250 MarkFunctionReferenced(CurrentLocation, CallOp); 12251 12252 // Retrieve the static invoker... 12253 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12254 // ... and get the corresponding specialization for a generic lambda. 12255 if (Lambda->isGenericLambda()) { 12256 assert(DeducedTemplateArgs && 12257 "Must have deduced template arguments from Conversion Operator"); 12258 FunctionTemplateDecl *InvokeTemplate = 12259 Invoker->getDescribedFunctionTemplate(); 12260 void *InsertPos = nullptr; 12261 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 12262 DeducedTemplateArgs->asArray(), 12263 InsertPos); 12264 assert(InvokeSpec && 12265 "Must have a corresponding static invoker specialization"); 12266 Invoker = cast<CXXMethodDecl>(InvokeSpec); 12267 } 12268 // Construct the body of the conversion function { return __invoke; }. 12269 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12270 VK_LValue, Conv->getLocation()).get(); 12271 assert(FunctionRef && "Can't refer to __invoke function?"); 12272 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12273 Conv->setBody(new (Context) CompoundStmt(Context, Return, 12274 Conv->getLocation(), 12275 Conv->getLocation())); 12276 12277 Conv->markUsed(Context); 12278 Conv->setReferenced(); 12279 12280 // Fill in the __invoke function with a dummy implementation. IR generation 12281 // will fill in the actual details. 12282 Invoker->markUsed(Context); 12283 Invoker->setReferenced(); 12284 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12285 12286 if (ASTMutationListener *L = getASTMutationListener()) { 12287 L->CompletedImplicitDefinition(Conv); 12288 L->CompletedImplicitDefinition(Invoker); 12289 } 12290 } 12291 12292 12293 12294 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12295 SourceLocation CurrentLocation, 12296 CXXConversionDecl *Conv) 12297 { 12298 assert(!Conv->getParent()->isGenericLambda()); 12299 12300 SynthesizedFunctionScope Scope(*this, Conv); 12301 12302 // Copy-initialize the lambda object as needed to capture it. 12303 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12304 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12305 12306 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12307 Conv->getLocation(), 12308 Conv, DerefThis); 12309 12310 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12311 // behavior. Note that only the general conversion function does this 12312 // (since it's unusable otherwise); in the case where we inline the 12313 // block literal, it has block literal lifetime semantics. 12314 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12315 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12316 CK_CopyAndAutoreleaseBlockObject, 12317 BuildBlock.get(), nullptr, VK_RValue); 12318 12319 if (BuildBlock.isInvalid()) { 12320 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12321 Conv->setInvalidDecl(); 12322 return; 12323 } 12324 12325 // Create the return statement that returns the block from the conversion 12326 // function. 12327 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12328 if (Return.isInvalid()) { 12329 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12330 Conv->setInvalidDecl(); 12331 return; 12332 } 12333 12334 // Set the body of the conversion function. 12335 Stmt *ReturnS = Return.get(); 12336 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 12337 Conv->getLocation(), 12338 Conv->getLocation())); 12339 Conv->markUsed(Context); 12340 12341 // We're done; notify the mutation listener, if any. 12342 if (ASTMutationListener *L = getASTMutationListener()) { 12343 L->CompletedImplicitDefinition(Conv); 12344 } 12345 } 12346 12347 /// \brief Determine whether the given list arguments contains exactly one 12348 /// "real" (non-default) argument. 12349 static bool hasOneRealArgument(MultiExprArg Args) { 12350 switch (Args.size()) { 12351 case 0: 12352 return false; 12353 12354 default: 12355 if (!Args[1]->isDefaultArgument()) 12356 return false; 12357 12358 // fall through 12359 case 1: 12360 return !Args[0]->isDefaultArgument(); 12361 } 12362 12363 return false; 12364 } 12365 12366 ExprResult 12367 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12368 NamedDecl *FoundDecl, 12369 CXXConstructorDecl *Constructor, 12370 MultiExprArg ExprArgs, 12371 bool HadMultipleCandidates, 12372 bool IsListInitialization, 12373 bool IsStdInitListInitialization, 12374 bool RequiresZeroInit, 12375 unsigned ConstructKind, 12376 SourceRange ParenRange) { 12377 bool Elidable = false; 12378 12379 // C++0x [class.copy]p34: 12380 // When certain criteria are met, an implementation is allowed to 12381 // omit the copy/move construction of a class object, even if the 12382 // copy/move constructor and/or destructor for the object have 12383 // side effects. [...] 12384 // - when a temporary class object that has not been bound to a 12385 // reference (12.2) would be copied/moved to a class object 12386 // with the same cv-unqualified type, the copy/move operation 12387 // can be omitted by constructing the temporary object 12388 // directly into the target of the omitted copy/move 12389 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12390 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12391 Expr *SubExpr = ExprArgs[0]; 12392 Elidable = SubExpr->isTemporaryObject( 12393 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12394 } 12395 12396 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12397 FoundDecl, Constructor, 12398 Elidable, ExprArgs, HadMultipleCandidates, 12399 IsListInitialization, 12400 IsStdInitListInitialization, RequiresZeroInit, 12401 ConstructKind, ParenRange); 12402 } 12403 12404 ExprResult 12405 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12406 NamedDecl *FoundDecl, 12407 CXXConstructorDecl *Constructor, 12408 bool Elidable, 12409 MultiExprArg ExprArgs, 12410 bool HadMultipleCandidates, 12411 bool IsListInitialization, 12412 bool IsStdInitListInitialization, 12413 bool RequiresZeroInit, 12414 unsigned ConstructKind, 12415 SourceRange ParenRange) { 12416 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12417 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12418 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12419 return ExprError(); 12420 } 12421 12422 return BuildCXXConstructExpr( 12423 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12424 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12425 RequiresZeroInit, ConstructKind, ParenRange); 12426 } 12427 12428 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12429 /// including handling of its default argument expressions. 12430 ExprResult 12431 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12432 CXXConstructorDecl *Constructor, 12433 bool Elidable, 12434 MultiExprArg ExprArgs, 12435 bool HadMultipleCandidates, 12436 bool IsListInitialization, 12437 bool IsStdInitListInitialization, 12438 bool RequiresZeroInit, 12439 unsigned ConstructKind, 12440 SourceRange ParenRange) { 12441 assert(declaresSameEntity( 12442 Constructor->getParent(), 12443 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12444 "given constructor for wrong type"); 12445 MarkFunctionReferenced(ConstructLoc, Constructor); 12446 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12447 return ExprError(); 12448 12449 return CXXConstructExpr::Create( 12450 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12451 ExprArgs, HadMultipleCandidates, IsListInitialization, 12452 IsStdInitListInitialization, RequiresZeroInit, 12453 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12454 ParenRange); 12455 } 12456 12457 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12458 assert(Field->hasInClassInitializer()); 12459 12460 // If we already have the in-class initializer nothing needs to be done. 12461 if (Field->getInClassInitializer()) 12462 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12463 12464 // If we might have already tried and failed to instantiate, don't try again. 12465 if (Field->isInvalidDecl()) 12466 return ExprError(); 12467 12468 // Maybe we haven't instantiated the in-class initializer. Go check the 12469 // pattern FieldDecl to see if it has one. 12470 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12471 12472 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12473 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12474 DeclContext::lookup_result Lookup = 12475 ClassPattern->lookup(Field->getDeclName()); 12476 12477 // Lookup can return at most two results: the pattern for the field, or the 12478 // injected class name of the parent record. No other member can have the 12479 // same name as the field. 12480 // In modules mode, lookup can return multiple results (coming from 12481 // different modules). 12482 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12483 "more than two lookup results for field name"); 12484 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12485 if (!Pattern) { 12486 assert(isa<CXXRecordDecl>(Lookup[0]) && 12487 "cannot have other non-field member with same name"); 12488 for (auto L : Lookup) 12489 if (isa<FieldDecl>(L)) { 12490 Pattern = cast<FieldDecl>(L); 12491 break; 12492 } 12493 assert(Pattern && "We must have set the Pattern!"); 12494 } 12495 12496 if (!Pattern->hasInClassInitializer() || 12497 InstantiateInClassInitializer(Loc, Field, Pattern, 12498 getTemplateInstantiationArgs(Field))) { 12499 // Don't diagnose this again. 12500 Field->setInvalidDecl(); 12501 return ExprError(); 12502 } 12503 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12504 } 12505 12506 // DR1351: 12507 // If the brace-or-equal-initializer of a non-static data member 12508 // invokes a defaulted default constructor of its class or of an 12509 // enclosing class in a potentially evaluated subexpression, the 12510 // program is ill-formed. 12511 // 12512 // This resolution is unworkable: the exception specification of the 12513 // default constructor can be needed in an unevaluated context, in 12514 // particular, in the operand of a noexcept-expression, and we can be 12515 // unable to compute an exception specification for an enclosed class. 12516 // 12517 // Any attempt to resolve the exception specification of a defaulted default 12518 // constructor before the initializer is lexically complete will ultimately 12519 // come here at which point we can diagnose it. 12520 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12521 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12522 << OutermostClass << Field; 12523 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12524 // Recover by marking the field invalid, unless we're in a SFINAE context. 12525 if (!isSFINAEContext()) 12526 Field->setInvalidDecl(); 12527 return ExprError(); 12528 } 12529 12530 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12531 if (VD->isInvalidDecl()) return; 12532 12533 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12534 if (ClassDecl->isInvalidDecl()) return; 12535 if (ClassDecl->hasIrrelevantDestructor()) return; 12536 if (ClassDecl->isDependentContext()) return; 12537 12538 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12539 MarkFunctionReferenced(VD->getLocation(), Destructor); 12540 CheckDestructorAccess(VD->getLocation(), Destructor, 12541 PDiag(diag::err_access_dtor_var) 12542 << VD->getDeclName() 12543 << VD->getType()); 12544 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12545 12546 if (Destructor->isTrivial()) return; 12547 if (!VD->hasGlobalStorage()) return; 12548 12549 // Emit warning for non-trivial dtor in global scope (a real global, 12550 // class-static, function-static). 12551 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12552 12553 // TODO: this should be re-enabled for static locals by !CXAAtExit 12554 if (!VD->isStaticLocal()) 12555 Diag(VD->getLocation(), diag::warn_global_destructor); 12556 } 12557 12558 /// \brief Given a constructor and the set of arguments provided for the 12559 /// constructor, convert the arguments and add any required default arguments 12560 /// to form a proper call to this constructor. 12561 /// 12562 /// \returns true if an error occurred, false otherwise. 12563 bool 12564 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12565 MultiExprArg ArgsPtr, 12566 SourceLocation Loc, 12567 SmallVectorImpl<Expr*> &ConvertedArgs, 12568 bool AllowExplicit, 12569 bool IsListInitialization) { 12570 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12571 unsigned NumArgs = ArgsPtr.size(); 12572 Expr **Args = ArgsPtr.data(); 12573 12574 const FunctionProtoType *Proto 12575 = Constructor->getType()->getAs<FunctionProtoType>(); 12576 assert(Proto && "Constructor without a prototype?"); 12577 unsigned NumParams = Proto->getNumParams(); 12578 12579 // If too few arguments are available, we'll fill in the rest with defaults. 12580 if (NumArgs < NumParams) 12581 ConvertedArgs.reserve(NumParams); 12582 else 12583 ConvertedArgs.reserve(NumArgs); 12584 12585 VariadicCallType CallType = 12586 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12587 SmallVector<Expr *, 8> AllArgs; 12588 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12589 Proto, 0, 12590 llvm::makeArrayRef(Args, NumArgs), 12591 AllArgs, 12592 CallType, AllowExplicit, 12593 IsListInitialization); 12594 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12595 12596 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12597 12598 CheckConstructorCall(Constructor, 12599 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12600 Proto, Loc); 12601 12602 return Invalid; 12603 } 12604 12605 static inline bool 12606 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12607 const FunctionDecl *FnDecl) { 12608 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12609 if (isa<NamespaceDecl>(DC)) { 12610 return SemaRef.Diag(FnDecl->getLocation(), 12611 diag::err_operator_new_delete_declared_in_namespace) 12612 << FnDecl->getDeclName(); 12613 } 12614 12615 if (isa<TranslationUnitDecl>(DC) && 12616 FnDecl->getStorageClass() == SC_Static) { 12617 return SemaRef.Diag(FnDecl->getLocation(), 12618 diag::err_operator_new_delete_declared_static) 12619 << FnDecl->getDeclName(); 12620 } 12621 12622 return false; 12623 } 12624 12625 static inline bool 12626 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12627 CanQualType ExpectedResultType, 12628 CanQualType ExpectedFirstParamType, 12629 unsigned DependentParamTypeDiag, 12630 unsigned InvalidParamTypeDiag) { 12631 QualType ResultType = 12632 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12633 12634 // Check that the result type is not dependent. 12635 if (ResultType->isDependentType()) 12636 return SemaRef.Diag(FnDecl->getLocation(), 12637 diag::err_operator_new_delete_dependent_result_type) 12638 << FnDecl->getDeclName() << ExpectedResultType; 12639 12640 // Check that the result type is what we expect. 12641 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12642 return SemaRef.Diag(FnDecl->getLocation(), 12643 diag::err_operator_new_delete_invalid_result_type) 12644 << FnDecl->getDeclName() << ExpectedResultType; 12645 12646 // A function template must have at least 2 parameters. 12647 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12648 return SemaRef.Diag(FnDecl->getLocation(), 12649 diag::err_operator_new_delete_template_too_few_parameters) 12650 << FnDecl->getDeclName(); 12651 12652 // The function decl must have at least 1 parameter. 12653 if (FnDecl->getNumParams() == 0) 12654 return SemaRef.Diag(FnDecl->getLocation(), 12655 diag::err_operator_new_delete_too_few_parameters) 12656 << FnDecl->getDeclName(); 12657 12658 // Check the first parameter type is not dependent. 12659 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12660 if (FirstParamType->isDependentType()) 12661 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12662 << FnDecl->getDeclName() << ExpectedFirstParamType; 12663 12664 // Check that the first parameter type is what we expect. 12665 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12666 ExpectedFirstParamType) 12667 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12668 << FnDecl->getDeclName() << ExpectedFirstParamType; 12669 12670 return false; 12671 } 12672 12673 static bool 12674 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12675 // C++ [basic.stc.dynamic.allocation]p1: 12676 // A program is ill-formed if an allocation function is declared in a 12677 // namespace scope other than global scope or declared static in global 12678 // scope. 12679 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12680 return true; 12681 12682 CanQualType SizeTy = 12683 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12684 12685 // C++ [basic.stc.dynamic.allocation]p1: 12686 // The return type shall be void*. The first parameter shall have type 12687 // std::size_t. 12688 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12689 SizeTy, 12690 diag::err_operator_new_dependent_param_type, 12691 diag::err_operator_new_param_type)) 12692 return true; 12693 12694 // C++ [basic.stc.dynamic.allocation]p1: 12695 // The first parameter shall not have an associated default argument. 12696 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12697 return SemaRef.Diag(FnDecl->getLocation(), 12698 diag::err_operator_new_default_arg) 12699 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12700 12701 return false; 12702 } 12703 12704 static bool 12705 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12706 // C++ [basic.stc.dynamic.deallocation]p1: 12707 // A program is ill-formed if deallocation functions are declared in a 12708 // namespace scope other than global scope or declared static in global 12709 // scope. 12710 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12711 return true; 12712 12713 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 12714 12715 // C++ P0722: 12716 // Within a class C, the first parameter of a destroying operator delete 12717 // shall be of type C *. The first parameter of any other deallocation 12718 // function shall be of type void *. 12719 CanQualType ExpectedFirstParamType = 12720 MD && MD->isDestroyingOperatorDelete() 12721 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 12722 SemaRef.Context.getRecordType(MD->getParent()))) 12723 : SemaRef.Context.VoidPtrTy; 12724 12725 // C++ [basic.stc.dynamic.deallocation]p2: 12726 // Each deallocation function shall return void 12727 if (CheckOperatorNewDeleteTypes( 12728 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 12729 diag::err_operator_delete_dependent_param_type, 12730 diag::err_operator_delete_param_type)) 12731 return true; 12732 12733 // C++ P0722: 12734 // A destroying operator delete shall be a usual deallocation function. 12735 if (MD && !MD->getParent()->isDependentContext() && 12736 MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) { 12737 SemaRef.Diag(MD->getLocation(), 12738 diag::err_destroying_operator_delete_not_usual); 12739 return true; 12740 } 12741 12742 return false; 12743 } 12744 12745 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12746 /// of this overloaded operator is well-formed. If so, returns false; 12747 /// otherwise, emits appropriate diagnostics and returns true. 12748 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12749 assert(FnDecl && FnDecl->isOverloadedOperator() && 12750 "Expected an overloaded operator declaration"); 12751 12752 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12753 12754 // C++ [over.oper]p5: 12755 // The allocation and deallocation functions, operator new, 12756 // operator new[], operator delete and operator delete[], are 12757 // described completely in 3.7.3. The attributes and restrictions 12758 // found in the rest of this subclause do not apply to them unless 12759 // explicitly stated in 3.7.3. 12760 if (Op == OO_Delete || Op == OO_Array_Delete) 12761 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12762 12763 if (Op == OO_New || Op == OO_Array_New) 12764 return CheckOperatorNewDeclaration(*this, FnDecl); 12765 12766 // C++ [over.oper]p6: 12767 // An operator function shall either be a non-static member 12768 // function or be a non-member function and have at least one 12769 // parameter whose type is a class, a reference to a class, an 12770 // enumeration, or a reference to an enumeration. 12771 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12772 if (MethodDecl->isStatic()) 12773 return Diag(FnDecl->getLocation(), 12774 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12775 } else { 12776 bool ClassOrEnumParam = false; 12777 for (auto Param : FnDecl->parameters()) { 12778 QualType ParamType = Param->getType().getNonReferenceType(); 12779 if (ParamType->isDependentType() || ParamType->isRecordType() || 12780 ParamType->isEnumeralType()) { 12781 ClassOrEnumParam = true; 12782 break; 12783 } 12784 } 12785 12786 if (!ClassOrEnumParam) 12787 return Diag(FnDecl->getLocation(), 12788 diag::err_operator_overload_needs_class_or_enum) 12789 << FnDecl->getDeclName(); 12790 } 12791 12792 // C++ [over.oper]p8: 12793 // An operator function cannot have default arguments (8.3.6), 12794 // except where explicitly stated below. 12795 // 12796 // Only the function-call operator allows default arguments 12797 // (C++ [over.call]p1). 12798 if (Op != OO_Call) { 12799 for (auto Param : FnDecl->parameters()) { 12800 if (Param->hasDefaultArg()) 12801 return Diag(Param->getLocation(), 12802 diag::err_operator_overload_default_arg) 12803 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12804 } 12805 } 12806 12807 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12808 { false, false, false } 12809 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12810 , { Unary, Binary, MemberOnly } 12811 #include "clang/Basic/OperatorKinds.def" 12812 }; 12813 12814 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12815 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12816 bool MustBeMemberOperator = OperatorUses[Op][2]; 12817 12818 // C++ [over.oper]p8: 12819 // [...] Operator functions cannot have more or fewer parameters 12820 // than the number required for the corresponding operator, as 12821 // described in the rest of this subclause. 12822 unsigned NumParams = FnDecl->getNumParams() 12823 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12824 if (Op != OO_Call && 12825 ((NumParams == 1 && !CanBeUnaryOperator) || 12826 (NumParams == 2 && !CanBeBinaryOperator) || 12827 (NumParams < 1) || (NumParams > 2))) { 12828 // We have the wrong number of parameters. 12829 unsigned ErrorKind; 12830 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12831 ErrorKind = 2; // 2 -> unary or binary. 12832 } else if (CanBeUnaryOperator) { 12833 ErrorKind = 0; // 0 -> unary 12834 } else { 12835 assert(CanBeBinaryOperator && 12836 "All non-call overloaded operators are unary or binary!"); 12837 ErrorKind = 1; // 1 -> binary 12838 } 12839 12840 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12841 << FnDecl->getDeclName() << NumParams << ErrorKind; 12842 } 12843 12844 // Overloaded operators other than operator() cannot be variadic. 12845 if (Op != OO_Call && 12846 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12847 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12848 << FnDecl->getDeclName(); 12849 } 12850 12851 // Some operators must be non-static member functions. 12852 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12853 return Diag(FnDecl->getLocation(), 12854 diag::err_operator_overload_must_be_member) 12855 << FnDecl->getDeclName(); 12856 } 12857 12858 // C++ [over.inc]p1: 12859 // The user-defined function called operator++ implements the 12860 // prefix and postfix ++ operator. If this function is a member 12861 // function with no parameters, or a non-member function with one 12862 // parameter of class or enumeration type, it defines the prefix 12863 // increment operator ++ for objects of that type. If the function 12864 // is a member function with one parameter (which shall be of type 12865 // int) or a non-member function with two parameters (the second 12866 // of which shall be of type int), it defines the postfix 12867 // increment operator ++ for objects of that type. 12868 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12869 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12870 QualType ParamType = LastParam->getType(); 12871 12872 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12873 !ParamType->isDependentType()) 12874 return Diag(LastParam->getLocation(), 12875 diag::err_operator_overload_post_incdec_must_be_int) 12876 << LastParam->getType() << (Op == OO_MinusMinus); 12877 } 12878 12879 return false; 12880 } 12881 12882 static bool 12883 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 12884 FunctionTemplateDecl *TpDecl) { 12885 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 12886 12887 // Must have one or two template parameters. 12888 if (TemplateParams->size() == 1) { 12889 NonTypeTemplateParmDecl *PmDecl = 12890 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 12891 12892 // The template parameter must be a char parameter pack. 12893 if (PmDecl && PmDecl->isTemplateParameterPack() && 12894 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 12895 return false; 12896 12897 } else if (TemplateParams->size() == 2) { 12898 TemplateTypeParmDecl *PmType = 12899 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 12900 NonTypeTemplateParmDecl *PmArgs = 12901 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 12902 12903 // The second template parameter must be a parameter pack with the 12904 // first template parameter as its type. 12905 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 12906 PmArgs->isTemplateParameterPack()) { 12907 const TemplateTypeParmType *TArgs = 12908 PmArgs->getType()->getAs<TemplateTypeParmType>(); 12909 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 12910 TArgs->getIndex() == PmType->getIndex()) { 12911 if (!SemaRef.inTemplateInstantiation()) 12912 SemaRef.Diag(TpDecl->getLocation(), 12913 diag::ext_string_literal_operator_template); 12914 return false; 12915 } 12916 } 12917 } 12918 12919 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 12920 diag::err_literal_operator_template) 12921 << TpDecl->getTemplateParameters()->getSourceRange(); 12922 return true; 12923 } 12924 12925 /// CheckLiteralOperatorDeclaration - Check whether the declaration 12926 /// of this literal operator function is well-formed. If so, returns 12927 /// false; otherwise, emits appropriate diagnostics and returns true. 12928 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 12929 if (isa<CXXMethodDecl>(FnDecl)) { 12930 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 12931 << FnDecl->getDeclName(); 12932 return true; 12933 } 12934 12935 if (FnDecl->isExternC()) { 12936 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 12937 if (const LinkageSpecDecl *LSD = 12938 FnDecl->getDeclContext()->getExternCContext()) 12939 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 12940 return true; 12941 } 12942 12943 // This might be the definition of a literal operator template. 12944 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 12945 12946 // This might be a specialization of a literal operator template. 12947 if (!TpDecl) 12948 TpDecl = FnDecl->getPrimaryTemplate(); 12949 12950 // template <char...> type operator "" name() and 12951 // template <class T, T...> type operator "" name() are the only valid 12952 // template signatures, and the only valid signatures with no parameters. 12953 if (TpDecl) { 12954 if (FnDecl->param_size() != 0) { 12955 Diag(FnDecl->getLocation(), 12956 diag::err_literal_operator_template_with_params); 12957 return true; 12958 } 12959 12960 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 12961 return true; 12962 12963 } else if (FnDecl->param_size() == 1) { 12964 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 12965 12966 QualType ParamType = Param->getType().getUnqualifiedType(); 12967 12968 // Only unsigned long long int, long double, any character type, and const 12969 // char * are allowed as the only parameters. 12970 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 12971 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 12972 Context.hasSameType(ParamType, Context.CharTy) || 12973 Context.hasSameType(ParamType, Context.WideCharTy) || 12974 Context.hasSameType(ParamType, Context.Char16Ty) || 12975 Context.hasSameType(ParamType, Context.Char32Ty)) { 12976 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 12977 QualType InnerType = Ptr->getPointeeType(); 12978 12979 // Pointer parameter must be a const char *. 12980 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 12981 Context.CharTy) && 12982 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 12983 Diag(Param->getSourceRange().getBegin(), 12984 diag::err_literal_operator_param) 12985 << ParamType << "'const char *'" << Param->getSourceRange(); 12986 return true; 12987 } 12988 12989 } else if (ParamType->isRealFloatingType()) { 12990 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12991 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 12992 return true; 12993 12994 } else if (ParamType->isIntegerType()) { 12995 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12996 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 12997 return true; 12998 12999 } else { 13000 Diag(Param->getSourceRange().getBegin(), 13001 diag::err_literal_operator_invalid_param) 13002 << ParamType << Param->getSourceRange(); 13003 return true; 13004 } 13005 13006 } else if (FnDecl->param_size() == 2) { 13007 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13008 13009 // First, verify that the first parameter is correct. 13010 13011 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13012 13013 // Two parameter function must have a pointer to const as a 13014 // first parameter; let's strip those qualifiers. 13015 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13016 13017 if (!PT) { 13018 Diag((*Param)->getSourceRange().getBegin(), 13019 diag::err_literal_operator_param) 13020 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13021 return true; 13022 } 13023 13024 QualType PointeeType = PT->getPointeeType(); 13025 // First parameter must be const 13026 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13027 Diag((*Param)->getSourceRange().getBegin(), 13028 diag::err_literal_operator_param) 13029 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13030 return true; 13031 } 13032 13033 QualType InnerType = PointeeType.getUnqualifiedType(); 13034 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 13035 // are allowed as the first parameter to a two-parameter function 13036 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13037 Context.hasSameType(InnerType, Context.WideCharTy) || 13038 Context.hasSameType(InnerType, Context.Char16Ty) || 13039 Context.hasSameType(InnerType, Context.Char32Ty))) { 13040 Diag((*Param)->getSourceRange().getBegin(), 13041 diag::err_literal_operator_param) 13042 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13043 return true; 13044 } 13045 13046 // Move on to the second and final parameter. 13047 ++Param; 13048 13049 // The second parameter must be a std::size_t. 13050 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13051 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13052 Diag((*Param)->getSourceRange().getBegin(), 13053 diag::err_literal_operator_param) 13054 << SecondParamType << Context.getSizeType() 13055 << (*Param)->getSourceRange(); 13056 return true; 13057 } 13058 } else { 13059 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13060 return true; 13061 } 13062 13063 // Parameters are good. 13064 13065 // A parameter-declaration-clause containing a default argument is not 13066 // equivalent to any of the permitted forms. 13067 for (auto Param : FnDecl->parameters()) { 13068 if (Param->hasDefaultArg()) { 13069 Diag(Param->getDefaultArgRange().getBegin(), 13070 diag::err_literal_operator_default_argument) 13071 << Param->getDefaultArgRange(); 13072 break; 13073 } 13074 } 13075 13076 StringRef LiteralName 13077 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13078 if (LiteralName[0] != '_') { 13079 // C++11 [usrlit.suffix]p1: 13080 // Literal suffix identifiers that do not start with an underscore 13081 // are reserved for future standardization. 13082 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13083 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13084 } 13085 13086 return false; 13087 } 13088 13089 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13090 /// linkage specification, including the language and (if present) 13091 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13092 /// language string literal. LBraceLoc, if valid, provides the location of 13093 /// the '{' brace. Otherwise, this linkage specification does not 13094 /// have any braces. 13095 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13096 Expr *LangStr, 13097 SourceLocation LBraceLoc) { 13098 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13099 if (!Lit->isAscii()) { 13100 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13101 << LangStr->getSourceRange(); 13102 return nullptr; 13103 } 13104 13105 StringRef Lang = Lit->getString(); 13106 LinkageSpecDecl::LanguageIDs Language; 13107 if (Lang == "C") 13108 Language = LinkageSpecDecl::lang_c; 13109 else if (Lang == "C++") 13110 Language = LinkageSpecDecl::lang_cxx; 13111 else { 13112 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13113 << LangStr->getSourceRange(); 13114 return nullptr; 13115 } 13116 13117 // FIXME: Add all the various semantics of linkage specifications 13118 13119 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13120 LangStr->getExprLoc(), Language, 13121 LBraceLoc.isValid()); 13122 CurContext->addDecl(D); 13123 PushDeclContext(S, D); 13124 return D; 13125 } 13126 13127 /// ActOnFinishLinkageSpecification - Complete the definition of 13128 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13129 /// valid, it's the position of the closing '}' brace in a linkage 13130 /// specification that uses braces. 13131 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13132 Decl *LinkageSpec, 13133 SourceLocation RBraceLoc) { 13134 if (RBraceLoc.isValid()) { 13135 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13136 LSDecl->setRBraceLoc(RBraceLoc); 13137 } 13138 PopDeclContext(); 13139 return LinkageSpec; 13140 } 13141 13142 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13143 AttributeList *AttrList, 13144 SourceLocation SemiLoc) { 13145 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13146 // Attribute declarations appertain to empty declaration so we handle 13147 // them here. 13148 if (AttrList) 13149 ProcessDeclAttributeList(S, ED, AttrList); 13150 13151 CurContext->addDecl(ED); 13152 return ED; 13153 } 13154 13155 /// \brief Perform semantic analysis for the variable declaration that 13156 /// occurs within a C++ catch clause, returning the newly-created 13157 /// variable. 13158 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13159 TypeSourceInfo *TInfo, 13160 SourceLocation StartLoc, 13161 SourceLocation Loc, 13162 IdentifierInfo *Name) { 13163 bool Invalid = false; 13164 QualType ExDeclType = TInfo->getType(); 13165 13166 // Arrays and functions decay. 13167 if (ExDeclType->isArrayType()) 13168 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13169 else if (ExDeclType->isFunctionType()) 13170 ExDeclType = Context.getPointerType(ExDeclType); 13171 13172 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13173 // The exception-declaration shall not denote a pointer or reference to an 13174 // incomplete type, other than [cv] void*. 13175 // N2844 forbids rvalue references. 13176 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13177 Diag(Loc, diag::err_catch_rvalue_ref); 13178 Invalid = true; 13179 } 13180 13181 if (ExDeclType->isVariablyModifiedType()) { 13182 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13183 Invalid = true; 13184 } 13185 13186 QualType BaseType = ExDeclType; 13187 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13188 unsigned DK = diag::err_catch_incomplete; 13189 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13190 BaseType = Ptr->getPointeeType(); 13191 Mode = 1; 13192 DK = diag::err_catch_incomplete_ptr; 13193 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13194 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13195 BaseType = Ref->getPointeeType(); 13196 Mode = 2; 13197 DK = diag::err_catch_incomplete_ref; 13198 } 13199 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13200 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13201 Invalid = true; 13202 13203 if (!Invalid && !ExDeclType->isDependentType() && 13204 RequireNonAbstractType(Loc, ExDeclType, 13205 diag::err_abstract_type_in_decl, 13206 AbstractVariableType)) 13207 Invalid = true; 13208 13209 // Only the non-fragile NeXT runtime currently supports C++ catches 13210 // of ObjC types, and no runtime supports catching ObjC types by value. 13211 if (!Invalid && getLangOpts().ObjC1) { 13212 QualType T = ExDeclType; 13213 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13214 T = RT->getPointeeType(); 13215 13216 if (T->isObjCObjectType()) { 13217 Diag(Loc, diag::err_objc_object_catch); 13218 Invalid = true; 13219 } else if (T->isObjCObjectPointerType()) { 13220 // FIXME: should this be a test for macosx-fragile specifically? 13221 if (getLangOpts().ObjCRuntime.isFragile()) 13222 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13223 } 13224 } 13225 13226 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13227 ExDeclType, TInfo, SC_None); 13228 ExDecl->setExceptionVariable(true); 13229 13230 // In ARC, infer 'retaining' for variables of retainable type. 13231 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13232 Invalid = true; 13233 13234 if (!Invalid && !ExDeclType->isDependentType()) { 13235 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13236 // Insulate this from anything else we might currently be parsing. 13237 EnterExpressionEvaluationContext scope( 13238 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13239 13240 // C++ [except.handle]p16: 13241 // The object declared in an exception-declaration or, if the 13242 // exception-declaration does not specify a name, a temporary (12.2) is 13243 // copy-initialized (8.5) from the exception object. [...] 13244 // The object is destroyed when the handler exits, after the destruction 13245 // of any automatic objects initialized within the handler. 13246 // 13247 // We just pretend to initialize the object with itself, then make sure 13248 // it can be destroyed later. 13249 QualType initType = Context.getExceptionObjectType(ExDeclType); 13250 13251 InitializedEntity entity = 13252 InitializedEntity::InitializeVariable(ExDecl); 13253 InitializationKind initKind = 13254 InitializationKind::CreateCopy(Loc, SourceLocation()); 13255 13256 Expr *opaqueValue = 13257 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13258 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13259 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13260 if (result.isInvalid()) 13261 Invalid = true; 13262 else { 13263 // If the constructor used was non-trivial, set this as the 13264 // "initializer". 13265 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13266 if (!construct->getConstructor()->isTrivial()) { 13267 Expr *init = MaybeCreateExprWithCleanups(construct); 13268 ExDecl->setInit(init); 13269 } 13270 13271 // And make sure it's destructable. 13272 FinalizeVarWithDestructor(ExDecl, recordType); 13273 } 13274 } 13275 } 13276 13277 if (Invalid) 13278 ExDecl->setInvalidDecl(); 13279 13280 return ExDecl; 13281 } 13282 13283 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13284 /// handler. 13285 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13286 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13287 bool Invalid = D.isInvalidType(); 13288 13289 // Check for unexpanded parameter packs. 13290 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13291 UPPC_ExceptionType)) { 13292 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13293 D.getIdentifierLoc()); 13294 Invalid = true; 13295 } 13296 13297 IdentifierInfo *II = D.getIdentifier(); 13298 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13299 LookupOrdinaryName, 13300 ForVisibleRedeclaration)) { 13301 // The scope should be freshly made just for us. There is just no way 13302 // it contains any previous declaration, except for function parameters in 13303 // a function-try-block's catch statement. 13304 assert(!S->isDeclScope(PrevDecl)); 13305 if (isDeclInScope(PrevDecl, CurContext, S)) { 13306 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13307 << D.getIdentifier(); 13308 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13309 Invalid = true; 13310 } else if (PrevDecl->isTemplateParameter()) 13311 // Maybe we will complain about the shadowed template parameter. 13312 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13313 } 13314 13315 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13316 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13317 << D.getCXXScopeSpec().getRange(); 13318 Invalid = true; 13319 } 13320 13321 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13322 D.getLocStart(), 13323 D.getIdentifierLoc(), 13324 D.getIdentifier()); 13325 if (Invalid) 13326 ExDecl->setInvalidDecl(); 13327 13328 // Add the exception declaration into this scope. 13329 if (II) 13330 PushOnScopeChains(ExDecl, S); 13331 else 13332 CurContext->addDecl(ExDecl); 13333 13334 ProcessDeclAttributes(S, ExDecl, D); 13335 return ExDecl; 13336 } 13337 13338 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13339 Expr *AssertExpr, 13340 Expr *AssertMessageExpr, 13341 SourceLocation RParenLoc) { 13342 StringLiteral *AssertMessage = 13343 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13344 13345 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13346 return nullptr; 13347 13348 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13349 AssertMessage, RParenLoc, false); 13350 } 13351 13352 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13353 Expr *AssertExpr, 13354 StringLiteral *AssertMessage, 13355 SourceLocation RParenLoc, 13356 bool Failed) { 13357 assert(AssertExpr != nullptr && "Expected non-null condition"); 13358 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13359 !Failed) { 13360 // In a static_assert-declaration, the constant-expression shall be a 13361 // constant expression that can be contextually converted to bool. 13362 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13363 if (Converted.isInvalid()) 13364 Failed = true; 13365 13366 llvm::APSInt Cond; 13367 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13368 diag::err_static_assert_expression_is_not_constant, 13369 /*AllowFold=*/false).isInvalid()) 13370 Failed = true; 13371 13372 if (!Failed && !Cond) { 13373 SmallString<256> MsgBuffer; 13374 llvm::raw_svector_ostream Msg(MsgBuffer); 13375 if (AssertMessage) 13376 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13377 13378 Expr *InnerCond = nullptr; 13379 std::string InnerCondDescription; 13380 std::tie(InnerCond, InnerCondDescription) = 13381 findFailedBooleanCondition(Converted.get(), 13382 /*AllowTopLevelCond=*/false); 13383 if (InnerCond) { 13384 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13385 << InnerCondDescription << !AssertMessage 13386 << Msg.str() << InnerCond->getSourceRange(); 13387 } else { 13388 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13389 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13390 } 13391 Failed = true; 13392 } 13393 } 13394 13395 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13396 /*DiscardedValue*/false, 13397 /*IsConstexpr*/true); 13398 if (FullAssertExpr.isInvalid()) 13399 Failed = true; 13400 else 13401 AssertExpr = FullAssertExpr.get(); 13402 13403 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13404 AssertExpr, AssertMessage, RParenLoc, 13405 Failed); 13406 13407 CurContext->addDecl(Decl); 13408 return Decl; 13409 } 13410 13411 /// \brief Perform semantic analysis of the given friend type declaration. 13412 /// 13413 /// \returns A friend declaration that. 13414 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13415 SourceLocation FriendLoc, 13416 TypeSourceInfo *TSInfo) { 13417 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13418 13419 QualType T = TSInfo->getType(); 13420 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13421 13422 // C++03 [class.friend]p2: 13423 // An elaborated-type-specifier shall be used in a friend declaration 13424 // for a class.* 13425 // 13426 // * The class-key of the elaborated-type-specifier is required. 13427 if (!CodeSynthesisContexts.empty()) { 13428 // Do not complain about the form of friend template types during any kind 13429 // of code synthesis. For template instantiation, we will have complained 13430 // when the template was defined. 13431 } else { 13432 if (!T->isElaboratedTypeSpecifier()) { 13433 // If we evaluated the type to a record type, suggest putting 13434 // a tag in front. 13435 if (const RecordType *RT = T->getAs<RecordType>()) { 13436 RecordDecl *RD = RT->getDecl(); 13437 13438 SmallString<16> InsertionText(" "); 13439 InsertionText += RD->getKindName(); 13440 13441 Diag(TypeRange.getBegin(), 13442 getLangOpts().CPlusPlus11 ? 13443 diag::warn_cxx98_compat_unelaborated_friend_type : 13444 diag::ext_unelaborated_friend_type) 13445 << (unsigned) RD->getTagKind() 13446 << T 13447 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13448 InsertionText); 13449 } else { 13450 Diag(FriendLoc, 13451 getLangOpts().CPlusPlus11 ? 13452 diag::warn_cxx98_compat_nonclass_type_friend : 13453 diag::ext_nonclass_type_friend) 13454 << T 13455 << TypeRange; 13456 } 13457 } else if (T->getAs<EnumType>()) { 13458 Diag(FriendLoc, 13459 getLangOpts().CPlusPlus11 ? 13460 diag::warn_cxx98_compat_enum_friend : 13461 diag::ext_enum_friend) 13462 << T 13463 << TypeRange; 13464 } 13465 13466 // C++11 [class.friend]p3: 13467 // A friend declaration that does not declare a function shall have one 13468 // of the following forms: 13469 // friend elaborated-type-specifier ; 13470 // friend simple-type-specifier ; 13471 // friend typename-specifier ; 13472 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13473 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13474 } 13475 13476 // If the type specifier in a friend declaration designates a (possibly 13477 // cv-qualified) class type, that class is declared as a friend; otherwise, 13478 // the friend declaration is ignored. 13479 return FriendDecl::Create(Context, CurContext, 13480 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13481 FriendLoc); 13482 } 13483 13484 /// Handle a friend tag declaration where the scope specifier was 13485 /// templated. 13486 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13487 unsigned TagSpec, SourceLocation TagLoc, 13488 CXXScopeSpec &SS, 13489 IdentifierInfo *Name, 13490 SourceLocation NameLoc, 13491 AttributeList *Attr, 13492 MultiTemplateParamsArg TempParamLists) { 13493 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13494 13495 bool IsMemberSpecialization = false; 13496 bool Invalid = false; 13497 13498 if (TemplateParameterList *TemplateParams = 13499 MatchTemplateParametersToScopeSpecifier( 13500 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13501 IsMemberSpecialization, Invalid)) { 13502 if (TemplateParams->size() > 0) { 13503 // This is a declaration of a class template. 13504 if (Invalid) 13505 return nullptr; 13506 13507 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13508 NameLoc, Attr, TemplateParams, AS_public, 13509 /*ModulePrivateLoc=*/SourceLocation(), 13510 FriendLoc, TempParamLists.size() - 1, 13511 TempParamLists.data()).get(); 13512 } else { 13513 // The "template<>" header is extraneous. 13514 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13515 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13516 IsMemberSpecialization = true; 13517 } 13518 } 13519 13520 if (Invalid) return nullptr; 13521 13522 bool isAllExplicitSpecializations = true; 13523 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13524 if (TempParamLists[I]->size()) { 13525 isAllExplicitSpecializations = false; 13526 break; 13527 } 13528 } 13529 13530 // FIXME: don't ignore attributes. 13531 13532 // If it's explicit specializations all the way down, just forget 13533 // about the template header and build an appropriate non-templated 13534 // friend. TODO: for source fidelity, remember the headers. 13535 if (isAllExplicitSpecializations) { 13536 if (SS.isEmpty()) { 13537 bool Owned = false; 13538 bool IsDependent = false; 13539 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13540 Attr, AS_public, 13541 /*ModulePrivateLoc=*/SourceLocation(), 13542 MultiTemplateParamsArg(), Owned, IsDependent, 13543 /*ScopedEnumKWLoc=*/SourceLocation(), 13544 /*ScopedEnumUsesClassTag=*/false, 13545 /*UnderlyingType=*/TypeResult(), 13546 /*IsTypeSpecifier=*/false, 13547 /*IsTemplateParamOrArg=*/false); 13548 } 13549 13550 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13551 ElaboratedTypeKeyword Keyword 13552 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13553 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13554 *Name, NameLoc); 13555 if (T.isNull()) 13556 return nullptr; 13557 13558 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13559 if (isa<DependentNameType>(T)) { 13560 DependentNameTypeLoc TL = 13561 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13562 TL.setElaboratedKeywordLoc(TagLoc); 13563 TL.setQualifierLoc(QualifierLoc); 13564 TL.setNameLoc(NameLoc); 13565 } else { 13566 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13567 TL.setElaboratedKeywordLoc(TagLoc); 13568 TL.setQualifierLoc(QualifierLoc); 13569 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13570 } 13571 13572 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13573 TSI, FriendLoc, TempParamLists); 13574 Friend->setAccess(AS_public); 13575 CurContext->addDecl(Friend); 13576 return Friend; 13577 } 13578 13579 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13580 13581 13582 13583 // Handle the case of a templated-scope friend class. e.g. 13584 // template <class T> class A<T>::B; 13585 // FIXME: we don't support these right now. 13586 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13587 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13588 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13589 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13590 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13591 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13592 TL.setElaboratedKeywordLoc(TagLoc); 13593 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13594 TL.setNameLoc(NameLoc); 13595 13596 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13597 TSI, FriendLoc, TempParamLists); 13598 Friend->setAccess(AS_public); 13599 Friend->setUnsupportedFriend(true); 13600 CurContext->addDecl(Friend); 13601 return Friend; 13602 } 13603 13604 13605 /// Handle a friend type declaration. This works in tandem with 13606 /// ActOnTag. 13607 /// 13608 /// Notes on friend class templates: 13609 /// 13610 /// We generally treat friend class declarations as if they were 13611 /// declaring a class. So, for example, the elaborated type specifier 13612 /// in a friend declaration is required to obey the restrictions of a 13613 /// class-head (i.e. no typedefs in the scope chain), template 13614 /// parameters are required to match up with simple template-ids, &c. 13615 /// However, unlike when declaring a template specialization, it's 13616 /// okay to refer to a template specialization without an empty 13617 /// template parameter declaration, e.g. 13618 /// friend class A<T>::B<unsigned>; 13619 /// We permit this as a special case; if there are any template 13620 /// parameters present at all, require proper matching, i.e. 13621 /// template <> template \<class T> friend class A<int>::B; 13622 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13623 MultiTemplateParamsArg TempParams) { 13624 SourceLocation Loc = DS.getLocStart(); 13625 13626 assert(DS.isFriendSpecified()); 13627 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13628 13629 // Try to convert the decl specifier to a type. This works for 13630 // friend templates because ActOnTag never produces a ClassTemplateDecl 13631 // for a TUK_Friend. 13632 Declarator TheDeclarator(DS, Declarator::MemberContext); 13633 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13634 QualType T = TSI->getType(); 13635 if (TheDeclarator.isInvalidType()) 13636 return nullptr; 13637 13638 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13639 return nullptr; 13640 13641 // This is definitely an error in C++98. It's probably meant to 13642 // be forbidden in C++0x, too, but the specification is just 13643 // poorly written. 13644 // 13645 // The problem is with declarations like the following: 13646 // template <T> friend A<T>::foo; 13647 // where deciding whether a class C is a friend or not now hinges 13648 // on whether there exists an instantiation of A that causes 13649 // 'foo' to equal C. There are restrictions on class-heads 13650 // (which we declare (by fiat) elaborated friend declarations to 13651 // be) that makes this tractable. 13652 // 13653 // FIXME: handle "template <> friend class A<T>;", which 13654 // is possibly well-formed? Who even knows? 13655 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13656 Diag(Loc, diag::err_tagless_friend_type_template) 13657 << DS.getSourceRange(); 13658 return nullptr; 13659 } 13660 13661 // C++98 [class.friend]p1: A friend of a class is a function 13662 // or class that is not a member of the class . . . 13663 // This is fixed in DR77, which just barely didn't make the C++03 13664 // deadline. It's also a very silly restriction that seriously 13665 // affects inner classes and which nobody else seems to implement; 13666 // thus we never diagnose it, not even in -pedantic. 13667 // 13668 // But note that we could warn about it: it's always useless to 13669 // friend one of your own members (it's not, however, worthless to 13670 // friend a member of an arbitrary specialization of your template). 13671 13672 Decl *D; 13673 if (!TempParams.empty()) 13674 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13675 TempParams, 13676 TSI, 13677 DS.getFriendSpecLoc()); 13678 else 13679 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13680 13681 if (!D) 13682 return nullptr; 13683 13684 D->setAccess(AS_public); 13685 CurContext->addDecl(D); 13686 13687 return D; 13688 } 13689 13690 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13691 MultiTemplateParamsArg TemplateParams) { 13692 const DeclSpec &DS = D.getDeclSpec(); 13693 13694 assert(DS.isFriendSpecified()); 13695 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13696 13697 SourceLocation Loc = D.getIdentifierLoc(); 13698 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13699 13700 // C++ [class.friend]p1 13701 // A friend of a class is a function or class.... 13702 // Note that this sees through typedefs, which is intended. 13703 // It *doesn't* see through dependent types, which is correct 13704 // according to [temp.arg.type]p3: 13705 // If a declaration acquires a function type through a 13706 // type dependent on a template-parameter and this causes 13707 // a declaration that does not use the syntactic form of a 13708 // function declarator to have a function type, the program 13709 // is ill-formed. 13710 if (!TInfo->getType()->isFunctionType()) { 13711 Diag(Loc, diag::err_unexpected_friend); 13712 13713 // It might be worthwhile to try to recover by creating an 13714 // appropriate declaration. 13715 return nullptr; 13716 } 13717 13718 // C++ [namespace.memdef]p3 13719 // - If a friend declaration in a non-local class first declares a 13720 // class or function, the friend class or function is a member 13721 // of the innermost enclosing namespace. 13722 // - The name of the friend is not found by simple name lookup 13723 // until a matching declaration is provided in that namespace 13724 // scope (either before or after the class declaration granting 13725 // friendship). 13726 // - If a friend function is called, its name may be found by the 13727 // name lookup that considers functions from namespaces and 13728 // classes associated with the types of the function arguments. 13729 // - When looking for a prior declaration of a class or a function 13730 // declared as a friend, scopes outside the innermost enclosing 13731 // namespace scope are not considered. 13732 13733 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13734 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13735 DeclarationName Name = NameInfo.getName(); 13736 assert(Name); 13737 13738 // Check for unexpanded parameter packs. 13739 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13740 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13741 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13742 return nullptr; 13743 13744 // The context we found the declaration in, or in which we should 13745 // create the declaration. 13746 DeclContext *DC; 13747 Scope *DCScope = S; 13748 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13749 ForExternalRedeclaration); 13750 13751 // There are five cases here. 13752 // - There's no scope specifier and we're in a local class. Only look 13753 // for functions declared in the immediately-enclosing block scope. 13754 // We recover from invalid scope qualifiers as if they just weren't there. 13755 FunctionDecl *FunctionContainingLocalClass = nullptr; 13756 if ((SS.isInvalid() || !SS.isSet()) && 13757 (FunctionContainingLocalClass = 13758 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13759 // C++11 [class.friend]p11: 13760 // If a friend declaration appears in a local class and the name 13761 // specified is an unqualified name, a prior declaration is 13762 // looked up without considering scopes that are outside the 13763 // innermost enclosing non-class scope. For a friend function 13764 // declaration, if there is no prior declaration, the program is 13765 // ill-formed. 13766 13767 // Find the innermost enclosing non-class scope. This is the block 13768 // scope containing the local class definition (or for a nested class, 13769 // the outer local class). 13770 DCScope = S->getFnParent(); 13771 13772 // Look up the function name in the scope. 13773 Previous.clear(LookupLocalFriendName); 13774 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13775 13776 if (!Previous.empty()) { 13777 // All possible previous declarations must have the same context: 13778 // either they were declared at block scope or they are members of 13779 // one of the enclosing local classes. 13780 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13781 } else { 13782 // This is ill-formed, but provide the context that we would have 13783 // declared the function in, if we were permitted to, for error recovery. 13784 DC = FunctionContainingLocalClass; 13785 } 13786 adjustContextForLocalExternDecl(DC); 13787 13788 // C++ [class.friend]p6: 13789 // A function can be defined in a friend declaration of a class if and 13790 // only if the class is a non-local class (9.8), the function name is 13791 // unqualified, and the function has namespace scope. 13792 if (D.isFunctionDefinition()) { 13793 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13794 } 13795 13796 // - There's no scope specifier, in which case we just go to the 13797 // appropriate scope and look for a function or function template 13798 // there as appropriate. 13799 } else if (SS.isInvalid() || !SS.isSet()) { 13800 // C++11 [namespace.memdef]p3: 13801 // If the name in a friend declaration is neither qualified nor 13802 // a template-id and the declaration is a function or an 13803 // elaborated-type-specifier, the lookup to determine whether 13804 // the entity has been previously declared shall not consider 13805 // any scopes outside the innermost enclosing namespace. 13806 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 13807 13808 // Find the appropriate context according to the above. 13809 DC = CurContext; 13810 13811 // Skip class contexts. If someone can cite chapter and verse 13812 // for this behavior, that would be nice --- it's what GCC and 13813 // EDG do, and it seems like a reasonable intent, but the spec 13814 // really only says that checks for unqualified existing 13815 // declarations should stop at the nearest enclosing namespace, 13816 // not that they should only consider the nearest enclosing 13817 // namespace. 13818 while (DC->isRecord()) 13819 DC = DC->getParent(); 13820 13821 DeclContext *LookupDC = DC; 13822 while (LookupDC->isTransparentContext()) 13823 LookupDC = LookupDC->getParent(); 13824 13825 while (true) { 13826 LookupQualifiedName(Previous, LookupDC); 13827 13828 if (!Previous.empty()) { 13829 DC = LookupDC; 13830 break; 13831 } 13832 13833 if (isTemplateId) { 13834 if (isa<TranslationUnitDecl>(LookupDC)) break; 13835 } else { 13836 if (LookupDC->isFileContext()) break; 13837 } 13838 LookupDC = LookupDC->getParent(); 13839 } 13840 13841 DCScope = getScopeForDeclContext(S, DC); 13842 13843 // - There's a non-dependent scope specifier, in which case we 13844 // compute it and do a previous lookup there for a function 13845 // or function template. 13846 } else if (!SS.getScopeRep()->isDependent()) { 13847 DC = computeDeclContext(SS); 13848 if (!DC) return nullptr; 13849 13850 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13851 13852 LookupQualifiedName(Previous, DC); 13853 13854 // Ignore things found implicitly in the wrong scope. 13855 // TODO: better diagnostics for this case. Suggesting the right 13856 // qualified scope would be nice... 13857 LookupResult::Filter F = Previous.makeFilter(); 13858 while (F.hasNext()) { 13859 NamedDecl *D = F.next(); 13860 if (!DC->InEnclosingNamespaceSetOf( 13861 D->getDeclContext()->getRedeclContext())) 13862 F.erase(); 13863 } 13864 F.done(); 13865 13866 if (Previous.empty()) { 13867 D.setInvalidType(); 13868 Diag(Loc, diag::err_qualified_friend_not_found) 13869 << Name << TInfo->getType(); 13870 return nullptr; 13871 } 13872 13873 // C++ [class.friend]p1: A friend of a class is a function or 13874 // class that is not a member of the class . . . 13875 if (DC->Equals(CurContext)) 13876 Diag(DS.getFriendSpecLoc(), 13877 getLangOpts().CPlusPlus11 ? 13878 diag::warn_cxx98_compat_friend_is_member : 13879 diag::err_friend_is_member); 13880 13881 if (D.isFunctionDefinition()) { 13882 // C++ [class.friend]p6: 13883 // A function can be defined in a friend declaration of a class if and 13884 // only if the class is a non-local class (9.8), the function name is 13885 // unqualified, and the function has namespace scope. 13886 SemaDiagnosticBuilder DB 13887 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 13888 13889 DB << SS.getScopeRep(); 13890 if (DC->isFileContext()) 13891 DB << FixItHint::CreateRemoval(SS.getRange()); 13892 SS.clear(); 13893 } 13894 13895 // - There's a scope specifier that does not match any template 13896 // parameter lists, in which case we use some arbitrary context, 13897 // create a method or method template, and wait for instantiation. 13898 // - There's a scope specifier that does match some template 13899 // parameter lists, which we don't handle right now. 13900 } else { 13901 if (D.isFunctionDefinition()) { 13902 // C++ [class.friend]p6: 13903 // A function can be defined in a friend declaration of a class if and 13904 // only if the class is a non-local class (9.8), the function name is 13905 // unqualified, and the function has namespace scope. 13906 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 13907 << SS.getScopeRep(); 13908 } 13909 13910 DC = CurContext; 13911 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 13912 } 13913 13914 if (!DC->isRecord()) { 13915 int DiagArg = -1; 13916 switch (D.getName().getKind()) { 13917 case UnqualifiedId::IK_ConstructorTemplateId: 13918 case UnqualifiedId::IK_ConstructorName: 13919 DiagArg = 0; 13920 break; 13921 case UnqualifiedId::IK_DestructorName: 13922 DiagArg = 1; 13923 break; 13924 case UnqualifiedId::IK_ConversionFunctionId: 13925 DiagArg = 2; 13926 break; 13927 case UnqualifiedId::IK_DeductionGuideName: 13928 DiagArg = 3; 13929 break; 13930 case UnqualifiedId::IK_Identifier: 13931 case UnqualifiedId::IK_ImplicitSelfParam: 13932 case UnqualifiedId::IK_LiteralOperatorId: 13933 case UnqualifiedId::IK_OperatorFunctionId: 13934 case UnqualifiedId::IK_TemplateId: 13935 break; 13936 } 13937 // This implies that it has to be an operator or function. 13938 if (DiagArg >= 0) { 13939 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 13940 return nullptr; 13941 } 13942 } 13943 13944 // FIXME: This is an egregious hack to cope with cases where the scope stack 13945 // does not contain the declaration context, i.e., in an out-of-line 13946 // definition of a class. 13947 Scope FakeDCScope(S, Scope::DeclScope, Diags); 13948 if (!DCScope) { 13949 FakeDCScope.setEntity(DC); 13950 DCScope = &FakeDCScope; 13951 } 13952 13953 bool AddToScope = true; 13954 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 13955 TemplateParams, AddToScope); 13956 if (!ND) return nullptr; 13957 13958 assert(ND->getLexicalDeclContext() == CurContext); 13959 13960 // If we performed typo correction, we might have added a scope specifier 13961 // and changed the decl context. 13962 DC = ND->getDeclContext(); 13963 13964 // Add the function declaration to the appropriate lookup tables, 13965 // adjusting the redeclarations list as necessary. We don't 13966 // want to do this yet if the friending class is dependent. 13967 // 13968 // Also update the scope-based lookup if the target context's 13969 // lookup context is in lexical scope. 13970 if (!CurContext->isDependentContext()) { 13971 DC = DC->getRedeclContext(); 13972 DC->makeDeclVisibleInContext(ND); 13973 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13974 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 13975 } 13976 13977 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 13978 D.getIdentifierLoc(), ND, 13979 DS.getFriendSpecLoc()); 13980 FrD->setAccess(AS_public); 13981 CurContext->addDecl(FrD); 13982 13983 if (ND->isInvalidDecl()) { 13984 FrD->setInvalidDecl(); 13985 } else { 13986 if (DC->isRecord()) CheckFriendAccess(ND); 13987 13988 FunctionDecl *FD; 13989 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 13990 FD = FTD->getTemplatedDecl(); 13991 else 13992 FD = cast<FunctionDecl>(ND); 13993 13994 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 13995 // default argument expression, that declaration shall be a definition 13996 // and shall be the only declaration of the function or function 13997 // template in the translation unit. 13998 if (functionDeclHasDefaultArgument(FD)) { 13999 // We can't look at FD->getPreviousDecl() because it may not have been set 14000 // if we're in a dependent context. If the function is known to be a 14001 // redeclaration, we will have narrowed Previous down to the right decl. 14002 if (D.isRedeclaration()) { 14003 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14004 Diag(Previous.getRepresentativeDecl()->getLocation(), 14005 diag::note_previous_declaration); 14006 } else if (!D.isFunctionDefinition()) 14007 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14008 } 14009 14010 // Mark templated-scope function declarations as unsupported. 14011 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14012 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14013 << SS.getScopeRep() << SS.getRange() 14014 << cast<CXXRecordDecl>(CurContext); 14015 FrD->setUnsupportedFriend(true); 14016 } 14017 } 14018 14019 return ND; 14020 } 14021 14022 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14023 AdjustDeclIfTemplate(Dcl); 14024 14025 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14026 if (!Fn) { 14027 Diag(DelLoc, diag::err_deleted_non_function); 14028 return; 14029 } 14030 14031 // Deleted function does not have a body. 14032 Fn->setWillHaveBody(false); 14033 14034 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14035 // Don't consider the implicit declaration we generate for explicit 14036 // specializations. FIXME: Do not generate these implicit declarations. 14037 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14038 Prev->getPreviousDecl()) && 14039 !Prev->isDefined()) { 14040 Diag(DelLoc, diag::err_deleted_decl_not_first); 14041 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14042 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14043 : diag::note_previous_declaration); 14044 } 14045 // If the declaration wasn't the first, we delete the function anyway for 14046 // recovery. 14047 Fn = Fn->getCanonicalDecl(); 14048 } 14049 14050 // dllimport/dllexport cannot be deleted. 14051 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14052 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14053 Fn->setInvalidDecl(); 14054 } 14055 14056 if (Fn->isDeleted()) 14057 return; 14058 14059 // See if we're deleting a function which is already known to override a 14060 // non-deleted virtual function. 14061 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14062 bool IssuedDiagnostic = false; 14063 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 14064 E = MD->end_overridden_methods(); 14065 I != E; ++I) { 14066 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14067 if (!IssuedDiagnostic) { 14068 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14069 IssuedDiagnostic = true; 14070 } 14071 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 14072 } 14073 } 14074 // If this function was implicitly deleted because it was defaulted, 14075 // explain why it was deleted. 14076 if (IssuedDiagnostic && MD->isDefaulted()) 14077 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14078 /*Diagnose*/true); 14079 } 14080 14081 // C++11 [basic.start.main]p3: 14082 // A program that defines main as deleted [...] is ill-formed. 14083 if (Fn->isMain()) 14084 Diag(DelLoc, diag::err_deleted_main); 14085 14086 // C++11 [dcl.fct.def.delete]p4: 14087 // A deleted function is implicitly inline. 14088 Fn->setImplicitlyInline(); 14089 Fn->setDeletedAsWritten(); 14090 } 14091 14092 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14093 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14094 14095 if (MD) { 14096 if (MD->getParent()->isDependentType()) { 14097 MD->setDefaulted(); 14098 MD->setExplicitlyDefaulted(); 14099 return; 14100 } 14101 14102 CXXSpecialMember Member = getSpecialMember(MD); 14103 if (Member == CXXInvalid) { 14104 if (!MD->isInvalidDecl()) 14105 Diag(DefaultLoc, diag::err_default_special_members); 14106 return; 14107 } 14108 14109 MD->setDefaulted(); 14110 MD->setExplicitlyDefaulted(); 14111 14112 // Unset that we will have a body for this function. We might not, 14113 // if it turns out to be trivial, and we don't need this marking now 14114 // that we've marked it as defaulted. 14115 MD->setWillHaveBody(false); 14116 14117 // If this definition appears within the record, do the checking when 14118 // the record is complete. 14119 const FunctionDecl *Primary = MD; 14120 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14121 // Ask the template instantiation pattern that actually had the 14122 // '= default' on it. 14123 Primary = Pattern; 14124 14125 // If the method was defaulted on its first declaration, we will have 14126 // already performed the checking in CheckCompletedCXXClass. Such a 14127 // declaration doesn't trigger an implicit definition. 14128 if (Primary->getCanonicalDecl()->isDefaulted()) 14129 return; 14130 14131 CheckExplicitlyDefaultedSpecialMember(MD); 14132 14133 if (!MD->isInvalidDecl()) 14134 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14135 } else { 14136 Diag(DefaultLoc, diag::err_default_special_members); 14137 } 14138 } 14139 14140 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14141 for (Stmt *SubStmt : S->children()) { 14142 if (!SubStmt) 14143 continue; 14144 if (isa<ReturnStmt>(SubStmt)) 14145 Self.Diag(SubStmt->getLocStart(), 14146 diag::err_return_in_constructor_handler); 14147 if (!isa<Expr>(SubStmt)) 14148 SearchForReturnInStmt(Self, SubStmt); 14149 } 14150 } 14151 14152 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14153 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14154 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14155 SearchForReturnInStmt(*this, Handler); 14156 } 14157 } 14158 14159 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14160 const CXXMethodDecl *Old) { 14161 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14162 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14163 14164 if (OldFT->hasExtParameterInfos()) { 14165 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14166 // A parameter of the overriding method should be annotated with noescape 14167 // if the corresponding parameter of the overridden method is annotated. 14168 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14169 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14170 Diag(New->getParamDecl(I)->getLocation(), 14171 diag::warn_overriding_method_missing_noescape); 14172 Diag(Old->getParamDecl(I)->getLocation(), 14173 diag::note_overridden_marked_noescape); 14174 } 14175 } 14176 14177 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14178 14179 // If the calling conventions match, everything is fine 14180 if (NewCC == OldCC) 14181 return false; 14182 14183 // If the calling conventions mismatch because the new function is static, 14184 // suppress the calling convention mismatch error; the error about static 14185 // function override (err_static_overrides_virtual from 14186 // Sema::CheckFunctionDeclaration) is more clear. 14187 if (New->getStorageClass() == SC_Static) 14188 return false; 14189 14190 Diag(New->getLocation(), 14191 diag::err_conflicting_overriding_cc_attributes) 14192 << New->getDeclName() << New->getType() << Old->getType(); 14193 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14194 return true; 14195 } 14196 14197 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14198 const CXXMethodDecl *Old) { 14199 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14200 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14201 14202 if (Context.hasSameType(NewTy, OldTy) || 14203 NewTy->isDependentType() || OldTy->isDependentType()) 14204 return false; 14205 14206 // Check if the return types are covariant 14207 QualType NewClassTy, OldClassTy; 14208 14209 /// Both types must be pointers or references to classes. 14210 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14211 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14212 NewClassTy = NewPT->getPointeeType(); 14213 OldClassTy = OldPT->getPointeeType(); 14214 } 14215 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14216 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14217 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14218 NewClassTy = NewRT->getPointeeType(); 14219 OldClassTy = OldRT->getPointeeType(); 14220 } 14221 } 14222 } 14223 14224 // The return types aren't either both pointers or references to a class type. 14225 if (NewClassTy.isNull()) { 14226 Diag(New->getLocation(), 14227 diag::err_different_return_type_for_overriding_virtual_function) 14228 << New->getDeclName() << NewTy << OldTy 14229 << New->getReturnTypeSourceRange(); 14230 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14231 << Old->getReturnTypeSourceRange(); 14232 14233 return true; 14234 } 14235 14236 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14237 // C++14 [class.virtual]p8: 14238 // If the class type in the covariant return type of D::f differs from 14239 // that of B::f, the class type in the return type of D::f shall be 14240 // complete at the point of declaration of D::f or shall be the class 14241 // type D. 14242 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14243 if (!RT->isBeingDefined() && 14244 RequireCompleteType(New->getLocation(), NewClassTy, 14245 diag::err_covariant_return_incomplete, 14246 New->getDeclName())) 14247 return true; 14248 } 14249 14250 // Check if the new class derives from the old class. 14251 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14252 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14253 << New->getDeclName() << NewTy << OldTy 14254 << New->getReturnTypeSourceRange(); 14255 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14256 << Old->getReturnTypeSourceRange(); 14257 return true; 14258 } 14259 14260 // Check if we the conversion from derived to base is valid. 14261 if (CheckDerivedToBaseConversion( 14262 NewClassTy, OldClassTy, 14263 diag::err_covariant_return_inaccessible_base, 14264 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14265 New->getLocation(), New->getReturnTypeSourceRange(), 14266 New->getDeclName(), nullptr)) { 14267 // FIXME: this note won't trigger for delayed access control 14268 // diagnostics, and it's impossible to get an undelayed error 14269 // here from access control during the original parse because 14270 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14271 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14272 << Old->getReturnTypeSourceRange(); 14273 return true; 14274 } 14275 } 14276 14277 // The qualifiers of the return types must be the same. 14278 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14279 Diag(New->getLocation(), 14280 diag::err_covariant_return_type_different_qualifications) 14281 << New->getDeclName() << NewTy << OldTy 14282 << New->getReturnTypeSourceRange(); 14283 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14284 << Old->getReturnTypeSourceRange(); 14285 return true; 14286 } 14287 14288 14289 // The new class type must have the same or less qualifiers as the old type. 14290 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14291 Diag(New->getLocation(), 14292 diag::err_covariant_return_type_class_type_more_qualified) 14293 << New->getDeclName() << NewTy << OldTy 14294 << New->getReturnTypeSourceRange(); 14295 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14296 << Old->getReturnTypeSourceRange(); 14297 return true; 14298 } 14299 14300 return false; 14301 } 14302 14303 /// \brief Mark the given method pure. 14304 /// 14305 /// \param Method the method to be marked pure. 14306 /// 14307 /// \param InitRange the source range that covers the "0" initializer. 14308 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14309 SourceLocation EndLoc = InitRange.getEnd(); 14310 if (EndLoc.isValid()) 14311 Method->setRangeEnd(EndLoc); 14312 14313 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14314 Method->setPure(); 14315 return false; 14316 } 14317 14318 if (!Method->isInvalidDecl()) 14319 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14320 << Method->getDeclName() << InitRange; 14321 return true; 14322 } 14323 14324 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14325 if (D->getFriendObjectKind()) 14326 Diag(D->getLocation(), diag::err_pure_friend); 14327 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14328 CheckPureMethod(M, ZeroLoc); 14329 else 14330 Diag(D->getLocation(), diag::err_illegal_initializer); 14331 } 14332 14333 /// \brief Determine whether the given declaration is a global variable or 14334 /// static data member. 14335 static bool isNonlocalVariable(const Decl *D) { 14336 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14337 return Var->hasGlobalStorage(); 14338 14339 return false; 14340 } 14341 14342 /// Invoked when we are about to parse an initializer for the declaration 14343 /// 'Dcl'. 14344 /// 14345 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14346 /// static data member of class X, names should be looked up in the scope of 14347 /// class X. If the declaration had a scope specifier, a scope will have 14348 /// been created and passed in for this purpose. Otherwise, S will be null. 14349 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14350 // If there is no declaration, there was an error parsing it. 14351 if (!D || D->isInvalidDecl()) 14352 return; 14353 14354 // We will always have a nested name specifier here, but this declaration 14355 // might not be out of line if the specifier names the current namespace: 14356 // extern int n; 14357 // int ::n = 0; 14358 if (S && D->isOutOfLine()) 14359 EnterDeclaratorContext(S, D->getDeclContext()); 14360 14361 // If we are parsing the initializer for a static data member, push a 14362 // new expression evaluation context that is associated with this static 14363 // data member. 14364 if (isNonlocalVariable(D)) 14365 PushExpressionEvaluationContext( 14366 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14367 } 14368 14369 /// Invoked after we are finished parsing an initializer for the declaration D. 14370 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14371 // If there is no declaration, there was an error parsing it. 14372 if (!D || D->isInvalidDecl()) 14373 return; 14374 14375 if (isNonlocalVariable(D)) 14376 PopExpressionEvaluationContext(); 14377 14378 if (S && D->isOutOfLine()) 14379 ExitDeclaratorContext(S); 14380 } 14381 14382 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14383 /// C++ if/switch/while/for statement. 14384 /// e.g: "if (int x = f()) {...}" 14385 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14386 // C++ 6.4p2: 14387 // The declarator shall not specify a function or an array. 14388 // The type-specifier-seq shall not contain typedef and shall not declare a 14389 // new class or enumeration. 14390 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14391 "Parser allowed 'typedef' as storage class of condition decl."); 14392 14393 Decl *Dcl = ActOnDeclarator(S, D); 14394 if (!Dcl) 14395 return true; 14396 14397 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14398 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14399 << D.getSourceRange(); 14400 return true; 14401 } 14402 14403 return Dcl; 14404 } 14405 14406 void Sema::LoadExternalVTableUses() { 14407 if (!ExternalSource) 14408 return; 14409 14410 SmallVector<ExternalVTableUse, 4> VTables; 14411 ExternalSource->ReadUsedVTables(VTables); 14412 SmallVector<VTableUse, 4> NewUses; 14413 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14414 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14415 = VTablesUsed.find(VTables[I].Record); 14416 // Even if a definition wasn't required before, it may be required now. 14417 if (Pos != VTablesUsed.end()) { 14418 if (!Pos->second && VTables[I].DefinitionRequired) 14419 Pos->second = true; 14420 continue; 14421 } 14422 14423 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14424 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14425 } 14426 14427 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14428 } 14429 14430 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14431 bool DefinitionRequired) { 14432 // Ignore any vtable uses in unevaluated operands or for classes that do 14433 // not have a vtable. 14434 if (!Class->isDynamicClass() || Class->isDependentContext() || 14435 CurContext->isDependentContext() || isUnevaluatedContext()) 14436 return; 14437 14438 // Try to insert this class into the map. 14439 LoadExternalVTableUses(); 14440 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14441 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14442 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14443 if (!Pos.second) { 14444 // If we already had an entry, check to see if we are promoting this vtable 14445 // to require a definition. If so, we need to reappend to the VTableUses 14446 // list, since we may have already processed the first entry. 14447 if (DefinitionRequired && !Pos.first->second) { 14448 Pos.first->second = true; 14449 } else { 14450 // Otherwise, we can early exit. 14451 return; 14452 } 14453 } else { 14454 // The Microsoft ABI requires that we perform the destructor body 14455 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14456 // the deleting destructor is emitted with the vtable, not with the 14457 // destructor definition as in the Itanium ABI. 14458 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14459 CXXDestructorDecl *DD = Class->getDestructor(); 14460 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14461 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14462 // If this is an out-of-line declaration, marking it referenced will 14463 // not do anything. Manually call CheckDestructor to look up operator 14464 // delete(). 14465 ContextRAII SavedContext(*this, DD); 14466 CheckDestructor(DD); 14467 } else { 14468 MarkFunctionReferenced(Loc, Class->getDestructor()); 14469 } 14470 } 14471 } 14472 } 14473 14474 // Local classes need to have their virtual members marked 14475 // immediately. For all other classes, we mark their virtual members 14476 // at the end of the translation unit. 14477 if (Class->isLocalClass()) 14478 MarkVirtualMembersReferenced(Loc, Class); 14479 else 14480 VTableUses.push_back(std::make_pair(Class, Loc)); 14481 } 14482 14483 bool Sema::DefineUsedVTables() { 14484 LoadExternalVTableUses(); 14485 if (VTableUses.empty()) 14486 return false; 14487 14488 // Note: The VTableUses vector could grow as a result of marking 14489 // the members of a class as "used", so we check the size each 14490 // time through the loop and prefer indices (which are stable) to 14491 // iterators (which are not). 14492 bool DefinedAnything = false; 14493 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14494 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14495 if (!Class) 14496 continue; 14497 TemplateSpecializationKind ClassTSK = 14498 Class->getTemplateSpecializationKind(); 14499 14500 SourceLocation Loc = VTableUses[I].second; 14501 14502 bool DefineVTable = true; 14503 14504 // If this class has a key function, but that key function is 14505 // defined in another translation unit, we don't need to emit the 14506 // vtable even though we're using it. 14507 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14508 if (KeyFunction && !KeyFunction->hasBody()) { 14509 // The key function is in another translation unit. 14510 DefineVTable = false; 14511 TemplateSpecializationKind TSK = 14512 KeyFunction->getTemplateSpecializationKind(); 14513 assert(TSK != TSK_ExplicitInstantiationDefinition && 14514 TSK != TSK_ImplicitInstantiation && 14515 "Instantiations don't have key functions"); 14516 (void)TSK; 14517 } else if (!KeyFunction) { 14518 // If we have a class with no key function that is the subject 14519 // of an explicit instantiation declaration, suppress the 14520 // vtable; it will live with the explicit instantiation 14521 // definition. 14522 bool IsExplicitInstantiationDeclaration = 14523 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14524 for (auto R : Class->redecls()) { 14525 TemplateSpecializationKind TSK 14526 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14527 if (TSK == TSK_ExplicitInstantiationDeclaration) 14528 IsExplicitInstantiationDeclaration = true; 14529 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14530 IsExplicitInstantiationDeclaration = false; 14531 break; 14532 } 14533 } 14534 14535 if (IsExplicitInstantiationDeclaration) 14536 DefineVTable = false; 14537 } 14538 14539 // The exception specifications for all virtual members may be needed even 14540 // if we are not providing an authoritative form of the vtable in this TU. 14541 // We may choose to emit it available_externally anyway. 14542 if (!DefineVTable) { 14543 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14544 continue; 14545 } 14546 14547 // Mark all of the virtual members of this class as referenced, so 14548 // that we can build a vtable. Then, tell the AST consumer that a 14549 // vtable for this class is required. 14550 DefinedAnything = true; 14551 MarkVirtualMembersReferenced(Loc, Class); 14552 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14553 if (VTablesUsed[Canonical]) 14554 Consumer.HandleVTable(Class); 14555 14556 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14557 // no key function or the key function is inlined. Don't warn in C++ ABIs 14558 // that lack key functions, since the user won't be able to make one. 14559 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14560 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14561 const FunctionDecl *KeyFunctionDef = nullptr; 14562 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14563 KeyFunctionDef->isInlined())) { 14564 Diag(Class->getLocation(), 14565 ClassTSK == TSK_ExplicitInstantiationDefinition 14566 ? diag::warn_weak_template_vtable 14567 : diag::warn_weak_vtable) 14568 << Class; 14569 } 14570 } 14571 } 14572 VTableUses.clear(); 14573 14574 return DefinedAnything; 14575 } 14576 14577 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14578 const CXXRecordDecl *RD) { 14579 for (const auto *I : RD->methods()) 14580 if (I->isVirtual() && !I->isPure()) 14581 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14582 } 14583 14584 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14585 const CXXRecordDecl *RD) { 14586 // Mark all functions which will appear in RD's vtable as used. 14587 CXXFinalOverriderMap FinalOverriders; 14588 RD->getFinalOverriders(FinalOverriders); 14589 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14590 E = FinalOverriders.end(); 14591 I != E; ++I) { 14592 for (OverridingMethods::const_iterator OI = I->second.begin(), 14593 OE = I->second.end(); 14594 OI != OE; ++OI) { 14595 assert(OI->second.size() > 0 && "no final overrider"); 14596 CXXMethodDecl *Overrider = OI->second.front().Method; 14597 14598 // C++ [basic.def.odr]p2: 14599 // [...] A virtual member function is used if it is not pure. [...] 14600 if (!Overrider->isPure()) 14601 MarkFunctionReferenced(Loc, Overrider); 14602 } 14603 } 14604 14605 // Only classes that have virtual bases need a VTT. 14606 if (RD->getNumVBases() == 0) 14607 return; 14608 14609 for (const auto &I : RD->bases()) { 14610 const CXXRecordDecl *Base = 14611 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14612 if (Base->getNumVBases() == 0) 14613 continue; 14614 MarkVirtualMembersReferenced(Loc, Base); 14615 } 14616 } 14617 14618 /// SetIvarInitializers - This routine builds initialization ASTs for the 14619 /// Objective-C implementation whose ivars need be initialized. 14620 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14621 if (!getLangOpts().CPlusPlus) 14622 return; 14623 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14624 SmallVector<ObjCIvarDecl*, 8> ivars; 14625 CollectIvarsToConstructOrDestruct(OID, ivars); 14626 if (ivars.empty()) 14627 return; 14628 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14629 for (unsigned i = 0; i < ivars.size(); i++) { 14630 FieldDecl *Field = ivars[i]; 14631 if (Field->isInvalidDecl()) 14632 continue; 14633 14634 CXXCtorInitializer *Member; 14635 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14636 InitializationKind InitKind = 14637 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14638 14639 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14640 ExprResult MemberInit = 14641 InitSeq.Perform(*this, InitEntity, InitKind, None); 14642 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14643 // Note, MemberInit could actually come back empty if no initialization 14644 // is required (e.g., because it would call a trivial default constructor) 14645 if (!MemberInit.get() || MemberInit.isInvalid()) 14646 continue; 14647 14648 Member = 14649 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14650 SourceLocation(), 14651 MemberInit.getAs<Expr>(), 14652 SourceLocation()); 14653 AllToInit.push_back(Member); 14654 14655 // Be sure that the destructor is accessible and is marked as referenced. 14656 if (const RecordType *RecordTy = 14657 Context.getBaseElementType(Field->getType()) 14658 ->getAs<RecordType>()) { 14659 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14660 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14661 MarkFunctionReferenced(Field->getLocation(), Destructor); 14662 CheckDestructorAccess(Field->getLocation(), Destructor, 14663 PDiag(diag::err_access_dtor_ivar) 14664 << Context.getBaseElementType(Field->getType())); 14665 } 14666 } 14667 } 14668 ObjCImplementation->setIvarInitializers(Context, 14669 AllToInit.data(), AllToInit.size()); 14670 } 14671 } 14672 14673 static 14674 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14675 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14676 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14677 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14678 Sema &S) { 14679 if (Ctor->isInvalidDecl()) 14680 return; 14681 14682 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14683 14684 // Target may not be determinable yet, for instance if this is a dependent 14685 // call in an uninstantiated template. 14686 if (Target) { 14687 const FunctionDecl *FNTarget = nullptr; 14688 (void)Target->hasBody(FNTarget); 14689 Target = const_cast<CXXConstructorDecl*>( 14690 cast_or_null<CXXConstructorDecl>(FNTarget)); 14691 } 14692 14693 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14694 // Avoid dereferencing a null pointer here. 14695 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14696 14697 if (!Current.insert(Canonical).second) 14698 return; 14699 14700 // We know that beyond here, we aren't chaining into a cycle. 14701 if (!Target || !Target->isDelegatingConstructor() || 14702 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14703 Valid.insert(Current.begin(), Current.end()); 14704 Current.clear(); 14705 // We've hit a cycle. 14706 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14707 Current.count(TCanonical)) { 14708 // If we haven't diagnosed this cycle yet, do so now. 14709 if (!Invalid.count(TCanonical)) { 14710 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14711 diag::warn_delegating_ctor_cycle) 14712 << Ctor; 14713 14714 // Don't add a note for a function delegating directly to itself. 14715 if (TCanonical != Canonical) 14716 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14717 14718 CXXConstructorDecl *C = Target; 14719 while (C->getCanonicalDecl() != Canonical) { 14720 const FunctionDecl *FNTarget = nullptr; 14721 (void)C->getTargetConstructor()->hasBody(FNTarget); 14722 assert(FNTarget && "Ctor cycle through bodiless function"); 14723 14724 C = const_cast<CXXConstructorDecl*>( 14725 cast<CXXConstructorDecl>(FNTarget)); 14726 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14727 } 14728 } 14729 14730 Invalid.insert(Current.begin(), Current.end()); 14731 Current.clear(); 14732 } else { 14733 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14734 } 14735 } 14736 14737 14738 void Sema::CheckDelegatingCtorCycles() { 14739 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14740 14741 for (DelegatingCtorDeclsType::iterator 14742 I = DelegatingCtorDecls.begin(ExternalSource), 14743 E = DelegatingCtorDecls.end(); 14744 I != E; ++I) 14745 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14746 14747 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14748 CE = Invalid.end(); 14749 CI != CE; ++CI) 14750 (*CI)->setInvalidDecl(); 14751 } 14752 14753 namespace { 14754 /// \brief AST visitor that finds references to the 'this' expression. 14755 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14756 Sema &S; 14757 14758 public: 14759 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14760 14761 bool VisitCXXThisExpr(CXXThisExpr *E) { 14762 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14763 << E->isImplicit(); 14764 return false; 14765 } 14766 }; 14767 } 14768 14769 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14770 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14771 if (!TSInfo) 14772 return false; 14773 14774 TypeLoc TL = TSInfo->getTypeLoc(); 14775 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14776 if (!ProtoTL) 14777 return false; 14778 14779 // C++11 [expr.prim.general]p3: 14780 // [The expression this] shall not appear before the optional 14781 // cv-qualifier-seq and it shall not appear within the declaration of a 14782 // static member function (although its type and value category are defined 14783 // within a static member function as they are within a non-static member 14784 // function). [ Note: this is because declaration matching does not occur 14785 // until the complete declarator is known. - end note ] 14786 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14787 FindCXXThisExpr Finder(*this); 14788 14789 // If the return type came after the cv-qualifier-seq, check it now. 14790 if (Proto->hasTrailingReturn() && 14791 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14792 return true; 14793 14794 // Check the exception specification. 14795 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14796 return true; 14797 14798 return checkThisInStaticMemberFunctionAttributes(Method); 14799 } 14800 14801 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14802 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14803 if (!TSInfo) 14804 return false; 14805 14806 TypeLoc TL = TSInfo->getTypeLoc(); 14807 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14808 if (!ProtoTL) 14809 return false; 14810 14811 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14812 FindCXXThisExpr Finder(*this); 14813 14814 switch (Proto->getExceptionSpecType()) { 14815 case EST_Unparsed: 14816 case EST_Uninstantiated: 14817 case EST_Unevaluated: 14818 case EST_BasicNoexcept: 14819 case EST_DynamicNone: 14820 case EST_MSAny: 14821 case EST_None: 14822 break; 14823 14824 case EST_ComputedNoexcept: 14825 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14826 return true; 14827 LLVM_FALLTHROUGH; 14828 14829 case EST_Dynamic: 14830 for (const auto &E : Proto->exceptions()) { 14831 if (!Finder.TraverseType(E)) 14832 return true; 14833 } 14834 break; 14835 } 14836 14837 return false; 14838 } 14839 14840 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14841 FindCXXThisExpr Finder(*this); 14842 14843 // Check attributes. 14844 for (const auto *A : Method->attrs()) { 14845 // FIXME: This should be emitted by tblgen. 14846 Expr *Arg = nullptr; 14847 ArrayRef<Expr *> Args; 14848 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14849 Arg = G->getArg(); 14850 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14851 Arg = G->getArg(); 14852 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14853 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14854 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14855 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14856 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14857 Arg = ETLF->getSuccessValue(); 14858 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14859 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14860 Arg = STLF->getSuccessValue(); 14861 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14862 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14863 Arg = LR->getArg(); 14864 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14865 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14866 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14867 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14868 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14869 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14870 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14871 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14872 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14873 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14874 14875 if (Arg && !Finder.TraverseStmt(Arg)) 14876 return true; 14877 14878 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14879 if (!Finder.TraverseStmt(Args[I])) 14880 return true; 14881 } 14882 } 14883 14884 return false; 14885 } 14886 14887 void Sema::checkExceptionSpecification( 14888 bool IsTopLevel, ExceptionSpecificationType EST, 14889 ArrayRef<ParsedType> DynamicExceptions, 14890 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 14891 SmallVectorImpl<QualType> &Exceptions, 14892 FunctionProtoType::ExceptionSpecInfo &ESI) { 14893 Exceptions.clear(); 14894 ESI.Type = EST; 14895 if (EST == EST_Dynamic) { 14896 Exceptions.reserve(DynamicExceptions.size()); 14897 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 14898 // FIXME: Preserve type source info. 14899 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 14900 14901 if (IsTopLevel) { 14902 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 14903 collectUnexpandedParameterPacks(ET, Unexpanded); 14904 if (!Unexpanded.empty()) { 14905 DiagnoseUnexpandedParameterPacks( 14906 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 14907 Unexpanded); 14908 continue; 14909 } 14910 } 14911 14912 // Check that the type is valid for an exception spec, and 14913 // drop it if not. 14914 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 14915 Exceptions.push_back(ET); 14916 } 14917 ESI.Exceptions = Exceptions; 14918 return; 14919 } 14920 14921 if (EST == EST_ComputedNoexcept) { 14922 // If an error occurred, there's no expression here. 14923 if (NoexceptExpr) { 14924 assert((NoexceptExpr->isTypeDependent() || 14925 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 14926 Context.BoolTy) && 14927 "Parser should have made sure that the expression is boolean"); 14928 if (IsTopLevel && NoexceptExpr && 14929 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 14930 ESI.Type = EST_BasicNoexcept; 14931 return; 14932 } 14933 14934 if (!NoexceptExpr->isValueDependent()) { 14935 ExprResult Result = VerifyIntegerConstantExpression( 14936 NoexceptExpr, nullptr, diag::err_noexcept_needs_constant_expression, 14937 /*AllowFold*/ false); 14938 if (Result.isInvalid()) { 14939 ESI.Type = EST_BasicNoexcept; 14940 return; 14941 } 14942 NoexceptExpr = Result.get(); 14943 } 14944 ESI.NoexceptExpr = NoexceptExpr; 14945 } 14946 return; 14947 } 14948 } 14949 14950 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 14951 ExceptionSpecificationType EST, 14952 SourceRange SpecificationRange, 14953 ArrayRef<ParsedType> DynamicExceptions, 14954 ArrayRef<SourceRange> DynamicExceptionRanges, 14955 Expr *NoexceptExpr) { 14956 if (!MethodD) 14957 return; 14958 14959 // Dig out the method we're referring to. 14960 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 14961 MethodD = FunTmpl->getTemplatedDecl(); 14962 14963 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 14964 if (!Method) 14965 return; 14966 14967 // Check the exception specification. 14968 llvm::SmallVector<QualType, 4> Exceptions; 14969 FunctionProtoType::ExceptionSpecInfo ESI; 14970 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 14971 DynamicExceptionRanges, NoexceptExpr, Exceptions, 14972 ESI); 14973 14974 // Update the exception specification on the function type. 14975 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 14976 14977 if (Method->isStatic()) 14978 checkThisInStaticMemberFunctionExceptionSpec(Method); 14979 14980 if (Method->isVirtual()) { 14981 // Check overrides, which we previously had to delay. 14982 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 14983 OEnd = Method->end_overridden_methods(); 14984 O != OEnd; ++O) 14985 CheckOverridingFunctionExceptionSpec(Method, *O); 14986 } 14987 } 14988 14989 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 14990 /// 14991 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 14992 SourceLocation DeclStart, 14993 Declarator &D, Expr *BitWidth, 14994 InClassInitStyle InitStyle, 14995 AccessSpecifier AS, 14996 AttributeList *MSPropertyAttr) { 14997 IdentifierInfo *II = D.getIdentifier(); 14998 if (!II) { 14999 Diag(DeclStart, diag::err_anonymous_property); 15000 return nullptr; 15001 } 15002 SourceLocation Loc = D.getIdentifierLoc(); 15003 15004 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15005 QualType T = TInfo->getType(); 15006 if (getLangOpts().CPlusPlus) { 15007 CheckExtraCXXDefaultArguments(D); 15008 15009 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15010 UPPC_DataMemberType)) { 15011 D.setInvalidType(); 15012 T = Context.IntTy; 15013 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15014 } 15015 } 15016 15017 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15018 15019 if (D.getDeclSpec().isInlineSpecified()) 15020 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15021 << getLangOpts().CPlusPlus1z; 15022 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15023 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15024 diag::err_invalid_thread) 15025 << DeclSpec::getSpecifierName(TSCS); 15026 15027 // Check to see if this name was declared as a member previously 15028 NamedDecl *PrevDecl = nullptr; 15029 LookupResult Previous(*this, II, Loc, LookupMemberName, 15030 ForVisibleRedeclaration); 15031 LookupName(Previous, S); 15032 switch (Previous.getResultKind()) { 15033 case LookupResult::Found: 15034 case LookupResult::FoundUnresolvedValue: 15035 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15036 break; 15037 15038 case LookupResult::FoundOverloaded: 15039 PrevDecl = Previous.getRepresentativeDecl(); 15040 break; 15041 15042 case LookupResult::NotFound: 15043 case LookupResult::NotFoundInCurrentInstantiation: 15044 case LookupResult::Ambiguous: 15045 break; 15046 } 15047 15048 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15049 // Maybe we will complain about the shadowed template parameter. 15050 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15051 // Just pretend that we didn't see the previous declaration. 15052 PrevDecl = nullptr; 15053 } 15054 15055 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15056 PrevDecl = nullptr; 15057 15058 SourceLocation TSSL = D.getLocStart(); 15059 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 15060 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 15061 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 15062 ProcessDeclAttributes(TUScope, NewPD, D); 15063 NewPD->setAccess(AS); 15064 15065 if (NewPD->isInvalidDecl()) 15066 Record->setInvalidDecl(); 15067 15068 if (D.getDeclSpec().isModulePrivateSpecified()) 15069 NewPD->setModulePrivate(); 15070 15071 if (NewPD->isInvalidDecl() && PrevDecl) { 15072 // Don't introduce NewFD into scope; there's already something 15073 // with the same name in the same scope. 15074 } else if (II) { 15075 PushOnScopeChains(NewPD, S); 15076 } else 15077 Record->addDecl(NewPD); 15078 15079 return NewPD; 15080 } 15081